Skip to content

Commit

Permalink
darwin: Fix racy teardown of SpawnInstance dispatch source
Browse files Browse the repository at this point in the history
Need to cancel the source and wait for the cancellation handler to be
called before releasing the Mach port being monitored.
  • Loading branch information
oleavr committed May 6, 2024
1 parent 60ef8a7 commit cacdd3e
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/darwin/frida-helper-backend-glue.m
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,7 @@
static void frida_spawn_instance_free (FridaSpawnInstance * instance);
static void frida_spawn_instance_resume (FridaSpawnInstance * self);

static void frida_spawn_instance_on_server_cancel (void * context);
static void frida_spawn_instance_on_server_recv (void * context);
static gboolean frida_spawn_instance_handle_breakpoint (FridaSpawnInstance * self, FridaBreakpoint * breakpoint, GumDarwinUnifiedThreadState * state);
static gboolean frida_spawn_instance_handle_dyld_restart (FridaSpawnInstance * self);
Expand Down Expand Up @@ -2138,6 +2139,7 @@ static void frida_darwin_helper_backend_launch_using_lsaw (NSString * identifier
source = dispatch_source_create (DISPATCH_SOURCE_TYPE_MACH_RECV, instance->server_port, 0, ctx->dispatch_queue);
instance->server_recv_source = source;
dispatch_set_context (source, instance);
dispatch_source_set_cancel_handler_f (source, frida_spawn_instance_on_server_cancel);
dispatch_source_set_event_handler_f (source, frida_spawn_instance_on_server_recv);
dispatch_resume (source);

Expand Down Expand Up @@ -2756,6 +2758,12 @@ static void frida_darwin_helper_backend_launch_using_lsaw (NSString * identifier
FridaExceptionPortSet * previous_ports;
mach_msg_type_number_t port_index;

if (instance->server_recv_source != NULL)
{
dispatch_source_cancel (instance->server_recv_source);
return;
}

self_task = mach_task_self ();

if (instance->do_modinit_strcmp_checks != NULL)
Expand All @@ -2768,8 +2776,6 @@ static void frida_darwin_helper_backend_launch_using_lsaw (NSString * identifier
{
mach_port_deallocate (self_task, previous_ports->ports[port_index]);
}
if (instance->server_recv_source != NULL)
dispatch_release (instance->server_recv_source);
if (instance->server_port != MACH_PORT_NULL)
{
mach_port_mod_refs (self_task, instance->server_port, MACH_PORT_RIGHT_SEND, -1);
Expand Down Expand Up @@ -2821,6 +2827,15 @@ static void frida_darwin_helper_backend_launch_using_lsaw (NSString * identifier
frida_spawn_instance_send_breakpoint_response (self);
}

static void
frida_spawn_instance_on_server_cancel (void * context)
{
FridaSpawnInstance * self = context;

dispatch_release (g_steal_pointer (&self->server_recv_source));
frida_spawn_instance_free (self);
}

static void
frida_spawn_instance_on_server_recv (void * context)
{
Expand Down

0 comments on commit cacdd3e

Please sign in to comment.