Bumping manifests a=b2g-bump
[gecko.git] / js / src / jsfun.cpp
blobc1bf646ce9ef7b03b38611aa81013255fdb0c588
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set ts=8 sts=4 et sw=4 tw=99:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /*
8 * JS function support.
9 */
11 #include "jsfuninlines.h"
13 #include "mozilla/ArrayUtils.h"
14 #include "mozilla/PodOperations.h"
15 #include "mozilla/Range.h"
17 #include <string.h>
19 #include "jsapi.h"
20 #include "jsarray.h"
21 #include "jsatom.h"
22 #include "jscntxt.h"
23 #include "jsobj.h"
24 #include "jsproxy.h"
25 #include "jsscript.h"
26 #include "jsstr.h"
27 #include "jstypes.h"
28 #include "jswrapper.h"
30 #include "builtin/Eval.h"
31 #include "builtin/Object.h"
32 #include "frontend/BytecodeCompiler.h"
33 #include "frontend/TokenStream.h"
34 #include "gc/Marking.h"
35 #include "jit/Ion.h"
36 #include "jit/JitFrameIterator.h"
37 #include "js/CallNonGenericMethod.h"
38 #include "vm/GlobalObject.h"
39 #include "vm/Interpreter.h"
40 #include "vm/Shape.h"
41 #include "vm/StringBuffer.h"
42 #include "vm/WrapperObject.h"
43 #include "vm/Xdr.h"
45 #include "jsscriptinlines.h"
47 #include "vm/Interpreter-inl.h"
48 #include "vm/Stack-inl.h"
50 using namespace js;
51 using namespace js::gc;
52 using namespace js::types;
53 using namespace js::frontend;
55 using mozilla::ArrayLength;
56 using mozilla::PodCopy;
57 using mozilla::RangedPtr;
59 static bool
60 fun_enumerate(JSContext* cx, HandleObject obj)
62 MOZ_ASSERT(obj->is<JSFunction>());
64 RootedId id(cx);
65 bool found;
67 if (!obj->isBoundFunction() && !obj->as<JSFunction>().isArrow()) {
68 id = NameToId(cx->names().prototype);
69 if (!JSObject::hasProperty(cx, obj, id, &found))
70 return false;
73 id = NameToId(cx->names().length);
74 if (!JSObject::hasProperty(cx, obj, id, &found))
75 return false;
77 id = NameToId(cx->names().name);
78 if (!JSObject::hasProperty(cx, obj, id, &found))
79 return false;
81 return true;
84 bool
85 IsFunction(HandleValue v)
87 return v.isObject() && v.toObject().is<JSFunction>();
90 static bool
91 AdvanceToActiveCallLinear(JSContext* cx, NonBuiltinScriptFrameIter& iter, HandleFunction fun)
93 MOZ_ASSERT(!fun->isBuiltin());
94 MOZ_ASSERT(!fun->isBoundFunction(), "all bound functions are currently native (ergo builtin)");
96 for (; !iter.done(); ++iter) {
97 if (!iter.isFunctionFrame() || iter.isEvalFrame())
98 continue;
99 if (iter.matchCallee(cx, fun))
100 return true;
102 return false;
105 static void
106 ThrowTypeErrorBehavior(JSContext* cx)
108 JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, js_GetErrorMessage, nullptr,
109 JSMSG_THROW_TYPE_ERROR);
112 // Beware: this function can be invoked on *any* function! That includes
113 // natives, strict mode functions, bound functions, arrow functions,
114 // self-hosted functions and constructors, asm.js functions, functions with
115 // destructuring arguments and/or a rest argument, and probably a few more I
116 // forgot. Turn back and save yourself while you still can. It's too late for
117 // me.
118 static bool
119 ArgumentsRestrictions(JSContext* cx, HandleFunction fun)
121 // Throw if the function is a builtin (note: this doesn't include asm.js),
122 // a strict mode function (FIXME: needs work handle strict asm.js functions
123 // correctly, should fall out of bug 1057208), or a bound function.
124 if (fun->isBuiltin() ||
125 (fun->isInterpreted() && fun->strict()) ||
126 fun->isBoundFunction())
128 ThrowTypeErrorBehavior(cx);
129 return false;
132 // Functions with rest arguments don't include a local |arguments| binding.
133 // Similarly, "arguments" shouldn't work on them.
134 if (fun->hasRest()) {
135 JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
136 JSMSG_FUNCTION_ARGUMENTS_AND_REST);
137 return false;
140 // Otherwise emit a strict warning about |f.arguments| to discourage use of
141 // this non-standard, performance-harmful feature.
142 if (!JS_ReportErrorFlagsAndNumber(cx, JSREPORT_WARNING | JSREPORT_STRICT, js_GetErrorMessage,
143 nullptr, JSMSG_DEPRECATED_USAGE, js_arguments_str))
145 return false;
148 return true;
151 bool
152 ArgumentsGetterImpl(JSContext* cx, CallArgs args)
154 MOZ_ASSERT(IsFunction(args.thisv()));
156 RootedFunction fun(cx, &args.thisv().toObject().as<JSFunction>());
157 if (!ArgumentsRestrictions(cx, fun))
158 return false;
160 // Return null if this function wasn't found on the stack.
161 NonBuiltinScriptFrameIter iter(cx);
162 if (!AdvanceToActiveCallLinear(cx, iter, fun)) {
163 args.rval().setNull();
164 return true;
167 Rooted<ArgumentsObject*> argsobj(cx, ArgumentsObject::createUnexpected(cx, iter));
168 if (!argsobj)
169 return false;
171 // Disabling compiling of this script in IonMonkey. IonMonkey doesn't
172 // guarantee |f.arguments| can be fully recovered, so we try to mitigate
173 // observing this behavior by detecting its use early.
174 JSScript* script = iter.script();
175 jit::ForbidCompilation(cx, script);
177 args.rval().setObject(*argsobj);
178 return true;
181 static bool
182 ArgumentsGetter(JSContext* cx, unsigned argc, Value* vp)
184 CallArgs args = CallArgsFromVp(argc, vp);
185 return CallNonGenericMethod<IsFunction, ArgumentsGetterImpl>(cx, args);
188 bool
189 ArgumentsSetterImpl(JSContext* cx, CallArgs args)
191 MOZ_ASSERT(IsFunction(args.thisv()));
193 RootedFunction fun(cx, &args.thisv().toObject().as<JSFunction>());
194 if (!ArgumentsRestrictions(cx, fun))
195 return false;
197 // If the function passes the gauntlet, return |undefined|.
198 args.rval().setUndefined();
199 return true;
202 static bool
203 ArgumentsSetter(JSContext* cx, unsigned argc, Value* vp)
205 CallArgs args = CallArgsFromVp(argc, vp);
206 return CallNonGenericMethod<IsFunction, ArgumentsSetterImpl>(cx, args);
209 // Beware: this function can be invoked on *any* function! That includes
210 // natives, strict mode functions, bound functions, arrow functions,
211 // self-hosted functions and constructors, asm.js functions, functions with
212 // destructuring arguments and/or a rest argument, and probably a few more I
213 // forgot. Turn back and save yourself while you still can. It's too late for
214 // me.
215 static bool
216 CallerRestrictions(JSContext* cx, HandleFunction fun)
218 // Throw if the function is a builtin (note: this doesn't include asm.js),
219 // a strict mode function (FIXME: needs work handle strict asm.js functions
220 // correctly, should fall out of bug 1057208), or a bound function.
221 if (fun->isBuiltin() ||
222 (fun->isInterpreted() && fun->strict()) ||
223 fun->isBoundFunction())
225 ThrowTypeErrorBehavior(cx);
226 return false;
229 // Otherwise emit a strict warning about |f.caller| to discourage use of
230 // this non-standard, performance-harmful feature.
231 if (!JS_ReportErrorFlagsAndNumber(cx, JSREPORT_WARNING | JSREPORT_STRICT, js_GetErrorMessage,
232 nullptr, JSMSG_DEPRECATED_USAGE, js_caller_str))
234 return false;
237 return true;
240 bool
241 CallerGetterImpl(JSContext* cx, CallArgs args)
243 MOZ_ASSERT(IsFunction(args.thisv()));
245 // Beware! This function can be invoked on *any* function! It can't
246 // assume it'll never be invoked on natives, strict mode functions, bound
247 // functions, or anything else that ordinarily has immutable .caller
248 // defined with [[ThrowTypeError]].
249 RootedFunction fun(cx, &args.thisv().toObject().as<JSFunction>());
250 if (!CallerRestrictions(cx, fun))
251 return false;
253 // Also return null if this function wasn't found on the stack.
254 NonBuiltinScriptFrameIter iter(cx);
255 if (!AdvanceToActiveCallLinear(cx, iter, fun)) {
256 args.rval().setNull();
257 return true;
260 ++iter;
261 if (iter.done() || !iter.isFunctionFrame()) {
262 args.rval().setNull();
263 return true;
266 // It might seem we need to replace call site clones with the original
267 // functions here. But we're iterating over *non-builtin* frames, and the
268 // only call site-clonable scripts are for builtin, self-hosted functions
269 // (see assertions in js::CloneFunctionAtCallsite). So the callee can't be
270 // a call site clone.
271 JSFunction* maybeClone = iter.callee(cx);
272 MOZ_ASSERT(!maybeClone->nonLazyScript()->isCallsiteClone(),
273 "non-builtin functions aren't call site-clonable");
275 RootedObject caller(cx, maybeClone);
276 if (!cx->compartment()->wrap(cx, &caller))
277 return false;
279 // Censor the caller if we don't have full access to it. If we do, but the
280 // caller is a function with strict mode code, throw a TypeError per ES5.
281 // If we pass these checks, we can return the computed caller.
283 JSObject* callerObj = CheckedUnwrap(caller);
284 if (!callerObj) {
285 args.rval().setNull();
286 return true;
289 JSFunction* callerFun = &callerObj->as<JSFunction>();
290 MOZ_ASSERT(!callerFun->isBuiltin(), "non-builtin iterator returned a builtin?");
292 if (callerFun->strict()) {
293 JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, js_GetErrorMessage, nullptr,
294 JSMSG_CALLER_IS_STRICT);
295 return false;
299 args.rval().setObject(*caller);
300 return true;
303 static bool
304 CallerGetter(JSContext* cx, unsigned argc, Value* vp)
306 CallArgs args = CallArgsFromVp(argc, vp);
307 return CallNonGenericMethod<IsFunction, CallerGetterImpl>(cx, args);
310 bool
311 CallerSetterImpl(JSContext* cx, CallArgs args)
313 MOZ_ASSERT(IsFunction(args.thisv()));
315 // Beware! This function can be invoked on *any* function! It can't
316 // assume it'll never be invoked on natives, strict mode functions, bound
317 // functions, or anything else that ordinarily has immutable .caller
318 // defined with [[ThrowTypeError]].
319 RootedFunction fun(cx, &args.thisv().toObject().as<JSFunction>());
320 if (!CallerRestrictions(cx, fun))
321 return false;
323 // Return |undefined| unless an error must be thrown.
324 args.rval().setUndefined();
326 // We can almost just return |undefined| here -- but if the caller function
327 // was strict mode code, we still have to throw a TypeError. This requires
328 // computing the caller, checking that no security boundaries are crossed,
329 // and throwing a TypeError if the resulting caller is strict.
331 NonBuiltinScriptFrameIter iter(cx);
332 if (!AdvanceToActiveCallLinear(cx, iter, fun))
333 return true;
335 ++iter;
336 if (iter.done() || !iter.isFunctionFrame())
337 return true;
339 // It might seem we need to replace call site clones with the original
340 // functions here. But we're iterating over *non-builtin* frames, and the
341 // only call site-clonable scripts are for builtin, self-hosted functions
342 // (see assertions in js::CloneFunctionAtCallsite). So the callee can't be
343 // a call site clone.
344 JSFunction* maybeClone = iter.callee(cx);
345 MOZ_ASSERT(!maybeClone->nonLazyScript()->isCallsiteClone(),
346 "non-builtin functions aren't call site-clonable");
348 RootedObject caller(cx, maybeClone);
349 if (!cx->compartment()->wrap(cx, &caller)) {
350 cx->clearPendingException();
351 return true;
354 // If we don't have full access to the caller, or the caller is not strict,
355 // return undefined. Otherwise throw a TypeError.
356 JSObject* callerObj = CheckedUnwrap(caller);
357 if (!callerObj)
358 return true;
360 JSFunction* callerFun = &callerObj->as<JSFunction>();
361 MOZ_ASSERT(!callerFun->isBuiltin(), "non-builtin iterator returned a builtin?");
363 if (callerFun->strict()) {
364 JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, js_GetErrorMessage, nullptr,
365 JSMSG_CALLER_IS_STRICT);
366 return false;
369 return true;
372 static bool
373 CallerSetter(JSContext* cx, unsigned argc, Value* vp)
375 CallArgs args = CallArgsFromVp(argc, vp);
376 return CallNonGenericMethod<IsFunction, CallerSetterImpl>(cx, args);
379 static const JSPropertySpec function_properties[] = {
380 JS_PSGS("arguments", ArgumentsGetter, ArgumentsSetter, 0),
381 JS_PSGS("caller", CallerGetter, CallerSetter, 0),
382 JS_PS_END
385 static JSObject*
386 ResolveInterpretedFunctionPrototype(JSContext* cx, HandleObject obj)
388 #ifdef DEBUG
389 JSFunction* fun = &obj->as<JSFunction>();
390 MOZ_ASSERT(fun->isInterpreted() || fun->isAsmJSNative());
391 MOZ_ASSERT(!fun->isFunctionPrototype());
392 #endif
394 // Assert that fun is not a compiler-created function object, which
395 // must never leak to script or embedding code and then be mutated.
396 // Also assert that obj is not bound, per the ES5 15.3.4.5 ref above.
397 MOZ_ASSERT(!IsInternalFunctionObject(obj));
398 MOZ_ASSERT(!obj->isBoundFunction());
400 // Make the prototype object an instance of Object with the same parent as
401 // the function object itself, unless the function is an ES6 generator. In
402 // that case, per the 15 July 2013 ES6 draft, section 15.19.3, its parent is
403 // the GeneratorObjectPrototype singleton.
404 bool isStarGenerator = obj->as<JSFunction>().isStarGenerator();
405 Rooted<GlobalObject*> global(cx, &obj->global());
406 JSObject* objProto;
407 if (isStarGenerator)
408 objProto = GlobalObject::getOrCreateStarGeneratorObjectPrototype(cx, global);
409 else
410 objProto = obj->global().getOrCreateObjectPrototype(cx);
411 if (!objProto)
412 return nullptr;
414 RootedPlainObject proto(cx, NewObjectWithGivenProto<PlainObject>(cx, objProto,
415 nullptr, SingletonObject));
416 if (!proto)
417 return nullptr;
419 // Per ES5 15.3.5.2 a user-defined function's .prototype property is
420 // initially non-configurable, non-enumerable, and writable.
421 RootedValue protoVal(cx, ObjectValue(*proto));
422 if (!JSObject::defineProperty(cx, obj, cx->names().prototype, protoVal, nullptr, nullptr,
423 JSPROP_PERMANENT))
425 return nullptr;
428 // Per ES5 13.2 the prototype's .constructor property is configurable,
429 // non-enumerable, and writable. However, per the 15 July 2013 ES6 draft,
430 // section 15.19.3, the .prototype of a generator function does not link
431 // back with a .constructor.
432 if (!isStarGenerator) {
433 RootedValue objVal(cx, ObjectValue(*obj));
434 if (!JSObject::defineProperty(cx, proto, cx->names().constructor, objVal, nullptr, nullptr,
437 return nullptr;
441 return proto;
444 bool
445 js::FunctionHasResolveHook(const JSAtomState& atomState, jsid id)
447 if (!JSID_IS_ATOM(id))
448 return false;
450 JSAtom* atom = JSID_TO_ATOM(id);
451 return atom == atomState.prototype || atom == atomState.length || atom == atomState.name;
454 bool
455 js::fun_resolve(JSContext* cx, HandleObject obj, HandleId id, bool* resolvedp)
457 if (!JSID_IS_ATOM(id))
458 return true;
460 RootedFunction fun(cx, &obj->as<JSFunction>());
462 if (JSID_IS_ATOM(id, cx->names().prototype)) {
464 * Built-in functions do not have a .prototype property per ECMA-262,
465 * or (Object.prototype, Function.prototype, etc.) have that property
466 * created eagerly.
468 * ES5 15.3.4: the non-native function object named Function.prototype
469 * does not have a .prototype property.
471 * ES5 15.3.4.5: bound functions don't have a prototype property. The
472 * isBuiltin() test covers this case because bound functions are native
473 * (and thus built-in) functions by definition/construction.
475 * ES6 19.2.4.3: arrow functions also don't have a prototype property.
477 if (fun->isBuiltin() || fun->isArrow() || fun->isFunctionPrototype())
478 return true;
480 if (!ResolveInterpretedFunctionPrototype(cx, fun))
481 return false;
483 *resolvedp = true;
484 return true;
487 bool isLength = JSID_IS_ATOM(id, cx->names().length);
488 if (isLength || JSID_IS_ATOM(id, cx->names().name)) {
489 MOZ_ASSERT(!IsInternalFunctionObject(obj));
491 RootedValue v(cx);
492 uint32_t attrs;
493 if (isLength) {
494 // Since f.length is configurable, it could be resolved and then deleted:
495 // function f(x) {}
496 // assertEq(f.length, 1);
497 // delete f.length;
498 // Afterwards, asking for f.length again will cause this resolve
499 // hook to run again. Defining the property again the second
500 // time through would be a bug.
501 // assertEq(f.length, 0); // gets Function.prototype.length!
502 // We use the RESOLVED_LENGTH flag as a hack to prevent this bug.
503 if (fun->hasResolvedLength())
504 return true;
506 if (fun->isInterpretedLazy() && !fun->getOrCreateScript(cx))
507 return false;
508 uint16_t length = fun->hasScript() ? fun->nonLazyScript()->funLength() :
509 fun->nargs() - fun->hasRest();
510 v.setInt32(length);
511 attrs = JSPROP_READONLY;
512 } else {
513 v.setString(fun->atom() == nullptr ? cx->runtime()->emptyString : fun->atom());
514 attrs = JSPROP_READONLY | JSPROP_PERMANENT;
517 if (!DefineNativeProperty(cx, fun, id, v, nullptr, nullptr, attrs))
518 return false;
520 if (isLength)
521 fun->setResolvedLength();
523 *resolvedp = true;
524 return true;
527 return true;
530 template<XDRMode mode>
531 bool
532 js::XDRInterpretedFunction(XDRState<mode>* xdr, HandleObject enclosingScope, HandleScript enclosingScript,
533 MutableHandleFunction objp)
535 enum FirstWordFlag {
536 HasAtom = 0x1,
537 IsStarGenerator = 0x2,
538 IsLazy = 0x4,
539 HasSingletonType = 0x8
542 /* NB: Keep this in sync with CloneFunctionAndScript. */
543 RootedAtom atom(xdr->cx());
544 uint32_t firstword = 0; /* bitmask of FirstWordFlag */
545 uint32_t flagsword = 0; /* word for argument count and fun->flags */
547 JSContext* cx = xdr->cx();
548 RootedFunction fun(cx);
549 RootedScript script(cx);
550 Rooted<LazyScript*> lazy(cx);
552 if (mode == XDR_ENCODE) {
553 fun = objp;
554 if (!fun->isInterpreted()) {
555 JSAutoByteString funNameBytes;
556 if (const char* name = GetFunctionNameBytes(cx, fun, &funNameBytes)) {
557 JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
558 JSMSG_NOT_SCRIPTED_FUNCTION, name);
560 return false;
563 if (fun->atom() || fun->hasGuessedAtom())
564 firstword |= HasAtom;
566 if (fun->isStarGenerator())
567 firstword |= IsStarGenerator;
569 if (fun->isInterpretedLazy()) {
570 // This can only happen for re-lazified cloned functions, so this
571 // does not apply to any JSFunction produced by the parser, only to
572 // JSFunction created by the runtime.
573 MOZ_ASSERT(!fun->lazyScript()->maybeScript());
575 // Encode a lazy script.
576 firstword |= IsLazy;
577 lazy = fun->lazyScript();
578 } else {
579 // Encode the script.
580 script = fun->nonLazyScript();
583 if (fun->hasSingletonType())
584 firstword |= HasSingletonType;
586 atom = fun->displayAtom();
587 flagsword = (fun->nargs() << 16) | fun->flags();
589 // The environment of any function which is not reused will always be
590 // null, it is later defined when a function is cloned or reused to
591 // mirror the scope chain.
592 MOZ_ASSERT_IF(fun->hasSingletonType() &&
593 !((lazy && lazy->hasBeenCloned()) || (script && script->hasBeenCloned())),
594 fun->environment() == nullptr);
597 if (!xdr->codeUint32(&firstword))
598 return false;
600 if ((firstword & HasAtom) && !XDRAtom(xdr, &atom))
601 return false;
602 if (!xdr->codeUint32(&flagsword))
603 return false;
605 if (mode == XDR_DECODE) {
606 JSObject* proto = nullptr;
607 if (firstword & IsStarGenerator) {
608 proto = GlobalObject::getOrCreateStarGeneratorFunctionPrototype(cx, cx->global());
609 if (!proto)
610 return false;
613 gc::AllocKind allocKind = JSFunction::FinalizeKind;
614 if (uint16_t(flagsword) & JSFunction::EXTENDED)
615 allocKind = JSFunction::ExtendedFinalizeKind;
616 fun = NewFunctionWithProto(cx, NullPtr(), nullptr, 0, JSFunction::INTERPRETED,
617 /* parent = */ NullPtr(), NullPtr(), proto,
618 allocKind, TenuredObject);
619 if (!fun)
620 return false;
621 script = nullptr;
624 if (firstword & IsLazy) {
625 if (!XDRLazyScript(xdr, enclosingScope, enclosingScript, fun, &lazy))
626 return false;
627 } else {
628 if (!XDRScript(xdr, enclosingScope, enclosingScript, fun, &script))
629 return false;
632 if (mode == XDR_DECODE) {
633 fun->setArgCount(flagsword >> 16);
634 fun->setFlags(uint16_t(flagsword));
635 fun->initAtom(atom);
636 if (firstword & IsLazy) {
637 fun->initLazyScript(lazy);
638 } else {
639 fun->initScript(script);
640 script->setFunction(fun);
641 MOZ_ASSERT(fun->nargs() == script->bindings.numArgs());
644 bool singleton = firstword & HasSingletonType;
645 if (!JSFunction::setTypeForScriptedFunction(cx, fun, singleton))
646 return false;
647 objp.set(fun);
650 return true;
653 template bool
654 js::XDRInterpretedFunction(XDRState<XDR_ENCODE>*, HandleObject, HandleScript, MutableHandleFunction);
656 template bool
657 js::XDRInterpretedFunction(XDRState<XDR_DECODE>*, HandleObject, HandleScript, MutableHandleFunction);
659 JSObject*
660 js::CloneFunctionAndScript(JSContext* cx, HandleObject enclosingScope, HandleFunction srcFun)
662 /* NB: Keep this in sync with XDRInterpretedFunction. */
663 JSObject* cloneProto = nullptr;
664 if (srcFun->isStarGenerator()) {
665 cloneProto = GlobalObject::getOrCreateStarGeneratorFunctionPrototype(cx, cx->global());
666 if (!cloneProto)
667 return nullptr;
670 gc::AllocKind allocKind = JSFunction::FinalizeKind;
671 if (srcFun->isExtended())
672 allocKind = JSFunction::ExtendedFinalizeKind;
673 RootedFunction clone(cx, NewFunctionWithProto(cx, NullPtr(), nullptr, 0,
674 JSFunction::INTERPRETED, NullPtr(), NullPtr(),
675 cloneProto, allocKind, TenuredObject));
676 if (!clone)
677 return nullptr;
679 RootedScript srcScript(cx, srcFun->getOrCreateScript(cx));
680 if (!srcScript)
681 return nullptr;
682 RootedScript clonedScript(cx, CloneScript(cx, enclosingScope, clone, srcScript));
683 if (!clonedScript)
684 return nullptr;
686 clone->setArgCount(srcFun->nargs());
687 clone->setFlags(srcFun->flags());
688 clone->initAtom(srcFun->displayAtom());
689 clone->initScript(clonedScript);
690 clonedScript->setFunction(clone);
691 if (!JSFunction::setTypeForScriptedFunction(cx, clone))
692 return nullptr;
694 RootedScript cloneScript(cx, clone->nonLazyScript());
695 return clone;
699 * [[HasInstance]] internal method for Function objects: fetch the .prototype
700 * property of its 'this' parameter, and walks the prototype chain of v (only
701 * if v is an object) returning true if .prototype is found.
703 static bool
704 fun_hasInstance(JSContext* cx, HandleObject objArg, MutableHandleValue v, bool* bp)
706 RootedObject obj(cx, objArg);
708 while (obj->is<JSFunction>() && obj->isBoundFunction())
709 obj = obj->as<JSFunction>().getBoundFunctionTarget();
711 RootedValue pval(cx);
712 if (!JSObject::getProperty(cx, obj, obj, cx->names().prototype, &pval))
713 return false;
715 if (pval.isPrimitive()) {
717 * Throw a runtime error if instanceof is called on a function that
718 * has a non-object as its .prototype value.
720 RootedValue val(cx, ObjectValue(*obj));
721 js_ReportValueError(cx, JSMSG_BAD_PROTOTYPE, -1, val, js::NullPtr());
722 return false;
725 RootedObject pobj(cx, &pval.toObject());
726 bool isDelegate;
727 if (!IsDelegate(cx, pobj, v, &isDelegate))
728 return false;
729 *bp = isDelegate;
730 return true;
733 inline void
734 JSFunction::trace(JSTracer* trc)
736 if (isExtended()) {
737 MarkValueRange(trc, ArrayLength(toExtended()->extendedSlots),
738 toExtended()->extendedSlots, "nativeReserved");
741 if (atom_)
742 MarkString(trc, &atom_, "atom");
744 if (isInterpreted()) {
745 // Functions can be be marked as interpreted despite having no script
746 // yet at some points when parsing, and can be lazy with no lazy script
747 // for self-hosted code.
748 if (hasScript() && u.i.s.script_) {
749 // Functions can be relazified under the following conditions:
750 // - their compartment isn't currently executing scripts or being
751 // debugged
752 // - they are not in the self-hosting compartment
753 // - they aren't generators
754 // - they don't have JIT code attached
755 // - they don't have child functions
756 // - they have information for un-lazifying them again later
757 // This information can either be a LazyScript, or the name of a
758 // self-hosted function which can be cloned over again. The latter
759 // is stored in the first extended slot.
760 if (IS_GC_MARKING_TRACER(trc) && !compartment()->hasBeenEntered() &&
761 !compartment()->isDebuggee() && !compartment()->isSelfHosting &&
762 u.i.s.script_->isRelazifiable() && (!isSelfHostedBuiltin() || isExtended()))
764 relazify(trc);
765 } else {
766 MarkScriptUnbarriered(trc, &u.i.s.script_, "script");
768 } else if (isInterpretedLazy() && u.i.s.lazy_) {
769 MarkLazyScriptUnbarriered(trc, &u.i.s.lazy_, "lazyScript");
771 if (u.i.env_)
772 MarkObjectUnbarriered(trc, &u.i.env_, "fun_environment");
776 static void
777 fun_trace(JSTracer* trc, JSObject* obj)
779 obj->as<JSFunction>().trace(trc);
782 static bool
783 ThrowTypeError(JSContext* cx, unsigned argc, Value* vp)
785 ThrowTypeErrorBehavior(cx);
786 return false;
789 static JSObject*
790 CreateFunctionConstructor(JSContext* cx, JSProtoKey key)
792 Rooted<GlobalObject*> self(cx, cx->global());
793 RootedObject functionProto(cx, &self->getPrototype(JSProto_Function).toObject());
795 RootedObject ctor(cx, NewObjectWithGivenProto(cx, &JSFunction::class_, functionProto,
796 self, SingletonObject));
797 if (!ctor)
798 return nullptr;
799 RootedObject functionCtor(cx, NewFunction(cx, ctor, Function, 1, JSFunction::NATIVE_CTOR, self,
800 HandlePropertyName(cx->names().Function)));
801 if (!functionCtor)
802 return nullptr;
804 MOZ_ASSERT(ctor == functionCtor);
805 return functionCtor;
809 static JSObject*
810 CreateFunctionPrototype(JSContext* cx, JSProtoKey key)
812 Rooted<GlobalObject*> self(cx, cx->global());
814 RootedObject objectProto(cx, &self->getPrototype(JSProto_Object).toObject());
815 JSObject* functionProto_ = NewObjectWithGivenProto(cx, &JSFunction::class_,
816 objectProto, self, SingletonObject);
817 if (!functionProto_)
818 return nullptr;
820 RootedFunction functionProto(cx, &functionProto_->as<JSFunction>());
823 * Bizarrely, |Function.prototype| must be an interpreted function, so
824 * give it the guts to be one.
827 JSObject* proto = NewFunction(cx, functionProto, nullptr, 0, JSFunction::INTERPRETED,
828 self, js::NullPtr());
829 if (!proto)
830 return nullptr;
832 MOZ_ASSERT(proto == functionProto);
833 functionProto->setIsFunctionPrototype();
836 const char* rawSource = "() {\n}";
837 size_t sourceLen = strlen(rawSource);
838 char16_t* source = InflateString(cx, rawSource, &sourceLen);
839 if (!source)
840 return nullptr;
842 ScriptSource* ss =
843 cx->new_<ScriptSource>();
844 if (!ss) {
845 js_free(source);
846 return nullptr;
848 ScriptSourceHolder ssHolder(ss);
849 ss->setSource(source, sourceLen);
850 CompileOptions options(cx);
851 options.setNoScriptRval(true)
852 .setVersion(JSVERSION_DEFAULT);
853 RootedScriptSource sourceObject(cx, ScriptSourceObject::create(cx, ss));
854 if (!sourceObject || !ScriptSourceObject::initFromOptions(cx, sourceObject, options))
855 return nullptr;
857 RootedScript script(cx, JSScript::Create(cx,
858 /* enclosingScope = */ js::NullPtr(),
859 /* savedCallerFun = */ false,
860 options,
861 /* staticLevel = */ 0,
862 sourceObject,
864 ss->length()));
865 if (!script || !JSScript::fullyInitTrivial(cx, script))
866 return nullptr;
868 functionProto->initScript(script);
869 types::TypeObject* protoType = functionProto->getType(cx);
870 if (!protoType)
871 return nullptr;
873 protoType->interpretedFunction = functionProto;
874 script->setFunction(functionProto);
877 * The default 'new' type of Function.prototype is required by type
878 * inference to have unknown properties, to simplify handling of e.g.
879 * CloneFunctionObject.
881 if (!JSObject::setNewTypeUnknown(cx, &JSFunction::class_, functionProto))
882 return nullptr;
884 // Construct the unique [[%ThrowTypeError%]] function object, used only for
885 // "callee" and "caller" accessors on strict mode arguments objects. (The
886 // spec also uses this for "arguments" and "caller" on various functions,
887 // but we're experimenting with implementing them using accessors on
888 // |Function.prototype| right now.)
889 RootedObject tte(cx, NewObjectWithGivenProto(cx, &JSFunction::class_, functionProto, self,
890 SingletonObject));
891 if (!tte)
892 return nullptr;
894 bool succeeded;
895 RootedFunction throwTypeError(cx, NewFunction(cx, tte, ThrowTypeError, 0,
896 JSFunction::NATIVE_FUN, self, js::NullPtr()));
897 if (!throwTypeError || !JSObject::preventExtensions(cx, throwTypeError, &succeeded))
898 return nullptr;
899 if (!succeeded) {
900 JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_CHANGE_EXTENSIBILITY);
901 return nullptr;
904 self->setThrowTypeError(throwTypeError);
906 return functionProto;
909 const Class JSFunction::class_ = {
910 js_Function_str,
911 JSCLASS_IMPLEMENTS_BARRIERS |
912 JSCLASS_HAS_CACHED_PROTO(JSProto_Function),
913 nullptr, /* addProperty */
914 nullptr, /* delProperty */
915 nullptr, /* getProperty */
916 nullptr, /* setProperty */
917 fun_enumerate,
918 js::fun_resolve,
919 nullptr, /* convert */
920 nullptr, /* finalize */
921 nullptr, /* call */
922 fun_hasInstance,
923 nullptr, /* construct */
924 fun_trace,
926 CreateFunctionConstructor,
927 CreateFunctionPrototype,
928 nullptr,
929 function_methods,
930 function_properties
934 const Class* const js::FunctionClassPtr = &JSFunction::class_;
936 /* Find the body of a function (not including braces). */
937 bool
938 js::FindBody(JSContext* cx, HandleFunction fun, HandleLinearString src, size_t* bodyStart,
939 size_t* bodyEnd)
941 // We don't need principals, since those are only used for error reporting.
942 CompileOptions options(cx);
943 options.setFileAndLine("internal-findBody", 0);
945 // For asm.js modules, there's no script.
946 if (fun->hasScript())
947 options.setVersion(fun->nonLazyScript()->getVersion());
949 AutoKeepAtoms keepAtoms(cx->perThreadData);
951 AutoStableStringChars stableChars(cx);
952 if (!stableChars.initTwoByte(cx, src))
953 return false;
955 const mozilla::Range<const char16_t> srcChars = stableChars.twoByteRange();
956 TokenStream ts(cx, options, srcChars.start().get(), srcChars.length(), nullptr);
957 int nest = 0;
958 bool onward = true;
959 // Skip arguments list.
960 do {
961 TokenKind tt;
962 if (!ts.getToken(&tt))
963 return false;
964 switch (tt) {
965 case TOK_NAME:
966 case TOK_YIELD:
967 if (nest == 0)
968 onward = false;
969 break;
970 case TOK_LP:
971 nest++;
972 break;
973 case TOK_RP:
974 if (--nest == 0)
975 onward = false;
976 break;
977 default:
978 break;
980 } while (onward);
981 TokenKind tt;
982 if (!ts.getToken(&tt))
983 return false;
984 if (tt == TOK_ARROW) {
985 if (!ts.getToken(&tt))
986 return false;
988 bool braced = tt == TOK_LC;
989 MOZ_ASSERT_IF(fun->isExprClosure(), !braced);
990 *bodyStart = ts.currentToken().pos.begin;
991 if (braced)
992 *bodyStart += 1;
993 mozilla::RangedPtr<const char16_t> end = srcChars.end();
994 if (end[-1] == '}') {
995 end--;
996 } else {
997 MOZ_ASSERT(!braced);
998 for (; unicode::IsSpaceOrBOM2(end[-1]); end--)
1001 *bodyEnd = end - srcChars.start();
1002 MOZ_ASSERT(*bodyStart <= *bodyEnd);
1003 return true;
1006 JSString*
1007 js::FunctionToString(JSContext* cx, HandleFunction fun, bool bodyOnly, bool lambdaParen)
1009 if (fun->isInterpretedLazy() && !fun->getOrCreateScript(cx))
1010 return nullptr;
1012 if (IsAsmJSModule(fun))
1013 return AsmJSModuleToString(cx, fun, !lambdaParen);
1014 if (IsAsmJSFunction(fun))
1015 return AsmJSFunctionToString(cx, fun);
1017 StringBuffer out(cx);
1018 RootedScript script(cx);
1020 if (fun->hasScript()) {
1021 script = fun->nonLazyScript();
1022 if (script->isGeneratorExp()) {
1023 if ((!bodyOnly && !out.append("function genexp() {")) ||
1024 !out.append("\n [generator expression]\n") ||
1025 (!bodyOnly && !out.append("}")))
1027 return nullptr;
1029 return out.finishString();
1032 if (!bodyOnly) {
1033 // If we're not in pretty mode, put parentheses around lambda functions.
1034 if (fun->isInterpreted() && !lambdaParen && fun->isLambda() && !fun->isArrow()) {
1035 if (!out.append("("))
1036 return nullptr;
1038 if (!fun->isArrow()) {
1039 if (!(fun->isStarGenerator() ? out.append("function* ") : out.append("function ")))
1040 return nullptr;
1042 if (fun->atom()) {
1043 if (!out.append(fun->atom()))
1044 return nullptr;
1047 bool haveSource = fun->isInterpreted() && !fun->isSelfHostedBuiltin();
1048 if (haveSource && !script->scriptSource()->hasSourceData() &&
1049 !JSScript::loadSource(cx, script->scriptSource(), &haveSource))
1051 return nullptr;
1053 if (haveSource) {
1054 Rooted<JSFlatString*> src(cx, script->sourceData(cx));
1055 if (!src)
1056 return nullptr;
1058 bool exprBody = fun->isExprClosure();
1060 // The source data for functions created by calling the Function
1061 // constructor is only the function's body. This depends on the fact,
1062 // asserted below, that in Function("function f() {}"), the inner
1063 // function's sourceStart points to the '(', not the 'f'.
1064 bool funCon = !fun->isArrow() &&
1065 script->sourceStart() == 0 &&
1066 script->sourceEnd() == script->scriptSource()->length() &&
1067 script->scriptSource()->argumentsNotIncluded();
1069 // Functions created with the constructor can't be arrow functions or
1070 // expression closures.
1071 MOZ_ASSERT_IF(funCon, !fun->isArrow());
1072 MOZ_ASSERT_IF(funCon, !exprBody);
1073 MOZ_ASSERT_IF(!funCon && !fun->isArrow(),
1074 src->length() > 0 && src->latin1OrTwoByteChar(0) == '(');
1076 // If a function inherits strict mode by having scopes above it that
1077 // have "use strict", we insert "use strict" into the body of the
1078 // function. This ensures that if the result of toString is evaled, the
1079 // resulting function will have the same semantics.
1080 bool addUseStrict = script->strict() && !script->explicitUseStrict() && !fun->isArrow();
1082 bool buildBody = funCon && !bodyOnly;
1083 if (buildBody) {
1084 // This function was created with the Function constructor. We don't
1085 // have source for the arguments, so we have to generate that. Part
1086 // of bug 755821 should be cobbling the arguments passed into the
1087 // Function constructor into the source string.
1088 if (!out.append("("))
1089 return nullptr;
1091 // Fish out the argument names.
1092 MOZ_ASSERT(script->bindings.numArgs() == fun->nargs());
1094 BindingIter bi(script);
1095 for (unsigned i = 0; i < fun->nargs(); i++, bi++) {
1096 MOZ_ASSERT(bi.argIndex() == i);
1097 if (i && !out.append(", "))
1098 return nullptr;
1099 if (i == unsigned(fun->nargs() - 1) && fun->hasRest() && !out.append("..."))
1100 return nullptr;
1101 if (!out.append(bi->name()))
1102 return nullptr;
1104 if (!out.append(") {\n"))
1105 return nullptr;
1107 if ((bodyOnly && !funCon) || addUseStrict) {
1108 // We need to get at the body either because we're only supposed to
1109 // return the body or we need to insert "use strict" into the body.
1110 size_t bodyStart = 0, bodyEnd;
1112 // If the function is defined in the Function constructor, we
1113 // already have a body.
1114 if (!funCon) {
1115 MOZ_ASSERT(!buildBody);
1116 if (!FindBody(cx, fun, src, &bodyStart, &bodyEnd))
1117 return nullptr;
1118 } else {
1119 bodyEnd = src->length();
1122 if (addUseStrict) {
1123 // Output source up to beginning of body.
1124 if (!out.appendSubstring(src, 0, bodyStart))
1125 return nullptr;
1126 if (exprBody) {
1127 // We can't insert a statement into a function with an
1128 // expression body. Do what the decompiler did, and insert a
1129 // comment.
1130 if (!out.append("/* use strict */ "))
1131 return nullptr;
1132 } else {
1133 if (!out.append("\n\"use strict\";\n"))
1134 return nullptr;
1138 // Output just the body (for bodyOnly) or the body and possibly
1139 // closing braces (for addUseStrict).
1140 size_t dependentEnd = bodyOnly ? bodyEnd : src->length();
1141 if (!out.appendSubstring(src, bodyStart, dependentEnd - bodyStart))
1142 return nullptr;
1143 } else {
1144 if (!out.append(src))
1145 return nullptr;
1147 if (buildBody) {
1148 if (!out.append("\n}"))
1149 return nullptr;
1151 if (bodyOnly) {
1152 // Slap a semicolon on the end of functions with an expression body.
1153 if (exprBody && !out.append(";"))
1154 return nullptr;
1155 } else if (!lambdaParen && fun->isLambda() && !fun->isArrow()) {
1156 if (!out.append(")"))
1157 return nullptr;
1159 } else if (fun->isInterpreted() && !fun->isSelfHostedBuiltin()) {
1160 if ((!bodyOnly && !out.append("() {\n ")) ||
1161 !out.append("[sourceless code]") ||
1162 (!bodyOnly && !out.append("\n}")))
1163 return nullptr;
1164 if (!lambdaParen && fun->isLambda() && !fun->isArrow() && !out.append(")"))
1165 return nullptr;
1166 } else {
1167 MOZ_ASSERT(!fun->isExprClosure());
1169 if ((!bodyOnly && !out.append("() {\n "))
1170 || !out.append("[native code]")
1171 || (!bodyOnly && !out.append("\n}")))
1173 return nullptr;
1176 return out.finishString();
1179 JSString*
1180 fun_toStringHelper(JSContext* cx, HandleObject obj, unsigned indent)
1182 if (!obj->is<JSFunction>()) {
1183 if (obj->is<ProxyObject>())
1184 return Proxy::fun_toString(cx, obj, indent);
1185 JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
1186 JSMSG_INCOMPATIBLE_PROTO,
1187 js_Function_str, js_toString_str,
1188 "object");
1189 return nullptr;
1192 RootedFunction fun(cx, &obj->as<JSFunction>());
1193 return FunctionToString(cx, fun, false, indent != JS_DONT_PRETTY_PRINT);
1196 bool
1197 js::fun_toString(JSContext* cx, unsigned argc, Value* vp)
1199 CallArgs args = CallArgsFromVp(argc, vp);
1200 MOZ_ASSERT(IsFunctionObject(args.calleev()));
1202 uint32_t indent = 0;
1204 if (args.length() != 0 && !ToUint32(cx, args[0], &indent))
1205 return false;
1207 RootedObject obj(cx, ToObject(cx, args.thisv()));
1208 if (!obj)
1209 return false;
1211 RootedString str(cx, fun_toStringHelper(cx, obj, indent));
1212 if (!str)
1213 return false;
1215 args.rval().setString(str);
1216 return true;
1219 #if JS_HAS_TOSOURCE
1220 static bool
1221 fun_toSource(JSContext* cx, unsigned argc, Value* vp)
1223 CallArgs args = CallArgsFromVp(argc, vp);
1224 MOZ_ASSERT(IsFunctionObject(args.calleev()));
1226 RootedObject obj(cx, ToObject(cx, args.thisv()));
1227 if (!obj)
1228 return false;
1230 RootedString str(cx);
1231 if (obj->isCallable())
1232 str = fun_toStringHelper(cx, obj, JS_DONT_PRETTY_PRINT);
1233 else
1234 str = ObjectToSource(cx, obj);
1236 if (!str)
1237 return false;
1238 args.rval().setString(str);
1239 return true;
1241 #endif
1243 bool
1244 js_fun_call(JSContext* cx, unsigned argc, Value* vp)
1246 CallArgs args = CallArgsFromVp(argc, vp);
1248 HandleValue fval = args.thisv();
1249 if (!IsCallable(fval)) {
1250 ReportIncompatibleMethod(cx, args, &JSFunction::class_);
1251 return false;
1254 args.setCallee(fval);
1255 args.setThis(args.get(0));
1257 if (args.length() > 0) {
1258 for (size_t i = 0; i < args.length() - 1; i++)
1259 args[i].set(args[i + 1]);
1260 args = CallArgsFromVp(args.length() - 1, vp);
1263 return Invoke(cx, args);
1266 // ES5 15.3.4.3
1267 bool
1268 js_fun_apply(JSContext* cx, unsigned argc, Value* vp)
1270 CallArgs args = CallArgsFromVp(argc, vp);
1272 // Step 1.
1273 HandleValue fval = args.thisv();
1274 if (!IsCallable(fval)) {
1275 ReportIncompatibleMethod(cx, args, &JSFunction::class_);
1276 return false;
1279 // Step 2.
1280 if (args.length() < 2 || args[1].isNullOrUndefined())
1281 return js_fun_call(cx, (args.length() > 0) ? 1 : 0, vp);
1283 InvokeArgs args2(cx);
1285 // A JS_OPTIMIZED_ARGUMENTS magic value means that 'arguments' flows into
1286 // this apply call from a scripted caller and, as an optimization, we've
1287 // avoided creating it since apply can simply pull the argument values from
1288 // the calling frame (which we must do now).
1289 if (args[1].isMagic(JS_OPTIMIZED_ARGUMENTS)) {
1290 // Step 3-6.
1291 ScriptFrameIter iter(cx);
1292 MOZ_ASSERT(iter.numActualArgs() <= ARGS_LENGTH_MAX);
1293 if (!args2.init(iter.numActualArgs()))
1294 return false;
1296 args2.setCallee(fval);
1297 args2.setThis(args[0]);
1299 // Steps 7-8.
1300 iter.unaliasedForEachActual(cx, CopyTo(args2.array()));
1301 } else {
1302 // Step 3.
1303 if (!args[1].isObject()) {
1304 JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr,
1305 JSMSG_BAD_APPLY_ARGS, js_apply_str);
1306 return false;
1309 // Steps 4-5 (note erratum removing steps originally numbered 5 and 7 in
1310 // original version of ES5).
1311 RootedObject aobj(cx, &args[1].toObject());
1312 uint32_t length;
1313 if (!GetLengthProperty(cx, aobj, &length))
1314 return false;
1316 // Step 6.
1317 if (length > ARGS_LENGTH_MAX) {
1318 JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_TOO_MANY_FUN_APPLY_ARGS);
1319 return false;
1322 if (!args2.init(length))
1323 return false;
1325 // Push fval, obj, and aobj's elements as args.
1326 args2.setCallee(fval);
1327 args2.setThis(args[0]);
1329 // Steps 7-8.
1330 if (!GetElements(cx, aobj, length, args2.array()))
1331 return false;
1334 // Step 9.
1335 if (!Invoke(cx, args2))
1336 return false;
1338 args.rval().set(args2.rval());
1339 return true;
1342 static const uint32_t JSSLOT_BOUND_FUNCTION_THIS = 0;
1343 static const uint32_t JSSLOT_BOUND_FUNCTION_ARGS_COUNT = 1;
1345 static const uint32_t BOUND_FUNCTION_RESERVED_SLOTS = 2;
1347 inline bool
1348 JSFunction::initBoundFunction(JSContext* cx, HandleValue thisArg,
1349 const Value* args, unsigned argslen)
1351 RootedFunction self(cx, this);
1354 * Convert to a dictionary to set the BOUND_FUNCTION flag and increase
1355 * the slot span to cover the arguments and additional slots for the 'this'
1356 * value and arguments count.
1358 if (!self->toDictionaryMode(cx))
1359 return false;
1361 if (!self->setFlag(cx, BaseShape::BOUND_FUNCTION))
1362 return false;
1364 if (!NativeObject::setSlotSpan(cx, self, BOUND_FUNCTION_RESERVED_SLOTS + argslen))
1365 return false;
1367 self->setSlot(JSSLOT_BOUND_FUNCTION_THIS, thisArg);
1368 self->setSlot(JSSLOT_BOUND_FUNCTION_ARGS_COUNT, PrivateUint32Value(argslen));
1370 self->initSlotRange(BOUND_FUNCTION_RESERVED_SLOTS, args, argslen);
1372 return true;
1375 const js::Value&
1376 JSFunction::getBoundFunctionThis() const
1378 MOZ_ASSERT(isBoundFunction());
1380 return getSlot(JSSLOT_BOUND_FUNCTION_THIS);
1383 const js::Value&
1384 JSFunction::getBoundFunctionArgument(unsigned which) const
1386 MOZ_ASSERT(isBoundFunction());
1387 MOZ_ASSERT(which < getBoundFunctionArgumentCount());
1389 return getSlot(BOUND_FUNCTION_RESERVED_SLOTS + which);
1392 size_t
1393 JSFunction::getBoundFunctionArgumentCount() const
1395 MOZ_ASSERT(isBoundFunction());
1397 return getSlot(JSSLOT_BOUND_FUNCTION_ARGS_COUNT).toPrivateUint32();
1400 /* static */ bool
1401 JSFunction::createScriptForLazilyInterpretedFunction(JSContext* cx, HandleFunction fun)
1403 MOZ_ASSERT(fun->isInterpretedLazy());
1405 Rooted<LazyScript*> lazy(cx, fun->lazyScriptOrNull());
1406 if (lazy) {
1407 // Trigger a pre barrier on the lazy script being overwritten.
1408 if (cx->zone()->needsIncrementalBarrier())
1409 LazyScript::writeBarrierPre(lazy);
1411 // Suppress GC for now although we should be able to remove this by
1412 // making 'lazy' a Rooted<LazyScript*> (which requires adding a
1413 // THING_ROOT_LAZY_SCRIPT).
1414 AutoSuppressGC suppressGC(cx);
1416 RootedScript script(cx, lazy->maybeScript());
1418 if (script) {
1419 fun->setUnlazifiedScript(script);
1420 // Remember the lazy script on the compiled script, so it can be
1421 // stored on the function again in case of re-lazification.
1422 // Only functions without inner functions are re-lazified.
1423 if (!lazy->numInnerFunctions())
1424 script->setLazyScript(lazy);
1425 return true;
1428 if (fun != lazy->functionNonDelazifying()) {
1429 if (!lazy->functionDelazifying(cx))
1430 return false;
1431 script = lazy->functionNonDelazifying()->nonLazyScript();
1432 if (!script)
1433 return false;
1435 fun->setUnlazifiedScript(script);
1436 return true;
1439 // Lazy script caching is only supported for leaf functions. If a
1440 // script with inner functions was returned by the cache, those inner
1441 // functions would be delazified when deep cloning the script, even if
1442 // they have never executed.
1444 // Additionally, the lazy script cache is not used during incremental
1445 // GCs, to avoid resurrecting dead scripts after incremental sweeping
1446 // has started.
1447 if (!lazy->numInnerFunctions() && !JS::IsIncrementalGCInProgress(cx->runtime())) {
1448 LazyScriptCache::Lookup lookup(cx, lazy);
1449 cx->runtime()->lazyScriptCache.lookup(lookup, script.address());
1452 if (script) {
1453 RootedObject enclosingScope(cx, lazy->enclosingScope());
1454 RootedScript clonedScript(cx, CloneScript(cx, enclosingScope, fun, script));
1455 if (!clonedScript)
1456 return false;
1458 clonedScript->setSourceObject(lazy->sourceObject());
1460 fun->initAtom(script->functionNonDelazifying()->displayAtom());
1461 clonedScript->setFunction(fun);
1463 fun->setUnlazifiedScript(clonedScript);
1465 if (!lazy->maybeScript())
1466 lazy->initScript(clonedScript);
1467 return true;
1470 MOZ_ASSERT(lazy->source()->hasSourceData());
1472 // Parse and compile the script from source.
1473 UncompressedSourceCache::AutoHoldEntry holder;
1474 const char16_t* chars = lazy->source()->chars(cx, holder);
1475 if (!chars)
1476 return false;
1478 const char16_t* lazyStart = chars + lazy->begin();
1479 size_t lazyLength = lazy->end() - lazy->begin();
1481 if (!frontend::CompileLazyFunction(cx, lazy, lazyStart, lazyLength))
1482 return false;
1484 script = fun->nonLazyScript();
1486 // Remember the compiled script on the lazy script itself, in case
1487 // there are clones of the function still pointing to the lazy script.
1488 if (!lazy->maybeScript())
1489 lazy->initScript(script);
1491 // Try to insert the newly compiled script into the lazy script cache.
1492 if (!lazy->numInnerFunctions()) {
1493 // A script's starting column isn't set by the bytecode emitter, so
1494 // specify this from the lazy script so that if an identical lazy
1495 // script is encountered later a match can be determined.
1496 script->setColumn(lazy->column());
1498 LazyScriptCache::Lookup lookup(cx, lazy);
1499 cx->runtime()->lazyScriptCache.insert(lookup, script);
1501 // Remember the lazy script on the compiled script, so it can be
1502 // stored on the function again in case of re-lazification.
1503 // Only functions without inner functions are re-lazified.
1504 script->setLazyScript(lazy);
1506 return true;
1509 /* Lazily cloned self-hosted script. */
1510 MOZ_ASSERT(fun->isSelfHostedBuiltin());
1511 RootedAtom funAtom(cx, &fun->getExtendedSlot(0).toString()->asAtom());
1512 if (!funAtom)
1513 return false;
1514 Rooted<PropertyName*> funName(cx, funAtom->asPropertyName());
1515 return cx->runtime()->cloneSelfHostedFunctionScript(cx, funName, fun);
1518 void
1519 JSFunction::relazify(JSTracer* trc)
1521 JSScript* script = nonLazyScript();
1522 MOZ_ASSERT(script->isRelazifiable());
1523 MOZ_ASSERT(!compartment()->hasBeenEntered());
1524 MOZ_ASSERT(!compartment()->isDebuggee());
1526 // If the script's canonical function isn't lazy, we have to mark the
1527 // script. Otherwise, the following scenario would leave it unmarked
1528 // and cause it to be swept while a function is still expecting it to be
1529 // valid:
1530 // 1. an incremental GC slice causes the canonical function to relazify
1531 // 2. a clone is used and delazifies the canonical function
1532 // 3. another GC slice causes the clone to relazify
1533 // The result is that no function marks the script, but the canonical
1534 // function expects it to be valid.
1535 if (script->functionNonDelazifying()->hasScript())
1536 MarkScriptUnbarriered(trc, &u.i.s.script_, "script");
1538 flags_ &= ~INTERPRETED;
1539 flags_ |= INTERPRETED_LAZY;
1540 LazyScript* lazy = script->maybeLazyScript();
1541 u.i.s.lazy_ = lazy;
1542 if (lazy) {
1543 MOZ_ASSERT(!isSelfHostedBuiltin());
1544 // If this is the script stored in the lazy script to be cloned
1545 // for un-lazifying other functions, reset it so the script can
1546 // be freed.
1547 if (lazy->maybeScript() == script)
1548 lazy->resetScript();
1549 MarkLazyScriptUnbarriered(trc, &u.i.s.lazy_, "lazyScript");
1550 } else {
1551 MOZ_ASSERT(isSelfHostedBuiltin());
1552 MOZ_ASSERT(isExtended());
1553 MOZ_ASSERT(getExtendedSlot(0).toString()->isAtom());
1557 /* ES5 15.3.4.5.1 and 15.3.4.5.2. */
1558 bool
1559 js::CallOrConstructBoundFunction(JSContext* cx, unsigned argc, Value* vp)
1561 CallArgs args = CallArgsFromVp(argc, vp);
1562 RootedFunction fun(cx, &args.callee().as<JSFunction>());
1563 MOZ_ASSERT(fun->isBoundFunction());
1565 /* 15.3.4.5.1 step 1, 15.3.4.5.2 step 3. */
1566 unsigned argslen = fun->getBoundFunctionArgumentCount();
1568 if (args.length() + argslen > ARGS_LENGTH_MAX) {
1569 js_ReportAllocationOverflow(cx);
1570 return false;
1573 /* 15.3.4.5.1 step 3, 15.3.4.5.2 step 1. */
1574 RootedObject target(cx, fun->getBoundFunctionTarget());
1576 /* 15.3.4.5.1 step 2. */
1577 const Value& boundThis = fun->getBoundFunctionThis();
1579 InvokeArgs invokeArgs(cx);
1580 if (!invokeArgs.init(args.length() + argslen))
1581 return false;
1583 /* 15.3.4.5.1, 15.3.4.5.2 step 4. */
1584 for (unsigned i = 0; i < argslen; i++)
1585 invokeArgs[i].set(fun->getBoundFunctionArgument(i));
1586 PodCopy(invokeArgs.array() + argslen, vp + 2, args.length());
1588 /* 15.3.4.5.1, 15.3.4.5.2 step 5. */
1589 invokeArgs.setCallee(ObjectValue(*target));
1591 bool constructing = args.isConstructing();
1592 if (!constructing)
1593 invokeArgs.setThis(boundThis);
1595 if (constructing ? !InvokeConstructor(cx, invokeArgs) : !Invoke(cx, invokeArgs))
1596 return false;
1598 args.rval().set(invokeArgs.rval());
1599 return true;
1602 static bool
1603 fun_isGenerator(JSContext* cx, unsigned argc, Value* vp)
1605 CallArgs args = CallArgsFromVp(argc, vp);
1606 JSFunction* fun;
1607 if (!IsFunctionObject(args.thisv(), &fun)) {
1608 args.rval().setBoolean(false);
1609 return true;
1612 args.rval().setBoolean(fun->isGenerator());
1613 return true;
1616 /* ES5 15.3.4.5. */
1617 bool
1618 js::fun_bind(JSContext* cx, unsigned argc, Value* vp)
1620 CallArgs args = CallArgsFromVp(argc, vp);
1622 /* Step 1. */
1623 RootedValue thisv(cx, args.thisv());
1625 /* Step 2. */
1626 if (!IsCallable(thisv)) {
1627 ReportIncompatibleMethod(cx, args, &JSFunction::class_);
1628 return false;
1631 /* Step 3. */
1632 Value* boundArgs = nullptr;
1633 unsigned argslen = 0;
1634 if (args.length() > 1) {
1635 boundArgs = args.array() + 1;
1636 argslen = args.length() - 1;
1639 /* Steps 7-9. */
1640 RootedValue thisArg(cx, args.length() >= 1 ? args[0] : UndefinedValue());
1641 RootedObject target(cx, &thisv.toObject());
1642 JSObject* boundFunction = js_fun_bind(cx, target, thisArg, boundArgs, argslen);
1643 if (!boundFunction)
1644 return false;
1646 /* Step 22. */
1647 args.rval().setObject(*boundFunction);
1648 return true;
1651 JSObject*
1652 js_fun_bind(JSContext* cx, HandleObject target, HandleValue thisArg,
1653 Value* boundArgs, unsigned argslen)
1655 /* Steps 15-16. */
1656 unsigned length = 0;
1657 if (target->is<JSFunction>()) {
1658 unsigned nargs = target->as<JSFunction>().nargs();
1659 if (nargs > argslen)
1660 length = nargs - argslen;
1663 /* Step 4-6, 10-11. */
1664 RootedAtom name(cx, target->is<JSFunction>() ? target->as<JSFunction>().atom() : nullptr);
1666 RootedObject funobj(cx, NewFunction(cx, js::NullPtr(), CallOrConstructBoundFunction, length,
1667 JSFunction::NATIVE_CTOR, target, name));
1668 if (!funobj)
1669 return nullptr;
1671 /* NB: Bound functions abuse |parent| to store their target. */
1672 if (!JSObject::setParent(cx, funobj, target))
1673 return nullptr;
1675 if (!funobj->as<JSFunction>().initBoundFunction(cx, thisArg, boundArgs, argslen))
1676 return nullptr;
1678 /* Steps 17, 19-21 are handled by fun_resolve. */
1679 /* Step 18 is the default for new functions. */
1680 return funobj;
1684 * Report "malformed formal parameter" iff no illegal char or similar scanner
1685 * error was already reported.
1687 static bool
1688 OnBadFormal(JSContext* cx)
1690 JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_BAD_FORMAL);
1691 return false;
1694 const JSFunctionSpec js::function_methods[] = {
1695 #if JS_HAS_TOSOURCE
1696 JS_FN(js_toSource_str, fun_toSource, 0,0),
1697 #endif
1698 JS_FN(js_toString_str, fun_toString, 0,0),
1699 JS_FN(js_apply_str, js_fun_apply, 2,0),
1700 JS_FN(js_call_str, js_fun_call, 1,0),
1701 JS_FN("bind", fun_bind, 1,0),
1702 JS_FN("isGenerator", fun_isGenerator,0,0),
1703 JS_FS_END
1706 static bool
1707 FunctionConstructor(JSContext* cx, unsigned argc, Value* vp, GeneratorKind generatorKind)
1709 CallArgs args = CallArgsFromVp(argc, vp);
1710 RootedString arg(cx); // used multiple times below
1712 /* Block this call if security callbacks forbid it. */
1713 Rooted<GlobalObject*> global(cx, &args.callee().global());
1714 if (!GlobalObject::isRuntimeCodeGenEnabled(cx, global)) {
1715 JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CSP_BLOCKED_FUNCTION);
1716 return false;
1719 AutoKeepAtoms keepAtoms(cx->perThreadData);
1720 AutoNameVector formals(cx);
1722 bool hasRest = false;
1724 bool isStarGenerator = generatorKind == StarGenerator;
1725 MOZ_ASSERT(generatorKind != LegacyGenerator);
1727 RootedScript maybeScript(cx);
1728 const char* filename;
1729 unsigned lineno;
1730 bool mutedErrors;
1731 uint32_t pcOffset;
1732 DescribeScriptedCallerForCompilation(cx, &maybeScript, &filename, &lineno, &pcOffset,
1733 &mutedErrors);
1735 const char* introductionType = "Function";
1736 if (generatorKind != NotGenerator)
1737 introductionType = "GeneratorFunction";
1739 const char* introducerFilename = filename;
1740 if (maybeScript && maybeScript->scriptSource()->introducerFilename())
1741 introducerFilename = maybeScript->scriptSource()->introducerFilename();
1743 CompileOptions options(cx);
1744 options.setMutedErrors(mutedErrors)
1745 .setFileAndLine(filename, 1)
1746 .setNoScriptRval(false)
1747 .setCompileAndGo(true)
1748 .setIntroductionInfo(introducerFilename, introductionType, lineno, maybeScript, pcOffset);
1750 unsigned n = args.length() ? args.length() - 1 : 0;
1751 if (n > 0) {
1753 * Collect the function-argument arguments into one string, separated
1754 * by commas, then make a tokenstream from that string, and scan it to
1755 * get the arguments. We need to throw the full scanner at the
1756 * problem, because the argument string can legitimately contain
1757 * comments and linefeeds. XXX It might be better to concatenate
1758 * everything up into a function definition and pass it to the
1759 * compiler, but doing it this way is less of a delta from the old
1760 * code. See ECMA 15.3.2.1.
1762 size_t args_length = 0;
1763 for (unsigned i = 0; i < n; i++) {
1764 /* Collect the lengths for all the function-argument arguments. */
1765 arg = ToString<CanGC>(cx, args[i]);
1766 if (!arg)
1767 return false;
1768 args[i].setString(arg);
1771 * Check for overflow. The < test works because the maximum
1772 * JSString length fits in 2 fewer bits than size_t has.
1774 size_t old_args_length = args_length;
1775 args_length = old_args_length + arg->length();
1776 if (args_length < old_args_length) {
1777 js_ReportAllocationOverflow(cx);
1778 return false;
1782 /* Add 1 for each joining comma and check for overflow (two ways). */
1783 size_t old_args_length = args_length;
1784 args_length = old_args_length + n - 1;
1785 if (args_length < old_args_length ||
1786 args_length >= ~(size_t)0 / sizeof(char16_t)) {
1787 js_ReportAllocationOverflow(cx);
1788 return false;
1792 * Allocate a string to hold the concatenated arguments, including room
1793 * for a terminating 0. Mark cx->tempLifeAlloc for later release, to
1794 * free collected_args and its tokenstream in one swoop.
1796 LifoAllocScope las(&cx->tempLifoAlloc());
1797 char16_t* cp = cx->tempLifoAlloc().newArray<char16_t>(args_length + 1);
1798 if (!cp) {
1799 js_ReportOutOfMemory(cx);
1800 return false;
1802 ConstTwoByteChars collected_args(cp, args_length + 1);
1805 * Concatenate the arguments into the new string, separated by commas.
1807 for (unsigned i = 0; i < n; i++) {
1808 JSLinearString* argLinear = args[i].toString()->ensureLinear(cx);
1809 if (!argLinear)
1810 return false;
1812 CopyChars(cp, *argLinear);
1813 cp += argLinear->length();
1815 /* Add separating comma or terminating 0. */
1816 *cp++ = (i + 1 < n) ? ',' : 0;
1820 * Initialize a tokenstream that reads from the given string. No
1821 * StrictModeGetter is needed because this TokenStream won't report any
1822 * strict mode errors. Any strict mode errors which might be reported
1823 * here (duplicate argument names, etc.) will be detected when we
1824 * compile the function body.
1826 TokenStream ts(cx, options, collected_args.get(), args_length,
1827 /* strictModeGetter = */ nullptr);
1828 bool yieldIsValidName = ts.versionNumber() < JSVERSION_1_7 && !isStarGenerator;
1830 /* The argument string may be empty or contain no tokens. */
1831 TokenKind tt;
1832 if (!ts.getToken(&tt))
1833 return false;
1834 if (tt != TOK_EOF) {
1835 for (;;) {
1836 /* Check that it's a name. */
1837 if (hasRest) {
1838 ts.reportError(JSMSG_PARAMETER_AFTER_REST);
1839 return false;
1842 if (tt == TOK_YIELD && yieldIsValidName)
1843 tt = TOK_NAME;
1845 if (tt != TOK_NAME) {
1846 if (tt == TOK_TRIPLEDOT) {
1847 hasRest = true;
1848 if (!ts.getToken(&tt))
1849 return false;
1850 if (tt == TOK_YIELD && yieldIsValidName)
1851 tt = TOK_NAME;
1852 if (tt != TOK_NAME) {
1853 ts.reportError(JSMSG_NO_REST_NAME);
1854 return false;
1856 } else {
1857 return OnBadFormal(cx);
1861 if (!formals.append(ts.currentName()))
1862 return false;
1865 * Get the next token. Stop on end of stream. Otherwise
1866 * insist on a comma, get another name, and iterate.
1868 if (!ts.getToken(&tt))
1869 return false;
1870 if (tt == TOK_EOF)
1871 break;
1872 if (tt != TOK_COMMA)
1873 return OnBadFormal(cx);
1874 if (!ts.getToken(&tt))
1875 return false;
1880 #ifdef DEBUG
1881 for (unsigned i = 0; i < formals.length(); ++i) {
1882 JSString* str = formals[i];
1883 MOZ_ASSERT(str->asAtom().asPropertyName() == formals[i]);
1885 #endif
1887 RootedString str(cx);
1888 if (!args.length())
1889 str = cx->runtime()->emptyString;
1890 else
1891 str = ToString<CanGC>(cx, args[args.length() - 1]);
1892 if (!str)
1893 return false;
1896 * NB: (new Function) is not lexically closed by its caller, it's just an
1897 * anonymous function in the top-level scope that its constructor inhabits.
1898 * Thus 'var x = 42; f = new Function("return x"); print(f())' prints 42,
1899 * and so would a call to f from another top-level's script or function.
1901 RootedAtom anonymousAtom(cx, cx->names().anonymous);
1902 JSObject* proto = nullptr;
1903 if (isStarGenerator) {
1904 proto = GlobalObject::getOrCreateStarGeneratorFunctionPrototype(cx, global);
1905 if (!proto)
1906 return false;
1908 RootedFunction fun(cx, NewFunctionWithProto(cx, js::NullPtr(), nullptr, 0,
1909 JSFunction::INTERPRETED_LAMBDA, global,
1910 anonymousAtom, proto,
1911 JSFunction::FinalizeKind, TenuredObject));
1912 if (!fun)
1913 return false;
1915 if (!JSFunction::setTypeForScriptedFunction(cx, fun))
1916 return false;
1918 if (hasRest)
1919 fun->setHasRest();
1921 AutoStableStringChars stableChars(cx);
1922 if (!stableChars.initTwoByte(cx, str))
1923 return false;
1925 mozilla::Range<const char16_t> chars = stableChars.twoByteRange();
1926 SourceBufferHolder::Ownership ownership = stableChars.maybeGiveOwnershipToCaller()
1927 ? SourceBufferHolder::GiveOwnership
1928 : SourceBufferHolder::NoOwnership;
1929 bool ok;
1930 SourceBufferHolder srcBuf(chars.start().get(), chars.length(), ownership);
1931 if (isStarGenerator)
1932 ok = frontend::CompileStarGeneratorBody(cx, &fun, options, formals, srcBuf);
1933 else
1934 ok = frontend::CompileFunctionBody(cx, &fun, options, formals, srcBuf,
1935 /* enclosingScope = */ js::NullPtr());
1936 args.rval().setObject(*fun);
1937 return ok;
1940 bool
1941 js::Function(JSContext* cx, unsigned argc, Value* vp)
1943 return FunctionConstructor(cx, argc, vp, NotGenerator);
1946 bool
1947 js::Generator(JSContext* cx, unsigned argc, Value* vp)
1949 return FunctionConstructor(cx, argc, vp, StarGenerator);
1952 bool
1953 JSFunction::isBuiltinFunctionConstructor()
1955 return maybeNative() == Function || maybeNative() == Generator;
1958 JSFunction*
1959 js::NewFunction(ExclusiveContext* cx, HandleObject funobjArg, Native native, unsigned nargs,
1960 JSFunction::Flags flags, HandleObject parent, HandleAtom atom,
1961 gc::AllocKind allocKind /* = JSFunction::FinalizeKind */,
1962 NewObjectKind newKind /* = GenericObject */)
1964 return NewFunctionWithProto(cx, funobjArg, native, nargs, flags, parent, atom, nullptr,
1965 allocKind, newKind);
1968 JSFunction*
1969 js::NewFunctionWithProto(ExclusiveContext* cx, HandleObject funobjArg, Native native,
1970 unsigned nargs, JSFunction::Flags flags, HandleObject parent,
1971 HandleAtom atom, JSObject* proto,
1972 gc::AllocKind allocKind /* = JSFunction::FinalizeKind */,
1973 NewObjectKind newKind /* = GenericObject */)
1975 MOZ_ASSERT(allocKind == JSFunction::FinalizeKind || allocKind == JSFunction::ExtendedFinalizeKind);
1976 MOZ_ASSERT(sizeof(JSFunction) <= gc::Arena::thingSize(JSFunction::FinalizeKind));
1977 MOZ_ASSERT(sizeof(FunctionExtended) <= gc::Arena::thingSize(JSFunction::ExtendedFinalizeKind));
1979 RootedObject funobj(cx, funobjArg);
1980 if (funobj) {
1981 MOZ_ASSERT(funobj->is<JSFunction>());
1982 MOZ_ASSERT(funobj->getParent() == parent);
1983 MOZ_ASSERT_IF(native, funobj->hasSingletonType());
1984 } else {
1985 // Don't give asm.js module functions a singleton type since they
1986 // are cloned (via CloneFunctionObjectIfNotSingleton) which assumes
1987 // that hasSingletonType implies isInterpreted.
1988 if (native && !IsAsmJSModuleNative(native))
1989 newKind = SingletonObject;
1990 funobj = NewObjectWithClassProto(cx, &JSFunction::class_, proto,
1991 SkipScopeParent(parent), allocKind, newKind);
1992 if (!funobj)
1993 return nullptr;
1995 RootedFunction fun(cx, &funobj->as<JSFunction>());
1997 if (allocKind == JSFunction::ExtendedFinalizeKind)
1998 flags = JSFunction::Flags(flags | JSFunction::EXTENDED);
2000 /* Initialize all function members. */
2001 fun->setArgCount(uint16_t(nargs));
2002 fun->setFlags(flags);
2003 if (fun->isInterpreted()) {
2004 MOZ_ASSERT(!native);
2005 fun->mutableScript().init(nullptr);
2006 fun->initEnvironment(parent);
2007 } else {
2008 MOZ_ASSERT(fun->isNative());
2009 MOZ_ASSERT(native);
2010 fun->initNative(native, nullptr);
2012 if (allocKind == JSFunction::ExtendedFinalizeKind)
2013 fun->initializeExtended();
2014 fun->initAtom(atom);
2016 return fun;
2019 bool
2020 js::CloneFunctionObjectUseSameScript(JSCompartment* compartment, HandleFunction fun)
2022 return compartment == fun->compartment() &&
2023 !fun->hasSingletonType() &&
2024 !types::UseNewTypeForClone(fun);
2027 JSFunction*
2028 js::CloneFunctionObject(JSContext* cx, HandleFunction fun, HandleObject parent, gc::AllocKind allocKind,
2029 NewObjectKind newKindArg /* = GenericObject */)
2031 MOZ_ASSERT(parent);
2032 MOZ_ASSERT(!fun->isBoundFunction());
2034 bool useSameScript = CloneFunctionObjectUseSameScript(cx->compartment(), fun);
2036 if (!useSameScript && fun->isInterpretedLazy() && !fun->getOrCreateScript(cx))
2037 return nullptr;
2039 NewObjectKind newKind = useSameScript ? newKindArg : SingletonObject;
2040 JSObject* cloneProto = nullptr;
2041 if (fun->isStarGenerator()) {
2042 cloneProto = GlobalObject::getOrCreateStarGeneratorFunctionPrototype(cx, cx->global());
2043 if (!cloneProto)
2044 return nullptr;
2046 JSObject* cloneobj = NewObjectWithClassProto(cx, &JSFunction::class_, cloneProto,
2047 SkipScopeParent(parent), allocKind, newKind);
2048 if (!cloneobj)
2049 return nullptr;
2050 RootedFunction clone(cx, &cloneobj->as<JSFunction>());
2052 uint16_t flags = fun->flags() & ~JSFunction::EXTENDED;
2053 if (allocKind == JSFunction::ExtendedFinalizeKind)
2054 flags |= JSFunction::EXTENDED;
2056 clone->setArgCount(fun->nargs());
2057 clone->setFlags(flags);
2058 if (fun->hasScript()) {
2059 clone->initScript(fun->nonLazyScript());
2060 clone->initEnvironment(parent);
2061 } else if (fun->isInterpretedLazy()) {
2062 LazyScript* lazy = fun->lazyScriptOrNull();
2063 clone->initLazyScript(lazy);
2064 clone->initEnvironment(parent);
2065 } else {
2066 clone->initNative(fun->native(), fun->jitInfo());
2068 clone->initAtom(fun->displayAtom());
2070 if (allocKind == JSFunction::ExtendedFinalizeKind) {
2071 if (fun->isExtended() && fun->compartment() == cx->compartment()) {
2072 for (unsigned i = 0; i < FunctionExtended::NUM_EXTENDED_SLOTS; i++)
2073 clone->initExtendedSlot(i, fun->getExtendedSlot(i));
2074 } else {
2075 clone->initializeExtended();
2079 if (useSameScript) {
2081 * Clone the function, reusing its script. We can use the same type as
2082 * the original function provided that its prototype is correct.
2084 if (fun->getProto() == clone->getProto())
2085 clone->setType(fun->type());
2086 return clone;
2089 RootedFunction cloneRoot(cx, clone);
2092 * Across compartments we have to clone the script for interpreted
2093 * functions. Cross-compartment cloning only happens via JSAPI
2094 * (JS::CloneFunctionObject) which dynamically ensures that 'script' has
2095 * no enclosing lexical scope (only the global scope).
2097 if (cloneRoot->isInterpreted() && !CloneFunctionScript(cx, fun, cloneRoot, newKindArg))
2098 return nullptr;
2100 return cloneRoot;
2104 * Return an atom for use as the name of a builtin method with the given
2105 * property id.
2107 * Function names are always strings. If id is the well-known @@iterator
2108 * symbol, this returns "[Symbol.iterator]".
2110 * Implements step 4 of SetFunctionName in ES6 draft rev 27 (24 Aug 2014).
2112 JSAtom*
2113 js::IdToFunctionName(JSContext* cx, HandleId id)
2115 if (JSID_IS_ATOM(id))
2116 return JSID_TO_ATOM(id);
2118 if (JSID_IS_SYMBOL(id)) {
2119 RootedAtom desc(cx, JSID_TO_SYMBOL(id)->description());
2120 StringBuffer sb(cx);
2121 if (!sb.append('[') || !sb.append(desc) || !sb.append(']'))
2122 return nullptr;
2123 return sb.finishAtom();
2126 RootedValue idv(cx, IdToValue(id));
2127 return ToAtom<CanGC>(cx, idv);
2130 JSFunction*
2131 js::DefineFunction(JSContext* cx, HandleObject obj, HandleId id, Native native,
2132 unsigned nargs, unsigned flags, AllocKind allocKind /* = FinalizeKind */,
2133 NewObjectKind newKind /* = GenericObject */)
2135 PropertyOp gop;
2136 StrictPropertyOp sop;
2137 if (flags & JSFUN_STUB_GSOPS) {
2139 * JSFUN_STUB_GSOPS is a request flag only, not stored in fun->flags or
2140 * the defined property's attributes. This allows us to encode another,
2141 * internal flag using the same bit, JSFUN_EXPR_CLOSURE -- see jsfun.h
2142 * for more on this.
2144 flags &= ~JSFUN_STUB_GSOPS;
2145 gop = nullptr;
2146 sop = nullptr;
2147 } else {
2148 gop = obj->getClass()->getProperty;
2149 sop = obj->getClass()->setProperty;
2150 MOZ_ASSERT(gop != JS_PropertyStub);
2151 MOZ_ASSERT(sop != JS_StrictPropertyStub);
2154 JSFunction::Flags funFlags;
2155 if (!native)
2156 funFlags = JSFunction::INTERPRETED_LAZY;
2157 else
2158 funFlags = JSAPIToJSFunctionFlags(flags);
2160 RootedAtom atom(cx, IdToFunctionName(cx, id));
2161 if (!atom)
2162 return nullptr;
2164 RootedFunction fun(cx, NewFunction(cx, NullPtr(), native, nargs, funFlags, obj, atom,
2165 allocKind, newKind));
2166 if (!fun)
2167 return nullptr;
2169 RootedValue funVal(cx, ObjectValue(*fun));
2170 if (!JSObject::defineGeneric(cx, obj, id, funVal, gop, sop, flags & ~JSFUN_FLAGS_MASK))
2171 return nullptr;
2173 return fun;
2176 void
2177 js::ReportIncompatibleMethod(JSContext* cx, CallReceiver call, const Class* clasp)
2179 RootedValue thisv(cx, call.thisv());
2181 #ifdef DEBUG
2182 if (thisv.isObject()) {
2183 MOZ_ASSERT(thisv.toObject().getClass() != clasp ||
2184 !thisv.toObject().isNative() ||
2185 !thisv.toObject().getProto() ||
2186 thisv.toObject().getProto()->getClass() != clasp);
2187 } else if (thisv.isString()) {
2188 MOZ_ASSERT(clasp != &StringObject::class_);
2189 } else if (thisv.isNumber()) {
2190 MOZ_ASSERT(clasp != &NumberObject::class_);
2191 } else if (thisv.isBoolean()) {
2192 MOZ_ASSERT(clasp != &BooleanObject::class_);
2193 } else if (thisv.isSymbol()) {
2194 MOZ_ASSERT(clasp != &SymbolObject::class_);
2195 } else {
2196 MOZ_ASSERT(thisv.isUndefined() || thisv.isNull());
2198 #endif
2200 if (JSFunction* fun = ReportIfNotFunction(cx, call.calleev())) {
2201 JSAutoByteString funNameBytes;
2202 if (const char* funName = GetFunctionNameBytes(cx, fun, &funNameBytes)) {
2203 JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_PROTO,
2204 clasp->name, funName, InformalValueTypeName(thisv));
2209 void
2210 js::ReportIncompatible(JSContext* cx, CallReceiver call)
2212 if (JSFunction* fun = ReportIfNotFunction(cx, call.calleev())) {
2213 JSAutoByteString funNameBytes;
2214 if (const char* funName = GetFunctionNameBytes(cx, fun, &funNameBytes)) {
2215 JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_METHOD,
2216 funName, "method", InformalValueTypeName(call.thisv()));
2221 namespace JS {
2222 namespace detail {
2224 JS_PUBLIC_API(void)
2225 CheckIsValidConstructible(Value calleev)
2227 JSObject* callee = &calleev.toObject();
2228 if (callee->is<JSFunction>())
2229 MOZ_ASSERT(callee->as<JSFunction>().isNativeConstructor());
2230 else
2231 MOZ_ASSERT(callee->constructHook() != nullptr);
2234 } // namespace detail
2235 } // namespace JS