forked from BrowserWorks/Waterfox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsapi.cpp
5975 lines (5083 loc) · 188 KB
/
jsapi.cpp
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.
*/
#include "jsapi.h"
#include "mozilla/FloatingPoint.h"
#include "mozilla/Maybe.h"
#include "mozilla/PodOperations.h"
#include "mozilla/Sprintf.h"
#include <ctype.h>
#ifdef __linux__
# include <dlfcn.h>
#endif
#include <stdarg.h>
#include <string.h>
#include "jsdate.h"
#include "jsexn.h"
#include "jsfriendapi.h"
#include "jsmath.h"
#include "jsnum.h"
#include "jstypes.h"
#include "jsutil.h"
#include "builtin/Array.h"
#include "builtin/AtomicsObject.h"
#include "builtin/Boolean.h"
#include "builtin/Eval.h"
#include "builtin/JSON.h"
#include "builtin/MapObject.h"
#include "builtin/Promise.h"
#include "builtin/Stream.h"
#include "builtin/String.h"
#include "builtin/Symbol.h"
#ifdef ENABLE_TYPED_OBJECTS
# include "builtin/TypedObject.h"
#endif
#include "frontend/BytecodeCompiler.h"
#include "gc/FreeOp.h"
#include "gc/Marking.h"
#include "gc/Policy.h"
#include "gc/PublicIterators.h"
#include "gc/WeakMap.h"
#include "jit/JitCommon.h"
#include "jit/JitSpewer.h"
#include "js/CharacterEncoding.h"
#include "js/CompilationAndEvaluation.h"
#include "js/CompileOptions.h"
#include "js/ContextOptions.h" // JS::ContextOptions{,Ref}
#include "js/Conversions.h"
#include "js/Date.h"
#include "js/Initialization.h"
#include "js/JSON.h"
#include "js/LocaleSensitive.h"
#include "js/MemoryFunctions.h"
#include "js/PropertySpec.h"
#include "js/Proxy.h"
#include "js/SliceBudget.h"
#include "js/SourceText.h"
#include "js/StableStringChars.h"
#include "js/StructuredClone.h"
#include "js/Symbol.h"
#include "js/Utility.h"
#include "js/Wrapper.h"
#include "util/CompleteFile.h"
#include "util/StringBuffer.h"
#include "util/Text.h"
#include "vm/AsyncFunction.h"
#include "vm/AsyncIteration.h"
#include "vm/DateObject.h"
#include "vm/Debugger.h"
#include "vm/EnvironmentObject.h"
#include "vm/ErrorObject.h"
#include "vm/HelperThreads.h"
#include "vm/Interpreter.h"
#include "vm/Iteration.h"
#include "vm/JSAtom.h"
#include "vm/JSContext.h"
#include "vm/JSFunction.h"
#include "vm/JSObject.h"
#include "vm/JSScript.h"
#include "vm/Runtime.h"
#include "vm/SavedStacks.h"
#include "vm/SelfHosting.h"
#include "vm/Shape.h"
#include "vm/StringType.h"
#include "vm/SymbolType.h"
#include "vm/WrapperObject.h"
#include "vm/Xdr.h"
#include "wasm/WasmModule.h"
#include "vm/Compartment-inl.h"
#include "vm/Interpreter-inl.h"
#include "vm/JSAtom-inl.h"
#include "vm/JSFunction-inl.h"
#include "vm/JSScript-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/SavedStacks-inl.h"
#include "vm/StringType-inl.h"
using namespace js;
using mozilla::Maybe;
using mozilla::PodCopy;
using mozilla::Some;
using JS::AutoStableStringChars;
using JS::CompileOptions;
using JS::ReadOnlyCompileOptions;
using JS::SourceText;
#ifdef HAVE_VA_LIST_AS_ARRAY
# define JS_ADDRESSOF_VA_LIST(ap) ((va_list*)(ap))
#else
# define JS_ADDRESSOF_VA_LIST(ap) (&(ap))
#endif
JS_PUBLIC_API void JS::CallArgs::reportMoreArgsNeeded(JSContext* cx,
const char* fnname,
unsigned required,
unsigned actual) {
char requiredArgsStr[40];
SprintfLiteral(requiredArgsStr, "%u", required);
char actualArgsStr[40];
SprintfLiteral(actualArgsStr, "%u", actual);
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_MORE_ARGS_NEEDED, fnname, requiredArgsStr,
required == 1 ? "" : "s", actualArgsStr);
}
static bool ErrorTakesArguments(unsigned msg) {
MOZ_ASSERT(msg < JSErr_Limit);
unsigned argCount = js_ErrorFormatString[msg].argCount;
MOZ_ASSERT(argCount <= 2);
return argCount == 1 || argCount == 2;
}
static bool ErrorTakesObjectArgument(unsigned msg) {
MOZ_ASSERT(msg < JSErr_Limit);
unsigned argCount = js_ErrorFormatString[msg].argCount;
MOZ_ASSERT(argCount <= 2);
return argCount == 2;
}
JS_PUBLIC_API bool JS::ObjectOpResult::reportStrictErrorOrWarning(
JSContext* cx, HandleObject obj, HandleId id, bool strict) {
static_assert(unsigned(OkCode) == unsigned(JSMSG_NOT_AN_ERROR),
"unsigned value of OkCode must not be an error code");
MOZ_ASSERT(code_ != Uninitialized);
MOZ_ASSERT(!ok());
cx->check(obj);
unsigned flags =
strict ? JSREPORT_ERROR : (JSREPORT_WARNING | JSREPORT_STRICT);
if (code_ == JSMSG_OBJECT_NOT_EXTENSIBLE) {
RootedValue val(cx, ObjectValue(*obj));
return ReportValueErrorFlags(cx, flags, code_, JSDVG_IGNORE_STACK, val,
nullptr, nullptr, nullptr);
}
if (ErrorTakesArguments(code_)) {
UniqueChars propName =
IdToPrintableUTF8(cx, id, IdToPrintableBehavior::IdIsPropertyKey);
if (!propName) {
return false;
}
if (code_ == JSMSG_SET_NON_OBJECT_RECEIVER) {
// We know that the original receiver was a primitive, so unbox it.
RootedValue val(cx, ObjectValue(*obj));
if (!obj->is<ProxyObject>()) {
if (!Unbox(cx, obj, &val)) {
return false;
}
}
return ReportValueErrorFlags(cx, flags, code_, JSDVG_IGNORE_STACK, val,
nullptr, propName.get(), nullptr);
}
if (ErrorTakesObjectArgument(code_)) {
return JS_ReportErrorFlagsAndNumberUTF8(
cx, flags, GetErrorMessage, nullptr, code_, obj->getClass()->name,
propName.get());
}
return JS_ReportErrorFlagsAndNumberUTF8(cx, flags, GetErrorMessage, nullptr,
code_, propName.get());
}
return JS_ReportErrorFlagsAndNumberASCII(cx, flags, GetErrorMessage, nullptr,
code_);
}
JS_PUBLIC_API bool JS::ObjectOpResult::reportStrictErrorOrWarning(
JSContext* cx, HandleObject obj, bool strict) {
MOZ_ASSERT(code_ != Uninitialized);
MOZ_ASSERT(!ok());
MOZ_ASSERT(!ErrorTakesArguments(code_));
cx->check(obj);
unsigned flags =
strict ? JSREPORT_ERROR : (JSREPORT_WARNING | JSREPORT_STRICT);
return JS_ReportErrorFlagsAndNumberASCII(cx, flags, GetErrorMessage, nullptr,
code_);
}
JS_PUBLIC_API bool JS::ObjectOpResult::failCantRedefineProp() {
return fail(JSMSG_CANT_REDEFINE_PROP);
}
JS_PUBLIC_API bool JS::ObjectOpResult::failReadOnly() {
return fail(JSMSG_READ_ONLY);
}
JS_PUBLIC_API bool JS::ObjectOpResult::failGetterOnly() {
return fail(JSMSG_GETTER_ONLY);
}
JS_PUBLIC_API bool JS::ObjectOpResult::failCantDelete() {
return fail(JSMSG_CANT_DELETE);
}
JS_PUBLIC_API bool JS::ObjectOpResult::failCantSetInterposed() {
return fail(JSMSG_CANT_SET_INTERPOSED);
}
JS_PUBLIC_API bool JS::ObjectOpResult::failCantDefineWindowElement() {
return fail(JSMSG_CANT_DEFINE_WINDOW_ELEMENT);
}
JS_PUBLIC_API bool JS::ObjectOpResult::failCantDeleteWindowElement() {
return fail(JSMSG_CANT_DELETE_WINDOW_ELEMENT);
}
JS_PUBLIC_API bool JS::ObjectOpResult::failCantDeleteWindowNamedProperty() {
return fail(JSMSG_CANT_DELETE_WINDOW_NAMED_PROPERTY);
}
JS_PUBLIC_API bool JS::ObjectOpResult::failCantDefineWindowNonConfigurable() {
return fail(JSMSG_CANT_DEFINE_WINDOW_NC);
}
JS_PUBLIC_API bool JS::ObjectOpResult::failCantPreventExtensions() {
return fail(JSMSG_CANT_PREVENT_EXTENSIONS);
}
JS_PUBLIC_API bool JS::ObjectOpResult::failCantSetProto() {
return fail(JSMSG_CANT_SET_PROTO);
}
JS_PUBLIC_API bool JS::ObjectOpResult::failNoNamedSetter() {
return fail(JSMSG_NO_NAMED_SETTER);
}
JS_PUBLIC_API bool JS::ObjectOpResult::failNoIndexedSetter() {
return fail(JSMSG_NO_INDEXED_SETTER);
}
JS_PUBLIC_API bool JS::ObjectOpResult::failNotDataDescriptor() {
return fail(JSMSG_NOT_DATA_DESCRIPTOR);
}
JS_PUBLIC_API int64_t JS_Now() { return PRMJ_Now(); }
JS_PUBLIC_API Value JS_GetNaNValue(JSContext* cx) {
return cx->runtime()->NaNValue;
}
JS_PUBLIC_API Value JS_GetNegativeInfinityValue(JSContext* cx) {
return cx->runtime()->negativeInfinityValue;
}
JS_PUBLIC_API Value JS_GetPositiveInfinityValue(JSContext* cx) {
return cx->runtime()->positiveInfinityValue;
}
JS_PUBLIC_API Value JS_GetEmptyStringValue(JSContext* cx) {
return StringValue(cx->runtime()->emptyString);
}
JS_PUBLIC_API JSString* JS_GetEmptyString(JSContext* cx) {
MOZ_ASSERT(cx->emptyString());
return cx->emptyString();
}
namespace js {
void AssertHeapIsIdle() { MOZ_ASSERT(!JS::RuntimeHeapIsBusy()); }
} // namespace js
static void AssertHeapIsIdleOrIterating() {
MOZ_ASSERT(!JS::RuntimeHeapIsCollecting());
}
static void AssertHeapIsIdleOrStringIsFlat(JSString* str) {
/*
* We allow some functions to be called during a GC as long as the argument
* is a flat string, since that will not cause allocation.
*/
MOZ_ASSERT_IF(JS::RuntimeHeapIsBusy(), str->isFlat());
}
JS_PUBLIC_API bool JS_ValueToObject(JSContext* cx, HandleValue value,
MutableHandleObject objp) {
AssertHeapIsIdle();
CHECK_THREAD(cx);
cx->check(value);
if (value.isNullOrUndefined()) {
objp.set(nullptr);
return true;
}
JSObject* obj = ToObject(cx, value);
if (!obj) {
return false;
}
objp.set(obj);
return true;
}
JS_PUBLIC_API JSFunction* JS_ValueToFunction(JSContext* cx, HandleValue value) {
AssertHeapIsIdle();
CHECK_THREAD(cx);
cx->check(value);
return ReportIfNotFunction(cx, value);
}
JS_PUBLIC_API JSFunction* JS_ValueToConstructor(JSContext* cx,
HandleValue value) {
AssertHeapIsIdle();
CHECK_THREAD(cx);
cx->check(value);
return ReportIfNotFunction(cx, value);
}
JS_PUBLIC_API JSString* JS_ValueToSource(JSContext* cx, HandleValue value) {
AssertHeapIsIdle();
CHECK_THREAD(cx);
cx->check(value);
return ValueToSource(cx, value);
}
JS_PUBLIC_API bool JS_DoubleIsInt32(double d, int32_t* ip) {
return mozilla::NumberIsInt32(d, ip);
}
JS_PUBLIC_API JSType JS_TypeOfValue(JSContext* cx, HandleValue value) {
AssertHeapIsIdle();
CHECK_THREAD(cx);
cx->check(value);
return TypeOfValue(value);
}
JS_PUBLIC_API bool JS_IsBuiltinEvalFunction(JSFunction* fun) {
return IsAnyBuiltinEval(fun);
}
JS_PUBLIC_API bool JS_IsBuiltinFunctionConstructor(JSFunction* fun) {
return fun->isBuiltinFunctionConstructor();
}
JS_PUBLIC_API bool JS_IsFunctionBound(JSFunction* fun) {
return fun->isBoundFunction();
}
JS_PUBLIC_API JSObject* JS_GetBoundFunctionTarget(JSFunction* fun) {
return fun->isBoundFunction() ? fun->getBoundFunctionTarget() : nullptr;
}
/************************************************************************/
JS_PUBLIC_API JSContext* JS_NewContext(uint32_t maxbytes,
uint32_t maxNurseryBytes,
JSRuntime* parentRuntime) {
MOZ_ASSERT(JS::detail::libraryInitState == JS::detail::InitState::Running,
"must call JS_Init prior to creating any JSContexts");
// Make sure that all parent runtimes are the topmost parent.
while (parentRuntime && parentRuntime->parentRuntime) {
parentRuntime = parentRuntime->parentRuntime;
}
return NewContext(maxbytes, maxNurseryBytes, parentRuntime);
}
JS_PUBLIC_API JSContext* JS_NewCooperativeContext(JSContext* siblingContext) {
MOZ_CRASH("Cooperative scheduling is unsupported");
}
JS_PUBLIC_API void JS_YieldCooperativeContext(JSContext* cx) {
MOZ_CRASH("Cooperative scheduling is unsupported");
}
JS_PUBLIC_API void JS_ResumeCooperativeContext(JSContext* cx) {
MOZ_CRASH("Cooperative scheduling is unsupported");
}
JS_PUBLIC_API void JS_DestroyContext(JSContext* cx) { DestroyContext(cx); }
JS_PUBLIC_API void* JS_GetContextPrivate(JSContext* cx) { return cx->data; }
JS_PUBLIC_API void JS_SetContextPrivate(JSContext* cx, void* data) {
cx->data = data;
}
JS_PUBLIC_API void JS_SetFutexCanWait(JSContext* cx) {
cx->fx.setCanWait(true);
}
JS_PUBLIC_API JSRuntime* JS_GetParentRuntime(JSContext* cx) {
return cx->runtime()->parentRuntime ? cx->runtime()->parentRuntime
: cx->runtime();
}
JS_PUBLIC_API JSRuntime* JS_GetRuntime(JSContext* cx) { return cx->runtime(); }
JS_PUBLIC_API JS::ContextOptions& JS::ContextOptionsRef(JSContext* cx) {
return cx->options();
}
JS_PUBLIC_API bool JS::InitSelfHostedCode(JSContext* cx) {
MOZ_RELEASE_ASSERT(!cx->runtime()->hasInitializedSelfHosting(),
"JS::InitSelfHostedCode() called more than once");
AutoNoteSingleThreadedRegion anstr;
JSRuntime* rt = cx->runtime();
if (!rt->initializeAtoms(cx)) {
return false;
}
#ifndef JS_CODEGEN_NONE
if (!rt->createJitRuntime(cx)) {
return false;
}
#endif
if (!rt->initSelfHosting(cx)) {
return false;
}
if (!rt->parentRuntime && !rt->initMainAtomsTables(cx)) {
return false;
}
return true;
}
JS_PUBLIC_API const char* JS_GetImplementationVersion(void) {
return "JavaScript-C" MOZILLA_VERSION;
}
JS_PUBLIC_API void JS_SetDestroyCompartmentCallback(
JSContext* cx, JSDestroyCompartmentCallback callback) {
cx->runtime()->destroyCompartmentCallback = callback;
}
JS_PUBLIC_API void JS_SetSizeOfIncludingThisCompartmentCallback(
JSContext* cx, JSSizeOfIncludingThisCompartmentCallback callback) {
cx->runtime()->sizeOfIncludingThisCompartmentCallback = callback;
}
#if defined(NIGHTLY_BUILD)
JS_PUBLIC_API void JS_SetErrorInterceptorCallback(
JSRuntime* rt, JSErrorInterceptor* callback) {
rt->errorInterception.interceptor = callback;
}
JS_PUBLIC_API JSErrorInterceptor* JS_GetErrorInterceptorCallback(
JSRuntime* rt) {
return rt->errorInterception.interceptor;
}
JS_PUBLIC_API Maybe<JSExnType> JS_GetErrorType(const JS::Value& val) {
// All errors are objects.
if (!val.isObject()) {
return mozilla::Nothing();
}
const JSObject& obj = val.toObject();
// All errors are `ErrorObject`.
if (!obj.is<js::ErrorObject>()) {
// Not one of the primitive errors.
return mozilla::Nothing();
}
const js::ErrorObject& err = obj.as<js::ErrorObject>();
return mozilla::Some(err.type());
}
#endif // defined(NIGHTLY_BUILD)
JS_PUBLIC_API void JS_SetWrapObjectCallbacks(
JSContext* cx, const JSWrapObjectCallbacks* callbacks) {
cx->runtime()->wrapObjectCallbacks = callbacks;
}
JS_PUBLIC_API void JS_SetExternalStringSizeofCallback(
JSContext* cx, JSExternalStringSizeofCallback callback) {
cx->runtime()->externalStringSizeofCallback = callback;
}
JS_PUBLIC_API Realm* JS::EnterRealm(JSContext* cx, JSObject* target) {
AssertHeapIsIdle();
CHECK_THREAD(cx);
MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(target));
Realm* oldRealm = cx->realm();
cx->enterRealmOf(target);
return oldRealm;
}
JS_PUBLIC_API void JS::LeaveRealm(JSContext* cx, JS::Realm* oldRealm) {
AssertHeapIsIdle();
CHECK_THREAD(cx);
cx->leaveRealm(oldRealm);
}
JSAutoRealm::JSAutoRealm(
JSContext* cx, JSObject* target MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
: cx_(cx), oldRealm_(cx->realm()) {
MOZ_GUARD_OBJECT_NOTIFIER_INIT;
MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(target));
AssertHeapIsIdleOrIterating();
cx_->enterRealmOf(target);
}
JSAutoRealm::JSAutoRealm(
JSContext* cx, JSScript* target MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
: cx_(cx), oldRealm_(cx->realm()) {
MOZ_GUARD_OBJECT_NOTIFIER_INIT;
AssertHeapIsIdleOrIterating();
cx_->enterRealmOf(target);
}
JSAutoRealm::~JSAutoRealm() { cx_->leaveRealm(oldRealm_); }
JSAutoNullableRealm::JSAutoNullableRealm(
JSContext* cx,
JSObject* targetOrNull MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
: cx_(cx), oldRealm_(cx->realm()) {
MOZ_GUARD_OBJECT_NOTIFIER_INIT;
AssertHeapIsIdleOrIterating();
if (targetOrNull) {
MOZ_DIAGNOSTIC_ASSERT(!js::IsCrossCompartmentWrapper(targetOrNull));
cx_->enterRealmOf(targetOrNull);
} else {
cx_->enterNullRealm();
}
}
JSAutoNullableRealm::~JSAutoNullableRealm() { cx_->leaveRealm(oldRealm_); }
JS_PUBLIC_API void JS_SetCompartmentPrivate(JS::Compartment* compartment,
void* data) {
compartment->data = data;
}
JS_PUBLIC_API void* JS_GetCompartmentPrivate(JS::Compartment* compartment) {
return compartment->data;
}
JS_PUBLIC_API void JS_MarkCrossZoneId(JSContext* cx, jsid id) {
cx->markId(id);
}
JS_PUBLIC_API void JS_MarkCrossZoneIdValue(JSContext* cx, const Value& value) {
cx->markAtomValue(value);
}
JS_PUBLIC_API void JS_SetZoneUserData(JS::Zone* zone, void* data) {
zone->data = data;
}
JS_PUBLIC_API void* JS_GetZoneUserData(JS::Zone* zone) { return zone->data; }
JS_PUBLIC_API bool JS_WrapObject(JSContext* cx, MutableHandleObject objp) {
AssertHeapIsIdle();
CHECK_THREAD(cx);
if (objp) {
JS::ExposeObjectToActiveJS(objp);
}
return cx->compartment()->wrap(cx, objp);
}
JS_PUBLIC_API bool JS_WrapValue(JSContext* cx, MutableHandleValue vp) {
AssertHeapIsIdle();
CHECK_THREAD(cx);
JS::ExposeValueToActiveJS(vp);
return cx->compartment()->wrap(cx, vp);
}
static void ReleaseAssertObjectHasNoWrappers(JSContext* cx,
HandleObject target) {
RootedValue origv(cx, ObjectValue(*target));
for (CompartmentsIter c(cx->runtime()); !c.done(); c.next()) {
if (c->lookupWrapper(origv)) {
MOZ_CRASH("wrapper found for target object");
}
}
}
/*
* [SMDOC] Brain transplants.
*
* Not for beginners or the squeamish.
*
* Sometimes a web spec requires us to transplant an object from one
* compartment to another, like when a DOM node is inserted into a document in
* another window and thus gets "adopted". We cannot literally change the
* `.compartment()` of a `JSObject`; that would break the compartment
* invariants. However, as usual, we have a workaround using wrappers.
*
* Of all the wrapper-based workarounds we do, it's safe to say this is the
* most spectacular and questionable.
*
* `JS_TransplantObject(cx, origobj, target)` changes `origobj` into a
* simulacrum of `target`, using highly esoteric means. To JS code, the effect
* is as if `origobj` magically "became" `target`, but most often what actually
* happens is that `origobj` gets turned into a cross-compartment wrapper for
* `target`. The old behavior and contents of `origobj` are overwritten or
* discarded.
*
* Thus, to "transplant" an object from one compartment to another:
*
* 1. Let `origobj` be the object that you want to move. First, create a
* clone of it, `target`, in the destination compartment.
*
* In our DOM adoption example, `target` will be a Node of the same type as
* `origobj`, same content, but in the adopting document. We're not done
* yet: the spec for DOM adoption requires that `origobj.ownerDocument`
* actually change. All we've done so far is make a copy.
*
* 2. Call `JS_TransplantObject(cx, origobj, target)`. This typically turns
* `origobj` into a wrapper for `target`, so that any JS code that has a
* reference to `origobj` will observe it to have the behavior of `target`
* going forward. In addition, all existing wrappers for `origobj` are
* changed into wrappers for `target`, extending the illusion to those
* compartments as well.
*
* During navigation, we use the above technique to transplant the WindowProxy
* into the new Window's compartment.
*
* A few rules:
*
* - `origobj` and `target` must be two distinct objects of the same
* `JSClass`. Some classes may not support transplantation; WindowProxy
* objects and DOM nodes are OK.
*
* - `target` should be created specifically to be passed to this function.
* There must be no existing cross-compartment wrappers for it; ideally
* there shouldn't be any pointers to it at all, except the one passed in.
*
* - `target` shouldn't be used afterwards. Instead, `JS_TransplantObject`
* returns a pointer to the transplanted object, which might be `target`
* but might be some other object in the same compartment. Use that.
*
* The reason for this last rule is that JS_TransplantObject does very strange
* things in some cases, like swapping `target`'s brain with that of another
* object. Leaving `target` behaving like its former self is not a goal.
*
* We don't have a good way to recover from failure in this function, so
* we intentionally crash instead.
*/
JS_PUBLIC_API JSObject* JS_TransplantObject(JSContext* cx, HandleObject origobj,
HandleObject target) {
AssertHeapIsIdle();
MOZ_ASSERT(origobj != target);
MOZ_ASSERT(!origobj->is<CrossCompartmentWrapperObject>());
MOZ_ASSERT(!target->is<CrossCompartmentWrapperObject>());
MOZ_ASSERT(origobj->getClass() == target->getClass());
ReleaseAssertObjectHasNoWrappers(cx, target);
JS::AssertCellIsNotGray(origobj);
JS::AssertCellIsNotGray(target);
RootedValue origv(cx, ObjectValue(*origobj));
RootedObject newIdentity(cx);
// Don't allow a compacting GC to observe any intermediate state.
AutoDisableCompactingGC nocgc(cx);
AutoDisableProxyCheck adpc;
JS::Compartment* destination = target->compartment();
if (origobj->compartment() == destination) {
// If the original object is in the same compartment as the
// destination, then we know that we won't find a wrapper in the
// destination's cross compartment map and that the same
// object will continue to work.
AutoRealm ar(cx, origobj);
JSObject::swap(cx, origobj, target);
newIdentity = origobj;
} else if (WrapperMap::Ptr p = destination->lookupWrapper(origv)) {
// There might already be a wrapper for the original object in
// the new compartment. If there is, we use its identity and swap
// in the contents of |target|.
newIdentity = &p->value().get().toObject();
// When we remove origv from the wrapper map, its wrapper, newIdentity,
// must immediately cease to be a cross-compartment wrapper. Nuke it.
destination->removeWrapper(p);
NukeCrossCompartmentWrapper(cx, newIdentity);
AutoRealm ar(cx, newIdentity);
JSObject::swap(cx, newIdentity, target);
} else {
// Otherwise, we use |target| for the new identity object.
newIdentity = target;
}
// Now, iterate through other scopes looking for references to the old
// object, and update the relevant cross-compartment wrappers. We do this
// even if origobj is in the same compartment as target and thus
// `newIdentity == origobj`, because this process also clears out any
// cached wrapper state.
if (!RemapAllWrappersForObject(cx, origobj, newIdentity)) {
MOZ_CRASH();
}
// Lastly, update the original object to point to the new one.
if (origobj->compartment() != destination) {
RootedObject newIdentityWrapper(cx, newIdentity);
AutoRealm ar(cx, origobj);
if (!JS_WrapObject(cx, &newIdentityWrapper)) {
MOZ_CRASH();
}
MOZ_ASSERT(Wrapper::wrappedObject(newIdentityWrapper) == newIdentity);
JSObject::swap(cx, origobj, newIdentityWrapper);
if (!origobj->compartment()->putWrapper(
cx, CrossCompartmentKey(newIdentity), origv)) {
MOZ_CRASH();
}
}
// The new identity object might be one of several things. Return it to avoid
// ambiguity.
JS::AssertCellIsNotGray(newIdentity);
return newIdentity;
}
/*
* Recompute all cross-compartment wrappers for an object, resetting state.
* Gecko uses this to clear Xray wrappers when doing a navigation that reuses
* the inner window and global object.
*/
JS_PUBLIC_API bool JS_RefreshCrossCompartmentWrappers(JSContext* cx,
HandleObject obj) {
return RemapAllWrappersForObject(cx, obj, obj);
}
typedef struct JSStdName {
size_t atomOffset; /* offset of atom pointer in JSAtomState */
JSProtoKey key;
bool isDummy() const { return key == JSProto_Null; }
bool isSentinel() const { return key == JSProto_LIMIT; }
} JSStdName;
static const JSStdName* LookupStdName(const JSAtomState& names, JSAtom* name,
const JSStdName* table) {
for (unsigned i = 0; !table[i].isSentinel(); i++) {
if (table[i].isDummy()) {
continue;
}
JSAtom* atom = AtomStateOffsetToName(names, table[i].atomOffset);
MOZ_ASSERT(atom);
if (name == atom) {
return &table[i];
}
}
return nullptr;
}
/*
* Table of standard classes, indexed by JSProtoKey. For entries where the
* JSProtoKey does not correspond to a class with a meaningful constructor, we
* insert a null entry into the table.
*/
#define STD_NAME_ENTRY(name, init, clasp) {NAME_OFFSET(name), JSProto_##name},
#define STD_DUMMY_ENTRY(name, init, dummy) {0, JSProto_Null},
static const JSStdName standard_class_names[] = {
JS_FOR_PROTOTYPES(STD_NAME_ENTRY, STD_DUMMY_ENTRY){0, JSProto_LIMIT}};
/*
* Table of top-level function and constant names and the JSProtoKey of the
* standard class that initializes them.
*/
static const JSStdName builtin_property_names[] = {
{NAME_OFFSET(eval), JSProto_Object},
/* Global properties and functions defined by the Number class. */
{NAME_OFFSET(NaN), JSProto_Number},
{NAME_OFFSET(Infinity), JSProto_Number},
{NAME_OFFSET(isNaN), JSProto_Number},
{NAME_OFFSET(isFinite), JSProto_Number},
{NAME_OFFSET(parseFloat), JSProto_Number},
{NAME_OFFSET(parseInt), JSProto_Number},
/* String global functions. */
{NAME_OFFSET(escape), JSProto_String},
{NAME_OFFSET(unescape), JSProto_String},
{NAME_OFFSET(decodeURI), JSProto_String},
{NAME_OFFSET(encodeURI), JSProto_String},
{NAME_OFFSET(decodeURIComponent), JSProto_String},
{NAME_OFFSET(encodeURIComponent), JSProto_String},
{NAME_OFFSET(uneval), JSProto_String},
{0, JSProto_LIMIT}};
JS_PUBLIC_API bool JS_ResolveStandardClass(JSContext* cx, HandleObject obj,
HandleId id, bool* resolved) {
const JSStdName* stdnm;
AssertHeapIsIdle();
CHECK_THREAD(cx);
cx->check(obj, id);
Handle<GlobalObject*> global = obj.as<GlobalObject>();
*resolved = false;
if (!JSID_IS_ATOM(id)) {
return true;
}
/* Check whether we're resolving 'undefined', and define it if so. */
JSAtom* idAtom = JSID_TO_ATOM(id);
if (idAtom == cx->names().undefined) {
*resolved = true;
return DefineDataProperty(
cx, global, id, UndefinedHandleValue,
JSPROP_PERMANENT | JSPROP_READONLY | JSPROP_RESOLVING);
}
// Resolve a "globalThis" self-referential property if necessary.
if (idAtom == cx->names().globalThis) {
return GlobalObject::maybeResolveGlobalThis(cx, global, resolved);
}
/* Try for class constructors/prototypes named by well-known atoms. */
stdnm = LookupStdName(cx->names(), idAtom, standard_class_names);
/* Try less frequently used top-level functions and constants. */
if (!stdnm) {
stdnm = LookupStdName(cx->names(), idAtom, builtin_property_names);
}
if (stdnm && GlobalObject::skipDeselectedConstructor(cx, stdnm->key)) {
stdnm = nullptr;
}
// If this class is anonymous, then it doesn't exist as a global
// property, so we won't resolve anything.
JSProtoKey key = stdnm ? stdnm->key : JSProto_Null;
if (key != JSProto_Null) {
const Class* clasp = ProtoKeyToClass(key);
if (!clasp || clasp->specShouldDefineConstructor()) {
if (!GlobalObject::ensureConstructor(cx, global, key)) {
return false;
}
*resolved = true;
return true;
}
}
// There is no such property to resolve. An ordinary resolve hook would
// just return true at this point. But the global object is special in one
// more way: its prototype chain is lazily initialized. That is,
// global->getProto() might be null right now because we haven't created
// Object.prototype yet. Force it now.
return GlobalObject::getOrCreateObjectPrototype(cx, global);
}
JS_PUBLIC_API bool JS_MayResolveStandardClass(const JSAtomState& names, jsid id,
JSObject* maybeObj) {
MOZ_ASSERT_IF(maybeObj, maybeObj->is<GlobalObject>());
// The global object's resolve hook is special: JS_ResolveStandardClass
// initializes the prototype chain lazily. Only attempt to optimize here
// if we know the prototype chain has been initialized.
if (!maybeObj || !maybeObj->staticPrototype()) {
return true;
}
if (!JSID_IS_ATOM(id)) {
return false;
}
JSAtom* atom = JSID_TO_ATOM(id);
// This will return true even for deselected constructors. (To do
// better, we need a JSContext here; it's fine as it is.)
return atom == names.undefined || atom == names.globalThis ||
LookupStdName(names, atom, standard_class_names) ||
LookupStdName(names, atom, builtin_property_names);
}
JS_PUBLIC_API bool JS_EnumerateStandardClasses(JSContext* cx,
HandleObject obj) {
AssertHeapIsIdle();
CHECK_THREAD(cx);
cx->check(obj);
Handle<GlobalObject*> global = obj.as<GlobalObject>();
return GlobalObject::initStandardClasses(cx, global);
}
static bool EnumerateStandardClassesInTable(JSContext* cx,
Handle<GlobalObject*> global,
AutoIdVector& properties,
const JSStdName* table,
bool includeResolved) {
for (unsigned i = 0; !table[i].isSentinel(); i++) {
if (table[i].isDummy()) {
continue;
}
JSProtoKey key = table[i].key;
// If the standard class has been resolved, the properties have been
// defined on the global so we don't need to add them here.
if (!includeResolved && global->isStandardClassResolved(key)) {
continue;
}
if (GlobalObject::skipDeselectedConstructor(cx, key)) {
continue;
}
if (const Class* clasp = ProtoKeyToClass(key)) {
if (!clasp->specShouldDefineConstructor()) {
continue;
}
}
jsid id = NameToId(AtomStateOffsetToName(cx->names(), table[i].atomOffset));
if (!properties.append(id)) {
return false;
}
}
return true;
}
static bool EnumerateStandardClasses(JSContext* cx, JS::HandleObject obj,
JS::AutoIdVector& properties,
bool enumerableOnly,
bool includeResolved) {
if (enumerableOnly) {
// There are no enumerable standard classes and "undefined" is
// not enumerable.
return true;
}
Handle<GlobalObject*> global = obj.as<GlobalObject>();
// It's fine to always append |undefined| here, it's non-configurable and
// the enumeration code filters duplicates.
if (!properties.append(NameToId(cx->names().undefined))) {
return false;
}
if (!EnumerateStandardClassesInTable(cx, global, properties,
standard_class_names, includeResolved)) {
return false;
}
if (!EnumerateStandardClassesInTable(
cx, global, properties, builtin_property_names, includeResolved)) {
return false;
}
return true;
}
JS_PUBLIC_API bool JS_NewEnumerateStandardClasses(JSContext* cx,
JS::HandleObject obj,
JS::AutoIdVector& properties,
bool enumerableOnly) {
return EnumerateStandardClasses(cx, obj, properties, enumerableOnly, false);
}
JS_PUBLIC_API bool JS_NewEnumerateStandardClassesIncludingResolved(
JSContext* cx, JS::HandleObject obj, JS::AutoIdVector& properties,
bool enumerableOnly) {
return EnumerateStandardClasses(cx, obj, properties, enumerableOnly, true);
}