/
jsapi.h
3758 lines (3076 loc) · 144 KB
/
jsapi.h
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* 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/. */
/* JavaScript API. */
#ifndef jsapi_h
#define jsapi_h
#include "mozilla/AlreadyAddRefed.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/Range.h"
#include "mozilla/RangedPtr.h"
#include "mozilla/RefPtr.h"
#include "mozilla/Utf8.h"
#include "mozilla/Variant.h"
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include "jspubtd.h"
#include "js/AllocPolicy.h"
#include "js/CallArgs.h"
#include "js/CharacterEncoding.h"
#include "js/Class.h"
#include "js/CompileOptions.h"
#include "js/ErrorReport.h"
#include "js/GCVector.h"
#include "js/HashTable.h"
#include "js/Id.h"
#include "js/OffThreadScriptCompilation.h"
#include "js/Principals.h"
#include "js/PropertyDescriptor.h"
#include "js/Realm.h"
#include "js/RefCounted.h"
#include "js/RootingAPI.h"
#include "js/TracingAPI.h"
#include "js/Transcoding.h"
#include "js/UniquePtr.h"
#include "js/Utility.h"
#include "js/Value.h"
#include "js/Vector.h"
/************************************************************************/
struct JSFreeOp;
struct JSFunctionSpec;
struct JSPropertySpec;
namespace JS {
template <typename UnitT>
class SourceText;
class TwoByteChars;
/** AutoValueArray roots an internal fixed-size array of Values. */
template <size_t N>
class MOZ_RAII AutoValueArray : public AutoGCRooter {
const size_t length_;
Value elements_[N];
public:
explicit AutoValueArray(JSContext* cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, AutoGCRooter::Tag::ValueArray), length_(N) {
/* Always initialize in case we GC before assignment. */
mozilla::PodArrayZero(elements_);
MOZ_GUARD_OBJECT_NOTIFIER_INIT;
}
unsigned length() const { return length_; }
const Value* begin() const { return elements_; }
Value* begin() { return elements_; }
HandleValue operator[](unsigned i) const {
MOZ_ASSERT(i < N);
return HandleValue::fromMarkedLocation(&elements_[i]);
}
MutableHandleValue operator[](unsigned i) {
MOZ_ASSERT(i < N);
return MutableHandleValue::fromMarkedLocation(&elements_[i]);
}
MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
};
using ValueVector = JS::GCVector<JS::Value>;
using IdVector = JS::GCVector<jsid>;
using ScriptVector = JS::GCVector<JSScript*>;
using StringVector = JS::GCVector<JSString*>;
/**
* Custom rooting behavior for internal and external clients.
*/
class MOZ_RAII JS_PUBLIC_API CustomAutoRooter : private AutoGCRooter {
public:
template <typename CX>
explicit CustomAutoRooter(const CX& cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
: AutoGCRooter(cx, AutoGCRooter::Tag::Custom) {
MOZ_GUARD_OBJECT_NOTIFIER_INIT;
}
friend void AutoGCRooter::trace(JSTracer* trc);
protected:
virtual ~CustomAutoRooter() {}
/** Supplied by derived class to trace roots. */
virtual void trace(JSTracer* trc) = 0;
private:
MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
};
/** A handle to an array of rooted values. */
class HandleValueArray {
const size_t length_;
const Value* const elements_;
HandleValueArray(size_t len, const Value* elements)
: length_(len), elements_(elements) {}
public:
explicit HandleValueArray(HandleValue value)
: length_(1), elements_(value.address()) {}
MOZ_IMPLICIT HandleValueArray(const AutoValueVector& values)
: length_(values.length()), elements_(values.begin()) {}
template <size_t N>
MOZ_IMPLICIT HandleValueArray(const AutoValueArray<N>& values)
: length_(N), elements_(values.begin()) {}
/** CallArgs must already be rooted somewhere up the stack. */
MOZ_IMPLICIT HandleValueArray(const JS::CallArgs& args)
: length_(args.length()), elements_(args.array()) {}
/** Use with care! Only call this if the data is guaranteed to be marked. */
static HandleValueArray fromMarkedLocation(size_t len,
const Value* elements) {
return HandleValueArray(len, elements);
}
static HandleValueArray subarray(const HandleValueArray& values,
size_t startIndex, size_t len) {
MOZ_ASSERT(startIndex + len <= values.length());
return HandleValueArray(len, values.begin() + startIndex);
}
static HandleValueArray empty() { return HandleValueArray(0, nullptr); }
size_t length() const { return length_; }
const Value* begin() const { return elements_; }
HandleValue operator[](size_t i) const {
MOZ_ASSERT(i < length_);
return HandleValue::fromMarkedLocation(&elements_[i]);
}
};
} /* namespace JS */
/* Callbacks and their arguments. */
/************************************************************************/
typedef bool (*JSInterruptCallback)(JSContext* cx);
/**
* Callback used to ask the embedding for the cross compartment wrapper handler
* that implements the desired prolicy for this kind of object in the
* destination compartment. |obj| is the object to be wrapped. If |existing| is
* non-nullptr, it will point to an existing wrapper object that should be
* re-used if possible. |existing| is guaranteed to be a cross-compartment
* wrapper with a lazily-defined prototype and the correct global. It is
* guaranteed not to wrap a function.
*/
typedef JSObject* (*JSWrapObjectCallback)(JSContext* cx,
JS::HandleObject existing,
JS::HandleObject obj);
/**
* Callback used by the wrap hook to ask the embedding to prepare an object
* for wrapping in a context. This might include unwrapping other wrappers
* or even finding a more suitable object for the new compartment.
*/
typedef void (*JSPreWrapCallback)(JSContext* cx, JS::HandleObject scope,
JS::HandleObject obj,
JS::HandleObject objectPassedToWrap,
JS::MutableHandleObject retObj);
struct JSWrapObjectCallbacks {
JSWrapObjectCallback wrap;
JSPreWrapCallback preWrap;
};
typedef void (*JSDestroyCompartmentCallback)(JSFreeOp* fop,
JS::Compartment* compartment);
typedef size_t (*JSSizeOfIncludingThisCompartmentCallback)(
mozilla::MallocSizeOf mallocSizeOf, JS::Compartment* compartment);
/**
* Callback used by memory reporting to ask the embedder how much memory an
* external string is keeping alive. The embedder is expected to return a value
* that corresponds to the size of the allocation that will be released by the
* JSStringFinalizer passed to JS_NewExternalString for this string.
*
* Implementations of this callback MUST NOT do anything that can cause GC.
*/
using JSExternalStringSizeofCallback =
size_t (*)(JSString* str, mozilla::MallocSizeOf mallocSizeOf);
/**
* Callback used to intercept JavaScript errors.
*/
struct JSErrorInterceptor {
/**
* This method is called whenever an error has been raised from JS code.
*
* This method MUST be infallible.
*/
virtual void interceptError(JSContext* cx, JS::HandleValue error) = 0;
};
/************************************************************************/
static MOZ_ALWAYS_INLINE JS::Value JS_NumberValue(double d) {
int32_t i;
d = JS::CanonicalizeNaN(d);
if (mozilla::NumberIsInt32(d, &i)) {
return JS::Int32Value(i);
}
return JS::DoubleValue(d);
}
/************************************************************************/
JS_PUBLIC_API bool JS_StringHasBeenPinned(JSContext* cx, JSString* str);
/************************************************************************/
/** Microseconds since the epoch, midnight, January 1, 1970 UTC. */
extern JS_PUBLIC_API int64_t JS_Now(void);
/** Don't want to export data, so provide accessors for non-inline Values. */
extern JS_PUBLIC_API JS::Value JS_GetNaNValue(JSContext* cx);
extern JS_PUBLIC_API JS::Value JS_GetNegativeInfinityValue(JSContext* cx);
extern JS_PUBLIC_API JS::Value JS_GetPositiveInfinityValue(JSContext* cx);
extern JS_PUBLIC_API JS::Value JS_GetEmptyStringValue(JSContext* cx);
extern JS_PUBLIC_API JSString* JS_GetEmptyString(JSContext* cx);
extern JS_PUBLIC_API bool JS_ValueToObject(JSContext* cx, JS::HandleValue v,
JS::MutableHandleObject objp);
extern JS_PUBLIC_API JSFunction* JS_ValueToFunction(JSContext* cx,
JS::HandleValue v);
extern JS_PUBLIC_API JSFunction* JS_ValueToConstructor(JSContext* cx,
JS::HandleValue v);
extern JS_PUBLIC_API JSString* JS_ValueToSource(JSContext* cx,
JS::Handle<JS::Value> v);
extern JS_PUBLIC_API bool JS_DoubleIsInt32(double d, int32_t* ip);
extern JS_PUBLIC_API JSType JS_TypeOfValue(JSContext* cx,
JS::Handle<JS::Value> v);
namespace JS {
extern JS_PUBLIC_API const char* InformalValueTypeName(const JS::Value& v);
} /* namespace JS */
/** True iff fun is the global eval function. */
extern JS_PUBLIC_API bool JS_IsBuiltinEvalFunction(JSFunction* fun);
/** True iff fun is the Function constructor. */
extern JS_PUBLIC_API bool JS_IsBuiltinFunctionConstructor(JSFunction* fun);
/************************************************************************/
// [SMDOC] Data Structures (JSContext, JSRuntime, Realm, Compartment, Zone)
//
// SpiderMonkey uses some data structures that behave a lot like Russian dolls:
// runtimes contain zones, zones contain compartments, compartments contain
// realms. Each layer has its own purpose.
//
// Realm
// -----
// Data associated with a global object. In the browser each frame has its
// own global/realm.
//
// Compartment
// -----------
// Security membrane; when an object from compartment A is used in compartment
// B, a cross-compartment wrapper (a kind of proxy) is used. In the browser each
// compartment currently contains one global/realm, but we want to change that
// so each compartment contains multiple same-origin realms (bug 1357862).
//
// Zone
// ----
// A Zone is a group of compartments that share GC resources (arenas, strings,
// etc) for memory usage and performance reasons. Zone is the GC unit: the GC
// can operate on one or more zones at a time. The browser uses roughly one zone
// per tab.
//
// Context
// -------
// JSContext represents a thread: there must be exactly one JSContext for each
// thread running JS/Wasm. Internally, helper threads have their own JSContext.
//
// Runtime
// -------
// JSRuntime is very similar to JSContext: each runtime belongs to one context
// (thread), but helper threads don't have their own runtimes (they're shared by
// all runtimes in the process and use the runtime of the task they're
// executing).
/*
* Locking, contexts, and memory allocation.
*
* It is important that SpiderMonkey be initialized, and the first context
* be created, in a single-threaded fashion. Otherwise the behavior of the
* library is undefined.
* See:
* https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/JSAPI_reference
*/
// Create a new context (and runtime) for this thread.
extern JS_PUBLIC_API JSContext* JS_NewContext(
uint32_t maxbytes, uint32_t maxNurseryBytes = JS::DefaultNurseryBytes,
JSRuntime* parentRuntime = nullptr);
// The methods below for controlling the active context in a cooperatively
// multithreaded runtime are not threadsafe, and the caller must ensure they
// are called serially if there is a chance for contention between threads.
// Called from the active context for a runtime, yield execution so that
// this context is no longer active and can no longer use the API.
extern JS_PUBLIC_API void JS_YieldCooperativeContext(JSContext* cx);
// Called from a context whose runtime has no active context, this thread
// becomes the active context for that runtime and may use the API.
extern JS_PUBLIC_API void JS_ResumeCooperativeContext(JSContext* cx);
// Create a new context on this thread for cooperative multithreading in the
// same runtime as siblingContext. Called on a runtime (as indicated by
// siblingContet) which has no active context, on success the new context will
// become the runtime's active context.
extern JS_PUBLIC_API JSContext* JS_NewCooperativeContext(
JSContext* siblingContext);
// Destroy a context allocated with JS_NewContext or JS_NewCooperativeContext.
// The context must be the current active context in the runtime, and after
// this call the runtime will have no active context.
extern JS_PUBLIC_API void JS_DestroyContext(JSContext* cx);
JS_PUBLIC_API void* JS_GetContextPrivate(JSContext* cx);
JS_PUBLIC_API void JS_SetContextPrivate(JSContext* cx, void* data);
extern JS_PUBLIC_API JSRuntime* JS_GetParentRuntime(JSContext* cx);
extern JS_PUBLIC_API JSRuntime* JS_GetRuntime(JSContext* cx);
extern JS_PUBLIC_API void JS_SetFutexCanWait(JSContext* cx);
namespace js {
void AssertHeapIsIdle();
} /* namespace js */
namespace JS {
/**
* Initialize the runtime's self-hosted code. Embeddings should call this
* exactly once per runtime/context, before the first JS_NewGlobalObject
* call.
*/
JS_PUBLIC_API bool InitSelfHostedCode(JSContext* cx);
/**
* Asserts (in debug and release builds) that `obj` belongs to the current
* thread's context.
*/
JS_PUBLIC_API void AssertObjectBelongsToCurrentThread(JSObject* obj);
} /* namespace JS */
extern JS_PUBLIC_API const char* JS_GetImplementationVersion(void);
extern JS_PUBLIC_API void JS_SetDestroyCompartmentCallback(
JSContext* cx, JSDestroyCompartmentCallback callback);
extern JS_PUBLIC_API void JS_SetSizeOfIncludingThisCompartmentCallback(
JSContext* cx, JSSizeOfIncludingThisCompartmentCallback callback);
extern JS_PUBLIC_API void JS_SetWrapObjectCallbacks(
JSContext* cx, const JSWrapObjectCallbacks* callbacks);
extern JS_PUBLIC_API void JS_SetExternalStringSizeofCallback(
JSContext* cx, JSExternalStringSizeofCallback callback);
#if defined(NIGHTLY_BUILD)
// Set a callback that will be called whenever an error
// is thrown in this runtime. This is designed as a mechanism
// for logging errors. Note that the VM makes no attempt to sanitize
// the contents of the error (so it may contain private data)
// or to sort out among errors (so it may not be the error you
// are interested in or for the component in which you are
// interested).
//
// If the callback sets a new error, this new error
// will replace the original error.
//
// May be `nullptr`.
extern JS_PUBLIC_API void JS_SetErrorInterceptorCallback(
JSRuntime*, JSErrorInterceptor* callback);
extern JS_PUBLIC_API JSErrorInterceptor* JS_GetErrorInterceptorCallback(
JSRuntime*);
// Examine a value to determine if it is one of the built-in Error types.
// If so, return the error type.
extern JS_PUBLIC_API mozilla::Maybe<JSExnType> JS_GetErrorType(
const JS::Value& val);
#endif // defined(NIGHTLY_BUILD)
extern JS_PUBLIC_API void JS_SetCompartmentPrivate(JS::Compartment* compartment,
void* data);
extern JS_PUBLIC_API void* JS_GetCompartmentPrivate(
JS::Compartment* compartment);
extern JS_PUBLIC_API void JS_SetZoneUserData(JS::Zone* zone, void* data);
extern JS_PUBLIC_API void* JS_GetZoneUserData(JS::Zone* zone);
extern JS_PUBLIC_API bool JS_WrapObject(JSContext* cx,
JS::MutableHandleObject objp);
extern JS_PUBLIC_API bool JS_WrapValue(JSContext* cx,
JS::MutableHandleValue vp);
extern JS_PUBLIC_API JSObject* JS_TransplantObject(JSContext* cx,
JS::HandleObject origobj,
JS::HandleObject target);
extern JS_PUBLIC_API bool JS_RefreshCrossCompartmentWrappers(
JSContext* cx, JS::Handle<JSObject*> obj);
/*
* At any time, a JSContext has a current (possibly-nullptr) realm.
* Realms are described in:
*
* developer.mozilla.org/en-US/docs/SpiderMonkey/SpiderMonkey_compartments
*
* The current realm of a context may be changed. The preferred way to do
* this is with JSAutoRealm:
*
* void foo(JSContext* cx, JSObject* obj) {
* // in some realm 'r'
* {
* JSAutoRealm ar(cx, obj); // constructor enters
* // in the realm of 'obj'
* } // destructor leaves
* // back in realm 'r'
* }
*
* The object passed to JSAutoRealm must *not* be a cross-compartment wrapper,
* because CCWs are not associated with a single realm.
*
* For more complicated uses that don't neatly fit in a C++ stack frame, the
* realm can be entered and left using separate function calls:
*
* void foo(JSContext* cx, JSObject* obj) {
* // in 'oldRealm'
* JS::Realm* oldRealm = JS::EnterRealm(cx, obj);
* // in the realm of 'obj'
* JS::LeaveRealm(cx, oldRealm);
* // back in 'oldRealm'
* }
*
* Note: these calls must still execute in a LIFO manner w.r.t all other
* enter/leave calls on the context. Furthermore, only the return value of a
* JS::EnterRealm call may be passed as the 'oldRealm' argument of
* the corresponding JS::LeaveRealm call.
*
* Entering a realm roots the realm and its global object for the lifetime of
* the JSAutoRealm.
*/
class MOZ_RAII JS_PUBLIC_API JSAutoRealm {
JSContext* cx_;
JS::Realm* oldRealm_;
public:
JSAutoRealm(JSContext* cx, JSObject* target MOZ_GUARD_OBJECT_NOTIFIER_PARAM);
JSAutoRealm(JSContext* cx, JSScript* target MOZ_GUARD_OBJECT_NOTIFIER_PARAM);
~JSAutoRealm();
MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
};
class MOZ_RAII JS_PUBLIC_API JSAutoNullableRealm {
JSContext* cx_;
JS::Realm* oldRealm_;
public:
explicit JSAutoNullableRealm(
JSContext* cx, JSObject* targetOrNull MOZ_GUARD_OBJECT_NOTIFIER_PARAM);
~JSAutoNullableRealm();
MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
};
namespace JS {
/** NB: This API is infallible; a nullptr return value does not indicate error.
*
* |target| must not be a cross-compartment wrapper because CCWs are not
* associated with a single realm.
*
* Entering a realm roots the realm and its global object until the matching
* JS::LeaveRealm() call.
*/
extern JS_PUBLIC_API JS::Realm* EnterRealm(JSContext* cx, JSObject* target);
extern JS_PUBLIC_API void LeaveRealm(JSContext* cx, JS::Realm* oldRealm);
using IterateRealmCallback = void (*)(JSContext* cx, void* data,
Handle<Realm*> realm);
/**
* This function calls |realmCallback| on every realm. Beware that there is no
* guarantee that the realm will survive after the callback returns. Also,
* barriers are disabled via the TraceSession.
*/
extern JS_PUBLIC_API void IterateRealms(JSContext* cx, void* data,
IterateRealmCallback realmCallback);
/**
* Like IterateRealms, but only call the callback for realms using |principals|.
*/
extern JS_PUBLIC_API void IterateRealmsWithPrincipals(
JSContext* cx, JSPrincipals* principals, void* data,
IterateRealmCallback realmCallback);
/**
* Like IterateRealms, but only iterates realms in |compartment|.
*/
extern JS_PUBLIC_API void IterateRealmsInCompartment(
JSContext* cx, JS::Compartment* compartment, void* data,
IterateRealmCallback realmCallback);
} // namespace JS
/**
* An enum that JSIterateCompartmentCallback can return to indicate
* whether to keep iterating.
*/
namespace JS {
enum class CompartmentIterResult { KeepGoing, Stop };
} // namespace JS
typedef JS::CompartmentIterResult (*JSIterateCompartmentCallback)(
JSContext* cx, void* data, JS::Compartment* compartment);
/**
* This function calls |compartmentCallback| on every compartment until either
* all compartments have been iterated or CompartmentIterResult::Stop is
* returned. Beware that there is no guarantee that the compartment will survive
* after the callback returns. Also, barriers are disabled via the TraceSession.
*/
extern JS_PUBLIC_API void JS_IterateCompartments(
JSContext* cx, void* data,
JSIterateCompartmentCallback compartmentCallback);
/**
* This function calls |compartmentCallback| on every compartment in the given
* zone until either all compartments have been iterated or
* CompartmentIterResult::Stop is returned. Beware that there is no guarantee
* that the compartment will survive after the callback returns. Also, barriers
* are disabled via the TraceSession.
*/
extern JS_PUBLIC_API void JS_IterateCompartmentsInZone(
JSContext* cx, JS::Zone* zone, void* data,
JSIterateCompartmentCallback compartmentCallback);
/**
* Mark a jsid after entering a new compartment. Different zones separately
* mark the ids in a runtime, and this must be used any time an id is obtained
* from one compartment and then used in another compartment, unless the two
* compartments are guaranteed to be in the same zone.
*/
extern JS_PUBLIC_API void JS_MarkCrossZoneId(JSContext* cx, jsid id);
/**
* If value stores a jsid (an atomized string or symbol), mark that id as for
* JS_MarkCrossZoneId.
*/
extern JS_PUBLIC_API void JS_MarkCrossZoneIdValue(JSContext* cx,
const JS::Value& value);
/**
* Resolve id, which must contain either a string or an int, to a standard
* class name in obj if possible, defining the class's constructor and/or
* prototype and storing true in *resolved. If id does not name a standard
* class or a top-level property induced by initializing a standard class,
* store false in *resolved and just return true. Return false on error,
* as usual for bool result-typed API entry points.
*
* This API can be called directly from a global object class's resolve op,
* to define standard classes lazily. The class should either have an enumerate
* hook that calls JS_EnumerateStandardClasses, or a newEnumerate hook that
* calls JS_NewEnumerateStandardClasses. newEnumerate is preferred because it's
* faster (does not define all standard classes).
*/
extern JS_PUBLIC_API bool JS_ResolveStandardClass(JSContext* cx,
JS::HandleObject obj,
JS::HandleId id,
bool* resolved);
extern JS_PUBLIC_API bool JS_MayResolveStandardClass(const JSAtomState& names,
jsid id,
JSObject* maybeObj);
extern JS_PUBLIC_API bool JS_EnumerateStandardClasses(JSContext* cx,
JS::HandleObject obj);
/**
* Fill "properties" with a list of standard class names that have not yet been
* resolved on "obj". This can be used as (part of) a newEnumerate class hook
* on a global. Already-resolved things are excluded because they might have
* been deleted by script after being resolved and enumeration considers
* already-defined properties anyway.
*/
extern JS_PUBLIC_API bool JS_NewEnumerateStandardClasses(
JSContext* cx, JS::HandleObject obj, JS::AutoIdVector& properties,
bool enumerableOnly);
/**
* Fill "properties" with a list of standard class names. This can be used for
* proxies that want to define behavior that looks like enumerating a global
* without touching the global itself.
*/
extern JS_PUBLIC_API bool JS_NewEnumerateStandardClassesIncludingResolved(
JSContext* cx, JS::HandleObject obj, JS::AutoIdVector& properties,
bool enumerableOnly);
extern JS_PUBLIC_API bool JS_GetClassObject(JSContext* cx, JSProtoKey key,
JS::MutableHandle<JSObject*> objp);
extern JS_PUBLIC_API bool JS_GetClassPrototype(
JSContext* cx, JSProtoKey key, JS::MutableHandle<JSObject*> objp);
namespace JS {
/*
* Determine if the given object is an instance/prototype/constructor for a
* standard class. If so, return the associated JSProtoKey. If not, return
* JSProto_Null.
*/
extern JS_PUBLIC_API JSProtoKey IdentifyStandardInstance(JSObject* obj);
extern JS_PUBLIC_API JSProtoKey IdentifyStandardPrototype(JSObject* obj);
extern JS_PUBLIC_API JSProtoKey
IdentifyStandardInstanceOrPrototype(JSObject* obj);
extern JS_PUBLIC_API JSProtoKey IdentifyStandardConstructor(JSObject* obj);
extern JS_PUBLIC_API void ProtoKeyToId(JSContext* cx, JSProtoKey key,
JS::MutableHandleId idp);
} /* namespace JS */
extern JS_PUBLIC_API JSProtoKey JS_IdToProtoKey(JSContext* cx, JS::HandleId id);
extern JS_PUBLIC_API bool JS_IsGlobalObject(JSObject* obj);
extern JS_PUBLIC_API JSObject* JS_GlobalLexicalEnvironment(JSObject* obj);
extern JS_PUBLIC_API bool JS_HasExtensibleLexicalEnvironment(JSObject* obj);
extern JS_PUBLIC_API JSObject* JS_ExtensibleLexicalEnvironment(JSObject* obj);
namespace JS {
/**
* Get the current realm's global. Returns nullptr if no realm has been
* entered.
*/
extern JS_PUBLIC_API JSObject* CurrentGlobalOrNull(JSContext* cx);
/**
* Get the global object associated with an object's realm. The object must not
* be a cross-compartment wrapper (because CCWs are shared by all realms in the
* compartment).
*/
extern JS_PUBLIC_API JSObject* GetNonCCWObjectGlobal(JSObject* obj);
} // namespace JS
/**
* Add 'Reflect.parse', a SpiderMonkey extension, to the Reflect object on the
* given global.
*/
extern JS_PUBLIC_API bool JS_InitReflectParse(JSContext* cx,
JS::HandleObject global);
/**
* Add various profiling-related functions as properties of the given object.
* Defined in builtin/Profilers.cpp.
*/
extern JS_PUBLIC_API bool JS_DefineProfilingFunctions(JSContext* cx,
JS::HandleObject obj);
/* Defined in vm/Debugger.cpp. */
extern JS_PUBLIC_API bool JS_DefineDebuggerObject(JSContext* cx,
JS::HandleObject obj);
namespace JS {
/**
* Tell JS engine whether Profile Timeline Recording is enabled or not.
* If Profile Timeline Recording is enabled, data shown there like stack won't
* be optimized out.
* This is global state and not associated with specific runtime or context.
*/
extern JS_PUBLIC_API void SetProfileTimelineRecordingEnabled(bool enabled);
extern JS_PUBLIC_API bool IsProfileTimelineRecordingEnabled();
} // namespace JS
#ifdef JS_HAS_CTYPES
/**
* Initialize the 'ctypes' object on a global variable 'obj'. The 'ctypes'
* object will be sealed.
*/
extern JS_PUBLIC_API bool JS_InitCTypesClass(JSContext* cx,
JS::HandleObject global);
/**
* Convert a unicode string 'source' of length 'slen' to the platform native
* charset, returning a null-terminated string allocated with JS_malloc. On
* failure, this function should report an error.
*/
typedef char* (*JSCTypesUnicodeToNativeFun)(JSContext* cx,
const char16_t* source,
size_t slen);
/**
* Set of function pointers that ctypes can use for various internal functions.
* See JS_SetCTypesCallbacks below. Providing nullptr for a function is safe,
* and will result in the applicable ctypes functionality not being available.
*/
struct JSCTypesCallbacks {
JSCTypesUnicodeToNativeFun unicodeToNative;
};
/**
* Set the callbacks on the provided 'ctypesObj' object. 'callbacks' should be a
* pointer to static data that exists for the lifetime of 'ctypesObj', but it
* may safely be altered after calling this function and without having
* to call this function again.
*/
extern JS_PUBLIC_API void JS_SetCTypesCallbacks(
JSObject* ctypesObj, const JSCTypesCallbacks* callbacks);
#endif
/*
* A replacement for MallocAllocPolicy that allocates in the JS heap and adds no
* extra behaviours.
*
* This is currently used for allocating source buffers for parsing. Since these
* are temporary and will not be freed by GC, the memory is not tracked by the
* usual accounting.
*/
class JS_PUBLIC_API JSMallocAllocPolicy : public js::AllocPolicyBase {
public:
void reportAllocOverflow() const {}
MOZ_MUST_USE bool checkSimulatedOOM() const { return true; }
};
/**
* Set the size of the native stack that should not be exceed. To disable
* stack size checking pass 0.
*
* SpiderMonkey allows for a distinction between system code (such as GCs, which
* may incidentally be triggered by script but are not strictly performed on
* behalf of such script), trusted script (as determined by
* JS_SetTrustedPrincipals), and untrusted script. Each kind of code may have a
* different stack quota, allowing embedders to keep higher-priority machinery
* running in the face of scripted stack exhaustion by something else.
*
* The stack quotas for each kind of code should be monotonically descending,
* and may be specified with this function. If 0 is passed for a given kind
* of code, it defaults to the value of the next-highest-priority kind.
*
* This function may only be called immediately after the runtime is initialized
* and before any code is executed and/or interrupts requested.
*/
extern JS_PUBLIC_API void JS_SetNativeStackQuota(
JSContext* cx, size_t systemCodeStackSize,
size_t trustedScriptStackSize = 0, size_t untrustedScriptStackSize = 0);
/************************************************************************/
extern JS_PUBLIC_API bool JS_ValueToId(JSContext* cx, JS::HandleValue v,
JS::MutableHandleId idp);
extern JS_PUBLIC_API bool JS_StringToId(JSContext* cx, JS::HandleString s,
JS::MutableHandleId idp);
extern JS_PUBLIC_API bool JS_IdToValue(JSContext* cx, jsid id,
JS::MutableHandle<JS::Value> vp);
namespace JS {
/**
* Convert obj to a primitive value. On success, store the result in vp and
* return true.
*
* The hint argument must be JSTYPE_STRING, JSTYPE_NUMBER, or
* JSTYPE_UNDEFINED (no hint).
*
* Implements: ES6 7.1.1 ToPrimitive(input, [PreferredType]).
*/
extern JS_PUBLIC_API bool ToPrimitive(JSContext* cx, JS::HandleObject obj,
JSType hint, JS::MutableHandleValue vp);
/**
* If args.get(0) is one of the strings "string", "number", or "default", set
* result to JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_UNDEFINED accordingly and
* return true. Otherwise, return false with a TypeError pending.
*
* This can be useful in implementing a @@toPrimitive method.
*/
extern JS_PUBLIC_API bool GetFirstArgumentAsTypeHint(JSContext* cx,
CallArgs args,
JSType* result);
} /* namespace JS */
template <typename T>
struct JSConstScalarSpec {
const char* name;
T val;
};
using JSConstDoubleSpec = JSConstScalarSpec<double>;
using JSConstIntegerSpec = JSConstScalarSpec<int32_t>;
extern JS_PUBLIC_API JSObject* JS_InitClass(
JSContext* cx, JS::HandleObject obj, JS::HandleObject parent_proto,
const JSClass* clasp, JSNative constructor, unsigned nargs,
const JSPropertySpec* ps, const JSFunctionSpec* fs,
const JSPropertySpec* static_ps, const JSFunctionSpec* static_fs);
/**
* Set up ctor.prototype = proto and proto.constructor = ctor with the
* right property flags.
*/
extern JS_PUBLIC_API bool JS_LinkConstructorAndPrototype(
JSContext* cx, JS::Handle<JSObject*> ctor, JS::Handle<JSObject*> proto);
extern JS_PUBLIC_API const JSClass* JS_GetClass(JSObject* obj);
extern JS_PUBLIC_API bool JS_InstanceOf(JSContext* cx,
JS::Handle<JSObject*> obj,
const JSClass* clasp,
JS::CallArgs* args);
extern JS_PUBLIC_API bool JS_HasInstance(JSContext* cx,
JS::Handle<JSObject*> obj,
JS::Handle<JS::Value> v, bool* bp);
namespace JS {
// Implementation of
// http://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance. If
// you're looking for the equivalent of "instanceof", you want JS_HasInstance,
// not this function.
extern JS_PUBLIC_API bool OrdinaryHasInstance(JSContext* cx,
HandleObject objArg,
HandleValue v, bool* bp);
// Implementation of
// https://www.ecma-international.org/ecma-262/6.0/#sec-instanceofoperator
// This is almost identical to JS_HasInstance, except the latter may call a
// custom hasInstance class op instead of InstanceofOperator.
extern JS_PUBLIC_API bool InstanceofOperator(JSContext* cx, HandleObject obj,
HandleValue v, bool* bp);
} // namespace JS
extern JS_PUBLIC_API void* JS_GetPrivate(JSObject* obj);
extern JS_PUBLIC_API void JS_SetPrivate(JSObject* obj, void* data);
extern JS_PUBLIC_API void* JS_GetInstancePrivate(JSContext* cx,
JS::Handle<JSObject*> obj,
const JSClass* clasp,
JS::CallArgs* args);
extern JS_PUBLIC_API JSObject* JS_GetConstructor(JSContext* cx,
JS::Handle<JSObject*> proto);
namespace JS {
// Specification for which compartment/zone a newly created realm should use.
enum class CompartmentSpecifier {
// Create a new realm and compartment in the single runtime wide system
// zone. The meaning of this zone is left to the embedder.
NewCompartmentInSystemZone,
// Create a new realm and compartment in a particular existing zone.
NewCompartmentInExistingZone,
// Create a new zone/compartment.
NewCompartmentAndZone,
// Create a new realm in an existing compartment.
ExistingCompartment,
};
/**
* RealmCreationOptions specifies options relevant to creating a new realm, that
* are either immutable characteristics of that realm or that are discarded
* after the realm has been created.
*
* Access to these options on an existing realm is read-only: if you need
* particular selections, make them before you create the realm.
*/
class JS_PUBLIC_API RealmCreationOptions {
public:
RealmCreationOptions()
: traceGlobal_(nullptr),
compSpec_(CompartmentSpecifier::NewCompartmentAndZone),
comp_(nullptr),
invisibleToDebugger_(false),
mergeable_(false),
preserveJitCode_(false),
cloneSingletons_(false),
sharedMemoryAndAtomics_(false),
streams_(false),
bigint_(false),
fields_(false),
secureContext_(false),
clampAndJitterTime_(true) {}
JSTraceOp getTrace() const { return traceGlobal_; }
RealmCreationOptions& setTrace(JSTraceOp op) {
traceGlobal_ = op;
return *this;
}
JS::Zone* zone() const {
MOZ_ASSERT(compSpec_ == CompartmentSpecifier::NewCompartmentInExistingZone);
return zone_;
}
JS::Compartment* compartment() const {
MOZ_ASSERT(compSpec_ == CompartmentSpecifier::ExistingCompartment);
return comp_;
}
CompartmentSpecifier compartmentSpecifier() const { return compSpec_; }
// Set the compartment/zone to use for the realm. See CompartmentSpecifier
// above.
RealmCreationOptions& setNewCompartmentInSystemZone();
RealmCreationOptions& setNewCompartmentInExistingZone(JSObject* obj);
RealmCreationOptions& setNewCompartmentAndZone();
RealmCreationOptions& setExistingCompartment(JSObject* obj);
RealmCreationOptions& setExistingCompartment(JS::Compartment* compartment);
// Certain compartments are implementation details of the embedding, and
// references to them should never leak out to script. This flag causes this
// realm to skip firing onNewGlobalObject and makes addDebuggee a no-op for
// this global.
//
// Debugger visibility is per-compartment, not per-realm (it's only practical