Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions ext/semian/resource.c
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ semian_resource_initialize(VALUE self, VALUE id, VALUE tickets, VALUE quota, VAL

// Populate struct fields
ms_to_timespec(c_timeout * 1000, &res->timeout);
res->name = strdup(c_id_str);
res->name = ruby_strdup(c_id_str);
res->quota = c_quota;
res->wait_time = -1;

Expand Down Expand Up @@ -370,11 +370,18 @@ static void
semian_resource_free(void *ptr)
{
semian_resource_t *res = (semian_resource_t *) ptr;

if (res->name) {
free(res->name);
xfree(res->name); // ruby_strdup
res->name = NULL;
}
xfree(res);

if (res->strkey) {
free(res->strkey); // malloc
res->strkey = NULL;
}

xfree(res); // TypedData_Make_Struct
}

static size_t
Expand Down
16 changes: 16 additions & 0 deletions test/resource_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,15 @@ def test_get_resource_key
assert_equal("0x874714f2", resource.key)
end

def test_resource_native_memory_can_be_reclaimed_by_gc
# Regression coverage for Semian::Resource's native free callback. ASAN/LSAN
# builds catch allocator mismatches and leaked native fields when GC runs it.
10.times do |i|
create_and_destroy_untracked_resource("testing_gc_#{Process.pid}_#{i}")
GC.start(full_mark: true, immediate_sweep: true)
end
end

def test_count
resource = create_resource(:testing, tickets: 2)
acquired = false
Expand Down Expand Up @@ -600,6 +609,13 @@ def create_resource(name, **kwargs)
resource
end

def create_and_destroy_untracked_resource(name)
resource = create_resource(name, tickets: 1)
resource.destroy
@resources.delete(resource)
nil
end

def destroy_resources
return unless @resources

Expand Down
Loading