michael@0: /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- michael@0: * vim: set ts=8 sts=4 et sw=4 tw=99: michael@0: * This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: /* michael@0: * JS function support. michael@0: */ michael@0: michael@0: #include "jsfuninlines.h" michael@0: michael@0: #include "mozilla/ArrayUtils.h" michael@0: #include "mozilla/PodOperations.h" michael@0: michael@0: #include michael@0: michael@0: #include "jsapi.h" michael@0: #include "jsarray.h" michael@0: #include "jsatom.h" michael@0: #include "jscntxt.h" michael@0: #include "jsobj.h" michael@0: #include "jsproxy.h" michael@0: #include "jsscript.h" michael@0: #include "jsstr.h" michael@0: #include "jstypes.h" michael@0: #include "jswrapper.h" michael@0: michael@0: #include "builtin/Eval.h" michael@0: #include "builtin/Object.h" michael@0: #include "frontend/BytecodeCompiler.h" michael@0: #include "frontend/TokenStream.h" michael@0: #include "gc/Marking.h" michael@0: #ifdef JS_ION michael@0: #include "jit/Ion.h" michael@0: #include "jit/JitFrameIterator.h" michael@0: #endif michael@0: #include "vm/Interpreter.h" michael@0: #include "vm/Shape.h" michael@0: #include "vm/StringBuffer.h" michael@0: #include "vm/WrapperObject.h" michael@0: #include "vm/Xdr.h" michael@0: michael@0: #include "jsscriptinlines.h" michael@0: michael@0: #include "vm/Interpreter-inl.h" michael@0: #include "vm/Stack-inl.h" michael@0: michael@0: using namespace js; michael@0: using namespace js::gc; michael@0: using namespace js::types; michael@0: using namespace js::frontend; michael@0: michael@0: using mozilla::ArrayLength; michael@0: using mozilla::PodCopy; michael@0: michael@0: static bool michael@0: fun_getProperty(JSContext *cx, HandleObject obj_, HandleId id, MutableHandleValue vp) michael@0: { michael@0: RootedObject obj(cx, obj_); michael@0: while (!obj->is()) { michael@0: if (!JSObject::getProto(cx, obj, &obj)) michael@0: return false; michael@0: if (!obj) michael@0: return true; michael@0: } michael@0: RootedFunction fun(cx, &obj->as()); michael@0: michael@0: /* Set to early to null in case of error */ michael@0: vp.setNull(); michael@0: michael@0: /* Find fun's top-most activation record. */ michael@0: NonBuiltinScriptFrameIter iter(cx); michael@0: for (; !iter.done(); ++iter) { michael@0: if (!iter.isFunctionFrame() || iter.isEvalFrame()) michael@0: continue; michael@0: if (iter.callee() == fun) michael@0: break; michael@0: } michael@0: if (iter.done()) michael@0: return true; michael@0: michael@0: if (JSID_IS_ATOM(id, cx->names().arguments)) { michael@0: if (fun->hasRest()) { michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, michael@0: JSMSG_FUNCTION_ARGUMENTS_AND_REST); michael@0: return false; michael@0: } michael@0: /* Warn if strict about f.arguments or equivalent unqualified uses. */ michael@0: if (!JS_ReportErrorFlagsAndNumber(cx, JSREPORT_WARNING | JSREPORT_STRICT, js_GetErrorMessage, michael@0: nullptr, JSMSG_DEPRECATED_USAGE, js_arguments_str)) { michael@0: return false; michael@0: } michael@0: michael@0: ArgumentsObject *argsobj = ArgumentsObject::createUnexpected(cx, iter); michael@0: if (!argsobj) michael@0: return false; michael@0: michael@0: #ifdef JS_ION michael@0: // Disabling compiling of this script in IonMonkey. michael@0: // IonMonkey does not guarantee |f.arguments| can be michael@0: // fully recovered, so we try to mitigate observing this behavior by michael@0: // detecting its use early. michael@0: JSScript *script = iter.script(); michael@0: jit::ForbidCompilation(cx, script); michael@0: #endif michael@0: michael@0: vp.setObject(*argsobj); michael@0: return true; michael@0: } michael@0: michael@0: if (JSID_IS_ATOM(id, cx->names().caller)) { michael@0: ++iter; michael@0: if (iter.done() || !iter.isFunctionFrame()) { michael@0: JS_ASSERT(vp.isNull()); michael@0: return true; michael@0: } michael@0: michael@0: /* Callsite clones should never escape to script. */ michael@0: JSObject &maybeClone = iter.calleev().toObject(); michael@0: if (maybeClone.is()) michael@0: vp.setObject(*maybeClone.as().originalFunction()); michael@0: else michael@0: vp.set(iter.calleev()); michael@0: michael@0: if (!cx->compartment()->wrap(cx, vp)) michael@0: return false; michael@0: michael@0: /* michael@0: * Censor the caller if we don't have full access to it. michael@0: */ michael@0: RootedObject caller(cx, &vp.toObject()); michael@0: if (caller->is() && Wrapper::wrapperHandler(caller)->hasSecurityPolicy()) { michael@0: vp.setNull(); michael@0: } else if (caller->is()) { michael@0: JSFunction *callerFun = &caller->as(); michael@0: if (callerFun->isInterpreted() && callerFun->strict()) { michael@0: JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, js_GetErrorMessage, nullptr, michael@0: JSMSG_CALLER_IS_STRICT); michael@0: return false; michael@0: } michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: MOZ_ASSUME_UNREACHABLE("fun_getProperty"); michael@0: } michael@0: michael@0: michael@0: michael@0: /* NB: no sentinels at ends -- use ArrayLength to bound loops. michael@0: * Properties censored into [[ThrowTypeError]] in strict mode. */ michael@0: static const uint16_t poisonPillProps[] = { michael@0: NAME_OFFSET(arguments), michael@0: NAME_OFFSET(caller), michael@0: }; michael@0: michael@0: static bool michael@0: fun_enumerate(JSContext *cx, HandleObject obj) michael@0: { michael@0: JS_ASSERT(obj->is()); michael@0: michael@0: RootedId id(cx); michael@0: bool found; michael@0: michael@0: if (!obj->isBoundFunction() && !obj->as().isArrow()) { michael@0: id = NameToId(cx->names().prototype); michael@0: if (!JSObject::hasProperty(cx, obj, id, &found)) michael@0: return false; michael@0: } michael@0: michael@0: id = NameToId(cx->names().length); michael@0: if (!JSObject::hasProperty(cx, obj, id, &found)) michael@0: return false; michael@0: michael@0: id = NameToId(cx->names().name); michael@0: if (!JSObject::hasProperty(cx, obj, id, &found)) michael@0: return false; michael@0: michael@0: for (unsigned i = 0; i < ArrayLength(poisonPillProps); i++) { michael@0: const uint16_t offset = poisonPillProps[i]; michael@0: id = NameToId(AtomStateOffsetToName(cx->names(), offset)); michael@0: if (!JSObject::hasProperty(cx, obj, id, &found)) michael@0: return false; michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: static JSObject * michael@0: ResolveInterpretedFunctionPrototype(JSContext *cx, HandleObject obj) michael@0: { michael@0: #ifdef DEBUG michael@0: JSFunction *fun = &obj->as(); michael@0: JS_ASSERT(fun->isInterpreted()); michael@0: JS_ASSERT(!fun->isFunctionPrototype()); michael@0: #endif michael@0: michael@0: // Assert that fun is not a compiler-created function object, which michael@0: // must never leak to script or embedding code and then be mutated. michael@0: // Also assert that obj is not bound, per the ES5 15.3.4.5 ref above. michael@0: JS_ASSERT(!IsInternalFunctionObject(obj)); michael@0: JS_ASSERT(!obj->isBoundFunction()); michael@0: michael@0: // Make the prototype object an instance of Object with the same parent as michael@0: // the function object itself, unless the function is an ES6 generator. In michael@0: // that case, per the 15 July 2013 ES6 draft, section 15.19.3, its parent is michael@0: // the GeneratorObjectPrototype singleton. michael@0: bool isStarGenerator = obj->as().isStarGenerator(); michael@0: Rooted global(cx, &obj->global()); michael@0: JSObject *objProto; michael@0: if (isStarGenerator) michael@0: objProto = GlobalObject::getOrCreateStarGeneratorObjectPrototype(cx, global); michael@0: else michael@0: objProto = obj->global().getOrCreateObjectPrototype(cx); michael@0: if (!objProto) michael@0: return nullptr; michael@0: const Class *clasp = &JSObject::class_; michael@0: michael@0: RootedObject proto(cx, NewObjectWithGivenProto(cx, clasp, objProto, nullptr, SingletonObject)); michael@0: if (!proto) michael@0: return nullptr; michael@0: michael@0: // Per ES5 15.3.5.2 a user-defined function's .prototype property is michael@0: // initially non-configurable, non-enumerable, and writable. michael@0: RootedValue protoVal(cx, ObjectValue(*proto)); michael@0: if (!JSObject::defineProperty(cx, obj, cx->names().prototype, michael@0: protoVal, JS_PropertyStub, JS_StrictPropertyStub, michael@0: JSPROP_PERMANENT)) michael@0: { michael@0: return nullptr; michael@0: } michael@0: michael@0: // Per ES5 13.2 the prototype's .constructor property is configurable, michael@0: // non-enumerable, and writable. However, per the 15 July 2013 ES6 draft, michael@0: // section 15.19.3, the .prototype of a generator function does not link michael@0: // back with a .constructor. michael@0: if (!isStarGenerator) { michael@0: RootedValue objVal(cx, ObjectValue(*obj)); michael@0: if (!JSObject::defineProperty(cx, proto, cx->names().constructor, michael@0: objVal, JS_PropertyStub, JS_StrictPropertyStub, 0)) michael@0: { michael@0: return nullptr; michael@0: } michael@0: } michael@0: michael@0: return proto; michael@0: } michael@0: michael@0: bool michael@0: js::FunctionHasResolveHook(const JSAtomState &atomState, PropertyName *name) michael@0: { michael@0: if (name == atomState.prototype || name == atomState.length || name == atomState.name) michael@0: return true; michael@0: michael@0: for (unsigned i = 0; i < ArrayLength(poisonPillProps); i++) { michael@0: const uint16_t offset = poisonPillProps[i]; michael@0: michael@0: if (name == AtomStateOffsetToName(atomState, offset)) michael@0: return true; michael@0: } michael@0: michael@0: return false; michael@0: } michael@0: michael@0: bool michael@0: js::fun_resolve(JSContext *cx, HandleObject obj, HandleId id, MutableHandleObject objp) michael@0: { michael@0: if (!JSID_IS_ATOM(id)) michael@0: return true; michael@0: michael@0: RootedFunction fun(cx, &obj->as()); michael@0: michael@0: if (JSID_IS_ATOM(id, cx->names().prototype)) { michael@0: /* michael@0: * Built-in functions do not have a .prototype property per ECMA-262, michael@0: * or (Object.prototype, Function.prototype, etc.) have that property michael@0: * created eagerly. michael@0: * michael@0: * ES5 15.3.4: the non-native function object named Function.prototype michael@0: * does not have a .prototype property. michael@0: * michael@0: * ES5 15.3.4.5: bound functions don't have a prototype property. The michael@0: * isBuiltin() test covers this case because bound functions are native michael@0: * (and thus built-in) functions by definition/construction. michael@0: * michael@0: * ES6 19.2.4.3: arrow functions also don't have a prototype property. michael@0: */ michael@0: if (fun->isBuiltin() || fun->isArrow() || fun->isFunctionPrototype()) michael@0: return true; michael@0: michael@0: if (!ResolveInterpretedFunctionPrototype(cx, fun)) michael@0: return false; michael@0: objp.set(fun); michael@0: return true; michael@0: } michael@0: michael@0: if (JSID_IS_ATOM(id, cx->names().length) || JSID_IS_ATOM(id, cx->names().name)) { michael@0: JS_ASSERT(!IsInternalFunctionObject(obj)); michael@0: michael@0: RootedValue v(cx); michael@0: if (JSID_IS_ATOM(id, cx->names().length)) { michael@0: if (fun->isInterpretedLazy() && !fun->getOrCreateScript(cx)) michael@0: return false; michael@0: uint16_t length = fun->hasScript() ? fun->nonLazyScript()->funLength() : michael@0: fun->nargs() - fun->hasRest(); michael@0: v.setInt32(length); michael@0: } else { michael@0: v.setString(fun->atom() == nullptr ? cx->runtime()->emptyString : fun->atom()); michael@0: } michael@0: michael@0: if (!DefineNativeProperty(cx, fun, id, v, JS_PropertyStub, JS_StrictPropertyStub, michael@0: JSPROP_PERMANENT | JSPROP_READONLY)) { michael@0: return false; michael@0: } michael@0: objp.set(fun); michael@0: return true; michael@0: } michael@0: michael@0: for (unsigned i = 0; i < ArrayLength(poisonPillProps); i++) { michael@0: const uint16_t offset = poisonPillProps[i]; michael@0: michael@0: if (JSID_IS_ATOM(id, AtomStateOffsetToName(cx->names(), offset))) { michael@0: JS_ASSERT(!IsInternalFunctionObject(fun)); michael@0: michael@0: PropertyOp getter; michael@0: StrictPropertyOp setter; michael@0: unsigned attrs = JSPROP_PERMANENT | JSPROP_SHARED; michael@0: if (fun->isInterpretedLazy() && !fun->getOrCreateScript(cx)) michael@0: return false; michael@0: if (fun->isInterpreted() ? fun->strict() : fun->isBoundFunction()) { michael@0: JSObject *throwTypeError = fun->global().getThrowTypeError(); michael@0: michael@0: getter = CastAsPropertyOp(throwTypeError); michael@0: setter = CastAsStrictPropertyOp(throwTypeError); michael@0: attrs |= JSPROP_GETTER | JSPROP_SETTER; michael@0: } else { michael@0: getter = fun_getProperty; michael@0: setter = JS_StrictPropertyStub; michael@0: } michael@0: michael@0: if (!DefineNativeProperty(cx, fun, id, UndefinedHandleValue, getter, setter, attrs)) michael@0: return false; michael@0: objp.set(fun); michael@0: return true; michael@0: } michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: template michael@0: bool michael@0: js::XDRInterpretedFunction(XDRState *xdr, HandleObject enclosingScope, HandleScript enclosingScript, michael@0: MutableHandleObject objp) michael@0: { michael@0: enum FirstWordFlag { michael@0: HasAtom = 0x1, michael@0: IsStarGenerator = 0x2, michael@0: IsLazy = 0x4, michael@0: HasSingletonType = 0x8 michael@0: }; michael@0: michael@0: /* NB: Keep this in sync with CloneFunctionAndScript. */ michael@0: RootedAtom atom(xdr->cx()); michael@0: uint32_t firstword = 0; /* bitmask of FirstWordFlag */ michael@0: uint32_t flagsword = 0; /* word for argument count and fun->flags */ michael@0: michael@0: JSContext *cx = xdr->cx(); michael@0: RootedFunction fun(cx); michael@0: RootedScript script(cx); michael@0: Rooted lazy(cx); michael@0: michael@0: if (mode == XDR_ENCODE) { michael@0: fun = &objp->as(); michael@0: if (!fun->isInterpreted()) { michael@0: JSAutoByteString funNameBytes; michael@0: if (const char *name = GetFunctionNameBytes(cx, fun, &funNameBytes)) { michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, michael@0: JSMSG_NOT_SCRIPTED_FUNCTION, name); michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: if (fun->atom() || fun->hasGuessedAtom()) michael@0: firstword |= HasAtom; michael@0: michael@0: if (fun->isStarGenerator()) michael@0: firstword |= IsStarGenerator; michael@0: michael@0: if (fun->isInterpretedLazy()) { michael@0: // This can only happen for re-lazified cloned functions, so this michael@0: // does not apply to any JSFunction produced by the parser, only to michael@0: // JSFunction created by the runtime. michael@0: JS_ASSERT(!fun->lazyScript()->maybeScript()); michael@0: michael@0: // Encode a lazy script. michael@0: firstword |= IsLazy; michael@0: lazy = fun->lazyScript(); michael@0: } else { michael@0: // Encode the script. michael@0: script = fun->nonLazyScript(); michael@0: } michael@0: michael@0: if (fun->hasSingletonType()) michael@0: firstword |= HasSingletonType; michael@0: michael@0: atom = fun->displayAtom(); michael@0: flagsword = (fun->nargs() << 16) | fun->flags(); michael@0: michael@0: // The environment of any function which is not reused will always be michael@0: // null, it is later defined when a function is cloned or reused to michael@0: // mirror the scope chain. michael@0: JS_ASSERT_IF(fun->hasSingletonType() && michael@0: !((lazy && lazy->hasBeenCloned()) || (script && script->hasBeenCloned())), michael@0: fun->environment() == nullptr); michael@0: } michael@0: michael@0: if (!xdr->codeUint32(&firstword)) michael@0: return false; michael@0: michael@0: if ((firstword & HasAtom) && !XDRAtom(xdr, &atom)) michael@0: return false; michael@0: if (!xdr->codeUint32(&flagsword)) michael@0: return false; michael@0: michael@0: if (mode == XDR_DECODE) { michael@0: JSObject *proto = nullptr; michael@0: if (firstword & IsStarGenerator) { michael@0: proto = GlobalObject::getOrCreateStarGeneratorFunctionPrototype(cx, cx->global()); michael@0: if (!proto) michael@0: return false; michael@0: } michael@0: michael@0: gc::AllocKind allocKind = JSFunction::FinalizeKind; michael@0: if (uint16_t(flagsword) & JSFunction::EXTENDED) michael@0: allocKind = JSFunction::ExtendedFinalizeKind; michael@0: fun = NewFunctionWithProto(cx, NullPtr(), nullptr, 0, JSFunction::INTERPRETED, michael@0: /* parent = */ NullPtr(), NullPtr(), proto, michael@0: allocKind, TenuredObject); michael@0: if (!fun) michael@0: return false; michael@0: script = nullptr; michael@0: } michael@0: michael@0: if (firstword & IsLazy) { michael@0: if (!XDRLazyScript(xdr, enclosingScope, enclosingScript, fun, &lazy)) michael@0: return false; michael@0: } else { michael@0: if (!XDRScript(xdr, enclosingScope, enclosingScript, fun, &script)) michael@0: return false; michael@0: } michael@0: michael@0: if (mode == XDR_DECODE) { michael@0: fun->setArgCount(flagsword >> 16); michael@0: fun->setFlags(uint16_t(flagsword)); michael@0: fun->initAtom(atom); michael@0: if (firstword & IsLazy) { michael@0: fun->initLazyScript(lazy); michael@0: } else { michael@0: fun->initScript(script); michael@0: script->setFunction(fun); michael@0: JS_ASSERT(fun->nargs() == script->bindings.numArgs()); michael@0: } michael@0: michael@0: bool singleton = firstword & HasSingletonType; michael@0: if (!JSFunction::setTypeForScriptedFunction(cx, fun, singleton)) michael@0: return false; michael@0: objp.set(fun); michael@0: } michael@0: michael@0: return true; michael@0: } michael@0: michael@0: template bool michael@0: js::XDRInterpretedFunction(XDRState *, HandleObject, HandleScript, MutableHandleObject); michael@0: michael@0: template bool michael@0: js::XDRInterpretedFunction(XDRState *, HandleObject, HandleScript, MutableHandleObject); michael@0: michael@0: JSObject * michael@0: js::CloneFunctionAndScript(JSContext *cx, HandleObject enclosingScope, HandleFunction srcFun) michael@0: { michael@0: /* NB: Keep this in sync with XDRInterpretedFunction. */ michael@0: JSObject *cloneProto = nullptr; michael@0: if (srcFun->isStarGenerator()) { michael@0: cloneProto = GlobalObject::getOrCreateStarGeneratorFunctionPrototype(cx, cx->global()); michael@0: if (!cloneProto) michael@0: return nullptr; michael@0: } michael@0: michael@0: gc::AllocKind allocKind = JSFunction::FinalizeKind; michael@0: if (srcFun->isExtended()) michael@0: allocKind = JSFunction::ExtendedFinalizeKind; michael@0: RootedFunction clone(cx, NewFunctionWithProto(cx, NullPtr(), nullptr, 0, michael@0: JSFunction::INTERPRETED, NullPtr(), NullPtr(), michael@0: cloneProto, allocKind, TenuredObject)); michael@0: if (!clone) michael@0: return nullptr; michael@0: michael@0: RootedScript srcScript(cx, srcFun->getOrCreateScript(cx)); michael@0: if (!srcScript) michael@0: return nullptr; michael@0: RootedScript clonedScript(cx, CloneScript(cx, enclosingScope, clone, srcScript)); michael@0: if (!clonedScript) michael@0: return nullptr; michael@0: michael@0: clone->setArgCount(srcFun->nargs()); michael@0: clone->setFlags(srcFun->flags()); michael@0: clone->initAtom(srcFun->displayAtom()); michael@0: clone->initScript(clonedScript); michael@0: clonedScript->setFunction(clone); michael@0: if (!JSFunction::setTypeForScriptedFunction(cx, clone)) michael@0: return nullptr; michael@0: michael@0: RootedScript cloneScript(cx, clone->nonLazyScript()); michael@0: CallNewScriptHook(cx, cloneScript, clone); michael@0: return clone; michael@0: } michael@0: michael@0: /* michael@0: * [[HasInstance]] internal method for Function objects: fetch the .prototype michael@0: * property of its 'this' parameter, and walks the prototype chain of v (only michael@0: * if v is an object) returning true if .prototype is found. michael@0: */ michael@0: static bool michael@0: fun_hasInstance(JSContext *cx, HandleObject objArg, MutableHandleValue v, bool *bp) michael@0: { michael@0: RootedObject obj(cx, objArg); michael@0: michael@0: while (obj->is() && obj->isBoundFunction()) michael@0: obj = obj->as().getBoundFunctionTarget(); michael@0: michael@0: RootedValue pval(cx); michael@0: if (!JSObject::getProperty(cx, obj, obj, cx->names().prototype, &pval)) michael@0: return false; michael@0: michael@0: if (pval.isPrimitive()) { michael@0: /* michael@0: * Throw a runtime error if instanceof is called on a function that michael@0: * has a non-object as its .prototype value. michael@0: */ michael@0: RootedValue val(cx, ObjectValue(*obj)); michael@0: js_ReportValueError(cx, JSMSG_BAD_PROTOTYPE, -1, val, js::NullPtr()); michael@0: return false; michael@0: } michael@0: michael@0: RootedObject pobj(cx, &pval.toObject()); michael@0: bool isDelegate; michael@0: if (!IsDelegate(cx, pobj, v, &isDelegate)) michael@0: return false; michael@0: *bp = isDelegate; michael@0: return true; michael@0: } michael@0: michael@0: inline void michael@0: JSFunction::trace(JSTracer *trc) michael@0: { michael@0: if (isExtended()) { michael@0: MarkValueRange(trc, ArrayLength(toExtended()->extendedSlots), michael@0: toExtended()->extendedSlots, "nativeReserved"); michael@0: } michael@0: michael@0: if (atom_) michael@0: MarkString(trc, &atom_, "atom"); michael@0: michael@0: if (isInterpreted()) { michael@0: // Functions can be be marked as interpreted despite having no script michael@0: // yet at some points when parsing, and can be lazy with no lazy script michael@0: // for self-hosted code. michael@0: if (hasScript() && u.i.s.script_) { michael@0: // Functions can be relazified under the following conditions: michael@0: // - their compartment isn't currently executing scripts or being michael@0: // debugged michael@0: // - they are not in the self-hosting compartment michael@0: // - they aren't generators michael@0: // - they don't have JIT code attached michael@0: // - they haven't ever been inlined michael@0: // - they don't have child functions michael@0: // - they have information for un-lazifying them again later michael@0: // This information can either be a LazyScript, or the name of a michael@0: // self-hosted function which can be cloned over again. The latter michael@0: // is stored in the first extended slot. michael@0: if (IS_GC_MARKING_TRACER(trc) && !compartment()->hasBeenEntered() && michael@0: !compartment()->debugMode() && !compartment()->isSelfHosting && michael@0: u.i.s.script_->isRelazifiable() && (!isSelfHostedBuiltin() || isExtended())) michael@0: { michael@0: relazify(trc); michael@0: } else { michael@0: MarkScriptUnbarriered(trc, &u.i.s.script_, "script"); michael@0: } michael@0: } else if (isInterpretedLazy() && u.i.s.lazy_) { michael@0: MarkLazyScriptUnbarriered(trc, &u.i.s.lazy_, "lazyScript"); michael@0: } michael@0: if (u.i.env_) michael@0: MarkObjectUnbarriered(trc, &u.i.env_, "fun_callscope"); michael@0: } michael@0: } michael@0: michael@0: static void michael@0: fun_trace(JSTracer *trc, JSObject *obj) michael@0: { michael@0: obj->as().trace(trc); michael@0: } michael@0: michael@0: const Class JSFunction::class_ = { michael@0: js_Function_str, michael@0: JSCLASS_NEW_RESOLVE | JSCLASS_IMPLEMENTS_BARRIERS | michael@0: JSCLASS_HAS_CACHED_PROTO(JSProto_Function), michael@0: JS_PropertyStub, /* addProperty */ michael@0: JS_DeletePropertyStub, /* delProperty */ michael@0: JS_PropertyStub, /* getProperty */ michael@0: JS_StrictPropertyStub, /* setProperty */ michael@0: fun_enumerate, michael@0: (JSResolveOp)js::fun_resolve, michael@0: JS_ConvertStub, michael@0: nullptr, /* finalize */ michael@0: nullptr, /* call */ michael@0: fun_hasInstance, michael@0: nullptr, /* construct */ michael@0: fun_trace michael@0: }; michael@0: michael@0: const Class* const js::FunctionClassPtr = &JSFunction::class_; michael@0: michael@0: /* Find the body of a function (not including braces). */ michael@0: bool michael@0: js::FindBody(JSContext *cx, HandleFunction fun, ConstTwoByteChars chars, size_t length, michael@0: size_t *bodyStart, size_t *bodyEnd) michael@0: { michael@0: // We don't need principals, since those are only used for error reporting. michael@0: CompileOptions options(cx); michael@0: options.setFileAndLine("internal-findBody", 0); michael@0: michael@0: // For asm.js modules, there's no script. michael@0: if (fun->hasScript()) michael@0: options.setVersion(fun->nonLazyScript()->getVersion()); michael@0: michael@0: AutoKeepAtoms keepAtoms(cx->perThreadData); michael@0: TokenStream ts(cx, options, chars.get(), length, nullptr); michael@0: int nest = 0; michael@0: bool onward = true; michael@0: // Skip arguments list. michael@0: do { michael@0: switch (ts.getToken()) { michael@0: case TOK_NAME: michael@0: case TOK_YIELD: michael@0: if (nest == 0) michael@0: onward = false; michael@0: break; michael@0: case TOK_LP: michael@0: nest++; michael@0: break; michael@0: case TOK_RP: michael@0: if (--nest == 0) michael@0: onward = false; michael@0: break; michael@0: case TOK_ERROR: michael@0: // Must be memory. michael@0: return false; michael@0: default: michael@0: break; michael@0: } michael@0: } while (onward); michael@0: TokenKind tt = ts.getToken(); michael@0: if (tt == TOK_ARROW) michael@0: tt = ts.getToken(); michael@0: if (tt == TOK_ERROR) michael@0: return false; michael@0: bool braced = tt == TOK_LC; michael@0: JS_ASSERT_IF(fun->isExprClosure(), !braced); michael@0: *bodyStart = ts.currentToken().pos.begin; michael@0: if (braced) michael@0: *bodyStart += 1; michael@0: ConstTwoByteChars end(chars.get() + length, chars.get(), length); michael@0: if (end[-1] == '}') { michael@0: end--; michael@0: } else { michael@0: JS_ASSERT(!braced); michael@0: for (; unicode::IsSpaceOrBOM2(end[-1]); end--) michael@0: ; michael@0: } michael@0: *bodyEnd = end - chars; michael@0: JS_ASSERT(*bodyStart <= *bodyEnd); michael@0: return true; michael@0: } michael@0: michael@0: JSString * michael@0: js::FunctionToString(JSContext *cx, HandleFunction fun, bool bodyOnly, bool lambdaParen) michael@0: { michael@0: if (fun->isInterpretedLazy() && !fun->getOrCreateScript(cx)) michael@0: return nullptr; michael@0: michael@0: if (IsAsmJSModule(fun)) michael@0: return AsmJSModuleToString(cx, fun, !lambdaParen); michael@0: if (IsAsmJSFunction(fun)) michael@0: return AsmJSFunctionToString(cx, fun); michael@0: michael@0: StringBuffer out(cx); michael@0: RootedScript script(cx); michael@0: michael@0: if (fun->hasScript()) { michael@0: script = fun->nonLazyScript(); michael@0: if (script->isGeneratorExp()) { michael@0: if ((!bodyOnly && !out.append("function genexp() {")) || michael@0: !out.append("\n [generator expression]\n") || michael@0: (!bodyOnly && !out.append("}"))) michael@0: { michael@0: return nullptr; michael@0: } michael@0: return out.finishString(); michael@0: } michael@0: } michael@0: if (!bodyOnly) { michael@0: // If we're not in pretty mode, put parentheses around lambda functions. michael@0: if (fun->isInterpreted() && !lambdaParen && fun->isLambda() && !fun->isArrow()) { michael@0: if (!out.append("(")) michael@0: return nullptr; michael@0: } michael@0: if (!fun->isArrow()) { michael@0: if (!(fun->isStarGenerator() ? out.append("function* ") : out.append("function "))) michael@0: return nullptr; michael@0: } michael@0: if (fun->atom()) { michael@0: if (!out.append(fun->atom())) michael@0: return nullptr; michael@0: } michael@0: } michael@0: bool haveSource = fun->isInterpreted() && !fun->isSelfHostedBuiltin(); michael@0: if (haveSource && !script->scriptSource()->hasSourceData() && michael@0: !JSScript::loadSource(cx, script->scriptSource(), &haveSource)) michael@0: { michael@0: return nullptr; michael@0: } michael@0: if (haveSource) { michael@0: RootedString srcStr(cx, script->sourceData(cx)); michael@0: if (!srcStr) michael@0: return nullptr; michael@0: Rooted src(cx, srcStr->ensureFlat(cx)); michael@0: if (!src) michael@0: return nullptr; michael@0: michael@0: ConstTwoByteChars chars(src->chars(), src->length()); michael@0: bool exprBody = fun->isExprClosure(); michael@0: michael@0: // The source data for functions created by calling the Function michael@0: // constructor is only the function's body. This depends on the fact, michael@0: // asserted below, that in Function("function f() {}"), the inner michael@0: // function's sourceStart points to the '(', not the 'f'. michael@0: bool funCon = !fun->isArrow() && michael@0: script->sourceStart() == 0 && michael@0: script->sourceEnd() == script->scriptSource()->length() && michael@0: script->scriptSource()->argumentsNotIncluded(); michael@0: michael@0: // Functions created with the constructor can't be arrow functions or michael@0: // expression closures. michael@0: JS_ASSERT_IF(funCon, !fun->isArrow()); michael@0: JS_ASSERT_IF(funCon, !exprBody); michael@0: JS_ASSERT_IF(!funCon && !fun->isArrow(), src->length() > 0 && chars[0] == '('); michael@0: michael@0: // If a function inherits strict mode by having scopes above it that michael@0: // have "use strict", we insert "use strict" into the body of the michael@0: // function. This ensures that if the result of toString is evaled, the michael@0: // resulting function will have the same semantics. michael@0: bool addUseStrict = script->strict() && !script->explicitUseStrict() && !fun->isArrow(); michael@0: michael@0: bool buildBody = funCon && !bodyOnly; michael@0: if (buildBody) { michael@0: // This function was created with the Function constructor. We don't michael@0: // have source for the arguments, so we have to generate that. Part michael@0: // of bug 755821 should be cobbling the arguments passed into the michael@0: // Function constructor into the source string. michael@0: if (!out.append("(")) michael@0: return nullptr; michael@0: michael@0: // Fish out the argument names. michael@0: BindingVector *localNames = cx->new_(cx); michael@0: ScopedJSDeletePtr freeNames(localNames); michael@0: if (!FillBindingVector(script, localNames)) michael@0: return nullptr; michael@0: for (unsigned i = 0; i < fun->nargs(); i++) { michael@0: if ((i && !out.append(", ")) || michael@0: (i == unsigned(fun->nargs() - 1) && fun->hasRest() && !out.append("...")) || michael@0: !out.append((*localNames)[i].name())) { michael@0: return nullptr; michael@0: } michael@0: } michael@0: if (!out.append(") {\n")) michael@0: return nullptr; michael@0: } michael@0: if ((bodyOnly && !funCon) || addUseStrict) { michael@0: // We need to get at the body either because we're only supposed to michael@0: // return the body or we need to insert "use strict" into the body. michael@0: size_t bodyStart = 0, bodyEnd; michael@0: michael@0: // If the function is defined in the Function constructor, we michael@0: // already have a body. michael@0: if (!funCon) { michael@0: JS_ASSERT(!buildBody); michael@0: if (!FindBody(cx, fun, chars, src->length(), &bodyStart, &bodyEnd)) michael@0: return nullptr; michael@0: } else { michael@0: bodyEnd = src->length(); michael@0: } michael@0: michael@0: if (addUseStrict) { michael@0: // Output source up to beginning of body. michael@0: if (!out.append(chars, bodyStart)) michael@0: return nullptr; michael@0: if (exprBody) { michael@0: // We can't insert a statement into a function with an michael@0: // expression body. Do what the decompiler did, and insert a michael@0: // comment. michael@0: if (!out.append("/* use strict */ ")) michael@0: return nullptr; michael@0: } else { michael@0: if (!out.append("\n\"use strict\";\n")) michael@0: return nullptr; michael@0: } michael@0: } michael@0: michael@0: // Output just the body (for bodyOnly) or the body and possibly michael@0: // closing braces (for addUseStrict). michael@0: size_t dependentEnd = bodyOnly ? bodyEnd : src->length(); michael@0: if (!out.append(chars + bodyStart, dependentEnd - bodyStart)) michael@0: return nullptr; michael@0: } else { michael@0: if (!out.append(src)) michael@0: return nullptr; michael@0: } michael@0: if (buildBody) { michael@0: if (!out.append("\n}")) michael@0: return nullptr; michael@0: } michael@0: if (bodyOnly) { michael@0: // Slap a semicolon on the end of functions with an expression body. michael@0: if (exprBody && !out.append(";")) michael@0: return nullptr; michael@0: } else if (!lambdaParen && fun->isLambda() && !fun->isArrow()) { michael@0: if (!out.append(")")) michael@0: return nullptr; michael@0: } michael@0: } else if (fun->isInterpreted() && !fun->isSelfHostedBuiltin()) { michael@0: if ((!bodyOnly && !out.append("() {\n ")) || michael@0: !out.append("[sourceless code]") || michael@0: (!bodyOnly && !out.append("\n}"))) michael@0: return nullptr; michael@0: if (!lambdaParen && fun->isLambda() && !fun->isArrow() && !out.append(")")) michael@0: return nullptr; michael@0: } else { michael@0: JS_ASSERT(!fun->isExprClosure()); michael@0: michael@0: if ((!bodyOnly && !out.append("() {\n ")) michael@0: || !out.append("[native code]") michael@0: || (!bodyOnly && !out.append("\n}"))) michael@0: { michael@0: return nullptr; michael@0: } michael@0: } michael@0: return out.finishString(); michael@0: } michael@0: michael@0: JSString * michael@0: fun_toStringHelper(JSContext *cx, HandleObject obj, unsigned indent) michael@0: { michael@0: if (!obj->is()) { michael@0: if (obj->is()) michael@0: return Proxy::fun_toString(cx, obj, indent); michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, michael@0: JSMSG_INCOMPATIBLE_PROTO, michael@0: js_Function_str, js_toString_str, michael@0: "object"); michael@0: return nullptr; michael@0: } michael@0: michael@0: RootedFunction fun(cx, &obj->as()); michael@0: return FunctionToString(cx, fun, false, indent != JS_DONT_PRETTY_PRINT); michael@0: } michael@0: michael@0: static bool michael@0: fun_toString(JSContext *cx, unsigned argc, Value *vp) michael@0: { michael@0: CallArgs args = CallArgsFromVp(argc, vp); michael@0: JS_ASSERT(IsFunctionObject(args.calleev())); michael@0: michael@0: uint32_t indent = 0; michael@0: michael@0: if (args.length() != 0 && !ToUint32(cx, args[0], &indent)) michael@0: return false; michael@0: michael@0: RootedObject obj(cx, ToObject(cx, args.thisv())); michael@0: if (!obj) michael@0: return false; michael@0: michael@0: RootedString str(cx, fun_toStringHelper(cx, obj, indent)); michael@0: if (!str) michael@0: return false; michael@0: michael@0: args.rval().setString(str); michael@0: return true; michael@0: } michael@0: michael@0: #if JS_HAS_TOSOURCE michael@0: static bool michael@0: fun_toSource(JSContext *cx, unsigned argc, Value *vp) michael@0: { michael@0: CallArgs args = CallArgsFromVp(argc, vp); michael@0: JS_ASSERT(IsFunctionObject(args.calleev())); michael@0: michael@0: RootedObject obj(cx, ToObject(cx, args.thisv())); michael@0: if (!obj) michael@0: return false; michael@0: michael@0: RootedString str(cx); michael@0: if (obj->isCallable()) michael@0: str = fun_toStringHelper(cx, obj, JS_DONT_PRETTY_PRINT); michael@0: else michael@0: str = ObjectToSource(cx, obj); michael@0: michael@0: if (!str) michael@0: return false; michael@0: args.rval().setString(str); michael@0: return true; michael@0: } michael@0: #endif michael@0: michael@0: bool michael@0: js_fun_call(JSContext *cx, unsigned argc, Value *vp) michael@0: { michael@0: CallArgs args = CallArgsFromVp(argc, vp); michael@0: michael@0: HandleValue fval = args.thisv(); michael@0: if (!js_IsCallable(fval)) { michael@0: ReportIncompatibleMethod(cx, args, &JSFunction::class_); michael@0: return false; michael@0: } michael@0: michael@0: args.setCallee(fval); michael@0: args.setThis(args.get(0)); michael@0: michael@0: if (args.length() > 0) { michael@0: for (size_t i = 0; i < args.length() - 1; i++) michael@0: args[i].set(args[i + 1]); michael@0: args = CallArgsFromVp(args.length() - 1, vp); michael@0: } michael@0: michael@0: return Invoke(cx, args); michael@0: } michael@0: michael@0: // ES5 15.3.4.3 michael@0: bool michael@0: js_fun_apply(JSContext *cx, unsigned argc, Value *vp) michael@0: { michael@0: CallArgs args = CallArgsFromVp(argc, vp); michael@0: michael@0: // Step 1. michael@0: HandleValue fval = args.thisv(); michael@0: if (!js_IsCallable(fval)) { michael@0: ReportIncompatibleMethod(cx, args, &JSFunction::class_); michael@0: return false; michael@0: } michael@0: michael@0: // Step 2. michael@0: if (args.length() < 2 || args[1].isNullOrUndefined()) michael@0: return js_fun_call(cx, (args.length() > 0) ? 1 : 0, vp); michael@0: michael@0: InvokeArgs args2(cx); michael@0: michael@0: // A JS_OPTIMIZED_ARGUMENTS magic value means that 'arguments' flows into michael@0: // this apply call from a scripted caller and, as an optimization, we've michael@0: // avoided creating it since apply can simply pull the argument values from michael@0: // the calling frame (which we must do now). michael@0: if (args[1].isMagic(JS_OPTIMIZED_ARGUMENTS)) { michael@0: // Step 3-6. michael@0: ScriptFrameIter iter(cx); michael@0: JS_ASSERT(iter.numActualArgs() <= ARGS_LENGTH_MAX); michael@0: if (!args2.init(iter.numActualArgs())) michael@0: return false; michael@0: michael@0: args2.setCallee(fval); michael@0: args2.setThis(args[0]); michael@0: michael@0: // Steps 7-8. michael@0: iter.unaliasedForEachActual(cx, CopyTo(args2.array())); michael@0: } else { michael@0: // Step 3. michael@0: if (!args[1].isObject()) { michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, michael@0: JSMSG_BAD_APPLY_ARGS, js_apply_str); michael@0: return false; michael@0: } michael@0: michael@0: // Steps 4-5 (note erratum removing steps originally numbered 5 and 7 in michael@0: // original version of ES5). michael@0: RootedObject aobj(cx, &args[1].toObject()); michael@0: uint32_t length; michael@0: if (!GetLengthProperty(cx, aobj, &length)) michael@0: return false; michael@0: michael@0: // Step 6. michael@0: if (length > ARGS_LENGTH_MAX) { michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_TOO_MANY_FUN_APPLY_ARGS); michael@0: return false; michael@0: } michael@0: michael@0: if (!args2.init(length)) michael@0: return false; michael@0: michael@0: // Push fval, obj, and aobj's elements as args. michael@0: args2.setCallee(fval); michael@0: args2.setThis(args[0]); michael@0: michael@0: // Steps 7-8. michael@0: if (!GetElements(cx, aobj, length, args2.array())) michael@0: return false; michael@0: } michael@0: michael@0: // Step 9. michael@0: if (!Invoke(cx, args2)) michael@0: return false; michael@0: michael@0: args.rval().set(args2.rval()); michael@0: return true; michael@0: } michael@0: michael@0: static const uint32_t JSSLOT_BOUND_FUNCTION_THIS = 0; michael@0: static const uint32_t JSSLOT_BOUND_FUNCTION_ARGS_COUNT = 1; michael@0: michael@0: static const uint32_t BOUND_FUNCTION_RESERVED_SLOTS = 2; michael@0: michael@0: inline bool michael@0: JSFunction::initBoundFunction(JSContext *cx, HandleValue thisArg, michael@0: const Value *args, unsigned argslen) michael@0: { michael@0: RootedFunction self(cx, this); michael@0: michael@0: /* michael@0: * Convert to a dictionary to set the BOUND_FUNCTION flag and increase michael@0: * the slot span to cover the arguments and additional slots for the 'this' michael@0: * value and arguments count. michael@0: */ michael@0: if (!self->toDictionaryMode(cx)) michael@0: return false; michael@0: michael@0: if (!self->setFlag(cx, BaseShape::BOUND_FUNCTION)) michael@0: return false; michael@0: michael@0: if (!JSObject::setSlotSpan(cx, self, BOUND_FUNCTION_RESERVED_SLOTS + argslen)) michael@0: return false; michael@0: michael@0: self->setSlot(JSSLOT_BOUND_FUNCTION_THIS, thisArg); michael@0: self->setSlot(JSSLOT_BOUND_FUNCTION_ARGS_COUNT, PrivateUint32Value(argslen)); michael@0: michael@0: self->initSlotRange(BOUND_FUNCTION_RESERVED_SLOTS, args, argslen); michael@0: michael@0: return true; michael@0: } michael@0: michael@0: const js::Value & michael@0: JSFunction::getBoundFunctionThis() const michael@0: { michael@0: JS_ASSERT(isBoundFunction()); michael@0: michael@0: return getSlot(JSSLOT_BOUND_FUNCTION_THIS); michael@0: } michael@0: michael@0: const js::Value & michael@0: JSFunction::getBoundFunctionArgument(unsigned which) const michael@0: { michael@0: JS_ASSERT(isBoundFunction()); michael@0: JS_ASSERT(which < getBoundFunctionArgumentCount()); michael@0: michael@0: return getSlot(BOUND_FUNCTION_RESERVED_SLOTS + which); michael@0: } michael@0: michael@0: size_t michael@0: JSFunction::getBoundFunctionArgumentCount() const michael@0: { michael@0: JS_ASSERT(isBoundFunction()); michael@0: michael@0: return getSlot(JSSLOT_BOUND_FUNCTION_ARGS_COUNT).toPrivateUint32(); michael@0: } michael@0: michael@0: /* static */ bool michael@0: JSFunction::createScriptForLazilyInterpretedFunction(JSContext *cx, HandleFunction fun) michael@0: { michael@0: JS_ASSERT(fun->isInterpretedLazy()); michael@0: michael@0: Rooted lazy(cx, fun->lazyScriptOrNull()); michael@0: if (lazy) { michael@0: // Trigger a pre barrier on the lazy script being overwritten. michael@0: if (cx->zone()->needsBarrier()) michael@0: LazyScript::writeBarrierPre(lazy); michael@0: michael@0: // Suppress GC for now although we should be able to remove this by michael@0: // making 'lazy' a Rooted (which requires adding a michael@0: // THING_ROOT_LAZY_SCRIPT). michael@0: AutoSuppressGC suppressGC(cx); michael@0: michael@0: RootedScript script(cx, lazy->maybeScript()); michael@0: michael@0: if (script) { michael@0: fun->setUnlazifiedScript(script); michael@0: // Remember the lazy script on the compiled script, so it can be michael@0: // stored on the function again in case of re-lazification. michael@0: // Only functions without inner functions are re-lazified. michael@0: if (!lazy->numInnerFunctions()) michael@0: script->setLazyScript(lazy); michael@0: return true; michael@0: } michael@0: michael@0: if (fun != lazy->functionNonDelazifying()) { michael@0: if (!lazy->functionDelazifying(cx)) michael@0: return false; michael@0: script = lazy->functionNonDelazifying()->nonLazyScript(); michael@0: if (!script) michael@0: return false; michael@0: michael@0: fun->setUnlazifiedScript(script); michael@0: return true; michael@0: } michael@0: michael@0: // Lazy script caching is only supported for leaf functions. If a michael@0: // script with inner functions was returned by the cache, those inner michael@0: // functions would be delazified when deep cloning the script, even if michael@0: // they have never executed. michael@0: // michael@0: // Additionally, the lazy script cache is not used during incremental michael@0: // GCs, to avoid resurrecting dead scripts after incremental sweeping michael@0: // has started. michael@0: if (!lazy->numInnerFunctions() && !JS::IsIncrementalGCInProgress(cx->runtime())) { michael@0: LazyScriptCache::Lookup lookup(cx, lazy); michael@0: cx->runtime()->lazyScriptCache.lookup(lookup, script.address()); michael@0: } michael@0: michael@0: if (script) { michael@0: RootedObject enclosingScope(cx, lazy->enclosingScope()); michael@0: RootedScript clonedScript(cx, CloneScript(cx, enclosingScope, fun, script)); michael@0: if (!clonedScript) michael@0: return false; michael@0: michael@0: clonedScript->setSourceObject(lazy->sourceObject()); michael@0: michael@0: fun->initAtom(script->functionNonDelazifying()->displayAtom()); michael@0: clonedScript->setFunction(fun); michael@0: michael@0: fun->setUnlazifiedScript(clonedScript); michael@0: michael@0: CallNewScriptHook(cx, clonedScript, fun); michael@0: michael@0: if (!lazy->maybeScript()) michael@0: lazy->initScript(clonedScript); michael@0: return true; michael@0: } michael@0: michael@0: JS_ASSERT(lazy->source()->hasSourceData()); michael@0: michael@0: // Parse and compile the script from source. michael@0: SourceDataCache::AutoHoldEntry holder; michael@0: const jschar *chars = lazy->source()->chars(cx, holder); michael@0: if (!chars) michael@0: return false; michael@0: michael@0: const jschar *lazyStart = chars + lazy->begin(); michael@0: size_t lazyLength = lazy->end() - lazy->begin(); michael@0: michael@0: if (!frontend::CompileLazyFunction(cx, lazy, lazyStart, lazyLength)) michael@0: return false; michael@0: michael@0: script = fun->nonLazyScript(); michael@0: michael@0: // Remember the compiled script on the lazy script itself, in case michael@0: // there are clones of the function still pointing to the lazy script. michael@0: if (!lazy->maybeScript()) michael@0: lazy->initScript(script); michael@0: michael@0: // Try to insert the newly compiled script into the lazy script cache. michael@0: if (!lazy->numInnerFunctions()) { michael@0: // A script's starting column isn't set by the bytecode emitter, so michael@0: // specify this from the lazy script so that if an identical lazy michael@0: // script is encountered later a match can be determined. michael@0: script->setColumn(lazy->column()); michael@0: michael@0: LazyScriptCache::Lookup lookup(cx, lazy); michael@0: cx->runtime()->lazyScriptCache.insert(lookup, script); michael@0: michael@0: // Remember the lazy script on the compiled script, so it can be michael@0: // stored on the function again in case of re-lazification. michael@0: // Only functions without inner functions are re-lazified. michael@0: script->setLazyScript(lazy); michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: /* Lazily cloned self-hosted script. */ michael@0: JS_ASSERT(fun->isSelfHostedBuiltin()); michael@0: RootedAtom funAtom(cx, &fun->getExtendedSlot(0).toString()->asAtom()); michael@0: if (!funAtom) michael@0: return false; michael@0: Rooted funName(cx, funAtom->asPropertyName()); michael@0: return cx->runtime()->cloneSelfHostedFunctionScript(cx, funName, fun); michael@0: } michael@0: michael@0: void michael@0: JSFunction::relazify(JSTracer *trc) michael@0: { michael@0: JSScript *script = nonLazyScript(); michael@0: JS_ASSERT(script->isRelazifiable()); michael@0: JS_ASSERT(!compartment()->hasBeenEntered()); michael@0: JS_ASSERT(!compartment()->debugMode()); michael@0: michael@0: // If the script's canonical function isn't lazy, we have to mark the michael@0: // script. Otherwise, the following scenario would leave it unmarked michael@0: // and cause it to be swept while a function is still expecting it to be michael@0: // valid: michael@0: // 1. an incremental GC slice causes the canonical function to relazify michael@0: // 2. a clone is used and delazifies the canonical function michael@0: // 3. another GC slice causes the clone to relazify michael@0: // The result is that no function marks the script, but the canonical michael@0: // function expects it to be valid. michael@0: if (script->functionNonDelazifying()->hasScript()) michael@0: MarkScriptUnbarriered(trc, &u.i.s.script_, "script"); michael@0: michael@0: flags_ &= ~INTERPRETED; michael@0: flags_ |= INTERPRETED_LAZY; michael@0: LazyScript *lazy = script->maybeLazyScript(); michael@0: u.i.s.lazy_ = lazy; michael@0: if (lazy) { michael@0: JS_ASSERT(!isSelfHostedBuiltin()); michael@0: // If this is the script stored in the lazy script to be cloned michael@0: // for un-lazifying other functions, reset it so the script can michael@0: // be freed. michael@0: if (lazy->maybeScript() == script) michael@0: lazy->resetScript(); michael@0: MarkLazyScriptUnbarriered(trc, &u.i.s.lazy_, "lazyScript"); michael@0: } else { michael@0: JS_ASSERT(isSelfHostedBuiltin()); michael@0: JS_ASSERT(isExtended()); michael@0: JS_ASSERT(getExtendedSlot(0).toString()->isAtom()); michael@0: } michael@0: } michael@0: michael@0: /* ES5 15.3.4.5.1 and 15.3.4.5.2. */ michael@0: bool michael@0: js::CallOrConstructBoundFunction(JSContext *cx, unsigned argc, Value *vp) michael@0: { michael@0: CallArgs args = CallArgsFromVp(argc, vp); michael@0: RootedFunction fun(cx, &args.callee().as()); michael@0: JS_ASSERT(fun->isBoundFunction()); michael@0: michael@0: /* 15.3.4.5.1 step 1, 15.3.4.5.2 step 3. */ michael@0: unsigned argslen = fun->getBoundFunctionArgumentCount(); michael@0: michael@0: if (args.length() + argslen > ARGS_LENGTH_MAX) { michael@0: js_ReportAllocationOverflow(cx); michael@0: return false; michael@0: } michael@0: michael@0: /* 15.3.4.5.1 step 3, 15.3.4.5.2 step 1. */ michael@0: RootedObject target(cx, fun->getBoundFunctionTarget()); michael@0: michael@0: /* 15.3.4.5.1 step 2. */ michael@0: const Value &boundThis = fun->getBoundFunctionThis(); michael@0: michael@0: InvokeArgs invokeArgs(cx); michael@0: if (!invokeArgs.init(args.length() + argslen)) michael@0: return false; michael@0: michael@0: /* 15.3.4.5.1, 15.3.4.5.2 step 4. */ michael@0: for (unsigned i = 0; i < argslen; i++) michael@0: invokeArgs[i].set(fun->getBoundFunctionArgument(i)); michael@0: PodCopy(invokeArgs.array() + argslen, vp + 2, args.length()); michael@0: michael@0: /* 15.3.4.5.1, 15.3.4.5.2 step 5. */ michael@0: invokeArgs.setCallee(ObjectValue(*target)); michael@0: michael@0: bool constructing = args.isConstructing(); michael@0: if (!constructing) michael@0: invokeArgs.setThis(boundThis); michael@0: michael@0: if (constructing ? !InvokeConstructor(cx, invokeArgs) : !Invoke(cx, invokeArgs)) michael@0: return false; michael@0: michael@0: args.rval().set(invokeArgs.rval()); michael@0: return true; michael@0: } michael@0: michael@0: static bool michael@0: fun_isGenerator(JSContext *cx, unsigned argc, Value *vp) michael@0: { michael@0: CallArgs args = CallArgsFromVp(argc, vp); michael@0: JSFunction *fun; michael@0: if (!IsFunctionObject(args.thisv(), &fun)) { michael@0: args.rval().setBoolean(false); michael@0: return true; michael@0: } michael@0: michael@0: args.rval().setBoolean(fun->isGenerator()); michael@0: return true; michael@0: } michael@0: michael@0: /* ES5 15.3.4.5. */ michael@0: static bool michael@0: fun_bind(JSContext *cx, unsigned argc, Value *vp) michael@0: { michael@0: CallArgs args = CallArgsFromVp(argc, vp); michael@0: michael@0: /* Step 1. */ michael@0: Value thisv = args.thisv(); michael@0: michael@0: /* Step 2. */ michael@0: if (!js_IsCallable(thisv)) { michael@0: ReportIncompatibleMethod(cx, args, &JSFunction::class_); michael@0: return false; michael@0: } michael@0: michael@0: /* Step 3. */ michael@0: Value *boundArgs = nullptr; michael@0: unsigned argslen = 0; michael@0: if (args.length() > 1) { michael@0: boundArgs = args.array() + 1; michael@0: argslen = args.length() - 1; michael@0: } michael@0: michael@0: /* Steps 7-9. */ michael@0: RootedValue thisArg(cx, args.length() >= 1 ? args[0] : UndefinedValue()); michael@0: RootedObject target(cx, &thisv.toObject()); michael@0: JSObject *boundFunction = js_fun_bind(cx, target, thisArg, boundArgs, argslen); michael@0: if (!boundFunction) michael@0: return false; michael@0: michael@0: /* Step 22. */ michael@0: args.rval().setObject(*boundFunction); michael@0: return true; michael@0: } michael@0: michael@0: JSObject* michael@0: js_fun_bind(JSContext *cx, HandleObject target, HandleValue thisArg, michael@0: Value *boundArgs, unsigned argslen) michael@0: { michael@0: /* Steps 15-16. */ michael@0: unsigned length = 0; michael@0: if (target->is()) { michael@0: unsigned nargs = target->as().nargs(); michael@0: if (nargs > argslen) michael@0: length = nargs - argslen; michael@0: } michael@0: michael@0: /* Step 4-6, 10-11. */ michael@0: RootedAtom name(cx, target->is() ? target->as().atom() : nullptr); michael@0: michael@0: RootedObject funobj(cx, NewFunction(cx, js::NullPtr(), CallOrConstructBoundFunction, length, michael@0: JSFunction::NATIVE_CTOR, target, name)); michael@0: if (!funobj) michael@0: return nullptr; michael@0: michael@0: /* NB: Bound functions abuse |parent| to store their target. */ michael@0: if (!JSObject::setParent(cx, funobj, target)) michael@0: return nullptr; michael@0: michael@0: if (!funobj->as().initBoundFunction(cx, thisArg, boundArgs, argslen)) michael@0: return nullptr; michael@0: michael@0: /* Steps 17, 19-21 are handled by fun_resolve. */ michael@0: /* Step 18 is the default for new functions. */ michael@0: return funobj; michael@0: } michael@0: michael@0: /* michael@0: * Report "malformed formal parameter" iff no illegal char or similar scanner michael@0: * error was already reported. michael@0: */ michael@0: static bool michael@0: OnBadFormal(JSContext *cx, TokenKind tt) michael@0: { michael@0: if (tt != TOK_ERROR) michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_FORMAL); michael@0: else michael@0: JS_ASSERT(cx->isExceptionPending()); michael@0: return false; michael@0: } michael@0: michael@0: const JSFunctionSpec js::function_methods[] = { michael@0: #if JS_HAS_TOSOURCE michael@0: JS_FN(js_toSource_str, fun_toSource, 0,0), michael@0: #endif michael@0: JS_FN(js_toString_str, fun_toString, 0,0), michael@0: JS_FN(js_apply_str, js_fun_apply, 2,0), michael@0: JS_FN(js_call_str, js_fun_call, 1,0), michael@0: JS_FN("bind", fun_bind, 1,0), michael@0: JS_FN("isGenerator", fun_isGenerator,0,0), michael@0: JS_FS_END michael@0: }; michael@0: michael@0: static bool michael@0: FunctionConstructor(JSContext *cx, unsigned argc, Value *vp, GeneratorKind generatorKind) michael@0: { michael@0: CallArgs args = CallArgsFromVp(argc, vp); michael@0: RootedString arg(cx); // used multiple times below michael@0: michael@0: /* Block this call if security callbacks forbid it. */ michael@0: Rooted global(cx, &args.callee().global()); michael@0: if (!GlobalObject::isRuntimeCodeGenEnabled(cx, global)) { michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CSP_BLOCKED_FUNCTION); michael@0: return false; michael@0: } michael@0: michael@0: AutoKeepAtoms keepAtoms(cx->perThreadData); michael@0: AutoNameVector formals(cx); michael@0: michael@0: bool hasRest = false; michael@0: michael@0: bool isStarGenerator = generatorKind == StarGenerator; michael@0: JS_ASSERT(generatorKind != LegacyGenerator); michael@0: michael@0: RootedScript maybeScript(cx); michael@0: const char *filename; michael@0: unsigned lineno; michael@0: JSPrincipals *originPrincipals; michael@0: uint32_t pcOffset; michael@0: DescribeScriptedCallerForCompilation(cx, &maybeScript, &filename, &lineno, &pcOffset, michael@0: &originPrincipals); michael@0: michael@0: const char *introductionType = "Function"; michael@0: if (generatorKind != NotGenerator) michael@0: introductionType = "GeneratorFunction"; michael@0: michael@0: const char *introducerFilename = filename; michael@0: if (maybeScript && maybeScript->scriptSource()->introducerFilename()) michael@0: introducerFilename = maybeScript->scriptSource()->introducerFilename(); michael@0: michael@0: CompileOptions options(cx); michael@0: options.setOriginPrincipals(originPrincipals) michael@0: .setFileAndLine(filename, 1) michael@0: .setNoScriptRval(false) michael@0: .setCompileAndGo(true) michael@0: .setIntroductionInfo(introducerFilename, introductionType, lineno, maybeScript, pcOffset); michael@0: michael@0: unsigned n = args.length() ? args.length() - 1 : 0; michael@0: if (n > 0) { michael@0: /* michael@0: * Collect the function-argument arguments into one string, separated michael@0: * by commas, then make a tokenstream from that string, and scan it to michael@0: * get the arguments. We need to throw the full scanner at the michael@0: * problem, because the argument string can legitimately contain michael@0: * comments and linefeeds. XXX It might be better to concatenate michael@0: * everything up into a function definition and pass it to the michael@0: * compiler, but doing it this way is less of a delta from the old michael@0: * code. See ECMA 15.3.2.1. michael@0: */ michael@0: size_t args_length = 0; michael@0: for (unsigned i = 0; i < n; i++) { michael@0: /* Collect the lengths for all the function-argument arguments. */ michael@0: arg = ToString(cx, args[i]); michael@0: if (!arg) michael@0: return false; michael@0: args[i].setString(arg); michael@0: michael@0: /* michael@0: * Check for overflow. The < test works because the maximum michael@0: * JSString length fits in 2 fewer bits than size_t has. michael@0: */ michael@0: size_t old_args_length = args_length; michael@0: args_length = old_args_length + arg->length(); michael@0: if (args_length < old_args_length) { michael@0: js_ReportAllocationOverflow(cx); michael@0: return false; michael@0: } michael@0: } michael@0: michael@0: /* Add 1 for each joining comma and check for overflow (two ways). */ michael@0: size_t old_args_length = args_length; michael@0: args_length = old_args_length + n - 1; michael@0: if (args_length < old_args_length || michael@0: args_length >= ~(size_t)0 / sizeof(jschar)) { michael@0: js_ReportAllocationOverflow(cx); michael@0: return false; michael@0: } michael@0: michael@0: /* michael@0: * Allocate a string to hold the concatenated arguments, including room michael@0: * for a terminating 0. Mark cx->tempLifeAlloc for later release, to michael@0: * free collected_args and its tokenstream in one swoop. michael@0: */ michael@0: LifoAllocScope las(&cx->tempLifoAlloc()); michael@0: jschar *cp = cx->tempLifoAlloc().newArray(args_length + 1); michael@0: if (!cp) { michael@0: js_ReportOutOfMemory(cx); michael@0: return false; michael@0: } michael@0: ConstTwoByteChars collected_args(cp, args_length + 1); michael@0: michael@0: /* michael@0: * Concatenate the arguments into the new string, separated by commas. michael@0: */ michael@0: for (unsigned i = 0; i < n; i++) { michael@0: arg = args[i].toString(); michael@0: size_t arg_length = arg->length(); michael@0: const jschar *arg_chars = arg->getChars(cx); michael@0: if (!arg_chars) michael@0: return false; michael@0: (void) js_strncpy(cp, arg_chars, arg_length); michael@0: cp += arg_length; michael@0: michael@0: /* Add separating comma or terminating 0. */ michael@0: *cp++ = (i + 1 < n) ? ',' : 0; michael@0: } michael@0: michael@0: /* michael@0: * Initialize a tokenstream that reads from the given string. No michael@0: * StrictModeGetter is needed because this TokenStream won't report any michael@0: * strict mode errors. Any strict mode errors which might be reported michael@0: * here (duplicate argument names, etc.) will be detected when we michael@0: * compile the function body. michael@0: */ michael@0: TokenStream ts(cx, options, collected_args.get(), args_length, michael@0: /* strictModeGetter = */ nullptr); michael@0: bool yieldIsValidName = ts.versionNumber() < JSVERSION_1_7 && !isStarGenerator; michael@0: michael@0: /* The argument string may be empty or contain no tokens. */ michael@0: TokenKind tt = ts.getToken(); michael@0: if (tt != TOK_EOF) { michael@0: for (;;) { michael@0: /* michael@0: * Check that it's a name. This also implicitly guards against michael@0: * TOK_ERROR, which was already reported. michael@0: */ michael@0: if (hasRest) { michael@0: ts.reportError(JSMSG_PARAMETER_AFTER_REST); michael@0: return false; michael@0: } michael@0: michael@0: if (tt == TOK_YIELD && yieldIsValidName) michael@0: tt = TOK_NAME; michael@0: michael@0: if (tt != TOK_NAME) { michael@0: if (tt == TOK_TRIPLEDOT) { michael@0: hasRest = true; michael@0: tt = ts.getToken(); michael@0: if (tt == TOK_YIELD && yieldIsValidName) michael@0: tt = TOK_NAME; michael@0: if (tt != TOK_NAME) { michael@0: if (tt != TOK_ERROR) michael@0: ts.reportError(JSMSG_NO_REST_NAME); michael@0: return false; michael@0: } michael@0: } else { michael@0: return OnBadFormal(cx, tt); michael@0: } michael@0: } michael@0: michael@0: if (!formals.append(ts.currentName())) michael@0: return false; michael@0: michael@0: /* michael@0: * Get the next token. Stop on end of stream. Otherwise michael@0: * insist on a comma, get another name, and iterate. michael@0: */ michael@0: tt = ts.getToken(); michael@0: if (tt == TOK_EOF) michael@0: break; michael@0: if (tt != TOK_COMMA) michael@0: return OnBadFormal(cx, tt); michael@0: tt = ts.getToken(); michael@0: } michael@0: } michael@0: } michael@0: michael@0: #ifdef DEBUG michael@0: for (unsigned i = 0; i < formals.length(); ++i) { michael@0: JSString *str = formals[i]; michael@0: JS_ASSERT(str->asAtom().asPropertyName() == formals[i]); michael@0: } michael@0: #endif michael@0: michael@0: RootedString str(cx); michael@0: if (!args.length()) michael@0: str = cx->runtime()->emptyString; michael@0: else michael@0: str = ToString(cx, args[args.length() - 1]); michael@0: if (!str) michael@0: return false; michael@0: JSLinearString *linear = str->ensureLinear(cx); michael@0: if (!linear) michael@0: return false; michael@0: michael@0: JS::Anchor strAnchor(str); michael@0: const jschar *chars = linear->chars(); michael@0: size_t length = linear->length(); michael@0: michael@0: /* michael@0: * NB: (new Function) is not lexically closed by its caller, it's just an michael@0: * anonymous function in the top-level scope that its constructor inhabits. michael@0: * Thus 'var x = 42; f = new Function("return x"); print(f())' prints 42, michael@0: * and so would a call to f from another top-level's script or function. michael@0: */ michael@0: RootedAtom anonymousAtom(cx, cx->names().anonymous); michael@0: JSObject *proto = nullptr; michael@0: if (isStarGenerator) { michael@0: proto = GlobalObject::getOrCreateStarGeneratorFunctionPrototype(cx, global); michael@0: if (!proto) michael@0: return false; michael@0: } michael@0: RootedFunction fun(cx, NewFunctionWithProto(cx, js::NullPtr(), nullptr, 0, michael@0: JSFunction::INTERPRETED_LAMBDA, global, michael@0: anonymousAtom, proto, michael@0: JSFunction::FinalizeKind, TenuredObject)); michael@0: if (!fun) michael@0: return false; michael@0: michael@0: if (!JSFunction::setTypeForScriptedFunction(cx, fun)) michael@0: return false; michael@0: michael@0: if (hasRest) michael@0: fun->setHasRest(); michael@0: michael@0: bool ok; michael@0: SourceBufferHolder srcBuf(chars, length, SourceBufferHolder::NoOwnership); michael@0: if (isStarGenerator) michael@0: ok = frontend::CompileStarGeneratorBody(cx, &fun, options, formals, srcBuf); michael@0: else michael@0: ok = frontend::CompileFunctionBody(cx, &fun, options, formals, srcBuf); michael@0: args.rval().setObject(*fun); michael@0: return ok; michael@0: } michael@0: michael@0: bool michael@0: js::Function(JSContext *cx, unsigned argc, Value *vp) michael@0: { michael@0: return FunctionConstructor(cx, argc, vp, NotGenerator); michael@0: } michael@0: michael@0: bool michael@0: js::Generator(JSContext *cx, unsigned argc, Value *vp) michael@0: { michael@0: return FunctionConstructor(cx, argc, vp, StarGenerator); michael@0: } michael@0: michael@0: bool michael@0: JSFunction::isBuiltinFunctionConstructor() michael@0: { michael@0: return maybeNative() == Function || maybeNative() == Generator; michael@0: } michael@0: michael@0: JSFunction * michael@0: js::NewFunction(ExclusiveContext *cx, HandleObject funobjArg, Native native, unsigned nargs, michael@0: JSFunction::Flags flags, HandleObject parent, HandleAtom atom, michael@0: gc::AllocKind allocKind /* = JSFunction::FinalizeKind */, michael@0: NewObjectKind newKind /* = GenericObject */) michael@0: { michael@0: return NewFunctionWithProto(cx, funobjArg, native, nargs, flags, parent, atom, nullptr, michael@0: allocKind, newKind); michael@0: } michael@0: michael@0: JSFunction * michael@0: js::NewFunctionWithProto(ExclusiveContext *cx, HandleObject funobjArg, Native native, michael@0: unsigned nargs, JSFunction::Flags flags, HandleObject parent, michael@0: HandleAtom atom, JSObject *proto, michael@0: gc::AllocKind allocKind /* = JSFunction::FinalizeKind */, michael@0: NewObjectKind newKind /* = GenericObject */) michael@0: { michael@0: JS_ASSERT(allocKind == JSFunction::FinalizeKind || allocKind == JSFunction::ExtendedFinalizeKind); michael@0: JS_ASSERT(sizeof(JSFunction) <= gc::Arena::thingSize(JSFunction::FinalizeKind)); michael@0: JS_ASSERT(sizeof(FunctionExtended) <= gc::Arena::thingSize(JSFunction::ExtendedFinalizeKind)); michael@0: michael@0: RootedObject funobj(cx, funobjArg); michael@0: if (funobj) { michael@0: JS_ASSERT(funobj->is()); michael@0: JS_ASSERT(funobj->getParent() == parent); michael@0: JS_ASSERT_IF(native, funobj->hasSingletonType()); michael@0: } else { michael@0: // Don't give asm.js module functions a singleton type since they michael@0: // are cloned (via CloneFunctionObjectIfNotSingleton) which assumes michael@0: // that hasSingletonType implies isInterpreted. michael@0: if (native && !IsAsmJSModuleNative(native)) michael@0: newKind = SingletonObject; michael@0: funobj = NewObjectWithClassProto(cx, &JSFunction::class_, proto, michael@0: SkipScopeParent(parent), allocKind, newKind); michael@0: if (!funobj) michael@0: return nullptr; michael@0: } michael@0: RootedFunction fun(cx, &funobj->as()); michael@0: michael@0: if (allocKind == JSFunction::ExtendedFinalizeKind) michael@0: flags = JSFunction::Flags(flags | JSFunction::EXTENDED); michael@0: michael@0: /* Initialize all function members. */ michael@0: fun->setArgCount(uint16_t(nargs)); michael@0: fun->setFlags(flags); michael@0: if (fun->isInterpreted()) { michael@0: JS_ASSERT(!native); michael@0: fun->mutableScript().init(nullptr); michael@0: fun->initEnvironment(parent); michael@0: } else { michael@0: JS_ASSERT(fun->isNative()); michael@0: JS_ASSERT(native); michael@0: fun->initNative(native, nullptr); michael@0: } michael@0: if (allocKind == JSFunction::ExtendedFinalizeKind) michael@0: fun->initializeExtended(); michael@0: fun->initAtom(atom); michael@0: michael@0: return fun; michael@0: } michael@0: michael@0: JSFunction * michael@0: js::CloneFunctionObject(JSContext *cx, HandleFunction fun, HandleObject parent, gc::AllocKind allocKind, michael@0: NewObjectKind newKindArg /* = GenericObject */) michael@0: { michael@0: JS_ASSERT(parent); michael@0: JS_ASSERT(!fun->isBoundFunction()); michael@0: michael@0: bool useSameScript = cx->compartment() == fun->compartment() && michael@0: !fun->hasSingletonType() && michael@0: !types::UseNewTypeForClone(fun); michael@0: michael@0: if (!useSameScript && fun->isInterpretedLazy() && !fun->getOrCreateScript(cx)) michael@0: return nullptr; michael@0: michael@0: NewObjectKind newKind = useSameScript ? newKindArg : SingletonObject; michael@0: JSObject *cloneProto = nullptr; michael@0: if (fun->isStarGenerator()) { michael@0: cloneProto = GlobalObject::getOrCreateStarGeneratorFunctionPrototype(cx, cx->global()); michael@0: if (!cloneProto) michael@0: return nullptr; michael@0: } michael@0: JSObject *cloneobj = NewObjectWithClassProto(cx, &JSFunction::class_, cloneProto, michael@0: SkipScopeParent(parent), allocKind, newKind); michael@0: if (!cloneobj) michael@0: return nullptr; michael@0: RootedFunction clone(cx, &cloneobj->as()); michael@0: michael@0: uint16_t flags = fun->flags() & ~JSFunction::EXTENDED; michael@0: if (allocKind == JSFunction::ExtendedFinalizeKind) michael@0: flags |= JSFunction::EXTENDED; michael@0: michael@0: clone->setArgCount(fun->nargs()); michael@0: clone->setFlags(flags); michael@0: if (fun->hasScript()) { michael@0: clone->initScript(fun->nonLazyScript()); michael@0: clone->initEnvironment(parent); michael@0: } else if (fun->isInterpretedLazy()) { michael@0: LazyScript *lazy = fun->lazyScriptOrNull(); michael@0: clone->initLazyScript(lazy); michael@0: clone->initEnvironment(parent); michael@0: } else { michael@0: clone->initNative(fun->native(), fun->jitInfo()); michael@0: } michael@0: clone->initAtom(fun->displayAtom()); michael@0: michael@0: if (allocKind == JSFunction::ExtendedFinalizeKind) { michael@0: if (fun->isExtended() && fun->compartment() == cx->compartment()) { michael@0: for (unsigned i = 0; i < FunctionExtended::NUM_EXTENDED_SLOTS; i++) michael@0: clone->initExtendedSlot(i, fun->getExtendedSlot(i)); michael@0: } else { michael@0: clone->initializeExtended(); michael@0: } michael@0: } michael@0: michael@0: if (useSameScript) { michael@0: /* michael@0: * Clone the function, reusing its script. We can use the same type as michael@0: * the original function provided that its prototype is correct. michael@0: */ michael@0: if (fun->getProto() == clone->getProto()) michael@0: clone->setType(fun->type()); michael@0: return clone; michael@0: } michael@0: michael@0: RootedFunction cloneRoot(cx, clone); michael@0: michael@0: /* michael@0: * Across compartments we have to clone the script for interpreted michael@0: * functions. Cross-compartment cloning only happens via JSAPI michael@0: * (JS_CloneFunctionObject) which dynamically ensures that 'script' has michael@0: * no enclosing lexical scope (only the global scope). michael@0: */ michael@0: if (cloneRoot->isInterpreted() && !CloneFunctionScript(cx, fun, cloneRoot, newKindArg)) michael@0: return nullptr; michael@0: michael@0: return cloneRoot; michael@0: } michael@0: michael@0: JSFunction * michael@0: js::DefineFunction(JSContext *cx, HandleObject obj, HandleId id, Native native, michael@0: unsigned nargs, unsigned flags, AllocKind allocKind /* = FinalizeKind */, michael@0: NewObjectKind newKind /* = GenericObject */) michael@0: { michael@0: PropertyOp gop; michael@0: StrictPropertyOp sop; michael@0: michael@0: RootedFunction fun(cx); michael@0: michael@0: if (flags & JSFUN_STUB_GSOPS) { michael@0: /* michael@0: * JSFUN_STUB_GSOPS is a request flag only, not stored in fun->flags or michael@0: * the defined property's attributes. This allows us to encode another, michael@0: * internal flag using the same bit, JSFUN_EXPR_CLOSURE -- see jsfun.h michael@0: * for more on this. michael@0: */ michael@0: flags &= ~JSFUN_STUB_GSOPS; michael@0: gop = JS_PropertyStub; michael@0: sop = JS_StrictPropertyStub; michael@0: } else { michael@0: gop = nullptr; michael@0: sop = nullptr; michael@0: } michael@0: michael@0: JSFunction::Flags funFlags; michael@0: if (!native) michael@0: funFlags = JSFunction::INTERPRETED_LAZY; michael@0: else michael@0: funFlags = JSAPIToJSFunctionFlags(flags); michael@0: RootedAtom atom(cx, JSID_IS_ATOM(id) ? JSID_TO_ATOM(id) : nullptr); michael@0: fun = NewFunction(cx, NullPtr(), native, nargs, funFlags, obj, atom, allocKind, newKind); michael@0: if (!fun) michael@0: return nullptr; michael@0: michael@0: RootedValue funVal(cx, ObjectValue(*fun)); michael@0: if (!JSObject::defineGeneric(cx, obj, id, funVal, gop, sop, flags & ~JSFUN_FLAGS_MASK)) michael@0: return nullptr; michael@0: michael@0: return fun; michael@0: } michael@0: michael@0: bool michael@0: js::IsConstructor(const Value &v) michael@0: { michael@0: // Step 2. michael@0: if (!v.isObject()) michael@0: return false; michael@0: michael@0: // Step 3-4, a bit complex for us, since we have several flavors of michael@0: // [[Construct]] internal method. michael@0: JSObject &obj = v.toObject(); michael@0: if (obj.is()) { michael@0: JSFunction &fun = obj.as(); michael@0: return fun.isNativeConstructor() || fun.isInterpretedConstructor(); michael@0: } michael@0: return obj.getClass()->construct != nullptr; michael@0: } michael@0: michael@0: void michael@0: js::ReportIncompatibleMethod(JSContext *cx, CallReceiver call, const Class *clasp) michael@0: { michael@0: RootedValue thisv(cx, call.thisv()); michael@0: michael@0: #ifdef DEBUG michael@0: if (thisv.isObject()) { michael@0: JS_ASSERT(thisv.toObject().getClass() != clasp || michael@0: !thisv.toObject().isNative() || michael@0: !thisv.toObject().getProto() || michael@0: thisv.toObject().getProto()->getClass() != clasp); michael@0: } else if (thisv.isString()) { michael@0: JS_ASSERT(clasp != &StringObject::class_); michael@0: } else if (thisv.isNumber()) { michael@0: JS_ASSERT(clasp != &NumberObject::class_); michael@0: } else if (thisv.isBoolean()) { michael@0: JS_ASSERT(clasp != &BooleanObject::class_); michael@0: } else { michael@0: JS_ASSERT(thisv.isUndefined() || thisv.isNull()); michael@0: } michael@0: #endif michael@0: michael@0: if (JSFunction *fun = ReportIfNotFunction(cx, call.calleev())) { michael@0: JSAutoByteString funNameBytes; michael@0: if (const char *funName = GetFunctionNameBytes(cx, fun, &funNameBytes)) { michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_PROTO, michael@0: clasp->name, funName, InformalValueTypeName(thisv)); michael@0: } michael@0: } michael@0: } michael@0: michael@0: void michael@0: js::ReportIncompatible(JSContext *cx, CallReceiver call) michael@0: { michael@0: if (JSFunction *fun = ReportIfNotFunction(cx, call.calleev())) { michael@0: JSAutoByteString funNameBytes; michael@0: if (const char *funName = GetFunctionNameBytes(cx, fun, &funNameBytes)) { michael@0: JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_METHOD, michael@0: funName, "method", InformalValueTypeName(call.thisv())); michael@0: } michael@0: } michael@0: } michael@0: michael@0: bool michael@0: JSObject::hasIdempotentProtoChain() const michael@0: { michael@0: // Return false if obj (or an object on its proto chain) is non-native or michael@0: // has a resolve or lookup hook. michael@0: JSObject *obj = const_cast(this); michael@0: while (true) { michael@0: if (!obj->isNative()) michael@0: return false; michael@0: michael@0: JSResolveOp resolve = obj->getClass()->resolve; michael@0: if (resolve != JS_ResolveStub && resolve != (JSResolveOp) js::fun_resolve) michael@0: return false; michael@0: michael@0: if (obj->getOps()->lookupProperty || obj->getOps()->lookupGeneric || obj->getOps()->lookupElement) michael@0: return false; michael@0: michael@0: obj = obj->getProto(); michael@0: if (!obj) michael@0: return true; michael@0: } michael@0: michael@0: MOZ_ASSUME_UNREACHABLE("Should not get here"); michael@0: } michael@0: michael@0: namespace JS { michael@0: namespace detail { michael@0: michael@0: JS_PUBLIC_API(void) michael@0: CheckIsValidConstructible(Value calleev) michael@0: { michael@0: JSObject *callee = &calleev.toObject(); michael@0: if (callee->is()) michael@0: JS_ASSERT(callee->as().isNativeConstructor()); michael@0: else michael@0: JS_ASSERT(callee->getClass()->construct != nullptr); michael@0: } michael@0: michael@0: } // namespace detail michael@0: } // namespace JS