This repository has been archived by the owner on Nov 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 117
/
Copy pathrust.rs
1679 lines (1476 loc) · 55.7 KB
/
rust.rs
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Rust wrappers around the raw JS apis
use libc::c_uint;
use mozjs_sys::jsgc::CustomAutoRooterVFTable;
use mozjs_sys::jsgc::RootKind;
use mozjs_sys::jsgc::IntoHandle as IntoRawHandle;
use mozjs_sys::jsgc::IntoMutableHandle as IntoRawMutableHandle;
use std::char;
use std::ffi;
use std::ptr;
use std::slice;
use std::str;
use std::u32;
use std::default::Default;
use std::ffi::CStr;
use std::ops::{Deref, DerefMut};
use std::os::raw::c_void;
use std::cell::Cell;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicU32, Ordering};
use consts::{JSCLASS_RESERVED_SLOTS_MASK, JSCLASS_GLOBAL_SLOT_COUNT};
use consts::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL};
use conversions::jsstr_to_string;
use jsapi;
use jsapi::{AutoGCRooter, AutoGCRooter_Tag};
use jsapi::{Evaluate2, HandleValueArray, Heap};
use jsapi::{InitSelfHostedCode, IsWindowSlow};
use jsapi::{JS_DefineFunctions, JS_DefineProperties, JS_DestroyContext, JS_ShutDown};
use jsapi::{JS_EnumerateStandardClasses, JS_GetRuntime, JS_GlobalObjectTraceHook};
use jsapi::{JS_MayResolveStandardClass, JS_NewContext, JS_ResolveStandardClass};
use jsapi::{JS_SetGCParameter, JS_SetNativeStackQuota, JS_WrapValue, JSAutoRealm};
use jsapi::{JSClass, JSCLASS_RESERVED_SLOTS_SHIFT, JSClassOps, Realm, JSContext};
use jsapi::{JSErrorReport, JSFunction, JSFunctionSpec, JSGCParamKey};
use jsapi::{JSObject, JSPropertySpec, JSRuntime, JSScript};
use jsapi::{JSString, JSTracer, Object, ObjectGroup, PersistentRootedIdVector};
use jsapi::{PersistentRootedObjectVector, ReadOnlyCompileOptions, Rooted, RootingContext};
use jsapi::{SetWarningReporter, SourceText, Symbol, ToBooleanSlow};
use jsapi::{ToInt32Slow, ToInt64Slow, ToNumberSlow, ToStringSlow, ToUint16Slow};
use jsapi::{ToUint32Slow, ToUint64Slow, ToWindowProxyIfWindowSlow};
use jsapi::{Value, jsid};
use jsapi::{CaptureCurrentStack, BuildStackString, StackFormat};
use jsapi::{JS_StackCapture_AllFrames, JS_StackCapture_MaxFrames};
use jsapi::Handle as RawHandle;
use jsapi::HandleObjectVector as RawHandleObjectVector;
use jsapi::HandleValue as RawHandleValue;
use jsapi::MutableHandle as RawMutableHandle;
use jsapi::MutableHandleIdVector as RawMutableHandleIdVector;
use jsapi::glue::{JS_Init, JS_NewRealmOptions, DeleteRealmOptions};
use jsapi::JS::RegExpFlags;
#[cfg(feature = "debugmozjs")]
use jsapi::mozilla::detail::GuardObjectNotificationReceiver;
use jsapi::mozilla::Utf8Unit;
use jsval::ObjectValue;
use glue::{AppendToRootedObjectVector, CallFunctionTracer, CallIdTracer, CallObjectRootTracer};
use glue::{CallObjectTracer, CallScriptTracer, CallStringTracer, CallValueRootTracer};
use glue::{CallValueTracer, CreateRootedIdVector, CreateRootedObjectVector};
use glue::{DeleteCompileOptions, DeleteRootedObjectVector, DescribeScriptedCaller, DestroyRootedIdVector};
use glue::{GetIdVectorAddress, GetObjectVectorAddress, NewCompileOptions, SliceRootedIdVector};
use panic::maybe_resume_unwind;
use default_heapsize;
pub use mozjs_sys::jsgc::{GCMethods, IntoHandle, IntoMutableHandle};
// From Gecko:
// Our "default" stack is what we use in configurations where we don't have a compelling reason to
// do things differently. This is effectively 1MB on 64-bit platforms.
const STACK_QUOTA: usize = 128 * 8 * 1024;
// From Gecko:
// The JS engine permits us to set different stack limits for system code,
// trusted script, and untrusted script. We have tests that ensure that
// we can always execute 10 "heavy" (eval+with) stack frames deeper in
// privileged code. Our stack sizes vary greatly in different configurations,
// so satisfying those tests requires some care. Manual measurements of the
// number of heavy stack frames achievable gives us the following rough data,
// ordered by the effective categories in which they are grouped in the
// JS_SetNativeStackQuota call (which predates this analysis).
//
// (NB: These numbers may have drifted recently - see bug 938429)
// OSX 64-bit Debug: 7MB stack, 636 stack frames => ~11.3k per stack frame
// OSX64 Opt: 7MB stack, 2440 stack frames => ~3k per stack frame
//
// Linux 32-bit Debug: 2MB stack, 426 stack frames => ~4.8k per stack frame
// Linux 64-bit Debug: 4MB stack, 455 stack frames => ~9.0k per stack frame
//
// Windows (Opt+Debug): 900K stack, 235 stack frames => ~3.4k per stack frame
//
// Linux 32-bit Opt: 1MB stack, 272 stack frames => ~3.8k per stack frame
// Linux 64-bit Opt: 2MB stack, 316 stack frames => ~6.5k per stack frame
//
// We tune the trusted/untrusted quotas for each configuration to achieve our
// invariants while attempting to minimize overhead. In contrast, our buffer
// between system code and trusted script is a very unscientific 10k.
const SYSTEM_CODE_BUFFER: usize = 10 * 1024;
// Gecko's value on 64-bit.
const TRUSTED_SCRIPT_BUFFER: usize = 8 * 12800;
trait ToResult {
fn to_result(self) -> Result<(), ()>;
}
impl ToResult for bool {
fn to_result(self) -> Result<(), ()> {
if self {
Ok(())
} else {
Err(())
}
}
}
// ___________________________________________________________________________
// friendly Rustic API to runtimes
pub struct RealmOptions(*mut jsapi::RealmOptions);
impl Deref for RealmOptions {
type Target = jsapi::RealmOptions;
fn deref(&self) -> &Self::Target {
unsafe { &*self.0 }
}
}
impl DerefMut for RealmOptions {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *self.0 }
}
}
impl Default for RealmOptions {
fn default() -> RealmOptions {
RealmOptions(unsafe { JS_NewRealmOptions() })
}
}
impl Drop for RealmOptions {
fn drop(&mut self) {
unsafe { DeleteRealmOptions(self.0) }
}
}
thread_local!(static CONTEXT: Cell<*mut JSContext> = Cell::new(ptr::null_mut()));
#[derive(PartialEq)]
enum EngineState {
Uninitialized,
InitFailed,
Initialized,
ShutDown,
}
lazy_static! {
static ref ENGINE_STATE: Mutex<EngineState> = Mutex::new(EngineState::Uninitialized);
}
#[derive(Debug)]
pub enum JSEngineError {
AlreadyInitialized,
AlreadyShutDown,
InitFailed,
}
/// A handle that must be kept alive in order to create new Runtimes.
/// When this handle is dropped, the engine is shut down and cannot
/// be reinitialized.
pub struct JSEngine {
/// The count of alive handles derived from this initialized instance.
outstanding_handles: Arc<AtomicU32>,
// Ensure this type cannot be sent between threads.
marker: PhantomData<*mut ()>,
}
pub struct JSEngineHandle(Arc<AtomicU32>);
impl Clone for JSEngineHandle {
fn clone(&self) -> JSEngineHandle {
self.0.fetch_add(1, Ordering::SeqCst);
JSEngineHandle(self.0.clone())
}
}
impl Drop for JSEngineHandle {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
impl JSEngine {
/// Initialize the JS engine to prepare for creating new JS runtimes.
pub fn init() -> Result<JSEngine, JSEngineError> {
let mut state = ENGINE_STATE.lock().unwrap();
match *state {
EngineState::Initialized => return Err(JSEngineError::AlreadyInitialized),
EngineState::InitFailed => return Err(JSEngineError::InitFailed),
EngineState::ShutDown => return Err(JSEngineError::AlreadyShutDown),
EngineState::Uninitialized => (),
}
if unsafe { !JS_Init() } {
*state = EngineState::InitFailed;
Err(JSEngineError::InitFailed)
} else {
*state = EngineState::Initialized;
Ok(JSEngine {
outstanding_handles: Arc::new(AtomicU32::new(0)),
marker: PhantomData,
})
}
}
pub fn can_shutdown(&self) -> bool {
self.outstanding_handles.load(Ordering::SeqCst) == 0
}
/// Create a handle to this engine.
pub fn handle(&self) -> JSEngineHandle {
self.outstanding_handles.fetch_add(1, Ordering::SeqCst);
JSEngineHandle(self.outstanding_handles.clone())
}
}
/// Shut down the JS engine, invalidating any existing runtimes and preventing
/// any new ones from being created.
impl Drop for JSEngine {
fn drop(&mut self) {
let mut state = ENGINE_STATE.lock().unwrap();
if *state == EngineState::Initialized {
assert_eq!(
self.outstanding_handles.load(Ordering::SeqCst),
0,
"There are outstanding JS engine handles"
);
*state = EngineState::ShutDown;
unsafe {
JS_ShutDown();
}
}
}
}
pub fn transform_str_to_source_text(source: &str) -> SourceText<Utf8Unit> {
SourceText {
units_: source.as_ptr() as *const _,
length_: source.len() as u32,
ownsUnits_: false,
_phantom_0: PhantomData,
}
}
pub fn transform_u16_to_source_text(source: &[u16]) -> SourceText<u16> {
SourceText {
units_: source.as_ptr() as *const _,
length_: source.len() as u32,
ownsUnits_: false,
_phantom_0: PhantomData,
}
}
/// A handle to a Runtime that will be used to create a new runtime in another
/// thread. This handle and the new runtime must be destroyed before the original
/// runtime can be dropped.
pub struct ParentRuntime {
/// Raw pointer to the underlying SpiderMonkey runtime.
parent: *mut JSRuntime,
/// Handle to ensure the JS engine remains running while this handle exists.
engine: JSEngineHandle,
/// The number of children of the runtime that created this ParentRuntime value.
children_of_parent: Arc<()>,
}
unsafe impl Send for ParentRuntime {}
/// A wrapper for the `JSContext` structure in SpiderMonkey.
pub struct Runtime {
/// Raw pointer to the underlying SpiderMonkey context.
cx: *mut JSContext,
/// The engine that this runtime is associated with.
engine: JSEngineHandle,
/// If this Runtime was created with a parent, this member exists to ensure
/// that that parent's count of outstanding children (see [outstanding_children])
/// remains accurate and will be automatically decreased when this Runtime value
/// is dropped.
_parent_child_count: Option<Arc<()>>,
/// The strong references to this value represent the number of child runtimes
/// that have been created using this Runtime as a parent. Since Runtime values
/// must be associated with a particular thread, we cannot simply use Arc<Runtime>
/// to represent the resulting ownership graph and risk destroying a Runtime on
/// the wrong thread.
outstanding_children: Arc<()>,
}
impl Runtime {
/// Get the `JSContext` for this thread.
pub fn get() -> *mut JSContext {
let cx = CONTEXT.with(|context| {
context.get()
});
assert!(!cx.is_null());
cx
}
/// Creates a new `JSContext`.
pub fn new(engine: JSEngineHandle) -> Runtime {
unsafe { Self::create(engine, None) }
}
/// Signal that a new child runtime will be created in the future, and ensure
/// that this runtime will not allow itself to be destroyed before the new
/// child runtime. Returns a handle that can be passed to `create_with_parent`
/// in order to create a new runtime on another thread that is associated with
/// this runtime.
pub fn prepare_for_new_child(&self) -> ParentRuntime {
ParentRuntime {
parent: self.rt(),
engine: self.engine.clone(),
children_of_parent: self.outstanding_children.clone(),
}
}
/// Creates a new `JSContext` with a parent runtime. If the parent does not outlive
/// the new runtime, its destructor will assert.
///
/// Unsafety:
/// If panicking does not abort the program, any threads with child runtimes will
/// continue executing after the thread with the parent runtime panics, but they
/// will be in an invalid and undefined state.
pub unsafe fn create_with_parent(parent: ParentRuntime) -> Runtime {
Self::create(parent.engine.clone(), Some(parent))
}
unsafe fn create(engine: JSEngineHandle, parent: Option<ParentRuntime>) -> Runtime {
let parent_runtime = parent.as_ref().map_or(
ptr::null_mut(),
|r| r.parent,
);
let js_context = JS_NewContext(default_heapsize + (ChunkSize as u32), parent_runtime);
assert!(!js_context.is_null());
// Unconstrain the runtime's threshold on nominal heap size, to avoid
// triggering GC too often if operating continuously near an arbitrary
// finite threshold. This leaves the maximum-JS_malloc-bytes threshold
// still in effect to cause periodical, and we hope hygienic,
// last-ditch GCs from within the GC's allocator.
JS_SetGCParameter(
js_context, JSGCParamKey::JSGC_MAX_BYTES, u32::MAX);
JS_SetNativeStackQuota(
js_context,
STACK_QUOTA,
STACK_QUOTA - SYSTEM_CODE_BUFFER,
STACK_QUOTA - SYSTEM_CODE_BUFFER - TRUSTED_SCRIPT_BUFFER);
CONTEXT.with(|context| {
assert!(context.get().is_null());
context.set(js_context);
});
InitSelfHostedCode(js_context);
SetWarningReporter(js_context, Some(report_warning));
Runtime {
engine,
_parent_child_count: parent.map(|p| p.children_of_parent),
cx: js_context,
outstanding_children: Arc::new(()),
}
}
/// Returns the `JSRuntime` object.
pub fn rt(&self) -> *mut JSRuntime {
unsafe {
JS_GetRuntime(self.cx)
}
}
/// Returns the `JSContext` object.
pub fn cx(&self) -> *mut JSContext {
self.cx
}
pub fn evaluate_script(&self, glob: HandleObject, script: &str, filename: &str,
line_num: u32, rval: MutableHandleValue)
-> Result<(),()> {
let filename_cstr = ffi::CString::new(filename.as_bytes()).unwrap();
debug!("Evaluating script from {} with content {}", filename, script);
let _ac = JSAutoRealm::new(self.cx(), glob.get());
let options = unsafe {
CompileOptionsWrapper::new(self.cx(), filename_cstr.as_ptr(), line_num)
};
unsafe {
let mut source = transform_str_to_source_text(&script);
if !Evaluate2(self.cx(), options.ptr, &mut source, rval.into()) {
debug!("...err!");
maybe_resume_unwind();
Err(())
} else {
// we could return the script result but then we'd have
// to root it and so forth and, really, who cares?
debug!("...ok!");
Ok(())
}
}
}
}
impl Drop for Runtime {
fn drop(&mut self) {
assert_eq!(Arc::strong_count(&self.outstanding_children),
1,
"This runtime still has live children.");
unsafe {
JS_DestroyContext(self.cx);
CONTEXT.with(|context| {
assert_eq!(context.get(), self.cx);
context.set(ptr::null_mut());
});
}
}
}
// Creates a C string literal `$str`.
macro_rules! c_str {
($str:expr) => {
concat!($str, "\0").as_ptr() as *const ::std::os::raw::c_char
}
}
/// Types that can be traced.
///
/// This trait is unsafe; if it is implemented incorrectly, the GC may end up collecting objects
/// that are still reachable.
pub unsafe trait Trace {
unsafe fn trace(&self, trc: *mut JSTracer);
}
unsafe impl Trace for Heap<*mut JSFunction> {
unsafe fn trace(&self, trc: *mut JSTracer) {
CallFunctionTracer(trc, self as *const _ as *mut Self, c_str!("function"));
}
}
unsafe impl Trace for Heap<*mut JSObject> {
unsafe fn trace(&self, trc: *mut JSTracer) {
CallObjectTracer(trc, self as *const _ as *mut Self, c_str!("object"));
}
}
unsafe impl Trace for Heap<*mut JSScript> {
unsafe fn trace(&self, trc: *mut JSTracer) {
CallScriptTracer(trc, self as *const _ as *mut Self, c_str!("script"));
}
}
unsafe impl Trace for Heap<*mut JSString> {
unsafe fn trace(&self, trc: *mut JSTracer) {
CallStringTracer(trc, self as *const _ as *mut Self, c_str!("string"));
}
}
unsafe impl Trace for Heap<Value> {
unsafe fn trace(&self, trc: *mut JSTracer) {
CallValueTracer(trc, self as *const _ as *mut Self, c_str!("value"));
}
}
unsafe impl Trace for Heap<jsid> {
unsafe fn trace(&self, trc: *mut JSTracer) {
CallIdTracer(trc, self as *const _ as *mut Self, c_str!("id"));
}
}
/// Rust API for keeping a Rooted value in the context's root stack.
/// Example usage: `rooted!(in(cx) let x = UndefinedValue());`.
/// `RootedGuard::new` also works, but the macro is preferred.
pub struct RootedGuard<'a, T: 'a + RootKind + GCMethods> {
root: &'a mut Rooted<T>
}
impl<'a, T: 'a + RootKind + GCMethods> RootedGuard<'a, T> {
pub fn new(cx: *mut JSContext, root: &'a mut Rooted<T>, initial: T) -> Self {
root.ptr = initial;
unsafe {
root.add_to_root_stack(cx);
}
RootedGuard {
root: root
}
}
pub fn handle(&'a self) -> Handle<'a, T> {
Handle::new(&self.root.ptr)
}
pub fn handle_mut(&mut self) -> MutableHandle<T> {
unsafe {
MutableHandle::from_marked_location(&mut self.root.ptr)
}
}
pub fn get(&self) -> T where T: Copy {
self.root.ptr
}
pub fn set(&mut self, v: T) {
self.root.ptr = v;
}
}
impl<'a, T: 'a + RootKind + GCMethods> Deref for RootedGuard<'a, T> {
type Target = T;
fn deref(&self) -> &T {
&self.root.ptr
}
}
impl<'a, T: 'a + RootKind + GCMethods> DerefMut for RootedGuard<'a, T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.root.ptr
}
}
impl<'a, T: 'a + RootKind + GCMethods> Drop for RootedGuard<'a, T> {
fn drop(&mut self) {
unsafe {
self.root.ptr = T::initial();
self.root.remove_from_root_stack();
}
}
}
#[macro_export]
macro_rules! rooted {
(in($cx:expr) let $name:ident = $init:expr) => {
let mut __root = $crate::jsapi::Rooted::new_unrooted();
let $name = $crate::rust::RootedGuard::new($cx, &mut __root, $init);
};
(in($cx:expr) let mut $name:ident = $init:expr) => {
let mut __root = $crate::jsapi::Rooted::new_unrooted();
let mut $name = $crate::rust::RootedGuard::new($cx, &mut __root, $init);
};
(in($cx:expr) let $name:ident: $type:ty) => {
let mut __root = $crate::jsapi::Rooted::new_unrooted();
let $name = $crate::rust::RootedGuard::new($cx, &mut __root, <$type as $crate::rust::GCMethods>::initial());
};
(in($cx:expr) let mut $name:ident: $type:ty) => {
let mut __root = $crate::jsapi::Rooted::new_unrooted();
let mut $name = $crate::rust::RootedGuard::new($cx, &mut __root, <$type as $crate::rust::GCMethods>::initial());
};
}
/// Similarly to `Trace` trait, it's used to specify tracing of various types
/// that are used in conjunction with `CustomAutoRooter`.
pub unsafe trait CustomTrace {
fn trace(&self, trc: *mut JSTracer);
}
unsafe impl CustomTrace for *mut JSObject {
fn trace(&self, trc: *mut JSTracer) {
let this = self as *const *mut _ as *mut *mut _;
unsafe { CallObjectRootTracer(trc, this, c_str!("object")); }
}
}
unsafe impl CustomTrace for Value {
fn trace(&self, trc: *mut JSTracer) {
let this = self as *const _ as *mut _;
unsafe { CallValueRootTracer(trc, this, c_str!("any")); }
}
}
unsafe impl<T: CustomTrace> CustomTrace for Option<T> {
fn trace(&self, trc: *mut JSTracer) {
if let Some(ref some) = *self {
some.trace(trc);
}
}
}
unsafe impl<T: CustomTrace> CustomTrace for Vec<T> {
fn trace(&self, trc: *mut JSTracer) {
for elem in self {
elem.trace(trc);
}
}
}
// This structure reimplements a C++ class that uses virtual dispatch, so
// use C layout to guarantee that vftable in CustomAutoRooter is in right place.
#[repr(C)]
pub struct CustomAutoRooter<T> {
_base: jsapi::CustomAutoRooter,
data: T,
}
impl<T> CustomAutoRooter<T> {
unsafe fn add_to_root_stack(&mut self, cx: *mut JSContext) {
self._base._base.add_to_root_stack(cx);
}
unsafe fn remove_from_root_stack(&mut self) {
self._base._base.remove_from_root_stack();
}
}
/// `CustomAutoRooter` uses dynamic dispatch on the C++ side for custom tracing,
/// so provide trace logic via vftable when creating an object on Rust side.
unsafe trait CustomAutoTraceable: Sized {
const vftable: CustomAutoRooterVFTable = CustomAutoRooterVFTable {
padding: CustomAutoRooterVFTable::PADDING,
trace: Self::trace,
};
unsafe extern "C" fn trace(this: *mut c_void, trc: *mut JSTracer) {
let this = this as *const Self;
let this = this.as_ref().unwrap();
Self::do_trace(this, trc);
}
/// Used by `CustomAutoTraceable` implementer to trace its contents.
/// Corresponds to virtual `trace` call in a `CustomAutoRooter` subclass (C++).
fn do_trace(&self, trc: *mut JSTracer);
}
unsafe impl<T: CustomTrace> CustomAutoTraceable for CustomAutoRooter<T> {
fn do_trace(&self, trc: *mut JSTracer) {
self.data.trace(trc);
}
}
impl<T: CustomTrace> CustomAutoRooter<T> {
pub fn new(data: T) -> Self {
let vftable = &Self::vftable;
CustomAutoRooter {
_base: jsapi::CustomAutoRooter {
vtable_: vftable as *const _ as *const _,
_base: AutoGCRooter::new_unrooted(AutoGCRooter_Tag::Custom),
#[cfg(feature = "debugmozjs")]
_mCheckNotUsedAsTemporary: GuardObjectNotificationReceiver {
mStatementDone: false,
},
},
data,
}
}
pub fn root<'a>(&'a mut self, cx: *mut JSContext) -> CustomAutoRooterGuard<'a, T> {
CustomAutoRooterGuard::new(cx, self)
}
}
/// An RAII guard used to root underlying data in `CustomAutoRooter` until the
/// guard is dropped (falls out of scope).
/// The underlying data can be accessed through this guard via its Deref and
/// DerefMut implementations.
/// This structure is created by `root` method on `CustomAutoRooter` or
/// by the `auto_root!` macro.
pub struct CustomAutoRooterGuard<'a, T: 'a + CustomTrace> {
rooter: &'a mut CustomAutoRooter<T>
}
impl<'a, T: 'a + CustomTrace> CustomAutoRooterGuard<'a, T> {
pub fn new(cx: *mut JSContext, rooter: &'a mut CustomAutoRooter<T>) -> Self {
unsafe {
rooter.add_to_root_stack(cx);
}
CustomAutoRooterGuard {
rooter
}
}
pub fn handle(&'a self) -> Handle<'a, T> where T: RootKind {
Handle::new(&self.rooter.data)
}
pub fn handle_mut(&mut self) -> MutableHandle<T> where T: RootKind {
unsafe {
MutableHandle::from_marked_location(&mut self.rooter.data)
}
}
}
impl<'a, T: 'a + CustomTrace> Deref for CustomAutoRooterGuard<'a, T> {
type Target = T;
fn deref(&self) -> &T {
&self.rooter.data
}
}
impl<'a, T: 'a + CustomTrace> DerefMut for CustomAutoRooterGuard<'a, T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.rooter.data
}
}
impl<'a, T: 'a + CustomTrace> Drop for CustomAutoRooterGuard<'a, T> {
fn drop(&mut self) {
unsafe {
self.rooter.remove_from_root_stack();
}
}
}
pub type SequenceRooter<T> = CustomAutoRooter<Vec<T>>;
pub type SequenceRooterGuard<'a, T> = CustomAutoRooterGuard<'a, Vec<T>>;
#[macro_export]
macro_rules! auto_root {
(in($cx:expr) let $name:ident = $init:expr) => {
let mut __root = $crate::rust::CustomAutoRooter::new($init);
let $name = __root.root($cx);
};
(in($cx:expr) let mut $name:ident = $init:expr) => {
let mut __root = $crate::rust::CustomAutoRooter::new($init);
let mut $name = __root.root($cx);
}
}
#[derive(Clone, Copy)]
pub struct Handle<'a, T: 'a> {
ptr: &'a T,
}
#[derive(Copy, Clone)]
pub struct MutableHandle<'a, T: 'a> {
ptr: *mut T,
anchor: PhantomData<&'a mut T>,
}
pub type HandleFunction<'a> = Handle<'a, *mut JSFunction>;
pub type HandleId<'a> = Handle<'a, jsid>;
pub type HandleObject<'a> = Handle<'a, *mut JSObject>;
pub type HandleScript<'a> = Handle<'a, *mut JSScript>;
pub type HandleString<'a> = Handle<'a, *mut JSString>;
pub type HandleSymbol<'a> = Handle<'a, *mut Symbol>;
pub type HandleValue<'a> = Handle<'a, Value>;
pub type MutableHandleFunction<'a> = MutableHandle<'a, *mut JSFunction>;
pub type MutableHandleId<'a> = MutableHandle<'a, jsid>;
pub type MutableHandleObject<'a> = MutableHandle<'a, *mut JSObject>;
pub type MutableHandleScript<'a> = MutableHandle<'a, *mut JSScript>;
pub type MutableHandleString<'a> = MutableHandle<'a, *mut JSString>;
pub type MutableHandleSymbol<'a> = MutableHandle<'a, *mut Symbol>;
pub type MutableHandleValue<'a> = MutableHandle<'a, Value>;
impl<'a, T> Handle<'a, T> {
pub fn get(&self) -> T
where T: Copy
{
*self.ptr
}
pub fn new(ptr: &'a T) -> Self {
Handle { ptr: ptr }
}
pub unsafe fn from_marked_location(ptr: *const T) -> Self {
Handle::new(&*ptr)
}
pub unsafe fn from_raw(handle: RawHandle<T>) -> Self {
Handle::from_marked_location(handle.ptr)
}
}
impl<'a, T> IntoRawHandle for Handle<'a, T> {
type Target = T;
fn into_handle(self) -> RawHandle<T> {
unsafe { RawHandle::from_marked_location(self.ptr) }
}
}
impl<'a, T> IntoRawHandle for MutableHandle<'a, T> {
type Target = T;
fn into_handle(self) -> RawHandle<T> {
unsafe { RawHandle::from_marked_location(self.ptr) }
}
}
impl<'a, T> IntoRawMutableHandle for MutableHandle<'a, T> {
fn into_handle_mut(self) -> RawMutableHandle<T> {
unsafe { RawMutableHandle::from_marked_location(self.ptr) }
}
}
impl<'a, T> Deref for Handle<'a, T> {
type Target = T;
fn deref(&self) -> &T {
self.ptr
}
}
impl<'a, T> MutableHandle<'a, T> {
pub unsafe fn from_marked_location(ptr: *mut T) -> Self {
MutableHandle::new(&mut *ptr)
}
pub unsafe fn from_raw(handle: RawMutableHandle<T>) -> Self {
MutableHandle::from_marked_location(handle.ptr)
}
pub fn handle(&self) -> Handle<T> {
unsafe { Handle::new(&*self.ptr) }
}
pub fn new(ptr: &'a mut T) -> Self {
Self { ptr: ptr, anchor: PhantomData }
}
pub fn get(&self) -> T
where T: Copy
{
unsafe { *self.ptr }
}
pub fn set(&mut self, v: T)
where T: Copy
{
unsafe { *self.ptr = v }
}
fn raw(&mut self) -> RawMutableHandle<T> {
unsafe {
RawMutableHandle::from_marked_location(self.ptr)
}
}
}
impl<'a, T> Deref for MutableHandle<'a, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.ptr }
}
}
impl<'a, T> DerefMut for MutableHandle<'a, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.ptr }
}
}
impl HandleValue<'static> {
pub fn null() -> Self {
unsafe { Self::from_raw(RawHandleValue::null()) }
}
pub fn undefined() -> Self {
unsafe { Self::from_raw(RawHandleValue::undefined()) }
}
}
const ConstNullValue: *mut JSObject = 0 as *mut JSObject;
impl<'a> HandleObject<'a> {
pub fn null() -> Self {
unsafe {
HandleObject::from_marked_location(&ConstNullValue)
}
}
}
const ChunkShift: usize = 20;
const ChunkSize: usize = 1 << ChunkShift;
#[cfg(target_pointer_width = "32")]
const ChunkLocationOffset: usize = ChunkSize - 2 * 4 - 8;
// ___________________________________________________________________________
// Wrappers around things in jsglue.cpp
pub struct RootedObjectVectorWrapper {
pub ptr: *mut PersistentRootedObjectVector
}
impl RootedObjectVectorWrapper {
pub fn new(cx: *mut JSContext) -> RootedObjectVectorWrapper {
RootedObjectVectorWrapper {
ptr: unsafe {
CreateRootedObjectVector(cx)
}
}
}
pub fn append(&self, obj: *mut JSObject) -> bool {
unsafe {
AppendToRootedObjectVector(self.ptr, obj)
}
}
pub fn handle(&self) -> RawHandleObjectVector {
RawHandleObjectVector {
ptr: unsafe { GetObjectVectorAddress(self.ptr) }
}
}
}
impl Drop for RootedObjectVectorWrapper {
fn drop(&mut self) {
unsafe { DeleteRootedObjectVector(self.ptr) }
}
}
pub struct CompileOptionsWrapper {
pub ptr: *mut ReadOnlyCompileOptions
}
impl CompileOptionsWrapper {
pub unsafe fn new(cx: *mut JSContext, file: *const ::libc::c_char, line: c_uint) -> Self {
let ptr = NewCompileOptions(cx, file, line);
assert!(!ptr.is_null());
Self { ptr }
}
}
impl Drop for CompileOptionsWrapper {
fn drop(&mut self) {
unsafe { DeleteCompileOptions(self.ptr) }
}
}
// ___________________________________________________________________________
// Fast inline converters
#[inline]
pub unsafe fn ToBoolean(v: HandleValue) -> bool {
let val = *v.ptr;
if val.is_boolean() {
return val.to_boolean();
}
if val.is_int32() {
return val.to_int32() != 0;
}
if val.is_null_or_undefined() {
return false;
}
if val.is_double() {
let d = val.to_double();
return !d.is_nan() && d != 0f64;
}
if val.is_symbol() {
return true;
}
ToBooleanSlow(v.into())
}
#[inline]
pub unsafe fn ToNumber(cx: *mut JSContext, v: HandleValue) -> Result<f64, ()> {
let val = *v.ptr;
if val.is_number() {
return Ok(val.to_number());
}
let mut out = Default::default();
if ToNumberSlow(cx, v.into_handle(), &mut out) {
Ok(out)
} else {
Err(())
}
}
#[inline]
unsafe fn convert_from_int32<T: Default + Copy>(
cx: *mut JSContext,
v: HandleValue,
conv_fn: unsafe extern "C" fn(*mut JSContext, RawHandleValue, *mut T) -> bool)
-> Result<T, ()> {
let val = *v.ptr;
if val.is_int32() {
let intval: i64 = val.to_int32() as i64;
// TODO: do something better here that works on big endian
let intval = *(&intval as *const i64 as *const T);
return Ok(intval);
}