From a837b3f9ef94147c14954d24983ea6325fe3aba0 Mon Sep 17 00:00:00 2001 From: Jake Hughes Date: Mon, 9 Sep 2024 20:15:59 +0100 Subject: [PATCH] Add a function for users to keep pointers alive This is useful for advanced users, who may allow references to GC objects to escape from their Gc 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. --- library/bdwgc/src/lib.rs | 2 ++ library/std/src/gc.rs | 10 +++++----- src/bdwgc | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/library/bdwgc/src/lib.rs b/library/bdwgc/src/lib.rs index e32dcca593223..3d336dbd60727 100644 --- a/library/bdwgc/src/lib.rs +++ b/library/bdwgc/src/lib.rs @@ -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); } diff --git a/library/std/src/gc.rs b/library/std/src/gc.rs index 7d1773104e560..c4d505176ca5a 100644 --- a/library/std/src/gc.rs +++ b/library/std/src/gc.rs @@ -173,6 +173,10 @@ pub fn thread_registered() -> bool { unsafe { bdwgc::GC_thread_is_registered() != 0 } } +pub fn keep_alive(ptr: *mut T) { + unsafe { bdwgc::GC_keep_alive(ptr as *mut u8) } +} + //////////////////////////////////////////////////////////////////////////////// // GC API //////////////////////////////////////////////////////////////////////////////// @@ -231,11 +235,7 @@ impl, U: ?Sized> DispatchFromDyn> for Gc {} #[cfg(all(not(bootstrap), not(test)))] impl Drop for Gc { 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); } } diff --git a/src/bdwgc b/src/bdwgc index 0da451d7a9bee..5fe238773ec92 160000 --- a/src/bdwgc +++ b/src/bdwgc @@ -1 +1 @@ -Subproject commit 0da451d7a9bee23ce839a2f7e203afc97a77ad83 +Subproject commit 5fe238773ec92e3588b1420126d15fade7872973