1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// Copyright 2019-2021 the Deno authors. All rights reserved. MIT license.
use crate::handle::UnsafeRefHandle;
use crate::isolate::BuildTypeIdHasher;
use crate::isolate::Isolate;
use crate::isolate::RawSlot;
use crate::Context;
use crate::Function;
use crate::HandleScope;
use crate::Local;
use crate::Object;
use crate::ObjectTemplate;
use crate::Value;
use crate::Weak;
use libc::c_int;
use std::any::TypeId;
use std::collections::HashMap;
use std::ffi::c_void;
use std::ptr::{null, null_mut};

extern "C" {
  fn v8__Context__New(
    isolate: *mut Isolate,
    templ: *const ObjectTemplate,
    global_object: *const Value,
  ) -> *const Context;
  fn v8__Context__GetIsolate(this: *const Context) -> *mut Isolate;
  fn v8__Context__Global(this: *const Context) -> *const Object;
  fn v8__Context__GetExtrasBindingObject(this: *const Context)
    -> *const Object;
  fn v8__Context__SetPromiseHooks(
    this: *const Context,
    init_hook: *const Function,
    before_hook: *const Function,
    after_hook: *const Function,
    resolve_hook: *const Function,
  );
  fn v8__Context__GetNumberOfEmbedderDataFields(this: *const Context) -> u32;
  fn v8__Context__GetAlignedPointerFromEmbedderData(
    this: *const Context,
    index: c_int,
  ) -> *mut c_void;
  fn v8__Context__SetAlignedPointerInEmbedderData(
    this: *const Context,
    index: c_int,
    value: *mut c_void,
  );
}

impl Context {
  const ANNEX_SLOT: c_int = 1;

  /// Creates a new context.
  pub fn new<'s>(scope: &mut HandleScope<'s, ()>) -> Local<'s, Context> {
    // TODO: optional arguments;
    unsafe {
      scope
        .cast_local(|sd| v8__Context__New(sd.get_isolate_ptr(), null(), null()))
    }
    .unwrap()
  }

  /// Creates a new context using the object template as the template for
  /// the global object.
  pub fn new_from_template<'s>(
    scope: &mut HandleScope<'s, ()>,
    templ: Local<ObjectTemplate>,
  ) -> Local<'s, Context> {
    unsafe {
      scope.cast_local(|sd| {
        v8__Context__New(sd.get_isolate_ptr(), &*templ, null())
      })
    }
    .unwrap()
  }

  pub fn get_extras_binding_object<'s>(
    &self,
    scope: &mut HandleScope<'s, ()>,
  ) -> Local<'s, Object> {
    unsafe { scope.cast_local(|_| v8__Context__GetExtrasBindingObject(self)) }
      .unwrap()
  }

  /// Returns the global proxy object.
  ///
  /// Global proxy object is a thin wrapper whose prototype points to actual
  /// context's global object with the properties like Object, etc. This is done
  /// that way for security reasons (for more details see
  /// https://wiki.mozilla.org/Gecko:SplitWindow).
  ///
  /// Please note that changes to global proxy object prototype most probably
  /// would break VM---v8 expects only global object as a prototype of global
  /// proxy object.
  pub fn global<'s>(
    &self,
    scope: &mut HandleScope<'s, ()>,
  ) -> Local<'s, Object> {
    unsafe { scope.cast_local(|_| v8__Context__Global(self)) }.unwrap()
  }

  pub fn set_promise_hooks(
    &self,
    init_hook: Local<Function>,
    before_hook: Local<Function>,
    after_hook: Local<Function>,
    resolve_hook: Local<Function>,
  ) {
    unsafe {
      v8__Context__SetPromiseHooks(
        self,
        &*init_hook,
        &*before_hook,
        &*after_hook,
        &*resolve_hook,
      )
    }
  }

  fn get_annex_mut<'a>(
    &'a self,
    isolate: &'a mut Isolate,
    create_if_not_present: bool,
  ) -> Option<&'a mut ContextAnnex> {
    assert!(
      std::ptr::eq(isolate, unsafe { v8__Context__GetIsolate(self) }),
      "attempted to use Context slots with the wrong Isolate"
    );

    let num_data_fields =
      unsafe { v8__Context__GetNumberOfEmbedderDataFields(self) } as c_int;
    if num_data_fields > Self::ANNEX_SLOT {
      let annex_ptr = unsafe {
        v8__Context__GetAlignedPointerFromEmbedderData(self, Self::ANNEX_SLOT)
      } as *mut ContextAnnex;
      if !annex_ptr.is_null() {
        // SAFETY: This reference doesn't outlive the Context, so it can't outlive
        // the annex itself. Also, any mutations or accesses to the annex after
        // its creation require a mutable reference to the context's isolate, but
        // such a mutable reference is consumed by this reference during its
        // lifetime.
        return Some(unsafe { &mut *annex_ptr });
      }
    }

    if !create_if_not_present {
      return None;
    }

    let annex = Box::new(ContextAnnex {
      slots: Default::default(),
      // Gets replaced later in the method.
      self_weak: Weak::empty(isolate),
    });
    let annex_ptr = Box::into_raw(annex);
    unsafe {
      v8__Context__SetAlignedPointerInEmbedderData(
        self,
        Self::ANNEX_SLOT,
        annex_ptr as *mut _,
      )
    };
    assert!(
      unsafe { v8__Context__GetNumberOfEmbedderDataFields(self) } as c_int
        > Self::ANNEX_SLOT
    );

    // Make sure to drop the annex after the context is dropped, by creating a
    // weak handle with a finalizer that drops the annex, and storing the weak
    // in the annex itself.
    let weak = {
      // SAFETY: `self` can only have been derived from a `Local` or `Global`,
      // and assuming the caller is only using safe code, the `Local` or
      // `Global` must still be alive, so `self_ref_handle` won't outlive it.
      // We also check above that `isolate` is the context's isolate.
      let self_ref_handle = unsafe { UnsafeRefHandle::new(self, isolate) };

      Weak::with_finalizer(
        isolate,
        self_ref_handle,
        Box::new(move |_| {
          // SAFETY: The lifetimes of references to the annex returned by this
          // method are always tied to the context, and because this is the
          // context's finalizer, we know there are no living references to
          // the annex. And since the finalizer is only called once, the annex
          // can't have been dropped before.
          let _ = unsafe { Box::from_raw(annex_ptr) };
        }),
      )
    };

    // SAFETY: This reference doesn't outlive the Context, so it can't outlive
    // the annex itself. Also, any mutations or accesses to the annex after
    // its creation require a mutable reference to the context's isolate, but
    // such a mutable reference is consumed by this reference during its
    // lifetime.
    let annex_mut = unsafe { &mut *annex_ptr };
    annex_mut.self_weak = weak;
    Some(annex_mut)
  }

  /// Get a reference to embedder data added with [`Self::set_slot()`].
  pub fn get_slot<'a, T: 'static>(
    &'a self,
    isolate: &'a mut Isolate,
  ) -> Option<&'a T> {
    if let Some(annex) = self.get_annex_mut(isolate, false) {
      annex.slots.get(&TypeId::of::<T>()).map(|slot| {
        // SAFETY: `Self::set_slot` guarantees that only values of type T will be
        // stored with T's TypeId as their key.
        unsafe { slot.borrow::<T>() }
      })
    } else {
      None
    }
  }

  /// Get a mutable reference to embedder data added with [`Self::set_slot()`].
  pub fn get_slot_mut<'a, T: 'static>(
    &'a self,
    isolate: &'a mut Isolate,
  ) -> Option<&'a mut T> {
    if let Some(annex) = self.get_annex_mut(isolate, false) {
      annex.slots.get_mut(&TypeId::of::<T>()).map(|slot| {
        // SAFETY: `Self::set_slot` guarantees that only values of type T will be
        // stored with T's TypeId as their key.
        unsafe { slot.borrow_mut::<T>() }
      })
    } else {
      None
    }
  }

  /// Use with [`Context::get_slot`] and [`Context::get_slot_mut`] to associate
  /// state with a Context.
  ///
  /// This method gives ownership of value to the Context. Exactly one object of
  /// each type can be associated with a Context. If called more than once with
  /// an object of the same type, the earlier version will be dropped and
  /// replaced.
  ///
  /// Returns true if value was set without replacing an existing value.
  ///
  /// The value will be dropped when the context is garbage collected.
  pub fn set_slot<'a, T: 'static>(
    &'a self,
    isolate: &'a mut Isolate,
    value: T,
  ) -> bool {
    self
      .get_annex_mut(isolate, true)
      .unwrap()
      .slots
      .insert(TypeId::of::<T>(), RawSlot::new(value))
      .is_none()
  }

  /// Removes the embedder data added with [`Self::set_slot()`] and returns it
  /// if it exists.
  pub fn remove_slot<'a, T: 'static>(
    &'a self,
    isolate: &'a mut Isolate,
  ) -> Option<T> {
    if let Some(annex) = self.get_annex_mut(isolate, false) {
      annex.slots.remove(&TypeId::of::<T>()).map(|slot| {
        // SAFETY: `Self::set_slot` guarantees that only values of type T will be
        // stored with T's TypeId as their key.
        unsafe { slot.into_inner::<T>() }
      })
    } else {
      None
    }
  }

  /// Removes all embedder data added with [`Self::set_slot()`], and
  /// deletes any internal state needed to keep track of such slots.
  ///
  /// This is needed to make a snapshot with
  /// [`SnapshotCreator`](crate::SnapshotCreator), since the internal embedder
  /// state uses [`Weak`] handles, which cannot be alive at the time of
  /// snapshotting.
  pub fn clear_all_slots<'a>(&'a self, isolate: &'a mut Isolate) {
    if let Some(annex_mut) = self.get_annex_mut(isolate, false) {
      let annex_ptr = annex_mut as *mut ContextAnnex;
      let _ = unsafe { Box::from_raw(annex_ptr) };
      unsafe {
        v8__Context__SetAlignedPointerInEmbedderData(
          self,
          Self::ANNEX_SLOT,
          null_mut(),
        )
      };
    }
  }
}

struct ContextAnnex {
  slots: HashMap<TypeId, RawSlot, BuildTypeIdHasher>,
  // In order to run the finalizer that drops the ContextAnnex when the Context
  // is GC'd, the corresponding Weak must be kept alive until that time.
  self_weak: Weak<Context>,
}