/* -*- 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/. */
using JS::AutoStableStringChars; using JS::CompileOptions; using JS::ReadOnlyCompileOptions;
// See preprocessor definition of JS_BITS_PER_WORD in jstypes.h; make sure // JS_64BIT (used internally) agrees with it #ifdef JS_64BIT
static_assert(JS_BITS_PER_WORD == 64, "values must be in sync"); #else
static_assert(JS_BITS_PER_WORD == 32, "values must be in sync"); #endif
bool JS::ObjectOpResult::reportError(JSContext* cx, HandleObject obj,
HandleId id) {
static_assert(unsigned(OkCode) == unsigned(JSMSG_NOT_AN_ERROR), "unsigned value of OkCode must not be an error code");
MOZ_ASSERT(code_ != Uninitialized);
MOZ_ASSERT(!ok());
cx->check(obj);
if (ErrorTakesArguments(code_)) {
UniqueChars propName =
IdToPrintableUTF8(cx, id, IdToPrintableBehavior::IdIsPropertyKey); if (!propName) { returnfalse;
}
if (code_ == JSMSG_SET_NON_OBJECT_RECEIVER) { // We know that the original receiver was a primitive, so unbox it.
RootedValue val(cx, ObjectValue(*obj)); if (!obj->is<ProxyObject>()) { if (!Unbox(cx, obj, &val)) { returnfalse;
}
} return ReportValueError(cx, code_, JSDVG_IGNORE_STACK, val, nullptr,
propName.get());
}
// Prevent functions from being discarded by linker, so that they are callable // when debugging. staticvoid PreventDiscardingFunctions() { if (reinterpret_cast<uintptr_t>(&PreventDiscardingFunctions) == 1) { // Never executed.
memset((void*)&js::debug::GetMarkInfo, 0, 1);
memset((void*)&js::debug::GetMarkWordAddress, 0, 1);
memset((void*)&js::debug::GetMarkMask, 0, 1);
}
}
JS_PUBLIC_API JSContext* JS_NewContext(uint32_t maxbytes,
JSRuntime* parentRuntime) {
MOZ_ASSERT(JS::detail::libraryInitState == JS::detail::InitState::Running, "must call JS_Init prior to creating any JSContexts");
// Prevent linker from discarding unused debug functions.
PreventDiscardingFunctions();
// Make sure that all parent runtimes are the topmost parent. while (parentRuntime && parentRuntime->parentRuntime) {
parentRuntime = parentRuntime->parentRuntime;
}
staticvoid ReleaseAssertObjectHasNoWrappers(JSContext* cx,
HandleObject target) { for (CompartmentsIter c(cx->runtime()); !c.done(); c.next()) { if (c->lookupWrapper(target)) {
MOZ_CRASH("wrapper found for target object");
}
}
}
/* * [SMDOC] Brain transplants. * * Not for beginners or the squeamish. * * Sometimes a web spec requires us to transplant an object from one * compartment to another, like when a DOM node is inserted into a document in * another window and thus gets "adopted". We cannot literally change the * `.compartment()` of a `JSObject`; that would break the compartment * invariants. However, as usual, we have a workaround using wrappers. * * Of all the wrapper-based workarounds we do, it's safe to say this is the * most spectacular and questionable. * * `JS_TransplantObject(cx, origobj, target)` changes `origobj` into a * simulacrum of `target`, using highly esoteric means. To JS code, the effect * is as if `origobj` magically "became" `target`, but most often what actually * happens is that `origobj` gets turned into a cross-compartment wrapper for * `target`. The old behavior and contents of `origobj` are overwritten or * discarded. * * Thus, to "transplant" an object from one compartment to another: * * 1. Let `origobj` be the object that you want to move. First, create a * clone of it, `target`, in the destination compartment. * * In our DOM adoption example, `target` will be a Node of the same type as * `origobj`, same content, but in the adopting document. We're not done * yet: the spec for DOM adoption requires that `origobj.ownerDocument` * actually change. All we've done so far is make a copy. * * 2. Call `JS_TransplantObject(cx, origobj, target)`. This typically turns * `origobj` into a wrapper for `target`, so that any JS code that has a * reference to `origobj` will observe it to have the behavior of `target` * going forward. In addition, all existing wrappers for `origobj` are * changed into wrappers for `target`, extending the illusion to those * compartments as well. * * During navigation, we use the above technique to transplant the WindowProxy * into the new Window's compartment. * * A few rules: * * - `origobj` and `target` must be two distinct objects of the same * `JSClass`. Some classes may not support transplantation; WindowProxy * objects and DOM nodes are OK. * * - `target` should be created specifically to be passed to this function. * There must be no existing cross-compartment wrappers for it; ideally * there shouldn't be any pointers to it at all, except the one passed in. * * - `target` shouldn't be used afterwards. Instead, `JS_TransplantObject` * returns a pointer to the transplanted object, which might be `target` * but might be some other object in the same compartment. Use that. * * The reason for this last rule is that JS_TransplantObject does very strange * things in some cases, like swapping `target`'s brain with that of another * object. Leaving `target` behaving like its former self is not a goal. * * We don't have a good way to recover from failure in this function, so * we intentionally crash instead.
*/
if (origobj->compartment() == destination) { // If the original object is in the same compartment as the // destination, then we know that we won't find a wrapper in the // destination's cross compartment map and that the same // object will continue to work.
AutoRealm ar(cx, origobj);
JSObject::swap(cx, origobj, target, oomUnsafe);
newIdentity = origobj;
} elseif (ObjectWrapperMap::Ptr p = destination->lookupWrapper(origobj)) { // There might already be a wrapper for the original object in // the new compartment. If there is, we use its identity and swap // in the contents of |target|.
newIdentity = p->value().get();
// When we remove origv from the wrapper map, its wrapper, newIdentity, // must immediately cease to be a cross-compartment wrapper. Nuke it.
destination->removeWrapper(p);
NukeCrossCompartmentWrapper(cx, newIdentity);
AutoRealm ar(cx, newIdentity);
JSObject::swap(cx, newIdentity, target, oomUnsafe);
} else { // Otherwise, we use |target| for the new identity object.
newIdentity = target;
}
// Now, iterate through other scopes looking for references to the old // object, and update the relevant cross-compartment wrappers. We do this // even if origobj is in the same compartment as target and thus // `newIdentity == origobj`, because this process also clears out any // cached wrapper state. if (!RemapAllWrappersForObject(cx, origobj, newIdentity)) {
oomUnsafe.crash("JS_TransplantObject");
}
// Lastly, update the original object to point to the new one. if (origobj->compartment() != destination) {
RootedObject newIdentityWrapper(cx, newIdentity);
AutoRealm ar(cx, origobj); if (!JS_WrapObject(cx, &newIdentityWrapper)) {
MOZ_RELEASE_ASSERT(cx->isThrowingOutOfMemory() ||
cx->isThrowingOverRecursed());
oomUnsafe.crash("JS_TransplantObject");
}
MOZ_ASSERT(Wrapper::wrappedObject(newIdentityWrapper) == newIdentity);
JSObject::swap(cx, origobj, newIdentityWrapper, oomUnsafe); if (origobj->compartment()->lookupWrapper(newIdentity)) {
MOZ_ASSERT(origobj->is<CrossCompartmentWrapperObject>()); if (!origobj->compartment()->putWrapper(cx, newIdentity, origobj)) {
oomUnsafe.crash("JS_TransplantObject");
}
}
}
// The new identity object might be one of several things. Return it to avoid // ambiguity.
JS::AssertCellIsNotGray(newIdentity); return newIdentity;
}
// |target| can't be a remote proxy, because we expect it to get a CCW when // wrapped across compartments.
MOZ_ASSERT(!js::IsDOMRemoteProxyObject(target));
// Don't allow a compacting GC to observe any intermediate state.
AutoDisableCompactingGC nocgc(cx);
AutoDisableProxyCheck adpc;
AutoEnterOOMUnsafeRegion oomUnsafe;
AutoCheckRecursionLimit recursion(cx); if (!recursion.checkSystem(cx)) {
oomUnsafe.crash("js::RemapRemoteWindowProxies");
}
// Use the callback to find remote proxies in all compartments that match // whatever criteria callback uses. for (CompartmentsIter c(cx->runtime()); !c.done(); c.next()) {
RootedObject remoteProxy(cx, callback->getObjectToTransplant(c)); if (!remoteProxy) { continue;
} // The object the callback returns should be a DOM remote proxy object in // the compartment c. We rely on it being a DOM remote proxy because that // means that it won't have any cross-compartment wrappers.
MOZ_ASSERT(js::IsDOMRemoteProxyObject(remoteProxy));
MOZ_ASSERT(remoteProxy->compartment() == c);
CheckTransplantObject(remoteProxy);
// Immediately turn the DOM remote proxy object into a dead proxy object // so we don't have to worry about anything weird going on with it.
js::NukeNonCCWProxy(cx, remoteProxy);
// If there was a remote proxy in |target|'s compartment, we need to use it // instead of |target|, in case it had any references, so swap it. Do this // before any other compartment so that the target object will be set up // correctly before we start wrapping it into other compartments. if (targetCompartmentProxy) {
AutoRealm ar(cx, targetCompartmentProxy);
JSObject::swap(cx, targetCompartmentProxy, target, oomUnsafe);
target.set(targetCompartmentProxy);
}
/* * Recompute all cross-compartment wrappers for an object, resetting state. * Gecko uses this to clear Xray wrappers when doing a navigation that reuses * the inner window and global object.
*/
JS_PUBLIC_API bool JS_RefreshCrossCompartmentWrappers(JSContext* cx,
HandleObject obj) { return RemapAllWrappersForObject(cx, obj, obj);
}
staticconst JSStdName* LookupStdName(const JSAtomState& names, JSAtom* name, const JSStdName* table) { for (unsigned i = 0; !table[i].isSentinel(); i++) { if (table[i].isDummy()) { continue;
}
JSAtom* atom = AtomStateOffsetToName(names, table[i].atomOffset);
MOZ_ASSERT(atom); if (name == atom) { return &table[i];
}
}
return nullptr;
}
/* * Table of standard classes, indexed by JSProtoKey. For entries where the * JSProtoKey does not correspond to a class with a meaningful constructor, we * insert a null entry into the table.
*/ #define STD_NAME_ENTRY(name, clasp) {NAME_OFFSET(name), JSProto_##name}, #define STD_DUMMY_ENTRY(name, dummy) {0, JSProto_Null}, staticconst JSStdName standard_class_names[] = {
JS_FOR_PROTOTYPES(STD_NAME_ENTRY, STD_DUMMY_ENTRY){0, JSProto_LIMIT}};
/* * Table of top-level function and constant names and the JSProtoKey of the * standard class that initializes them.
*/ staticconst JSStdName builtin_property_names[] = {
{NAME_OFFSET(eval), JSProto_Object},
/* Global properties and functions defined by the Number class. */
{NAME_OFFSET(NaN), JSProto_Number},
{NAME_OFFSET(Infinity), JSProto_Number},
{NAME_OFFSET(isNaN), JSProto_Number},
{NAME_OFFSET(isFinite), JSProto_Number},
{NAME_OFFSET(parseFloat), JSProto_Number},
{NAME_OFFSET(parseInt), JSProto_Number},
const JS::RealmCreationOptions& options = global->realm()->creationOptions();
MOZ_ASSERT(options.getSharedMemoryAndAtomicsEnabled(), "shouldn't contemplate defining SharedArrayBuffer if shared " "memory is disabled");
// On the web, it isn't presently possible to expose the global // "SharedArrayBuffer" property unless the page is cross-site-isolated. Only // define this constructor if an option on the realm indicates that it should // be defined. return !options.defineSharedArrayBufferConstructor();
}
Handle<GlobalObject*> global = obj.as<GlobalObject>();
*resolved = false;
if (!id.isAtom()) { returntrue;
}
/* Check whether we're resolving 'undefined', and define it if so. */
JSAtom* idAtom = id.toAtom(); if (idAtom == cx->names().undefined) {
*resolved = true; return js::DefineDataProperty(
cx, global, id, UndefinedHandleValue,
JSPROP_PERMANENT | JSPROP_READONLY | JSPROP_RESOLVING);
}
// Resolve a "globalThis" self-referential property if necessary. if (idAtom == cx->names().globalThis) { return GlobalObject::maybeResolveGlobalThis(cx, global, resolved);
}
// Try for class constructors/prototypes named by well-known atoms. const JSStdName* stdnm =
LookupStdName(cx->names(), idAtom, standard_class_names); if (!stdnm) { // Try less frequently used top-level functions and constants.
stdnm = LookupStdName(cx->names(), idAtom, builtin_property_names); if (!stdnm) { returntrue;
}
}
// If this class is anonymous (or it's "SharedArrayBuffer" but that global // constructor isn't supposed to be defined), then it doesn't exist as a // global property, so we won't resolve anything. const JSClass* clasp = ProtoKeyToClass(key); if (clasp && !clasp->specShouldDefineConstructor()) { returntrue;
} if (SkipSharedArrayBufferConstructor(key, global)) { returntrue;
}
// The global object's resolve hook is special: JS_ResolveStandardClass // initializes the prototype chain lazily. Only attempt to optimize here // if we know the prototype chain has been initialized. if (!maybeObj || !maybeObj->staticPrototype()) { returntrue;
}
if (!id.isAtom()) { returnfalse;
}
JSAtom* atom = id.toAtom();
// This will return true even for deselected constructors. (To do // better, we need a JSContext here; it's fine as it is.)
return atom == names.undefined || atom == names.globalThis ||
LookupStdName(names, atom, standard_class_names) ||
LookupStdName(names, atom, builtin_property_names);
}
staticbool EnumerateStandardClassesInTable(JSContext* cx,
Handle<GlobalObject*> global,
MutableHandleIdVector properties, const JSStdName* table, bool includeResolved) { for (unsigned i = 0; !table[i].isSentinel(); i++) { if (table[i].isDummy()) { continue;
}
JSProtoKey key = table[i].key;
// If the standard class has been resolved, the properties have been // defined on the global so we don't need to add them here. if (!includeResolved && global->isStandardClassResolved(key)) { continue;
}
if (GlobalObject::skipDeselectedConstructor(cx, key)) { continue;
}
if (const JSClass* clasp = ProtoKeyToClass(key)) { if (!clasp->specShouldDefineConstructor() ||
SkipSharedArrayBufferConstructor(key, global)) { continue;
}
}
jsid id = NameToId(AtomStateOffsetToName(cx->names(), table[i].atomOffset));
if (SkipUneval(id, cx)) { continue;
}
if (!properties.append(id)) { returnfalse;
}
}
returntrue;
}
staticbool EnumerateStandardClasses(JSContext* cx, JS::HandleObject obj,
JS::MutableHandleIdVector properties, bool enumerableOnly, bool includeResolved) { if (enumerableOnly) { // There are no enumerable standard classes and "undefined" is // not enumerable. returntrue;
}
Handle<GlobalObject*> global = obj.as<GlobalObject>();
// It's fine to always append |undefined| here, it's non-configurable and // the enumeration code filters duplicates. if (!properties.append(NameToId(cx->names().undefined))) { returnfalse;
}
bool resolved = false; if (!GlobalObject::maybeResolveGlobalThis(cx, global, &resolved)) { returnfalse;
} if (resolved || includeResolved) { if (!properties.append(NameToId(cx->names().globalThis))) { returnfalse;
}
}
if (!EnumerateStandardClassesInTable(cx, global, properties,
standard_class_names, includeResolved)) { returnfalse;
} if (!EnumerateStandardClassesInTable(
cx, global, properties, builtin_property_names, includeResolved)) { returnfalse;
}
// Bound functions don't have their own prototype object: they reuse the // prototype of the target object. This is typically Function.prototype so we // use that here. if (key == JSProto_BoundFunction) {
key = JSProto_Function;
}
JSObject* proto = GlobalObject::getOrCreatePrototype(cx, key); if (!proto) { returnfalse;
}
objp.set(proto); returntrue;
}
JS_PUBLIC_API void JS_SetGCParameter(JSContext* cx, JSGCParamKey key,
uint32_t value) { // Bug 1742118: JS_SetGCParameter has no way to return an error // The GC ignores invalid values internally but this is not reported to the // caller.
(void)cx->runtime()->gc.setParameter(cx, key, value);
}
JS::SmallestEncoding encoding = JS::FindSmallestEncoding(utf8); if (encoding == JS::SmallestEncoding::ASCII) { // ASCII case can use the external buffer as Latin1 buffer. return NewMaybeExternalString(
cx, reinterpret_cast<JS::Latin1Char*>(utf8.begin().get()),
utf8.length(), callbacks, allocatedExternal);
}
// Non-ASCII case cannot use the external buffer.
*allocatedExternal = false; return NewStringCopyUTF8N(cx, utf8, encoding);
}
// If we GC when creating the global, we may not have set that global's // realm's global pointer yet. In this case, the realm will not yet contain // anything that needs to be traced. if (globalRealm->unsafeUnbarrieredMaybeGlobal() != globalObj) { return;
}
// Trace the realm for any GC things that should only stick around if we // know the global is live.
globalRealm->traceGlobalData(trc);
globalObj->traceData(trc, globalObj);
if (JSTraceOp trace = globalRealm->creationOptions().getTrace()) {
trace(trc, global);
}
}
JS_PUBLIC_API void JS_FireOnNewGlobalObject(JSContext* cx,
JS::HandleObject global) { // This hook is infallible, because we don't really want arbitrary script // to be able to throw errors during delicate global creation routines. // This infallibility will eat OOM and slow script, but if that happens // we'll likely run up into them again soon in a fallible context.
cx->check(global);
Rooted<js::GlobalObject*> globalObject(cx, &global->as<GlobalObject>()); #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED if (JS::GetReduceMicrosecondTimePrecisionCallback()) {
MOZ_DIAGNOSTIC_ASSERT(globalObject->realm()
->behaviors()
.reduceTimerPrecisionCallerType()
.isSome(), "Trying to create a global without setting an " "explicit RTPCallerType!");
} #endif
DebugAPI::onNewGlobalObject(cx, globalObject);
cx->runtime()->ensureRealmIsRecordingAllocations(globalObject);
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung ist noch experimentell.