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.

Implementation

Mercurial (d38398e5144e)

VCS Links

AssertCompartmentUnchanged

AutoAtomsCompartment

AutoCompartment

AutoCompartmentUnchecked

AutoSetNewObjectMetadata

AutoSuppressAllocationMetadataBuilder

AutoWrapperRooter

AutoWrapperVector

CrossCompartmentKey

DebuggerMatcher

DebuggerObjectKind

DelayMetadata

DeprecatedLanguageExtension

DtoaCache

Entry

ErrorCopier

GCPolicy

GetCompartmentFunctor

HashFunctor

Hasher

ImmediateMetadata

IsTenuredFunctor

JSCompartment

NewProxyCache

WrappedMatcher

WrapperEnum

WrapperValue

Macros

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 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * vim: set ts=8 sts=4 et sw=4 tw=99:
 * 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/. */

#ifndef jscompartment_h
#define jscompartment_h

#include "mozilla/LinkedList.h"
#include "mozilla/Maybe.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/Tuple.h"
#include "mozilla/Variant.h"
#include "mozilla/XorShift128PlusRNG.h"

#include "builtin/RegExp.h"
#include "gc/Barrier.h"
#include "gc/NurseryAwareHashMap.h"
#include "gc/Zone.h"
#include "vm/GlobalObject.h"
#include "vm/PIC.h"
#include "vm/SavedStacks.h"
#include "vm/Time.h"
#include "wasm/WasmCompartment.h"

namespace js {

namespace jit {
class JitCompartment;
} // namespace jit

namespace gc {
template <typename Node, typename Derived> class ComponentFinder;
} // namespace gc

class LexicalEnvironmentObject;
class ScriptSourceObject;
struct NativeIterator;

/*
 * A single-entry cache for some base-10 double-to-string conversions. This
 * helps date-format-xparb.js.  It also avoids skewing the results for
 * v8-splay.js when measured by the SunSpider harness, where the splay tree
 * initialization (which includes many repeated double-to-string conversions)
 * is erroneously included in the measurement; see bug 562553.
 */
class DtoaCache {
    double       d;
    int          base;
    JSFlatString* s;      // if s==nullptr, d and base are not valid

  public:
    DtoaCache() : s(nullptr) {}
    void purge() { s = nullptr; }

    JSFlatString* lookup(int base, double d) {
        return this->s && base == this->base && d == this->d ? this->s : nullptr;
    }

    void cache(int base, double d, JSFlatString* s) {
        this->base = base;
        this->d = d;
        this->s = s;
    }

#ifdef JSGC_HASH_TABLE_CHECKS
    void checkCacheAfterMovingGC() { MOZ_ASSERT(!s || !IsForwarded(s)); }
#endif
};

// Cache to speed up the group/shape lookup in ProxyObject::create. A proxy's
// group/shape is only determined by the Class + proto, so a small cache for
// this is very effective in practice.
class NewProxyCache
{
    struct Entry {
        ObjectGroup* group;
        Shape* shape;
    };
    static const size_t NumEntries = 4;
    mozilla::UniquePtr<Entry[], JS::FreePolicy> entries_;

  public:
    MOZ_ALWAYS_INLINE bool lookup(const Class* clasp, TaggedProto proto,
                                  ObjectGroup** group, Shape** shape) const
    {
        if (!entries_)
            return false;
        for (size_t i = 0; i < NumEntries; i++) {
            const Entry& entry = entries_[i];
            if (entry.group && entry.group->clasp() == clasp && entry.group->proto() == proto) {
                *group = entry.group;
                *shape = entry.shape;
                return true;
            }
        }
        return false;
    }
    void add(ObjectGroup* group, Shape* shape) {
        MOZ_ASSERT(group && shape);
        if (!entries_) {
            entries_.reset(js_pod_calloc<Entry>(NumEntries));
            if (!entries_)
                return;
        } else {
            for (size_t i = NumEntries - 1; i > 0; i--)
                entries_[i] = entries_[i - 1];
        }
        entries_[0].group = group;
        entries_[0].shape = shape;
    }
    void purge() {
        entries_.reset();
    }
};

class CrossCompartmentKey
{
  public:
    enum DebuggerObjectKind : uint8_t { DebuggerSource, DebuggerEnvironment, DebuggerObject,
                                        DebuggerWasmScript, DebuggerWasmSource };
    using DebuggerAndObject = mozilla::Tuple<NativeObject*, JSObject*, DebuggerObjectKind>;
    using DebuggerAndScript = mozilla::Tuple<NativeObject*, JSScript*>;
    using WrappedType = mozilla::Variant<
        JSObject*,
        JSString*,
        DebuggerAndScript,
        DebuggerAndObject>;

    explicit CrossCompartmentKey(JSObject* obj) : wrapped(obj) { MOZ_RELEASE_ASSERT(obj); }
    explicit CrossCompartmentKey(JSString* str) : wrapped(str) { MOZ_RELEASE_ASSERT(str); }
    explicit CrossCompartmentKey(const JS::Value& v)
      : wrapped(v.isString() ? WrappedType(v.toString()) : WrappedType(&v.toObject()))
    {}
    explicit CrossCompartmentKey(NativeObject* debugger, JSObject* obj, DebuggerObjectKind kind)
      : wrapped(DebuggerAndObject(debugger, obj, kind))
    {
        MOZ_RELEASE_ASSERT(debugger);
        MOZ_RELEASE_ASSERT(obj);
    }
    explicit CrossCompartmentKey(NativeObject* debugger, JSScript* script)
      : wrapped(DebuggerAndScript(debugger, script))
    {
        MOZ_RELEASE_ASSERT(debugger);
        MOZ_RELEASE_ASSERT(script);
    }

    bool operator==(const CrossCompartmentKey& other) const { return wrapped == other.wrapped; }
    bool operator!=(const CrossCompartmentKey& other) const { return wrapped != other.wrapped; }

    template <typename T> bool is() const { return wrapped.is<T>(); }
    template <typename T> const T& as() const { return wrapped.as<T>(); }

    template <typename F>
    auto applyToWrapped(F f) -> decltype(f(static_cast<JSObject**>(nullptr))) {
        using ReturnType = decltype(f(static_cast<JSObject**>(nullptr)));
        struct WrappedMatcher {
            F f_;
            explicit WrappedMatcher(F f) : f_(f) {}
            ReturnType match(JSObject*& obj) { return f_(&obj); }
            ReturnType match(JSString*& str) { return f_(&str); }
            ReturnType match(DebuggerAndScript& tpl) { return f_(&mozilla::Get<1>(tpl)); }
            ReturnType match(DebuggerAndObject& tpl) { return f_(&mozilla::Get<1>(tpl)); }
        } matcher(f);
        return wrapped.match(matcher);
    }

    template <typename F>
    auto applyToDebugger(F f) -> decltype(f(static_cast<NativeObject**>(nullptr))) {
        using ReturnType = decltype(f(static_cast<NativeObject**>(nullptr)));
        struct DebuggerMatcher {
            F f_;
            explicit DebuggerMatcher(F f) : f_(f) {}
            ReturnType match(JSObject*& obj) { return ReturnType(); }
            ReturnType match(JSString*& str) { return ReturnType(); }
            ReturnType match(DebuggerAndScript& tpl) { return f_(&mozilla::Get<0>(tpl)); }
            ReturnType match(DebuggerAndObject& tpl) { return f_(&mozilla::Get<0>(tpl)); }
        } matcher(f);
        return wrapped.match(matcher);
    }

    // Valid for JSObject* and Debugger keys. Crashes immediately if used on a
    // JSString* key.
    JSCompartment* compartment() {
        struct GetCompartmentFunctor {
            JSCompartment* operator()(JSObject** tp) const { return (*tp)->compartment(); }
            JSCompartment* operator()(JSScript** tp) const { return (*tp)->compartment(); }
            JSCompartment* operator()(JSString** tp) const {
                MOZ_CRASH("invalid ccw key"); return nullptr;
            }
        };
        return applyToWrapped(GetCompartmentFunctor());
    }

    struct Hasher : public DefaultHasher<CrossCompartmentKey>
    {
        struct HashFunctor {
            HashNumber match(JSObject* obj) { return DefaultHasher<JSObject*>::hash(obj); }
            HashNumber match(JSString* str) { return DefaultHasher<JSString*>::hash(str); }
            HashNumber match(const DebuggerAndScript& tpl) {
                return DefaultHasher<NativeObject*>::hash(mozilla::Get<0>(tpl)) ^
                       DefaultHasher<JSScript*>::hash(mozilla::Get<1>(tpl));
            }
            HashNumber match(const DebuggerAndObject& tpl) {
                return DefaultHasher<NativeObject*>::hash(mozilla::Get<0>(tpl)) ^
                       DefaultHasher<JSObject*>::hash(mozilla::Get<1>(tpl)) ^
                       (mozilla::Get<2>(tpl) << 5);
            }
        };
        static HashNumber hash(const CrossCompartmentKey& key) {
            return key.wrapped.match(HashFunctor());
        }

        static bool match(const CrossCompartmentKey& l, const CrossCompartmentKey& k) {
            return l.wrapped == k.wrapped;
        }
    };

    bool isTenured() const {
        struct IsTenuredFunctor {
            using ReturnType = bool;
            ReturnType operator()(JSObject** tp) { return !IsInsideNursery(*tp); }
            ReturnType operator()(JSScript** tp) { return true; }
            ReturnType operator()(JSString** tp) { return true; }
        };
        return const_cast<CrossCompartmentKey*>(this)->applyToWrapped(IsTenuredFunctor());
    }

    void trace(JSTracer* trc);
    bool needsSweep();

  private:
    CrossCompartmentKey() = delete;
    WrappedType wrapped;
};


using WrapperMap = NurseryAwareHashMap<CrossCompartmentKey, JS::Value,
                                       CrossCompartmentKey::Hasher, SystemAllocPolicy>;

// We must ensure that all newly allocated JSObjects get their metadata
// set. However, metadata builders may require the new object be in a sane
// state (eg, have its reserved slots initialized so they can get the
// sizeOfExcludingThis of the object). Therefore, for objects of certain
// JSClasses (those marked with JSCLASS_DELAY_METADATA_BUILDER), it is not safe
// for the allocation paths to call the object metadata builder
// immediately. Instead, the JSClass-specific "constructor" C++ function up the
// stack makes a promise that it will ensure that the new object has its
// metadata set after the object is initialized.
//
// To help those constructor functions keep their promise of setting metadata,
// each compartment is in one of three states at any given time:
//
// * ImmediateMetadata: Allocators should set new object metadata immediately,
//                      as usual.
//
// * DelayMetadata: Allocators should *not* set new object metadata, it will be
//                  handled after reserved slots are initialized by custom code
//                  for the object's JSClass. The newly allocated object's
//                  JSClass *must* have the JSCLASS_DELAY_METADATA_BUILDER flag
//                  set.
//
// * PendingMetadata: This object has been allocated and is still pending its
//                    metadata. This should never be the case when we begin an
//                    allocation, as a constructor function was supposed to have
//                    set the metadata of the previous object *before*
//                    allocating another object.
//
// The js::AutoSetNewObjectMetadata RAII class provides an ergonomic way for
// constructor functions to navigate state transitions, and its instances
// collectively maintain a stack of previous states. The stack is required to
// support the lazy resolution and allocation of global builtin constructors and
// prototype objects. The initial (and intuitively most common) state is
// ImmediateMetadata.
//
// Without the presence of internal errors (such as OOM), transitions between
// the states are as follows:
//
//     ImmediateMetadata                 .----- previous state on stack
//           |                           |          ^
//           | via constructor           |          |
//           |                           |          | via setting the new
//           |        via constructor    |          | object's metadata
//           |   .-----------------------'          |
//           |   |                                  |
//           V   V                                  |
//     DelayMetadata -------------------------> PendingMetadata
//                         via allocation
//
// In the presence of internal errors, we do not set the new object's metadata
// (if it was even allocated) and reset to the previous state on the stack.

struct ImmediateMetadata { };
struct DelayMetadata { };
using PendingMetadata = JSObject*;

using NewObjectMetadataState = mozilla::Variant<ImmediateMetadata,
                                                DelayMetadata,
                                                PendingMetadata>;

class MOZ_RAII AutoSetNewObjectMetadata : private JS::CustomAutoRooter
{
    MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER;

    JSContext* cx_;
    NewObjectMetadataState prevState_;

    AutoSetNewObjectMetadata(const AutoSetNewObjectMetadata& aOther) = delete;
    void operator=(const AutoSetNewObjectMetadata& aOther) = delete;

  protected:
    virtual void trace(JSTracer* trc) override {
        if (prevState_.is<PendingMetadata>()) {
            TraceRoot(trc,
                      &prevState_.as<PendingMetadata>(),
                      "Object pending metadata");
        }
    }

  public:
    explicit AutoSetNewObjectMetadata(JSContext* cx MOZ_GUARD_OBJECT_NOTIFIER_PARAM);
    ~AutoSetNewObjectMetadata();
};

} /* namespace js */

namespace js {
class DebugEnvironments;
class ObjectWeakMap;
class WatchpointMap;
class WeakMapBase;
} // namespace js

struct JSCompartment
{
    const JS::CompartmentCreationOptions creationOptions_;
    JS::CompartmentBehaviors behaviors_;

  private:
    JS::Zone*                    zone_;
    JSRuntime*                   runtime_;

  public:
    /*
     * The principals associated with this compartment. Note that the
     * same several compartments may share the same principals and
     * that a compartment may change principals during its lifetime
     * (e.g. in case of lazy parsing).
     */
    inline JSPrincipals* principals() {
        return principals_;
    }
    inline void setPrincipals(JSPrincipals* principals) {
        if (principals_ == principals)
            return;

        // If we change principals, we need to unlink immediately this
        // compartment from its PerformanceGroup. For one thing, the
        // performance data we collect should not be improperly associated
        // with a group to which we do not belong anymore. For another thing,
        // we use `principals()` as part of the key to map compartments
        // to a `PerformanceGroup`, so if we do not unlink now, this will
        // be too late once we have updated `principals_`.
        performanceMonitoring.unlink();
        principals_ = principals;
    }
    inline bool isSystem() const {
        return isSystem_;
    }
    inline void setIsSystem(bool isSystem) {
        if (isSystem_ == isSystem)
            return;

        // If we change `isSystem*(`, we need to unlink immediately this
        // compartment from its PerformanceGroup. For one thing, the
        // performance data we collect should not be improperly associated
        // to a group to which we do not belong anymore. For another thing,
        // we use `isSystem()` as part of the key to map compartments
        // to a `PerformanceGroup`, so if we do not unlink now, this will
        // be too late once we have updated `isSystem_`.
        performanceMonitoring.unlink();
        isSystem_ = isSystem;
    }

    bool isAtomsCompartment() const {
        return isAtomsCompartment_;
    }
    void setIsAtomsCompartment() {
        isAtomsCompartment_ = true;
    }

    // Used to approximate non-content code when reporting telemetry.
    inline bool isProbablySystemOrAddonCode() const {
        if (creationOptions_.addonIdOrNull())
            return true;

        return isSystem_;
    }
  private:
    JSPrincipals*                principals_;
    bool                         isSystem_;
    bool                         isAtomsCompartment_;

  public:
    bool                         isSelfHosting;
    bool                         marked;
    bool                         warnedAboutExprClosure;
    bool                         warnedAboutForEach;
    uint32_t                     warnedAboutStringGenericsMethods;

#ifdef DEBUG
    bool                         firedOnNewGlobalObject;
#endif

    void mark() { marked = true; }

  private:
    friend struct JSRuntime;
    friend struct JSContext;
    js::ReadBarrieredGlobalObject global_;

    unsigned                     enterCompartmentDepth;

  public:
    js::PerformanceGroupHolder performanceMonitoring;

    void enter() {
        enterCompartmentDepth++;
    }
    void leave() {
        enterCompartmentDepth--;
    }
    bool hasBeenEntered() { return !!enterCompartmentDepth; }

    JS::Zone* zone() { return zone_; }
    const JS::Zone* zone() const { return zone_; }

    const JS::CompartmentCreationOptions& creationOptions() const { return creationOptions_; }
    JS::CompartmentBehaviors& behaviors() { return behaviors_; }
    const JS::CompartmentBehaviors& behaviors() const { return behaviors_; }

    JSRuntime* runtimeFromActiveCooperatingThread() const {
        MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime_));
        return runtime_;
    }

    // Note: Unrestricted access to the zone's runtime from an arbitrary
    // thread can easily lead to races. Use this method very carefully.
    JSRuntime* runtimeFromAnyThread() const {
        return runtime_;
    }

    /*
     * Nb: global_ might be nullptr, if (a) it's the atoms compartment, or
     * (b) the compartment's global has been collected.  The latter can happen
     * if e.g. a string in a compartment is rooted but no object is, and thus
     * the global isn't rooted, and thus the global can be finalized while the
     * compartment lives on.
     *
     * In contrast, JSObject::global() is infallible because marking a JSObject
     * always marks its global as well.
     * TODO: add infallible JSScript::global()
     */
    inline js::GlobalObject* maybeGlobal() const;

    /* An unbarriered getter for use while tracing. */
    inline js::GlobalObject* unsafeUnbarrieredMaybeGlobal() const;

    inline void initGlobal(js::GlobalObject& global);

  public:
    void*                        data;

  private:
    const js::AllocationMetadataBuilder *allocationMetadataBuilder;

    js::SavedStacks              savedStacks_;

    js::WrapperMap               crossCompartmentWrappers;

    using CCKeyVector = mozilla::Vector<js::CrossCompartmentKey, 0, js::SystemAllocPolicy>;
    CCKeyVector                  nurseryCCKeys;

    // The global environment record's [[VarNames]] list that contains all
    // names declared using FunctionDeclaration, GeneratorDeclaration, and
    // VariableDeclaration declarations in global code in this compartment.
    // Names are only removed from this list by a |delete IdentifierReference|
    // that successfully removes that global property.
    JS::GCHashSet<JSAtom*,
                  js::DefaultHasher<JSAtom*>,
                  js::SystemAllocPolicy> varNames_;

  public:
    /* Last time at which an animation was played for a global in this compartment. */
    int64_t                      lastAnimationTime;

    js::RegExpCompartment        regExps;

    /*
     * For generational GC, record whether a write barrier has added this
     * compartment's global to the store buffer since the last minor GC.
     *
     * This is used to avoid calling into the VM every time a nursery object is
     * written to a property of the global.
     */
    uint32_t                     globalWriteBarriered;

    // Non-zero if the storage underlying any typed object in this compartment
    // might be detached.
    int32_t                      detachedTypedObjects;

  private:
    friend class js::AutoSetNewObjectMetadata;
    js::NewObjectMetadataState objectMetadataState;

  public:
    // Recompute the probability with which this compartment should record
    // profiling data (stack traces, allocations log, etc.) about each
    // allocation. We consult the probabilities requested by the Debugger
    // instances observing us, if any.
    void chooseAllocationSamplingProbability() { savedStacks_.chooseSamplingProbability(this); }

    bool hasObjectPendingMetadata() const { return objectMetadataState.is<js::PendingMetadata>(); }

    void setObjectPendingMetadata(JSContext* cx, JSObject* obj) {
        if (!cx->helperThread()) {
            MOZ_ASSERT(objectMetadataState.is<js::DelayMetadata>());
            objectMetadataState = js::NewObjectMetadataState(js::PendingMetadata(obj));
        }
    }

  public:
    void addSizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf,
                                size_t* tiAllocationSiteTables,
                                size_t* tiArrayTypeTables,
                                size_t* tiObjectTypeTables,
                                size_t* compartmentObject,
                                size_t* compartmentTables,
                                size_t* innerViews,
                                size_t* lazyArrayBuffers,
                                size_t* objectMetadataTables,
                                size_t* crossCompartmentWrappers,
                                size_t* regexpCompartment,
                                size_t* savedStacksSet,
                                size_t* varNamesSet,
                                size_t* nonSyntacticLexicalScopes,
                                size_t* jitCompartment,
                                size_t* privateData);

    // Object group tables and other state in the compartment.
    js::ObjectGroupCompartment   objectGroups;

#ifdef JSGC_HASH_TABLE_CHECKS
    void checkWrapperMapAfterMovingGC();
    void checkScriptMapsAfterMovingGC();
#endif

    /*
     * Lazily initialized script source object to use for scripts cloned
     * from the self-hosting global.
     */
    js::ReadBarrieredScriptSourceObject selfHostingScriptSource;

    // Keep track of the metadata objects which can be associated with each JS
    // object. Both keys and values are in this compartment.
    js::ObjectWeakMap* objectMetadataTable;

    // Map from array buffers to views sharing that storage.
    JS::WeakCache<js::InnerViewTable> innerViews;

    // Inline transparent typed objects do not initially have an array buffer,
    // but can have that buffer created lazily if it is accessed later. This
    // table manages references from such typed objects to their buffers.
    js::ObjectWeakMap* lazyArrayBuffers;

    // All unboxed layouts in the compartment.
    mozilla::LinkedList<js::UnboxedLayout> unboxedLayouts;

    // WebAssembly state for the compartment.
    js::wasm::Compartment wasm;

  private:
    // All non-syntactic lexical environments in the compartment. These are kept in
    // a map because when loading scripts into a non-syntactic environment, we need
    // to use the same lexical environment to persist lexical bindings.
    js::ObjectWeakMap* nonSyntacticLexicalEnvironments_;

  public:
    /* During GC, stores the index of this compartment in rt->compartments. */
    unsigned                     gcIndex;

    /*
     * During GC, stores the head of a list of incoming pointers from gray cells.
     *
     * The objects in the list are either cross-compartment wrappers, or
     * debugger wrapper objects.  The list link is either in the second extra
     * slot for the former, or a special slot for the latter.
     */
    JSObject*                    gcIncomingGrayPointers;

  private:
    enum {
        IsDebuggee = 1 << 0,
        DebuggerObservesAllExecution = 1 << 1,
        DebuggerObservesAsmJS = 1 << 2,
        DebuggerObservesCoverage = 1 << 3,
        DebuggerNeedsDelazification = 1 << 4
    };

    unsigned debugModeBits;
    friend class AutoRestoreCompartmentDebugMode;

    static const unsigned DebuggerObservesMask = IsDebuggee |
                                                 DebuggerObservesAllExecution |
                                                 DebuggerObservesCoverage |
                                                 DebuggerObservesAsmJS;

    void updateDebuggerObservesFlag(unsigned flag);

    bool getNonWrapperObjectForCurrentCompartment(JSContext* cx, js::MutableHandleObject obj);
    bool getOrCreateWrapper(JSContext* cx, js::HandleObject existing, js::MutableHandleObject obj);

  private:
    // This pointer is controlled by the embedder. If it is non-null, and if
    // cx->enableAccessValidation is true, then we assert that *validAccessPtr
    // is true before running any code in this compartment.
    bool* validAccessPtr;

  public:
    bool isAccessValid() const { return validAccessPtr ? *validAccessPtr : true; }
    void setValidAccessPtr(bool* accessp) { validAccessPtr = accessp; }

  public:
    JSCompartment(JS::Zone* zone, const JS::CompartmentOptions& options);
    ~JSCompartment();

    MOZ_MUST_USE bool init(JSContext* maybecx);

    MOZ_MUST_USE inline bool wrap(JSContext* cx, JS::MutableHandleValue vp);

    MOZ_MUST_USE bool wrap(JSContext* cx, js::MutableHandleString strp);
    MOZ_MUST_USE bool wrap(JSContext* cx, JS::MutableHandleObject obj);
    MOZ_MUST_USE bool wrap(JSContext* cx, JS::MutableHandle<js::PropertyDescriptor> desc);
    MOZ_MUST_USE bool wrap(JSContext* cx, JS::MutableHandle<JS::GCVector<JS::Value>> vec);
    MOZ_MUST_USE bool rewrap(