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/. */
6
7 /*
8 * JS function support.
9 */
10
11 #include "jsfuninlines.h"
12
13 #include "mozilla/ArrayUtils.h"
14 #include "mozilla/CheckedInt.h"
15 #include "mozilla/PodOperations.h"
16 #include "mozilla/Range.h"
17
18 #include <string.h>
19
20 #include "jsapi.h"
21 #include "jsarray.h"
22 #include "jsatom.h"
23 #include "jscntxt.h"
24 #include "jsobj.h"
25 #include "jsscript.h"
26 #include "jsstr.h"
27 #include "jstypes.h"
28 #include "jswrapper.h"
29
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/InlinableNatives.h"
36 #include "jit/Ion.h"
37 #include "jit/JitFrameIterator.h"
38 #include "js/CallNonGenericMethod.h"
39 #include "js/Proxy.h"
40 #include "vm/Debugger.h"
41 #include "vm/GlobalObject.h"
42 #include "vm/Interpreter.h"
43 #include "vm/Shape.h"
44 #include "vm/StringBuffer.h"
45 #include "vm/WrapperObject.h"
46 #include "vm/Xdr.h"
47
48 #include "jsscriptinlines.h"
49
50 #include "vm/Interpreter-inl.h"
51 #include "vm/Stack-inl.h"
52
53 using namespace js;
54 using namespace js::gc;
55 using namespace js::frontend;
56
57 using mozilla::ArrayLength;
58 using mozilla::PodCopy;
59 using mozilla::RangedPtr;
60
61 static bool
fun_enumerate(JSContext * cx,HandleObject obj)62 fun_enumerate(JSContext* cx, HandleObject obj)
63 {
64 MOZ_ASSERT(obj->is<JSFunction>());
65
66 RootedId id(cx);
67 bool found;
68
69 if (!obj->isBoundFunction() && !obj->as<JSFunction>().isArrow()) {
70 id = NameToId(cx->names().prototype);
71 if (!HasProperty(cx, obj, id, &found))
72 return false;
73 }
74
75 id = NameToId(cx->names().length);
76 if (!HasProperty(cx, obj, id, &found))
77 return false;
78
79 id = NameToId(cx->names().name);
80 if (!HasProperty(cx, obj, id, &found))
81 return false;
82
83 return true;
84 }
85
86 bool
IsFunction(HandleValue v)87 IsFunction(HandleValue v)
88 {
89 return v.isObject() && v.toObject().is<JSFunction>();
90 }
91
92 static bool
AdvanceToActiveCallLinear(JSContext * cx,NonBuiltinScriptFrameIter & iter,HandleFunction fun)93 AdvanceToActiveCallLinear(JSContext* cx, NonBuiltinScriptFrameIter& iter, HandleFunction fun)
94 {
95 MOZ_ASSERT(!fun->isBuiltin());
96 MOZ_ASSERT(!fun->isBoundFunction(), "all bound functions are currently native (ergo builtin)");
97
98 for (; !iter.done(); ++iter) {
99 if (!iter.isFunctionFrame() || iter.isEvalFrame())
100 continue;
101 if (iter.matchCallee(cx, fun))
102 return true;
103 }
104 return false;
105 }
106
107 static void
ThrowTypeErrorBehavior(JSContext * cx)108 ThrowTypeErrorBehavior(JSContext* cx)
109 {
110 JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, GetErrorMessage, nullptr,
111 JSMSG_THROW_TYPE_ERROR);
112 }
113
114 // Beware: this function can be invoked on *any* function! That includes
115 // natives, strict mode functions, bound functions, arrow functions,
116 // self-hosted functions and constructors, asm.js functions, functions with
117 // destructuring arguments and/or a rest argument, and probably a few more I
118 // forgot. Turn back and save yourself while you still can. It's too late for
119 // me.
120 static bool
ArgumentsRestrictions(JSContext * cx,HandleFunction fun)121 ArgumentsRestrictions(JSContext* cx, HandleFunction fun)
122 {
123 // Throw if the function is a builtin (note: this doesn't include asm.js),
124 // a strict mode function (FIXME: needs work handle strict asm.js functions
125 // correctly, should fall out of bug 1057208), or a bound function.
126 if (fun->isBuiltin() ||
127 (fun->isInterpreted() && fun->strict()) ||
128 fun->isBoundFunction())
129 {
130 ThrowTypeErrorBehavior(cx);
131 return false;
132 }
133
134 // Otherwise emit a strict warning about |f.arguments| to discourage use of
135 // this non-standard, performance-harmful feature.
136 if (!JS_ReportErrorFlagsAndNumber(cx, JSREPORT_WARNING | JSREPORT_STRICT, GetErrorMessage,
137 nullptr, JSMSG_DEPRECATED_USAGE, js_arguments_str))
138 {
139 return false;
140 }
141
142 return true;
143 }
144
145 bool
ArgumentsGetterImpl(JSContext * cx,const CallArgs & args)146 ArgumentsGetterImpl(JSContext* cx, const CallArgs& args)
147 {
148 MOZ_ASSERT(IsFunction(args.thisv()));
149
150 RootedFunction fun(cx, &args.thisv().toObject().as<JSFunction>());
151 if (!ArgumentsRestrictions(cx, fun))
152 return false;
153
154 // Return null if this function wasn't found on the stack.
155 NonBuiltinScriptFrameIter iter(cx);
156 if (!AdvanceToActiveCallLinear(cx, iter, fun)) {
157 args.rval().setNull();
158 return true;
159 }
160
161 Rooted<ArgumentsObject*> argsobj(cx, ArgumentsObject::createUnexpected(cx, iter));
162 if (!argsobj)
163 return false;
164
165 // Disabling compiling of this script in IonMonkey. IonMonkey doesn't
166 // guarantee |f.arguments| can be fully recovered, so we try to mitigate
167 // observing this behavior by detecting its use early.
168 JSScript* script = iter.script();
169 jit::ForbidCompilation(cx, script);
170
171 args.rval().setObject(*argsobj);
172 return true;
173 }
174
175 static bool
ArgumentsGetter(JSContext * cx,unsigned argc,Value * vp)176 ArgumentsGetter(JSContext* cx, unsigned argc, Value* vp)
177 {
178 CallArgs args = CallArgsFromVp(argc, vp);
179 return CallNonGenericMethod<IsFunction, ArgumentsGetterImpl>(cx, args);
180 }
181
182 bool
ArgumentsSetterImpl(JSContext * cx,const CallArgs & args)183 ArgumentsSetterImpl(JSContext* cx, const CallArgs& args)
184 {
185 MOZ_ASSERT(IsFunction(args.thisv()));
186
187 RootedFunction fun(cx, &args.thisv().toObject().as<JSFunction>());
188 if (!ArgumentsRestrictions(cx, fun))
189 return false;
190
191 // If the function passes the gauntlet, return |undefined|.
192 args.rval().setUndefined();
193 return true;
194 }
195
196 static bool
ArgumentsSetter(JSContext * cx,unsigned argc,Value * vp)197 ArgumentsSetter(JSContext* cx, unsigned argc, Value* vp)
198 {
199 CallArgs args = CallArgsFromVp(argc, vp);
200 return CallNonGenericMethod<IsFunction, ArgumentsSetterImpl>(cx, args);
201 }
202
203 // Beware: this function can be invoked on *any* function! That includes
204 // natives, strict mode functions, bound functions, arrow functions,
205 // self-hosted functions and constructors, asm.js functions, functions with
206 // destructuring arguments and/or a rest argument, and probably a few more I
207 // forgot. Turn back and save yourself while you still can. It's too late for
208 // me.
209 static bool
CallerRestrictions(JSContext * cx,HandleFunction fun)210 CallerRestrictions(JSContext* cx, HandleFunction fun)
211 {
212 // Throw if the function is a builtin (note: this doesn't include asm.js),
213 // a strict mode function (FIXME: needs work handle strict asm.js functions
214 // correctly, should fall out of bug 1057208), or a bound function.
215 if (fun->isBuiltin() ||
216 (fun->isInterpreted() && fun->strict()) ||
217 fun->isBoundFunction())
218 {
219 ThrowTypeErrorBehavior(cx);
220 return false;
221 }
222
223 // Otherwise emit a strict warning about |f.caller| to discourage use of
224 // this non-standard, performance-harmful feature.
225 if (!JS_ReportErrorFlagsAndNumber(cx, JSREPORT_WARNING | JSREPORT_STRICT, GetErrorMessage,
226 nullptr, JSMSG_DEPRECATED_USAGE, js_caller_str))
227 {
228 return false;
229 }
230
231 return true;
232 }
233
234 bool
CallerGetterImpl(JSContext * cx,const CallArgs & args)235 CallerGetterImpl(JSContext* cx, const CallArgs& args)
236 {
237 MOZ_ASSERT(IsFunction(args.thisv()));
238
239 // Beware! This function can be invoked on *any* function! It can't
240 // assume it'll never be invoked on natives, strict mode functions, bound
241 // functions, or anything else that ordinarily has immutable .caller
242 // defined with [[ThrowTypeError]].
243 RootedFunction fun(cx, &args.thisv().toObject().as<JSFunction>());
244 if (!CallerRestrictions(cx, fun))
245 return false;
246
247 // Also return null if this function wasn't found on the stack.
248 NonBuiltinScriptFrameIter iter(cx);
249 if (!AdvanceToActiveCallLinear(cx, iter, fun)) {
250 args.rval().setNull();
251 return true;
252 }
253
254 ++iter;
255 if (iter.done() || !iter.isFunctionFrame()) {
256 args.rval().setNull();
257 return true;
258 }
259
260 RootedObject caller(cx, iter.callee(cx));
261 if (!cx->compartment()->wrap(cx, &caller))
262 return false;
263
264 // Censor the caller if we don't have full access to it. If we do, but the
265 // caller is a function with strict mode code, throw a TypeError per ES5.
266 // If we pass these checks, we can return the computed caller.
267 {
268 JSObject* callerObj = CheckedUnwrap(caller);
269 if (!callerObj) {
270 args.rval().setNull();
271 return true;
272 }
273
274 JSFunction* callerFun = &callerObj->as<JSFunction>();
275 MOZ_ASSERT(!callerFun->isBuiltin(), "non-builtin iterator returned a builtin?");
276
277 if (callerFun->strict()) {
278 JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, GetErrorMessage, nullptr,
279 JSMSG_CALLER_IS_STRICT);
280 return false;
281 }
282 }
283
284 args.rval().setObject(*caller);
285 return true;
286 }
287
288 static bool
CallerGetter(JSContext * cx,unsigned argc,Value * vp)289 CallerGetter(JSContext* cx, unsigned argc, Value* vp)
290 {
291 CallArgs args = CallArgsFromVp(argc, vp);
292 return CallNonGenericMethod<IsFunction, CallerGetterImpl>(cx, args);
293 }
294
295 bool
CallerSetterImpl(JSContext * cx,const CallArgs & args)296 CallerSetterImpl(JSContext* cx, const CallArgs& args)
297 {
298 MOZ_ASSERT(IsFunction(args.thisv()));
299
300 // Beware! This function can be invoked on *any* function! It can't
301 // assume it'll never be invoked on natives, strict mode functions, bound
302 // functions, or anything else that ordinarily has immutable .caller
303 // defined with [[ThrowTypeError]].
304 RootedFunction fun(cx, &args.thisv().toObject().as<JSFunction>());
305 if (!CallerRestrictions(cx, fun))
306 return false;
307
308 // Return |undefined| unless an error must be thrown.
309 args.rval().setUndefined();
310
311 // We can almost just return |undefined| here -- but if the caller function
312 // was strict mode code, we still have to throw a TypeError. This requires
313 // computing the caller, checking that no security boundaries are crossed,
314 // and throwing a TypeError if the resulting caller is strict.
315
316 NonBuiltinScriptFrameIter iter(cx);
317 if (!AdvanceToActiveCallLinear(cx, iter, fun))
318 return true;
319
320 ++iter;
321 if (iter.done() || !iter.isFunctionFrame())
322 return true;
323
324 RootedObject caller(cx, iter.callee(cx));
325 if (!cx->compartment()->wrap(cx, &caller)) {
326 cx->clearPendingException();
327 return true;
328 }
329
330 // If we don't have full access to the caller, or the caller is not strict,
331 // return undefined. Otherwise throw a TypeError.
332 JSObject* callerObj = CheckedUnwrap(caller);
333 if (!callerObj)
334 return true;
335
336 JSFunction* callerFun = &callerObj->as<JSFunction>();
337 MOZ_ASSERT(!callerFun->isBuiltin(), "non-builtin iterator returned a builtin?");
338
339 if (callerFun->strict()) {
340 JS_ReportErrorFlagsAndNumber(cx, JSREPORT_ERROR, GetErrorMessage, nullptr,
341 JSMSG_CALLER_IS_STRICT);
342 return false;
343 }
344
345 return true;
346 }
347
348 static bool
CallerSetter(JSContext * cx,unsigned argc,Value * vp)349 CallerSetter(JSContext* cx, unsigned argc, Value* vp)
350 {
351 CallArgs args = CallArgsFromVp(argc, vp);
352 return CallNonGenericMethod<IsFunction, CallerSetterImpl>(cx, args);
353 }
354
355 static const JSPropertySpec function_properties[] = {
356 JS_PSGS("arguments", ArgumentsGetter, ArgumentsSetter, 0),
357 JS_PSGS("caller", CallerGetter, CallerSetter, 0),
358 JS_PS_END
359 };
360
361 static bool
ResolveInterpretedFunctionPrototype(JSContext * cx,HandleFunction fun,HandleId id)362 ResolveInterpretedFunctionPrototype(JSContext* cx, HandleFunction fun, HandleId id)
363 {
364 MOZ_ASSERT(fun->isInterpreted() || fun->isAsmJSNative());
365 MOZ_ASSERT(!fun->isFunctionPrototype());
366 MOZ_ASSERT(id == NameToId(cx->names().prototype));
367
368 // Assert that fun is not a compiler-created function object, which
369 // must never leak to script or embedding code and then be mutated.
370 // Also assert that fun is not bound, per the ES5 15.3.4.5 ref above.
371 MOZ_ASSERT(!IsInternalFunctionObject(*fun));
372 MOZ_ASSERT(!fun->isBoundFunction());
373
374 // Make the prototype object an instance of Object with the same parent as
375 // the function object itself, unless the function is an ES6 generator. In
376 // that case, per the 15 July 2013 ES6 draft, section 15.19.3, its parent is
377 // the GeneratorObjectPrototype singleton.
378 bool isStarGenerator = fun->isStarGenerator();
379 Rooted<GlobalObject*> global(cx, &fun->global());
380 RootedObject objProto(cx);
381 if (isStarGenerator)
382 objProto = GlobalObject::getOrCreateStarGeneratorObjectPrototype(cx, global);
383 else
384 objProto = fun->global().getOrCreateObjectPrototype(cx);
385 if (!objProto)
386 return false;
387
388 RootedPlainObject proto(cx, NewObjectWithGivenProto<PlainObject>(cx, objProto,
389 SingletonObject));
390 if (!proto)
391 return false;
392
393 // Per ES5 13.2 the prototype's .constructor property is configurable,
394 // non-enumerable, and writable. However, per the 15 July 2013 ES6 draft,
395 // section 15.19.3, the .prototype of a generator function does not link
396 // back with a .constructor.
397 if (!isStarGenerator) {
398 RootedValue objVal(cx, ObjectValue(*fun));
399 if (!DefineProperty(cx, proto, cx->names().constructor, objVal, nullptr, nullptr, 0))
400 return false;
401 }
402
403 // Per ES5 15.3.5.2 a user-defined function's .prototype property is
404 // initially non-configurable, non-enumerable, and writable.
405 RootedValue protoVal(cx, ObjectValue(*proto));
406 return DefineProperty(cx, fun, id, protoVal, nullptr, nullptr,
407 JSPROP_PERMANENT | JSPROP_RESOLVING);
408 }
409
410 static bool
fun_mayResolve(const JSAtomState & names,jsid id,JSObject *)411 fun_mayResolve(const JSAtomState& names, jsid id, JSObject*)
412 {
413 if (!JSID_IS_ATOM(id))
414 return false;
415
416 JSAtom* atom = JSID_TO_ATOM(id);
417 return atom == names.prototype || atom == names.length || atom == names.name;
418 }
419
420 static bool
fun_resolve(JSContext * cx,HandleObject obj,HandleId id,bool * resolvedp)421 fun_resolve(JSContext* cx, HandleObject obj, HandleId id, bool* resolvedp)
422 {
423 if (!JSID_IS_ATOM(id))
424 return true;
425
426 RootedFunction fun(cx, &obj->as<JSFunction>());
427
428 if (JSID_IS_ATOM(id, cx->names().prototype)) {
429 /*
430 * Built-in functions do not have a .prototype property per ECMA-262,
431 * or (Object.prototype, Function.prototype, etc.) have that property
432 * created eagerly.
433 *
434 * ES5 15.3.4.5: bound functions don't have a prototype property. The
435 * isBuiltin() test covers this case because bound functions are native
436 * (and thus built-in) functions by definition/construction.
437 *
438 * ES6 9.2.8 MakeConstructor defines the .prototype property on constructors.
439 * Generators are not constructors, but they have a .prototype property anyway,
440 * according to errata to ES6. See bug 1191486.
441 *
442 * Thus all of the following don't get a .prototype property:
443 * - Methods (that are not class-constructors or generators)
444 * - Arrow functions
445 * - Function.prototype
446 */
447 if (fun->isBuiltin() || (!fun->isConstructor() && !fun->isGenerator()))
448 return true;
449
450 if (!ResolveInterpretedFunctionPrototype(cx, fun, id))
451 return false;
452
453 *resolvedp = true;
454 return true;
455 }
456
457 bool isLength = JSID_IS_ATOM(id, cx->names().length);
458 if (isLength || JSID_IS_ATOM(id, cx->names().name)) {
459 MOZ_ASSERT(!IsInternalFunctionObject(*obj));
460
461 RootedValue v(cx);
462
463 // Since f.length and f.name are configurable, they could be resolved
464 // and then deleted:
465 // function f(x) {}
466 // assertEq(f.length, 1);
467 // delete f.length;
468 // assertEq(f.name, "f");
469 // delete f.name;
470 // Afterwards, asking for f.length or f.name again will cause this
471 // resolve hook to run again. Defining the property again the second
472 // time through would be a bug.
473 // assertEq(f.length, 0); // gets Function.prototype.length!
474 // assertEq(f.name, ""); // gets Function.prototype.name!
475 // We use the RESOLVED_LENGTH and RESOLVED_NAME flags as a hack to prevent this
476 // bug.
477 if (isLength) {
478 if (fun->hasResolvedLength())
479 return true;
480
481 uint16_t length;
482 if (!fun->getLength(cx, &length))
483 return false;
484
485 v.setInt32(length);
486 } else {
487 if (fun->hasResolvedName())
488 return true;
489
490 if (fun->isClassConstructor()) {
491 // It's impossible to have an empty named class expression. We
492 // use empty as a sentinel when creating default class
493 // constructors.
494 MOZ_ASSERT(fun->atom() != cx->names().empty);
495
496 // Unnamed class expressions should not get a .name property
497 // at all.
498 if (fun->atom() == nullptr)
499 return true;
500 }
501
502 v.setString(fun->atom() == nullptr ? cx->runtime()->emptyString : fun->atom());
503 }
504
505 if (!NativeDefineProperty(cx, fun, id, v, nullptr, nullptr,
506 JSPROP_READONLY | JSPROP_RESOLVING))
507 {
508 return false;
509 }
510
511 if (isLength)
512 fun->setResolvedLength();
513 else
514 fun->setResolvedName();
515
516 *resolvedp = true;
517 return true;
518 }
519
520 return true;
521 }
522
523 template<XDRMode mode>
524 bool
XDRInterpretedFunction(XDRState<mode> * xdr,HandleObject enclosingScope,HandleScript enclosingScript,MutableHandleFunction objp)525 js::XDRInterpretedFunction(XDRState<mode>* xdr, HandleObject enclosingScope, HandleScript enclosingScript,
526 MutableHandleFunction objp)
527 {
528 enum FirstWordFlag {
529 HasAtom = 0x1,
530 IsStarGenerator = 0x2,
531 IsLazy = 0x4,
532 HasSingletonType = 0x8
533 };
534
535 /* NB: Keep this in sync with CloneInnerInterpretedFunction. */
536 RootedAtom atom(xdr->cx());
537 uint32_t firstword = 0; /* bitmask of FirstWordFlag */
538 uint32_t flagsword = 0; /* word for argument count and fun->flags */
539
540 JSContext* cx = xdr->cx();
541 RootedFunction fun(cx);
542 RootedScript script(cx);
543 Rooted<LazyScript*> lazy(cx);
544
545 if (mode == XDR_ENCODE) {
546 fun = objp;
547 if (!fun->isInterpreted()) {
548 JSAutoByteString funNameBytes;
549 if (const char* name = GetFunctionNameBytes(cx, fun, &funNameBytes)) {
550 JS_ReportErrorNumber(cx, GetErrorMessage, nullptr,
551 JSMSG_NOT_SCRIPTED_FUNCTION, name);
552 }
553 return false;
554 }
555
556 if (fun->atom() || fun->hasGuessedAtom())
557 firstword |= HasAtom;
558
559 if (fun->isStarGenerator())
560 firstword |= IsStarGenerator;
561
562 if (fun->isInterpretedLazy()) {
563 // Encode a lazy script.
564 firstword |= IsLazy;
565 lazy = fun->lazyScript();
566 } else {
567 // Encode the script.
568 script = fun->nonLazyScript();
569 }
570
571 if (fun->isSingleton())
572 firstword |= HasSingletonType;
573
574 atom = fun->displayAtom();
575 flagsword = (fun->nargs() << 16) |
576 (fun->flags() & ~JSFunction::NO_XDR_FLAGS);
577
578 // The environment of any function which is not reused will always be
579 // null, it is later defined when a function is cloned or reused to
580 // mirror the scope chain.
581 MOZ_ASSERT_IF(fun->isSingleton() &&
582 !((lazy && lazy->hasBeenCloned()) || (script && script->hasBeenCloned())),
583 fun->environment() == nullptr);
584 }
585
586 if (!xdr->codeUint32(&firstword))
587 return false;
588
589 if ((firstword & HasAtom) && !XDRAtom(xdr, &atom))
590 return false;
591 if (!xdr->codeUint32(&flagsword))
592 return false;
593
594 if (mode == XDR_DECODE) {
595 RootedObject proto(cx);
596 if (firstword & IsStarGenerator) {
597 proto = GlobalObject::getOrCreateStarGeneratorFunctionPrototype(cx, cx->global());
598 if (!proto)
599 return false;
600 }
601
602 gc::AllocKind allocKind = gc::AllocKind::FUNCTION;
603 if (uint16_t(flagsword) & JSFunction::EXTENDED)
604 allocKind = gc::AllocKind::FUNCTION_EXTENDED;
605 fun = NewFunctionWithProto(cx, nullptr, 0, JSFunction::INTERPRETED,
606 /* enclosingDynamicScope = */ nullptr, nullptr, proto,
607 allocKind, TenuredObject);
608 if (!fun)
609 return false;
610 script = nullptr;
611 }
612
613 if (firstword & IsLazy) {
614 if (!XDRLazyScript(xdr, enclosingScope, enclosingScript, fun, &lazy))
615 return false;
616 } else {
617 if (!XDRScript(xdr, enclosingScope, enclosingScript, fun, &script))
618 return false;
619 }
620
621 if (mode == XDR_DECODE) {
622 fun->setArgCount(flagsword >> 16);
623 fun->setFlags(uint16_t(flagsword));
624 fun->initAtom(atom);
625 if (firstword & IsLazy) {
626 MOZ_ASSERT(fun->lazyScript() == lazy);
627 } else {
628 MOZ_ASSERT(fun->nonLazyScript() == script);
629 MOZ_ASSERT(fun->nargs() == script->bindings.numArgs());
630 }
631
632 bool singleton = firstword & HasSingletonType;
633 if (!JSFunction::setTypeForScriptedFunction(cx, fun, singleton))
634 return false;
635 objp.set(fun);
636 }
637
638 return true;
639 }
640
641 template bool
642 js::XDRInterpretedFunction(XDRState<XDR_ENCODE>*, HandleObject, HandleScript, MutableHandleFunction);
643
644 template bool
645 js::XDRInterpretedFunction(XDRState<XDR_DECODE>*, HandleObject, HandleScript, MutableHandleFunction);
646
647 /*
648 * [[HasInstance]] internal method for Function objects: fetch the .prototype
649 * property of its 'this' parameter, and walks the prototype chain of v (only
650 * if v is an object) returning true if .prototype is found.
651 */
652 static bool
fun_hasInstance(JSContext * cx,HandleObject objArg,MutableHandleValue v,bool * bp)653 fun_hasInstance(JSContext* cx, HandleObject objArg, MutableHandleValue v, bool* bp)
654 {
655 RootedObject obj(cx, objArg);
656
657 while (obj->is<JSFunction>() && obj->isBoundFunction())
658 obj = obj->as<JSFunction>().getBoundFunctionTarget();
659
660 RootedValue pval(cx);
661 if (!GetProperty(cx, obj, obj, cx->names().prototype, &pval))
662 return false;
663
664 if (pval.isPrimitive()) {
665 /*
666 * Throw a runtime error if instanceof is called on a function that
667 * has a non-object as its .prototype value.
668 */
669 RootedValue val(cx, ObjectValue(*obj));
670 ReportValueError(cx, JSMSG_BAD_PROTOTYPE, -1, val, nullptr);
671 return false;
672 }
673
674 RootedObject pobj(cx, &pval.toObject());
675 bool isDelegate;
676 if (!IsDelegate(cx, pobj, v, &isDelegate))
677 return false;
678 *bp = isDelegate;
679 return true;
680 }
681
682 inline void
trace(JSTracer * trc)683 JSFunction::trace(JSTracer* trc)
684 {
685 if (isExtended()) {
686 TraceRange(trc, ArrayLength(toExtended()->extendedSlots),
687 (HeapValue*)toExtended()->extendedSlots, "nativeReserved");
688 }
689
690 if (atom_)
691 TraceEdge(trc, &atom_, "atom");
692
693 if (isInterpreted()) {
694 // Functions can be be marked as interpreted despite having no script
695 // yet at some points when parsing, and can be lazy with no lazy script
696 // for self-hosted code.
697 if (hasScript() && !hasUncompiledScript())
698 TraceManuallyBarrieredEdge(trc, &u.i.s.script_, "script");
699 else if (isInterpretedLazy() && u.i.s.lazy_)
700 TraceManuallyBarrieredEdge(trc, &u.i.s.lazy_, "lazyScript");
701
702 if (!isBeingParsed() && u.i.env_)
703 TraceManuallyBarrieredEdge(trc, &u.i.env_, "fun_environment");
704 }
705 }
706
707 static void
fun_trace(JSTracer * trc,JSObject * obj)708 fun_trace(JSTracer* trc, JSObject* obj)
709 {
710 obj->as<JSFunction>().trace(trc);
711 }
712
713 static bool
ThrowTypeError(JSContext * cx,unsigned argc,Value * vp)714 ThrowTypeError(JSContext* cx, unsigned argc, Value* vp)
715 {
716 ThrowTypeErrorBehavior(cx);
717 return false;
718 }
719
720 static JSObject*
CreateFunctionConstructor(JSContext * cx,JSProtoKey key)721 CreateFunctionConstructor(JSContext* cx, JSProtoKey key)
722 {
723 Rooted<GlobalObject*> global(cx, cx->global());
724 RootedObject functionProto(cx, &global->getPrototype(JSProto_Function).toObject());
725
726 RootedObject functionCtor(cx,
727 NewFunctionWithProto(cx, Function, 1, JSFunction::NATIVE_CTOR,
728 nullptr, HandlePropertyName(cx->names().Function),
729 functionProto, AllocKind::FUNCTION, SingletonObject));
730 if (!functionCtor)
731 return nullptr;
732
733 return functionCtor;
734
735 }
736
737 static JSObject*
CreateFunctionPrototype(JSContext * cx,JSProtoKey key)738 CreateFunctionPrototype(JSContext* cx, JSProtoKey key)
739 {
740 Rooted<GlobalObject*> self(cx, cx->global());
741
742 RootedObject objectProto(cx, &self->getPrototype(JSProto_Object).toObject());
743 /*
744 * Bizarrely, |Function.prototype| must be an interpreted function, so
745 * give it the guts to be one.
746 */
747 JSObject* functionProto_ =
748 NewFunctionWithProto(cx, nullptr, 0, JSFunction::INTERPRETED,
749 self, nullptr, objectProto, AllocKind::FUNCTION,
750 SingletonObject);
751 if (!functionProto_)
752 return nullptr;
753
754 RootedFunction functionProto(cx, &functionProto_->as<JSFunction>());
755 functionProto->setIsFunctionPrototype();
756
757 const char* rawSource = "() {\n}";
758 size_t sourceLen = strlen(rawSource);
759 char16_t* source = InflateString(cx, rawSource, &sourceLen);
760 if (!source)
761 return nullptr;
762
763 ScriptSource* ss =
764 cx->new_<ScriptSource>();
765 if (!ss) {
766 js_free(source);
767 return nullptr;
768 }
769 ScriptSourceHolder ssHolder(ss);
770 ss->setSource(source, sourceLen);
771 CompileOptions options(cx);
772 options.setNoScriptRval(true)
773 .setVersion(JSVERSION_DEFAULT);
774 RootedScriptSource sourceObject(cx, ScriptSourceObject::create(cx, ss));
775 if (!sourceObject || !ScriptSourceObject::initFromOptions(cx, sourceObject, options))
776 return nullptr;
777
778 RootedScript script(cx, JSScript::Create(cx,
779 /* enclosingScope = */ nullptr,
780 /* savedCallerFun = */ false,
781 options,
782 sourceObject,
783 0,
784 ss->length()));
785 if (!script || !JSScript::fullyInitTrivial(cx, script))
786 return nullptr;
787
788 functionProto->initScript(script);
789 ObjectGroup* protoGroup = functionProto->getGroup(cx);
790 if (!protoGroup)
791 return nullptr;
792
793 protoGroup->setInterpretedFunction(functionProto);
794 script->setFunction(functionProto);
795
796 /*
797 * The default 'new' group of Function.prototype is required by type
798 * inference to have unknown properties, to simplify handling of e.g.
799 * NewFunctionClone.
800 */
801 if (!JSObject::setNewGroupUnknown(cx, &JSFunction::class_, functionProto))
802 return nullptr;
803
804 // Construct the unique [[%ThrowTypeError%]] function object, used only for
805 // "callee" and "caller" accessors on strict mode arguments objects. (The
806 // spec also uses this for "arguments" and "caller" on various functions,
807 // but we're experimenting with implementing them using accessors on
808 // |Function.prototype| right now.)
809 //
810 // Note that we can't use NewFunction here, even though we want the normal
811 // Function.prototype for our proto, because we're still in the middle of
812 // creating that as far as the world is concerned, so things will get all
813 // confused.
814 RootedFunction throwTypeError(cx,
815 NewFunctionWithProto(cx, ThrowTypeError, 0, JSFunction::NATIVE_FUN,
816 nullptr, nullptr, functionProto, AllocKind::FUNCTION,
817 SingletonObject));
818 if (!throwTypeError || !PreventExtensions(cx, throwTypeError))
819 return nullptr;
820
821 self->setThrowTypeError(throwTypeError);
822
823 return functionProto;
824 }
825
826 const Class JSFunction::class_ = {
827 js_Function_str,
828 JSCLASS_HAS_CACHED_PROTO(JSProto_Function),
829 nullptr, /* addProperty */
830 nullptr, /* delProperty */
831 nullptr, /* getProperty */
832 nullptr, /* setProperty */
833 fun_enumerate,
834 fun_resolve,
835 fun_mayResolve,
836 nullptr, /* finalize */
837 nullptr, /* call */
838 fun_hasInstance,
839 nullptr, /* construct */
840 fun_trace,
841 {
842 CreateFunctionConstructor,
843 CreateFunctionPrototype,
844 nullptr,
845 nullptr,
846 function_methods,
847 function_properties
848 }
849 };
850
851 const Class* const js::FunctionClassPtr = &JSFunction::class_;
852
853 /* Find the body of a function (not including braces). */
854 bool
FindBody(JSContext * cx,HandleFunction fun,HandleLinearString src,size_t * bodyStart,size_t * bodyEnd)855 js::FindBody(JSContext* cx, HandleFunction fun, HandleLinearString src, size_t* bodyStart,
856 size_t* bodyEnd)
857 {
858 // We don't need principals, since those are only used for error reporting.
859 CompileOptions options(cx);
860 options.setFileAndLine("internal-findBody", 0);
861
862 // For asm.js modules, there's no script.
863 if (fun->hasScript())
864 options.setVersion(fun->nonLazyScript()->getVersion());
865
866 AutoKeepAtoms keepAtoms(cx->perThreadData);
867
868 AutoStableStringChars stableChars(cx);
869 if (!stableChars.initTwoByte(cx, src))
870 return false;
871
872 const mozilla::Range<const char16_t> srcChars = stableChars.twoByteRange();
873 TokenStream ts(cx, options, srcChars.start().get(), srcChars.length(), nullptr);
874 int nest = 0;
875 bool onward = true;
876 // Skip arguments list.
877 do {
878 TokenKind tt;
879 if (!ts.getToken(&tt))
880 return false;
881 switch (tt) {
882 case TOK_NAME:
883 case TOK_YIELD:
884 if (nest == 0)
885 onward = false;
886 break;
887 case TOK_LP:
888 nest++;
889 break;
890 case TOK_RP:
891 if (--nest == 0)
892 onward = false;
893 break;
894 default:
895 break;
896 }
897 } while (onward);
898 TokenKind tt;
899 if (!ts.getToken(&tt))
900 return false;
901 if (tt == TOK_ARROW) {
902 if (!ts.getToken(&tt))
903 return false;
904 }
905 bool braced = tt == TOK_LC;
906 MOZ_ASSERT_IF(fun->isExprBody(), !braced);
907 *bodyStart = ts.currentToken().pos.begin;
908 if (braced)
909 *bodyStart += 1;
910 mozilla::RangedPtr<const char16_t> end = srcChars.end();
911 if (end[-1] == '}') {
912 end--;
913 } else {
914 MOZ_ASSERT(!braced);
915 for (; unicode::IsSpaceOrBOM2(end[-1]); end--)
916 ;
917 }
918 *bodyEnd = end - srcChars.start();
919 MOZ_ASSERT(*bodyStart <= *bodyEnd);
920 return true;
921 }
922
923 JSString*
FunctionToString(JSContext * cx,HandleFunction fun,bool lambdaParen)924 js::FunctionToString(JSContext* cx, HandleFunction fun, bool lambdaParen)
925 {
926 if (fun->isInterpretedLazy() && !fun->getOrCreateScript(cx))
927 return nullptr;
928
929 if (IsAsmJSModule(fun))
930 return AsmJSModuleToString(cx, fun, !lambdaParen);
931 if (IsAsmJSFunction(fun))
932 return AsmJSFunctionToString(cx, fun);
933
934 StringBuffer out(cx);
935 RootedScript script(cx);
936
937 if (fun->hasScript()) {
938 script = fun->nonLazyScript();
939 if (script->isGeneratorExp()) {
940 if (!out.append("function genexp() {") ||
941 !out.append("\n [generator expression]\n") ||
942 !out.append("}"))
943 {
944 return nullptr;
945 }
946 return out.finishString();
947 }
948 }
949
950 bool funIsMethodOrNonArrowLambda = (fun->isLambda() && !fun->isArrow()) || fun->isMethod() ||
951 fun->isGetter() || fun->isSetter();
952
953 // If we're not in pretty mode, put parentheses around lambda functions and methods.
954 if (fun->isInterpreted() && !lambdaParen && funIsMethodOrNonArrowLambda) {
955 if (!out.append("("))
956 return nullptr;
957 }
958 if (!fun->isArrow()) {
959 if (!(fun->isStarGenerator() ? out.append("function* ") : out.append("function ")))
960 return nullptr;
961 }
962 if (fun->atom()) {
963 if (!out.append(fun->atom()))
964 return nullptr;
965 }
966
967 bool haveSource = fun->isInterpreted() && !fun->isSelfHostedBuiltin();
968 if (haveSource && !script->scriptSource()->hasSourceData() &&
969 !JSScript::loadSource(cx, script->scriptSource(), &haveSource))
970 {
971 return nullptr;
972 }
973 if (haveSource) {
974 Rooted<JSFlatString*> src(cx, script->sourceData(cx));
975 if (!src)
976 return nullptr;
977
978 bool exprBody = fun->isExprBody();
979
980 // The source data for functions created by calling the Function
981 // constructor is only the function's body. This depends on the fact,
982 // asserted below, that in Function("function f() {}"), the inner
983 // function's sourceStart points to the '(', not the 'f'.
984 bool funCon = !fun->isArrow() &&
985 script->sourceStart() == 0 &&
986 script->sourceEnd() == script->scriptSource()->length() &&
987 script->scriptSource()->argumentsNotIncluded();
988
989 // Functions created with the constructor can't be arrow functions or
990 // expression closures.
991 MOZ_ASSERT_IF(funCon, !fun->isArrow());
992 MOZ_ASSERT_IF(funCon, !exprBody);
993 MOZ_ASSERT_IF(!funCon && !fun->isArrow(),
994 src->length() > 0 && src->latin1OrTwoByteChar(0) == '(');
995
996 // If a function inherits strict mode by having scopes above it that
997 // have "use strict", we insert "use strict" into the body of the
998 // function. This ensures that if the result of toString is evaled, the
999 // resulting function will have the same semantics.
1000 bool addUseStrict = script->strict() && !script->explicitUseStrict() && !fun->isArrow();
1001
1002 bool buildBody = funCon;
1003 if (buildBody) {
1004 // This function was created with the Function constructor. We don't
1005 // have source for the arguments, so we have to generate that. Part
1006 // of bug 755821 should be cobbling the arguments passed into the
1007 // Function constructor into the source string.
1008 if (!out.append("("))
1009 return nullptr;
1010
1011 // Fish out the argument names.
1012 MOZ_ASSERT(script->bindings.numArgs() == fun->nargs());
1013
1014 BindingIter bi(script);
1015 for (unsigned i = 0; i < fun->nargs(); i++, bi++) {
1016 MOZ_ASSERT(bi.argIndex() == i);
1017 if (i && !out.append(", "))
1018 return nullptr;
1019 if (i == unsigned(fun->nargs() - 1) && fun->hasRest() && !out.append("..."))
1020 return nullptr;
1021 if (!out.append(bi->name()))
1022 return nullptr;
1023 }
1024 if (!out.append(") {\n"))
1025 return nullptr;
1026 }
1027 if (addUseStrict) {
1028 // We need to get at the body either because we're only supposed to
1029 // return the body or we need to insert "use strict" into the body.
1030 size_t bodyStart = 0, bodyEnd;
1031
1032 // If the function is defined in the Function constructor, we
1033 // already have a body.
1034 if (!funCon) {
1035 MOZ_ASSERT(!buildBody);
1036 if (!FindBody(cx, fun, src, &bodyStart, &bodyEnd))
1037 return nullptr;
1038 } else {
1039 bodyEnd = src->length();
1040 }
1041
1042 if (addUseStrict) {
1043 // Output source up to beginning of body.
1044 if (!out.appendSubstring(src, 0, bodyStart))
1045 return nullptr;
1046 if (exprBody) {
1047 // We can't insert a statement into a function with an
1048 // expression body. Do what the decompiler did, and insert a
1049 // comment.
1050 if (!out.append("/* use strict */ "))
1051 return nullptr;
1052 } else {
1053 if (!out.append("\n\"use strict\";\n"))
1054 return nullptr;
1055 }
1056 }
1057
1058 // Output the body and possibly closing braces (for addUseStrict).
1059 if (!out.appendSubstring(src, bodyStart, src->length() - bodyStart))
1060 return nullptr;
1061 } else {
1062 if (!out.append(src))
1063 return nullptr;
1064 }
1065 if (buildBody) {
1066 if (!out.append("\n}"))
1067 return nullptr;
1068 }
1069 if (!lambdaParen && funIsMethodOrNonArrowLambda) {
1070 if (!out.append(")"))
1071 return nullptr;
1072 }
1073 } else if (fun->isInterpreted() && !fun->isSelfHostedBuiltin()) {
1074 if (!out.append("() {\n ") ||
1075 !out.append("[sourceless code]") ||
1076 !out.append("\n}"))
1077 {
1078 return nullptr;
1079 }
1080 if (!lambdaParen && fun->isLambda() && !fun->isArrow() && !out.append(")"))
1081 return nullptr;
1082 } else {
1083 MOZ_ASSERT(!fun->isExprBody());
1084
1085 if (fun->isNative() && fun->native() == js::DefaultDerivedClassConstructor) {
1086 if (!out.append("(...args) {\n ") ||
1087 !out.append("super(...args);\n}"))
1088 {
1089 return nullptr;
1090 }
1091 } else {
1092 if (!out.append("() {\n "))
1093 return nullptr;
1094
1095 if (!fun->isNative() || fun->native() != js::DefaultClassConstructor) {
1096 if (!out.append("[native code]"))
1097 return nullptr;
1098 }
1099
1100 if (!out.append("\n}"))
1101 return nullptr;
1102 }
1103 }
1104 return out.finishString();
1105 }
1106
1107 JSString*
fun_toStringHelper(JSContext * cx,HandleObject obj,unsigned indent)1108 fun_toStringHelper(JSContext* cx, HandleObject obj, unsigned indent)
1109 {
1110 if (!obj->is<JSFunction>()) {
1111 if (JSFunToStringOp op = obj->getOps()->funToString)
1112 return op(cx, obj, indent);
1113
1114 JS_ReportErrorNumber(cx, GetErrorMessage, nullptr,
1115 JSMSG_INCOMPATIBLE_PROTO,
1116 js_Function_str, js_toString_str,
1117 "object");
1118 return nullptr;
1119 }
1120
1121 RootedFunction fun(cx, &obj->as<JSFunction>());
1122 return FunctionToString(cx, fun, indent != JS_DONT_PRETTY_PRINT);
1123 }
1124
1125 bool
fun_toString(JSContext * cx,unsigned argc,Value * vp)1126 js::fun_toString(JSContext* cx, unsigned argc, Value* vp)
1127 {
1128 CallArgs args = CallArgsFromVp(argc, vp);
1129 MOZ_ASSERT(IsFunctionObject(args.calleev()));
1130
1131 uint32_t indent = 0;
1132
1133 if (args.length() != 0 && !ToUint32(cx, args[0], &indent))
1134 return false;
1135
1136 RootedObject obj(cx, ToObject(cx, args.thisv()));
1137 if (!obj)
1138 return false;
1139
1140 RootedString str(cx, fun_toStringHelper(cx, obj, indent));
1141 if (!str)
1142 return false;
1143
1144 args.rval().setString(str);
1145 return true;
1146 }
1147
1148 #if JS_HAS_TOSOURCE
1149 static bool
fun_toSource(JSContext * cx,unsigned argc,Value * vp)1150 fun_toSource(JSContext* cx, unsigned argc, Value* vp)
1151 {
1152 CallArgs args = CallArgsFromVp(argc, vp);
1153 MOZ_ASSERT(IsFunctionObject(args.calleev()));
1154
1155 RootedObject obj(cx, ToObject(cx, args.thisv()));
1156 if (!obj)
1157 return false;
1158
1159 RootedString str(cx);
1160 if (obj->isCallable())
1161 str = fun_toStringHelper(cx, obj, JS_DONT_PRETTY_PRINT);
1162 else
1163 str = ObjectToSource(cx, obj);
1164
1165 if (!str)
1166 return false;
1167 args.rval().setString(str);
1168 return true;
1169 }
1170 #endif
1171
1172 bool
fun_call(JSContext * cx,unsigned argc,Value * vp)1173 js::fun_call(JSContext* cx, unsigned argc, Value* vp)
1174 {
1175 CallArgs args = CallArgsFromVp(argc, vp);
1176
1177 HandleValue fval = args.thisv();
1178 if (!IsCallable(fval)) {
1179 ReportIncompatibleMethod(cx, args, &JSFunction::class_);
1180 return false;
1181 }
1182
1183 args.setCallee(fval);
1184 args.setThis(args.get(0));
1185
1186 if (args.length() > 0) {
1187 for (size_t i = 0; i < args.length() - 1; i++)
1188 args[i].set(args[i + 1]);
1189 args = CallArgsFromVp(args.length() - 1, vp);
1190 }
1191
1192 return Invoke(cx, args);
1193 }
1194
1195 // ES5 15.3.4.3
1196 bool
fun_apply(JSContext * cx,unsigned argc,Value * vp)1197 js::fun_apply(JSContext* cx, unsigned argc, Value* vp)
1198 {
1199 CallArgs args = CallArgsFromVp(argc, vp);
1200
1201 // Step 1.
1202 HandleValue fval = args.thisv();
1203 if (!IsCallable(fval)) {
1204 ReportIncompatibleMethod(cx, args, &JSFunction::class_);
1205 return false;
1206 }
1207
1208 // Step 2.
1209 if (args.length() < 2 || args[1].isNullOrUndefined())
1210 return fun_call(cx, (args.length() > 0) ? 1 : 0, vp);
1211
1212 InvokeArgs args2(cx);
1213
1214 // A JS_OPTIMIZED_ARGUMENTS magic value means that 'arguments' flows into
1215 // this apply call from a scripted caller and, as an optimization, we've
1216 // avoided creating it since apply can simply pull the argument values from
1217 // the calling frame (which we must do now).
1218 if (args[1].isMagic(JS_OPTIMIZED_ARGUMENTS)) {
1219 // Step 3-6.
1220 ScriptFrameIter iter(cx);
1221 MOZ_ASSERT(iter.numActualArgs() <= ARGS_LENGTH_MAX);
1222 if (!args2.init(cx, iter.numActualArgs()))
1223 return false;
1224
1225 args2.setCallee(fval);
1226 args2.setThis(args[0]);
1227
1228 // Steps 7-8.
1229 iter.unaliasedForEachActual(cx, CopyTo(args2.array()));
1230 } else {
1231 // Step 3.
1232 if (!args[1].isObject()) {
1233 JS_ReportErrorNumber(cx, GetErrorMessage, nullptr,
1234 JSMSG_BAD_APPLY_ARGS, js_apply_str);
1235 return false;
1236 }
1237
1238 // Steps 4-5 (note erratum removing steps originally numbered 5 and 7 in
1239 // original version of ES5).
1240 RootedObject aobj(cx, &args[1].toObject());
1241 uint32_t length;
1242 if (!GetLengthProperty(cx, aobj, &length))
1243 return false;
1244
1245 // Step 6.
1246 if (!args2.init(cx, length))
1247 return false;
1248
1249 // Push fval, obj, and aobj's elements as args.
1250 args2.setCallee(fval);
1251 args2.setThis(args[0]);
1252
1253 // Steps 7-8.
1254 if (!GetElements(cx, aobj, length, args2.array()))
1255 return false;
1256 }
1257
1258 // Step 9.
1259 if (!Invoke(cx, args2))
1260 return false;
1261
1262 args.rval().set(args2.rval());
1263 return true;
1264 }
1265
1266 static const uint32_t JSSLOT_BOUND_FUNCTION_TARGET = 0;
1267 static const uint32_t JSSLOT_BOUND_FUNCTION_THIS = 1;
1268 static const uint32_t JSSLOT_BOUND_FUNCTION_ARGS_COUNT = 2;
1269
1270 static const uint32_t BOUND_FUNCTION_RESERVED_SLOTS = 3;
1271
1272 inline bool
initBoundFunction(JSContext * cx,HandleObject target,HandleValue thisArg,const Value * args,unsigned argslen)1273 JSFunction::initBoundFunction(JSContext* cx, HandleObject target, HandleValue thisArg,
1274 const Value* args, unsigned argslen)
1275 {
1276 RootedFunction self(cx, this);
1277
1278 /*
1279 * Convert to a dictionary to set the BOUND_FUNCTION flag and increase
1280 * the slot span to cover the arguments and additional slots for the 'this'
1281 * value and arguments count.
1282 */
1283 if (!self->toDictionaryMode(cx))
1284 return false;
1285
1286 if (!self->JSObject::setFlags(cx, BaseShape::BOUND_FUNCTION))
1287 return false;
1288
1289 if (!self->setSlotSpan(cx, BOUND_FUNCTION_RESERVED_SLOTS + argslen))
1290 return false;
1291
1292 self->setSlot(JSSLOT_BOUND_FUNCTION_TARGET, ObjectValue(*target));
1293 self->setSlot(JSSLOT_BOUND_FUNCTION_THIS, thisArg);
1294 self->setSlot(JSSLOT_BOUND_FUNCTION_ARGS_COUNT, PrivateUint32Value(argslen));
1295
1296 self->initSlotRange(BOUND_FUNCTION_RESERVED_SLOTS, args, argslen);
1297
1298 self->setJitInfo(&jit::JitInfo_CallBoundFunction);
1299
1300 return true;
1301 }
1302
1303 JSObject*
getBoundFunctionTarget() const1304 JSFunction::getBoundFunctionTarget() const
1305 {
1306 MOZ_ASSERT(isBoundFunction());
1307
1308 return &getSlot(JSSLOT_BOUND_FUNCTION_TARGET).toObject();
1309 }
1310
1311 const js::Value&
getBoundFunctionThis() const1312 JSFunction::getBoundFunctionThis() const
1313 {
1314 MOZ_ASSERT(isBoundFunction());
1315
1316 return getSlot(JSSLOT_BOUND_FUNCTION_THIS);
1317 }
1318
1319 const js::Value&
getBoundFunctionArgument(unsigned which) const1320 JSFunction::getBoundFunctionArgument(unsigned which) const
1321 {
1322 MOZ_ASSERT(isBoundFunction());
1323 MOZ_ASSERT(which < getBoundFunctionArgumentCount());
1324
1325 return getSlot(BOUND_FUNCTION_RESERVED_SLOTS + which);
1326 }
1327
1328 size_t
getBoundFunctionArgumentCount() const1329 JSFunction::getBoundFunctionArgumentCount() const
1330 {
1331 MOZ_ASSERT(isBoundFunction());
1332
1333 return getSlot(JSSLOT_BOUND_FUNCTION_ARGS_COUNT).toPrivateUint32();
1334 }
1335
1336 /* static */ bool
createScriptForLazilyInterpretedFunction(JSContext * cx,HandleFunction fun)1337 JSFunction::createScriptForLazilyInterpretedFunction(JSContext* cx, HandleFunction fun)
1338 {
1339 MOZ_ASSERT(fun->isInterpretedLazy());
1340
1341 Rooted<LazyScript*> lazy(cx, fun->lazyScriptOrNull());
1342 if (lazy) {
1343 // Trigger a pre barrier on the lazy script being overwritten.
1344 if (cx->zone()->needsIncrementalBarrier())
1345 LazyScript::writeBarrierPre(lazy);
1346
1347 // Suppress GC for now although we should be able to remove this by
1348 // making 'lazy' a Rooted<LazyScript*> (which requires adding a
1349 // THING_ROOT_LAZY_SCRIPT).
1350 AutoSuppressGC suppressGC(cx);
1351
1352 RootedScript script(cx, lazy->maybeScript());
1353
1354 // Only functions without inner functions or direct eval are
1355 // re-lazified. Functions with either of those are on the static scope
1356 // chain of their inner functions, or in the case of eval, possibly
1357 // eval'd inner functions. This prohibits re-lazification as
1358 // StaticScopeIter queries needsCallObject of those functions, which
1359 // requires a non-lazy script. Note that if this ever changes,
1360 // XDRRelazificationInfo will have to be fixed.
1361 bool canRelazify = !lazy->numInnerFunctions() && !lazy->hasDirectEval();
1362
1363 if (script) {
1364 fun->setUnlazifiedScript(script);
1365 // Remember the lazy script on the compiled script, so it can be
1366 // stored on the function again in case of re-lazification.
1367 if (canRelazify)
1368 script->setLazyScript(lazy);
1369 return true;
1370 }
1371
1372 if (fun != lazy->functionNonDelazifying()) {
1373 if (!lazy->functionDelazifying(cx))
1374 return false;
1375 script = lazy->functionNonDelazifying()->nonLazyScript();
1376 if (!script)
1377 return false;
1378
1379 fun->setUnlazifiedScript(script);
1380 return true;
1381 }
1382
1383 // Lazy script caching is only supported for leaf functions. If a
1384 // script with inner functions was returned by the cache, those inner
1385 // functions would be delazified when deep cloning the script, even if
1386 // they have never executed.
1387 //
1388 // Additionally, the lazy script cache is not used during incremental
1389 // GCs, to avoid resurrecting dead scripts after incremental sweeping
1390 // has started.
1391 if (canRelazify && !JS::IsIncrementalGCInProgress(cx->runtime())) {
1392 LazyScriptCache::Lookup lookup(cx, lazy);
1393 cx->runtime()->lazyScriptCache.lookup(lookup, script.address());
1394 }
1395
1396 if (script) {
1397 RootedObject enclosingScope(cx, lazy->enclosingScope());
1398 RootedScript clonedScript(cx, CloneScriptIntoFunction(cx, enclosingScope, fun, script));
1399 if (!clonedScript)
1400 return false;
1401
1402 clonedScript->setSourceObject(lazy->sourceObject());
1403
1404 fun->initAtom(script->functionNonDelazifying()->displayAtom());
1405
1406 if (!lazy->maybeScript())
1407 lazy->initScript(clonedScript);
1408 return true;
1409 }
1410
1411 MOZ_ASSERT(lazy->scriptSource()->hasSourceData());
1412
1413 // Parse and compile the script from source.
1414 UncompressedSourceCache::AutoHoldEntry holder;
1415 const char16_t* chars = lazy->scriptSource()->chars(cx, holder);
1416 if (!chars)
1417 return false;
1418
1419 const char16_t* lazyStart = chars + lazy->begin();
1420 size_t lazyLength = lazy->end() - lazy->begin();
1421
1422 if (!frontend::CompileLazyFunction(cx, lazy, lazyStart, lazyLength)) {
1423 // The frontend may have linked the function and the non-lazy
1424 // script together during bytecode compilation. Reset it now on
1425 // error.
1426 fun->initLazyScript(lazy);
1427 if (lazy->hasScript())
1428 lazy->resetScript();
1429 return false;
1430 }
1431
1432 script = fun->nonLazyScript();
1433
1434 // Remember the compiled script on the lazy script itself, in case
1435 // there are clones of the function still pointing to the lazy script.
1436 if (!lazy->maybeScript())
1437 lazy->initScript(script);
1438
1439 // Try to insert the newly compiled script into the lazy script cache.
1440 if (canRelazify) {
1441 // A script's starting column isn't set by the bytecode emitter, so
1442 // specify this from the lazy script so that if an identical lazy
1443 // script is encountered later a match can be determined.
1444 script->setColumn(lazy->column());
1445
1446 LazyScriptCache::Lookup lookup(cx, lazy);
1447 cx->runtime()->lazyScriptCache.insert(lookup, script);
1448
1449 // Remember the lazy script on the compiled script, so it can be
1450 // stored on the function again in case of re-lazification.
1451 // Only functions without inner functions are re-lazified.
1452 script->setLazyScript(lazy);
1453 }
1454 return true;
1455 }
1456
1457 /* Lazily cloned self-hosted script. */
1458 MOZ_ASSERT(fun->isSelfHostedBuiltin());
1459 RootedAtom funAtom(cx, &fun->getExtendedSlot(LAZY_FUNCTION_NAME_SLOT).toString()->asAtom());
1460 if (!funAtom)
1461 return false;
1462 Rooted<PropertyName*> funName(cx, funAtom->asPropertyName());
1463 return cx->runtime()->cloneSelfHostedFunctionScript(cx, funName, fun);
1464 }
1465
1466 void
maybeRelazify(JSRuntime * rt)1467 JSFunction::maybeRelazify(JSRuntime* rt)
1468 {
1469 // Try to relazify functions with a non-lazy script. Note: functions can be
1470 // marked as interpreted despite having no script yet at some points when
1471 // parsing.
1472 if (!hasScript() || !u.i.s.script_)
1473 return;
1474
1475 // Don't relazify functions in compartments that are active.
1476 JSCompartment* comp = compartment();
1477 if (comp->hasBeenEntered() && !rt->allowRelazificationForTesting)
1478 return;
1479
1480 // Don't relazify if the compartment is being debugged or is the
1481 // self-hosting compartment.
1482 if (comp->isDebuggee() || comp->isSelfHosting)
1483 return;
1484
1485 // Don't relazify functions with JIT code.
1486 if (!u.i.s.script_->isRelazifiable())
1487 return;
1488
1489 // To delazify self-hosted builtins we need the name of the function
1490 // to clone. This name is stored in the first extended slot.
1491 if (isSelfHostedBuiltin() && !isExtended())
1492 return;
1493
1494 JSScript* script = nonLazyScript();
1495
1496 flags_ &= ~INTERPRETED;
1497 flags_ |= INTERPRETED_LAZY;
1498 LazyScript* lazy = script->maybeLazyScript();
1499 u.i.s.lazy_ = lazy;
1500 if (lazy) {
1501 MOZ_ASSERT(!isSelfHostedBuiltin());
1502 } else {
1503 MOZ_ASSERT(isSelfHostedBuiltin());
1504 MOZ_ASSERT(isExtended());
1505 MOZ_ASSERT(getExtendedSlot(LAZY_FUNCTION_NAME_SLOT).toString()->isAtom());
1506 }
1507 }
1508
1509 /* ES5 15.3.4.5.1 and 15.3.4.5.2. */
1510 bool
CallOrConstructBoundFunction(JSContext * cx,unsigned argc,Value * vp)1511 js::CallOrConstructBoundFunction(JSContext* cx, unsigned argc, Value* vp)
1512 {
1513 CallArgs args = CallArgsFromVp(argc, vp);
1514 RootedFunction fun(cx, &args.callee().as<JSFunction>());
1515 MOZ_ASSERT(fun->isBoundFunction());
1516
1517 /* 15.3.4.5.1 step 1, 15.3.4.5.2 step 3. */
1518 unsigned boundArgsLen = fun->getBoundFunctionArgumentCount();
1519
1520 uint32_t argsLen = args.length();
1521 if (argsLen + boundArgsLen > ARGS_LENGTH_MAX) {
1522 ReportAllocationOverflow(cx);
1523 return false;
1524 }
1525
1526 /* 15.3.4.5.1 step 3, 15.3.4.5.2 step 1. */
1527 RootedObject target(cx, fun->getBoundFunctionTarget());
1528
1529 /* 15.3.4.5.1 step 2. */
1530 const Value& boundThis = fun->getBoundFunctionThis();
1531
1532 if (args.isConstructing()) {
1533 ConstructArgs cargs(cx);
1534 if (!cargs.init(cx, argsLen + boundArgsLen))
1535 return false;
1536
1537 /* 15.3.4.5.1, 15.3.4.5.2 step 4. */
1538 for (uint32_t i = 0; i < boundArgsLen; i++)
1539 cargs[i].set(fun->getBoundFunctionArgument(i));
1540 for (uint32_t i = 0; i < argsLen; i++)
1541 cargs[boundArgsLen + i].set(args[i]);
1542
1543 RootedValue targetv(cx, ObjectValue(*target));
1544
1545 /* ES6 9.4.1.2 step 5 */
1546 RootedValue newTarget(cx);
1547 if (&args.newTarget().toObject() == fun)
1548 newTarget.set(targetv);
1549 else
1550 newTarget.set(args.newTarget());
1551
1552 return Construct(cx, targetv, cargs, newTarget, args.rval());
1553 }
1554
1555 InvokeArgs invokeArgs(cx);
1556 if (!invokeArgs.init(cx, argsLen + boundArgsLen))
1557 return false;
1558
1559 /* 15.3.4.5.1, 15.3.4.5.2 step 4. */
1560 for (uint32_t i = 0; i < boundArgsLen; i++)
1561 invokeArgs[i].set(fun->getBoundFunctionArgument(i));
1562 for (uint32_t i = 0; i < argsLen; i++)
1563 invokeArgs[boundArgsLen + i].set(args[i]);
1564
1565 /* 15.3.4.5.1, 15.3.4.5.2 step 5. */
1566 invokeArgs.setCallee(ObjectValue(*target));
1567 invokeArgs.setThis(boundThis);
1568
1569 if (!Invoke(cx, invokeArgs))
1570 return false;
1571
1572 args.rval().set(invokeArgs.rval());
1573 return true;
1574 }
1575
1576 static bool
fun_isGenerator(JSContext * cx,unsigned argc,Value * vp)1577 fun_isGenerator(JSContext* cx, unsigned argc, Value* vp)
1578 {
1579 CallArgs args = CallArgsFromVp(argc, vp);
1580 JSFunction* fun;
1581 if (!IsFunctionObject(args.thisv(), &fun)) {
1582 args.rval().setBoolean(false);
1583 return true;
1584 }
1585
1586 args.rval().setBoolean(fun->isGenerator());
1587 return true;
1588 }
1589
1590 static JSFunction*
NewNativeFunctionWithGivenProto(JSContext * cx,Native native,unsigned nargs,HandleAtom atom,HandleObject proto)1591 NewNativeFunctionWithGivenProto(JSContext* cx, Native native, unsigned nargs,
1592 HandleAtom atom, HandleObject proto)
1593 {
1594 return NewFunctionWithProto(cx, native, nargs, JSFunction::NATIVE_FUN, nullptr, atom, proto,
1595 AllocKind::FUNCTION, GenericObject, NewFunctionGivenProto);
1596 }
1597
1598 static JSFunction*
NewNativeConstructorWithGivenProto(JSContext * cx,Native native,unsigned nargs,HandleAtom atom,HandleObject proto)1599 NewNativeConstructorWithGivenProto(JSContext* cx, Native native, unsigned nargs,
1600 HandleAtom atom, HandleObject proto)
1601 {
1602 return NewFunctionWithProto(cx, native, nargs, JSFunction::NATIVE_CTOR, nullptr, atom, proto,
1603 AllocKind::FUNCTION, GenericObject, NewFunctionGivenProto);
1604 }
1605
1606 // ES6 draft rev32 19.2.3.2
1607 bool
fun_bind(JSContext * cx,unsigned argc,Value * vp)1608 js::fun_bind(JSContext* cx, unsigned argc, Value* vp)
1609 {
1610 CallArgs args = CallArgsFromVp(argc, vp);
1611
1612 // Step 1.
1613 RootedValue thisv(cx, args.thisv());
1614
1615 // Step 2.
1616 if (!IsCallable(thisv)) {
1617 ReportIncompatibleMethod(cx, args, &JSFunction::class_);
1618 return false;
1619 }
1620
1621 // Step 3.
1622 Value* boundArgs = nullptr;
1623 unsigned argslen = 0;
1624 if (args.length() > 1) {
1625 boundArgs = args.array() + 1;
1626 argslen = args.length() - 1;
1627 }
1628
1629 RootedValue thisArg(cx, args.length() >= 1 ? args[0] : UndefinedValue());
1630 RootedObject target(cx, &thisv.toObject());
1631
1632 // This is part of step 4, but we're delaying allocating the function object.
1633 RootedObject proto(cx);
1634 if (!GetPrototype(cx, target, &proto))
1635 return false;
1636
1637 double length = 0.0;
1638 // Try to avoid invoking the resolve hook.
1639 if (target->is<JSFunction>() && !target->as<JSFunction>().hasResolvedLength()) {
1640 uint16_t len;
1641 if (!target->as<JSFunction>().getLength(cx, &len))
1642 return false;
1643 length = Max(0.0, double(len) - argslen);
1644 } else {
1645 // Steps 5-6.
1646 RootedId id(cx, NameToId(cx->names().length));
1647 bool hasLength;
1648 if (!HasOwnProperty(cx, target, id, &hasLength))
1649 return false;
1650
1651 // Step 7-8.
1652 if (hasLength) {
1653 // a-b.
1654 RootedValue targetLen(cx);
1655 if (!GetProperty(cx, target, target, id, &targetLen))
1656 return false;
1657 // d.
1658 if (targetLen.isNumber())
1659 length = Max(0.0, JS::ToInteger(targetLen.toNumber()) - argslen);
1660 }
1661 }
1662
1663 RootedString name(cx, cx->names().empty);
1664 if (target->is<JSFunction>() && !target->as<JSFunction>().hasResolvedName()) {
1665 if (target->as<JSFunction>().atom())
1666 name = target->as<JSFunction>().atom();
1667 } else {
1668 // Steps 11-12.
1669 RootedValue targetName(cx);
1670 if (!GetProperty(cx, target, target, cx->names().name, &targetName))
1671 return false;
1672
1673 // Step 13.
1674 if (targetName.isString())
1675 name = targetName.toString();
1676 }
1677
1678 // Step 14. Relevant bits from SetFunctionName.
1679 StringBuffer sb(cx);
1680 // Disabled for B2G failures.
1681 // if (!sb.append("bound ") || !sb.append(name))
1682 // return false;
1683 if (!sb.append(name))
1684 return false;
1685
1686 RootedAtom nameAtom(cx, sb.finishAtom());
1687 if (!nameAtom)
1688 return false;
1689
1690 // Step 4.
1691 RootedFunction fun(cx, target->isConstructor() ?
1692 NewNativeConstructorWithGivenProto(cx, CallOrConstructBoundFunction, length, nameAtom, proto) :
1693 NewNativeFunctionWithGivenProto(cx, CallOrConstructBoundFunction, length, nameAtom, proto));
1694 if (!fun)
1695 return false;
1696
1697 if (!fun->initBoundFunction(cx, target, thisArg, boundArgs, argslen))
1698 return false;
1699
1700 // Steps 9-10. Set length again, because NewNativeFunction/NewNativeConstructor
1701 // sometimes truncates.
1702 if (length != fun->nargs()) {
1703 RootedValue lengthVal(cx, NumberValue(length));
1704 if (!DefineProperty(cx, fun, cx->names().length, lengthVal, nullptr, nullptr,
1705 JSPROP_READONLY))
1706 {
1707 return false;
1708 }
1709 }
1710
1711 // Step 15.
1712 args.rval().setObject(*fun);
1713 return true;
1714 }
1715
1716 /*
1717 * Report "malformed formal parameter" iff no illegal char or similar scanner
1718 * error was already reported.
1719 */
1720 static bool
OnBadFormal(JSContext * cx)1721 OnBadFormal(JSContext* cx)
1722 {
1723 JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_BAD_FORMAL);
1724 return false;
1725 }
1726
1727 const JSFunctionSpec js::function_methods[] = {
1728 #if JS_HAS_TOSOURCE
1729 JS_FN(js_toSource_str, fun_toSource, 0,0),
1730 #endif
1731 JS_FN(js_toString_str, fun_toString, 0,0),
1732 JS_FN(js_apply_str, fun_apply, 2,0),
1733 JS_FN(js_call_str, fun_call, 1,0),
1734 JS_FN("bind", fun_bind, 1,0),
1735 JS_FN("isGenerator", fun_isGenerator,0,0),
1736 JS_FS_END
1737 };
1738
1739 static bool
FunctionConstructor(JSContext * cx,unsigned argc,Value * vp,GeneratorKind generatorKind)1740 FunctionConstructor(JSContext* cx, unsigned argc, Value* vp, GeneratorKind generatorKind)
1741 {
1742 CallArgs args = CallArgsFromVp(argc, vp);
1743
1744 /* Block this call if security callbacks forbid it. */
1745 Rooted<GlobalObject*> global(cx, &args.callee().global());
1746 if (!GlobalObject::isRuntimeCodeGenEnabled(cx, global)) {
1747 JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_CSP_BLOCKED_FUNCTION);
1748 return false;
1749 }
1750
1751 bool isStarGenerator = generatorKind == StarGenerator;
1752 MOZ_ASSERT(generatorKind != LegacyGenerator);
1753
1754 RootedScript maybeScript(cx);
1755 const char* filename;
1756 unsigned lineno;
1757 bool mutedErrors;
1758 uint32_t pcOffset;
1759 DescribeScriptedCallerForCompilation(cx, &maybeScript, &filename, &lineno, &pcOffset,
1760 &mutedErrors);
1761
1762 const char* introductionType = "Function";
1763 if (generatorKind != NotGenerator)
1764 introductionType = "GeneratorFunction";
1765
1766 const char* introducerFilename = filename;
1767 if (maybeScript && maybeScript->scriptSource()->introducerFilename())
1768 introducerFilename = maybeScript->scriptSource()->introducerFilename();
1769
1770 CompileOptions options(cx);
1771 options.setMutedErrors(mutedErrors)
1772 .setFileAndLine(filename, 1)
1773 .setNoScriptRval(false)
1774 .setIntroductionInfo(introducerFilename, introductionType, lineno, maybeScript, pcOffset);
1775
1776 Vector<char16_t> paramStr(cx);
1777 RootedString bodyText(cx);
1778
1779 if (args.length() == 0) {
1780 bodyText = cx->names().empty;
1781 } else {
1782 // Collect the function-argument arguments into one string, separated
1783 // by commas, then make a tokenstream from that string, and scan it to
1784 // get the arguments. We need to throw the full scanner at the
1785 // problem because the argument string may contain comments, newlines,
1786 // destructuring arguments, and similar manner of insanities. ("I have
1787 // a feeling we're not in simple-comma-separated-parameters land any
1788 // more, Toto....")
1789 //
1790 // XXX It'd be better if the parser provided utility methods to parse
1791 // an argument list, and to parse a function body given a parameter
1792 // list. But our parser provides no such pleasant interface now.
1793 unsigned n = args.length() - 1;
1794
1795 // Convert the parameters-related arguments to strings, and determine
1796 // the length of the string containing the overall parameter list.
1797 mozilla::CheckedInt<uint32_t> paramStrLen = 0;
1798 RootedString str(cx);
1799 for (unsigned i = 0; i < n; i++) {
1800 str = ToString<CanGC>(cx, args[i]);
1801 if (!str)
1802 return false;
1803
1804 args[i].setString(str);
1805 paramStrLen += str->length();
1806 }
1807
1808 // Tack in space for any combining commas.
1809 if (n > 0)
1810 paramStrLen += n - 1;
1811
1812 // Check for integer and string-size overflow.
1813 if (!paramStrLen.isValid() || paramStrLen.value() > JSString::MAX_LENGTH) {
1814 ReportAllocationOverflow(cx);
1815 return false;
1816 }
1817
1818 uint32_t paramsLen = paramStrLen.value();
1819
1820 // Fill a vector with the comma-joined arguments. Careful! This
1821 // string is *not* null-terminated!
1822 MOZ_ASSERT(paramStr.length() == 0);
1823 if (!paramStr.growBy(paramsLen)) {
1824 ReportOutOfMemory(cx);
1825 return false;
1826 }
1827
1828 char16_t* cp = paramStr.begin();
1829 for (unsigned i = 0; i < n; i++) {
1830 JSLinearString* argLinear = args[i].toString()->ensureLinear(cx);
1831 if (!argLinear)
1832 return false;
1833
1834 CopyChars(cp, *argLinear);
1835 cp += argLinear->length();
1836
1837 if (i + 1 < n)
1838 *cp++ = ',';
1839 }
1840
1841 MOZ_ASSERT(cp == paramStr.end());
1842
1843 bodyText = ToString(cx, args[n]);
1844 if (!bodyText)
1845 return false;
1846 }
1847
1848 /*
1849 * NB: (new Function) is not lexically closed by its caller, it's just an
1850 * anonymous function in the top-level scope that its constructor inhabits.
1851 * Thus 'var x = 42; f = new Function("return x"); print(f())' prints 42,
1852 * and so would a call to f from another top-level's script or function.
1853 */
1854 RootedAtom anonymousAtom(cx, cx->names().anonymous);
1855 RootedObject proto(cx);
1856 if (isStarGenerator) {
1857 proto = GlobalObject::getOrCreateStarGeneratorFunctionPrototype(cx, global);
1858 if (!proto)
1859 return false;
1860 } else {
1861 if (!GetPrototypeFromCallableConstructor(cx, args, &proto))
1862 return false;
1863 }
1864
1865 RootedObject globalLexical(cx, &global->lexicalScope());
1866 RootedFunction fun(cx, NewFunctionWithProto(cx, nullptr, 0,
1867 JSFunction::INTERPRETED_LAMBDA, globalLexical,
1868 anonymousAtom, proto,
1869 AllocKind::FUNCTION, TenuredObject));
1870 if (!fun)
1871 return false;
1872
1873 if (!JSFunction::setTypeForScriptedFunction(cx, fun))
1874 return false;
1875
1876 AutoStableStringChars stableChars(cx);
1877 if (!stableChars.initTwoByte(cx, bodyText))
1878 return false;
1879
1880 bool hasRest = false;
1881
1882 Rooted<PropertyNameVector> formals(cx, PropertyNameVector(cx));
1883 if (args.length() > 1) {
1884 // Initialize a tokenstream to parse the new function's arguments. No
1885 // StrictModeGetter is needed because this TokenStream won't report any
1886 // strict mode errors. Strict mode errors that might be reported here
1887 // (duplicate argument names, etc.) will be detected when we compile
1888 // the function body.
1889 //
1890 // XXX Bug! We have to parse the body first to determine strictness.
1891 // We have to know strictness to parse arguments correctly, in case
1892 // arguments contains a strict mode violation. And we should be
1893 // using full-fledged arguments parsing here, in order to handle
1894 // destructuring and other exotic syntaxes.
1895 AutoKeepAtoms keepAtoms(cx->perThreadData);
1896 TokenStream ts(cx, options, paramStr.begin(), paramStr.length(),
1897 /* strictModeGetter = */ nullptr);
1898 bool yieldIsValidName = ts.versionNumber() < JSVERSION_1_7 && !isStarGenerator;
1899
1900 // The argument string may be empty or contain no tokens.
1901 TokenKind tt;
1902 if (!ts.getToken(&tt))
1903 return false;
1904 if (tt != TOK_EOF) {
1905 while (true) {
1906 // Check that it's a name.
1907 if (hasRest) {
1908 ts.reportError(JSMSG_PARAMETER_AFTER_REST);
1909 return false;
1910 }
1911
1912 if (tt == TOK_YIELD && yieldIsValidName)
1913 tt = TOK_NAME;
1914
1915 if (tt != TOK_NAME) {
1916 if (tt == TOK_TRIPLEDOT) {
1917 hasRest = true;
1918 if (!ts.getToken(&tt))
1919 return false;
1920 if (tt == TOK_YIELD && yieldIsValidName)
1921 tt = TOK_NAME;
1922 if (tt != TOK_NAME) {
1923 ts.reportError(JSMSG_NO_REST_NAME);
1924 return false;
1925 }
1926 } else {
1927 return OnBadFormal(cx);
1928 }
1929 }
1930
1931 if (!formals.append(ts.currentName()))
1932 return false;
1933
1934 // Get the next token. Stop on end of stream. Otherwise
1935 // insist on a comma, get another name, and iterate.
1936 if (!ts.getToken(&tt))
1937 return false;
1938 if (tt == TOK_EOF)
1939 break;
1940 if (tt != TOK_COMMA)
1941 return OnBadFormal(cx);
1942 if (!ts.getToken(&tt))
1943 return false;
1944 }
1945 }
1946 }
1947
1948 if (hasRest)
1949 fun->setHasRest();
1950
1951 mozilla::Range<const char16_t> chars = stableChars.twoByteRange();
1952 SourceBufferHolder::Ownership ownership = stableChars.maybeGiveOwnershipToCaller()
1953 ? SourceBufferHolder::GiveOwnership
1954 : SourceBufferHolder::NoOwnership;
1955 bool ok;
1956 SourceBufferHolder srcBuf(chars.start().get(), chars.length(), ownership);
1957 if (isStarGenerator)
1958 ok = frontend::CompileStarGeneratorBody(cx, &fun, options, formals, srcBuf);
1959 else
1960 ok = frontend::CompileFunctionBody(cx, &fun, options, formals, srcBuf);
1961 args.rval().setObject(*fun);
1962 return ok;
1963 }
1964
1965 bool
Function(JSContext * cx,unsigned argc,Value * vp)1966 js::Function(JSContext* cx, unsigned argc, Value* vp)
1967 {
1968 return FunctionConstructor(cx, argc, vp, NotGenerator);
1969 }
1970
1971 bool
Generator(JSContext * cx,unsigned argc,Value * vp)1972 js::Generator(JSContext* cx, unsigned argc, Value* vp)
1973 {
1974 return FunctionConstructor(cx, argc, vp, StarGenerator);
1975 }
1976
1977 bool
isBuiltinFunctionConstructor()1978 JSFunction::isBuiltinFunctionConstructor()
1979 {
1980 return maybeNative() == Function || maybeNative() == Generator;
1981 }
1982
1983 JSFunction*
NewNativeFunction(ExclusiveContext * cx,Native native,unsigned nargs,HandleAtom atom,gc::AllocKind allocKind,NewObjectKind newKind)1984 js::NewNativeFunction(ExclusiveContext* cx, Native native, unsigned nargs, HandleAtom atom,
1985 gc::AllocKind allocKind /* = AllocKind::FUNCTION */,
1986 NewObjectKind newKind /* = GenericObject */)
1987 {
1988 return NewFunctionWithProto(cx, native, nargs, JSFunction::NATIVE_FUN,
1989 nullptr, atom, nullptr, allocKind, newKind);
1990 }
1991
1992 JSFunction*
NewNativeConstructor(ExclusiveContext * cx,Native native,unsigned nargs,HandleAtom atom,gc::AllocKind allocKind,NewObjectKind newKind,JSFunction::Flags flags)1993 js::NewNativeConstructor(ExclusiveContext* cx, Native native, unsigned nargs, HandleAtom atom,
1994 gc::AllocKind allocKind /* = AllocKind::FUNCTION */,
1995 NewObjectKind newKind /* = GenericObject */,
1996 JSFunction::Flags flags /* = JSFunction::NATIVE_CTOR */)
1997 {
1998 MOZ_ASSERT(flags & JSFunction::NATIVE_CTOR);
1999 return NewFunctionWithProto(cx, native, nargs, flags, nullptr, atom,
2000 nullptr, allocKind, newKind);
2001 }
2002
2003 JSFunction*
NewScriptedFunction(ExclusiveContext * cx,unsigned nargs,JSFunction::Flags flags,HandleAtom atom,gc::AllocKind allocKind,NewObjectKind newKind,HandleObject enclosingDynamicScopeArg)2004 js::NewScriptedFunction(ExclusiveContext* cx, unsigned nargs,
2005 JSFunction::Flags flags, HandleAtom atom,
2006 gc::AllocKind allocKind /* = AllocKind::FUNCTION */,
2007 NewObjectKind newKind /* = GenericObject */,
2008 HandleObject enclosingDynamicScopeArg /* = nullptr */)
2009 {
2010 RootedObject enclosingDynamicScope(cx, enclosingDynamicScopeArg);
2011 if (!enclosingDynamicScope)
2012 enclosingDynamicScope = &cx->global()->lexicalScope();
2013 return NewFunctionWithProto(cx, nullptr, nargs, flags, enclosingDynamicScope,
2014 atom, nullptr, allocKind, newKind);
2015 }
2016
2017 #ifdef DEBUG
2018 static bool
NewFunctionScopeIsWellFormed(ExclusiveContext * cx,HandleObject parent)2019 NewFunctionScopeIsWellFormed(ExclusiveContext* cx, HandleObject parent)
2020 {
2021 // Assert that the parent is null, global, or a debug scope proxy. All
2022 // other cases of polluting global scope behavior are handled by
2023 // ScopeObjects (viz. non-syntactic DynamicWithObject and
2024 // NonSyntacticVariablesObject).
2025 RootedObject realParent(cx, SkipScopeParent(parent));
2026 return !realParent || realParent == cx->global() ||
2027 realParent->is<DebugScopeObject>();
2028 }
2029 #endif
2030
2031 JSFunction*
NewFunctionWithProto(ExclusiveContext * cx,Native native,unsigned nargs,JSFunction::Flags flags,HandleObject enclosingDynamicScope,HandleAtom atom,HandleObject proto,gc::AllocKind allocKind,NewObjectKind newKind,NewFunctionProtoHandling protoHandling)2032 js::NewFunctionWithProto(ExclusiveContext* cx, Native native,
2033 unsigned nargs, JSFunction::Flags flags, HandleObject enclosingDynamicScope,
2034 HandleAtom atom, HandleObject proto,
2035 gc::AllocKind allocKind /* = AllocKind::FUNCTION */,
2036 NewObjectKind newKind /* = GenericObject */,
2037 NewFunctionProtoHandling protoHandling /* = NewFunctionClassProto */)
2038 {
2039 MOZ_ASSERT(allocKind == AllocKind::FUNCTION || allocKind == AllocKind::FUNCTION_EXTENDED);
2040 MOZ_ASSERT_IF(native, !enclosingDynamicScope);
2041 MOZ_ASSERT(NewFunctionScopeIsWellFormed(cx, enclosingDynamicScope));
2042
2043 RootedObject funobj(cx);
2044 // Don't mark asm.js module functions as singleton since they are
2045 // cloned (via CloneFunctionObjectIfNotSingleton) which assumes that
2046 // isSingleton implies isInterpreted.
2047 if (native && !IsAsmJSModuleNative(native))
2048 newKind = SingletonObject;
2049
2050 if (protoHandling == NewFunctionClassProto) {
2051 funobj = NewObjectWithClassProto(cx, &JSFunction::class_, proto, allocKind,
2052 newKind);
2053 } else {
2054 funobj = NewObjectWithGivenTaggedProto(cx, &JSFunction::class_, AsTaggedProto(proto),
2055 allocKind, newKind);
2056 }
2057 if (!funobj)
2058 return nullptr;
2059
2060 RootedFunction fun(cx, &funobj->as<JSFunction>());
2061
2062 if (allocKind == AllocKind::FUNCTION_EXTENDED)
2063 flags = JSFunction::Flags(flags | JSFunction::EXTENDED);
2064
2065 /* Initialize all function members. */
2066 fun->setArgCount(uint16_t(nargs));
2067 fun->setFlags(flags);
2068 if (fun->isInterpreted()) {
2069 MOZ_ASSERT(!native);
2070 if (fun->isInterpretedLazy())
2071 fun->initLazyScript(nullptr);
2072 else
2073 fun->initScript(nullptr);
2074 fun->initEnvironment(enclosingDynamicScope);
2075 } else {
2076 MOZ_ASSERT(fun->isNative());
2077 MOZ_ASSERT(native);
2078 fun->initNative(native, nullptr);
2079 }
2080 if (allocKind == AllocKind::FUNCTION_EXTENDED)
2081 fun->initializeExtended();
2082 fun->initAtom(atom);
2083
2084 return fun;
2085 }
2086
2087 bool
CanReuseScriptForClone(JSCompartment * compartment,HandleFunction fun,HandleObject newParent)2088 js::CanReuseScriptForClone(JSCompartment* compartment, HandleFunction fun,
2089 HandleObject newParent)
2090 {
2091 if (compartment != fun->compartment() ||
2092 fun->isSingleton() ||
2093 ObjectGroup::useSingletonForClone(fun))
2094 {
2095 return false;
2096 }
2097
2098 if (newParent->is<GlobalObject>())
2099 return true;
2100
2101 // Don't need to clone the script if newParent is a syntactic scope, since
2102 // in that case we have some actual scope objects on our scope chain and
2103 // whatnot; whoever put them there should be responsible for setting our
2104 // script's flags appropriately. We hit this case for JSOP_LAMBDA, for
2105 // example.
2106 if (IsSyntacticScope(newParent))
2107 return true;
2108
2109 // We need to clone the script if we're interpreted and not already marked
2110 // as having a non-syntactic scope. If we're lazy, go ahead and clone the
2111 // script; see the big comment at the end of CopyScriptInternal for the
2112 // explanation of what's going on there.
2113 return !fun->isInterpreted() ||
2114 (fun->hasScript() && fun->nonLazyScript()->hasNonSyntacticScope());
2115 }
2116
2117 static inline JSFunction*
NewFunctionClone(JSContext * cx,HandleFunction fun,NewObjectKind newKind,gc::AllocKind allocKind,HandleObject proto)2118 NewFunctionClone(JSContext* cx, HandleFunction fun, NewObjectKind newKind,
2119 gc::AllocKind allocKind, HandleObject proto)
2120 {
2121 RootedObject cloneProto(cx, proto);
2122 if (!proto && fun->isStarGenerator()) {
2123 cloneProto = GlobalObject::getOrCreateStarGeneratorFunctionPrototype(cx, cx->global());
2124 if (!cloneProto)
2125 return nullptr;
2126 }
2127
2128 JSObject* cloneobj = NewObjectWithClassProto(cx, &JSFunction::class_, cloneProto,
2129 allocKind, newKind);
2130 if (!cloneobj)
2131 return nullptr;
2132 RootedFunction clone(cx, &cloneobj->as<JSFunction>());
2133
2134 uint16_t flags = fun->flags() & ~JSFunction::EXTENDED;
2135 if (allocKind == AllocKind::FUNCTION_EXTENDED)
2136 flags |= JSFunction::EXTENDED;
2137
2138 clone->setArgCount(fun->nargs());
2139 clone->setFlags(flags);
2140 clone->initAtom(fun->displayAtom());
2141
2142 if (allocKind == AllocKind::FUNCTION_EXTENDED) {
2143 if (fun->isExtended() && fun->compartment() == cx->compartment()) {
2144 for (unsigned i = 0; i < FunctionExtended::NUM_EXTENDED_SLOTS; i++)
2145 clone->initExtendedSlot(i, fun->getExtendedSlot(i));
2146 } else {
2147 clone->initializeExtended();
2148 }
2149 }
2150
2151 return clone;
2152 }
2153
2154 JSFunction*
CloneFunctionReuseScript(JSContext * cx,HandleFunction fun,HandleObject parent,gc::AllocKind allocKind,NewObjectKind newKind,HandleObject proto)2155 js::CloneFunctionReuseScript(JSContext* cx, HandleFunction fun, HandleObject parent,
2156 gc::AllocKind allocKind /* = FUNCTION */ ,
2157 NewObjectKind newKind /* = GenericObject */,
2158 HandleObject proto /* = nullptr */)
2159 {
2160 MOZ_ASSERT(NewFunctionScopeIsWellFormed(cx, parent));
2161 MOZ_ASSERT(!fun->isBoundFunction());
2162 MOZ_ASSERT(CanReuseScriptForClone(cx->compartment(), fun, parent));
2163
2164 RootedFunction clone(cx, NewFunctionClone(cx, fun, newKind, allocKind, proto));
2165 if (!clone)
2166 return nullptr;
2167
2168 if (fun->hasScript()) {
2169 clone->initScript(fun->nonLazyScript());
2170 clone->initEnvironment(parent);
2171 } else if (fun->isInterpretedLazy()) {
2172 MOZ_ASSERT(fun->compartment() == clone->compartment());
2173 LazyScript* lazy = fun->lazyScriptOrNull();
2174 clone->initLazyScript(lazy);
2175 clone->initEnvironment(parent);
2176 } else {
2177 clone->initNative(fun->native(), fun->jitInfo());
2178 }
2179
2180 /*
2181 * Clone the function, reusing its script. We can use the same group as
2182 * the original function provided that its prototype is correct.
2183 */
2184 if (fun->getProto() == clone->getProto())
2185 clone->setGroup(fun->group());
2186 return clone;
2187 }
2188
2189 JSFunction*
CloneFunctionAndScript(JSContext * cx,HandleFunction fun,HandleObject parent,HandleObject newStaticScope,gc::AllocKind allocKind,HandleObject proto)2190 js::CloneFunctionAndScript(JSContext* cx, HandleFunction fun, HandleObject parent,
2191 HandleObject newStaticScope,
2192 gc::AllocKind allocKind /* = FUNCTION */,
2193 HandleObject proto /* = nullptr */)
2194 {
2195 MOZ_ASSERT(NewFunctionScopeIsWellFormed(cx, parent));
2196 MOZ_ASSERT(!fun->isBoundFunction());
2197
2198 JSScript::AutoDelazify funScript(cx);
2199 if (fun->isInterpreted()) {
2200 funScript = fun;
2201 if (!funScript)
2202 return nullptr;
2203 }
2204
2205 RootedFunction clone(cx, NewFunctionClone(cx, fun, SingletonObject, allocKind, proto));
2206 if (!clone)
2207 return nullptr;
2208
2209 if (fun->hasScript()) {
2210 clone->initScript(nullptr);
2211 clone->initEnvironment(parent);
2212 } else {
2213 clone->initNative(fun->native(), fun->jitInfo());
2214 }
2215
2216 /*
2217 * Across compartments or if we have to introduce a non-syntactic scope we
2218 * have to clone the script for interpreted functions. Cross-compartment
2219 * cloning only happens via JSAPI (JS::CloneFunctionObject) which
2220 * dynamically ensures that 'script' has no enclosing lexical scope (only
2221 * the global scope or other non-lexical scope).
2222 */
2223 #ifdef DEBUG
2224 RootedObject terminatingScope(cx, parent);
2225 while (IsSyntacticScope(terminatingScope))
2226 terminatingScope = terminatingScope->enclosingScope();
2227 MOZ_ASSERT_IF(!terminatingScope->is<GlobalObject>(),
2228 HasNonSyntacticStaticScopeChain(newStaticScope));
2229 #endif
2230
2231 if (clone->isInterpreted()) {
2232 RootedScript script(cx, fun->nonLazyScript());
2233 MOZ_ASSERT(script->compartment() == fun->compartment());
2234 MOZ_ASSERT(cx->compartment() == clone->compartment(),
2235 "Otherwise we could relazify clone below!");
2236
2237 RootedScript clonedScript(cx, CloneScriptIntoFunction(cx, newStaticScope, clone, script));
2238 if (!clonedScript)
2239 return nullptr;
2240 Debugger::onNewScript(cx, clonedScript);
2241 }
2242
2243 return clone;
2244 }
2245
2246 /*
2247 * Return an atom for use as the name of a builtin method with the given
2248 * property id.
2249 *
2250 * Function names are always strings. If id is the well-known @@iterator
2251 * symbol, this returns "[Symbol.iterator]".
2252 *
2253 * Implements step 4 of SetFunctionName in ES6 draft rev 27 (24 Aug 2014).
2254 */
2255 JSAtom*
IdToFunctionName(JSContext * cx,HandleId id)2256 js::IdToFunctionName(JSContext* cx, HandleId id)
2257 {
2258 if (JSID_IS_ATOM(id))
2259 return JSID_TO_ATOM(id);
2260
2261 if (JSID_IS_SYMBOL(id)) {
2262 RootedAtom desc(cx, JSID_TO_SYMBOL(id)->description());
2263 StringBuffer sb(cx);
2264 if (!sb.append('[') || !sb.append(desc) || !sb.append(']'))
2265 return nullptr;
2266 return sb.finishAtom();
2267 }
2268
2269 RootedValue idv(cx, IdToValue(id));
2270 return ToAtom<CanGC>(cx, idv);
2271 }
2272
2273 JSFunction*
DefineFunction(JSContext * cx,HandleObject obj,HandleId id,Native native,unsigned nargs,unsigned flags,AllocKind allocKind)2274 js::DefineFunction(JSContext* cx, HandleObject obj, HandleId id, Native native,
2275 unsigned nargs, unsigned flags, AllocKind allocKind /* = AllocKind::FUNCTION */)
2276 {
2277 GetterOp gop;
2278 SetterOp sop;
2279 if (flags & JSFUN_STUB_GSOPS) {
2280 /*
2281 * JSFUN_STUB_GSOPS is a request flag only, not stored in fun->flags or
2282 * the defined property's attributes. This allows us to encode another,
2283 * internal flag using the same bit, JSFUN_EXPR_CLOSURE -- see jsfun.h
2284 * for more on this.
2285 */
2286 flags &= ~JSFUN_STUB_GSOPS;
2287 gop = nullptr;
2288 sop = nullptr;
2289 } else {
2290 gop = obj->getClass()->getProperty;
2291 sop = obj->getClass()->setProperty;
2292 MOZ_ASSERT(gop != JS_PropertyStub);
2293 MOZ_ASSERT(sop != JS_StrictPropertyStub);
2294 }
2295
2296 RootedAtom atom(cx, IdToFunctionName(cx, id));
2297 if (!atom)
2298 return nullptr;
2299
2300 RootedFunction fun(cx);
2301 if (!native)
2302 fun = NewScriptedFunction(cx, nargs,
2303 JSFunction::INTERPRETED_LAZY, atom,
2304 allocKind, GenericObject, obj);
2305 else if (flags & JSFUN_CONSTRUCTOR)
2306 fun = NewNativeConstructor(cx, native, nargs, atom, allocKind);
2307 else
2308 fun = NewNativeFunction(cx, native, nargs, atom, allocKind);
2309
2310 if (!fun)
2311 return nullptr;
2312
2313 RootedValue funVal(cx, ObjectValue(*fun));
2314 if (!DefineProperty(cx, obj, id, funVal, gop, sop, flags & ~JSFUN_FLAGS_MASK))
2315 return nullptr;
2316
2317 return fun;
2318 }
2319
2320 void
ReportIncompatibleMethod(JSContext * cx,CallReceiver call,const Class * clasp)2321 js::ReportIncompatibleMethod(JSContext* cx, CallReceiver call, const Class* clasp)
2322 {
2323 RootedValue thisv(cx, call.thisv());
2324
2325 #ifdef DEBUG
2326 if (thisv.isObject()) {
2327 MOZ_ASSERT(thisv.toObject().getClass() != clasp ||
2328 !thisv.toObject().isNative() ||
2329 !thisv.toObject().getProto() ||
2330 thisv.toObject().getProto()->getClass() != clasp);
2331 } else if (thisv.isString()) {
2332 MOZ_ASSERT(clasp != &StringObject::class_);
2333 } else if (thisv.isNumber()) {
2334 MOZ_ASSERT(clasp != &NumberObject::class_);
2335 } else if (thisv.isBoolean()) {
2336 MOZ_ASSERT(clasp != &BooleanObject::class_);
2337 } else if (thisv.isSymbol()) {
2338 MOZ_ASSERT(clasp != &SymbolObject::class_);
2339 } else {
2340 MOZ_ASSERT(thisv.isUndefined() || thisv.isNull());
2341 }
2342 #endif
2343
2344 if (JSFunction* fun = ReportIfNotFunction(cx, call.calleev())) {
2345 JSAutoByteString funNameBytes;
2346 if (const char* funName = GetFunctionNameBytes(cx, fun, &funNameBytes)) {
2347 JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_PROTO,
2348 clasp->name, funName, InformalValueTypeName(thisv));
2349 }
2350 }
2351 }
2352
2353 void
ReportIncompatible(JSContext * cx,CallReceiver call)2354 js::ReportIncompatible(JSContext* cx, CallReceiver call)
2355 {
2356 if (JSFunction* fun = ReportIfNotFunction(cx, call.calleev())) {
2357 JSAutoByteString funNameBytes;
2358 if (const char* funName = GetFunctionNameBytes(cx, fun, &funNameBytes)) {
2359 JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_INCOMPATIBLE_METHOD,
2360 funName, "method", InformalValueTypeName(call.thisv()));
2361 }
2362 }
2363 }
2364
2365 namespace JS {
2366 namespace detail {
2367
2368 JS_PUBLIC_API(void)
CheckIsValidConstructible(Value calleev)2369 CheckIsValidConstructible(Value calleev)
2370 {
2371 JSObject* callee = &calleev.toObject();
2372 if (callee->is<JSFunction>())
2373 MOZ_ASSERT(callee->as<JSFunction>().isConstructor());
2374 else
2375 MOZ_ASSERT(callee->constructHook() != nullptr);
2376 }
2377
2378 } // namespace detail
2379 } // namespace JS
2380