From 8a3a049d9fb62046082631c06e17ed48467a53f6 Mon Sep 17 00:00:00 2001 From: Divy Srivastava Date: Tue, 18 Oct 2022 17:31:54 +0530 Subject: [PATCH] Access to raw v8::Context slots (#1092) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Bartek IwaƄczuk --- src/context.rs | 27 +++++++++++++++++++++++++++ tests/test_api.rs | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/src/context.rs b/src/context.rs index 4f230705..73e1aa13 100644 --- a/src/context.rs +++ b/src/context.rs @@ -52,6 +52,7 @@ extern "C" { impl Context { const ANNEX_SLOT: c_int = 1; + const INTERNAL_SLOT_COUNT: c_int = 1; /// Creates a new context. #[inline(always)] @@ -307,6 +308,32 @@ impl Context { } } + #[inline(always)] + pub unsafe fn set_aligned_pointer_in_embedder_data( + &self, + slot: i32, + data: *mut c_void, + ) { + v8__Context__SetAlignedPointerInEmbedderData( + self, + slot + Self::INTERNAL_SLOT_COUNT, + data, + ) + } + + #[inline(always)] + pub fn get_aligned_pointer_from_embedder_data( + &self, + slot: i32, + ) -> *mut c_void { + unsafe { + v8__Context__GetAlignedPointerFromEmbedderData( + self, + slot + Self::INTERNAL_SLOT_COUNT, + ) + } + } + /// Create a new context from a (non-default) context snapshot. There /// is no way to provide a global object template since we do not create /// a new global object from template, but we can reuse a global object. diff --git a/tests/test_api.rs b/tests/test_api.rs index 602bb8a8..a2b840ad 100644 --- a/tests/test_api.rs +++ b/tests/test_api.rs @@ -7674,6 +7674,46 @@ fn isolate_data_slots() { assert_eq!(actual1, expected1); } +#[test] +fn context_embedder_data() { + let _setup_guard = setup(); + let isolate = &mut v8::Isolate::new(Default::default()); + let global_context; + + let expected0 = "Bla"; + let expected1 = 123.456f64; + { + let scope = &mut v8::HandleScope::new(isolate); + let context = v8::Context::new(scope); + + unsafe { + context.set_aligned_pointer_in_embedder_data( + 0, + &expected0 as *const _ as *mut &str as *mut c_void, + ); + context.set_aligned_pointer_in_embedder_data( + 1, + &expected1 as *const _ as *mut f64 as *mut c_void, + ); + } + + global_context = v8::Global::new(scope, context); + } + + { + let scope = &mut v8::HandleScope::new(isolate); + let context = global_context.open(scope); + let actual0 = + context.get_aligned_pointer_from_embedder_data(0) as *mut &str; + let actual0 = unsafe { *actual0 }; + assert_eq!(actual0, expected0); + + let actual1 = context.get_aligned_pointer_from_embedder_data(1) as *mut f64; + let actual1 = unsafe { *actual1 }; + assert_eq!(actual1, expected1); + } +} + #[test] fn host_create_shadow_realm_context_callback() { let _setup_guard = setup();