blob: d406451a62069770d714c2aedb3af435a4c904ce [file] [log] [blame]
/* -*- 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/. */
/*
* JS script operations.
*/
#include "jsscriptinlines.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/PodOperations.h"
#include "mozilla/Vector.h"
#include <algorithm>
#include <string.h>
#include "jsapi.h"
#include "jsatom.h"
#include "jscntxt.h"
#include "jsfun.h"
#include "jsgc.h"
#include "jsobj.h"
#include "jsopcode.h"
#include "jsprf.h"
#include "jstypes.h"
#include "jsutil.h"
#include "jswrapper.h"
#include "frontend/BytecodeCompiler.h"
#include "frontend/BytecodeEmitter.h"
#include "frontend/SharedContext.h"
#include "gc/Marking.h"
#include "jit/BaselineJIT.h"
#include "jit/Ion.h"
#include "jit/IonCode.h"
#include "js/MemoryMetrics.h"
#include "js/Utility.h"
#include "vm/ArgumentsObject.h"
#include "vm/Compression.h"
#include "vm/Debugger.h"
#include "vm/Opcodes.h"
#include "vm/SelfHosting.h"
#include "vm/Shape.h"
#include "vm/Xdr.h"
#include "jsfuninlines.h"
#include "jsobjinlines.h"
#include "vm/ScopeObject-inl.h"
#include "vm/Stack-inl.h"
using namespace js;
using namespace js::gc;
using namespace js::frontend;
using mozilla::PodCopy;
using mozilla::PodZero;
using mozilla::RotateLeft;
static BindingIter
GetBinding(HandleScript script, HandlePropertyName name)
{
BindingIter bi(script);
while (bi->name() != name)
bi++;
return bi;
}
/* static */ BindingIter
Bindings::argumentsBinding(ExclusiveContext* cx, HandleScript script)
{
return GetBinding(script, cx->names().arguments);
}
/* static */ BindingIter
Bindings::thisBinding(ExclusiveContext* cx, HandleScript script)
{
return GetBinding(script, cx->names().dotThis);
}
bool
Bindings::initWithTemporaryStorage(ExclusiveContext* cx, MutableHandle<Bindings> self,
uint32_t numArgs, uint32_t numVars,
uint32_t numBodyLevelLexicals, uint32_t numBlockScoped,
uint32_t numUnaliasedVars, uint32_t numUnaliasedBodyLevelLexicals,
const Binding* bindingArray, bool isModule /* = false */)
{
MOZ_ASSERT(!self.callObjShape());
MOZ_ASSERT(self.bindingArrayUsingTemporaryStorage());
MOZ_ASSERT(!self.bindingArray());
MOZ_ASSERT(!(uintptr_t(bindingArray) & TEMPORARY_STORAGE_BIT));
MOZ_ASSERT(numArgs <= ARGC_LIMIT);
MOZ_ASSERT(numVars <= LOCALNO_LIMIT);
MOZ_ASSERT(numBlockScoped <= LOCALNO_LIMIT);
MOZ_ASSERT(numBodyLevelLexicals <= LOCALNO_LIMIT);
mozilla::DebugOnly<uint64_t> totalSlots = uint64_t(numVars) +
uint64_t(numBodyLevelLexicals) +
uint64_t(numBlockScoped);
MOZ_ASSERT(totalSlots <= LOCALNO_LIMIT);
MOZ_ASSERT(UINT32_MAX - numArgs >= totalSlots);
MOZ_ASSERT(numUnaliasedVars <= numVars);
MOZ_ASSERT(numUnaliasedBodyLevelLexicals <= numBodyLevelLexicals);
self.setBindingArray(bindingArray, TEMPORARY_STORAGE_BIT);
self.setNumArgs(numArgs);
self.setNumVars(numVars);
self.setNumBodyLevelLexicals(numBodyLevelLexicals);
self.setNumBlockScoped(numBlockScoped);
self.setNumUnaliasedVars(numUnaliasedVars);
self.setNumUnaliasedBodyLevelLexicals(numUnaliasedBodyLevelLexicals);
// Get the initial shape to use when creating CallObjects for this script.
// After creation, a CallObject's shape may change completely (via direct eval() or
// other operations that mutate the lexical scope). However, since the
// lexical bindings added to the initial shape are permanent and the
// allocKind/nfixed of a CallObject cannot change, one may assume that the
// slot location (whether in the fixed or dynamic slots) of a variable is
// the same as in the initial shape. (This is assumed by the interpreter and
// JITs when interpreting/compiling aliasedvar ops.)
// Since unaliased variables are, by definition, only accessed by local
// operations and never through the scope chain, only give shapes to
// aliased variables. While the debugger may observe any scope object at
// any time, such accesses are mediated by DebugScopeProxy (see
// DebugScopeProxy::handleUnaliasedAccess).
uint32_t nslots = CallObject::RESERVED_SLOTS;
// Unless there are aliased body-level lexical bindings at all, set the
// begin index to an impossible slot number.
uint32_t aliasedBodyLevelLexicalBegin = LOCALNO_LIMIT;
for (BindingIter bi(self); bi; bi++) {
if (bi->aliased()) {
// Per ES6, lexical bindings cannot be accessed until
// initialized. Remember the first aliased slot that is a
// body-level lexical, so that they may be initialized to sentinel
// magic values.
if (numBodyLevelLexicals > 0 &&
nslots < aliasedBodyLevelLexicalBegin &&
bi.isBodyLevelLexical() &&
bi.localIndex() >= numVars)
{
aliasedBodyLevelLexicalBegin = nslots;
}
nslots++;
}
}
self.setAliasedBodyLevelLexicalBegin(aliasedBodyLevelLexicalBegin);
// Put as many of nslots inline into the object header as possible.
uint32_t nfixed = gc::GetGCKindSlots(gc::GetGCObjectKind(nslots));
// Start with the empty shape and then append one shape per aliased binding.
const Class* cls = isModule ? &ModuleEnvironmentObject::class_ : &CallObject::class_;
uint32_t baseShapeFlags = BaseShape::QUALIFIED_VAROBJ | BaseShape::DELEGATE;
if (isModule)
baseShapeFlags |= BaseShape::NOT_EXTENSIBLE; // Module code is always strict.
RootedShape shape(cx,
EmptyShape::getInitialShape(cx, cls, TaggedProto(nullptr), nfixed, baseShapeFlags));
if (!shape)
return false;
#ifdef DEBUG
HashSet<PropertyName*> added(cx);
if (!added.init()) {
ReportOutOfMemory(cx);
return false;
}
#endif
uint32_t slot = CallObject::RESERVED_SLOTS;
for (BindingIter bi(self); bi; bi++) {
MOZ_ASSERT_IF(isModule, bi->aliased());
if (!bi->aliased())
continue;
#ifdef DEBUG
// The caller ensures no duplicate aliased names.
MOZ_ASSERT(!added.has(bi->name()));
if (!added.put(bi->name())) {
ReportOutOfMemory(cx);
return false;
}
#endif
StackBaseShape stackBase(cx, cls, baseShapeFlags);
UnownedBaseShape* base = BaseShape::getUnowned(cx, stackBase);
if (!base)
return false;
unsigned attrs = JSPROP_PERMANENT |
JSPROP_ENUMERATE |
(bi->kind() == Binding::CONSTANT ? JSPROP_READONLY : 0);
Rooted<StackShape> child(cx, StackShape(base, NameToId(bi->name()), slot, attrs, 0));
shape = cx->compartment()->propertyTree.getChild(cx, shape, child);
if (!shape)
return false;
MOZ_ASSERT(slot < nslots);
slot++;
}
MOZ_ASSERT(slot == nslots);
MOZ_ASSERT(!shape->inDictionary());
self.setCallObjShape(shape);
return true;
}
bool
Bindings::initTrivial(ExclusiveContext* cx)
{
Shape* shape = EmptyShape::getInitialShape(cx, &CallObject::class_, TaggedProto(nullptr),
CallObject::RESERVED_SLOTS,
BaseShape::QUALIFIED_VAROBJ | BaseShape::DELEGATE);
if (!shape)
return false;
callObjShape_.init(shape);
return true;
}
uint8_t*
Bindings::switchToScriptStorage(Binding* newBindingArray)
{
MOZ_ASSERT(bindingArrayUsingTemporaryStorage());
MOZ_ASSERT(!(uintptr_t(newBindingArray) & TEMPORARY_STORAGE_BIT));
if (count() > 0)
PodCopy(newBindingArray, bindingArray(), count());
bindingArrayAndFlag_ = uintptr_t(newBindingArray);
return reinterpret_cast<uint8_t*>(newBindingArray + count());
}
/* static */ bool
Bindings::clone(JSContext* cx, MutableHandle<Bindings> self,
uint8_t* dstScriptData, HandleScript srcScript)
{
/* The clone has the same bindingArray_ offset as 'src'. */
Handle<Bindings> src = Handle<Bindings>::fromMarkedLocation(&srcScript->bindings);
ptrdiff_t off = (uint8_t*)src.bindingArray() - srcScript->data;
MOZ_ASSERT(off >= 0);
MOZ_ASSERT(size_t(off) <= srcScript->dataSize());
Binding* dstPackedBindings = (Binding*)(dstScriptData + off);
/*
* Since atoms are shareable throughout the runtime, we can simply copy
* the source's bindingArray directly.
*/
if (!initWithTemporaryStorage(cx, self, src.numArgs(), src.numVars(),
src.numBodyLevelLexicals(),
src.numBlockScoped(),
src.numUnaliasedVars(),
src.numUnaliasedBodyLevelLexicals(),
src.bindingArray()))
{
return false;
}
self.switchToScriptStorage(dstPackedBindings);
return true;
}
template<XDRMode mode>
static bool
XDRScriptBindings(XDRState<mode>* xdr, LifoAllocScope& las, uint16_t numArgs, uint32_t numVars,
uint16_t numBodyLevelLexicals, uint16_t numBlockScoped,
uint32_t numUnaliasedVars, uint16_t numUnaliasedBodyLevelLexicals,
HandleScript script)
{
JSContext* cx = xdr->cx();
if (mode == XDR_ENCODE) {
for (BindingIter bi(script); bi; bi++) {
RootedAtom atom(cx, bi->name());
if (!XDRAtom(xdr, &atom))
return false;
}
for (BindingIter bi(script); bi; bi++) {
uint8_t u8 = (uint8_t(bi->kind()) << 1) | uint8_t(bi->aliased());
if (!xdr->codeUint8(&u8))
return false;
}
} else {
uint32_t nameCount = numArgs + numVars + numBodyLevelLexicals;
AutoValueVector atoms(cx);
if (!atoms.resize(nameCount))
return false;
for (uint32_t i = 0; i < nameCount; i++) {
RootedAtom atom(cx);
if (!XDRAtom(xdr, &atom))
return false;
atoms[i].setString(atom);
}
Binding* bindingArray = las.alloc().newArrayUninitialized<Binding>(nameCount);
if (!bindingArray)
return false;
for (uint32_t i = 0; i < nameCount; i++) {
uint8_t u8;
if (!xdr->codeUint8(&u8))
return false;
PropertyName* name = atoms[i].toString()->asAtom().asPropertyName();
Binding::Kind kind = Binding::Kind(u8 >> 1);
bool aliased = bool(u8 & 1);
bindingArray[i] = Binding(name, kind, aliased);
}
Rooted<Bindings> bindings(cx, script->bindings);
if (!Bindings::initWithTemporaryStorage(cx, &bindings, numArgs, numVars,
numBodyLevelLexicals, numBlockScoped,
numUnaliasedVars, numUnaliasedBodyLevelLexicals,
bindingArray))
{
return false;
}
script->bindings = bindings;
}
return true;
}
bool
Bindings::bindingIsAliased(uint32_t bindingIndex)
{
MOZ_ASSERT(bindingIndex < count());
return bindingArray()[bindingIndex].aliased();
}
void
Binding::trace(JSTracer* trc)
{
PropertyName* name = this->name();
TraceManuallyBarrieredEdge(trc, &name, "binding");
}
void
Bindings::trace(JSTracer* trc)
{
if (callObjShape_)
TraceEdge(trc, &callObjShape_, "callObjShape");
/*
* As the comment in Bindings explains, bindingsArray may point into freed
* storage when bindingArrayUsingTemporaryStorage so we don't mark it.
* Note: during compilation, atoms are already kept alive by gcKeepAtoms.
*/
if (bindingArrayUsingTemporaryStorage())
return;
for (Binding& b : *this)
b.trace(trc);
}
template<XDRMode mode>
bool
js::XDRScriptConst(XDRState<mode>* xdr, MutableHandleValue vp)
{
JSContext* cx = xdr->cx();
/*
* A script constant can be an arbitrary primitive value as they are used
* to implement JSOP_LOOKUPSWITCH. But they cannot be objects, see
* bug 407186.
*/
enum ConstTag {
SCRIPT_INT = 0,
SCRIPT_DOUBLE = 1,
SCRIPT_ATOM = 2,
SCRIPT_TRUE = 3,
SCRIPT_FALSE = 4,
SCRIPT_NULL = 5,
SCRIPT_OBJECT = 6,
SCRIPT_VOID = 7,
SCRIPT_HOLE = 8
};
uint32_t tag;
if (mode == XDR_ENCODE) {
if (vp.isInt32()) {
tag = SCRIPT_INT;
} else if (vp.isDouble()) {
tag = SCRIPT_DOUBLE;
} else if (vp.isString()) {
tag = SCRIPT_ATOM;
} else if (vp.isTrue()) {
tag = SCRIPT_TRUE;
} else if (vp.isFalse()) {
tag = SCRIPT_FALSE;
} else if (vp.isNull()) {
tag = SCRIPT_NULL;
} else if (vp.isObject()) {
tag = SCRIPT_OBJECT;
} else if (vp.isMagic(JS_ELEMENTS_HOLE)) {
tag = SCRIPT_HOLE;
} else {
MOZ_ASSERT(vp.isUndefined());
tag = SCRIPT_VOID;
}
}
if (!xdr->codeUint32(&tag))
return false;
switch (tag) {
case SCRIPT_INT: {
uint32_t i;
if (mode == XDR_ENCODE)
i = uint32_t(vp.toInt32());
if (!xdr->codeUint32(&i))
return false;
if (mode == XDR_DECODE)
vp.set(Int32Value(int32_t(i)));
break;
}
case SCRIPT_DOUBLE: {
double d;
if (mode == XDR_ENCODE)
d = vp.toDouble();
if (!xdr->codeDouble(&d))
return false;
if (mode == XDR_DECODE)
vp.set(DoubleValue(d));
break;
}
case SCRIPT_ATOM: {
RootedAtom atom(cx);
if (mode == XDR_ENCODE)
atom = &vp.toString()->asAtom();
if (!XDRAtom(xdr, &atom))
return false;
if (mode == XDR_DECODE)
vp.set(StringValue(atom));
break;
}
case SCRIPT_TRUE:
if (mode == XDR_DECODE)
vp.set(BooleanValue(true));
break;
case SCRIPT_FALSE:
if (mode == XDR_DECODE)
vp.set(BooleanValue(false));
break;
case SCRIPT_NULL:
if (mode == XDR_DECODE)
vp.set(NullValue());
break;
case SCRIPT_OBJECT: {
RootedObject obj(cx);
if (mode == XDR_ENCODE)
obj = &vp.toObject();
if (!XDRObjectLiteral(xdr, &obj))
return false;
if (mode == XDR_DECODE)
vp.setObject(*obj);
break;
}
case SCRIPT_VOID:
if (mode == XDR_DECODE)
vp.set(UndefinedValue());
break;
case SCRIPT_HOLE:
if (mode == XDR_DECODE)
vp.setMagic(JS_ELEMENTS_HOLE);
break;
}
return true;
}
template bool
js::XDRScriptConst(XDRState<XDR_ENCODE>*, MutableHandleValue);
template bool
js::XDRScriptConst(XDRState<XDR_DECODE>*, MutableHandleValue);
// Code LazyScript's free variables.
template<XDRMode mode>
static bool
XDRLazyFreeVariables(XDRState<mode>* xdr, MutableHandle<LazyScript*> lazy)
{
JSContext* cx = xdr->cx();
RootedAtom atom(cx);
uint8_t isHoistedUse;
LazyScript::FreeVariable* freeVariables = lazy->freeVariables();
size_t numFreeVariables = lazy->numFreeVariables();
for (size_t i = 0; i < numFreeVariables; i++) {
if (mode == XDR_ENCODE) {
atom = freeVariables[i].atom();
isHoistedUse = freeVariables[i].isHoistedUse();
}
if (!XDRAtom(xdr, &atom))
return false;
if (!xdr->codeUint8(&isHoistedUse))
return false;
if (mode == XDR_DECODE) {
freeVariables[i] = LazyScript::FreeVariable(atom);
if (isHoistedUse)
freeVariables[i].setIsHoistedUse();
}
}
return true;
}
// Code the missing part needed to re-create a LazyScript from a JSScript.
template<XDRMode mode>
static bool
XDRRelazificationInfo(XDRState<mode>* xdr, HandleFunction fun, HandleScript script,
HandleObject enclosingScope, MutableHandle<LazyScript*> lazy)
{
MOZ_ASSERT_IF(mode == XDR_ENCODE, script->isRelazifiable() && script->maybeLazyScript());
MOZ_ASSERT_IF(mode == XDR_ENCODE, !lazy->numInnerFunctions());
JSContext* cx = xdr->cx();
uint64_t packedFields;
{
uint32_t begin = script->sourceStart();
uint32_t end = script->sourceEnd();
uint32_t lineno = script->lineno();
uint32_t column = script->column();
if (mode == XDR_ENCODE) {
packedFields = lazy->packedFields();
MOZ_ASSERT(begin == lazy->begin());
MOZ_ASSERT(end == lazy->end());
MOZ_ASSERT(lineno == lazy->lineno());
MOZ_ASSERT(column == lazy->column());
// We can assert we have no inner functions because we don't
// relazify scripts with inner functions. See
// JSFunction::createScriptForLazilyInterpretedFunction.
MOZ_ASSERT(lazy->numInnerFunctions() == 0);
}
if (!xdr->codeUint64(&packedFields))
return false;
if (mode == XDR_DECODE) {
lazy.set(LazyScript::Create(cx, fun, script, enclosingScope, script,
packedFields, begin, end, lineno, column));
// As opposed to XDRLazyScript, we need to restore the runtime bits
// of the script, as we are trying to match the fact this function
// has already been parsed and that it would need to be re-lazified.
lazy->initRuntimeFields(packedFields);
}
}
// Code free variables.
if (!XDRLazyFreeVariables(xdr, lazy))
return false;
// No need to do anything with inner functions, since we asserted we don't
// have any.
return true;
}
static inline uint32_t
FindScopeObjectIndex(JSScript* script, NestedScopeObject& scope)
{
ObjectArray* objects = script->objects();
HeapPtrObject* vector = objects->vector;
unsigned length = objects->length;
for (unsigned i = 0; i < length; ++i) {
if (vector[i] == &scope)
return i;
}
MOZ_CRASH("Scope not found");
}
static bool
SaveSharedScriptData(ExclusiveContext*, Handle<JSScript*>, SharedScriptData*, uint32_t);
enum XDRClassKind {
CK_BlockObject = 0,
CK_WithObject = 1,
CK_JSFunction = 2,
CK_JSObject = 3
};
template<XDRMode mode>
bool
js::XDRScript(XDRState<mode>* xdr, HandleObject enclosingScopeArg, HandleScript enclosingScript,
HandleFunction fun, MutableHandleScript scriptp)
{
/* NB: Keep this in sync with CopyScript. */
MOZ_ASSERT(enclosingScopeArg);
enum ScriptBits {
NoScriptRval,
SavedCallerFun,
Strict,
ContainsDynamicNameAccess,
FunHasExtensibleScope,
FunNeedsDeclEnvObject,
FunHasAnyAliasedFormal,
ArgumentsHasVarBinding,
NeedsArgsObj,
HasMappedArgsObj,
FunctionHasThisBinding,
IsGeneratorExp,
IsLegacyGenerator,
IsStarGenerator,
OwnSource,
ExplicitUseStrict,
SelfHosted,
HasSingleton,
TreatAsRunOnce,
HasLazyScript,
HasNonSyntacticScope,
HasInnerFunctions,
NeedsHomeObject,
IsDerivedClassConstructor,
};
uint32_t length, lineno, column, nslots;
uint32_t natoms, nsrcnotes, i;
uint32_t nconsts, nobjects, nregexps, ntrynotes, nblockscopes, nyieldoffsets;
uint32_t prologueLength, version;
uint32_t funLength = 0;
uint32_t nTypeSets = 0;
uint32_t scriptBits = 0;
JSContext* cx = xdr->cx();
RootedScript script(cx);
RootedObject enclosingScope(cx, enclosingScopeArg);
natoms = nsrcnotes = 0;
nconsts = nobjects = nregexps = ntrynotes = nblockscopes = nyieldoffsets = 0;
/* XDR arguments and vars. */
uint16_t nargs = 0;
uint16_t nblocklocals = 0;
uint16_t nbodylevellexicals = 0;
uint32_t nvars = 0;
uint32_t nunaliasedvars = 0;
uint16_t nunaliasedbodylevellexicals = 0;
if (mode == XDR_ENCODE) {
script = scriptp.get();
MOZ_ASSERT_IF(enclosingScript, enclosingScript->compartment() == script->compartment());
MOZ_ASSERT(script->functionNonDelazifying() == fun);
if (!fun && script->treatAsRunOnce()) {
// This is a toplevel or eval script that's runOnce. We want to
// make sure that we're not XDR-saving an object we emitted for
// JSOP_OBJECT that then got modified. So throw if we're not
// cloning in JSOP_OBJECT or if we ever didn't clone in it in the
// past.
const JS::CompartmentOptions& opts = JS::CompartmentOptionsRef(cx);
if (!opts.cloneSingletons() || !opts.getSingletonsAsTemplates()) {
JS_ReportError(cx,
"Can't serialize a run-once non-function script "
"when we're not doing singleton cloning");
return false;
}
}
nargs = script->bindings.numArgs();
nblocklocals = script->bindings.numBlockScoped();
nbodylevellexicals = script->bindings.numBodyLevelLexicals();
nvars = script->bindings.numVars();
nunaliasedvars = script->bindings.numUnaliasedVars();
nunaliasedbodylevellexicals = script->bindings.numUnaliasedBodyLevelLexicals();
}
if (!xdr->codeUint16(&nargs))
return false;
if (!xdr->codeUint16(&nblocklocals))
return false;
if (!xdr->codeUint16(&nbodylevellexicals))
return false;
if (!xdr->codeUint32(&nvars))
return false;
if (!xdr->codeUint32(&nunaliasedvars))
return false;
if (!xdr->codeUint16(&nunaliasedbodylevellexicals))
return false;
if (mode == XDR_ENCODE)
length = script->length();
if (!xdr->codeUint32(&length))
return false;
if (mode == XDR_ENCODE) {
prologueLength = script->mainOffset();
MOZ_ASSERT(script->getVersion() != JSVERSION_UNKNOWN);
version = script->getVersion();
lineno = script->lineno();
column = script->column();
nslots = script->nslots();
natoms = script->natoms();
nsrcnotes = script->numNotes();
if (script->hasConsts())
nconsts = script->consts()->length;
if (script->hasObjects())
nobjects = script->objects()->length;
if (script->hasRegexps())
nregexps = script->regexps()->length;
if (script->hasTrynotes())
ntrynotes = script->trynotes()->length;
if (script->hasBlockScopes())
nblockscopes = script->blockScopes()->length;
if (script->hasYieldOffsets())
nyieldoffsets = script->yieldOffsets().length();
nTypeSets = script->nTypeSets();
funLength = script->funLength();
if (script->noScriptRval())
scriptBits |= (1 << NoScriptRval);
if (script->savedCallerFun())
scriptBits |= (1 << SavedCallerFun);
if (script->strict())
scriptBits |= (1 << Strict);
if (script->explicitUseStrict())
scriptBits |= (1 << ExplicitUseStrict);
if (script->selfHosted())
scriptBits |= (1 << SelfHosted);
if (script->bindingsAccessedDynamically())
scriptBits |= (1 << ContainsDynamicNameAccess);
if (script->funHasExtensibleScope())
scriptBits |= (1 << FunHasExtensibleScope);
if (script->funNeedsDeclEnvObject())
scriptBits |= (1 << FunNeedsDeclEnvObject);
if (script->funHasAnyAliasedFormal())
scriptBits |= (1 << FunHasAnyAliasedFormal);
if (script->argumentsHasVarBinding())
scriptBits |= (1 << ArgumentsHasVarBinding);
if (script->analyzedArgsUsage() && script->needsArgsObj())
scriptBits |= (1 << NeedsArgsObj);
if (script->hasMappedArgsObj())
scriptBits |= (1 << HasMappedArgsObj);
if (script->functionHasThisBinding())
scriptBits |= (1 << FunctionHasThisBinding);
if (!enclosingScript || enclosingScript->scriptSource() != script->scriptSource())
scriptBits |= (1 << OwnSource);
if (script->isGeneratorExp())
scriptBits |= (1 << IsGeneratorExp);
if (script->isLegacyGenerator())
scriptBits |= (1 << IsLegacyGenerator);
if (script->isStarGenerator())
scriptBits |= (1 << IsStarGenerator);
if (script->hasSingletons())
scriptBits |= (1 << HasSingleton);
if (script->treatAsRunOnce())
scriptBits |= (1 << TreatAsRunOnce);
if (script->isRelazifiable())
scriptBits |= (1 << HasLazyScript);
if (script->hasNonSyntacticScope())
scriptBits |= (1 << HasNonSyntacticScope);
if (script->hasInnerFunctions())
scriptBits |= (1 << HasInnerFunctions);
if (script->needsHomeObject())
scriptBits |= (1 << NeedsHomeObject);
if (script->isDerivedClassConstructor())
scriptBits |= (1 << IsDerivedClassConstructor);
}
if (!xdr->codeUint32(&prologueLength))
return false;
if (!xdr->codeUint32(&version))
return false;
// To fuse allocations, we need lengths of all embedded arrays early.
if (!xdr->codeUint32(&natoms))
return false;
if (!xdr->codeUint32(&nsrcnotes))
return false;
if (!xdr->codeUint32(&nconsts))
return false;
if (!xdr->codeUint32(&nobjects))
return false;
if (!xdr->codeUint32(&nregexps))
return false;
if (!xdr->codeUint32(&ntrynotes))
return false;
if (!xdr->codeUint32(&nblockscopes))
return false;
if (!xdr->codeUint32(&nyieldoffsets))
return false;
if (!xdr->codeUint32(&nTypeSets))
return false;
if (!xdr->codeUint32(&funLength))
return false;
if (!xdr->codeUint32(&scriptBits))
return false;
if (mode == XDR_DECODE) {
JSVersion version_ = JSVersion(version);
MOZ_ASSERT((version_ & VersionFlags::MASK) == unsigned(version_));
CompileOptions options(cx);
options.setVersion(version_)
.setNoScriptRval(!!(scriptBits & (1 << NoScriptRval)))
.setSelfHostingMode(!!(scriptBits & (1 << SelfHosted)));
RootedScriptSource sourceObject(cx);
if (scriptBits & (1 << OwnSource)) {
ScriptSource* ss = cx->new_<ScriptSource>();
if (!ss)
return false;
ScriptSourceHolder ssHolder(ss);
/*
* We use this CompileOptions only to initialize the
* ScriptSourceObject. Most CompileOptions fields aren't used by
* ScriptSourceObject, and those that are (element; elementAttributeName)
* aren't preserved by XDR. So this can be simple.
*/
CompileOptions options(cx);
ss->initFromOptions(cx, options);
sourceObject = ScriptSourceObject::create(cx, ss);
if (!sourceObject ||
!ScriptSourceObject::initFromOptions(cx, sourceObject, options))
return false;
} else {
MOZ_ASSERT(enclosingScript);
// When decoding, all the scripts and the script source object
// are in the same compartment, so the script's source object
// should never be a cross-compartment wrapper.
MOZ_ASSERT(enclosingScript->sourceObject()->is<ScriptSourceObject>());
sourceObject = &enclosingScript->sourceObject()->as<ScriptSourceObject>();
}
// If the outermost script has a non-syntactic scope, reflect that on
// the static scope chain.
if (scriptBits & (1 << HasNonSyntacticScope) &&
IsStaticGlobalLexicalScope(enclosingScope))
{
enclosingScope = StaticNonSyntacticScopeObjects::create(cx, enclosingScope);
if (!enclosingScope)
return false;
}
script = JSScript::Create(cx, enclosingScope, !!(scriptBits & (1 << SavedCallerFun)),
options, sourceObject, 0, 0);
if (!script)
return false;
// Set the script in its function now so that inner scripts to be
// decoded may iterate the static scope chain.
if (fun) {
fun->initScript(script);
script->setFunction(fun);
}
}
/* JSScript::partiallyInit assumes script->bindings is fully initialized. */
LifoAllocScope las(&cx->tempLifoAlloc());
if (!XDRScriptBindings(xdr, las, nargs, nvars, nbodylevellexicals, nblocklocals,
nunaliasedvars, nunaliasedbodylevellexicals, script))
return false;
if (mode == XDR_DECODE) {
if (!JSScript::partiallyInit(cx, script, nconsts, nobjects, nregexps, ntrynotes,
nblockscopes, nyieldoffsets, nTypeSets))
{
return false;
}
MOZ_ASSERT(!script->mainOffset());
script->mainOffset_ = prologueLength;
script->setLength(length);
script->funLength_ = funLength;
scriptp.set(script);
if (scriptBits & (1 << Strict))
script->strict_ = true;
if (scriptBits & (1 << ExplicitUseStrict))
script->explicitUseStrict_ = true;
if (scriptBits & (1 << ContainsDynamicNameAccess))
script->bindingsAccessedDynamically_ = true;
if (scriptBits & (1 << FunHasExtensibleScope))
script->funHasExtensibleScope_ = true;
if (scriptBits & (1 << FunNeedsDeclEnvObject))
script->funNeedsDeclEnvObject_ = true;
if (scriptBits & (1 << FunHasAnyAliasedFormal))
script->funHasAnyAliasedFormal_ = true;
if (scriptBits & (1 << ArgumentsHasVarBinding))
script->setArgumentsHasVarBinding();
if (scriptBits & (1 << NeedsArgsObj))
script->setNeedsArgsObj(true);
if (scriptBits & (1 << HasMappedArgsObj))
script->hasMappedArgsObj_ = true;
if (scriptBits & (1 << FunctionHasThisBinding))
script->functionHasThisBinding_ = true;
if (scriptBits & (1 << IsGeneratorExp))
script->isGeneratorExp_ = true;
if (scriptBits & (1 << HasSingleton))
script->hasSingletons_ = true;
if (scriptBits & (1 << TreatAsRunOnce))
script->treatAsRunOnce_ = true;
if (scriptBits & (1 << HasNonSyntacticScope))
script->hasNonSyntacticScope_ = true;
if (scriptBits & (1 << HasInnerFunctions))
script->hasInnerFunctions_ = true;
if (scriptBits & (1 << NeedsHomeObject))
script->needsHomeObject_ = true;
if (scriptBits & (1 << IsDerivedClassConstructor))
script->isDerivedClassConstructor_ = true;
if (scriptBits & (1 << IsLegacyGenerator)) {
MOZ_ASSERT(!(scriptBits & (1 << IsStarGenerator)));
script->setGeneratorKind(LegacyGenerator);
} else if (scriptBits & (1 << IsStarGenerator))
script->setGeneratorKind(StarGenerator);
}
JS_STATIC_ASSERT(sizeof(jsbytecode) == 1);
JS_STATIC_ASSERT(sizeof(jssrcnote) == 1);
if (scriptBits & (1 << OwnSource)) {
if (!script->scriptSource()->performXDR<mode>(xdr))
return false;
}
if (!xdr->codeUint32(&script->sourceStart_))
return false;
if (!xdr->codeUint32(&script->sourceEnd_))
return false;
if (!xdr->codeUint32(&lineno) ||
!xdr->codeUint32(&column) ||
!xdr->codeUint32(&nslots))
{
return false;
}
if (mode == XDR_DECODE) {
script->lineno_ = lineno;
script->column_ = column;
script->nslots_ = nslots;
}
jsbytecode* code = script->code();
SharedScriptData* ssd;
if (mode == XDR_DECODE) {
ssd = SharedScriptData::new_(cx, length, nsrcnotes, natoms);
if (!ssd)
return false;
code = ssd->data;
if (natoms != 0) {
script->natoms_ = natoms;
script->atoms = ssd->atoms();
}
}
if (!xdr->codeBytes(code, length) || !xdr->codeBytes(code + length, nsrcnotes)) {
if (mode == XDR_DECODE)
js_free(ssd);
return false;
}
for (i = 0; i != natoms; ++i) {
if (mode == XDR_DECODE) {
RootedAtom tmp(cx);
if (!XDRAtom(xdr, &tmp))
return false;
script->atoms[i].init(tmp);
} else {
RootedAtom tmp(cx, script->atoms[i]);
if (!XDRAtom(xdr, &tmp))
return false;
}
}
if (mode == XDR_DECODE) {
if (!SaveSharedScriptData(cx, script, ssd, nsrcnotes))
return false;
}
if (nconsts) {
HeapValue* vector = script->consts()->vector;
RootedValue val(cx);
for (i = 0; i != nconsts; ++i) {
if (mode == XDR_ENCODE)
val = vector[i];
if (!XDRScriptConst(xdr, &val))
return false;
if (mode == XDR_DECODE)
vector[i].init(val);
}
}
/*
* Here looping from 0-to-length to xdr objects is essential to ensure that
* all references to enclosing blocks (via FindScopeObjectIndex below) happen
* after the enclosing block has been XDR'd.
*/
for (i = 0; i != nobjects; ++i) {
HeapPtrObject* objp = &script->objects()->vector[i];
XDRClassKind classk;
if (mode == XDR_ENCODE) {
JSObject* obj = *objp;
if (obj->is<BlockObject>())
classk = CK_BlockObject;
else if (obj->is<StaticWithObject>())
classk = CK_WithObject;
else if (obj->is<JSFunction>())
classk = CK_JSFunction;
else if (obj->is<PlainObject>() || obj->is<ArrayObject>())
classk = CK_JSObject;
else
MOZ_CRASH("Cannot encode this class of object.");
}
if (!xdr->codeEnum32(&classk))
return false;
switch (classk) {
case CK_BlockObject:
case CK_WithObject: {
/* Code the nested block's enclosing scope. */
uint32_t enclosingStaticScopeIndex = 0;
if (mode == XDR_ENCODE) {
NestedScopeObject& scope = (*objp)->as<NestedScopeObject>();
if (NestedScopeObject* enclosing = scope.enclosingNestedScope()) {
if (IsStaticGlobalLexicalScope(enclosing))
enclosingStaticScopeIndex = UINT32_MAX;
else
enclosingStaticScopeIndex = FindScopeObjectIndex(script, *enclosing);
} else {
enclosingStaticScopeIndex = UINT32_MAX;
}
}
if (!xdr->codeUint32(&enclosingStaticScopeIndex))
return false;
Rooted<JSObject*> enclosingStaticScope(cx);
if (mode == XDR_DECODE) {
if (enclosingStaticScopeIndex != UINT32_MAX) {
MOZ_ASSERT(enclosingStaticScopeIndex < i);
enclosingStaticScope = script->objects()->vector[enclosingStaticScopeIndex];
} else {
// This is not ternary because MSVC can't typecheck the
// ternary.
if (fun)
enclosingStaticScope = fun;
else
enclosingStaticScope = enclosingScope;
}
}
if (classk == CK_BlockObject) {
Rooted<StaticBlockObject*> tmp(cx, static_cast<StaticBlockObject*>(objp->get()));
if (!XDRStaticBlockObject(xdr, enclosingStaticScope, &tmp))
return false;
*objp = tmp;
} else {
Rooted<StaticWithObject*> tmp(cx, static_cast<StaticWithObject*>(objp->get()));
if (!XDRStaticWithObject(xdr, enclosingStaticScope, &tmp))
return false;
*objp = tmp;
}
break;
}
case CK_JSFunction: {
/* Code the nested function's enclosing scope. */
uint32_t funEnclosingScopeIndex = 0;
RootedObject funEnclosingScope(cx);
if (mode == XDR_ENCODE) {
RootedFunction function(cx, &(*objp)->as<JSFunction>());
if (function->isInterpretedLazy())
funEnclosingScope = function->lazyScript()->enclosingScope();
else if (function->isInterpreted())
funEnclosingScope = function->nonLazyScript()->enclosingStaticScope();
else {
MOZ_ASSERT(function->isAsmJSNative());
JS_ReportError(cx, "AsmJS modules are not yet supported in XDR serialization.");
return false;
}
StaticScopeIter<NoGC> ssi(funEnclosingScope);
// Starting from a nested function, hitting a non-syntactic
// scope on the static scope chain means that its enclosing
// function has a non-syntactic scope. Nested functions
// themselves never have non-syntactic scope chains.
if (ssi.done() ||
ssi.type() == StaticScopeIter<NoGC>::NonSyntactic ||
ssi.type() == StaticScopeIter<NoGC>::Function)
{
MOZ_ASSERT_IF(ssi.done() || ssi.type() != StaticScopeIter<NoGC>::Function, !fun);
funEnclosingScopeIndex = UINT32_MAX;
} else if (ssi.type() == StaticScopeIter<NoGC>::Block) {
if (ssi.block().isGlobal()) {
funEnclosingScopeIndex = UINT32_MAX;
} else {
funEnclosingScopeIndex = FindScopeObjectIndex(script, ssi.block());
MOZ_ASSERT(funEnclosingScopeIndex < i);
}
} else {
funEnclosingScopeIndex = FindScopeObjectIndex(script, ssi.staticWith());
MOZ_ASSERT(funEnclosingScopeIndex < i);
}
}
if (!xdr->codeUint32(&funEnclosingScopeIndex))
return false;
if (mode == XDR_DECODE) {
if (funEnclosingScopeIndex == UINT32_MAX) {
// This is not ternary because MSVC can't typecheck the
// ternary.
if (fun)
funEnclosingScope = fun;
else
funEnclosingScope = enclosingScope;
} else {
MOZ_ASSERT(funEnclosingScopeIndex < i);
funEnclosingScope = script->objects()->vector[funEnclosingScopeIndex];
}
}
// Code nested function and script.
RootedFunction tmp(cx);
if (mode == XDR_ENCODE)
tmp = &(*objp)->as<JSFunction>();
if (!XDRInterpretedFunction(xdr, funEnclosingScope, script, &tmp))
return false;
*objp = tmp;
break;
}
case CK_JSObject: {
/* Code object literal. */
RootedObject tmp(cx, *objp);
if (!XDRObjectLiteral(xdr, &tmp))
return false;
*objp = tmp;
break;
}
default: {
MOZ_ASSERT(false, "Unknown class kind.");
return false;
}
}
}
for (i = 0; i != nregexps; ++i) {
Rooted<RegExpObject*> regexp(cx);
if (mode == XDR_ENCODE)
regexp = &script->regexps()->vector[i]->as<RegExpObject>();
if (!XDRScriptRegExpObject(xdr, &regexp))
return false;
if (mode == XDR_DECODE)
script->regexps()->vector[i] = regexp;
}
if (ntrynotes != 0) {
JSTryNote* tnfirst = script->trynotes()->vector;
MOZ_ASSERT(script->trynotes()->length == ntrynotes);
JSTryNote* tn = tnfirst + ntrynotes;
do {
--tn;
if (!xdr->codeUint8(&tn->kind) ||
!xdr->codeUint32(&tn->stackDepth) ||
!xdr->codeUint32(&tn->start) ||
!xdr->codeUint32(&tn->length)) {
return false;
}
} while (tn != tnfirst);
}
for (i = 0; i < nblockscopes; ++i) {
BlockScopeNote* note = &script->blockScopes()->vector[i];
if (!xdr->codeUint32(&note->index) ||
!xdr->codeUint32(&note->start) ||
!xdr->codeUint32(&note->length) ||
!xdr->codeUint32(&note->parent))
{
return false;
}
}
for (i = 0; i < nyieldoffsets; ++i) {
uint32_t* offset = &script->yieldOffsets()[i];
if (!xdr->codeUint32(offset))
return false;
}
if (scriptBits & (1 << HasLazyScript)) {
Rooted<LazyScript*> lazy(cx);
if (mode == XDR_ENCODE)
lazy = script->maybeLazyScript();
if (!XDRRelazificationInfo(xdr, fun, script, enclosingScope, &lazy))
return false;
if (mode == XDR_DECODE)
script->setLazyScript(lazy);
}
if (mode == XDR_DECODE) {
scriptp.set(script);
/* see BytecodeEmitter::tellDebuggerAboutCompiledScript */
if (!fun)
Debugger::onNewScript(cx, script);
}
return true;
}
template bool
js::XDRScript(XDRState<XDR_ENCODE>*, HandleObject, HandleScript, HandleFunction,
MutableHandleScript);
template bool
js::XDRScript(XDRState<XDR_DECODE>*, HandleObject, HandleScript, HandleFunction,
MutableHandleScript);
template<XDRMode mode>
bool
js::XDRLazyScript(XDRState<mode>* xdr, HandleObject enclosingScope, HandleScript enclosingScript,
HandleFunction fun, MutableHandle<LazyScript*> lazy)
{
JSContext* cx = xdr->cx();
{
uint32_t begin;
uint32_t end;
uint32_t lineno;
uint32_t column;
uint64_t packedFields;
if (mode == XDR_ENCODE) {
// Note: it's possible the LazyScript has a non-null script_ pointer
// to a JSScript. We don't encode it: we can just delazify the
// lazy script.
MOZ_ASSERT(fun == lazy->functionNonDelazifying());
begin = lazy->begin();
end = lazy->end();
lineno = lazy->lineno();
column = lazy->column();
packedFields = lazy->packedFields();
}
if (!xdr->codeUint32(&begin) || !xdr->codeUint32(&end) ||
!xdr->codeUint32(&lineno) || !xdr->codeUint32(&column) ||
!xdr->codeUint64(&packedFields))
{
return false;
}
if (mode == XDR_DECODE) {
lazy.set(LazyScript::Create(cx, fun, nullptr, enclosingScope, enclosingScript,
packedFields, begin, end, lineno, column));
if (!lazy)
return false;
fun->initLazyScript(lazy);
}
}
// Code free variables.
if (!XDRLazyFreeVariables(xdr, lazy))
return false;
// Code inner functions.
{
RootedFunction func(cx);
HeapPtrFunction* innerFunctions = lazy->innerFunctions();
size_t numInnerFunctions = lazy->numInnerFunctions();
for (size_t i = 0; i < numInnerFunctions; i++) {
if (mode == XDR_ENCODE)
func = innerFunctions[i];
if (!XDRInterpretedFunction(xdr, fun, enclosingScript, &func))
return false;
if (mode == XDR_DECODE)
innerFunctions[i] = func;
}
}
return true;
}
template bool
js::XDRLazyScript(XDRState<XDR_ENCODE>*, HandleObject, HandleScript,
HandleFunction, MutableHandle<LazyScript*>);
template bool
js::XDRLazyScript(XDRState<XDR_DECODE>*, HandleObject, HandleScript,
HandleFunction, MutableHandle<LazyScript*>);
void
JSScript::setSourceObject(JSObject* object)
{
MOZ_ASSERT(compartment() == object->compartment());
sourceObject_ = object;
}
js::ScriptSourceObject&
JSScript::scriptSourceUnwrap() const {
return UncheckedUnwrap(sourceObject())->as<ScriptSourceObject>();
}
js::ScriptSource*
JSScript::scriptSource() const {
return scriptSourceUnwrap().source();
}
js::ScriptSource*
JSScript::maybeForwardedScriptSource() const {
return UncheckedUnwrap(MaybeForwarded(sourceObject()))->as<ScriptSourceObject>().source();
}
bool
JSScript::initScriptCounts(JSContext* cx)
{
MOZ_ASSERT(!hasScriptCounts());
// Record all pc which are the first instruction of a basic block.
mozilla::Vector<jsbytecode*, 16, SystemAllocPolicy> jumpTargets;
jsbytecode* end = codeEnd();
jsbytecode* mainEntry = main();
for (jsbytecode* pc = code(); pc != end; pc = GetNextPc(pc)) {
if (pc == mainEntry) {
if (!jumpTargets.append(pc))
return false;
}
bool jump = IsJumpOpcode(JSOp(*pc));
if (jump) {
jsbytecode* target = pc + GET_JUMP_OFFSET(pc);
if (!jumpTargets.append(target))
return false;
if (BytecodeFallsThrough(JSOp(*pc))) {
jsbytecode* fallthrough = GetNextPc(pc);
if (!jumpTargets.append(fallthrough))
return false;
}
}
if (JSOp(*pc) == JSOP_TABLESWITCH) {
jsbytecode* pc2 = pc;
int32_t len = GET_JUMP_OFFSET(pc2);
// Default target.
if (!jumpTargets.append(pc + len))
return false;
pc2 += JUMP_OFFSET_LEN;
int32_t low = GET_JUMP_OFFSET(pc2);
pc2 += JUMP_OFFSET_LEN;
int32_t high = GET_JUMP_OFFSET(pc2);
for (int i = 0; i < high-low+1; i++) {
pc2 += JUMP_OFFSET_LEN;
int32_t off = (int32_t) GET_JUMP_OFFSET(pc2);
if (off) {
// Case (i + low)
if (!jumpTargets.append(pc + off))
return false;
}
}
}
}
// Mark catch/finally blocks as being jump targets.
if (hasTrynotes()) {
JSTryNote* tn = trynotes()->vector;
JSTryNote* tnlimit = tn + trynotes()->length;
for (; tn < tnlimit; tn++) {
jsbytecode* tryStart = mainEntry + tn->start;
jsbytecode* tryPc = tryStart - 1;
if (JSOp(*tryPc) != JSOP_TRY)
continue;
jsbytecode* tryTarget = tryStart + tn->length;
if (!jumpTargets.append(tryTarget))
return false;
}
}
// Sort all pc, and remove duplicates.
std::sort(jumpTargets.begin(), jumpTargets.end());
auto last = std::unique(jumpTargets.begin(), jumpTargets.end());
jumpTargets.erase(last, jumpTargets.end());
// Initialize all PCCounts counters to 0.
ScriptCounts::PCCountsVector base;
if (!base.reserve(jumpTargets.length()))
return false;
for (size_t i = 0; i < jumpTargets.length(); i++)
base.infallibleEmplaceBack(pcToOffset(jumpTargets[i]));
// Create compartment's scriptCountsMap if necessary.
ScriptCountsMap* map = compartment()->scriptCountsMap;
if (!map) {
map = cx->new_<ScriptCountsMap>();
if (!map)
return false;
if (!map->init()) {
js_delete(map);
ReportOutOfMemory(cx);
return false;
}
compartment()->scriptCountsMap = map;
}
// Register the current ScriptCount in the compartment's map.
if (!map->putNew(this, Move(base)))
return false;
// safe to set this; we can't fail after this point.
hasScriptCounts_ = true;
// Enable interrupts in any interpreter frames running on this script. This
// is used to let the interpreter increment the PCCounts, if present.
for (ActivationIterator iter(cx->runtime()); !iter.done(); ++iter) {
if (iter->isInterpreter())
iter->asInterpreter()->enableInterruptsIfRunning(this);
}
return true;
}
static inline ScriptCountsMap::Ptr GetScriptCountsMapEntry(JSScript* script)
{
MOZ_ASSERT(script->hasScriptCounts());
ScriptCountsMap* map = script->compartment()->scriptCountsMap;
ScriptCountsMap::Ptr p = map->lookup(script);
MOZ_ASSERT(p);
return p;
}
ScriptCounts&
JSScript::getScriptCounts()
{
ScriptCountsMap::Ptr p = GetScriptCountsMapEntry(this);
return p->value();
}
js::PCCounts*
ScriptCounts::maybeGetPCCounts(size_t offset) {
PCCounts searched = PCCounts(offset);
PCCounts* elem = std::lower_bound(pcCounts_.begin(), pcCounts_.end(), searched);
if (elem == pcCounts_.end() || elem->pcOffset() != offset)
return nullptr;
return elem;
}
const js::PCCounts*
ScriptCounts::maybeGetPCCounts(size_t offset) const {
PCCounts searched = PCCounts(offset);
const PCCounts* elem = std::lower_bound(pcCounts_.begin(), pcCounts_.end(), searched);
if (elem == pcCounts_.end() || elem->pcOffset() != offset)
return nullptr;
return elem;
}
js::PCCounts*
ScriptCounts::getImmediatePrecedingPCCounts(size_t offset)
{
PCCounts searched = PCCounts(offset);
PCCounts* elem = std::lower_bound(pcCounts_.begin(), pcCounts_.end(), searched);
if (elem == pcCounts_.end())
return &pcCounts_.back();
if (elem->pcOffset() == offset)
return elem;
if (elem != pcCounts_.begin())
return elem - 1;
return nullptr;
}
const js::PCCounts*
ScriptCounts::maybeGetThrowCounts(size_t offset) const {
PCCounts searched = PCCounts(offset);
const PCCounts* elem = std::lower_bound(throwCounts_.begin(), throwCounts_.end(), searched);
if (elem == throwCounts_.end() || elem->pcOffset() != offset)
return nullptr;
return elem;
}
const js::PCCounts*
ScriptCounts::getImmediatePrecedingThrowCounts(size_t offset) const
{
PCCounts searched = PCCounts(offset);
const PCCounts* elem = std::lower_bound(throwCounts_.begin(), throwCounts_.end(), searched);
if (elem == throwCounts_.end()) {
if (throwCounts_.begin() == throwCounts_.end())
return nullptr;
return &throwCounts_.back();
}
if (elem->pcOffset() == offset)
return elem;
if (elem != throwCounts_.begin())
return elem - 1;
return nullptr;
}
js::PCCounts*
ScriptCounts::getThrowCounts(size_t offset) {
PCCounts searched = PCCounts(offset);
PCCounts* elem = std::lower_bound(throwCounts_.begin(), throwCounts_.end(), searched);
if (elem == throwCounts_.end() || elem->pcOffset() != offset)
elem = throwCounts_.insert(elem, searched);
return elem;
}
void
JSScript::setIonScript(JSContext* maybecx, js::jit::IonScript* ionScript)
{
MOZ_ASSERT_IF(ionScript != ION_DISABLED_SCRIPT, !baselineScript()->hasPendingIonBuilder());
if (hasIonScript())
js::jit::IonScript::writeBarrierPre(zone(), ion);
ion = ionScript;
MOZ_ASSERT_IF(hasIonScript(), hasBaselineScript());
updateBaselineOrIonRaw(maybecx);
}
js::PCCounts*
JSScript::maybeGetPCCounts(jsbytecode* pc) {
MOZ_ASSERT(containsPC(pc));
return getScriptCounts().maybeGetPCCounts(pcToOffset(pc));
}
const js::PCCounts*
JSScript::maybeGetThrowCounts(jsbytecode* pc) {
MOZ_ASSERT(containsPC(pc));
return getScriptCounts().maybeGetThrowCounts(pcToOffset(pc));
}
js::PCCounts*
JSScript::getThrowCounts(jsbytecode* pc) {
MOZ_ASSERT(containsPC(pc));
return getScriptCounts().getThrowCounts(pcToOffset(pc));
}
uint64_t
JSScript::getHitCount(jsbytecode* pc)
{
MOZ_ASSERT(containsPC(pc));
if (pc < main())
pc = main();
ScriptCounts& sc = getScriptCounts();
size_t targetOffset = pcToOffset(pc);
const js::PCCounts* baseCount = sc.getImmediatePrecedingPCCounts(targetOffset);
if (!baseCount)
return 0;
if (baseCount->pcOffset() == targetOffset)
return baseCount->numExec();
MOZ_ASSERT(baseCount->pcOffset() < targetOffset);
uint64_t count = baseCount->numExec();
do {
const js::PCCounts* throwCount = sc.getImmediatePrecedingThrowCounts(targetOffset);
if (!throwCount)
return count;
if (throwCount->pcOffset() <= baseCount->pcOffset())
return count;
count -= throwCount->numExec();
targetOffset = throwCount->pcOffset() - 1;
} while (true);
}
void
JSScript::incHitCount(jsbytecode* pc)
{
MOZ_ASSERT(containsPC(pc));
if (pc < main())
pc = main();
ScriptCounts& sc = getScriptCounts();
js::PCCounts* baseCount = sc.getImmediatePrecedingPCCounts(pcToOffset(pc));
if (!baseCount)
return;
baseCount->numExec()++;
}
void
JSScript::addIonCounts(jit::IonScriptCounts* ionCounts)
{
ScriptCounts& sc = getScriptCounts();
if (sc.ionCounts_)
ionCounts->setPrevious(sc.ionCounts_);
sc.ionCounts_ = ionCounts;
}
jit::IonScriptCounts*
JSScript::getIonCounts()
{
return getScriptCounts().ionCounts_;
}
void
JSScript::takeOverScriptCountsMapEntry(ScriptCounts* entryValue)
{
#ifdef DEBUG
ScriptCountsMap::Ptr p = GetScriptCountsMapEntry(this);
MOZ_ASSERT(entryValue == &p->value());
#endif
hasScriptCounts_ = false;
}
void
JSScript::releaseScriptCounts(ScriptCounts* counts)
{
ScriptCountsMap::Ptr p = GetScriptCountsMapEntry(this);
*counts = Move(p->value());
compartment()->scriptCountsMap->remove(p);
hasScriptCounts_ = false;
}
void
JSScript::destroyScriptCounts(FreeOp* fop)
{
if (hasScriptCounts()) {
ScriptCounts scriptCounts;
releaseScriptCounts(&scriptCounts);
}
}
void
ScriptSourceObject::trace(JSTracer* trc, JSObject* obj)
{
ScriptSourceObject* sso = static_cast<ScriptSourceObject*>(obj);
// Don't trip over the poison 'not yet initialized' values.
if (!sso->getReservedSlot(INTRODUCTION_SCRIPT_SLOT).isMagic(JS_GENERIC_MAGIC)) {
JSScript* script = sso->introductionScript();
if (script) {
TraceManuallyBarrieredEdge(trc, &script, "ScriptSourceObject introductionScript");
sso->setReservedSlot(INTRODUCTION_SCRIPT_SLOT, PrivateValue(script));
}
}
}
void
ScriptSourceObject::finalize(FreeOp* fop, JSObject* obj)
{
ScriptSourceObject* sso = &obj->as<ScriptSourceObject>();
// If code coverage is enabled, record the filename associated with this
// source object.
if (fop->runtime()->lcovOutput.isEnabled())
sso->compartment()->lcovOutput.collectSourceFile(sso->compartment(), sso);
sso->source()->decref();
sso->setReservedSlot(SOURCE_SLOT, PrivateValue(nullptr));
}
const Class ScriptSourceObject::class_ = {
"ScriptSource",
JSCLASS_HAS_RESERVED_SLOTS(RESERVED_SLOTS) |
JSCLASS_IS_ANONYMOUS,
nullptr, /* addProperty */
nullptr, /* delProperty */
nullptr, /* getProperty */
nullptr, /* setProperty */
nullptr, /* enumerate */
nullptr, /* resolve */
nullptr, /* mayResolve */
finalize,
nullptr, /* call */
nullptr, /* hasInstance */
nullptr, /* construct */
trace
};
ScriptSourceObject*
ScriptSourceObject::create(ExclusiveContext* cx, ScriptSource* source)
{
RootedObject object(cx, NewObjectWithGivenProto(cx, &class_, nullptr));
if (!object)
return nullptr;
RootedScriptSource sourceObject(cx, &object->as<ScriptSourceObject>());
source->incref(); // The matching decref is in ScriptSourceObject::finalize.
sourceObject->initReservedSlot(SOURCE_SLOT, PrivateValue(source));
// The remaining slots should eventually be populated by a call to
// initFromOptions. Poison them until that point.
sourceObject->initReservedSlot(ELEMENT_SLOT, MagicValue(JS_GENERIC_MAGIC));
sourceObject->initReservedSlot(ELEMENT_PROPERTY_SLOT, MagicValue(JS_GENERIC_MAGIC));
sourceObject->initReservedSlot(INTRODUCTION_SCRIPT_SLOT, MagicValue(JS_GENERIC_MAGIC));
return sourceObject;
}
/* static */ bool
ScriptSourceObject::initFromOptions(JSContext* cx, HandleScriptSource source,
const ReadOnlyCompileOptions& options)
{
assertSameCompartment(cx, source);
MOZ_ASSERT(source->getReservedSlot(ELEMENT_SLOT).isMagic(JS_GENERIC_MAGIC));
MOZ_ASSERT(source->getReservedSlot(ELEMENT_PROPERTY_SLOT).isMagic(JS_GENERIC_MAGIC));
MOZ_ASSERT(source->getReservedSlot(INTRODUCTION_SCRIPT_SLOT).isMagic(JS_GENERIC_MAGIC));
RootedValue element(cx, ObjectOrNullValue(options.element()));
if (!cx->compartment()->wrap(cx, &element))
return false;
source->setReservedSlot(ELEMENT_SLOT, element);
RootedValue elementAttributeName(cx);
if (options.elementAttributeName())
elementAttributeName = StringValue(options.elementAttributeName());
else
elementAttributeName = UndefinedValue();
if (!cx->compartment()->wrap(cx, &elementAttributeName))
return false;
source->setReservedSlot(ELEMENT_PROPERTY_SLOT, elementAttributeName);
// There is no equivalent of cross-compartment wrappers for scripts. If the
// introduction script and ScriptSourceObject are in different compartments,
// we would be creating a cross-compartment script reference, which is
// forbidden. In that case, simply don't bother to retain the introduction
// script.
if (options.introductionScript() &&
options.introductionScript()->compartment() == cx->compartment())
{
source->setReservedSlot(INTRODUCTION_SCRIPT_SLOT, PrivateValue(options.introductionScript()));
} else {
source->setReservedSlot(INTRODUCTION_SCRIPT_SLOT, UndefinedValue());
}
return true;
}
/* static */ bool
JSScript::loadSource(JSContext* cx, ScriptSource* ss, bool* worked)
{
MOZ_ASSERT(!ss->hasSourceData());
*worked = false;
if (!cx->runtime()->sourceHook || !ss->sourceRetrievable())
return true;
char16_t* src = nullptr;
size_t length;
if (!cx->runtime()->sourceHook->load(cx, ss->filename(), &src, &length))
return false;
if (!src)
return true;
ss->setSource(src, length);
*worked = true;
return true;
}
JSFlatString*
JSScript::sourceData(JSContext* cx)
{
MOZ_ASSERT(scriptSource()->hasSourceData());
return scriptSource()->substring(cx, sourceStart(), sourceEnd());
}
UncompressedSourceCache::AutoHoldEntry::AutoHoldEntry()
: cache_(nullptr), source_(nullptr), charsToFree_(nullptr)
{
}
void
UncompressedSourceCache::AutoHoldEntry::holdEntry(UncompressedSourceCache* cache, ScriptSource* source)
{
// Initialise the holder for a specific cache and script source. This will
// hold on to the cached source chars in the event that the cache is purged.
MOZ_ASSERT(!cache_ && !source_ && !charsToFree_);
cache_ = cache;
source_ = source;
}
void
UncompressedSourceCache::AutoHoldEntry::deferDelete(const char16_t* chars)
{
// Take ownership of source chars now the cache is being purged. Remove our
// reference to the ScriptSource which might soon be destroyed.
MOZ_ASSERT(cache_ && source_ && !charsToFree_);
cache_ = nullptr;
source_ = nullptr;
charsToFree_ = chars;
}
UncompressedSourceCache::AutoHoldEntry::~AutoHoldEntry()
{
// The holder is going out of scope. If it has taken ownership of cached
// chars then delete them, otherwise unregister ourself with the cache.
if (charsToFree_) {
MOZ_ASSERT(!cache_ && !source_);
js_free(const_cast<char16_t*>(charsToFree_));
} else if (cache_) {
MOZ_ASSERT(source_);
cache_->releaseEntry(*this);
}
}
void
UncompressedSourceCache::holdEntry(AutoHoldEntry& holder, ScriptSource* ss)
{
MOZ_ASSERT(!holder_);
holder.holdEntry(this, ss);
holder_ = &holder;
}
void
UncompressedSourceCache::releaseEntry(AutoHoldEntry& holder)
{
MOZ_ASSERT(holder_ == &holder);
holder_ = nullptr;
}
const char16_t*
UncompressedSourceCache::lookup(ScriptSource* ss, AutoHoldEntry& holder)
{
MOZ_ASSERT(!holder_);
if (!map_)
return nullptr;
if (Map::Ptr p = map_->lookup(ss)) {
holdEntry(holder, ss);
return p->value();
}
return nullptr;
}
bool
UncompressedSourceCache::put(ScriptSource* ss, const char16_t* str, AutoHoldEntry& holder)
{
MOZ_ASSERT(!holder_);
if (!map_) {
map_ = js_new<Map>();
if (!map_)
return false;
if (!map_->init()) {
js_delete(map_);
map_ = nullptr;
return false;
}
}
if (!map_->put(ss, str))
return false;
holdEntry(holder, ss);
return true;
}
void
UncompressedSourceCache::purge()
{
if (!map_)
return;
for (Map::Range r = map_->all(); !r.empty(); r.popFront()) {
const char16_t* chars = r.front().value();
if (holder_ && r.front().key() == holder_->source()) {
holder_->deferDelete(chars);
holder_ = nullptr;
} else {
js_free(const_cast<char16_t*>(chars));
}
}
js_delete(map_);
map_ = nullptr;
}
size_t
UncompressedSourceCache::sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf)
{
size_t n = 0;
if (map_ && !map_->empty()) {
n += map_->sizeOfIncludingThis(mallocSizeOf);
for (Map::Range r = map_->all(); !r.empty(); r.popFront()) {
const char16_t* v = r.front().value();
n += mallocSizeOf(v);
}
}
return n;
}
const char16_t*
ScriptSource::chars(JSContext* cx, UncompressedSourceCache::AutoHoldEntry& holder)
{
switch (dataType) {
case DataUncompressed:
return uncompressedChars();
case DataCompressed: {
if (const char16_t* decompressed = cx->runtime()->uncompressedSourceCache.lookup(this, holder))
return decompressed;
const size_t nbytes = sizeof(char16_t) * (length_ + 1);
char16_t* decompressed = static_cast<char16_t*>(js_malloc(nbytes));
if (!decompressed) {
JS_ReportOutOfMemory(cx);
return nullptr;
}
if (!DecompressString((const unsigned char*) compressedData(), compressedBytes(),
reinterpret_cast<unsigned char*>(decompressed), nbytes)) {
JS_ReportOutOfMemory(cx);
js_free(decompressed);
return nullptr;
}
decompressed[length_] = 0;
if (!cx->runtime()->uncompressedSourceCache.put(this, decompressed, holder)) {
JS_ReportOutOfMemory(cx);
js_free(decompressed);
return nullptr;
}
return decompressed;
}
case DataParent:
return parent()->chars(cx, holder);
default:
MOZ_CRASH();
}
}
JSFlatString*
ScriptSource::substring(JSContext* cx, uint32_t start, uint32_t stop)
{
MOZ_ASSERT(start <= stop);
UncompressedSourceCache::AutoHoldEntry holder;
const char16_t* chars = this->chars(cx, holder);
if (!chars)
return nullptr;
return NewStringCopyN<CanGC>(cx, chars + start, stop - start);
}
JSFlatString*
ScriptSource::substringDontDeflate(JSContext* cx, uint32_t start, uint32_t stop)
{
MOZ_ASSERT(start <= stop);
UncompressedSourceCache::AutoHoldEntry holder;
const char16_t* chars = this->chars(cx, holder);
if (!chars)
return nullptr;
return NewStringCopyNDontDeflate<CanGC>(cx, chars + start, stop - start);
}
void
ScriptSource::setSource(const char16_t* chars, size_t length, bool ownsChars /* = true */)
{
MOZ_ASSERT(dataType == DataMissing);
dataType = DataUncompressed;
data.uncompressed.chars = chars;
data.uncompressed.ownsChars = ownsChars;
length_ = length;
}
void
ScriptSource::setCompressedSource(JSRuntime* maybert, void* raw, size_t nbytes, HashNumber hash)
{
MOZ_ASSERT(dataType == DataMissing || dataType == DataUncompressed);
if (dataType == DataUncompressed && ownsUncompressedChars())
js_free(const_cast<char16_t*>(uncompressedChars()));
dataType = DataCompressed;
data.compressed.raw = raw;
data.compressed.nbytes = nbytes;
data.compressed.hash = hash;
if (maybert)
updateCompressedSourceSet(maybert);
}
void
ScriptSource::updateCompressedSourceSet(JSRuntime* rt)
{
MOZ_ASSERT(dataType == DataCompressed);
MOZ_ASSERT(!inCompressedSourceSet);
CompressedSourceSet::AddPtr p = rt->compressedSourceSet.lookupForAdd(this);
if (p) {
// There is another ScriptSource with the same compressed data.
// Mark that ScriptSource as the parent and use it for all attempts to
// get the source for this ScriptSource.
ScriptSource* parent = *p;
parent->incref();
js_free(compressedData());
dataType = DataParent;
data.parent = parent;
} else {
if (rt->compressedSourceSet.add(p, this))
inCompressedSourceSet = true;
}
}
bool
ScriptSource::ensureOwnsSource(ExclusiveContext* cx)
{
MOZ_ASSERT(dataType == DataUncompressed);
if (ownsUncompressedChars())
return true;
char16_t* uncompressed = cx->zone()->pod_malloc<char16_t>(Max<size_t>(length_, 1));
if (!uncompressed) {
ReportOutOfMemory(cx);
return false;
}
PodCopy(uncompressed, uncompressedChars(), length_);
data.uncompressed.chars = uncompressed;
data.uncompressed.ownsChars = true;
return true;
}
bool
ScriptSource::setSourceCopy(ExclusiveContext* cx, SourceBufferHolder& srcBuf,
bool argumentsNotIncluded, SourceCompressionTask* task)
{
MOZ_ASSERT(!hasSourceData());
argumentsNotIncluded_ = argumentsNotIncluded;
bool owns = srcBuf.ownsChars();
setSource(owns ? srcBuf.take() : srcBuf.get(), srcBuf.length(), owns);
// There are several cases where source compression is not a good idea:
// - If the script is tiny, then compression will save little or no space.
// - If the script is enormous, then decompression can take seconds. With
// lazy parsing, decompression is not uncommon, so this can significantly
// increase latency.
// - If there is only one core, then compression will contend with JS
// execution (which hurts benchmarketing).
// - If the source contains a giant string, then parsing will finish much
// faster than compression which increases latency (this case is handled
// in Parser::stringLiteral).
//
// Lastly, since the parsing thread will eventually perform a blocking wait
// on the compression task's thread, require that there are at least 2
// helper threads:
// - If we are on a helper thread, there must be another helper thread to
// execute our compression task.
// - If we are on the main thread, there must be at least two helper
// threads since at most one helper thread can be blocking on the main
// thread (see HelperThreadState::canStartParseTask) which would cause a
// deadlock if there wasn't a second helper thread that could make
// progress on our compression task.
bool canCompressOffThread =
HelperThreadState().cpuCount > 1 &&
HelperThreadState().threadCount >= 2 &&
CanUseExtraThreads();
const size_t TINY_SCRIPT = 256;
const size_t HUGE_SCRIPT = 5 * 1024 * 1024;
if (TINY_SCRIPT <= srcBuf.length() && srcBuf.length() < HUGE_SCRIPT && canCompressOffThread) {
task->ss = this;
if (!StartOffThreadCompression(cx, task))
return false;
} else if (!ensureOwnsSource(cx)) {
return false;
}
return true;
}
SourceCompressionTask::ResultType
SourceCompressionTask::work()
{
// Try to keep the maximum memory usage down by only allocating half the
// size of the string, first.
size_t inputBytes = ss->length() * sizeof(char16_t);
size_t firstSize = inputBytes / 2;
compressed = js_malloc(firstSize);
if (!compressed)
return OOM;
Compressor comp(reinterpret_cast<const unsigned char*>(ss->uncompressedChars()), inputBytes);
if (!comp.init())
return OOM;
comp.setOutput((unsigned char*) compressed, firstSize);
bool cont = true;
while (cont) {
if (abort_)
return Aborted;
switch (comp.compressMore()) {
case Compressor::CONTINUE:
break;
case Compressor::MOREOUTPUT: {
if (comp.outWritten() == inputBytes) {
// The compressed string is longer than the original string.
return Aborted;
}
// The compressed output is greater than half the size of the
// original string. Reallocate to the full size.
compressed = js_realloc(compressed, inputBytes);
if (!compressed)
return OOM;
comp.setOutput((unsigned char*) compressed, inputBytes);
break;
}
case Compressor::DONE:
cont = false;
break;
case Compressor::OOM:
return OOM;
}
}
compressedBytes = comp.outWritten();
compressedHash = CompressedSourceHasher::computeHash(compressed, compressedBytes);
// Shrink the buffer to the size of the compressed data.
if (void* newCompressed = js_realloc(compressed, compressedBytes))
compressed = newCompressed;
return Success;
}
ScriptSource::~ScriptSource()
{
MOZ_ASSERT_IF(inCompressedSourceSet, dataType == DataCompressed);
switch (dataType) {
case DataUncompressed:
if (ownsUncompressedChars())
js_free(const_cast<char16_t*>(uncompressedChars()));
break;
case DataCompressed:
// Script source references are only manipulated on the main thread,
// except during off thread parsing when the source may be created
// and used exclusively by the thread doing the parse. In this case the
// ScriptSource might be destroyed while off the main thread, but it
// will not have been added to the runtime's compressed source set
// until the parse is finished on the main thread.
if (inCompressedSourceSet)
TlsPerThreadData.get()->runtimeFromMainThread()->compressedSourceSet.remove(this);
js_free(compressedData());
break;
case DataParent:
parent()->decref();
break;
default:
break;
}
}
void
ScriptSource::addSizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf,
JS::ScriptSourceInfo* info) const
{
if (dataType == DataUncompressed && ownsUncompressedChars())
info->uncompressed += mallocSizeOf(uncompressedChars());
else if (dataType == DataCompressed)
info->compressed += mallocSizeOf(compressedData());
info->misc += mallocSizeOf(this) +
mallocSizeOf(filename_.get()) +
mallocSizeOf(introducerFilename_.get());
info->numScripts++;
}
template<XDRMode mode>
bool
ScriptSource::performXDR(XDRState<mode>* xdr)
{
uint8_t hasSource = hasSourceData();
if (!xdr->codeUint8(&hasSource))
return false;
uint8_t retrievable = sourceRetrievable_;
if (!xdr->codeUint8(&retrievable))
return false;
sourceRetrievable_ = retrievable;
if (hasSource && !sourceRetrievable_) {
if (!xdr->codeUint32(&length_))
return false;
uint32_t compressedLength;
if (mode == XDR_ENCODE) {
switch (dataType) {
case DataUncompressed:
compressedLength = 0;
break;
case DataCompressed:
compressedLength = compressedBytes();
break;
case DataParent:
compressedLength = parent()->compressedBytes();
break;
default:
MOZ_CRASH();
}
}
if (!xdr->codeUint32(&compressedLength))
return false;
{
uint8_t argumentsNotIncluded;
if (mode == XDR_ENCODE)
argumentsNotIncluded = argumentsNotIncluded_;
if (!xdr->codeUint8(&argumentsNotIncluded))
return false;
if (mode == XDR_DECODE)
argumentsNotIncluded_ = argumentsNotIncluded;
}
size_t byteLen = compressedLength ? compressedLength : (length_ * sizeof(char16_t));
if (mode == XDR_DECODE) {
uint8_t* p = xdr->cx()->template pod_malloc<uint8_t>(Max<size_t>(byteLen, 1));
if (!p || !xdr->codeBytes(p, byteLen)) {
js_free(p);
return false;
}
if (compressedLength)
setCompressedSource(xdr->cx()->runtime(), p, compressedLength,
CompressedSourceHasher::computeHash(p, compressedLength));
else
setSource((const char16_t*) p, length_);
} else {
void* p;
switch (dataType) {
case DataUncompressed:
p = (void*) uncompressedChars();
break;
case DataCompressed:
p = compressedData();
break;
case DataParent:
p = parent()->compressedData();
break;
default:
MOZ_CRASH();
}
if (!xdr->codeBytes(p, byteLen))
return false;
}
}
uint8_t haveSourceMap = hasSourceMapURL();
if (!xdr->codeUint8(&haveSourceMap))
return false;
if (haveSourceMap) {
uint32_t sourceMapURLLen = (mode == XDR_DECODE) ? 0 : js_strlen(sourceMapURL_.get());
if (!xdr->codeUint32(&sourceMapURLLen))
return false;
if (mode == XDR_DECODE) {
sourceMapURL_ = xdr->cx()->template make_pod_array<char16_t>(sourceMapURLLen + 1);
if (!sourceMapURL_)
return false;
}
if (!xdr->codeChars(sourceMapURL_.get(), sourceMapURLLen)) {
if (mode == XDR_DECODE)
sourceMapURL_ = nullptr;
return false;
}
sourceMapURL_[sourceMapURLLen] = '\0';
}
uint8_t haveDisplayURL = hasDisplayURL();
if (!xdr->codeUint8(&haveDisplayURL))
return false;
if (haveDisplayURL) {
uint32_t displayURLLen = (mode == XDR_DECODE) ? 0 : js_strlen(displayURL_.get());
if (!xdr->codeUint32(&displayURLLen))
return false;
if (mode == XDR_DECODE) {
displayURL_ = xdr->cx()->template make_pod_array<char16_t>(displayURLLen + 1);
if (!displayURL_)
return false;
}
if (!xdr->codeChars(displayURL_.get(), displayURLLen)) {
if (mode == XDR_DECODE)
displayURL_ = nullptr;
return false;
}
displayURL_[displayURLLen] = '\0';
}
uint8_t haveFilename = !!filename_;
if (!xdr->codeUint8(&haveFilename))
return false;
if (haveFilename) {
const char* fn = filename();
if (!xdr->codeCString(&fn))
return false;
if (mode == XDR_DECODE && !setFilename(xdr->cx(), fn))
return false;
}
return true;
}
// Format and return a cx->zone()->pod_malloc'ed URL for a generated script like:
// {filename} line {lineno} > {introducer}
// For example:
// foo.js line 7 > eval
// indicating code compiled by the call to 'eval' on line 7 of foo.js.
static char*
FormatIntroducedFilename(ExclusiveContext* cx, const char* filename, unsigned lineno,
const char* introducer)
{
// Compute the length of the string in advance, so we can allocate a
// buffer of the right size on the first shot.
//
// (JS_smprintf would be perfect, as that allocates the result
// dynamically as it formats the string, but it won't allocate from cx,
// and wants us to use a special free function.)
char linenoBuf[15];
size_t filenameLen = strlen(filename);
size_t linenoLen = JS_snprintf(linenoBuf, 15, "%u", lineno);
size_t introducerLen = strlen(introducer);
size_t len = filenameLen +
6 /* == strlen(" line ") */ +
linenoLen +
3 /* == strlen(" > ") */ +
introducerLen +
1 /* \0 */;
char* formatted = cx->zone()->pod_malloc<char>(len);
if (!formatted) {
ReportOutOfMemory(cx);
return nullptr;
}
mozilla::DebugOnly<size_t> checkLen = JS_snprintf(formatted, len, "%s line %s > %s",
filename, linenoBuf, introducer);
MOZ_ASSERT(checkLen == len - 1);
return formatted;
}
bool
ScriptSource::initFromOptions(ExclusiveContext* cx, const ReadOnlyCompileOptions& options)
{
MOZ_ASSERT(!filename_);
MOZ_ASSERT(!introducerFilename_);
mutedErrors_ = options.mutedErrors();
introductionType_ = options.introductionType;
setIntroductionOffset(options.introductionOffset);
if (options.hasIntroductionInfo) {
MOZ_ASSERT(options.introductionType != nullptr);
const char* filename = options.filename() ? options.filename() : "<unknown>";
char* formatted = FormatIntroducedFilename(cx, filename, options.introductionLineno,
options.introductionType);
if (!formatted)
return false;
filename_.reset(formatted);
} else if (options.filename()) {
if (!setFilename(cx, options.filename()))
return false;
}
if (options.introducerFilename()) {
introducerFilename_ = DuplicateString(cx, options.introducerFilename());
if (!introducerFilename_)
return false;
}
return true;
}
bool
ScriptSource::setFilename(ExclusiveContext* cx, const char* filename)
{
MOZ_ASSERT(!filename_);
filename_ = DuplicateString(cx, filename);
return filename_ != nullptr;
}
bool
ScriptSource::setDisplayURL(ExclusiveContext* cx, const char16_t* displayURL)
{
MOZ_ASSERT(displayURL);
if (hasDisplayURL()) {
if (cx->isJSContext() &&
!JS_ReportErrorFlagsAndNumber(cx->asJSContext(), JSREPORT_WARNING,
GetErrorMessage, nullptr,
JSMSG_ALREADY_HAS_PRAGMA, filename_.get(),
"//# sourceURL"))
{
return false;
}
}
size_t len = js_strlen(displayURL) + 1;
if (len == 1)
return true;
displayURL_ = DuplicateString(cx, displayURL);
return displayURL_ != nullptr;
}
bool
ScriptSource::setSourceMapURL(ExclusiveContext* cx, const char16_t* sourceMapURL)
{
MOZ_ASSERT(sourceMapURL);
size_t len = js_strlen(sourceMapURL) + 1;
if (len == 1)
return true;
sourceMapURL_ = DuplicateString(cx, sourceMapURL);
return sourceMapURL_ != nullptr;
}
size_t
ScriptSource::computedSizeOfData() const
{
if (dataType == DataUncompressed && ownsUncompressedChars())
return sizeof(char16_t) * length_;
if (dataType == DataCompressed)
return compressedBytes();
return 0;
}
/*
* Shared script data management.
*/
SharedScriptData*
js::SharedScriptData::new_(ExclusiveContext* cx, uint32_t codeLength,
uint32_t srcnotesLength, uint32_t natoms)
{
/*
* Ensure the atoms are aligned, as some architectures don't allow unaligned
* access.
*/
const uint32_t pointerSize = sizeof(JSAtom*);
const uint32_t pointerMask = pointerSize - 1;
const uint32_t dataOffset = offsetof(SharedScriptData, data);
uint32_t baseLength = codeLength + srcnotesLength;
uint32_t padding = (pointerSize - ((baseLength + dataOffset) & pointerMask)) & pointerMask;
uint32_t length = baseLength + padding + pointerSize * natoms;
SharedScriptData* entry = reinterpret_cast<SharedScriptData*>(
cx->zone()->pod_malloc<uint8_t>(length + dataOffset));
if (!entry) {
ReportOutOfMemory(cx);
return nullptr;
}
entry->length = length;
entry->natoms = natoms;
entry->marked = false;
memset(entry->data + baseLength, 0, padding);
/*
* Call constructors to initialize the storage that will be accessed as a
* HeapPtrAtom array via atoms().
*/
HeapPtrAtom* atoms = entry->atoms();
MOZ_ASSERT(reinterpret_cast<uintptr_t>(atoms) % sizeof(JSAtom*) == 0);
for (unsigned i = 0; i < natoms; ++i)
new (&atoms[i]) HeapPtrAtom();
return entry;
}
/*
* Takes ownership of its *ssd parameter and either adds it into the runtime's
* ScriptDataTable or frees it if a matching entry already exists.
*
* Sets the |code| and |atoms| fields on the given JSScript.
*/
static bool
SaveSharedScriptData(ExclusiveContext* cx, Handle<JSScript*> script, SharedScriptData* ssd,
uint32_t nsrcnotes)
{
MOZ_ASSERT(script != nullptr);
MOZ_ASSERT(ssd != nullptr);
AutoLockForExclusiveAccess lock(cx);
ScriptBytecodeHasher::Lookup l(ssd);
ScriptDataTable::AddPtr p = cx->scriptDataTable().lookupForAdd(l);
if (p) {
js_free(ssd);
ssd = *p;
} else {
if (!cx->scriptDataTable().add(p, ssd)) {
script->setCode(nullptr);
script->atoms = nullptr;
js_free(ssd);
ReportOutOfMemory(cx);
return false;
}
}
/*
* During the IGC we need to ensure that bytecode is marked whenever it is
* accessed even if the bytecode was already in the table: at this point
* old scripts or exceptions pointing to the bytecode may no longer be
* reachable. This is effectively a read barrier.
*/
if (cx->isJSContext()) {
JSRuntime* rt = cx->asJSContext()->runtime();
if (JS::IsIncrementalGCInProgress(rt) && rt->gc.isFullGc())
ssd->marked = true;
}
script->setCode(ssd->data);
script->atoms = ssd->atoms();
return true;
}
static inline void
MarkScriptData(JSRuntime* rt, const jsbytecode* bytecode)
{
/*
* As an invariant, a ScriptBytecodeEntry should not be 'marked' outside of
* a GC. Since SweepScriptBytecodes is only called during a full gc,
* to preserve this invariant, only mark during a full gc.
*/
if (rt->gc.isFullGc())
SharedScriptData::fromBytecode(bytecode)->marked = true;
}
void
js::UnmarkScriptData(JSRuntime* rt)
{
MOZ_ASSERT(rt->gc.isFullGc());
ScriptDataTable& table = rt->scriptDataTable();
for (ScriptDataTable::Enum e(table); !e.empty(); e.popFront()) {
SharedScriptData* entry = e.front();
entry->marked = false;
}
}
void
js::SweepScriptData(JSRuntime* rt)
{
MOZ_ASSERT(rt->gc.isFullGc());
ScriptDataTable& table = rt->scriptDataTable();
if (rt->keepAtoms())
return;
for (ScriptDataTable::Enum e(table); !e.empty(); e.popFront()) {
SharedScriptData* entry = e.front();
if (!entry->marked) {
js_free(entry);
e.removeFront();
}
}
}
void
js::FreeScriptData(JSRuntime* rt)
{
ScriptDataTable& table = rt->scriptDataTable();
if (!table.initialized())
return;
for (ScriptDataTable::Enum e(table); !e.empty(); e.popFront())
js_free(e.front());
table.clear();
}
/*
* JSScript::data and SharedScriptData::data have complex,
* manually-controlled, memory layouts.
*
* JSScript::data begins with some optional array headers. They are optional
* because they often aren't needed, i.e. the corresponding arrays often have
* zero elements. Each header has a bit in JSScript::hasArrayBits that
* indicates if it's present within |data|; from this the offset of each
* present array header can be computed. Each header has an accessor function
* in JSScript that encapsulates this offset computation.
*
* Array type Array elements Accessor
* ---------- -------------- --------
* ConstArray Consts consts()
* ObjectArray Objects objects()
* ObjectArray Regexps regexps()
* TryNoteArray Try notes trynotes()
* BlockScopeArray Scope notes blockScopes()
*
* Then are the elements of several arrays.
* - Most of these arrays have headers listed above (if present). For each of
* these, th