emscripten_fetch_close() does not abort an asynchronous fetch
Hello,
The fetch documentation states:
Additionally, emscripten_fetch_close() can be called at any time for asynchronous and waitable fetches to abort the download.
However, this is not true. emscripten_fetch_close() simply frees the structure, but does nothing to actually abort the xhr.
xhr.onload() gets invoked at one point, resulting in either crash early in Fetch.js, or a successful invoke on attr.onerror() with pointer to released memory.
Simple tests case:
#include <emscripten.h>
#include <emscripten/fetch.h>
#include <cstring>
#include <cstdlib>
#include <iostream>
void on_success(emscripten_fetch_t *)
{
std::cout << "on_success()" << std::endl;
//std::abort();
//emscripten_fetch_close(fetch);
}
void on_error(emscripten_fetch_t *)
{
std::cout << "on_error()" << std::endl;
//std::abort();
//emscripten_fetch_close(fetch);
}
int main(int, char *[])
{
emscripten_fetch_attr_t attr;
emscripten_fetch_attr_init(&attr);
std::strcpy(attr.requestMethod, "GET");
attr.onsuccess = on_success;
attr.onerror = on_error;
attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
// Random URL from a CORS-friendly CDN
auto fetch = emscripten_fetch(&attr, "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.44.0/codemirror.js");
// This will trigger either an alignment fault in Fetch.js, or an unexpected call to on_success()
emscripten_fetch_close(fetch);
emscripten_set_main_loop([]() {}, 0, 1);
}
https://github.com/emscripten-core/emscripten/pull/8191 may help here, but I'm not sure yet that that PR is the right approach, waiting for feedback.
I don't believe that fixes the fundamental issue, which is that emscripten_fetch_close() releases the memory.
Actually, I believe that the paradigm of invoking onerror handler upon explicit emscripten_fetch_close() is part of the problem. It's IMHO an unusual pattern in event-driven approach (no additional calls should be made once the initial action was aborted). Moreover, since onerror is very likely to invoke emscripten_fetch_close() on itself (as suggested by the documentation), an access-after-free and/or double free() are very likely to occur, and eventually go unnoticed. This could be circumvented by making emscripten_fetch_close() explicitly "reentrant" (ie. setting id to 0 upon entry, and checking id against 0 before fetch_free()), but that is kind of hack-ish.
I don't believe these issues can be fixed without a BC breaking change and an API re-design.
I see two different approaches to start with:
-
Removing
emscripten_fetch_close()altogether,free()'ing theemscripten_fetch_timplicitly after completition (whatever that means), and providing anemscripten_fetch_abort()instead. -
Renaming
emscripten_fetch_close()toemscripten_fetch_free()so that the intent is clear, while still providingemscripten_fetch_abort()as a separate API.
In both approaches, I would not invoke onerror (nor anything else) after emscripten_fetch_abort().
Still, those approaches are somehow flawed as well. If the user does not set the completition/error handlers, it would have no way of knowing that the handle (emscripten_fetch_t) was invalidated and may no longer be used in a emscripten_fetch_abort() call. That being said, this issue already exists with the current implementation as well.
A third approach would be to provide an opaque identifier/handle (managed by the fetch implementation) instead of a heap-allocated struct. Yet, that requires some housekeeping in the fetch implementation, which could possibly be hard to setup in a multi-threaded use case.
Disclaimer: The above only takes the single-threaded asynchronous fetches into consideration (I haven't used nor considered the synchronous nor the threaded counterpart).
I forgot to mention that, in the current implementation, if the user does not set both the onerror/onsuccess handlers, and invokes emscripten_fetch_close() from there, then emscripten_fetch_t implicitly leaks.
AFAICS a simple usage of emscripten_fetch_close outside of callbacks will trigger an infinite loop, and if worked-around, a double free:
#include <emscripten.h>
#include <emscripten/fetch.h>
#include <string.h>
void onerror(emscripten_fetch_t *fetch) {
static int i = 0;
if (i == 0) {
//i++; // uncomment to escape recursion but trigger a double free
emscripten_fetch_close(fetch); // must be done on legit d/l error to avoid leak
}
}
int main() {
emscripten_fetch_attr_t attr;
emscripten_fetch_attr_init(&attr);
strcpy(attr.requestMethod, "GET");
attr.onerror = onerror;
emscripten_fetch(&attr, "myfile.dat");
emscripten_fetch_t* f = emscripten_fetch(&attr, "/very_long_download");
// user cancelled:
emscripten_fetch_close(f);
}
In addition the download doesn't seem interrupted anyway (no xhr.abort()), so in the current state I would remove the documentation bit mentioned in the original post. WDYT?
It would be good to update the docs, I agree. Mentioning that there is a bug, and linking to here, may be best.
As a temporary solution, I added an interrupt line in the final js file. function __emscripten_fetch_free(id) { Fetch.xhrs[id-1].abort(); //Note: should just be [id], but indexes off by 1 (see: #8803) delete Fetch.xhrs[id-1]; }
I also met this problem. Is there any new progress on this issue?
Does anyone have a workaround for this issue? Or alternatively, is there any progress on a real fix for this?
I made a pull request to fix this.
This issue should be closed, because it is resolved in my pull request that is already merged.
Thanks @kusharami , closing.
I can reproduce the bug in 3.1.27
@vedadkajtaz did you ever resolve your understanding the issues WRT the API design? I want to be able to abort my fetches, but I'm confused how emscripten_fetch_close() can be used without risk of access-after-free or double free. What if I call emscripten_fetch_close() to abort right as my onsuccess is being invoked?
I could check before trying to abort by calling emscripten_fetch_close() whether emscripten_fetch_t's readyState is LOADING or earlier, but I would worry that checking unsigned short readyState isn't atomic.
So I'm not sure how to abort. I might have thought there'd be one API to abort and another to free. There could be something about the WASM/.js interaction that I don't understand that makes this a non-issue.
I should add that I'm using PROXY_TO_PTHREAD and emscripten_set_main_loop_arg() and pthreads but can constrain myself to calling the fetch APIs from my em_arg_callback_func (with emscripten_async_run_in_main_runtime_thread()).
@kusharami - I couldn't tell yet from the description or code if your fix addresses this or other concerns. Do you have any advice? Thanks.
I have those fixes for 3 years already in my production code - all works great. But I am not calling emscripten_fetch_close in a working thread directly. I run it in a main thread like that:
void FetchDataReceiver::abortAll()
{
emscripten_dispatch_to_thread(
emscripten_main_browser_thread_id(), EM_FUNC_SIG_V, (void*)&FetchDataReceiver::abortAllInternal, nullptr);
}
void FetchDataReceiver::abortAllInternal()
{
auto fetches = std::move(sActiveFetches);
for (auto fetch : fetches) {
closeFetch(fetch);
}
}
void FetchDataReceiver::closeFetch(emscripten_fetch_t* fetch)
{
reinterpret_cast<FetchDataReceiver*>(fetch->userData)->mClosed = true;
sActiveFetches.erase(fetch);
emscripten_fetch_close(fetch);
}
void FetchDataReceiver::fetchInternal(FetchDataReceiver* thiz, const char* url)
{
thiz->mStartTimeMS = cc::utils::getTimeInMilliseconds();
sActiveFetches.insert(emscripten_fetch(&thiz->mAttr, url));
}
running fetch in a main thread too:
emscripten_dispatch_to_thread(emscripten_main_browser_thread_id(), EM_FUNC_SIG_VII,
(void*)&FetchDataReceiver::fetchInternal, nullptr, intptr_t(this), intptr_t(url.c_str()));
I also have an atomic flag that can abort a specific fetch, I just check that flag in onsuccess and onprogress handlers, and call emscripten_fetch_close if it was set and mClosed is not already set in userData
In onerror handler I check if mClosed flag is not set then I call emscripten_fetch_close there too.
But I don't know if there were some other changes which could break that in newer versions of emscripten, I use version 3.1.21.
@kusharami, I came to the conclusion I'd need to do something similar. Thanks for confirming!