Skip to content

Commit

Permalink
WeakRef: Do not register non heap pointers as diasappearing links
Browse files Browse the repository at this point in the history
This should allow at least pointers to the data section
to work seamlessly with WeakRef and in some cases even
allow stack pointers to be passed, for the crazy
  • Loading branch information
jhass authored and bcardiff committed Apr 19, 2017
1 parent c49cf61 commit 8b0fd63
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
14 changes: 13 additions & 1 deletion spec/std/weak_ref_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,25 @@ private class Foo
end

describe WeakRef do
it "should get dereference object" do
it "should get dereferenced object" do
foo = Foo.new :foo
ref = WeakRef.new(foo)
ref.should_not be_nil
ref.target.should be(foo)
end

it "should get dereferenced object in data section" do
foo = "foo"
ref = WeakRef.new(foo)
ref.target.should be(foo)
end

it "should not crash with object in data section during GC" do
foo = "foo"
ref = WeakRef.new(foo)
GC.collect
end

it "State counts released objects" do
State.reset
State.count(:foo).should eq 0
Expand Down
5 changes: 5 additions & 0 deletions src/gc/boehm.cr
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ lib LibGC
fun set_handle_fork = GC_set_handle_fork(value : Int)

fun base = GC_base(displaced_pointer : Void*) : Void*
fun is_heap_ptr = GC_is_heap_ptr(pointer : Void*) : Int
fun general_register_disappearing_link = GC_general_register_disappearing_link(link : Void**, obj : Void*) : Int

type Finalizer = Void*, Void* ->
Expand Down Expand Up @@ -120,6 +121,10 @@ module GC
LibGC.general_register_disappearing_link(pointer, base)
end

def self.is_heap_ptr(pointer : Void*)
LibGC.is_heap_ptr(pointer) != 0
end

record Stats,
# collections : LibC::ULong,
# bytes_found : LibC::Long,
Expand Down
4 changes: 3 additions & 1 deletion src/weak_ref.cr
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ class WeakRef(T)

def initialize(target : T)
@target = target.as(Void*)
GC.register_disappearing_link(pointerof(@target))
if GC.is_heap_ptr(@target)
GC.register_disappearing_link(pointerof(@target))
end
end

def self.allocate
Expand Down

0 comments on commit 8b0fd63

Please sign in to comment.