Debian Codegraph @

js/src/vm/GlobalObject.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "vm/GlobalObject.h"
8
9 #include "jsapi.h"
10 #include "jsfriendapi.h"
11
12 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
13 # include "builtin/AsyncDisposableStackObject.h"
14 #endif
15 #include "builtin/AtomicsObject.h"
16 #include "builtin/BigInt.h"
17 #include "builtin/DataViewObject.h"
18 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
19 # include "builtin/DisposableStackObject.h"
20 #endif
21 #ifdef JS_HAS_INTL_API
22 # include "builtin/intl/Collator.h"
23 # include "builtin/intl/DateTimeFormat.h"
24 # include "builtin/intl/DisplayNames.h"
25 # include "builtin/intl/DurationFormat.h"
26 # include "builtin/intl/ListFormat.h"
27 # include "builtin/intl/Locale.h"
28 # include "builtin/intl/NumberFormat.h"
29 # include "builtin/intl/PluralRules.h"
30 # include "builtin/intl/RelativeTimeFormat.h"
31 # include "builtin/intl/Segmenter.h"
32 #endif
33 #include "builtin/FinalizationRegistryObject.h"
34 #include "builtin/MapObject.h"
35 #include "builtin/ShadowRealm.h"
36 #include "builtin/Symbol.h"
37 #ifdef JS_HAS_INTL_API
38 # include "builtin/temporal/Duration.h"
39 # include "builtin/temporal/Instant.h"
40 # include "builtin/temporal/PlainDate.h"
41 # include "builtin/temporal/PlainDateTime.h"
42 # include "builtin/temporal/PlainMonthDay.h"
43 # include "builtin/temporal/PlainTime.h"
44 # include "builtin/temporal/PlainYearMonth.h"
45 # include "builtin/temporal/Temporal.h"
46 # include "builtin/temporal/TemporalNow.h"
47 # include "builtin/temporal/ZonedDateTime.h"
48 #endif
49 #include "builtin/WeakMapObject.h"
50 #include "builtin/WeakRefObject.h"
51 #include "builtin/WeakSetObject.h"
52 #include "debugger/DebugAPI.h"
53 #include "frontend/CompilationStencil.h"
54 #include "gc/FinalizationObservers.h"
55 #include "gc/GC.h"
56 #include "gc/GCContext.h"
57 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
58 #include "js/friend/WindowProxy.h" // js::ToWindowProxyIfWindow
59 #include "js/Prefs.h" // JS::Prefs
60 #include "js/PropertyAndElement.h" // JS_DefineFunctions, JS_DefineProperties
61 #include "js/ProtoKey.h"
62 #include "vm/AsyncFunction.h"
63 #include "vm/AsyncIteration.h"
64 #include "vm/BooleanObject.h"
65 #include "vm/Compartment.h"
66 #include "vm/DateObject.h"
67 #include "vm/EnvironmentObject.h"
68 #include "vm/ErrorObject.h"
69 #include "vm/GeneratorObject.h"
70 #include "vm/JSContext.h"
71 #include "vm/NumberObject.h"
72 #include "vm/PlainObject.h"
73 #include "vm/RegExpObject.h"
74 #include "vm/RegExpStatics.h"
75 #include "vm/SelfHosting.h"
76 #include "vm/StringObject.h"
77 #include "wasm/WasmFeatures.h"
78 #include "wasm/WasmJS.h"
79 #include "gc/GCContext-inl.h"
80 #include "vm/JSObject-inl.h"
81 #include "vm/Realm-inl.h"
82
83 using namespace js;
84
85 namespace js {
86
87 extern const JSClass IntlClass;
88 extern const JSClass JSONClass;
89 extern const JSClass MathClass;
90 extern const JSClass ReflectClass;
91
92 } // namespace js
93
94 static constexpr const JSClass* const protoTable[JSProto_LIMIT] = {
95 #define INIT_FUNC(name, clasp) clasp,
96 #define INIT_FUNC_DUMMY(name, clasp) nullptr,
97 JS_FOR_PROTOTYPES(INIT_FUNC, INIT_FUNC_DUMMY)
98 #undef INIT_FUNC_DUMMY
99 #undef INIT_FUNC
100 };
101
102 JS_PUBLIC_API const JSClass* js::ProtoKeyToClass(JSProtoKey key) {
103 MOZ_ASSERT(key < JSProto_LIMIT);
104 return protoTable[key];
105 }
106
107 static bool IsAsyncIteratorHelpersEnabled() {
108 #ifdef NIGHTLY_BUILD
109 return JS::Prefs::experimental_async_iterator_helpers();
110 #else
111 return false;
112 #endif
113 }
114
115 /* static */
116 bool GlobalObject::skipDeselectedConstructor(JSContext* cx, JSProtoKey key) {
117 switch (key) {
118 case JSProto_Null:
119 case JSProto_Object:
120 case JSProto_Function:
121 case JSProto_BoundFunction:
122 case JSProto_Array:
123 case JSProto_Boolean:
124 case JSProto_JSON:
125 case JSProto_Date:
126 case JSProto_Math:
127 case JSProto_Number:
128 case JSProto_String:
129 case JSProto_RegExp:
130 case JSProto_Error:
131 case JSProto_InternalError:
132 case JSProto_Iterator:
133 case JSProto_AggregateError:
134 case JSProto_EvalError:
135 case JSProto_RangeError:
136 case JSProto_ReferenceError:
137 case JSProto_SyntaxError:
138 case JSProto_TypeError:
139 case JSProto_URIError:
140 case JSProto_DebuggeeWouldRun:
141 case JSProto_CompileError:
142 case JSProto_LinkError:
143 case JSProto_RuntimeError:
144 case JSProto_ArrayBuffer:
145 case JSProto_Int8Array:
146 case JSProto_Uint8Array:
147 case JSProto_Int16Array:
148 case JSProto_Uint16Array:
149 case JSProto_Int32Array:
150 case JSProto_Uint32Array:
151 case JSProto_Float16Array:
152 case JSProto_Float32Array:
153 case JSProto_Float64Array:
154 case JSProto_Uint8ClampedArray:
155 case JSProto_BigInt64Array:
156 case JSProto_BigUint64Array:
157 case JSProto_BigInt:
158 case JSProto_Proxy:
159 case JSProto_WeakMap:
160 case JSProto_Map:
161 case JSProto_Set:
162 case JSProto_DataView:
163 case JSProto_Symbol:
164 case JSProto_Reflect:
165 case JSProto_WeakSet:
166 case JSProto_TypedArray:
167 case JSProto_SavedFrame:
168 case JSProto_Promise:
169 case JSProto_AsyncFunction:
170 case JSProto_GeneratorFunction:
171 case JSProto_AsyncGeneratorFunction:
172 case JSProto_WeakRef:
173 case JSProto_FinalizationRegistry:
174 return false;
175
176 case JSProto_WebAssembly:
177 return !wasm::HasSupport(cx);
178
179 case JSProto_WasmModule:
180 case JSProto_WasmInstance:
181 case JSProto_WasmMemory:
182 case JSProto_WasmTable:
183 case JSProto_WasmGlobal:
184 case JSProto_WasmTag:
185 #ifdef ENABLE_WASM_TYPE_REFLECTIONS
186 case JSProto_WasmFunction:
187 #endif
188 #ifdef ENABLE_WASM_JSPI
189 case JSProto_WasmSuspending:
190 case JSProto_SuspendError:
191 #endif
192 case JSProto_WasmException:
193 return false;
194
195 #ifdef JS_HAS_INTL_API
196 case JSProto_Intl:
197 case JSProto_Collator:
198 case JSProto_DateTimeFormat:
199 case JSProto_DisplayNames:
200 case JSProto_DurationFormat:
201 case JSProto_Locale:
202 case JSProto_ListFormat:
203 case JSProto_NumberFormat:
204 case JSProto_PluralRules:
205 case JSProto_RelativeTimeFormat:
206 case JSProto_Segmenter:
207 return false;
208
209 case JSProto_Temporal:
210 case JSProto_Duration:
211 case JSProto_Instant:
212 case JSProto_PlainDate:
213 case JSProto_PlainDateTime:
214 case JSProto_PlainMonthDay:
215 case JSProto_PlainTime:
216 case JSProto_PlainYearMonth:
217 case JSProto_TemporalNow:
218 case JSProto_ZonedDateTime:
219 return !JS::Prefs::experimental_temporal();
220 #endif
221
222 // Return true if the given constructor has been disabled at run-time.
223 case JSProto_Atomics:
224 case JSProto_SharedArrayBuffer:
225 return !cx->realm()->creationOptions().getSharedMemoryAndAtomicsEnabled();
226
227 case JSProto_AsyncIterator:
228 return !IsAsyncIteratorHelpersEnabled();
229
230 case JSProto_ShadowRealm:
231 return !JS::Prefs::experimental_shadow_realms();
232
233 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
234 case JSProto_SuppressedError:
235 case JSProto_DisposableStack:
236 case JSProto_AsyncDisposableStack:
237 return !JS::Prefs::experimental_explicit_resource_management();
238 #endif
239
240 default:
241 MOZ_CRASH("unexpected JSProtoKey");
242 }
243 }
244
245 static bool ShouldFreezeBuiltin(JSProtoKey key) {
246 // We can't freeze Reflect because JS_InitReflectParse defines Reflect.parse.
247 if (key == JSProto_Reflect) {
248 return false;
249 }
250 // We can't freeze Date because some browser tests use the Sinon library which
251 // redefines Date.now.
252 if (key == JSProto_Date) {
253 return false;
254 }
255 return true;
256 }
257
258 static unsigned GetAttrsForResolvedGlobal(GlobalObject* global,
259 JSProtoKey key) {
260 unsigned attrs = JSPROP_RESOLVING;
261 if (global->realm()->creationOptions().freezeBuiltins() &&
262 ShouldFreezeBuiltin(key)) {
263 attrs |= JSPROP_PERMANENT | JSPROP_READONLY;
264 }
265 return attrs;
266 }
267
268 /* static*/
269 bool GlobalObject::resolveConstructor(JSContext* cx,
270 Handle<GlobalObject*> global,
271 JSProtoKey key, IfClassIsDisabled mode) {
272 MOZ_ASSERT(key != JSProto_Null);
273 MOZ_ASSERT(key != JSProto_BoundFunction,
274 "bound functions don't have their own proto object");
275 MOZ_ASSERT(!global->isStandardClassResolved(key));
276 MOZ_ASSERT(cx->compartment() == global->compartment());
277
278 // |global| must be same-compartment but make sure we're in its realm: the
279 // code below relies on this.
280 AutoRealm ar(cx, global);
281
282 // Prohibit collection of allocation metadata. Metadata builders shouldn't
283 // need to observe lazily-constructed prototype objects coming into
284 // existence. And assertions start to fail when the builder itself attempts
285 // an allocation that re-entrantly tries to create the same prototype.
286 AutoSuppressAllocationMetadataBuilder suppressMetadata(cx);
287
288 // Constructor resolution may execute self-hosted scripts. These
289 // self-hosted scripts do not call out to user code by construction. Allow
290 // all scripts to execute, even in debuggee compartments that are paused.
291 AutoSuppressDebuggeeNoExecuteChecks suppressNX(cx);
292
293 // Some classes can be disabled at compile time, others at run time;
294 // if a feature is compile-time disabled, clasp is null.
295 const JSClass* clasp = ProtoKeyToClass(key);
296 if (!clasp || skipDeselectedConstructor(cx, key)) {
297 if (mode == IfClassIsDisabled::Throw) {
298 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
299 JSMSG_CONSTRUCTOR_DISABLED,
300 clasp ? clasp->name : "constructor");
301 return false;
302 }
303 return true;
304 }
305
306 // Class spec must have a constructor defined.
307 if (!clasp->specDefined()) {
308 return true;
309 }
310
311 bool isObjectOrFunction = key == JSProto_Function || key == JSProto_Object;
312
313 // We need to create the prototype first, and immediately stash it in the
314 // slot. This is so the following bootstrap ordering is possible:
315 // * Object.prototype
316 // * Function.prototype
317 // * Function
318 // * Object
319 //
320 // We get the above when Object is resolved before Function. If Function
321 // is resolved before Object, we'll end up re-entering resolveConstructor
322 // for Function, which is a problem. So if Function is being resolved
323 // before Object.prototype exists, we just resolve Object instead, since we
324 // know that Function will also be resolved before we return.
325 if (key == JSProto_Function && !global->hasPrototype(JSProto_Object)) {
326 return resolveConstructor(cx, global, JSProto_Object,
327 IfClassIsDisabled::DoNothing);
328 }
329
330 // %IteratorPrototype%.map.[[Prototype]] is %Generator% and
331 // %Generator%.prototype.[[Prototype]] is %IteratorPrototype%.
332 if (key == JSProto_GeneratorFunction &&
333 !global->hasPrototype(JSProto_Iterator)) {
334 if (!getOrCreateIteratorPrototype(cx, global)) {
335 return false;
336 }
337
338 // If iterator helpers are enabled, populating %IteratorPrototype% will
339 // have recursively gone through here.
340 if (global->isStandardClassResolved(key)) {
341 return true;
342 }
343 }
344
345 // We don't always have a prototype (i.e. Math and JSON). If we don't,
346 // |createPrototype|, |prototypeFunctions|, and |prototypeProperties|
347 // should all be null.
348 RootedObject proto(cx);
349 if (ClassObjectCreationOp createPrototype =
350 clasp->specCreatePrototypeHook()) {
351 proto = createPrototype(cx, key);
352 if (!proto) {
353 return false;
354 }
355
356 if (isObjectOrFunction) {
357 // Make sure that creating the prototype didn't recursively resolve
358 // our own constructor. We can't just assert that there's no
359 // prototype; OOMs can result in incomplete resolutions in which
360 // the prototype is saved but not the constructor. So use the same
361 // criteria that protects entry into this function.
362 MOZ_ASSERT(!global->isStandardClassResolved(key));
363
364 global->setPrototype(key, proto);
365 }
366 }
367
368 // Create the constructor.
369 RootedObject ctor(cx, clasp->specCreateConstructorHook()(cx, key));
370 if (!ctor) {
371 return false;
372 }
373
374 RootedId id(cx, NameToId(ClassName(key, cx)));
375 if (isObjectOrFunction) {
376 if (clasp->specShouldDefineConstructor()) {
377 RootedValue ctorValue(cx, ObjectValue(*ctor));
378 unsigned attrs = GetAttrsForResolvedGlobal(global, key);
379 if (!DefineDataProperty(cx, global, id, ctorValue, attrs)) {
380 return false;
381 }
382 }
383
384 global->setConstructor(key, ctor);
385 }
386
387 if (const JSFunctionSpec* funs = clasp->specPrototypeFunctions()) {
388 if (!JS_DefineFunctions(cx, proto, funs)) {
389 return false;
390 }
391 }
392 if (const JSPropertySpec* props = clasp->specPrototypeProperties()) {
393 if (!JS_DefineProperties(cx, proto, props)) {
394 return false;
395 }
396 }
397 if (const JSFunctionSpec* funs = clasp->specConstructorFunctions()) {
398 if (!JS_DefineFunctions(cx, ctor, funs)) {
399 return false;
400 }
401 }
402 if (const JSPropertySpec* props = clasp->specConstructorProperties()) {
403 if (!JS_DefineProperties(cx, ctor, props)) {
404 return false;
405 }
406 }
407
408 // If the prototype exists, link it with the constructor.
409 if (proto && !LinkConstructorAndPrototype(cx, ctor, proto)) {
410 return false;
411 }
412
413 // Call the post-initialization hook, if provided.
414 if (FinishClassInitOp finishInit = clasp->specFinishInitHook()) {
415 if (!finishInit(cx, ctor, proto)) {
416 return false;
417 }
418 }
419
420 if (ShouldFreezeBuiltin(key)) {
421 if (!JS::MaybeFreezeCtorAndPrototype(cx, ctor, proto)) {
422 return false;
423 }
424 }
425
426 // If the prototype exists, mark the object as used as a prototype to enable
427 // Watchtower observation of protos which may not yet actually have an
428 // instance which yet uses it as a proto!
429 //
430 // You might well be asking: "Why not set IsUsedAsPrototype when constructing
431 // the proto object?". This ends up leading to a fair amount of complexity in
432 // how standard protos are linked together and the properties we want to
433 // enforce. Generally, it's fine if we don't watch for mutations on protos
434 // until they get exposed to user code.
435 if (proto && !JSObject::setFlag(cx, proto, ObjectFlag::IsUsedAsPrototype)) {
436 return false;
437 }
438
439 if (!isObjectOrFunction) {
440 // Any operations that modifies the global object should be placed
441 // after any other fallible operations.
442
443 // Fallible operation that modifies the global object.
444 if (clasp->specShouldDefineConstructor()) {
445 bool shouldReallyDefine = true;
446
447 // On the web, it isn't presently possible to expose the global
448 // "SharedArrayBuffer" property unless the page is cross-site-isolated.
449 // Only define this constructor if an option on the realm indicates that
450 // it should be defined.
451 if (key == JSProto_SharedArrayBuffer) {
452 const JS::RealmCreationOptions& options =
453 global->realm()->creationOptions();
454
455 MOZ_ASSERT(options.getSharedMemoryAndAtomicsEnabled(),
456 "shouldn't be defining SharedArrayBuffer if shared memory "
457 "is disabled");
458
459 shouldReallyDefine = options.defineSharedArrayBufferConstructor();
460 }
461
462 if (shouldReallyDefine) {
463 RootedValue ctorValue(cx, ObjectValue(*ctor));
464 unsigned attrs = GetAttrsForResolvedGlobal(global, key);
465 if (!DefineDataProperty(cx, global, id, ctorValue, attrs)) {
466 return false;
467 }
468 }
469 }
470
471 // Infallible operations that modify the global object.
472 global->setConstructor(key, ctor);
473 if (proto) {
474 global->setPrototype(key, proto);
475 }
476 }
477
478 return true;
479 }
480
481 // Resolve a "globalThis" self-referential property if necessary,
482 // per a stage-3 proposal. https://github.com/tc39/ecma262/pull/702
483 //
484 // We could also do this in |FinishObjectClassInit| to trim the global
485 // resolve hook. Unfortunately, |ToWindowProxyIfWindow| doesn't work then:
486 // the browser's |nsGlobalWindow::SetNewDocument| invokes Object init
487 // *before* it sets the global's WindowProxy using |js::SetWindowProxy|.
488 //
489 // Refactoring global object creation code to support this approach is a
490 // challenge for another day.
491 /* static */
492 bool GlobalObject::maybeResolveGlobalThis(JSContext* cx,
493 Handle<GlobalObject*> global,
494 bool* resolved) {
495 if (!global->data().globalThisResolved) {
496 RootedValue v(cx, ObjectValue(*ToWindowProxyIfWindow(global)));
497 if (!DefineDataProperty(cx, global, cx->names().globalThis, v,
498 JSPROP_RESOLVING)) {
499 return false;
500 }
501
502 *resolved = true;
503 global->data().globalThisResolved = true;
504 }
505
506 return true;
507 }
508
509 /* static */
510 JSObject* GlobalObject::createBuiltinProto(JSContext* cx,
511 Handle<GlobalObject*> global,
512 ProtoKind kind, ObjectInitOp init) {
513 if (!init(cx, global)) {
514 return nullptr;
515 }
516
517 return &global->getBuiltinProto(kind);
518 }
519
520 JSObject* GlobalObject::createBuiltinProto(JSContext* cx,
521 Handle<GlobalObject*> global,
522 ProtoKind kind, Handle<JSAtom*> tag,
523 ObjectInitWithTagOp init) {
524 if (!init(cx, global, tag)) {
525 return nullptr;
526 }
527
528 return &global->getBuiltinProto(kind);
529 }
530
531 static bool ThrowTypeError(JSContext* cx, unsigned argc, Value* vp) {
532 ThrowTypeErrorBehavior(cx);
533 return false;
534 }
535
536 /* static */
537 JSObject* GlobalObject::getOrCreateThrowTypeError(
538 JSContext* cx, Handle<GlobalObject*> global) {
539 if (JSFunction* fun = global->data().throwTypeError) {
540 return fun;
541 }
542
543 // Construct the unique [[%ThrowTypeError%]] function object, used only for
544 // "callee" and "caller" accessors on strict mode arguments objects. (The
545 // spec also uses this for "arguments" and "caller" on various functions,
546 // but we're experimenting with implementing them using accessors on
547 // |Function.prototype| right now.)
548
549 RootedFunction throwTypeError(
550 cx, NewNativeFunction(cx, ThrowTypeError, 0, nullptr));
551 if (!throwTypeError || !PreventExtensions(cx, throwTypeError)) {
552 return nullptr;
553 }
554
555 // The "length" property of %ThrowTypeError% is non-configurable.
556 Rooted<PropertyDescriptor> nonConfigurableDesc(cx,
557 PropertyDescriptor::Empty());
558 nonConfigurableDesc.setConfigurable(false);
559
560 RootedId lengthId(cx, NameToId(cx->names().length));
561 ObjectOpResult lengthResult;
562 if (!NativeDefineProperty(cx, throwTypeError, lengthId, nonConfigurableDesc,
563 lengthResult)) {
564 return nullptr;
565 }
566 MOZ_ASSERT(lengthResult);
567
568 // The "name" property of %ThrowTypeError% is non-configurable, adjust
569 // the default property attributes accordingly.
570 RootedId nameId(cx, NameToId(cx->names().name));
571 ObjectOpResult nameResult;
572 if (!NativeDefineProperty(cx, throwTypeError, nameId, nonConfigurableDesc,
573 nameResult)) {
574 return nullptr;
575 }
576 MOZ_ASSERT(nameResult);
577
578 global->data().throwTypeError.init(throwTypeError);
579 return throwTypeError;
580 }
581
582 GlobalObject* GlobalObject::createInternal(JSContext* cx,
583 const JSClass* clasp) {
584 MOZ_ASSERT(clasp->flags & JSCLASS_IS_GLOBAL);
585 MOZ_ASSERT(clasp->isTrace(JS_GlobalObjectTraceHook));
586
587 ObjectFlags objectFlags = {
588 ObjectFlag::QualifiedVarObj,
589 ObjectFlag::GenerationCountedGlobal,
590 };
591
592 JSObject* obj =
593 NewTenuredObjectWithGivenProto(cx, clasp, nullptr, objectFlags);
594 if (!obj) {
595 return nullptr;
596 }
597
598 Rooted<GlobalObject*> global(cx, &obj->as<GlobalObject>());
599
600 // Global holds both variables qualified with `var` and those that are not.
601 MOZ_ASSERT(global->isUnqualifiedVarObj());
602 MOZ_ASSERT(global->isQualifiedVarObj());
603
604 // Global objects support generation counts.
605 MOZ_ASSERT(global->isGenerationCountedGlobal());
606
607 {
608 auto data = cx->make_unique<GlobalObjectData>(cx->zone());
609 if (!data) {
610 return nullptr;
611 }
612 // Note: it's important for the realm's global to be initialized at the
613 // same time as the global's GlobalObjectData, because we free the global's
614 // data when Realm::global_ is cleared.
615 cx->realm()->initGlobal(*global);
616 InitReservedSlot(global, GLOBAL_DATA_SLOT, data.release(),
617 MemoryUse::GlobalObjectData);
618 }
619
620 Rooted<GlobalLexicalEnvironmentObject*> lexical(
621 cx, GlobalLexicalEnvironmentObject::create(cx, global));
622 if (!lexical) {
623 return nullptr;
624 }
625 global->data().lexicalEnvironment.init(lexical);
626
627 Rooted<GlobalScope*> emptyGlobalScope(
628 cx, GlobalScope::createEmpty(cx, ScopeKind::Global));
629 if (!emptyGlobalScope) {
630 return nullptr;
631 }
632 global->data().emptyGlobalScope.init(emptyGlobalScope);
633
634 if (!GlobalObject::createIntrinsicsHolder(cx, global)) {
635 return nullptr;
636 }
637
638 return global;
639 }
640
641 /* static */
642 GlobalObject* GlobalObject::new_(JSContext* cx, const JSClass* clasp,
643 JSPrincipals* principals,
644 JS::OnNewGlobalHookOption hookOption,
645 const JS::RealmOptions& options) {
646 MOZ_ASSERT(!cx->isExceptionPending());
647 MOZ_ASSERT_IF(cx->zone(), !cx->zone()->isAtomsZone());
648
649 // If we are creating a new global in an existing compartment, make sure the
650 // compartment has a live global at all times (by rooting it here).
651 // See bug 1530364.
652 Rooted<GlobalObject*> existingGlobal(cx);
653 const JS::RealmCreationOptions& creationOptions = options.creationOptions();
654 if (creationOptions.compartmentSpecifier() ==
655 JS::CompartmentSpecifier::ExistingCompartment) {
656 Compartment* comp = creationOptions.compartment();
657 existingGlobal = &comp->firstGlobal();
658 }
659
660 Realm* realm = NewRealm(cx, principals, options);
661 if (!realm) {
662 return nullptr;
663 }
664
665 Rooted<GlobalObject*> global(cx);
666 {
667 AutoRealmUnchecked ar(cx, realm);
668 global = GlobalObject::createInternal(cx, clasp);
669 if (!global) {
670 return nullptr;
671 }
672
673 // Make transactional initialization of these constructors by discarding the
674 // incompletely initialized global if an error occur. This also ensures the
675 // global's prototype chain is initialized (in FinishObjectClassInit).
676 if (!ensureConstructor(cx, global, JSProto_Object) ||
677 !ensureConstructor(cx, global, JSProto_Function)) {
678 return nullptr;
679 }
680
681 // Create a shape for plain objects with zero slots. This is required to be
682 // present in case allocating dynamic slots for objects fails, so we can
683 // leave a valid object in the heap.
684 if (!createPlainObjectShapeWithDefaultProto(cx, gc::AllocKind::OBJECT0)) {
685 return nullptr;
686 }
687
688 realm->clearInitializingGlobal();
689 if (hookOption == JS::FireOnNewGlobalHook) {
690 JS_FireOnNewGlobalObject(cx, global);
691 }
692 }
693
694 return global;
695 }
696
697 GlobalScope& GlobalObject::emptyGlobalScope() const {
698 return *data().emptyGlobalScope;
699 }
700
701 bool GlobalObject::valueIsEval(const Value& val) {
702 return val.isObject() && data().eval == &val.toObject();
703 }
704
705 /* static */
706 bool GlobalObject::initStandardClasses(JSContext* cx,
707 Handle<GlobalObject*> global) {
708 /* Define a top-level property 'undefined' with the undefined value. */
709 if (!DefineDataProperty(
710 cx, global, cx->names().undefined, UndefinedHandleValue,
711 JSPROP_PERMANENT | JSPROP_READONLY | JSPROP_RESOLVING)) {
712 return false;
713 }
714
715 // Resolve a "globalThis" self-referential property if necessary.
716 bool resolved;
717 if (!GlobalObject::maybeResolveGlobalThis(cx, global, &resolved)) {
718 return false;
719 }
720
721 for (size_t k = 0; k < JSProto_LIMIT; ++k) {
722 JSProtoKey key = static_cast<JSProtoKey>(k);
723 if (key != JSProto_Null && key != JSProto_BoundFunction &&
724 !global->isStandardClassResolved(key)) {
725 if (!resolveConstructor(cx, global, static_cast<JSProtoKey>(k),
726 IfClassIsDisabled::DoNothing)) {
727 return false;
728 }
729 }
730 }
731 return true;
732 }
733
734 /* static */
735 JSFunction* GlobalObject::createConstructor(JSContext* cx, Native ctor,
736 JSAtom* nameArg, unsigned length,
737 gc::AllocKind kind,
738 const JSJitInfo* jitInfo) {
739 Rooted<JSAtom*> name(cx, nameArg);
740 JSFunction* fun = NewNativeConstructor(cx, ctor, length, name, kind);
741 if (!fun) {
742 return nullptr;
743 }
744
745 if (jitInfo) {
746 fun->setJitInfo(jitInfo);
747 }
748
749 return fun;
750 }
751
752 static NativeObject* CreateBlankProto(JSContext* cx, const JSClass* clasp,
753 HandleObject proto,
754 ObjectFlags objFlags) {
755 MOZ_ASSERT(!clasp->isJSFunction());
756
757 if (clasp == &PlainObject::class_) {
758 // NOTE: There should be no reason currently to support this. It could
759 // however be added later if needed.
760 MOZ_ASSERT(objFlags.isEmpty());
761 return NewPlainObjectWithProto(cx, proto, TenuredObject);
762 }
763
764 return NewTenuredObjectWithGivenProto(cx, clasp, proto, objFlags);
765 }
766
767 /* static */
768 NativeObject* GlobalObject::createBlankPrototype(JSContext* cx,
769 Handle<GlobalObject*> global,
770 const JSClass* clasp,
771 ObjectFlags objFlags) {
772 RootedObject objectProto(cx, &global->getObjectPrototype());
773 return CreateBlankProto(cx, clasp, objectProto, objFlags);
774 }
775
776 /* static */
777 NativeObject* GlobalObject::createBlankPrototypeInheriting(JSContext* cx,
778 const JSClass* clasp,
779 HandleObject proto) {
780 return CreateBlankProto(cx, clasp, proto, ObjectFlags());
781 }
782
783 bool js::LinkConstructorAndPrototype(JSContext* cx, JSObject* ctor_,
784 JSObject* proto_, unsigned prototypeAttrs,
785 unsigned constructorAttrs) {
786 RootedObject ctor(cx, ctor_), proto(cx, proto_);
787
788 RootedValue protoVal(cx, ObjectValue(*proto));
789 RootedValue ctorVal(cx, ObjectValue(*ctor));
790
791 return DefineDataProperty(cx, ctor, cx->names().prototype, protoVal,
792 prototypeAttrs) &&
793 DefineDataProperty(cx, proto, cx->names().constructor, ctorVal,
794 constructorAttrs);
795 }
796
797 bool js::DefinePropertiesAndFunctions(JSContext* cx, HandleObject obj,
798 const JSPropertySpec* ps,
799 const JSFunctionSpec* fs) {
800 if (ps && !JS_DefineProperties(cx, obj, ps)) {
801 return false;
802 }
803 if (fs && !JS_DefineFunctions(cx, obj, fs)) {
804 return false;
805 }
806 return true;
807 }
808
809 bool js::DefineToStringTag(JSContext* cx, HandleObject obj, JSAtom* tag) {
810 RootedId toStringTagId(
811 cx, PropertyKey::Symbol(cx->wellKnownSymbols().toStringTag));
812 RootedValue tagString(cx, StringValue(tag));
813 return DefineDataProperty(cx, obj, toStringTagId, tagString, JSPROP_READONLY);
814 }
815
816 /* static */
817 JSObject* GlobalObject::getOrCreateRealmKeyObject(
818 JSContext* cx, Handle<GlobalObject*> global) {
819 cx->check(global);
820 if (PlainObject* key = global->data().realmKeyObject) {
821 return key;
822 }
823
824 PlainObject* key = NewPlainObject(cx);
825 if (!key) {
826 return nullptr;
827 }
828
829 global->data().realmKeyObject.init(key);
830 return key;
831 }
832
833 /* static */
834 RegExpStatics* GlobalObject::getRegExpStatics(JSContext* cx,
835 Handle<GlobalObject*> global) {
836 MOZ_ASSERT(cx);
837
838 if (!global->regExpRealm().regExpStatics) {
839 auto statics = RegExpStatics::create(cx);
840 if (!statics) {
841 return nullptr;
842 }
843 global->regExpRealm().regExpStatics = std::move(statics);
844 }
845
846 return global->regExpRealm().regExpStatics.get();
847 }
848
849 gc::FinalizationRegistryGlobalData*
850 GlobalObject::getOrCreateFinalizationRegistryData() {
851 if (!data().finalizationRegistryData) {
852 data().finalizationRegistryData =
853 MakeUnique<gc::FinalizationRegistryGlobalData>(zone());
854 }
855
856 return maybeFinalizationRegistryData();
857 }
858
859 /* static */
860 bool GlobalObject::createIntrinsicsHolder(JSContext* cx,
861 Handle<GlobalObject*> global) {
862 Rooted<NativeObject*> intrinsicsHolder(
863 cx, NewPlainObjectWithProto(cx, nullptr, TenuredObject));
864 if (!intrinsicsHolder) {
865 return false;
866 }
867
868 // Install the intrinsics holder on the global.
869 global->data().intrinsicsHolder.init(intrinsicsHolder);
870 return true;
871 }
872
873 /* static */
874 bool GlobalObject::getSelfHostedFunction(JSContext* cx,
875 Handle<GlobalObject*> global,
876 Handle<PropertyName*> selfHostedName,
877 Handle<JSAtom*> name, unsigned nargs,
878 MutableHandleValue funVal) {
879 if (global->maybeGetIntrinsicValue(selfHostedName, funVal.address(), cx)) {
880 RootedFunction fun(cx, &funVal.toObject().as<JSFunction>());
881 if (fun->fullExplicitName() == name) {
882 return true;
883 }
884
885 if (fun->fullExplicitName() == selfHostedName) {
886 // This function was initially cloned because it was called by
887 // other self-hosted code, so the clone kept its self-hosted name,
888 // instead of getting the name it's intended to have in content
889 // compartments. This can happen when a lazy builtin is initialized
890 // after self-hosted code for another builtin used the same
891 // function. In that case, we need to change the function's name,
892 // which is ok because it can't have been exposed to content
893 // before.
894 fun->setAtom(name);
895 return true;
896 }
897
898 // The function might be installed multiple times on the same or
899 // different builtins, under different property names, so its name
900 // might be neither "selfHostedName" nor "name". In that case, its
901 // canonical name must've been set using the `_SetCanonicalName`
902 // intrinsic.
903 cx->runtime()->assertSelfHostedFunctionHasCanonicalName(selfHostedName);
904 return true;
905 }
906
907 // Don't collect metadata for self-hosted functions or intrinsics.
908 // This is similar to the suppression in GlobalObject::resolveConstructor.
909 AutoSuppressAllocationMetadataBuilder suppressMetadata(cx);
910
911 JSRuntime* runtime = cx->runtime();
912 frontend::ScriptIndex index =
913 runtime->getSelfHostedScriptIndexRange(selfHostedName)->start;
914 JSFunction* fun =
915 runtime->selfHostStencil().instantiateSelfHostedLazyFunction(
916 cx, runtime->selfHostStencilInput().atomCache, index, name);
917 if (!fun) {
918 return false;
919 }
920 MOZ_ASSERT(fun->nargs() == nargs);
921 funVal.setObject(*fun);
922
923 return GlobalObject::addIntrinsicValue(cx, global, selfHostedName, funVal);
924 }
925
926 /* static */
927 bool GlobalObject::getIntrinsicValueSlow(JSContext* cx,
928 Handle<GlobalObject*> global,
929 Handle<PropertyName*> name,
930 MutableHandleValue value) {
931 // Don't collect metadata for self-hosted functions or intrinsics.
932 // This is similar to the suppression in GlobalObject::resolveConstructor.
933 AutoSuppressAllocationMetadataBuilder suppressMetadata(cx);
934
935 // If this is a C++ intrinsic, simply define the function on the intrinsics
936 // holder.
937 if (const JSFunctionSpec* spec = js::FindIntrinsicSpec(name)) {
938 RootedId id(cx, NameToId(name));
939 RootedFunction fun(cx, JS::NewFunctionFromSpec(cx, spec, id));
940 if (!fun) {
941 return false;
942 }
943 fun->setIsIntrinsic();
944
945 value.setObject(*fun);
946 return GlobalObject::addIntrinsicValue(cx, global, name, value);
947 }
948
949 if (!cx->runtime()->getSelfHostedValue(cx, name, value)) {
950 return false;
951 }
952
953 // It's possible in certain edge cases that cloning the value ended up
954 // defining the intrinsic. For instance, cloning can call NewArray, which
955 // resolves Array.prototype, which defines some self-hosted functions. If this
956 // happens we use the value already defined on the intrinsics holder.
957 if (global->maybeGetIntrinsicValue(name, value.address(), cx)) {
958 return true;
959 }
960
961 return GlobalObject::addIntrinsicValue(cx, global, name, value);
962 }
963
964 /* static */
965 bool GlobalObject::addIntrinsicValue(JSContext* cx,
966 Handle<GlobalObject*> global,
967 Handle<PropertyName*> name,
968 HandleValue value) {
969 Rooted<NativeObject*> holder(cx, &global->getIntrinsicsHolder());
970
971 RootedId id(cx, NameToId(name));
972 MOZ_ASSERT(!holder->containsPure(id));
973
974 constexpr PropertyFlags propFlags = {PropertyFlag::Configurable,
975 PropertyFlag::Writable};
976 uint32_t slot;
977 if (!NativeObject::addProperty(cx, holder, id, propFlags, &slot)) {
978 return false;
979 }
980 holder->initSlot(slot, value);
981 return true;
982 }
983
984 /* static */
985 JSObject* GlobalObject::createIteratorPrototype(JSContext* cx,
986 Handle<GlobalObject*> global) {
987 if (!ensureConstructor(cx, global, JSProto_Iterator)) {
988 return nullptr;
989 }
990 JSObject* proto = &global->getPrototype(JSProto_Iterator);
991 return proto;
992 }
993
994 /* static */
995 JSObject* GlobalObject::createAsyncIteratorPrototype(
996 JSContext* cx, Handle<GlobalObject*> global) {
997 if (!IsAsyncIteratorHelpersEnabled()) {
998 return getOrCreateBuiltinProto(cx, global, ProtoKind::AsyncIteratorProto,
999 initAsyncIteratorProto);
1000 }
1001
1002 if (!ensureConstructor(cx, global, JSProto_AsyncIterator)) {
1003 return nullptr;
1004 }
1005 JSObject* proto = &global->getPrototype(JSProto_AsyncIterator);
1006 global->initBuiltinProto(ProtoKind::AsyncIteratorProto, proto);
1007 return proto;
1008 }
1009
1010 void GlobalObject::releaseData(JS::GCContext* gcx) {
1011 GlobalObjectData* data = maybeData();
1012 setReservedSlot(GLOBAL_DATA_SLOT, PrivateValue(nullptr));
1013 gcx->delete_(this, data, MemoryUse::GlobalObjectData);
1014 }
1015
1016 GlobalObjectData::GlobalObjectData(Zone* zone) {}
1017
1018 GlobalObjectData::~GlobalObjectData() = default;
1019
1020 void GlobalObjectData::trace(JSTracer* trc, GlobalObject* global) {
1021 for (auto& ctorWithProto : builtinConstructors) {
1022 TraceNullableEdge(trc, &ctorWithProto.constructor, "global-builtin-ctor");
1023 TraceNullableEdge(trc, &ctorWithProto.prototype,
1024 "global-builtin-ctor-proto");
1025 }
1026
1027 for (auto& proto : builtinProtos) {
1028 TraceNullableEdge(trc, &proto, "global-builtin-proto");
1029 }
1030
1031 TraceNullableEdge(trc, &emptyGlobalScope, "global-empty-scope");
1032
1033 TraceNullableEdge(trc, &lexicalEnvironment, "global-lexical-env");
1034 TraceNullableEdge(trc, &windowProxy, "global-window-proxy");
1035 TraceNullableEdge(trc, &intrinsicsHolder, "global-intrinsics-holder");
1036 TraceNullableEdge(trc, &computedIntrinsicsHolder,
1037 "global-computed-intrinsics-holder");
1038 TraceNullableEdge(trc, &sourceURLsHolder, "global-source-urls");
1039 TraceNullableEdge(trc, &realmKeyObject, "global-realm-key");
1040 TraceNullableEdge(trc, &throwTypeError, "global-throw-type-error");
1041 TraceNullableEdge(trc, &eval, "global-eval");
1042 TraceNullableEdge(trc, &emptyIterator, "global-empty-iterator");
1043
1044 TraceNullableEdge(trc, &arrayShapeWithDefaultProto, "global-array-shape");
1045
1046 for (auto& shape : plainObjectShapesWithDefaultProto) {
1047 TraceNullableEdge(trc, &shape, "global-plain-shape");
1048 }
1049
1050 TraceNullableEdge(trc, &functionShapeWithDefaultProto,
1051 "global-function-shape");
1052 TraceNullableEdge(trc, &extendedFunctionShapeWithDefaultProto,
1053 "global-ext-function-shape");
1054
1055 TraceNullableEdge(trc, &boundFunctionShapeWithDefaultProto,
1056 "global-bound-function-shape");
1057 TraceNullableEdge(trc, &regExpShapeWithDefaultProto, "global-regexp-shape");
1058
1059 regExpRealm.trace(trc);
1060
1061 TraceNullableEdge(trc, &mappedArgumentsTemplate, "mapped-arguments-template");
1062 TraceNullableEdge(trc, &unmappedArgumentsTemplate,
1063 "unmapped-arguments-template");
1064
1065 TraceNullableEdge(trc, &mapObjectTemplate, "map-object-template");
1066 TraceNullableEdge(trc, &setObjectTemplate, "set-object-template");
1067
1068 TraceNullableEdge(trc, &iterResultTemplate, "iter-result-template_");
1069 TraceNullableEdge(trc, &iterResultWithoutPrototypeTemplate,
1070 "iter-result-without-prototype-template");
1071
1072 TraceNullableEdge(trc, &selfHostingScriptSource,
1073 "self-hosting-script-source");
1074
1075 if (finalizationRegistryData) {
1076 finalizationRegistryData->trace(trc);
1077 }
1078 }
1079
1080 void GlobalObjectData::addSizeOfIncludingThis(
1081 mozilla::MallocSizeOf mallocSizeOf, JS::ClassInfo* info) const {
1082 info->objectsMallocHeapGlobalData += mallocSizeOf(this);
1083
1084 if (regExpRealm.regExpStatics) {
1085 info->objectsMallocHeapGlobalData +=
1086 regExpRealm.regExpStatics->sizeOfIncludingThis(mallocSizeOf);
1087 }
1088 }