From 031636cfb340a13585d9a10917aed76dc1e6818b Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Mon, 25 Sep 2023 17:18:18 +0200 Subject: [PATCH 1/2] Handle null pointer in async_cb_dispatcher mark and free Fix: https://github.com/ffi/ffi/issues/1050 I don't fully understand that code, so my fix might be totally off. But according to production crashes, `ctx` might be NULL sometimes. --- ext/ffi_c/Function.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/ext/ffi_c/Function.c b/ext/ffi_c/Function.c index 78100563a..996d7b75e 100644 --- a/ext/ffi_c/Function.c +++ b/ext/ffi_c/Function.c @@ -166,14 +166,18 @@ static void async_cb_dispatcher_mark(void *ptr) { struct async_cb_dispatcher *ctx = (struct async_cb_dispatcher *)ptr; - rb_gc_mark(ctx->thread); + if (ctx) { + rb_gc_mark(ctx->thread); + } } static void async_cb_dispatcher_free(void *ptr) { struct async_cb_dispatcher *ctx = (struct async_cb_dispatcher *)ptr; - xfree(ctx); + if (ctx) { + xfree(ctx); + } } struct rb_ractor_local_storage_type async_cb_dispatcher_key_type = { From 97ce4efd11582e74fcf24493f80b94cb786a6e7f Mon Sep 17 00:00:00 2001 From: Lars Kanis Date: Mon, 25 Sep 2023 20:28:32 +0200 Subject: [PATCH 2/2] Add test case for #1050 Fixing commit is 031636cfb340a13585d9a10917aed76dc1e6818b --- spec/ffi/fork_spec.rb | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/spec/ffi/fork_spec.rb b/spec/ffi/fork_spec.rb index 2c663ee2a..421982df2 100644 --- a/spec/ffi/fork_spec.rb +++ b/spec/ffi/fork_spec.rb @@ -62,5 +62,14 @@ def run_async_callback(libtest) expect(Process.wait2[1].exitstatus).to eq(44) end + + it "GC doesn't crash when the dispatcher thread was stopped. #1050" do + FFI::Function.new(:int, [], proc{}) + fork do + GC.start + Process.exit 45 + end + expect(Process.wait2[1].exitstatus).to eq(45) + end end end