Thanks to visit codestin.com
Credit goes to github.com

Skip to content

AutoPointer subclasses cause double free when cloned #1155

@uvlad7

Description

@uvlad7
require 'ffi'
require 'ffi/libc'

puts FFI::VERSION

class CPtr < FFI::AutoPointer
  def self.from_native(ptr, _ctx)
    raise Error, 'malloc failed' if ptr.null?
    super
  end

  def self.release(ptr)
    p ptr
    C.free(ptr) unless ptr.null?
  end
end

module C
  extend FFI::Library
  ffi_lib FFI::Library::LIBC

  attach_function :malloc, [:size_t], CPtr
  attach_function :free, [CPtr], :void
end

# ptr = FFI::AutoPointer.new(FFI::LibC.malloc(4), FFI::LibC.method(:free))
# p ptr
# p ptr.dup
# # 1.17.2
# # #<FFI::AutoPointer address=0x00005fa73349c690>
# # test_ffi.rb:28:in `initialize_copy': cannot duplicate unbounded memory area (RuntimeError)
# # 	from test_ffi.rb:28:in `initialize_dup'
# # 	from test_ffi.rb:28:in `dup'
# # 	from test_ffi.rb:28:in `<main>'
# # free(): double free detected in tcache 2
# # Aborted (core dumped)
# # Same with clone

# val = C.malloc(4)
# p val
# # val.autorelease = false
# p val.dup
# # 1.17.2
# # #<CPtr address=0x0000556540d42870>
# # test_ffi.rb:43:in `initialize_copy': cannot duplicate unbounded memory area (RuntimeError)
# # 	from test_ffi.rb:43:in `initialize_dup'
# # 	from test_ffi.rb:43:in `dup'
# # 	from test_ffi.rb:43:in `<main>'
# # #<FFI::Pointer address=0x0000556540d42870>
# # #<FFI::Pointer address=0x0000556540d42870>
# # free(): double free detected in tcache 2
# # Aborted (core dumped)
# # Same with clone

I guess autorelease must be set to false when the exception is raised, or it should be raised before ptr is assigned

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions