From: "jcalvert (Jonathan Calvert) via ruby-core" <ruby-core@...>
Date: 2024-09-06T21:45:06+00:00
Subject: [ruby-core:119091] [Ruby master Bug#20718] Objects created with Data_Make_Struct and the default free function are not freed

Issue #20718 has been reported by jcalvert (Jonathan Calvert).

----------------------------------------
Bug #20718: Objects created with Data_Make_Struct and the default free function are not freed
https://bugs.ruby-lang.org/issues/20718

* Author: jcalvert (Jonathan Calvert)
* Status: Open
* ruby -v: ruby 3.3.5 (2024-09-03 revision ef084cc8f4) [x86_64-linux]
* Backport: 3.1: UNKNOWN, 3.2: UNKNOWN, 3.3: UNKNOWN
----------------------------------------
I discovered a memory leak when using the FFI gem prior to version 1.16 and Ruby 3.3 and up.

During debugging I found that this earlier version of FFI uses Data_Make_Struct (https://github.com/ffi/ffi/blob/v1.15.5/ext/ffi_c/Pointer.c#L57) instead of TypedData_Make_Struct and it uses -1 as the free function, which is RUBY_DEFAULT_FREE

When the object goes to get garbage collected, it enters into rb_data_free and it is passed to the RTYPEDDATA_EMBEDDED_P macro even though it is not of RTypedData. Because of that, the conditional is evaluated to false and xfree is never called. This was discovered by using jemalloc leak detection.

I have attached a somewhat minimal replication of the issue. The fix would appear to check the type of the obj before casting it. 

---Files--------------------------------
pointer_bug.rb (418 Bytes)
Gemfile.txt (104 Bytes)


-- 
https://bugs.ruby-lang.org/
 ______________________________________________
 ruby-core mailing list -- ruby-core@ml.ruby-lang.org
 To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org
 ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/