Skip to content

Commit

Permalink
Add a function for users to keep pointers alive
Browse files Browse the repository at this point in the history
This is useful for advanced users, who may allow references to GC
objects to escape from their Gc<T> smart pointers. In such cases, one
must be careful to ensure that a finalizer is not run early because of
compiler optimisations (e.g. scalar replacement). This commit provides a
unified way to do this using the same mechanism as Gc::drop.
  • Loading branch information
jacob-hughes committed Sep 9, 2024
1 parent 1ca12b0 commit a837b3f
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 6 deletions.
2 changes: 2 additions & 0 deletions library/bdwgc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,4 +84,6 @@ extern "C" {
pub fn GC_ignore_warn_proc(proc: *mut u8, word: usize);

pub fn GC_finalized_total() -> u64;

pub fn GC_keep_alive(ptr: *mut u8);
}
10 changes: 5 additions & 5 deletions library/std/src/gc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,10 @@ pub fn thread_registered() -> bool {
unsafe { bdwgc::GC_thread_is_registered() != 0 }
}

pub fn keep_alive<T>(ptr: *mut T) {
unsafe { bdwgc::GC_keep_alive(ptr as *mut u8) }
}

////////////////////////////////////////////////////////////////////////////////
// GC API
////////////////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -231,11 +235,7 @@ impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Gc<U>> for Gc<T> {}
#[cfg(all(not(bootstrap), not(test)))]
impl<T: ?Sized> Drop for Gc<T> {
fn drop(&mut self) {
unsafe {
// asm macro clobber by default, so this is enough to introduce a
// barrier.
core::arch::asm!("/* {0} */", in(reg) self);
}
keep_alive(self);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/bdwgc
Submodule bdwgc updated 2 files
+7 −0 include/gc/gc.h
+5 −0 mark.c

0 comments on commit a837b3f

Please sign in to comment.