Skip to content

Commit

Permalink
Catch main thread callback errors #2239
Browse files Browse the repository at this point in the history
  • Loading branch information
CouleeApps committed Jun 24, 2021
1 parent 7f488c8 commit 4783514
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions mainthread.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ using namespace std;
struct MainThreadActionContext
{
function<void()> action;
exception_ptr exception;
};


Expand Down Expand Up @@ -53,7 +54,26 @@ void BinaryNinja::RegisterMainThread(MainThreadActionHandler* handler)
static void ExecuteAction(void* ctxt)
{
MainThreadActionContext* action = (MainThreadActionContext*)ctxt;
action->action();

// We can't throw across a thread and *certainly* not across the api boundary
// But how do we deal with exceptions thrown in main thread callbacks if the caller doesn't wait for them?
// Likely the only good solution is abort()
try
{
action->action();
}
catch (const std::exception& e)
{
LogError("Exception in main thread handler: %s", e.what());
fprintf(stderr, "Exception in main thread handler: %s\n", e.what());
abort();
}
catch (...)
{
LogError("Exception in main thread handler: <unknown exception>");
fprintf(stderr, "Exception in main thread handler: <unknown exception>\n");
abort();
}
delete action;
}

Expand All @@ -70,15 +90,27 @@ Ref<MainThreadAction> BinaryNinja::ExecuteOnMainThread(const function<void()>& a
static void ExecuteActionLocal(void* ctxt)
{
MainThreadActionContext* action = (MainThreadActionContext*)ctxt;
action->action();
try
{
action->action();
}
catch (...)
{
action->exception = current_exception();
}
}


void BinaryNinja::ExecuteOnMainThreadAndWait(const function<void()>& action)
{
MainThreadActionContext ctxt;
ctxt.action = action;
ctxt.exception = exception_ptr();
BNExecuteOnMainThreadAndWait(&ctxt, ExecuteActionLocal);
if (ctxt.exception)
{
rethrow_exception(ctxt.exception);
}
}


Expand Down

0 comments on commit 4783514

Please sign in to comment.