DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (b6d82b1a6b02)

VCS Links

Line Code
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
/* -*- 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/. */

#include "vm/GlobalObject.h"

#include "jsdate.h"
#include "jsexn.h"
#include "jsfriendapi.h"

#include "builtin/AtomicsObject.h"
#include "builtin/BigInt.h"
#include "builtin/DataViewObject.h"
#include "builtin/Eval.h"
#include "builtin/MapObject.h"
#include "builtin/ModuleObject.h"
#include "builtin/Object.h"
#include "builtin/Promise.h"
#include "builtin/RegExp.h"
#include "builtin/SelfHostingDefines.h"
#include "builtin/Stream.h"
#include "builtin/streams/QueueingStrategies.h"  // js::{ByteLength,Count}QueueingStrategy
#include "builtin/streams/ReadableStream.h"      // js::ReadableStream
#include "builtin/streams/ReadableStreamController.h"  // js::Readable{StreamDefault,ByteStream}Controller
#include "builtin/streams/ReadableStreamReader.h"  // js::ReadableStreamDefaultReader
#include "builtin/Symbol.h"
#include "builtin/TypedObject.h"
#include "builtin/WeakMapObject.h"
#include "builtin/WeakSetObject.h"
#include "debugger/DebugAPI.h"
#include "gc/FreeOp.h"
#include "js/ProtoKey.h"
#include "vm/DateObject.h"
#include "vm/EnvironmentObject.h"
#include "vm/HelperThreads.h"
#include "vm/JSContext.h"
#include "vm/PIC.h"
#include "vm/RegExpStatics.h"
#include "vm/RegExpStaticsObject.h"

#include "gc/FreeOp-inl.h"
#include "vm/JSObject-inl.h"
#include "vm/JSScript-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/Realm-inl.h"

using namespace js;

struct ProtoTableEntry {
  const JSClass* clasp;
  ClassInitializerOp init;
};

namespace js {

extern const JSClass IntlClass;
extern const JSClass JSONClass;
extern const JSClass MathClass;
extern const JSClass WebAssemblyClass;

#define DECLARE_PROTOTYPE_CLASS_INIT(name, init, clasp) \
  extern JSObject* init(JSContext* cx, Handle<GlobalObject*> global);
JS_FOR_EACH_PROTOTYPE(DECLARE_PROTOTYPE_CLASS_INIT)
#undef DECLARE_PROTOTYPE_CLASS_INIT

}  // namespace js

JSObject* js::InitViaClassSpec(JSContext* cx, Handle<GlobalObject*> global) {
  MOZ_CRASH("InitViaClassSpec() should not be called.");
}

static const ProtoTableEntry protoTable[JSProto_LIMIT] = {
#define INIT_FUNC(name, init, clasp) {clasp, init},
#define INIT_FUNC_DUMMY(name, init, clasp) {nullptr, nullptr},
    JS_FOR_PROTOTYPES(INIT_FUNC, INIT_FUNC_DUMMY)
#undef INIT_FUNC_DUMMY
#undef INIT_FUNC
};

JS_FRIEND_API const JSClass* js::ProtoKeyToClass(JSProtoKey key) {
  MOZ_ASSERT(key < JSProto_LIMIT);
  return protoTable[key].clasp;
}

// This method is not in the header file to avoid having to include
// TypedObject.h from GlobalObject.h. It is not generally perf
// sensitive.
TypedObjectModuleObject& js::GlobalObject::getTypedObjectModule() const {
  Value v = getConstructor(JSProto_TypedObject);
  // only gets called from contexts where TypedObject must be initialized
  MOZ_ASSERT(v.isObject());
  return v.toObject().as<TypedObjectModuleObject>();
}

/* static */
bool GlobalObject::skipDeselectedConstructor(JSContext* cx, JSProtoKey key) {
  switch (key) {
    case JSProto_WebAssembly:
      return !wasm::HasSupport(cx);

    case JSProto_ReadableStream:
    case JSProto_ReadableStreamDefaultReader:
    case JSProto_ReadableStreamDefaultController:
    case JSProto_ReadableByteStreamController:
    case JSProto_ByteLengthQueuingStrategy:
    case JSProto_CountQueuingStrategy:
      return !cx->realm()->creationOptions().getStreamsEnabled();

    // Return true if the given constructor has been disabled at run-time.
    case JSProto_Atomics:
    case JSProto_SharedArrayBuffer:
      return !cx->realm()->creationOptions().getSharedMemoryAndAtomicsEnabled();
    default:
      return false;
  }
}

/* static*/
bool GlobalObject::resolveConstructor(JSContext* cx,
                                      Handle<GlobalObject*> global,
                                      JSProtoKey key, IfClassIsDisabled mode) {
  MOZ_ASSERT(key != JSProto_Null);
  MOZ_ASSERT(!global->isStandardClassResolved(key));
  MOZ_ASSERT(cx->compartment() == global->compartment());

  // |global| must be same-compartment but make sure we're in its realm: the
  // code below relies on this.
  AutoRealm ar(cx, global);

  if (global->zone()->createdForHelperThread()) {
    return resolveOffThreadConstructor(cx, global, key);
  }

  MOZ_ASSERT(!cx->isHelperThreadContext());

  // Prohibit collection of allocation metadata. Metadata builders shouldn't
  // need to observe lazily-constructed prototype objects coming into
  // existence. And assertions start to fail when the builder itself attempts
  // an allocation that re-entrantly tries to create the same prototype.
  AutoSuppressAllocationMetadataBuilder suppressMetadata(cx);

  // Constructor resolution may execute self-hosted scripts. These
  // self-hosted scripts do not call out to user code by construction. Allow
  // all scripts to execute, even in debuggee compartments that are paused.
  AutoSuppressDebuggeeNoExecuteChecks suppressNX(cx);

  // There are two different kinds of initialization hooks. One of them is
  // the class js::InitFoo hook, defined in a JSProtoKey-keyed table at the
  // top of this file. The other lives in the ClassSpec for classes that
  // define it. Classes may use one or the other, but not both.
  ClassInitializerOp init = protoTable[key].init;
  if (init == InitViaClassSpec) {
    init = nullptr;
  }

  // Some classes can be disabled at compile time, others at run time;
  // if a feature is compile-time disabled, init and clasp are both null.
  const JSClass* clasp = ProtoKeyToClass(key);
  if ((!init && !clasp) || skipDeselectedConstructor(cx, key)) {
    if (mode == IfClassIsDisabled::Throw) {
      JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                                JSMSG_CONSTRUCTOR_DISABLED,
                                clasp ? clasp->name : "constructor");
      return false;
    }
    return true;
  }

  // Some classes have no init routine, which means that they're disabled at
  // compile-time. We could try to enforce that callers never pass such keys
  // to resolveConstructor, but that would cramp the style of consumers like
  // GlobalObject::initStandardClasses that want to just carpet-bomb-call
  // resolveConstructor with every JSProtoKey. So it's easier to just handle
  // it here.
  bool haveSpec = clasp && clasp->specDefined();
  if (!init && !haveSpec) {
    return true;
  }

  // See if there's an old-style initialization hook.
  if (init) {
    MOZ_ASSERT(!haveSpec);
    return init(cx, global);
  }

  //
  // Ok, we're doing it with a class spec.
  //

  bool isObjectOrFunction = key == JSProto_Function || key == JSProto_Object;

  // We need to create the prototype first, and immediately stash it in the
  // slot. This is so the following bootstrap ordering is possible:
  // * Object.prototype
  // * Function.prototype
  // * Function
  // * Object
  //
  // We get the above when Object is resolved before Function. If Function
  // is resolved before Object, we'll end up re-entering resolveConstructor
  // for Function, which is a problem. So if Function is being resolved
  // before Object.prototype exists, we just resolve Object instead, since we
  // know that Function will also be resolved before we return.
  if (key == JSProto_Function &&
      global->getPrototype(JSProto_Object).isUndefined()) {
    return resolveConstructor(cx, global, JSProto_Object,
                              IfClassIsDisabled::DoNothing);
  }

  // We don't always have a prototype (i.e. Math and JSON). If we don't,
  // |createPrototype|, |prototypeFunctions|, and |prototypeProperties|
  // should all be null.
  RootedObject proto(cx);
  if (ClassObjectCreationOp createPrototype =
          clasp->specCreatePrototypeHook()) {
    proto = createPrototype(cx, key);
    if (!proto) {
      return false;
    }

    if (isObjectOrFunction) {
      // Make sure that creating the prototype didn't recursively resolve
      // our own constructor. We can't just assert that there's no
      // prototype; OOMs can result in incomplete resolutions in which
      // the prototype is saved but not the constructor. So use the same
      // criteria that protects entry into this function.
      MOZ_ASSERT(!global->isStandardClassResolved(key));

      global->setPrototype(key, ObjectValue(*proto));
    }
  }

  // Create the constructor.
  RootedObject ctor(cx, clasp->specCreateConstructorHook()(cx, key));
  if (!ctor) {
    return false;
  }

  RootedId id(cx, NameToId(ClassName(key, cx)));
  if (isObjectOrFunction) {
    if (clasp->specShouldDefineConstructor()) {
      RootedValue ctorValue(cx, ObjectValue(*ctor));
      if (!DefineDataProperty(cx, global, id, ctorValue, JSPROP_RESOLVING)) {
        return false;
      }
    }

    global->setConstructor(key, ObjectValue(*ctor));
  }

  // If we're operating on the self-hosting global, we don't want any
  // functions and properties on the builtins and their prototypes.
  if (!cx->runtime()->isSelfHostingGlobal(global)) {
    if (const JSFunctionSpec* funs = clasp->specPrototypeFunctions()) {
      if (!JS_DefineFunctions(cx, proto, funs)) {
        return false;
      }
    }
    if (const JSPropertySpec* props = clasp->specPrototypeProperties()) {
      if (!JS_DefineProperties(cx, proto, props)) {
        return false;
      }
    }
    if (const JSFunctionSpec* funs = clasp->specConstructorFunctions()) {
      if (!JS_DefineFunctions(cx, ctor, funs)) {
        return false;
      }
    }
    if (const JSPropertySpec* props = clasp->specConstructorProperties()) {
      if (!JS_DefineProperties(cx, ctor, props)) {
        return false;
      }
    }
  }

  // If the prototype exists, link it with the constructor.
  if (proto && !LinkConstructorAndPrototype(cx, ctor, proto)) {
    return false;
  }

  // Call the post-initialization hook, if provided.
  if (FinishClassInitOp finishInit = clasp->specFinishInitHook()) {
    if (!finishInit(cx, ctor, proto)) {
      return false;
    }
  }

  if (!isObjectOrFunction) {
    // Any operations that modifies the global object should be placed
    // after any other fallible operations.

    // Fallible operation that modifies the global object.
    if (clasp->specShouldDefineConstructor()) {
      RootedValue ctorValue(cx, ObjectValue(*ctor));
      if (!DefineDataProperty(cx, global, id, ctorValue, JSPROP_RESOLVING)) {
        return false;
      }
    }

    // Infallible operations that modify the global object.
    global->setConstructor(key, ObjectValue(*ctor));
    if (proto) {
      global->setPrototype(key, ObjectValue(*proto));
    }
  }

  return true;
}

// Resolve a "globalThis" self-referential property if necessary,
// per a stage-3 proposal. https://github.com/tc39/ecma262/pull/702
//
// We could also do this in |FinishObjectClassInit| to trim the global
// resolve hook.  Unfortunately, |ToWindowProxyIfWindow| doesn't work then:
// the browser's |nsGlobalWindow::SetNewDocument| invokes Object init
// *before* it sets the global's WindowProxy using |js::SetWindowProxy|.
//
// Refactoring global object creation code to support this approach is a
// challenge for another day.
/* static */
bool GlobalObject::maybeResolveGlobalThis(JSContext* cx,
                                          Handle<GlobalObject*> global,
                                          bool* resolved) {
  if (global->getSlot(GLOBAL_THIS_RESOLVED).isUndefined()) {
    RootedValue v(cx, ObjectValue(*ToWindowProxyIfWindow(global)));
    if (!DefineDataProperty(cx, global, cx->names().globalThis, v,
                            JSPROP_RESOLVING)) {
      return false;
    }

    *resolved = true;
    global->setSlot(GLOBAL_THIS_RESOLVED, BooleanValue(true));
  }

  return true;
}

/* static */
JSObject* GlobalObject::createObject(JSContext* cx,
                                     Handle<GlobalObject*> global,
                                     unsigned slot, ObjectInitOp init) {
  if (global->zone()->createdForHelperThread()) {
    return createOffThreadObject(cx, global, slot);
  }

  MOZ_ASSERT(!cx->isHelperThreadContext());
  if (!init(cx, global)) {
    return nullptr;
  }

  return &global->getSlot(slot).toObject();
}

const JSClass GlobalObject::OffThreadPlaceholderObject::class_ = {
    "off-thread-prototype-placeholder", JSCLASS_HAS_RESERVED_SLOTS(1)};

/* static */ GlobalObject::OffThreadPlaceholderObject*
GlobalObject::OffThreadPlaceholderObject::New(JSContext* cx, unsigned slot) {
  Rooted<OffThreadPlaceholderObject*> placeholder(cx);
  placeholder = NewObjectWithGivenTaggedProto<OffThreadPlaceholderObject>(
      cx, AsTaggedProto(nullptr));
  if (!placeholder) {
    return nullptr;
  }

  placeholder->setReservedSlot(SlotIndexSlot, Int32Value(slot));
  return placeholder;
}

inline int32_t GlobalObject::OffThreadPlaceholderObject::getSlotIndex() const {
  return getReservedSlot(SlotIndexSlot).toInt32();
}

/* static */
bool GlobalObject::resolveOffThreadConstructor(JSContext* cx,
                                               Handle<GlobalObject*> global,
                                               JSProtoKey key) {
  // Don't resolve constructors for off-thread parse globals. Instead create a
  // placeholder object for the prototype which we can use to find the real
  // prototype when the off-thread compartment is merged back into the target
  // compartment.

  MOZ_ASSERT(global->zone()->createdForHelperThread());
  MOZ_ASSERT(key == JSProto_Object || key == JSProto_Function ||
             key == JSProto_Array || key == JSProto_RegExp);

  Rooted<OffThreadPlaceholderObject*> placeholder(cx);
  placeholder = OffThreadPlaceholderObject::New(cx, prototypeSlot(key));
  if (!placeholder) {
    return false;
  }

  if (key == JSProto_Object &&
      !JSObject::setFlags(cx, placeholder, BaseShape::IMMUTABLE_PROTOTYPE)) {
    return false;
  }

  if (key == JSProto_Object || key == JSProto_Function ||
      key == JSProto_Array) {
    ObjectGroupRealm& realm = ObjectGroupRealm::getForNewObject(cx);
    if (!JSObject::setNewGroupUnknown(cx, realm, placeholder->getClass(),
                                      placeholder)) {
      return false;
    }
  }

  global->setPrototype(key, ObjectValue(*placeholder));
  global->setConstructor(key, MagicValue(JS_OFF_THREAD_CONSTRUCTOR));
  return true;
}

/* static */
JSObject* GlobalObject::createOffThreadObject(JSContext* cx,
                                              Handle<GlobalObject*> global,
                                              unsigned slot) {
  // Don't create prototype objects for off-thread parse globals. Instead
  // create a placeholder object which we can use to find the real prototype
  // when the off-thread compartment is merged back into the target
  // compartment.

  MOZ_ASSERT(global->zone()->createdForHelperThread());
  MOZ_ASSERT(slot == GENERATOR_FUNCTION_PROTO || slot == ASYNC_FUNCTION_PROTO ||
             slot == ASYNC_GENERATOR || slot == MODULE_PROTO ||
             slot == IMPORT_ENTRY_PROTO || slot == EXPORT_ENTRY_PROTO ||
             slot == REQUESTED_MODULE_PROTO);

  auto placeholder = OffThreadPlaceholderObject::New(cx, slot);
  if (!placeholder) {
    return nullptr;
  }

  global->setSlot(slot, ObjectValue(*placeholder));
  return placeholder;
}

JSObject* GlobalObject::getPrototypeForOffThreadPlaceholder(JSObject* obj) {
  auto placeholder = &obj->as<OffThreadPlaceholderObject>();
  return &getSlot(placeholder->getSlotIndex()).toObject();
}

/* static */
bool GlobalObject::initBuiltinConstructor(JSContext* cx,
                                          Handle<GlobalObject*> global,
                                          JSProtoKey key, HandleObject ctor,
                                          HandleObject proto) {
  MOZ_ASSERT(!global->empty());  // reserved slots already allocated
  MOZ_ASSERT(key != JSProto_Null);
  MOZ_ASSERT(ctor);
  MOZ_ASSERT(proto);

  RootedId id(cx, NameToId(ClassName(key, cx)));
  MOZ_ASSERT(!global->lookup(cx, id));

  RootedValue ctorValue(cx, ObjectValue(*ctor));
  if (!DefineDataProperty(cx, global, id, ctorValue, JSPROP_RESOLVING)) {
    return false;
  }

  global->setConstructor(key, ObjectValue(*ctor));
  global->setPrototype(key, ObjectValue(*proto));
  return true;
}

static bool ThrowTypeError(JSContext* cx, unsigned argc, Value* vp) {
  ThrowTypeErrorBehavior(cx);
  return false;
}

/* static */
JSObject* GlobalObject::getOrCreateThrowTypeError(
    JSContext* cx, Handle<GlobalObject*> global) {
  Value v = global->getReservedSlot(THROWTYPEERROR);
  if (v.isObject()) {
    return &v.toObject();
  }
  MOZ_ASSERT(v.isUndefined());

  // Construct the unique [[%ThrowTypeError%]] function object, used only for
  // "callee" and "caller" accessors on strict mode arguments objects.  (The
  // spec also uses this for "arguments" and "caller" on various functions,
  // but we're experimenting with implementing them using accessors on
  // |Function.prototype| right now.)

  RootedFunction throwTypeError(
      cx, NewNativeFunction(cx, ThrowTypeError, 0, nullptr));
  if (!throwTypeError || !PreventExtensions(cx, throwTypeError)) {
    return nullptr;
  }

  // The "length" property of %ThrowTypeError% is non-configurable, adjust
  // the default property attributes accordingly.
  Rooted<PropertyDescriptor> nonConfigurableDesc(cx);
  nonConfigurableDesc.setAttributes(JSPROP_PERMANENT | JSPROP_IGNORE_READONLY |
                                    JSPROP_IGNORE_ENUMERATE |
                                    JSPROP_IGNORE_VALUE);

  RootedId lengthId(cx, NameToId(cx->names().length));
  ObjectOpResult lengthResult;
  if (!NativeDefineProperty(cx, throwTypeError, lengthId, nonConfigurableDesc,
                            lengthResult)) {
    return nullptr;
  }
  MOZ_ASSERT(lengthResult);

  // The "name" property of %ThrowTypeError% is non-configurable, adjust
  // the default property attributes accordingly.
  RootedId nameId(cx, NameToId(cx->names().name));
  ObjectOpResult nameResult;
  if (!NativeDefineProperty(cx, throwTypeError, nameId, nonConfigurableDesc,
                            nameResult)) {
    return nullptr;
  }
  MOZ_ASSERT(nameResult);

  global->setReservedSlot(THROWTYPEERROR, ObjectValue(*throwTypeError));
  return throwTypeError;
}

GlobalObject* GlobalObject::createInternal(JSContext* cx,
                                           const JSClass* clasp) {
  MOZ_ASSERT(clasp->flags & JSCLASS_IS_GLOBAL);
  MOZ_ASSERT(clasp->isTrace(JS_GlobalObjectTraceHook));

  JSObject* obj = NewObjectWithGivenProto(cx, clasp, nullptr, SingletonObject);
  if (!obj) {
    return nullptr;
  }

  Rooted<GlobalObject*> global(cx, &obj->as<GlobalObject>());
  MOZ_ASSERT(global->isUnqualifiedVarObj());

  // Initialize the private slot to null if present, as GC can call class
  // hooks before the caller gets to set this to a non-garbage value.
  if (clasp->flags & JSCLASS_HAS_PRIVATE) {
    global->setPrivate(nullptr);
  }

  Rooted<LexicalEnvironmentObject*> lexical(
      cx, LexicalEnvironmentObject::createGlobal(cx, global));
  if (!lexical) {
    return nullptr;
  }

  Rooted<GlobalScope*> emptyGlobalScope(
      cx, GlobalScope::createEmpty(cx, ScopeKind::Global));
  if (!emptyGlobalScope) {
    return nullptr;
  }
  global->setReservedSlot(EMPTY_GLOBAL_SCOPE,
                          PrivateGCThingValue(emptyGlobalScope));

  cx->realm()->initGlobal(*global, *lexical);

  if (!JSObject::setQualifiedVarObj(cx, global)) {
    return nullptr;
  }
  if (!JSObject::setDelegate(cx, global)) {
    return nullptr;
  }

  return global;
}

/* static */
GlobalObject* GlobalObject::new_(JSContext* cx, const JSClass* clasp,
                                 JSPrincipals* principals,
                                 JS::OnNewGlobalHookOption hookOption,
                                 const JS::RealmOptions& options) {
  MOZ_ASSERT(!cx->isExceptionPending());
  MOZ_ASSERT_IF(cx->zone(), !cx->zone()->isAtomsZone());

  // If we are creating a new global in an existing compartment, make sure the
  // compartment has a live global at all times (by rooting it here).
  // See bug 1530364.
  Rooted<GlobalObject*> existingGlobal(cx);
  const JS::RealmCreationOptions& creationOptions = options.creationOptions();
  if (creationOptions.compartmentSpecifier() ==
      JS::CompartmentSpecifier::ExistingCompartment) {
    Compartment* comp = creationOptions.compartment();
    existingGlobal = &comp->firstGlobal();
  }

  Realm* realm = NewRealm(cx, principals, options);
  if (!realm) {
    return nullptr;
  }

  Rooted<GlobalObject*> global(cx);
  {
    AutoRealmUnchecked ar(cx, realm);
    global = GlobalObject::createInternal(cx, clasp);
    if (!global) {
      return nullptr;
    }

    if (hookOption == JS::FireOnNewGlobalHook) {
      JS_FireOnNewGlobalObject(cx, global);
    }
  }

  return global;
}

LexicalEnvironmentObject& GlobalObject::lexicalEnvironment() const {
  // The lexical environment is marked when marking the global, so we don't need
  // a read barrier here because we know the global is live.
  return *realm()->unbarrieredLexicalEnvironment();
}

GlobalScope& GlobalObject::emptyGlobalScope() const {
  const Value& v = getReservedSlot(EMPTY_GLOBAL_SCOPE);
  MOZ_ASSERT(v.isPrivateGCThing() && v.traceKind() == JS::TraceKind::Scope);
  return static_cast<Scope*>(v.toGCThing())->as<GlobalScope>();
}

/* static */
bool GlobalObject::getOrCreateEval(JSContext* cx, Handle<GlobalObject*> global,
                                   MutableHandleObject eval) {
  if (!getOrCreateObjectPrototype(cx, global)) {
    return false;
  }
  eval.set(&global->getSlot(EVAL).toObject());
  return true;
}

bool GlobalObject::valueIsEval(const Value& val) {
  Value eval = getSlot(EVAL);
  return eval.isObject() && eval == val;
}

/* static */
bool GlobalObject::initStandardClasses(JSContext* cx,
                                       Handle<GlobalObject*> global) {
  /* Define a top-level property 'undefined' with the undefined value. */
  if (!DefineDataProperty(
          cx, global, cx->names().undefined, UndefinedHandleValue,
          JSPROP_PERMANENT | JSPROP_READONLY | JSPROP_RESOLVING)) {
    return false;
  }

  // Resolve a "globalThis" self-referential property if necessary.
  bool resolved;
  if (!GlobalObject::maybeResolveGlobalThis(cx, global, &resolved)) {
    return false;
  }

  for (size_t k = 0; k < JSProto_LIMIT; ++k) {
    JSProtoKey key = static_cast<JSProtoKey>(k);
    if (key != JSProto_Null && !global->isStandardClassResolved(key)) {
      if (!resolveConstructor(cx, global, static_cast<JSProtoKey>(k),
                              IfClassIsDisabled::DoNothing)) {
        return false;
      }
    }
  }
  return true;
}

/**
 * Initializes a builtin constructor and its prototype without defining any
 * properties or functions on it.
 *
 * Used in self-hosting to install the few builtin constructors required by
 * self-hosted builtins.
 */
static bool InitBareBuiltinCtor(JSContext* cx, Handle<GlobalObject*> global,
                                JSProtoKey protoKey) {
  MOZ_ASSERT(cx->runtime()->isSelfHostingGlobal(global));
  const JSClass* clasp = ProtoKeyToClass(protoKey);
  RootedObject proto(cx);
  proto = clasp->specCreatePrototypeHook()(cx, protoKey);
  if (!proto) {
    return false;
  }

  RootedObject ctor(cx, clasp->specCreateConstructorHook()(cx, protoKey));
  if (!ctor) {
    return false;
  }

  return GlobalObject::initBuiltinConstructor(cx, global, protoKey, ctor,
                                              proto);
}

/**
 * The self-hosting global only gets a small subset of all standard classes.
 * Even those are only created as bare constructors without any properties
 * or functions.
 */
/* static */
bool GlobalObject::initSelfHostingBuiltins(JSContext* cx,
                                           Handle<GlobalObject*> global,
                                           const JSFunctionSpec* builtins) {
  // Define a top-level property 'undefined' with the undefined value.
  if (!DefineDataProperty(cx, global, cx->names().undefined,
                          UndefinedHandleValue,
                          JSPROP_PERMANENT | JSPROP_READONLY)) {
    return false;
  }

  struct SymbolAndName {
    JS::SymbolCode code;
    const char* name;
  };

  SymbolAndName wellKnownSymbols[] = {
      {JS::SymbolCode::isConcatSpreadable, "std_isConcatSpreadable"},
      {JS::SymbolCode::iterator, "std_iterator"},
      {JS::SymbolCode::match, "std_match"},
      {JS::SymbolCode::matchAll, "std_matchAll"},
      {JS::SymbolCode::replace, "std_replace"},
      {JS::SymbolCode::search, "std_search"},
      {JS::SymbolCode::species, "std_species"},
      {JS::SymbolCode::split, "std_split"},
  };

  RootedValue symVal(cx);
  for (const auto& sym : wellKnownSymbols) {
    symVal.setSymbol(cx->wellKnownSymbols().get(sym.code));
    if (!JS_DefineProperty(cx, global, sym.name, symVal,
                           JSPROP_PERMANENT | JSPROP_READONLY)) {
      return false;
    }
  }

  return InitBareBuiltinCtor(cx, global, JSProto_Array) &&
         InitBareBuiltinCtor(cx, global, JSProto_TypedArray) &&
         InitBareBuiltinCtor(cx, global, JSProto_Uint8Array) &&
         InitBareBuiltinCtor(cx, global, JSProto_Int32Array) &&
         InitBareSymbolCtor(cx, global) &&
         DefineFunctions(cx, global, builtins, AsIntrinsic);
}

/* static */
bool GlobalObject::isRuntimeCodeGenEnabled(JSContext* cx, HandleValue code,
                                           Handle<GlobalObject*> global) {
  HeapSlot& v = global->getSlotRef(RUNTIME_CODEGEN_ENABLED);
  if (v.isUndefined()) {
    /*
     * If there are callbacks, make sure that the CSP callback is installed
     * and that it permits runtime code generation.
     */
    JSCSPEvalChecker allows =
        cx->runtime()->securityCallbacks->contentSecurityPolicyAllows;
    if (allows) {
      return allows(cx, code);
    }

    // Let's cache the result only if the contentSecurityPolicyAllows callback
    // is not set. In this way, contentSecurityPolicyAllows callback is executed
    // each time, with the current HandleValue code.
    v.set(global, HeapSlot::Slot, RUNTIME_CODEGEN_ENABLED, JS::TrueValue());
  }
  return !v.isFalse();
}

/* static */
JSFunction* GlobalObject::createConstructor(JSContext* cx, Native ctor,
                                            JSAtom* nameArg, unsigned length,
                                            gc::AllocKind kind,
                                            const JSJitInfo* jitInfo) {
  RootedAtom name(cx, nameArg);
  JSFunction* fun = NewNativeConstructor(cx, ctor, length, name, kind);
  if (!fun) {
    return nullptr;
  }

  if (jitInfo) {
    fun->setJitInfo(jitInfo);
  }

  return fun;
}

static NativeObject* CreateBlankProto(JSContext* cx, const JSClass* clasp,
                                      HandleObject proto) {
  MOZ_ASSERT(clasp != &JSFunction::class_);

  RootedNativeObject blankProto(
      cx, NewNativeObjectWithGivenProto(cx, clasp, proto, SingletonObject));
  if (!blankProto || !JSObject::setDelegate(cx, blankProto)) {
    return nullptr;
  }

  return blankProto;
}

/* static */
NativeObject* GlobalObject::createBlankPrototype(JSContext* cx,
                                                 Handle<GlobalObject*> global,
                                                 const JSClass* clasp) {
  RootedObject objectProto(cx, getOrCreateObjectPrototype(cx, global));
  if (!objectProto) {
    return nullptr;
  }

  return CreateBlankProto(cx, clasp, objectProto);
}

/* static */
NativeObject* GlobalObject::createBlankPrototypeInheriting(JSContext* cx,
                                                           const JSClass* clasp,
                                                           HandleObject proto) {
  return CreateBlankProto(cx, clasp, proto);
}

bool js::LinkConstructorAndPrototype(JSContext* cx, JSObject* ctor_,
                                     JSObject* proto_, unsigned prototypeAttrs,
                                     unsigned constructorAttrs) {
  RootedObject ctor(cx, ctor_), proto(cx, proto_);

  RootedValue protoVal(cx, ObjectValue(*proto));
  RootedValue ctorVal(cx, ObjectValue(*ctor));

  return DefineDataProperty(cx, ctor, cx->names().prototype, protoVal,
                            prototypeAttrs) &&
         DefineDataProperty(cx, proto, cx->names().constructor, ctorVal,
                            constructorAttrs);
}

bool js::DefinePropertiesAndFunctions(JSContext* cx, HandleObject obj,
                                      const JSPropertySpec* ps,
                                      const JSFunctionSpec* fs) {
  if (ps && !JS_DefineProperties(cx, obj, ps)) {
    return false;
  }
  if (fs && !JS_DefineFunctions(cx, obj, fs)) {
    return false;
  }
  return true;
}

bool js::DefineToStringTag(JSContext* cx, HandleObject obj, JSAtom* tag) {
  RootedId toStringTagId(cx,
                         SYMBOL_TO_JSID(cx->wellKnownSymbols().toStringTag));
  RootedValue tagString(cx, StringValue(tag));
  return DefineDataProperty(cx, obj, toStringTagId, tagString, JSPROP_READONLY);
}

GlobalObject::DebuggerVector* GlobalObject::getDebuggers() const {
  Value debuggers = getReservedSlot(DEBUGGERS);
  if (debuggers.isUndefined()) {
    return nullptr;
  }
  return DebugAPI::getGlobalDebuggers(&debuggers.toObject());
}

/* static */ GlobalObject::DebuggerVector* GlobalObject::getOrCreateDebuggers(
    JSContext* cx, Handle<GlobalObject*> global) {
  cx->check(global);
  DebuggerVector* debuggers = global->getDebuggers();
  if (debuggers) {
    return debuggers;
  }

  JSObject* obj = DebugAPI::newGlobalDebuggersHolder(cx);
  if (!obj) {
    return nullptr;
  }

  global->setReservedSlot(DEBUGGERS, ObjectValue(*obj));
  return global->getDebuggers();
}

/* static */
NativeObject* GlobalObject::getOrCreateForOfPICObject(
    JSContext* cx, Handle<GlobalObject*> global) {
  cx->check(global);
  NativeObject* forOfPIC = global->getForOfPICObject();
  if (forOfPIC) {
    return forOfPIC;
  }

  forOfPIC = ForOfPIC::createForOfPICObject(cx, global);
  if (!forOfPIC) {
    return nullptr;
  }
  global->setReservedSlot(FOR_OF_PIC_CHAIN, ObjectValue(*forOfPIC));
  return forOfPIC;
}

bool GlobalObject::hasRegExpStatics() const {
  return !getSlot(REGEXP_STATICS).isUndefined();
}

/* static */
RegExpStatics* GlobalObject::getRegExpStatics(JSContext* cx,
                                              Handle<GlobalObject*> global) {
  MOZ_ASSERT(cx);
  RegExpStaticsObject* resObj = nullptr;
  const Value& val = global->getSlot(REGEXP_STATICS);
  if (!val.isObject()) {
    MOZ_ASSERT(val.isUndefined());
    resObj = RegExpStatics::create(cx);
    if (!resObj) {
      return nullptr;
    }

    global->initSlot(REGEXP_STATICS, ObjectValue(*resObj));
  } else {
    resObj = &val.toObject().as<RegExpStaticsObject>();
  }
  return static_cast<RegExpStatics*>(resObj->getPrivate(/* nfixed = */ 1));
}

RegExpStatics* GlobalObject::getAlreadyCreatedRegExpStatics() const {
  const Value& val = this->getSlot(REGEXP_STATICS);
  MOZ_ASSERT(val.isObject());
  return static_cast<RegExpStatics*>(
      val.toObject().as<RegExpStaticsObject>().getPrivate(/* nfixed = */ 1));
}

/* static */
NativeObject* GlobalObject::getIntrinsicsHolder(JSContext* cx,
                                                Handle<GlobalObject*> global) {
  Value slot = global->getReservedSlot(INTRINSICS);
  MOZ_ASSERT(slot.isUndefined() || slot.isObject());

  if (slot.isObject()) {
    return &slot.toObject().as<NativeObject>();
  }

  Rooted<NativeObject*> intrinsicsHolder(cx);
  bool isSelfHostingGlobal = cx->runtime()->isSelfHostingGlobal(global);
  if (isSelfHostingGlobal) {
    intrinsicsHolder = global;
  } else {
    intrinsicsHolder =
        NewObjectWithGivenProto<PlainObject>(cx, nullptr, TenuredObject);
    if (!intrinsicsHolder) {
      return nullptr;
    }
  }

  /* Define a property 'global' with the current global as its value. */
  RootedValue globalValue(cx, ObjectValue(*global));
  if (!DefineDataProperty(cx, intrinsicsHolder, cx->names().global, globalValue,
                          JSPROP_PERMANENT | JSPROP_READONLY)) {
    return nullptr;
  }

  // Install the intrinsics holder in the intrinsics.
  global->setReservedSlot(INTRINSICS, ObjectValue(*intrinsicsHolder));
  return intrinsicsHolder;
}

/* static */
bool GlobalObject::getSelfHostedFunction(JSContext* cx,
                                         Handle<GlobalObject*> global,
                                         HandlePropertyName selfHostedName,
                                         HandleAtom name, unsigned nargs,
                                         MutableHandleValue funVal) {
  bool exists = false;
  if (!GlobalObject::maybeGetIntrinsicValue(cx, global, selfHostedName, funVal,
                                            &exists)) {
    return false;
  }
  if (exists) {
    RootedFunction fun(cx, &funVal.toObject().as<JSFunction>());
    if (fun->explicitName() == name) {
      return true;
    }

    if (fun->explicitName() == selfHostedName) {
      // This function was initially cloned because it was called by
      // other self-hosted code, so the clone kept its self-hosted name,
      // instead of getting the name it's intended to have in content
      // compartments. This can happen when a lazy builtin is initialized
      // after self-hosted code for another builtin used the same
      // function. In that case, we need to change the function's name,
      // which is ok because it can't have been exposed to content
      // before.
      fun->initAtom(name);
      return true;
    }

    // The function might be installed multiple times on the same or
    // different builtins, under different property names, so its name
    // might be neither "selfHostedName" nor "name". In that case, its
    // canonical name must've been set using the `_SetCanonicalName`
    // intrinsic.
    cx->runtime()->assertSelfHostedFunctionHasCanonicalName(cx, selfHostedName);
    return true;
  }

  RootedFunction fun(cx);
  if (!cx->runtime()->createLazySelfHostedFunctionClone(
          cx, selfHostedName, name, nargs,
          /* proto = */ nullptr, SingletonObject, &fun)) {
    return false;
  }
  funVal.setObject(*fun);

  return GlobalObject::addIntrinsicValue(cx, global, selfHostedName, funVal);
}

/* static */
bool GlobalObject::addIntrinsicValue(JSContext* cx,
                                     Handle<GlobalObject*> global,
                                     HandlePropertyName name,
                                     HandleValue value) {
  RootedNativeObject holder(cx, GlobalObject::getIntrinsicsHolder(cx, global));
  if (!holder) {
    return false;
  }

  uint32_t slot = holder->slotSpan();
  RootedShape last(cx, holder->lastProperty());
  Rooted<UnownedBaseShape*> base(cx, last->base()->unowned());

  RootedId id(cx, NameToId(name));
  Rooted<StackShape> child(cx, StackShape(base, id, slot, 0));
  Shape* shape = cx->zone()->propertyTree().getChild(cx, last, child);
  if (!shape) {
    return false;
  }

  if (!holder->setLastProperty(cx, shape)) {
    return false;
  }

  holder->setSlot(shape->slot(), value);
  return true;
}

/* static */
bool GlobalObject::ensureModulePrototypesCreated(JSContext* cx,
                                                 Handle<GlobalObject*> global) {
  return getOrCreateModulePrototype(cx, global) &&
         getOrCreateImportEntryPrototype(cx, global) &&
         getOrCreateExportEntryPrototype(cx, global) &&
         getOrCreateRequestedModulePrototype(cx, global);
}