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  * JavaScript API.
9  */
10 
11 #include "jsapi.h"
12 
13 #include "mozilla/FloatingPoint.h"
14 #include "mozilla/PodOperations.h"
15 #include "mozilla/UniquePtr.h"
16 
17 #include <ctype.h>
18 #include <stdarg.h>
19 #include <string.h>
20 #include <sys/stat.h>
21 
22 #include "jsarray.h"
23 #include "jsatom.h"
24 #include "jsbool.h"
25 #include "jscntxt.h"
26 #include "jsdate.h"
27 #include "jsexn.h"
28 #include "jsfriendapi.h"
29 #include "jsfun.h"
30 #include "jsgc.h"
31 #include "jsiter.h"
32 #include "jslock.h"
33 #include "jsmath.h"
34 #include "jsnum.h"
35 #include "jsobj.h"
36 #include "json.h"
37 #include "jsprf.h"
38 #include "jsscript.h"
39 #include "jsstr.h"
40 #include "jstypes.h"
41 #include "jsutil.h"
42 #include "jswatchpoint.h"
43 #include "jsweakmap.h"
44 #include "jswrapper.h"
45 
46 #include "asmjs/AsmJSLink.h"
47 #include "builtin/AtomicsObject.h"
48 #include "builtin/Eval.h"
49 #include "builtin/Intl.h"
50 #include "builtin/MapObject.h"
51 #include "builtin/RegExp.h"
52 #include "builtin/SymbolObject.h"
53 #ifdef ENABLE_BINARYDATA
54 #include "builtin/SIMD.h"
55 #include "builtin/TypedObject.h"
56 #endif
57 #include "frontend/BytecodeCompiler.h"
58 #include "frontend/FullParseHandler.h"  // for JS_BufferIsCompileableUnit
59 #include "frontend/Parser.h" // for JS_BufferIsCompileableUnit
60 #include "gc/Marking.h"
61 #include "jit/JitCommon.h"
62 #include "js/CharacterEncoding.h"
63 #include "js/Conversions.h"
64 #include "js/Date.h"
65 #include "js/Initialization.h"
66 #include "js/Proxy.h"
67 #include "js/SliceBudget.h"
68 #include "js/StructuredClone.h"
69 #include "vm/DateObject.h"
70 #include "vm/Debugger.h"
71 #include "vm/ErrorObject.h"
72 #include "vm/HelperThreads.h"
73 #include "vm/Interpreter.h"
74 #include "vm/RegExpStatics.h"
75 #include "vm/Runtime.h"
76 #include "vm/SavedStacks.h"
77 #include "vm/ScopeObject.h"
78 #include "vm/Shape.h"
79 #include "vm/StopIterationObject.h"
80 #include "vm/StringBuffer.h"
81 #include "vm/Symbol.h"
82 #include "vm/TypedArrayCommon.h"
83 #include "vm/WrapperObject.h"
84 #include "vm/Xdr.h"
85 
86 #include "jsatominlines.h"
87 #include "jsfuninlines.h"
88 #include "jsscriptinlines.h"
89 
90 #include "vm/Interpreter-inl.h"
91 #include "vm/NativeObject-inl.h"
92 #include "vm/SavedStacks-inl.h"
93 #include "vm/String-inl.h"
94 
95 using namespace js;
96 using namespace js::gc;
97 
98 using mozilla::Maybe;
99 using mozilla::PodCopy;
100 using mozilla::PodZero;
101 using mozilla::UniquePtr;
102 
103 using JS::AutoGCRooter;
104 using JS::ToInt32;
105 using JS::ToInteger;
106 using JS::ToUint32;
107 
108 using js::frontend::Parser;
109 
110 #ifdef HAVE_VA_LIST_AS_ARRAY
111 #define JS_ADDRESSOF_VA_LIST(ap) ((va_list*)(ap))
112 #else
113 #define JS_ADDRESSOF_VA_LIST(ap) (&(ap))
114 #endif
115 
116 bool
requireAtLeast(JSContext * cx,const char * fnname,unsigned required) const117 JS::CallArgs::requireAtLeast(JSContext* cx, const char* fnname, unsigned required) const
118 {
119     if (length() < required) {
120         char numArgsStr[40];
121         JS_snprintf(numArgsStr, sizeof numArgsStr, "%u", required - 1);
122         JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_MORE_ARGS_NEEDED,
123                              fnname, numArgsStr, required == 2 ? "" : "s");
124         return false;
125     }
126 
127     return true;
128 }
129 
130 static bool
ErrorTakesArguments(unsigned msg)131 ErrorTakesArguments(unsigned msg)
132 {
133     MOZ_ASSERT(msg < JSErr_Limit);
134     unsigned argCount = js_ErrorFormatString[msg].argCount;
135     MOZ_ASSERT(argCount <= 2);
136     return argCount == 1 || argCount == 2;
137 }
138 
139 static bool
ErrorTakesObjectArgument(unsigned msg)140 ErrorTakesObjectArgument(unsigned msg)
141 {
142     MOZ_ASSERT(msg < JSErr_Limit);
143     unsigned argCount = js_ErrorFormatString[msg].argCount;
144     MOZ_ASSERT(argCount <= 2);
145     return argCount == 2;
146 }
147 
JS_PUBLIC_API(bool)148 JS_PUBLIC_API(bool)
149 JS::ObjectOpResult::reportStrictErrorOrWarning(JSContext* cx, HandleObject obj, HandleId id,
150                                                bool strict)
151 {
152     static_assert(unsigned(OkCode) == unsigned(JSMSG_NOT_AN_ERROR),
153                   "unsigned value of OkCode must not be an error code");
154     MOZ_ASSERT(code_ != Uninitialized);
155     MOZ_ASSERT(!ok());
156 
157     unsigned flags = strict ? JSREPORT_ERROR : (JSREPORT_WARNING | JSREPORT_STRICT);
158     if (code_ == JSMSG_OBJECT_NOT_EXTENSIBLE || code_ == JSMSG_SET_NON_OBJECT_RECEIVER) {
159         RootedValue val(cx, ObjectValue(*obj));
160         return ReportValueErrorFlags(cx, flags, code_, JSDVG_IGNORE_STACK, val,
161                                      nullptr, nullptr, nullptr);
162     }
163     if (ErrorTakesArguments(code_)) {
164         RootedValue idv(cx, IdToValue(id));
165         RootedString str(cx, ValueToSource(cx, idv));
166         if (!str)
167             return false;
168 
169         JSAutoByteString propName(cx, str);
170         if (!propName)
171             return false;
172 
173         if (ErrorTakesObjectArgument(code_)) {
174             return JS_ReportErrorFlagsAndNumber(cx, flags, GetErrorMessage, nullptr, code_,
175                                                 obj->getClass()->name, propName.ptr());
176         }
177 
178         return JS_ReportErrorFlagsAndNumber(cx, flags, GetErrorMessage, nullptr, code_,
179                                             propName.ptr());
180     }
181     return JS_ReportErrorFlagsAndNumber(cx, flags, GetErrorMessage, nullptr, code_);
182 }
183 
JS_PUBLIC_API(bool)184 JS_PUBLIC_API(bool)
185 JS::ObjectOpResult::reportStrictErrorOrWarning(JSContext* cx, HandleObject obj, bool strict)
186 {
187     MOZ_ASSERT(code_ != Uninitialized);
188     MOZ_ASSERT(!ok());
189     MOZ_ASSERT(!ErrorTakesArguments(code_));
190 
191     unsigned flags = strict ? JSREPORT_ERROR : (JSREPORT_WARNING | JSREPORT_STRICT);
192     return JS_ReportErrorFlagsAndNumber(cx, flags, GetErrorMessage, nullptr, code_);
193 }
194 
JS_PUBLIC_API(bool)195 JS_PUBLIC_API(bool)
196 JS::ObjectOpResult::failCantRedefineProp()
197 {
198     return fail(JSMSG_CANT_REDEFINE_PROP);
199 }
200 
JS_PUBLIC_API(bool)201 JS_PUBLIC_API(bool)
202 JS::ObjectOpResult::failReadOnly()
203 {
204     return fail(JSMSG_READ_ONLY);
205 }
206 
JS_PUBLIC_API(bool)207 JS_PUBLIC_API(bool)
208 JS::ObjectOpResult::failGetterOnly()
209 {
210     return fail(JSMSG_GETTER_ONLY);
211 }
212 
JS_PUBLIC_API(bool)213 JS_PUBLIC_API(bool)
214 JS::ObjectOpResult::failCantDelete()
215 {
216     return fail(JSMSG_CANT_DELETE);
217 }
218 
JS_PUBLIC_API(bool)219 JS_PUBLIC_API(bool)
220 JS::ObjectOpResult::failCantSetInterposed()
221 {
222     return fail(JSMSG_CANT_SET_INTERPOSED);
223 }
224 
JS_PUBLIC_API(bool)225 JS_PUBLIC_API(bool)
226 JS::ObjectOpResult::failCantDefineWindowElement()
227 {
228     return fail(JSMSG_CANT_DEFINE_WINDOW_ELEMENT);
229 }
230 
JS_PUBLIC_API(bool)231 JS_PUBLIC_API(bool)
232 JS::ObjectOpResult::failCantDeleteWindowElement()
233 {
234     return fail(JSMSG_CANT_DELETE_WINDOW_ELEMENT);
235 }
236 
JS_PUBLIC_API(bool)237 JS_PUBLIC_API(bool)
238 JS::ObjectOpResult::failCantDeleteWindowNamedProperty()
239 {
240     return fail(JSMSG_CANT_DELETE_WINDOW_NAMED_PROPERTY);
241 }
242 
JS_PUBLIC_API(bool)243 JS_PUBLIC_API(bool)
244 JS::ObjectOpResult::failCantPreventExtensions()
245 {
246     return fail(JSMSG_CANT_PREVENT_EXTENSIONS);
247 }
248 
JS_PUBLIC_API(bool)249 JS_PUBLIC_API(bool)
250 JS::ObjectOpResult::failCantSetProto()
251 {
252     return fail(JSMSG_CANT_SET_PROTO);
253 }
254 
JS_PUBLIC_API(bool)255 JS_PUBLIC_API(bool)
256 JS::ObjectOpResult::failNoNamedSetter()
257 {
258     return fail(JSMSG_NO_NAMED_SETTER);
259 }
260 
JS_PUBLIC_API(bool)261 JS_PUBLIC_API(bool)
262 JS::ObjectOpResult::failNoIndexedSetter()
263 {
264     return fail(JSMSG_NO_INDEXED_SETTER);
265 }
266 
267 JS_PUBLIC_API(int64_t)
JS_Now()268 JS_Now()
269 {
270     return PRMJ_Now();
271 }
272 
273 JS_PUBLIC_API(Value)
JS_GetNaNValue(JSContext * cx)274 JS_GetNaNValue(JSContext* cx)
275 {
276     return cx->runtime()->NaNValue;
277 }
278 
279 JS_PUBLIC_API(Value)
JS_GetNegativeInfinityValue(JSContext * cx)280 JS_GetNegativeInfinityValue(JSContext* cx)
281 {
282     return cx->runtime()->negativeInfinityValue;
283 }
284 
285 JS_PUBLIC_API(Value)
JS_GetPositiveInfinityValue(JSContext * cx)286 JS_GetPositiveInfinityValue(JSContext* cx)
287 {
288     return cx->runtime()->positiveInfinityValue;
289 }
290 
291 JS_PUBLIC_API(Value)
JS_GetEmptyStringValue(JSContext * cx)292 JS_GetEmptyStringValue(JSContext* cx)
293 {
294     return StringValue(cx->runtime()->emptyString);
295 }
296 
297 JS_PUBLIC_API(JSString*)
JS_GetEmptyString(JSRuntime * rt)298 JS_GetEmptyString(JSRuntime* rt)
299 {
300     MOZ_ASSERT(rt->hasContexts());
301     return rt->emptyString;
302 }
303 
304 namespace js {
305 
306 void
AssertHeapIsIdle(JSRuntime * rt)307 AssertHeapIsIdle(JSRuntime* rt)
308 {
309     MOZ_ASSERT(!rt->isHeapBusy());
310 }
311 
312 void
AssertHeapIsIdle(JSContext * cx)313 AssertHeapIsIdle(JSContext* cx)
314 {
315     AssertHeapIsIdle(cx->runtime());
316 }
317 
318 } // namespace js
319 
320 static void
AssertHeapIsIdleOrIterating(JSRuntime * rt)321 AssertHeapIsIdleOrIterating(JSRuntime* rt)
322 {
323     MOZ_ASSERT(!rt->isHeapCollecting());
324 }
325 
326 static void
AssertHeapIsIdleOrIterating(JSContext * cx)327 AssertHeapIsIdleOrIterating(JSContext* cx)
328 {
329     AssertHeapIsIdleOrIterating(cx->runtime());
330 }
331 
332 static void
AssertHeapIsIdleOrStringIsFlat(JSContext * cx,JSString * str)333 AssertHeapIsIdleOrStringIsFlat(JSContext* cx, JSString* str)
334 {
335     /*
336      * We allow some functions to be called during a GC as long as the argument
337      * is a flat string, since that will not cause allocation.
338      */
339     MOZ_ASSERT_IF(cx->runtime()->isHeapBusy(), str->isFlat());
340 }
341 
342 JS_PUBLIC_API(bool)
JS_ValueToObject(JSContext * cx,HandleValue value,MutableHandleObject objp)343 JS_ValueToObject(JSContext* cx, HandleValue value, MutableHandleObject objp)
344 {
345     AssertHeapIsIdle(cx);
346     CHECK_REQUEST(cx);
347     assertSameCompartment(cx, value);
348     if (value.isNullOrUndefined()) {
349         objp.set(nullptr);
350         return true;
351     }
352     JSObject* obj = ToObject(cx, value);
353     if (!obj)
354         return false;
355     objp.set(obj);
356     return true;
357 }
358 
359 JS_PUBLIC_API(JSFunction*)
JS_ValueToFunction(JSContext * cx,HandleValue value)360 JS_ValueToFunction(JSContext* cx, HandleValue value)
361 {
362     AssertHeapIsIdle(cx);
363     CHECK_REQUEST(cx);
364     assertSameCompartment(cx, value);
365     return ReportIfNotFunction(cx, value);
366 }
367 
368 JS_PUBLIC_API(JSFunction*)
JS_ValueToConstructor(JSContext * cx,HandleValue value)369 JS_ValueToConstructor(JSContext* cx, HandleValue value)
370 {
371     AssertHeapIsIdle(cx);
372     CHECK_REQUEST(cx);
373     assertSameCompartment(cx, value);
374     return ReportIfNotFunction(cx, value);
375 }
376 
377 JS_PUBLIC_API(JSString*)
JS_ValueToSource(JSContext * cx,HandleValue value)378 JS_ValueToSource(JSContext* cx, HandleValue value)
379 {
380     AssertHeapIsIdle(cx);
381     CHECK_REQUEST(cx);
382     assertSameCompartment(cx, value);
383     return ValueToSource(cx, value);
384 }
385 
386 JS_PUBLIC_API(bool)
JS_DoubleIsInt32(double d,int32_t * ip)387 JS_DoubleIsInt32(double d, int32_t* ip)
388 {
389     return mozilla::NumberIsInt32(d, ip);
390 }
391 
392 JS_PUBLIC_API(JSType)
JS_TypeOfValue(JSContext * cx,HandleValue value)393 JS_TypeOfValue(JSContext* cx, HandleValue value)
394 {
395     AssertHeapIsIdle(cx);
396     CHECK_REQUEST(cx);
397     assertSameCompartment(cx, value);
398     return TypeOfValue(value);
399 }
400 
401 JS_PUBLIC_API(bool)
JS_StrictlyEqual(JSContext * cx,HandleValue value1,HandleValue value2,bool * equal)402 JS_StrictlyEqual(JSContext* cx, HandleValue value1, HandleValue value2, bool* equal)
403 {
404     AssertHeapIsIdle(cx);
405     CHECK_REQUEST(cx);
406     assertSameCompartment(cx, value1, value2);
407     MOZ_ASSERT(equal);
408     return StrictlyEqual(cx, value1, value2, equal);
409 }
410 
411 JS_PUBLIC_API(bool)
JS_LooselyEqual(JSContext * cx,HandleValue value1,HandleValue value2,bool * equal)412 JS_LooselyEqual(JSContext* cx, HandleValue value1, HandleValue value2, bool* equal)
413 {
414     AssertHeapIsIdle(cx);
415     CHECK_REQUEST(cx);
416     assertSameCompartment(cx, value1, value2);
417     MOZ_ASSERT(equal);
418     return LooselyEqual(cx, value1, value2, equal);
419 }
420 
421 JS_PUBLIC_API(bool)
JS_SameValue(JSContext * cx,HandleValue value1,HandleValue value2,bool * same)422 JS_SameValue(JSContext* cx, HandleValue value1, HandleValue value2, bool* same)
423 {
424     AssertHeapIsIdle(cx);
425     CHECK_REQUEST(cx);
426     assertSameCompartment(cx, value1, value2);
427     MOZ_ASSERT(same);
428     return SameValue(cx, value1, value2, same);
429 }
430 
431 JS_PUBLIC_API(bool)
JS_IsBuiltinEvalFunction(JSFunction * fun)432 JS_IsBuiltinEvalFunction(JSFunction* fun)
433 {
434     return IsAnyBuiltinEval(fun);
435 }
436 
437 JS_PUBLIC_API(bool)
JS_IsBuiltinFunctionConstructor(JSFunction * fun)438 JS_IsBuiltinFunctionConstructor(JSFunction* fun)
439 {
440     return fun->isBuiltinFunctionConstructor();
441 }
442 
443 /************************************************************************/
444 
445 #ifdef DEBUG
JS_FRIEND_API(bool)446 JS_FRIEND_API(bool)
447 JS::isGCEnabled()
448 {
449     return !TlsPerThreadData.get()->suppressGC;
450 }
451 #else
JS_FRIEND_API(bool)452 JS_FRIEND_API(bool) JS::isGCEnabled() { return true; }
453 #endif
454 
455 JS_PUBLIC_API(JSRuntime*)
JS_NewRuntime(uint32_t maxbytes,uint32_t maxNurseryBytes,JSRuntime * parentRuntime)456 JS_NewRuntime(uint32_t maxbytes, uint32_t maxNurseryBytes, JSRuntime* parentRuntime)
457 {
458     MOZ_ASSERT(JS::detail::libraryInitState == JS::detail::InitState::Running,
459                "must call JS_Init prior to creating any JSRuntimes");
460 
461     // Make sure that all parent runtimes are the topmost parent.
462     while (parentRuntime && parentRuntime->parentRuntime)
463         parentRuntime = parentRuntime->parentRuntime;
464 
465     JSRuntime* rt = js_new<JSRuntime>(parentRuntime);
466     if (!rt)
467         return nullptr;
468 
469     if (!rt->init(maxbytes, maxNurseryBytes)) {
470         JS_DestroyRuntime(rt);
471         return nullptr;
472     }
473 
474     return rt;
475 }
476 
477 JS_PUBLIC_API(void)
JS_DestroyRuntime(JSRuntime * rt)478 JS_DestroyRuntime(JSRuntime* rt)
479 {
480     js_delete(rt);
481 }
482 
483 static JS_CurrentEmbedderTimeFunction currentEmbedderTimeFunction;
484 
485 JS_PUBLIC_API(void)
JS_SetCurrentEmbedderTimeFunction(JS_CurrentEmbedderTimeFunction timeFn)486 JS_SetCurrentEmbedderTimeFunction(JS_CurrentEmbedderTimeFunction timeFn)
487 {
488     currentEmbedderTimeFunction = timeFn;
489 }
490 
491 JS_PUBLIC_API(double)
JS_GetCurrentEmbedderTime()492 JS_GetCurrentEmbedderTime()
493 {
494     if (currentEmbedderTimeFunction)
495         return currentEmbedderTimeFunction();
496     return PRMJ_Now() / static_cast<double>(PRMJ_USEC_PER_MSEC);
497 }
498 
499 JS_PUBLIC_API(void*)
JS_GetRuntimePrivate(JSRuntime * rt)500 JS_GetRuntimePrivate(JSRuntime* rt)
501 {
502     return rt->data;
503 }
504 
505 JS_PUBLIC_API(void)
JS_SetRuntimePrivate(JSRuntime * rt,void * data)506 JS_SetRuntimePrivate(JSRuntime* rt, void* data)
507 {
508     rt->data = data;
509 }
510 
511 static void
StartRequest(JSContext * cx)512 StartRequest(JSContext* cx)
513 {
514     JSRuntime* rt = cx->runtime();
515     MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt));
516 
517     if (rt->requestDepth) {
518         rt->requestDepth++;
519     } else {
520         /* Indicate that a request is running. */
521         rt->requestDepth = 1;
522         rt->triggerActivityCallback(true);
523     }
524 }
525 
526 static void
StopRequest(JSContext * cx)527 StopRequest(JSContext* cx)
528 {
529     JSRuntime* rt = cx->runtime();
530     MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt));
531 
532     MOZ_ASSERT(rt->requestDepth != 0);
533     if (rt->requestDepth != 1) {
534         rt->requestDepth--;
535     } else {
536         rt->requestDepth = 0;
537         rt->triggerActivityCallback(false);
538     }
539 }
540 
541 JS_PUBLIC_API(void)
JS_BeginRequest(JSContext * cx)542 JS_BeginRequest(JSContext* cx)
543 {
544     cx->outstandingRequests++;
545     StartRequest(cx);
546 }
547 
548 JS_PUBLIC_API(void)
JS_EndRequest(JSContext * cx)549 JS_EndRequest(JSContext* cx)
550 {
551     MOZ_ASSERT(cx->outstandingRequests != 0);
552     cx->outstandingRequests--;
553     StopRequest(cx);
554 }
555 
556 JS_PUBLIC_API(void)
JS_SetContextCallback(JSRuntime * rt,JSContextCallback cxCallback,void * data)557 JS_SetContextCallback(JSRuntime* rt, JSContextCallback cxCallback, void* data)
558 {
559     rt->cxCallback = cxCallback;
560     rt->cxCallbackData = data;
561 }
562 
563 JS_PUBLIC_API(JSContext*)
JS_NewContext(JSRuntime * rt,size_t stackChunkSize)564 JS_NewContext(JSRuntime* rt, size_t stackChunkSize)
565 {
566     return NewContext(rt, stackChunkSize);
567 }
568 
569 JS_PUBLIC_API(void)
JS_DestroyContext(JSContext * cx)570 JS_DestroyContext(JSContext* cx)
571 {
572     MOZ_ASSERT(!cx->compartment());
573     DestroyContext(cx, DCM_FORCE_GC);
574 }
575 
576 JS_PUBLIC_API(void)
JS_DestroyContextNoGC(JSContext * cx)577 JS_DestroyContextNoGC(JSContext* cx)
578 {
579     MOZ_ASSERT(!cx->compartment());
580     DestroyContext(cx, DCM_NO_GC);
581 }
582 
583 JS_PUBLIC_API(void*)
JS_GetContextPrivate(JSContext * cx)584 JS_GetContextPrivate(JSContext* cx)
585 {
586     return cx->data;
587 }
588 
589 JS_PUBLIC_API(void)
JS_SetContextPrivate(JSContext * cx,void * data)590 JS_SetContextPrivate(JSContext* cx, void* data)
591 {
592     cx->data = data;
593 }
594 
595 JS_PUBLIC_API(void*)
JS_GetSecondContextPrivate(JSContext * cx)596 JS_GetSecondContextPrivate(JSContext* cx)
597 {
598     return cx->data2;
599 }
600 
601 JS_PUBLIC_API(void)
JS_SetSecondContextPrivate(JSContext * cx,void * data)602 JS_SetSecondContextPrivate(JSContext* cx, void* data)
603 {
604     cx->data2 = data;
605 }
606 
607 JS_PUBLIC_API(JSRuntime*)
JS_GetRuntime(JSContext * cx)608 JS_GetRuntime(JSContext* cx)
609 {
610     return cx->runtime();
611 }
612 
613 JS_PUBLIC_API(JSRuntime*)
JS_GetParentRuntime(JSContext * cx)614 JS_GetParentRuntime(JSContext* cx)
615 {
616     JSRuntime* rt = cx->runtime();
617     return rt->parentRuntime ? rt->parentRuntime : rt;
618 }
619 
620 JS_PUBLIC_API(JSContext*)
JS_ContextIterator(JSRuntime * rt,JSContext ** iterp)621 JS_ContextIterator(JSRuntime* rt, JSContext** iterp)
622 {
623     JSContext* cx = *iterp;
624     cx = cx ? cx->getNext() : rt->contextList.getFirst();
625     *iterp = cx;
626     return cx;
627 }
628 
629 JS_PUBLIC_API(JSVersion)
JS_GetVersion(JSContext * cx)630 JS_GetVersion(JSContext* cx)
631 {
632     return VersionNumber(cx->findVersion());
633 }
634 
635 JS_PUBLIC_API(void)
JS_SetVersionForCompartment(JSCompartment * compartment,JSVersion version)636 JS_SetVersionForCompartment(JSCompartment* compartment, JSVersion version)
637 {
638     compartment->options().setVersion(version);
639 }
640 
641 static const struct v2smap {
642     JSVersion   version;
643     const char* string;
644 } v2smap[] = {
645     {JSVERSION_ECMA_3,  "ECMAv3"},
646     {JSVERSION_1_6,     "1.6"},
647     {JSVERSION_1_7,     "1.7"},
648     {JSVERSION_1_8,     "1.8"},
649     {JSVERSION_ECMA_5,  "ECMAv5"},
650     {JSVERSION_DEFAULT, js_default_str},
651     {JSVERSION_DEFAULT, "1.0"},
652     {JSVERSION_DEFAULT, "1.1"},
653     {JSVERSION_DEFAULT, "1.2"},
654     {JSVERSION_DEFAULT, "1.3"},
655     {JSVERSION_DEFAULT, "1.4"},
656     {JSVERSION_DEFAULT, "1.5"},
657     {JSVERSION_UNKNOWN, nullptr},          /* must be last, nullptr is sentinel */
658 };
659 
660 JS_PUBLIC_API(const char*)
JS_VersionToString(JSVersion version)661 JS_VersionToString(JSVersion version)
662 {
663     int i;
664 
665     for (i = 0; v2smap[i].string; i++)
666         if (v2smap[i].version == version)
667             return v2smap[i].string;
668     return "unknown";
669 }
670 
671 JS_PUBLIC_API(JSVersion)
JS_StringToVersion(const char * string)672 JS_StringToVersion(const char* string)
673 {
674     int i;
675 
676     for (i = 0; v2smap[i].string; i++)
677         if (strcmp(v2smap[i].string, string) == 0)
678             return v2smap[i].version;
679     return JSVERSION_UNKNOWN;
680 }
681 
JS_PUBLIC_API(JS::RuntimeOptions &)682 JS_PUBLIC_API(JS::RuntimeOptions&)
683 JS::RuntimeOptionsRef(JSRuntime* rt)
684 {
685     return rt->options();
686 }
687 
JS_PUBLIC_API(JS::RuntimeOptions &)688 JS_PUBLIC_API(JS::RuntimeOptions&)
689 JS::RuntimeOptionsRef(JSContext* cx)
690 {
691     return cx->runtime()->options();
692 }
693 
JS_PUBLIC_API(JS::ContextOptions &)694 JS_PUBLIC_API(JS::ContextOptions&)
695 JS::ContextOptionsRef(JSContext* cx)
696 {
697     return cx->options();
698 }
699 
700 JS_PUBLIC_API(const char*)
JS_GetImplementationVersion(void)701 JS_GetImplementationVersion(void)
702 {
703     return "JavaScript-C" MOZILLA_VERSION;
704 }
705 
706 JS_PUBLIC_API(void)
JS_SetDestroyCompartmentCallback(JSRuntime * rt,JSDestroyCompartmentCallback callback)707 JS_SetDestroyCompartmentCallback(JSRuntime* rt, JSDestroyCompartmentCallback callback)
708 {
709     rt->destroyCompartmentCallback = callback;
710 }
711 
712 JS_PUBLIC_API(void)
JS_SetDestroyZoneCallback(JSRuntime * rt,JSZoneCallback callback)713 JS_SetDestroyZoneCallback(JSRuntime* rt, JSZoneCallback callback)
714 {
715     rt->destroyZoneCallback = callback;
716 }
717 
718 JS_PUBLIC_API(void)
JS_SetSweepZoneCallback(JSRuntime * rt,JSZoneCallback callback)719 JS_SetSweepZoneCallback(JSRuntime* rt, JSZoneCallback callback)
720 {
721     rt->sweepZoneCallback = callback;
722 }
723 
724 JS_PUBLIC_API(void)
JS_SetCompartmentNameCallback(JSRuntime * rt,JSCompartmentNameCallback callback)725 JS_SetCompartmentNameCallback(JSRuntime* rt, JSCompartmentNameCallback callback)
726 {
727     rt->compartmentNameCallback = callback;
728 }
729 
730 JS_PUBLIC_API(void)
JS_SetWrapObjectCallbacks(JSRuntime * rt,const JSWrapObjectCallbacks * callbacks)731 JS_SetWrapObjectCallbacks(JSRuntime* rt, const JSWrapObjectCallbacks* callbacks)
732 {
733     rt->wrapObjectCallbacks = callbacks;
734 }
735 
736 JS_PUBLIC_API(JSCompartment*)
JS_EnterCompartment(JSContext * cx,JSObject * target)737 JS_EnterCompartment(JSContext* cx, JSObject* target)
738 {
739     AssertHeapIsIdle(cx);
740     CHECK_REQUEST(cx);
741 
742     JSCompartment* oldCompartment = cx->compartment();
743     cx->enterCompartment(target->compartment());
744     return oldCompartment;
745 }
746 
747 JS_PUBLIC_API(void)
JS_LeaveCompartment(JSContext * cx,JSCompartment * oldCompartment)748 JS_LeaveCompartment(JSContext* cx, JSCompartment* oldCompartment)
749 {
750     AssertHeapIsIdle(cx);
751     CHECK_REQUEST(cx);
752     cx->leaveCompartment(oldCompartment);
753 }
754 
JSAutoCompartment(JSContext * cx,JSObject * target MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)755 JSAutoCompartment::JSAutoCompartment(JSContext* cx, JSObject* target
756                                      MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
757   : cx_(cx),
758     oldCompartment_(cx->compartment())
759 {
760     AssertHeapIsIdleOrIterating(cx_);
761     MOZ_GUARD_OBJECT_NOTIFIER_INIT;
762     cx_->enterCompartment(target->compartment());
763 }
764 
JSAutoCompartment(JSContext * cx,JSScript * target MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)765 JSAutoCompartment::JSAutoCompartment(JSContext* cx, JSScript* target
766                                      MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
767   : cx_(cx),
768     oldCompartment_(cx->compartment())
769 {
770     AssertHeapIsIdleOrIterating(cx_);
771     MOZ_GUARD_OBJECT_NOTIFIER_INIT;
772     cx_->enterCompartment(target->compartment());
773 }
774 
775 
~JSAutoCompartment()776 JSAutoCompartment::~JSAutoCompartment()
777 {
778     cx_->leaveCompartment(oldCompartment_);
779 }
780 
JSAutoNullableCompartment(JSContext * cx,JSObject * targetOrNull MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)781 JSAutoNullableCompartment::JSAutoNullableCompartment(JSContext* cx,
782                                                      JSObject* targetOrNull
783                                                      MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
784   : cx_(cx),
785     oldCompartment_(cx->compartment())
786 {
787     AssertHeapIsIdleOrIterating(cx_);
788     MOZ_GUARD_OBJECT_NOTIFIER_INIT;
789     if (targetOrNull) {
790         cx_->enterCompartment(targetOrNull->compartment());
791     } else {
792         cx_->enterNullCompartment();
793     }
794 }
795 
~JSAutoNullableCompartment()796 JSAutoNullableCompartment::~JSAutoNullableCompartment()
797 {
798     cx_->leaveCompartment(oldCompartment_);
799 }
800 
801 JS_PUBLIC_API(void)
JS_SetCompartmentPrivate(JSCompartment * compartment,void * data)802 JS_SetCompartmentPrivate(JSCompartment* compartment, void* data)
803 {
804     compartment->data = data;
805 }
806 
807 JS_PUBLIC_API(void*)
JS_GetCompartmentPrivate(JSCompartment * compartment)808 JS_GetCompartmentPrivate(JSCompartment* compartment)
809 {
810     return compartment->data;
811 }
812 
JS_PUBLIC_API(JSAddonId *)813 JS_PUBLIC_API(JSAddonId*)
814 JS::NewAddonId(JSContext* cx, HandleString str)
815 {
816     return static_cast<JSAddonId*>(JS_AtomizeAndPinJSString(cx, str));
817 }
818 
JS_PUBLIC_API(JSString *)819 JS_PUBLIC_API(JSString*)
820 JS::StringOfAddonId(JSAddonId* id)
821 {
822     return id;
823 }
824 
JS_PUBLIC_API(JSAddonId *)825 JS_PUBLIC_API(JSAddonId*)
826 JS::AddonIdOfObject(JSObject* obj)
827 {
828     return obj->compartment()->addonId;
829 }
830 
831 JS_PUBLIC_API(void)
JS_SetZoneUserData(JS::Zone * zone,void * data)832 JS_SetZoneUserData(JS::Zone* zone, void* data)
833 {
834     zone->data = data;
835 }
836 
837 JS_PUBLIC_API(void*)
JS_GetZoneUserData(JS::Zone * zone)838 JS_GetZoneUserData(JS::Zone* zone)
839 {
840     return zone->data;
841 }
842 
843 JS_PUBLIC_API(bool)
JS_WrapObject(JSContext * cx,MutableHandleObject objp)844 JS_WrapObject(JSContext* cx, MutableHandleObject objp)
845 {
846     AssertHeapIsIdle(cx);
847     CHECK_REQUEST(cx);
848     if (objp)
849         JS::ExposeObjectToActiveJS(objp);
850     return cx->compartment()->wrap(cx, objp);
851 }
852 
853 JS_PUBLIC_API(bool)
JS_WrapValue(JSContext * cx,MutableHandleValue vp)854 JS_WrapValue(JSContext* cx, MutableHandleValue vp)
855 {
856     AssertHeapIsIdle(cx);
857     CHECK_REQUEST(cx);
858     JS::ExposeValueToActiveJS(vp);
859     return cx->compartment()->wrap(cx, vp);
860 }
861 
862 /*
863  * Identity remapping. Not for casual consumers.
864  *
865  * Normally, an object's contents and its identity are inextricably linked.
866  * Identity is determined by the address of the JSObject* in the heap, and
867  * the contents are what is located at that address. Transplanting allows these
868  * concepts to be separated through a combination of swapping (exchanging the
869  * contents of two same-compartment objects) and remapping cross-compartment
870  * identities by altering wrappers.
871  *
872  * The |origobj| argument should be the object whose identity needs to be
873  * remapped, usually to another compartment. The contents of |origobj| are
874  * destroyed.
875  *
876  * The |target| argument serves two purposes:
877  *
878  * First, |target| serves as a hint for the new identity of the object. The new
879  * identity object will always be in the same compartment as |target|, but
880  * if that compartment already had an object representing |origobj| (either a
881  * cross-compartment wrapper for it, or |origobj| itself if the two arguments
882  * are same-compartment), the existing object is used. Otherwise, |target|
883  * itself is used. To avoid ambiguity, JS_TransplantObject always returns the
884  * new identity.
885  *
886  * Second, the new identity object's contents will be those of |target|. A swap()
887  * is used to make this happen if an object other than |target| is used.
888  *
889  * We don't have a good way to recover from failure in this function, so
890  * we intentionally crash instead.
891  */
892 
893 JS_PUBLIC_API(JSObject*)
JS_TransplantObject(JSContext * cx,HandleObject origobj,HandleObject target)894 JS_TransplantObject(JSContext* cx, HandleObject origobj, HandleObject target)
895 {
896     AssertHeapIsIdle(cx);
897     MOZ_ASSERT(origobj != target);
898     MOZ_ASSERT(!origobj->is<CrossCompartmentWrapperObject>());
899     MOZ_ASSERT(!target->is<CrossCompartmentWrapperObject>());
900 
901     RootedValue origv(cx, ObjectValue(*origobj));
902     RootedObject newIdentity(cx);
903 
904     {
905         AutoDisableProxyCheck adpc(cx->runtime());
906 
907         JSCompartment* destination = target->compartment();
908 
909         if (origobj->compartment() == destination) {
910             // If the original object is in the same compartment as the
911             // destination, then we know that we won't find a wrapper in the
912             // destination's cross compartment map and that the same
913             // object will continue to work.
914             if (!JSObject::swap(cx, origobj, target))
915                 MOZ_CRASH();
916             newIdentity = origobj;
917         } else if (WrapperMap::Ptr p = destination->lookupWrapper(origv)) {
918             // There might already be a wrapper for the original object in
919             // the new compartment. If there is, we use its identity and swap
920             // in the contents of |target|.
921             newIdentity = &p->value().get().toObject();
922 
923             // When we remove origv from the wrapper map, its wrapper, newIdentity,
924             // must immediately cease to be a cross-compartment wrapper. Neuter it.
925             destination->removeWrapper(p);
926             NukeCrossCompartmentWrapper(cx, newIdentity);
927 
928             if (!JSObject::swap(cx, newIdentity, target))
929                 MOZ_CRASH();
930         } else {
931             // Otherwise, we use |target| for the new identity object.
932             newIdentity = target;
933         }
934 
935         // Now, iterate through other scopes looking for references to the
936         // old object, and update the relevant cross-compartment wrappers.
937         if (!RemapAllWrappersForObject(cx, origobj, newIdentity))
938             MOZ_CRASH();
939 
940         // Lastly, update the original object to point to the new one.
941         if (origobj->compartment() != destination) {
942             RootedObject newIdentityWrapper(cx, newIdentity);
943             AutoCompartment ac(cx, origobj);
944             if (!JS_WrapObject(cx, &newIdentityWrapper))
945                 MOZ_CRASH();
946             MOZ_ASSERT(Wrapper::wrappedObject(newIdentityWrapper) == newIdentity);
947             if (!JSObject::swap(cx, origobj, newIdentityWrapper))
948                 MOZ_CRASH();
949             origobj->compartment()->putWrapper(cx, CrossCompartmentKey(newIdentity), origv);
950         }
951     }
952 
953     // The new identity object might be one of several things. Return it to avoid
954     // ambiguity.
955     return newIdentity;
956 }
957 
958 /*
959  * Recompute all cross-compartment wrappers for an object, resetting state.
960  * Gecko uses this to clear Xray wrappers when doing a navigation that reuses
961  * the inner window and global object.
962  */
963 JS_PUBLIC_API(bool)
JS_RefreshCrossCompartmentWrappers(JSContext * cx,HandleObject obj)964 JS_RefreshCrossCompartmentWrappers(JSContext* cx, HandleObject obj)
965 {
966     return RemapAllWrappersForObject(cx, obj, obj);
967 }
968 
969 JS_PUBLIC_API(bool)
JS_InitStandardClasses(JSContext * cx,HandleObject obj)970 JS_InitStandardClasses(JSContext* cx, HandleObject obj)
971 {
972     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
973     AssertHeapIsIdle(cx);
974     CHECK_REQUEST(cx);
975 
976     assertSameCompartment(cx, obj);
977 
978     Rooted<GlobalObject*> global(cx, &obj->global());
979     return GlobalObject::initStandardClasses(cx, global);
980 }
981 
982 #define EAGER_ATOM(name)            NAME_OFFSET(name)
983 
984 typedef struct JSStdName {
985     size_t      atomOffset;     /* offset of atom pointer in JSAtomState */
986     JSProtoKey  key;
isDummyJSStdName987     bool isDummy() const { return key == JSProto_Null; }
isSentinelJSStdName988     bool isSentinel() const { return key == JSProto_LIMIT; }
989 } JSStdName;
990 
991 static const JSStdName*
LookupStdName(const JSAtomState & names,JSAtom * name,const JSStdName * table)992 LookupStdName(const JSAtomState& names, JSAtom* name, const JSStdName* table)
993 {
994     for (unsigned i = 0; !table[i].isSentinel(); i++) {
995         if (table[i].isDummy())
996             continue;
997         JSAtom* atom = AtomStateOffsetToName(names, table[i].atomOffset);
998         MOZ_ASSERT(atom);
999         if (name == atom)
1000             return &table[i];
1001     }
1002 
1003     return nullptr;
1004 }
1005 
1006 /*
1007  * Table of standard classes, indexed by JSProtoKey. For entries where the
1008  * JSProtoKey does not correspond to a class with a meaningful constructor, we
1009  * insert a null entry into the table.
1010  */
1011 #define STD_NAME_ENTRY(name, code, init, clasp) { EAGER_ATOM(name), static_cast<JSProtoKey>(code) },
1012 #define STD_DUMMY_ENTRY(name, code, init, dummy) { 0, JSProto_Null },
1013 static const JSStdName standard_class_names[] = {
1014   JS_FOR_PROTOTYPES(STD_NAME_ENTRY, STD_DUMMY_ENTRY)
1015   { 0, JSProto_LIMIT }
1016 };
1017 
1018 /*
1019  * Table of top-level function and constant names and the JSProtoKey of the
1020  * standard class that initializes them.
1021  */
1022 static const JSStdName builtin_property_names[] = {
1023     { EAGER_ATOM(eval), JSProto_Object },
1024 
1025     /* Global properties and functions defined by the Number class. */
1026     { EAGER_ATOM(NaN), JSProto_Number },
1027     { EAGER_ATOM(Infinity), JSProto_Number },
1028     { EAGER_ATOM(isNaN), JSProto_Number },
1029     { EAGER_ATOM(isFinite), JSProto_Number },
1030     { EAGER_ATOM(parseFloat), JSProto_Number },
1031     { EAGER_ATOM(parseInt), JSProto_Number },
1032 
1033     /* String global functions. */
1034     { EAGER_ATOM(escape), JSProto_String },
1035     { EAGER_ATOM(unescape), JSProto_String },
1036     { EAGER_ATOM(decodeURI), JSProto_String },
1037     { EAGER_ATOM(encodeURI), JSProto_String },
1038     { EAGER_ATOM(decodeURIComponent), JSProto_String },
1039     { EAGER_ATOM(encodeURIComponent), JSProto_String },
1040 #if JS_HAS_UNEVAL
1041     { EAGER_ATOM(uneval), JSProto_String },
1042 #endif
1043 #ifdef ENABLE_BINARYDATA
1044     { EAGER_ATOM(SIMD), JSProto_SIMD },
1045     { EAGER_ATOM(TypedObject), JSProto_TypedObject },
1046 #endif
1047 #ifdef ENABLE_SHARED_ARRAY_BUFFER
1048     { EAGER_ATOM(Atomics), JSProto_Atomics },
1049 #endif
1050 
1051     { 0, JSProto_LIMIT }
1052 };
1053 
1054 #undef EAGER_ATOM
1055 
1056 JS_PUBLIC_API(bool)
JS_ResolveStandardClass(JSContext * cx,HandleObject obj,HandleId id,bool * resolved)1057 JS_ResolveStandardClass(JSContext* cx, HandleObject obj, HandleId id, bool* resolved)
1058 {
1059     JSRuntime* rt;
1060     const JSStdName* stdnm;
1061 
1062     AssertHeapIsIdle(cx);
1063     CHECK_REQUEST(cx);
1064     assertSameCompartment(cx, obj, id);
1065 
1066     Rooted<GlobalObject*> global(cx, &obj->as<GlobalObject>());
1067     *resolved = false;
1068 
1069     rt = cx->runtime();
1070     if (!rt->hasContexts() || !JSID_IS_ATOM(id))
1071         return true;
1072 
1073     /* Check whether we're resolving 'undefined', and define it if so. */
1074     JSAtom* idAtom = JSID_TO_ATOM(id);
1075     JSAtom* undefinedAtom = cx->names().undefined;
1076     if (idAtom == undefinedAtom) {
1077         *resolved = true;
1078         return DefineProperty(cx, global, id, UndefinedHandleValue, nullptr, nullptr,
1079                               JSPROP_PERMANENT | JSPROP_READONLY | JSPROP_RESOLVING);
1080     }
1081 
1082     /* Try for class constructors/prototypes named by well-known atoms. */
1083     stdnm = LookupStdName(cx->names(), idAtom, standard_class_names);
1084 
1085     /* Try less frequently used top-level functions and constants. */
1086     if (!stdnm)
1087         stdnm = LookupStdName(cx->names(), idAtom, builtin_property_names);
1088 
1089     // If this class is anonymous, then it doesn't exist as a global
1090     // property, so we won't resolve anything.
1091     JSProtoKey key = stdnm ? stdnm->key : JSProto_Null;
1092     if (key != JSProto_Null) {
1093         const Class* clasp = ProtoKeyToClass(key);
1094         if (!clasp || !(clasp->flags & JSCLASS_IS_ANONYMOUS)) {
1095             if (!GlobalObject::ensureConstructor(cx, global, key))
1096                 return false;
1097 
1098             *resolved = true;
1099             return true;
1100         }
1101     }
1102 
1103     // There is no such property to resolve. An ordinary resolve hook would
1104     // just return true at this point. But the global object is special in one
1105     // more way: its prototype chain is lazily initialized. That is,
1106     // global->getProto() might be null right now because we haven't created
1107     // Object.prototype yet. Force it now.
1108     if (!global->getOrCreateObjectPrototype(cx))
1109         return false;
1110 
1111     return true;
1112 }
1113 
1114 JS_PUBLIC_API(bool)
JS_MayResolveStandardClass(const JSAtomState & names,jsid id,JSObject * maybeObj)1115 JS_MayResolveStandardClass(const JSAtomState& names, jsid id, JSObject* maybeObj)
1116 {
1117     MOZ_ASSERT_IF(maybeObj, maybeObj->is<GlobalObject>());
1118 
1119     // The global object's resolve hook is special: JS_ResolveStandardClass
1120     // initializes the prototype chain lazily. Only attempt to optimize here
1121     // if we know the prototype chain has been initialized.
1122     if (!maybeObj || !maybeObj->getProto())
1123         return true;
1124 
1125     if (!JSID_IS_ATOM(id))
1126         return false;
1127 
1128     JSAtom* atom = JSID_TO_ATOM(id);
1129 
1130     return atom == names.undefined ||
1131            LookupStdName(names, atom, standard_class_names) ||
1132            LookupStdName(names, atom, builtin_property_names);
1133 }
1134 
1135 JS_PUBLIC_API(bool)
JS_EnumerateStandardClasses(JSContext * cx,HandleObject obj)1136 JS_EnumerateStandardClasses(JSContext* cx, HandleObject obj)
1137 {
1138     AssertHeapIsIdle(cx);
1139     CHECK_REQUEST(cx);
1140     assertSameCompartment(cx, obj);
1141     MOZ_ASSERT(obj->is<GlobalObject>());
1142     Rooted<GlobalObject*> global(cx, &obj->as<GlobalObject>());
1143     return GlobalObject::initStandardClasses(cx, global);
1144 }
1145 
1146 JS_PUBLIC_API(bool)
JS_GetClassObject(JSContext * cx,JSProtoKey key,MutableHandleObject objp)1147 JS_GetClassObject(JSContext* cx, JSProtoKey key, MutableHandleObject objp)
1148 {
1149     AssertHeapIsIdle(cx);
1150     CHECK_REQUEST(cx);
1151     return GetBuiltinConstructor(cx, key, objp);
1152 }
1153 
1154 JS_PUBLIC_API(bool)
JS_GetClassPrototype(JSContext * cx,JSProtoKey key,MutableHandleObject objp)1155 JS_GetClassPrototype(JSContext* cx, JSProtoKey key, MutableHandleObject objp)
1156 {
1157     AssertHeapIsIdle(cx);
1158     CHECK_REQUEST(cx);
1159     return GetBuiltinPrototype(cx, key, objp);
1160 }
1161 
1162 namespace JS {
1163 
1164 JS_PUBLIC_API(void)
ProtoKeyToId(JSContext * cx,JSProtoKey key,MutableHandleId idp)1165 ProtoKeyToId(JSContext* cx, JSProtoKey key, MutableHandleId idp)
1166 {
1167     idp.set(NameToId(ClassName(key, cx)));
1168 }
1169 
1170 } /* namespace JS */
1171 
1172 JS_PUBLIC_API(JSProtoKey)
JS_IdToProtoKey(JSContext * cx,HandleId id)1173 JS_IdToProtoKey(JSContext* cx, HandleId id)
1174 {
1175     AssertHeapIsIdle(cx);
1176     CHECK_REQUEST(cx);
1177 
1178     if (!JSID_IS_ATOM(id))
1179         return JSProto_Null;
1180 
1181     JSAtom* atom = JSID_TO_ATOM(id);
1182     const JSStdName* stdnm = LookupStdName(cx->names(), atom, standard_class_names);
1183     if (!stdnm)
1184         return JSProto_Null;
1185 
1186     MOZ_ASSERT(MOZ_ARRAY_LENGTH(standard_class_names) == JSProto_LIMIT + 1);
1187     return static_cast<JSProtoKey>(stdnm - standard_class_names);
1188 }
1189 
1190 JS_PUBLIC_API(JSObject*)
JS_GetObjectPrototype(JSContext * cx,HandleObject forObj)1191 JS_GetObjectPrototype(JSContext* cx, HandleObject forObj)
1192 {
1193     CHECK_REQUEST(cx);
1194     assertSameCompartment(cx, forObj);
1195     return forObj->global().getOrCreateObjectPrototype(cx);
1196 }
1197 
1198 JS_PUBLIC_API(JSObject*)
JS_GetFunctionPrototype(JSContext * cx,HandleObject forObj)1199 JS_GetFunctionPrototype(JSContext* cx, HandleObject forObj)
1200 {
1201     CHECK_REQUEST(cx);
1202     assertSameCompartment(cx, forObj);
1203     return forObj->global().getOrCreateFunctionPrototype(cx);
1204 }
1205 
1206 JS_PUBLIC_API(JSObject*)
JS_GetArrayPrototype(JSContext * cx,HandleObject forObj)1207 JS_GetArrayPrototype(JSContext* cx, HandleObject forObj)
1208 {
1209     CHECK_REQUEST(cx);
1210     assertSameCompartment(cx, forObj);
1211     Rooted<GlobalObject*> global(cx, &forObj->global());
1212     return GlobalObject::getOrCreateArrayPrototype(cx, global);
1213 }
1214 
1215 JS_PUBLIC_API(JSObject*)
JS_GetErrorPrototype(JSContext * cx)1216 JS_GetErrorPrototype(JSContext* cx)
1217 {
1218     CHECK_REQUEST(cx);
1219     Rooted<GlobalObject*> global(cx, cx->global());
1220     return GlobalObject::getOrCreateCustomErrorPrototype(cx, global, JSEXN_ERR);
1221 }
1222 
1223 JS_PUBLIC_API(JSObject*)
JS_GetIteratorPrototype(JSContext * cx)1224 JS_GetIteratorPrototype(JSContext* cx)
1225 {
1226     CHECK_REQUEST(cx);
1227     Rooted<GlobalObject*> global(cx, cx->global());
1228     return GlobalObject::getOrCreateIteratorPrototype(cx, global);
1229 }
1230 
1231 JS_PUBLIC_API(JSObject*)
JS_GetGlobalForObject(JSContext * cx,JSObject * obj)1232 JS_GetGlobalForObject(JSContext* cx, JSObject* obj)
1233 {
1234     AssertHeapIsIdle(cx);
1235     assertSameCompartment(cx, obj);
1236     return &obj->global();
1237 }
1238 
1239 extern JS_PUBLIC_API(bool)
JS_IsGlobalObject(JSObject * obj)1240 JS_IsGlobalObject(JSObject* obj)
1241 {
1242     return obj->is<GlobalObject>();
1243 }
1244 
1245 extern JS_PUBLIC_API(JSObject*)
JS_GlobalLexicalScope(JSObject * obj)1246 JS_GlobalLexicalScope(JSObject* obj)
1247 {
1248     return &obj->as<GlobalObject>().lexicalScope();
1249 }
1250 
1251 extern JS_PUBLIC_API(bool)
JS_HasExtensibleLexicalScope(JSObject * obj)1252 JS_HasExtensibleLexicalScope(JSObject* obj)
1253 {
1254     return obj->is<GlobalObject>() || obj->compartment()->getNonSyntacticLexicalScope(obj);
1255 }
1256 
1257 extern JS_PUBLIC_API(JSObject*)
JS_ExtensibleLexicalScope(JSObject * obj)1258 JS_ExtensibleLexicalScope(JSObject* obj)
1259 {
1260     JSObject* lexical = nullptr;
1261     if (obj->is<GlobalObject>())
1262         lexical = JS_GlobalLexicalScope(obj);
1263     else
1264         lexical = obj->compartment()->getNonSyntacticLexicalScope(obj);
1265     MOZ_ASSERT(lexical);
1266     return lexical;
1267 }
1268 
1269 JS_PUBLIC_API(JSObject*)
JS_GetGlobalForCompartmentOrNull(JSContext * cx,JSCompartment * c)1270 JS_GetGlobalForCompartmentOrNull(JSContext* cx, JSCompartment* c)
1271 {
1272     AssertHeapIsIdleOrIterating(cx);
1273     assertSameCompartment(cx, c);
1274     return c->maybeGlobal();
1275 }
1276 
JS_PUBLIC_API(JSObject *)1277 JS_PUBLIC_API(JSObject*)
1278 JS::CurrentGlobalOrNull(JSContext* cx)
1279 {
1280     AssertHeapIsIdleOrIterating(cx);
1281     CHECK_REQUEST(cx);
1282     if (!cx->compartment())
1283         return nullptr;
1284     return cx->global();
1285 }
1286 
1287 JS_PUBLIC_API(Value)
JS_ComputeThis(JSContext * cx,Value * vp)1288 JS_ComputeThis(JSContext* cx, Value* vp)
1289 {
1290     AssertHeapIsIdle(cx);
1291     assertSameCompartment(cx, JSValueArray(vp, 2));
1292     CallReceiver call = CallReceiverFromVp(vp);
1293     if (!BoxNonStrictThis(cx, call))
1294         return NullValue();
1295     return call.thisv();
1296 }
1297 
1298 JS_PUBLIC_API(void*)
JS_malloc(JSContext * cx,size_t nbytes)1299 JS_malloc(JSContext* cx, size_t nbytes)
1300 {
1301     AssertHeapIsIdle(cx);
1302     CHECK_REQUEST(cx);
1303     return static_cast<void*>(cx->runtime()->pod_malloc<uint8_t>(nbytes));
1304 }
1305 
1306 JS_PUBLIC_API(void*)
JS_realloc(JSContext * cx,void * p,size_t oldBytes,size_t newBytes)1307 JS_realloc(JSContext* cx, void* p, size_t oldBytes, size_t newBytes)
1308 {
1309     AssertHeapIsIdle(cx);
1310     CHECK_REQUEST(cx);
1311     return static_cast<void*>(cx->zone()->pod_realloc<uint8_t>(static_cast<uint8_t*>(p), oldBytes,
1312                                                                 newBytes));
1313 }
1314 
1315 JS_PUBLIC_API(void)
JS_free(JSContext * cx,void * p)1316 JS_free(JSContext* cx, void* p)
1317 {
1318     return js_free(p);
1319 }
1320 
1321 JS_PUBLIC_API(void)
JS_freeop(JSFreeOp * fop,void * p)1322 JS_freeop(JSFreeOp* fop, void* p)
1323 {
1324     return FreeOp::get(fop)->free_(p);
1325 }
1326 
1327 JS_PUBLIC_API(JSFreeOp*)
JS_GetDefaultFreeOp(JSRuntime * rt)1328 JS_GetDefaultFreeOp(JSRuntime* rt)
1329 {
1330     return rt->defaultFreeOp();
1331 }
1332 
1333 JS_PUBLIC_API(void)
JS_updateMallocCounter(JSContext * cx,size_t nbytes)1334 JS_updateMallocCounter(JSContext* cx, size_t nbytes)
1335 {
1336     return cx->runtime()->updateMallocCounter(cx->zone(), nbytes);
1337 }
1338 
1339 JS_PUBLIC_API(char*)
JS_strdup(JSContext * cx,const char * s)1340 JS_strdup(JSContext* cx, const char* s)
1341 {
1342     AssertHeapIsIdle(cx);
1343     return DuplicateString(cx, s).release();
1344 }
1345 
1346 JS_PUBLIC_API(char*)
JS_strdup(JSRuntime * rt,const char * s)1347 JS_strdup(JSRuntime* rt, const char* s)
1348 {
1349     AssertHeapIsIdle(rt);
1350     size_t n = strlen(s) + 1;
1351     char* p = rt->pod_malloc<char>(n);
1352     if (!p)
1353         return nullptr;
1354     return static_cast<char*>(js_memcpy(p, s, n));
1355 }
1356 
1357 #undef JS_AddRoot
1358 
1359 JS_PUBLIC_API(bool)
JS_AddExtraGCRootsTracer(JSRuntime * rt,JSTraceDataOp traceOp,void * data)1360 JS_AddExtraGCRootsTracer(JSRuntime* rt, JSTraceDataOp traceOp, void* data)
1361 {
1362     return rt->gc.addBlackRootsTracer(traceOp, data);
1363 }
1364 
1365 JS_PUBLIC_API(void)
JS_RemoveExtraGCRootsTracer(JSRuntime * rt,JSTraceDataOp traceOp,void * data)1366 JS_RemoveExtraGCRootsTracer(JSRuntime* rt, JSTraceDataOp traceOp, void* data)
1367 {
1368     return rt->gc.removeBlackRootsTracer(traceOp, data);
1369 }
1370 
1371 JS_PUBLIC_API(void)
JS_GC(JSRuntime * rt)1372 JS_GC(JSRuntime* rt)
1373 {
1374     AssertHeapIsIdle(rt);
1375     JS::PrepareForFullGC(rt);
1376     rt->gc.gc(GC_NORMAL, JS::gcreason::API);
1377 }
1378 
1379 JS_PUBLIC_API(void)
JS_MaybeGC(JSContext * cx)1380 JS_MaybeGC(JSContext* cx)
1381 {
1382     GCRuntime& gc = cx->runtime()->gc;
1383     if (!gc.maybeGC(cx->zone()))
1384         gc.maybePeriodicFullGC();
1385 }
1386 
1387 JS_PUBLIC_API(void)
JS_SetGCCallback(JSRuntime * rt,JSGCCallback cb,void * data)1388 JS_SetGCCallback(JSRuntime* rt, JSGCCallback cb, void* data)
1389 {
1390     AssertHeapIsIdle(rt);
1391     rt->gc.setGCCallback(cb, data);
1392 }
1393 
1394 JS_PUBLIC_API(bool)
JS_AddFinalizeCallback(JSRuntime * rt,JSFinalizeCallback cb,void * data)1395 JS_AddFinalizeCallback(JSRuntime* rt, JSFinalizeCallback cb, void* data)
1396 {
1397     AssertHeapIsIdle(rt);
1398     return rt->gc.addFinalizeCallback(cb, data);
1399 }
1400 
1401 JS_PUBLIC_API(void)
JS_RemoveFinalizeCallback(JSRuntime * rt,JSFinalizeCallback cb)1402 JS_RemoveFinalizeCallback(JSRuntime* rt, JSFinalizeCallback cb)
1403 {
1404     rt->gc.removeFinalizeCallback(cb);
1405 }
1406 
1407 JS_PUBLIC_API(bool)
JS_AddWeakPointerZoneGroupCallback(JSRuntime * rt,JSWeakPointerZoneGroupCallback cb,void * data)1408 JS_AddWeakPointerZoneGroupCallback(JSRuntime* rt, JSWeakPointerZoneGroupCallback cb, void* data)
1409 {
1410     AssertHeapIsIdle(rt);
1411     return rt->gc.addWeakPointerZoneGroupCallback(cb, data);
1412 }
1413 
1414 JS_PUBLIC_API(void)
JS_RemoveWeakPointerZoneGroupCallback(JSRuntime * rt,JSWeakPointerZoneGroupCallback cb)1415 JS_RemoveWeakPointerZoneGroupCallback(JSRuntime* rt, JSWeakPointerZoneGroupCallback cb)
1416 {
1417     rt->gc.removeWeakPointerZoneGroupCallback(cb);
1418 }
1419 
1420 JS_PUBLIC_API(bool)
JS_AddWeakPointerCompartmentCallback(JSRuntime * rt,JSWeakPointerCompartmentCallback cb,void * data)1421 JS_AddWeakPointerCompartmentCallback(JSRuntime* rt, JSWeakPointerCompartmentCallback cb,
1422                                      void* data)
1423 {
1424     AssertHeapIsIdle(rt);
1425     return rt->gc.addWeakPointerCompartmentCallback(cb, data);
1426 }
1427 
1428 JS_PUBLIC_API(void)
JS_RemoveWeakPointerCompartmentCallback(JSRuntime * rt,JSWeakPointerCompartmentCallback cb)1429 JS_RemoveWeakPointerCompartmentCallback(JSRuntime* rt, JSWeakPointerCompartmentCallback cb)
1430 {
1431     rt->gc.removeWeakPointerCompartmentCallback(cb);
1432 }
1433 
1434 
1435 JS_PUBLIC_API(void)
JS_UpdateWeakPointerAfterGC(JS::Heap<JSObject * > * objp)1436 JS_UpdateWeakPointerAfterGC(JS::Heap<JSObject*>* objp)
1437 {
1438     JS_UpdateWeakPointerAfterGCUnbarriered(objp->unsafeGet());
1439 }
1440 
1441 JS_PUBLIC_API(void)
JS_UpdateWeakPointerAfterGCUnbarriered(JSObject ** objp)1442 JS_UpdateWeakPointerAfterGCUnbarriered(JSObject** objp)
1443 {
1444     if (IsAboutToBeFinalizedUnbarriered(objp))
1445         *objp = nullptr;
1446 }
1447 
1448 JS_PUBLIC_API(void)
JS_SetGCParameter(JSRuntime * rt,JSGCParamKey key,uint32_t value)1449 JS_SetGCParameter(JSRuntime* rt, JSGCParamKey key, uint32_t value)
1450 {
1451     AutoLockGC lock(rt);
1452     rt->gc.setParameter(key, value, lock);
1453 }
1454 
1455 JS_PUBLIC_API(uint32_t)
JS_GetGCParameter(JSRuntime * rt,JSGCParamKey key)1456 JS_GetGCParameter(JSRuntime* rt, JSGCParamKey key)
1457 {
1458     AutoLockGC lock(rt);
1459     return rt->gc.getParameter(key, lock);
1460 }
1461 
1462 JS_PUBLIC_API(void)
JS_SetGCParameterForThread(JSContext * cx,JSGCParamKey key,uint32_t value)1463 JS_SetGCParameterForThread(JSContext* cx, JSGCParamKey key, uint32_t value)
1464 {
1465     MOZ_ASSERT(key == JSGC_MAX_CODE_CACHE_BYTES);
1466 }
1467 
1468 JS_PUBLIC_API(uint32_t)
JS_GetGCParameterForThread(JSContext * cx,JSGCParamKey key)1469 JS_GetGCParameterForThread(JSContext* cx, JSGCParamKey key)
1470 {
1471     MOZ_ASSERT(key == JSGC_MAX_CODE_CACHE_BYTES);
1472     return 0;
1473 }
1474 
1475 static const size_t NumGCConfigs = 14;
1476 struct JSGCConfig {
1477     JSGCParamKey key;
1478     uint32_t value;
1479 };
1480 
1481 JS_PUBLIC_API(void)
JS_SetGCParametersBasedOnAvailableMemory(JSRuntime * rt,uint32_t availMem)1482 JS_SetGCParametersBasedOnAvailableMemory(JSRuntime* rt, uint32_t availMem)
1483 {
1484     static const JSGCConfig minimal[NumGCConfigs] = {
1485         {JSGC_MAX_MALLOC_BYTES, 6 * 1024 * 1024},
1486         {JSGC_SLICE_TIME_BUDGET, 30},
1487         {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
1488         {JSGC_HIGH_FREQUENCY_HIGH_LIMIT, 40},
1489         {JSGC_HIGH_FREQUENCY_LOW_LIMIT, 0},
1490         {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX, 300},
1491         {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN, 120},
1492         {JSGC_LOW_FREQUENCY_HEAP_GROWTH, 120},
1493         {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
1494         {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
1495         {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
1496         {JSGC_ALLOCATION_THRESHOLD, 1},
1497         {JSGC_DECOMMIT_THRESHOLD, 1},
1498         {JSGC_MODE, JSGC_MODE_INCREMENTAL}
1499     };
1500 
1501     const JSGCConfig* config = minimal;
1502     if (availMem > 512) {
1503         static const JSGCConfig nominal[NumGCConfigs] = {
1504             {JSGC_MAX_MALLOC_BYTES, 6 * 1024 * 1024},
1505             {JSGC_SLICE_TIME_BUDGET, 30},
1506             {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1000},
1507             {JSGC_HIGH_FREQUENCY_HIGH_LIMIT, 500},
1508             {JSGC_HIGH_FREQUENCY_LOW_LIMIT, 100},
1509             {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX, 300},
1510             {JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN, 150},
1511             {JSGC_LOW_FREQUENCY_HEAP_GROWTH, 150},
1512             {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
1513             {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
1514             {JSGC_HIGH_FREQUENCY_TIME_LIMIT, 1500},
1515             {JSGC_ALLOCATION_THRESHOLD, 30},
1516             {JSGC_DECOMMIT_THRESHOLD, 32},
1517             {JSGC_MODE, JSGC_MODE_COMPARTMENT}
1518         };
1519 
1520         config = nominal;
1521     }
1522 
1523     for (size_t i = 0; i < NumGCConfigs; i++)
1524         JS_SetGCParameter(rt, config[i].key, config[i].value);
1525 }
1526 
1527 
1528 JS_PUBLIC_API(JSString*)
JS_NewExternalString(JSContext * cx,const char16_t * chars,size_t length,const JSStringFinalizer * fin)1529 JS_NewExternalString(JSContext* cx, const char16_t* chars, size_t length,
1530                      const JSStringFinalizer* fin)
1531 {
1532     AssertHeapIsIdle(cx);
1533     CHECK_REQUEST(cx);
1534     JSString* s = JSExternalString::new_(cx, chars, length, fin);
1535     return s;
1536 }
1537 
1538 extern JS_PUBLIC_API(bool)
JS_IsExternalString(JSString * str)1539 JS_IsExternalString(JSString* str)
1540 {
1541     return str->isExternal();
1542 }
1543 
1544 extern JS_PUBLIC_API(const JSStringFinalizer*)
JS_GetExternalStringFinalizer(JSString * str)1545 JS_GetExternalStringFinalizer(JSString* str)
1546 {
1547     return str->asExternal().externalFinalizer();
1548 }
1549 
1550 static void
SetNativeStackQuotaAndLimit(JSRuntime * rt,StackKind kind,size_t stackSize)1551 SetNativeStackQuotaAndLimit(JSRuntime* rt, StackKind kind, size_t stackSize)
1552 {
1553     rt->nativeStackQuota[kind] = stackSize;
1554 
1555 #if JS_STACK_GROWTH_DIRECTION > 0
1556     if (stackSize == 0) {
1557         rt->mainThread.nativeStackLimit[kind] = UINTPTR_MAX;
1558     } else {
1559         MOZ_ASSERT(rt->nativeStackBase <= size_t(-1) - stackSize);
1560         rt->mainThread.nativeStackLimit[kind] = rt->nativeStackBase + stackSize - 1;
1561     }
1562 #else
1563     if (stackSize == 0) {
1564         rt->mainThread.nativeStackLimit[kind] = 0;
1565     } else {
1566         MOZ_ASSERT(rt->nativeStackBase >= stackSize);
1567         rt->mainThread.nativeStackLimit[kind] = rt->nativeStackBase - (stackSize - 1);
1568     }
1569 #endif
1570 }
1571 
1572 JS_PUBLIC_API(void)
JS_SetNativeStackQuota(JSRuntime * rt,size_t systemCodeStackSize,size_t trustedScriptStackSize,size_t untrustedScriptStackSize)1573 JS_SetNativeStackQuota(JSRuntime* rt, size_t systemCodeStackSize, size_t trustedScriptStackSize,
1574                        size_t untrustedScriptStackSize)
1575 {
1576     MOZ_ASSERT(rt->requestDepth == 0);
1577 
1578     if (!trustedScriptStackSize)
1579         trustedScriptStackSize = systemCodeStackSize;
1580     else
1581         MOZ_ASSERT(trustedScriptStackSize < systemCodeStackSize);
1582 
1583     if (!untrustedScriptStackSize)
1584         untrustedScriptStackSize = trustedScriptStackSize;
1585     else
1586         MOZ_ASSERT(untrustedScriptStackSize < trustedScriptStackSize);
1587 
1588     SetNativeStackQuotaAndLimit(rt, StackForSystemCode, systemCodeStackSize);
1589     SetNativeStackQuotaAndLimit(rt, StackForTrustedScript, trustedScriptStackSize);
1590     SetNativeStackQuotaAndLimit(rt, StackForUntrustedScript, untrustedScriptStackSize);
1591 
1592     rt->initJitStackLimit();
1593 }
1594 
1595 /************************************************************************/
1596 
1597 JS_PUBLIC_API(bool)
JS_ValueToId(JSContext * cx,HandleValue value,MutableHandleId idp)1598 JS_ValueToId(JSContext* cx, HandleValue value, MutableHandleId idp)
1599 {
1600     AssertHeapIsIdle(cx);
1601     CHECK_REQUEST(cx);
1602     assertSameCompartment(cx, value);
1603     return ValueToId<CanGC>(cx, value, idp);
1604 }
1605 
1606 JS_PUBLIC_API(bool)
JS_StringToId(JSContext * cx,HandleString string,MutableHandleId idp)1607 JS_StringToId(JSContext* cx, HandleString string, MutableHandleId idp)
1608 {
1609     AssertHeapIsIdle(cx);
1610     CHECK_REQUEST(cx);
1611     assertSameCompartment(cx, string);
1612     RootedValue value(cx, StringValue(string));
1613     return ValueToId<CanGC>(cx, value, idp);
1614 }
1615 
1616 JS_PUBLIC_API(bool)
JS_IdToValue(JSContext * cx,jsid id,MutableHandleValue vp)1617 JS_IdToValue(JSContext* cx, jsid id, MutableHandleValue vp)
1618 {
1619     AssertHeapIsIdle(cx);
1620     CHECK_REQUEST(cx);
1621     vp.set(IdToValue(id));
1622     assertSameCompartment(cx, vp);
1623     return true;
1624 }
1625 
JS_PUBLIC_API(bool)1626 JS_PUBLIC_API(bool)
1627 JS::ToPrimitive(JSContext* cx, HandleObject obj, JSType hint, MutableHandleValue vp)
1628 {
1629     AssertHeapIsIdle(cx);
1630     CHECK_REQUEST(cx);
1631     MOZ_ASSERT(obj != nullptr);
1632     MOZ_ASSERT(hint == JSTYPE_VOID || hint == JSTYPE_STRING || hint == JSTYPE_NUMBER);
1633     vp.setObject(*obj);
1634     return ToPrimitiveSlow(cx, hint, vp);
1635 }
1636 
JS_PUBLIC_API(bool)1637 JS_PUBLIC_API(bool)
1638 JS::GetFirstArgumentAsTypeHint(JSContext* cx, CallArgs args, JSType *result)
1639 {
1640     if (!args.get(0).isString()) {
1641         JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_NOT_EXPECTED_TYPE,
1642                              "Symbol.toPrimitive",
1643                              "\"string\", \"number\", or \"default\"",
1644                              InformalValueTypeName(args.get(0)));
1645         return false;
1646     }
1647 
1648     RootedString str(cx, args.get(0).toString());
1649     bool match;
1650 
1651     if (!EqualStrings(cx, str, cx->names().default_, &match))
1652         return false;
1653     if (match) {
1654         *result = JSTYPE_VOID;
1655         return true;
1656     }
1657 
1658     if (!EqualStrings(cx, str, cx->names().string, &match))
1659         return false;
1660     if (match) {
1661         *result = JSTYPE_STRING;
1662         return true;
1663     }
1664 
1665     if (!EqualStrings(cx, str, cx->names().number, &match))
1666         return false;
1667     if (match) {
1668         *result = JSTYPE_NUMBER;
1669         return true;
1670     }
1671 
1672     JSAutoByteString bytes;
1673     JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_NOT_EXPECTED_TYPE,
1674                          "Symbol.toPrimitive",
1675                          "\"string\", \"number\", or \"default\"",
1676                          ValueToSourceForError(cx, args.get(0), bytes));
1677     return false;
1678 }
1679 
1680 JS_PUBLIC_API(bool)
JS_PropertyStub(JSContext * cx,HandleObject obj,HandleId id,MutableHandleValue vp)1681 JS_PropertyStub(JSContext* cx, HandleObject obj, HandleId id, MutableHandleValue vp)
1682 {
1683     return true;
1684 }
1685 
1686 JS_PUBLIC_API(bool)
JS_StrictPropertyStub(JSContext * cx,HandleObject obj,HandleId id,MutableHandleValue vp,ObjectOpResult & result)1687 JS_StrictPropertyStub(JSContext* cx, HandleObject obj, HandleId id, MutableHandleValue vp,
1688                       ObjectOpResult& result)
1689 {
1690     return result.succeed();
1691 }
1692 
1693 JS_PUBLIC_API(JSObject*)
JS_InitClass(JSContext * cx,HandleObject obj,HandleObject parent_proto,const JSClass * clasp,JSNative constructor,unsigned nargs,const JSPropertySpec * ps,const JSFunctionSpec * fs,const JSPropertySpec * static_ps,const JSFunctionSpec * static_fs)1694 JS_InitClass(JSContext* cx, HandleObject obj, HandleObject parent_proto,
1695              const JSClass* clasp, JSNative constructor, unsigned nargs,
1696              const JSPropertySpec* ps, const JSFunctionSpec* fs,
1697              const JSPropertySpec* static_ps, const JSFunctionSpec* static_fs)
1698 {
1699     AssertHeapIsIdle(cx);
1700     CHECK_REQUEST(cx);
1701     assertSameCompartment(cx, obj, parent_proto);
1702     return InitClass(cx, obj, parent_proto, Valueify(clasp), constructor,
1703                      nargs, ps, fs, static_ps, static_fs);
1704 }
1705 
1706 JS_PUBLIC_API(bool)
JS_LinkConstructorAndPrototype(JSContext * cx,HandleObject ctor,HandleObject proto)1707 JS_LinkConstructorAndPrototype(JSContext* cx, HandleObject ctor, HandleObject proto)
1708 {
1709     return LinkConstructorAndPrototype(cx, ctor, proto);
1710 }
1711 
1712 JS_PUBLIC_API(const JSClass*)
JS_GetClass(JSObject * obj)1713 JS_GetClass(JSObject* obj)
1714 {
1715     return obj->getJSClass();
1716 }
1717 
1718 JS_PUBLIC_API(bool)
JS_InstanceOf(JSContext * cx,HandleObject obj,const JSClass * clasp,CallArgs * args)1719 JS_InstanceOf(JSContext* cx, HandleObject obj, const JSClass* clasp, CallArgs* args)
1720 {
1721     AssertHeapIsIdle(cx);
1722     CHECK_REQUEST(cx);
1723 #ifdef DEBUG
1724     if (args) {
1725         assertSameCompartment(cx, obj);
1726         assertSameCompartment(cx, args->thisv(), args->calleev());
1727     }
1728 #endif
1729     if (!obj || obj->getJSClass() != clasp) {
1730         if (args)
1731             ReportIncompatibleMethod(cx, *args, Valueify(clasp));
1732         return false;
1733     }
1734     return true;
1735 }
1736 
1737 JS_PUBLIC_API(bool)
JS_HasInstance(JSContext * cx,HandleObject obj,HandleValue value,bool * bp)1738 JS_HasInstance(JSContext* cx, HandleObject obj, HandleValue value, bool* bp)
1739 {
1740     AssertHeapIsIdle(cx);
1741     assertSameCompartment(cx, obj, value);
1742     return HasInstance(cx, obj, value, bp);
1743 }
1744 
1745 JS_PUBLIC_API(void*)
JS_GetPrivate(JSObject * obj)1746 JS_GetPrivate(JSObject* obj)
1747 {
1748     /* This function can be called by a finalizer. */
1749     return obj->as<NativeObject>().getPrivate();
1750 }
1751 
1752 JS_PUBLIC_API(void)
JS_SetPrivate(JSObject * obj,void * data)1753 JS_SetPrivate(JSObject* obj, void* data)
1754 {
1755     /* This function can be called by a finalizer. */
1756     obj->as<NativeObject>().setPrivate(data);
1757 }
1758 
1759 JS_PUBLIC_API(void*)
JS_GetInstancePrivate(JSContext * cx,HandleObject obj,const JSClass * clasp,CallArgs * args)1760 JS_GetInstancePrivate(JSContext* cx, HandleObject obj, const JSClass* clasp, CallArgs* args)
1761 {
1762     if (!JS_InstanceOf(cx, obj, clasp, args))
1763         return nullptr;
1764     return obj->as<NativeObject>().getPrivate();
1765 }
1766 
1767 JS_PUBLIC_API(JSObject*)
JS_GetConstructor(JSContext * cx,HandleObject proto)1768 JS_GetConstructor(JSContext* cx, HandleObject proto)
1769 {
1770     AssertHeapIsIdle(cx);
1771     CHECK_REQUEST(cx);
1772     assertSameCompartment(cx, proto);
1773 
1774     RootedValue cval(cx);
1775     if (!GetProperty(cx, proto, proto, cx->names().constructor, &cval))
1776         return nullptr;
1777     if (!IsFunctionObject(cval)) {
1778         JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_NO_CONSTRUCTOR,
1779                              proto->getClass()->name);
1780         return nullptr;
1781     }
1782     return &cval.toObject();
1783 }
1784 
1785 bool
extraWarnings(JSRuntime * rt) const1786 JS::CompartmentOptions::extraWarnings(JSRuntime* rt) const
1787 {
1788     return extraWarningsOverride_.get(rt->options().extraWarnings());
1789 }
1790 
1791 bool
extraWarnings(JSContext * cx) const1792 JS::CompartmentOptions::extraWarnings(JSContext* cx) const
1793 {
1794     return extraWarnings(cx->runtime());
1795 }
1796 
1797 JS::CompartmentOptions&
setZone(ZoneSpecifier spec)1798 JS::CompartmentOptions::setZone(ZoneSpecifier spec)
1799 {
1800     zone_.spec = spec;
1801     return *this;
1802 }
1803 
1804 JS::CompartmentOptions&
setSameZoneAs(JSObject * obj)1805 JS::CompartmentOptions::setSameZoneAs(JSObject* obj)
1806 {
1807     zone_.pointer = static_cast<void*>(obj->zone());
1808     return *this;
1809 }
1810 
1811 JS::CompartmentOptions&
CompartmentOptionsRef(JSCompartment * compartment)1812 JS::CompartmentOptionsRef(JSCompartment* compartment)
1813 {
1814     return compartment->options();
1815 }
1816 
1817 JS::CompartmentOptions&
CompartmentOptionsRef(JSObject * obj)1818 JS::CompartmentOptionsRef(JSObject* obj)
1819 {
1820     return obj->compartment()->options();
1821 }
1822 
1823 JS::CompartmentOptions&
CompartmentOptionsRef(JSContext * cx)1824 JS::CompartmentOptionsRef(JSContext* cx)
1825 {
1826     return cx->compartment()->options();
1827 }
1828 
1829 JS_PUBLIC_API(JSObject*)
JS_NewGlobalObject(JSContext * cx,const JSClass * clasp,JSPrincipals * principals,JS::OnNewGlobalHookOption hookOption,const JS::CompartmentOptions & options)1830 JS_NewGlobalObject(JSContext* cx, const JSClass* clasp, JSPrincipals* principals,
1831                    JS::OnNewGlobalHookOption hookOption,
1832                    const JS::CompartmentOptions& options /* = JS::CompartmentOptions() */)
1833 {
1834     AssertHeapIsIdle(cx);
1835     CHECK_REQUEST(cx);
1836 
1837     return GlobalObject::new_(cx, Valueify(clasp), principals, hookOption, options);
1838 }
1839 
1840 JS_PUBLIC_API(void)
JS_GlobalObjectTraceHook(JSTracer * trc,JSObject * global)1841 JS_GlobalObjectTraceHook(JSTracer* trc, JSObject* global)
1842 {
1843     MOZ_ASSERT(global->is<GlobalObject>());
1844 
1845     // Off thread parsing and compilation tasks create a dummy global which is then
1846     // merged back into the host compartment. Since it used to be a global, it will still
1847     // have this trace hook, but it does not have a meaning relative to its new compartment.
1848     // We can safely skip it.
1849     if (!global->isOwnGlobal())
1850         return;
1851 
1852     // Trace the compartment for any GC things that should only stick around if we know the
1853     // compartment is live.
1854     global->compartment()->trace(trc);
1855 
1856     JSTraceOp trace = global->compartment()->options().getTrace();
1857     if (trace)
1858         trace(trc, global);
1859 }
1860 
1861 JS_PUBLIC_API(void)
JS_FireOnNewGlobalObject(JSContext * cx,JS::HandleObject global)1862 JS_FireOnNewGlobalObject(JSContext* cx, JS::HandleObject global)
1863 {
1864     // This hook is infallible, because we don't really want arbitrary script
1865     // to be able to throw errors during delicate global creation routines.
1866     // This infallibility will eat OOM and slow script, but if that happens
1867     // we'll likely run up into them again soon in a fallible context.
1868     Rooted<js::GlobalObject*> globalObject(cx, &global->as<GlobalObject>());
1869     Debugger::onNewGlobalObject(cx, globalObject);
1870 }
1871 
1872 JS_PUBLIC_API(JSObject*)
JS_NewObject(JSContext * cx,const JSClass * jsclasp)1873 JS_NewObject(JSContext* cx, const JSClass* jsclasp)
1874 {
1875     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
1876     AssertHeapIsIdle(cx);
1877     CHECK_REQUEST(cx);
1878 
1879     const Class* clasp = Valueify(jsclasp);
1880     if (!clasp)
1881         clasp = &PlainObject::class_;    /* default class is Object */
1882 
1883     MOZ_ASSERT(clasp != &JSFunction::class_);
1884     MOZ_ASSERT(!(clasp->flags & JSCLASS_IS_GLOBAL));
1885 
1886     return NewObjectWithClassProto(cx, clasp, nullptr);
1887 }
1888 
1889 JS_PUBLIC_API(JSObject*)
JS_NewObjectWithGivenProto(JSContext * cx,const JSClass * jsclasp,HandleObject proto)1890 JS_NewObjectWithGivenProto(JSContext* cx, const JSClass* jsclasp, HandleObject proto)
1891 {
1892     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
1893     AssertHeapIsIdle(cx);
1894     CHECK_REQUEST(cx);
1895     assertSameCompartment(cx, proto);
1896 
1897     const Class* clasp = Valueify(jsclasp);
1898     if (!clasp)
1899         clasp = &PlainObject::class_;    /* default class is Object */
1900 
1901     MOZ_ASSERT(clasp != &JSFunction::class_);
1902     MOZ_ASSERT(!(clasp->flags & JSCLASS_IS_GLOBAL));
1903 
1904     return NewObjectWithGivenProto(cx, clasp, proto);
1905 }
1906 
1907 JS_PUBLIC_API(JSObject*)
JS_NewPlainObject(JSContext * cx)1908 JS_NewPlainObject(JSContext* cx)
1909 {
1910     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
1911     AssertHeapIsIdle(cx);
1912     CHECK_REQUEST(cx);
1913 
1914     return NewBuiltinClassInstance<PlainObject>(cx);
1915 }
1916 
1917 JS_PUBLIC_API(JSObject*)
JS_NewObjectForConstructor(JSContext * cx,const JSClass * clasp,const CallArgs & args)1918 JS_NewObjectForConstructor(JSContext* cx, const JSClass* clasp, const CallArgs& args)
1919 {
1920     AssertHeapIsIdle(cx);
1921     CHECK_REQUEST(cx);
1922 
1923     Value callee = args.calleev();
1924     assertSameCompartment(cx, callee);
1925     RootedObject obj(cx, &callee.toObject());
1926     return CreateThis(cx, Valueify(clasp), obj);
1927 }
1928 
1929 JS_PUBLIC_API(bool)
JS_IsNative(JSObject * obj)1930 JS_IsNative(JSObject* obj)
1931 {
1932     return obj->isNative();
1933 }
1934 
1935 JS_PUBLIC_API(JSRuntime*)
JS_GetObjectRuntime(JSObject * obj)1936 JS_GetObjectRuntime(JSObject* obj)
1937 {
1938     return obj->compartment()->runtimeFromMainThread();
1939 }
1940 
1941 
1942 /*** Standard internal methods *******************************************************************/
1943 
1944 JS_PUBLIC_API(bool)
JS_GetPrototype(JSContext * cx,HandleObject obj,MutableHandleObject result)1945 JS_GetPrototype(JSContext* cx, HandleObject obj, MutableHandleObject result)
1946 {
1947     return GetPrototype(cx, obj, result);
1948 }
1949 
1950 JS_PUBLIC_API(bool)
JS_SetPrototype(JSContext * cx,HandleObject obj,HandleObject proto)1951 JS_SetPrototype(JSContext* cx, HandleObject obj, HandleObject proto)
1952 {
1953     AssertHeapIsIdle(cx);
1954     CHECK_REQUEST(cx);
1955     assertSameCompartment(cx, obj, proto);
1956 
1957     return SetPrototype(cx, obj, proto);
1958 }
1959 
1960 JS_PUBLIC_API(bool)
JS_IsExtensible(JSContext * cx,HandleObject obj,bool * extensible)1961 JS_IsExtensible(JSContext* cx, HandleObject obj, bool* extensible)
1962 {
1963     return IsExtensible(cx, obj, extensible);
1964 }
1965 
1966 JS_PUBLIC_API(bool)
JS_PreventExtensions(JSContext * cx,JS::HandleObject obj,ObjectOpResult & result)1967 JS_PreventExtensions(JSContext* cx, JS::HandleObject obj, ObjectOpResult& result)
1968 {
1969     return PreventExtensions(cx, obj, result);
1970 }
1971 
1972 JS_PUBLIC_API(bool)
JS_SetImmutablePrototype(JSContext * cx,JS::HandleObject obj,bool * succeeded)1973 JS_SetImmutablePrototype(JSContext *cx, JS::HandleObject obj, bool *succeeded)
1974 {
1975     return SetImmutablePrototype(cx, obj, succeeded);
1976 }
1977 
1978 JS_PUBLIC_API(bool)
JS_GetOwnPropertyDescriptorById(JSContext * cx,HandleObject obj,HandleId id,MutableHandle<JSPropertyDescriptor> desc)1979 JS_GetOwnPropertyDescriptorById(JSContext* cx, HandleObject obj, HandleId id,
1980                                 MutableHandle<JSPropertyDescriptor> desc)
1981 {
1982     AssertHeapIsIdle(cx);
1983     CHECK_REQUEST(cx);
1984 
1985     return GetOwnPropertyDescriptor(cx, obj, id, desc);
1986 }
1987 
1988 JS_PUBLIC_API(bool)
JS_GetOwnPropertyDescriptor(JSContext * cx,HandleObject obj,const char * name,MutableHandle<JSPropertyDescriptor> desc)1989 JS_GetOwnPropertyDescriptor(JSContext* cx, HandleObject obj, const char* name,
1990                             MutableHandle<JSPropertyDescriptor> desc)
1991 {
1992     JSAtom* atom = Atomize(cx, name, strlen(name));
1993     if (!atom)
1994         return false;
1995     RootedId id(cx, AtomToId(atom));
1996     return JS_GetOwnPropertyDescriptorById(cx, obj, id, desc);
1997 }
1998 
1999 JS_PUBLIC_API(bool)
JS_GetOwnUCPropertyDescriptor(JSContext * cx,HandleObject obj,const char16_t * name,MutableHandle<JSPropertyDescriptor> desc)2000 JS_GetOwnUCPropertyDescriptor(JSContext* cx, HandleObject obj, const char16_t* name,
2001                               MutableHandle<JSPropertyDescriptor> desc)
2002 {
2003     JSAtom* atom = AtomizeChars(cx, name, js_strlen(name));
2004     if (!atom)
2005         return false;
2006     RootedId id(cx, AtomToId(atom));
2007     return JS_GetOwnPropertyDescriptorById(cx, obj, id, desc);
2008 }
2009 
2010 JS_PUBLIC_API(bool)
JS_GetPropertyDescriptorById(JSContext * cx,HandleObject obj,HandleId id,MutableHandle<JSPropertyDescriptor> desc)2011 JS_GetPropertyDescriptorById(JSContext* cx, HandleObject obj, HandleId id,
2012                              MutableHandle<JSPropertyDescriptor> desc)
2013 {
2014     return GetPropertyDescriptor(cx, obj, id, desc);
2015 }
2016 
2017 JS_PUBLIC_API(bool)
JS_GetPropertyDescriptor(JSContext * cx,HandleObject obj,const char * name,MutableHandle<JSPropertyDescriptor> desc)2018 JS_GetPropertyDescriptor(JSContext* cx, HandleObject obj, const char* name,
2019                          MutableHandle<JSPropertyDescriptor> desc)
2020 {
2021     JSAtom* atom = Atomize(cx, name, strlen(name));
2022     if (!atom)
2023         return false;
2024     RootedId id(cx, AtomToId(atom));
2025     return atom && JS_GetPropertyDescriptorById(cx, obj, id, desc);
2026 }
2027 
2028 static bool
DefinePropertyByDescriptor(JSContext * cx,HandleObject obj,HandleId id,Handle<JSPropertyDescriptor> desc,ObjectOpResult & result)2029 DefinePropertyByDescriptor(JSContext* cx, HandleObject obj, HandleId id,
2030                            Handle<JSPropertyDescriptor> desc, ObjectOpResult& result)
2031 {
2032     AssertHeapIsIdle(cx);
2033     CHECK_REQUEST(cx);
2034     assertSameCompartment(cx, obj, id, desc);
2035     return DefineProperty(cx, obj, id, desc.value(), desc.getter(), desc.setter(),
2036                           desc.attributes(), result);
2037 }
2038 
2039 JS_PUBLIC_API(bool)
JS_DefinePropertyById(JSContext * cx,HandleObject obj,HandleId id,Handle<JSPropertyDescriptor> desc,ObjectOpResult & result)2040 JS_DefinePropertyById(JSContext* cx, HandleObject obj, HandleId id,
2041                       Handle<JSPropertyDescriptor> desc, ObjectOpResult& result)
2042 {
2043     return DefinePropertyByDescriptor(cx, obj, id, desc, result);
2044 }
2045 
2046 JS_PUBLIC_API(bool)
JS_DefinePropertyById(JSContext * cx,HandleObject obj,HandleId id,Handle<JSPropertyDescriptor> desc)2047 JS_DefinePropertyById(JSContext* cx, HandleObject obj, HandleId id,
2048                       Handle<JSPropertyDescriptor> desc)
2049 {
2050     ObjectOpResult result;
2051     return DefinePropertyByDescriptor(cx, obj, id, desc, result) &&
2052            result.checkStrict(cx, obj, id);
2053 }
2054 
2055 static bool
DefinePropertyById(JSContext * cx,HandleObject obj,HandleId id,HandleValue value,const JSNativeWrapper & get,const JSNativeWrapper & set,unsigned attrs,unsigned flags)2056 DefinePropertyById(JSContext* cx, HandleObject obj, HandleId id, HandleValue value,
2057                    const JSNativeWrapper& get, const JSNativeWrapper& set,
2058                    unsigned attrs, unsigned flags)
2059 {
2060     JSGetterOp getter = JS_CAST_NATIVE_TO(get.op, JSGetterOp);
2061     JSSetterOp setter = JS_CAST_NATIVE_TO(set.op, JSSetterOp);
2062 
2063     // JSPROP_READONLY has no meaning when accessors are involved. Ideally we'd
2064     // throw if this happens, but we've accepted it for long enough that it's
2065     // not worth trying to make callers change their ways. Just flip it off on
2066     // its way through the API layer so that we can enforce this internally.
2067     if (attrs & (JSPROP_GETTER | JSPROP_SETTER))
2068         attrs &= ~JSPROP_READONLY;
2069 
2070     // When we use DefineProperty, we need full scriptable Function objects rather
2071     // than JSNatives. However, we might be pulling this property descriptor off
2072     // of something with JSNative property descriptors. If we are, wrap them in
2073     // JS Function objects.
2074     //
2075     // But skip doing this if our accessors are the well-known stub
2076     // accessors, since those are known to be JSGetterOps.  Assert
2077     // some sanity about it, though.
2078     MOZ_ASSERT_IF(getter == JS_PropertyStub,
2079                   setter == JS_StrictPropertyStub || (attrs & JSPROP_PROPOP_ACCESSORS));
2080     MOZ_ASSERT_IF(setter == JS_StrictPropertyStub,
2081                   getter == JS_PropertyStub || (attrs & JSPROP_PROPOP_ACCESSORS));
2082 
2083     // If !(attrs & JSPROP_PROPOP_ACCESSORS), then either getter/setter are both
2084     // possibly-null JSNatives (or possibly-null JSFunction* if JSPROP_GETTER or
2085     // JSPROP_SETTER is appropriately set), or both are the well-known property
2086     // stubs.  The subsequent block must handle only the first of these cases,
2087     // so carefully exclude the latter case.
2088     if (!(attrs & JSPROP_PROPOP_ACCESSORS) &&
2089         getter != JS_PropertyStub && setter != JS_StrictPropertyStub)
2090     {
2091         RootedAtom atom(cx, JSID_IS_ATOM(id) ? JSID_TO_ATOM(id) : nullptr);
2092         if (getter && !(attrs & JSPROP_GETTER)) {
2093             JSFunction* getobj = NewNativeFunction(cx, (Native) getter, 0, atom);
2094             if (!getobj)
2095                 return false;
2096 
2097             if (get.info)
2098                 getobj->setJitInfo(get.info);
2099 
2100             getter = JS_DATA_TO_FUNC_PTR(GetterOp, getobj);
2101             attrs |= JSPROP_GETTER;
2102         }
2103         if (setter && !(attrs & JSPROP_SETTER)) {
2104             // Root just the getter, since the setter is not yet a JSObject.
2105             AutoRooterGetterSetter getRoot(cx, JSPROP_GETTER, &getter, nullptr);
2106             JSFunction* setobj = NewNativeFunction(cx, (Native) setter, 1, atom);
2107             if (!setobj)
2108                 return false;
2109 
2110             if (set.info)
2111                 setobj->setJitInfo(set.info);
2112 
2113             setter = JS_DATA_TO_FUNC_PTR(SetterOp, setobj);
2114             attrs |= JSPROP_SETTER;
2115         }
2116     } else {
2117         attrs &= ~JSPROP_PROPOP_ACCESSORS;
2118     }
2119 
2120     AssertHeapIsIdle(cx);
2121     CHECK_REQUEST(cx);
2122     assertSameCompartment(cx, obj, id, value,
2123                           (attrs & JSPROP_GETTER)
2124                           ? JS_FUNC_TO_DATA_PTR(JSObject*, getter)
2125                           : nullptr,
2126                           (attrs & JSPROP_SETTER)
2127                           ? JS_FUNC_TO_DATA_PTR(JSObject*, setter)
2128                           : nullptr);
2129 
2130     // In most places throughout the engine, a property with null getter and
2131     // not JSPROP_GETTER/SETTER/SHARED has no getter, and the same for setters:
2132     // it's just a plain old data property. However the JS_Define* APIs use
2133     // null getter and setter to mean "default to the Class getProperty and
2134     // setProperty ops".
2135     if (!(attrs & (JSPROP_GETTER | JSPROP_SETTER))) {
2136         if (!getter)
2137             getter = obj->getClass()->getProperty;
2138         if (!setter)
2139             setter = obj->getClass()->setProperty;
2140     }
2141     if (getter == JS_PropertyStub)
2142         getter = nullptr;
2143     if (setter == JS_StrictPropertyStub)
2144         setter = nullptr;
2145     return DefineProperty(cx, obj, id, value, getter, setter, attrs);
2146 }
2147 
2148 /*
2149  * Wrapper functions to create wrappers with no corresponding JSJitInfo from API
2150  * function arguments.
2151  */
2152 static JSNativeWrapper
NativeOpWrapper(Native native)2153 NativeOpWrapper(Native native)
2154 {
2155     JSNativeWrapper ret;
2156     ret.op = native;
2157     ret.info = nullptr;
2158     return ret;
2159 }
2160 
2161 JS_PUBLIC_API(bool)
JS_DefinePropertyById(JSContext * cx,HandleObject obj,HandleId id,HandleValue value,unsigned attrs,Native getter,Native setter)2162 JS_DefinePropertyById(JSContext* cx, HandleObject obj, HandleId id, HandleValue value,
2163                       unsigned attrs, Native getter, Native setter)
2164 {
2165     return DefinePropertyById(cx, obj, id, value,
2166                               NativeOpWrapper(getter), NativeOpWrapper(setter),
2167                               attrs, 0);
2168 }
2169 
2170 JS_PUBLIC_API(bool)
JS_DefinePropertyById(JSContext * cx,HandleObject obj,HandleId id,HandleObject valueArg,unsigned attrs,Native getter,Native setter)2171 JS_DefinePropertyById(JSContext* cx, HandleObject obj, HandleId id, HandleObject valueArg,
2172                       unsigned attrs, Native getter, Native setter)
2173 {
2174     RootedValue value(cx, ObjectValue(*valueArg));
2175     return DefinePropertyById(cx, obj, id, value,
2176                               NativeOpWrapper(getter), NativeOpWrapper(setter),
2177                               attrs, 0);
2178 }
2179 
2180 JS_PUBLIC_API(bool)
JS_DefinePropertyById(JSContext * cx,HandleObject obj,HandleId id,HandleString valueArg,unsigned attrs,Native getter,Native setter)2181 JS_DefinePropertyById(JSContext* cx, HandleObject obj, HandleId id, HandleString valueArg,
2182                       unsigned attrs, Native getter, Native setter)
2183 {
2184     RootedValue value(cx, StringValue(valueArg));
2185     return DefinePropertyById(cx, obj, id, value,
2186                               NativeOpWrapper(getter), NativeOpWrapper(setter),
2187                               attrs, 0);
2188 }
2189 
2190 JS_PUBLIC_API(bool)
JS_DefinePropertyById(JSContext * cx,HandleObject obj,HandleId id,int32_t valueArg,unsigned attrs,Native getter,Native setter)2191 JS_DefinePropertyById(JSContext* cx, HandleObject obj, HandleId id, int32_t valueArg,
2192                       unsigned attrs, Native getter, Native setter)
2193 {
2194     Value value = Int32Value(valueArg);
2195     return DefinePropertyById(cx, obj, id, HandleValue::fromMarkedLocation(&value),
2196                               NativeOpWrapper(getter), NativeOpWrapper(setter), attrs, 0);
2197 }
2198 
2199 JS_PUBLIC_API(bool)
JS_DefinePropertyById(JSContext * cx,HandleObject obj,HandleId id,uint32_t valueArg,unsigned attrs,Native getter,Native setter)2200 JS_DefinePropertyById(JSContext* cx, HandleObject obj, HandleId id, uint32_t valueArg,
2201                       unsigned attrs, Native getter, Native setter)
2202 {
2203     Value value = NumberValue(valueArg);
2204     return DefinePropertyById(cx, obj, id, HandleValue::fromMarkedLocation(&value),
2205                               NativeOpWrapper(getter), NativeOpWrapper(setter), attrs, 0);
2206 }
2207 
2208 JS_PUBLIC_API(bool)
JS_DefinePropertyById(JSContext * cx,HandleObject obj,HandleId id,double valueArg,unsigned attrs,Native getter,Native setter)2209 JS_DefinePropertyById(JSContext* cx, HandleObject obj, HandleId id, double valueArg,
2210                       unsigned attrs, Native getter, Native setter)
2211 {
2212     Value value = NumberValue(valueArg);
2213     return DefinePropertyById(cx, obj, id, HandleValue::fromMarkedLocation(&value),
2214                               NativeOpWrapper(getter), NativeOpWrapper(setter), attrs, 0);
2215 }
2216 
2217 static bool
DefineProperty(JSContext * cx,HandleObject obj,const char * name,HandleValue value,const JSNativeWrapper & getter,const JSNativeWrapper & setter,unsigned attrs,unsigned flags)2218 DefineProperty(JSContext* cx, HandleObject obj, const char* name, HandleValue value,
2219                const JSNativeWrapper& getter, const JSNativeWrapper& setter,
2220                unsigned attrs, unsigned flags)
2221 {
2222     AutoRooterGetterSetter gsRoot(cx, attrs, const_cast<JSNative*>(&getter.op),
2223                                   const_cast<JSNative*>(&setter.op));
2224 
2225     JSAtom* atom = Atomize(cx, name, strlen(name));
2226     if (!atom)
2227         return false;
2228     RootedId id(cx, AtomToId(atom));
2229 
2230     return DefinePropertyById(cx, obj, id, value, getter, setter, attrs, flags);
2231 }
2232 
2233 JS_PUBLIC_API(bool)
JS_DefineProperty(JSContext * cx,HandleObject obj,const char * name,HandleValue value,unsigned attrs,Native getter,Native setter)2234 JS_DefineProperty(JSContext* cx, HandleObject obj, const char* name, HandleValue value,
2235                   unsigned attrs,
2236                   Native getter /* = nullptr */, Native setter /* = nullptr */)
2237 {
2238     return DefineProperty(cx, obj, name, value, NativeOpWrapper(getter), NativeOpWrapper(setter),
2239                           attrs, 0);
2240 }
2241 
2242 JS_PUBLIC_API(bool)
JS_DefineProperty(JSContext * cx,HandleObject obj,const char * name,HandleObject valueArg,unsigned attrs,Native getter,Native setter)2243 JS_DefineProperty(JSContext* cx, HandleObject obj, const char* name, HandleObject valueArg,
2244                   unsigned attrs,
2245                   Native getter /* = nullptr */, Native setter /* = nullptr */)
2246 {
2247     RootedValue value(cx, ObjectValue(*valueArg));
2248     return DefineProperty(cx, obj, name, value, NativeOpWrapper(getter), NativeOpWrapper(setter),
2249                           attrs, 0);
2250 }
2251 
2252 JS_PUBLIC_API(bool)
JS_DefineProperty(JSContext * cx,HandleObject obj,const char * name,HandleString valueArg,unsigned attrs,Native getter,Native setter)2253 JS_DefineProperty(JSContext* cx, HandleObject obj, const char* name, HandleString valueArg,
2254                   unsigned attrs,
2255                   Native getter /* = nullptr */, Native setter /* = nullptr */)
2256 {
2257     RootedValue value(cx, StringValue(valueArg));
2258     return DefineProperty(cx, obj, name, value, NativeOpWrapper(getter), NativeOpWrapper(setter),
2259                           attrs, 0);
2260 }
2261 
2262 JS_PUBLIC_API(bool)
JS_DefineProperty(JSContext * cx,HandleObject obj,const char * name,int32_t valueArg,unsigned attrs,Native getter,Native setter)2263 JS_DefineProperty(JSContext* cx, HandleObject obj, const char* name, int32_t valueArg,
2264                   unsigned attrs,
2265                   Native getter /* = nullptr */, Native setter /* = nullptr */)
2266 {
2267     Value value = Int32Value(valueArg);
2268     return DefineProperty(cx, obj, name, HandleValue::fromMarkedLocation(&value),
2269                           NativeOpWrapper(getter), NativeOpWrapper(setter), attrs, 0);
2270 }
2271 
2272 JS_PUBLIC_API(bool)
JS_DefineProperty(JSContext * cx,HandleObject obj,const char * name,uint32_t valueArg,unsigned attrs,Native getter,Native setter)2273 JS_DefineProperty(JSContext* cx, HandleObject obj, const char* name, uint32_t valueArg,
2274                   unsigned attrs,
2275                   Native getter /* = nullptr */, Native setter /* = nullptr */)
2276 {
2277     Value value = NumberValue(valueArg);
2278     return DefineProperty(cx, obj, name, HandleValue::fromMarkedLocation(&value),
2279                           NativeOpWrapper(getter), NativeOpWrapper(setter), attrs, 0);
2280 }
2281 
2282 JS_PUBLIC_API(bool)
JS_DefineProperty(JSContext * cx,HandleObject obj,const char * name,double valueArg,unsigned attrs,Native getter,Native setter)2283 JS_DefineProperty(JSContext* cx, HandleObject obj, const char* name, double valueArg,
2284                   unsigned attrs,
2285                   Native getter /* = nullptr */, Native setter /* = nullptr */)
2286 {
2287     Value value = NumberValue(valueArg);
2288     return DefineProperty(cx, obj, name, HandleValue::fromMarkedLocation(&value),
2289                           NativeOpWrapper(getter), NativeOpWrapper(setter), attrs, 0);
2290 }
2291 
2292 #define AUTO_NAMELEN(s,n)   (((n) == (size_t)-1) ? js_strlen(s) : (n))
2293 
2294 JS_PUBLIC_API(bool)
JS_DefineUCProperty(JSContext * cx,HandleObject obj,const char16_t * name,size_t namelen,Handle<JSPropertyDescriptor> desc,ObjectOpResult & result)2295 JS_DefineUCProperty(JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
2296                     Handle<JSPropertyDescriptor> desc,
2297                     ObjectOpResult& result)
2298 {
2299     JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
2300     if (!atom)
2301         return false;
2302     RootedId id(cx, AtomToId(atom));
2303     return DefinePropertyByDescriptor(cx, obj, id, desc, result);
2304 }
2305 
2306 JS_PUBLIC_API(bool)
JS_DefineUCProperty(JSContext * cx,HandleObject obj,const char16_t * name,size_t namelen,Handle<JSPropertyDescriptor> desc)2307 JS_DefineUCProperty(JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
2308                     Handle<JSPropertyDescriptor> desc)
2309 {
2310     JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
2311     if (!atom)
2312         return false;
2313     RootedId id(cx, AtomToId(atom));
2314     ObjectOpResult result;
2315     return DefinePropertyByDescriptor(cx, obj, id, desc, result) &&
2316            result.checkStrict(cx, obj, id);
2317 }
2318 
2319 static bool
DefineUCProperty(JSContext * cx,HandleObject obj,const char16_t * name,size_t namelen,const Value & value_,Native getter,Native setter,unsigned attrs,unsigned flags)2320 DefineUCProperty(JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
2321                  const Value& value_, Native getter, Native setter, unsigned attrs,
2322                  unsigned flags)
2323 {
2324     RootedValue value(cx, value_);
2325     AutoRooterGetterSetter gsRoot(cx, attrs, &getter, &setter);
2326     JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
2327     if (!atom)
2328         return false;
2329     RootedId id(cx, AtomToId(atom));
2330     return DefinePropertyById(cx, obj, id, value, NativeOpWrapper(getter), NativeOpWrapper(setter),
2331                               attrs, flags);
2332 }
2333 
2334 JS_PUBLIC_API(bool)
JS_DefineUCProperty(JSContext * cx,HandleObject obj,const char16_t * name,size_t namelen,HandleValue value,unsigned attrs,Native getter,Native setter)2335 JS_DefineUCProperty(JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
2336                     HandleValue value, unsigned attrs, Native getter, Native setter)
2337 {
2338     return DefineUCProperty(cx, obj, name, namelen, value, getter, setter, attrs, 0);
2339 }
2340 
2341 JS_PUBLIC_API(bool)
JS_DefineUCProperty(JSContext * cx,HandleObject obj,const char16_t * name,size_t namelen,HandleObject valueArg,unsigned attrs,Native getter,Native setter)2342 JS_DefineUCProperty(JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
2343                     HandleObject valueArg, unsigned attrs, Native getter, Native setter)
2344 {
2345     RootedValue value(cx, ObjectValue(*valueArg));
2346     return DefineUCProperty(cx, obj, name, namelen, value, getter, setter, attrs, 0);
2347 }
2348 
2349 JS_PUBLIC_API(bool)
JS_DefineUCProperty(JSContext * cx,HandleObject obj,const char16_t * name,size_t namelen,HandleString valueArg,unsigned attrs,Native getter,Native setter)2350 JS_DefineUCProperty(JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
2351                     HandleString valueArg, unsigned attrs, Native getter, Native setter)
2352 {
2353     RootedValue value(cx, StringValue(valueArg));
2354     return DefineUCProperty(cx, obj, name, namelen, value, getter, setter, attrs, 0);
2355 }
2356 
2357 JS_PUBLIC_API(bool)
JS_DefineUCProperty(JSContext * cx,HandleObject obj,const char16_t * name,size_t namelen,int32_t valueArg,unsigned attrs,Native getter,Native setter)2358 JS_DefineUCProperty(JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
2359                     int32_t valueArg, unsigned attrs, Native getter, Native setter)
2360 {
2361     Value value = Int32Value(valueArg);
2362     return DefineUCProperty(cx, obj, name, namelen, HandleValue::fromMarkedLocation(&value),
2363                             getter, setter, attrs, 0);
2364 }
2365 
2366 JS_PUBLIC_API(bool)
JS_DefineUCProperty(JSContext * cx,HandleObject obj,const char16_t * name,size_t namelen,uint32_t valueArg,unsigned attrs,Native getter,Native setter)2367 JS_DefineUCProperty(JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
2368                     uint32_t valueArg, unsigned attrs, Native getter, Native setter)
2369 {
2370     Value value = NumberValue(valueArg);
2371     return DefineUCProperty(cx, obj, name, namelen, HandleValue::fromMarkedLocation(&value),
2372                             getter, setter, attrs, 0);
2373 }
2374 
2375 JS_PUBLIC_API(bool)
JS_DefineUCProperty(JSContext * cx,HandleObject obj,const char16_t * name,size_t namelen,double valueArg,unsigned attrs,Native getter,Native setter)2376 JS_DefineUCProperty(JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
2377                     double valueArg, unsigned attrs, Native getter, Native setter)
2378 {
2379     Value value = NumberValue(valueArg);
2380     return DefineUCProperty(cx, obj, name, namelen, HandleValue::fromMarkedLocation(&value),
2381                             getter, setter, attrs, 0);
2382 }
2383 
2384 static bool
DefineElement(JSContext * cx,HandleObject obj,uint32_t index,HandleValue value,unsigned attrs,Native getter,Native setter)2385 DefineElement(JSContext* cx, HandleObject obj, uint32_t index, HandleValue value,
2386               unsigned attrs, Native getter, Native setter)
2387 {
2388     AutoRooterGetterSetter gsRoot(cx, attrs, &getter, &setter);
2389     AssertHeapIsIdle(cx);
2390     CHECK_REQUEST(cx);
2391     RootedId id(cx);
2392     if (!IndexToId(cx, index, &id))
2393         return false;
2394     return DefinePropertyById(cx, obj, id, value,
2395                               NativeOpWrapper(getter), NativeOpWrapper(setter),
2396                               attrs, 0);
2397 }
2398 
2399 JS_PUBLIC_API(bool)
JS_DefineElement(JSContext * cx,HandleObject obj,uint32_t index,HandleValue value,unsigned attrs,Native getter,Native setter)2400 JS_DefineElement(JSContext* cx, HandleObject obj, uint32_t index, HandleValue value,
2401                  unsigned attrs, Native getter, Native setter)
2402 {
2403     return DefineElement(cx, obj, index, value, attrs, getter, setter);
2404 }
2405 
2406 JS_PUBLIC_API(bool)
JS_DefineElement(JSContext * cx,HandleObject obj,uint32_t index,HandleObject valueArg,unsigned attrs,Native getter,Native setter)2407 JS_DefineElement(JSContext* cx, HandleObject obj, uint32_t index, HandleObject valueArg,
2408                  unsigned attrs, Native getter, Native setter)
2409 {
2410     RootedValue value(cx, ObjectValue(*valueArg));
2411     return DefineElement(cx, obj, index, value, attrs, getter, setter);
2412 }
2413 
2414 JS_PUBLIC_API(bool)
JS_DefineElement(JSContext * cx,HandleObject obj,uint32_t index,HandleString valueArg,unsigned attrs,Native getter,Native setter)2415 JS_DefineElement(JSContext* cx, HandleObject obj, uint32_t index, HandleString valueArg,
2416                  unsigned attrs, Native getter, Native setter)
2417 {
2418     RootedValue value(cx, StringValue(valueArg));
2419     return DefineElement(cx, obj, index, value, attrs, getter, setter);
2420 }
2421 
2422 JS_PUBLIC_API(bool)
JS_DefineElement(JSContext * cx,HandleObject obj,uint32_t index,int32_t valueArg,unsigned attrs,Native getter,Native setter)2423 JS_DefineElement(JSContext* cx, HandleObject obj, uint32_t index, int32_t valueArg,
2424                  unsigned attrs, Native getter, Native setter)
2425 {
2426     Value value = Int32Value(valueArg);
2427     return DefineElement(cx, obj, index, HandleValue::fromMarkedLocation(&value),
2428                          attrs, getter, setter);
2429 }
2430 
2431 JS_PUBLIC_API(bool)
JS_DefineElement(JSContext * cx,HandleObject obj,uint32_t index,uint32_t valueArg,unsigned attrs,Native getter,Native setter)2432 JS_DefineElement(JSContext* cx, HandleObject obj, uint32_t index, uint32_t valueArg,
2433                  unsigned attrs, Native getter, Native setter)
2434 {
2435     Value value = NumberValue(valueArg);
2436     return DefineElement(cx, obj, index, HandleValue::fromMarkedLocation(&value),
2437                          attrs, getter, setter);
2438 }
2439 
2440 JS_PUBLIC_API(bool)
JS_DefineElement(JSContext * cx,HandleObject obj,uint32_t index,double valueArg,unsigned attrs,Native getter,Native setter)2441 JS_DefineElement(JSContext* cx, HandleObject obj, uint32_t index, double valueArg,
2442                  unsigned attrs, Native getter, Native setter)
2443 {
2444     Value value = NumberValue(valueArg);
2445     return DefineElement(cx, obj, index, HandleValue::fromMarkedLocation(&value),
2446                          attrs, getter, setter);
2447 }
2448 
2449 JS_PUBLIC_API(bool)
JS_HasPropertyById(JSContext * cx,HandleObject obj,HandleId id,bool * foundp)2450 JS_HasPropertyById(JSContext* cx, HandleObject obj, HandleId id, bool* foundp)
2451 {
2452     AssertHeapIsIdle(cx);
2453     CHECK_REQUEST(cx);
2454 
2455     return HasProperty(cx, obj, id, foundp);
2456 }
2457 
2458 JS_PUBLIC_API(bool)
JS_HasProperty(JSContext * cx,HandleObject obj,const char * name,bool * foundp)2459 JS_HasProperty(JSContext* cx, HandleObject obj, const char* name, bool* foundp)
2460 {
2461     JSAtom* atom = Atomize(cx, name, strlen(name));
2462     if (!atom)
2463         return false;
2464     RootedId id(cx, AtomToId(atom));
2465     return JS_HasPropertyById(cx, obj, id, foundp);
2466 }
2467 
2468 JS_PUBLIC_API(bool)
JS_HasUCProperty(JSContext * cx,HandleObject obj,const char16_t * name,size_t namelen,bool * foundp)2469 JS_HasUCProperty(JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen, bool* foundp)
2470 {
2471     JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
2472     if (!atom)
2473         return false;
2474     RootedId id(cx, AtomToId(atom));
2475     return JS_HasPropertyById(cx, obj, id, foundp);
2476 }
2477 
2478 JS_PUBLIC_API(bool)
JS_HasElement(JSContext * cx,HandleObject obj,uint32_t index,bool * foundp)2479 JS_HasElement(JSContext* cx, HandleObject obj, uint32_t index, bool* foundp)
2480 {
2481     AssertHeapIsIdle(cx);
2482     CHECK_REQUEST(cx);
2483     RootedId id(cx);
2484     if (!IndexToId(cx, index, &id))
2485         return false;
2486     return JS_HasPropertyById(cx, obj, id, foundp);
2487 }
2488 
2489 JS_PUBLIC_API(bool)
JS_HasOwnPropertyById(JSContext * cx,HandleObject obj,HandleId id,bool * foundp)2490 JS_HasOwnPropertyById(JSContext* cx, HandleObject obj, HandleId id, bool* foundp)
2491 {
2492     AssertHeapIsIdle(cx);
2493     CHECK_REQUEST(cx);
2494     assertSameCompartment(cx, obj, id);
2495 
2496     return HasOwnProperty(cx, obj, id, foundp);
2497 }
2498 
2499 JS_PUBLIC_API(bool)
JS_HasOwnProperty(JSContext * cx,HandleObject obj,const char * name,bool * foundp)2500 JS_HasOwnProperty(JSContext* cx, HandleObject obj, const char* name, bool* foundp)
2501 {
2502     JSAtom* atom = Atomize(cx, name, strlen(name));
2503     if (!atom)
2504         return false;
2505     RootedId id(cx, AtomToId(atom));
2506     return JS_HasOwnPropertyById(cx, obj, id, foundp);
2507 }
2508 
2509 JS_PUBLIC_API(bool)
JS_ForwardGetPropertyTo(JSContext * cx,HandleObject obj,HandleId id,HandleValue receiver,MutableHandleValue vp)2510 JS_ForwardGetPropertyTo(JSContext* cx, HandleObject obj, HandleId id, HandleValue receiver,
2511                         MutableHandleValue vp)
2512 {
2513     AssertHeapIsIdle(cx);
2514     CHECK_REQUEST(cx);
2515     assertSameCompartment(cx, obj, id, receiver);
2516 
2517     return GetProperty(cx, obj, receiver, id, vp);
2518 }
2519 
2520 JS_PUBLIC_API(bool)
JS_ForwardGetElementTo(JSContext * cx,HandleObject obj,uint32_t index,HandleObject receiver,MutableHandleValue vp)2521 JS_ForwardGetElementTo(JSContext* cx, HandleObject obj, uint32_t index, HandleObject receiver,
2522                        MutableHandleValue vp)
2523 {
2524     AssertHeapIsIdle(cx);
2525     CHECK_REQUEST(cx);
2526     assertSameCompartment(cx, obj);
2527 
2528     return GetElement(cx, obj, receiver, index, vp);
2529 }
2530 
2531 JS_PUBLIC_API(bool)
JS_GetPropertyById(JSContext * cx,HandleObject obj,HandleId id,MutableHandleValue vp)2532 JS_GetPropertyById(JSContext* cx, HandleObject obj, HandleId id, MutableHandleValue vp)
2533 {
2534     RootedValue receiver(cx, ObjectValue(*obj));
2535     return JS_ForwardGetPropertyTo(cx, obj, id, receiver, vp);
2536 }
2537 
2538 JS_PUBLIC_API(bool)
JS_GetProperty(JSContext * cx,HandleObject obj,const char * name,MutableHandleValue vp)2539 JS_GetProperty(JSContext* cx, HandleObject obj, const char* name, MutableHandleValue vp)
2540 {
2541     JSAtom* atom = Atomize(cx, name, strlen(name));
2542     if (!atom)
2543         return false;
2544     RootedId id(cx, AtomToId(atom));
2545     return JS_GetPropertyById(cx, obj, id, vp);
2546 }
2547 
2548 JS_PUBLIC_API(bool)
JS_GetUCProperty(JSContext * cx,HandleObject obj,const char16_t * name,size_t namelen,MutableHandleValue vp)2549 JS_GetUCProperty(JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
2550                  MutableHandleValue vp)
2551 {
2552     JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
2553     if (!atom)
2554         return false;
2555     RootedId id(cx, AtomToId(atom));
2556     return JS_GetPropertyById(cx, obj, id, vp);
2557 }
2558 
2559 JS_PUBLIC_API(bool)
JS_GetElement(JSContext * cx,HandleObject objArg,uint32_t index,MutableHandleValue vp)2560 JS_GetElement(JSContext* cx, HandleObject objArg, uint32_t index, MutableHandleValue vp)
2561 {
2562     return JS_ForwardGetElementTo(cx, objArg, index, objArg, vp);
2563 }
2564 
2565 JS_PUBLIC_API(bool)
JS_ForwardSetPropertyTo(JSContext * cx,HandleObject obj,HandleId id,HandleValue v,HandleValue receiver,ObjectOpResult & result)2566 JS_ForwardSetPropertyTo(JSContext* cx, HandleObject obj, HandleId id, HandleValue v,
2567                         HandleValue receiver, ObjectOpResult& result)
2568 {
2569     AssertHeapIsIdle(cx);
2570     CHECK_REQUEST(cx);
2571     assertSameCompartment(cx, obj, id, receiver);
2572 
2573     return SetProperty(cx, obj, id, v, receiver, result);
2574 }
2575 
2576 JS_PUBLIC_API(bool)
JS_SetPropertyById(JSContext * cx,HandleObject obj,HandleId id,HandleValue v)2577 JS_SetPropertyById(JSContext* cx, HandleObject obj, HandleId id, HandleValue v)
2578 {
2579     AssertHeapIsIdle(cx);
2580     CHECK_REQUEST(cx);
2581     assertSameCompartment(cx, obj, id);
2582 
2583     RootedValue receiver(cx, ObjectValue(*obj));
2584     ObjectOpResult ignored;
2585     return SetProperty(cx, obj, id, v, receiver, ignored);
2586 }
2587 
2588 JS_PUBLIC_API(bool)
JS_SetProperty(JSContext * cx,HandleObject obj,const char * name,HandleValue v)2589 JS_SetProperty(JSContext* cx, HandleObject obj, const char* name, HandleValue v)
2590 {
2591     JSAtom* atom = Atomize(cx, name, strlen(name));
2592     if (!atom)
2593         return false;
2594     RootedId id(cx, AtomToId(atom));
2595     return JS_SetPropertyById(cx, obj, id, v);
2596 }
2597 
2598 JS_PUBLIC_API(bool)
JS_SetUCProperty(JSContext * cx,HandleObject obj,const char16_t * name,size_t namelen,HandleValue v)2599 JS_SetUCProperty(JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
2600                  HandleValue v)
2601 {
2602     JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
2603     if (!atom)
2604         return false;
2605     RootedId id(cx, AtomToId(atom));
2606     return JS_SetPropertyById(cx, obj, id, v);
2607 }
2608 
2609 static bool
SetElement(JSContext * cx,HandleObject obj,uint32_t index,HandleValue v)2610 SetElement(JSContext* cx, HandleObject obj, uint32_t index, HandleValue v)
2611 {
2612     AssertHeapIsIdle(cx);
2613     CHECK_REQUEST(cx);
2614     assertSameCompartment(cx, obj, v);
2615 
2616     RootedValue receiver(cx, ObjectValue(*obj));
2617     ObjectOpResult ignored;
2618     return SetElement(cx, obj, index, v, receiver, ignored);
2619 }
2620 
2621 JS_PUBLIC_API(bool)
JS_SetElement(JSContext * cx,HandleObject obj,uint32_t index,HandleValue v)2622 JS_SetElement(JSContext* cx, HandleObject obj, uint32_t index, HandleValue v)
2623 {
2624     return SetElement(cx, obj, index, v);
2625 }
2626 
2627 JS_PUBLIC_API(bool)
JS_SetElement(JSContext * cx,HandleObject obj,uint32_t index,HandleObject v)2628 JS_SetElement(JSContext* cx, HandleObject obj, uint32_t index, HandleObject v)
2629 {
2630     RootedValue value(cx, ObjectOrNullValue(v));
2631     return SetElement(cx, obj, index, value);
2632 }
2633 
2634 JS_PUBLIC_API(bool)
JS_SetElement(JSContext * cx,HandleObject obj,uint32_t index,HandleString v)2635 JS_SetElement(JSContext* cx, HandleObject obj, uint32_t index, HandleString v)
2636 {
2637     RootedValue value(cx, StringValue(v));
2638     return SetElement(cx, obj, index, value);
2639 }
2640 
2641 JS_PUBLIC_API(bool)
JS_SetElement(JSContext * cx,HandleObject obj,uint32_t index,int32_t v)2642 JS_SetElement(JSContext* cx, HandleObject obj, uint32_t index, int32_t v)
2643 {
2644     RootedValue value(cx, NumberValue(v));
2645     return SetElement(cx, obj, index, value);
2646 }
2647 
2648 JS_PUBLIC_API(bool)
JS_SetElement(JSContext * cx,HandleObject obj,uint32_t index,uint32_t v)2649 JS_SetElement(JSContext* cx, HandleObject obj, uint32_t index, uint32_t v)
2650 {
2651     RootedValue value(cx, NumberValue(v));
2652     return SetElement(cx, obj, index, value);
2653 }
2654 
2655 JS_PUBLIC_API(bool)
JS_SetElement(JSContext * cx,HandleObject obj,uint32_t index,double v)2656 JS_SetElement(JSContext* cx, HandleObject obj, uint32_t index, double v)
2657 {
2658     RootedValue value(cx, NumberValue(v));
2659     return SetElement(cx, obj, index, value);
2660 }
2661 
2662 JS_PUBLIC_API(bool)
JS_DeletePropertyById(JSContext * cx,HandleObject obj,HandleId id,ObjectOpResult & result)2663 JS_DeletePropertyById(JSContext* cx, HandleObject obj, HandleId id, ObjectOpResult& result)
2664 {
2665     AssertHeapIsIdle(cx);
2666     CHECK_REQUEST(cx);
2667     assertSameCompartment(cx, obj, id);
2668 
2669     return DeleteProperty(cx, obj, id, result);
2670 }
2671 
2672 JS_PUBLIC_API(bool)
JS_DeleteProperty(JSContext * cx,HandleObject obj,const char * name,ObjectOpResult & result)2673 JS_DeleteProperty(JSContext* cx, HandleObject obj, const char* name, ObjectOpResult& result)
2674 {
2675     CHECK_REQUEST(cx);
2676     assertSameCompartment(cx, obj);
2677 
2678     JSAtom* atom = Atomize(cx, name, strlen(name));
2679     if (!atom)
2680         return false;
2681     RootedId id(cx, AtomToId(atom));
2682     return DeleteProperty(cx, obj, id, result);
2683 }
2684 
2685 JS_PUBLIC_API(bool)
JS_DeleteUCProperty(JSContext * cx,HandleObject obj,const char16_t * name,size_t namelen,ObjectOpResult & result)2686 JS_DeleteUCProperty(JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
2687                     ObjectOpResult& result)
2688 {
2689     CHECK_REQUEST(cx);
2690     assertSameCompartment(cx, obj);
2691 
2692     JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
2693     if (!atom)
2694         return false;
2695     RootedId id(cx, AtomToId(atom));
2696     return DeleteProperty(cx, obj, id, result);
2697 }
2698 
2699 JS_PUBLIC_API(bool)
JS_DeleteElement(JSContext * cx,HandleObject obj,uint32_t index,ObjectOpResult & result)2700 JS_DeleteElement(JSContext* cx, HandleObject obj, uint32_t index, ObjectOpResult& result)
2701 {
2702     AssertHeapIsIdle(cx);
2703     CHECK_REQUEST(cx);
2704     assertSameCompartment(cx, obj);
2705 
2706     return DeleteElement(cx, obj, index, result);
2707 }
2708 
2709 JS_PUBLIC_API(bool)
JS_DeletePropertyById(JSContext * cx,HandleObject obj,HandleId id)2710 JS_DeletePropertyById(JSContext* cx, HandleObject obj, HandleId id)
2711 {
2712     ObjectOpResult ignored;
2713     return JS_DeletePropertyById(cx, obj, id, ignored);
2714 }
2715 
2716 JS_PUBLIC_API(bool)
JS_DeleteProperty(JSContext * cx,HandleObject obj,const char * name)2717 JS_DeleteProperty(JSContext* cx, HandleObject obj, const char* name)
2718 {
2719     ObjectOpResult ignored;
2720     return JS_DeleteProperty(cx, obj, name, ignored);
2721 }
2722 
2723 JS_PUBLIC_API(bool)
JS_DeleteElement(JSContext * cx,HandleObject obj,uint32_t index)2724 JS_DeleteElement(JSContext* cx, HandleObject obj, uint32_t index)
2725 {
2726     ObjectOpResult ignored;
2727     return JS_DeleteElement(cx, obj, index, ignored);
2728 }
2729 
2730 JS_PUBLIC_API(bool)
JS_Enumerate(JSContext * cx,HandleObject obj,JS::MutableHandle<IdVector> props)2731 JS_Enumerate(JSContext* cx, HandleObject obj, JS::MutableHandle<IdVector> props)
2732 {
2733     AssertHeapIsIdle(cx);
2734     CHECK_REQUEST(cx);
2735     assertSameCompartment(cx, obj);
2736     MOZ_ASSERT(props.empty());
2737 
2738     AutoIdVector ids(cx);
2739     if (!GetPropertyKeys(cx, obj, JSITER_OWNONLY, &ids))
2740         return false;
2741 
2742     return props.append(ids.begin(), ids.end());
2743 }
2744 
JS_PUBLIC_API(bool)2745 JS_PUBLIC_API(bool)
2746 JS::IsCallable(JSObject* obj)
2747 {
2748     return obj->isCallable();
2749 }
2750 
JS_PUBLIC_API(bool)2751 JS_PUBLIC_API(bool)
2752 JS::IsConstructor(JSObject* obj)
2753 {
2754     return obj->isConstructor();
2755 }
2756 
2757 struct AutoLastFrameCheck
2758 {
AutoLastFrameCheckAutoLastFrameCheck2759     explicit AutoLastFrameCheck(JSContext* cx
2760                                 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
2761       : cx(cx)
2762     {
2763         MOZ_ASSERT(cx);
2764         MOZ_GUARD_OBJECT_NOTIFIER_INIT;
2765     }
2766 
~AutoLastFrameCheckAutoLastFrameCheck2767     ~AutoLastFrameCheck() {
2768         if (cx->isExceptionPending() &&
2769             !JS_IsRunning(cx) &&
2770             (!cx->options().dontReportUncaught() && !cx->options().autoJSAPIOwnsErrorReporting())) {
2771             ReportUncaughtException(cx);
2772         }
2773     }
2774 
2775   private:
2776     JSContext* cx;
2777     MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
2778 };
2779 
2780 JS_PUBLIC_API(bool)
JS_CallFunctionValue(JSContext * cx,HandleObject obj,HandleValue fval,const HandleValueArray & args,MutableHandleValue rval)2781 JS_CallFunctionValue(JSContext* cx, HandleObject obj, HandleValue fval, const HandleValueArray& args,
2782                      MutableHandleValue rval)
2783 {
2784     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
2785     AssertHeapIsIdle(cx);
2786     CHECK_REQUEST(cx);
2787     assertSameCompartment(cx, obj, fval, args);
2788     AutoLastFrameCheck lfc(cx);
2789 
2790     return Invoke(cx, ObjectOrNullValue(obj), fval, args.length(), args.begin(), rval);
2791 }
2792 
2793 JS_PUBLIC_API(bool)
JS_CallFunction(JSContext * cx,HandleObject obj,HandleFunction fun,const HandleValueArray & args,MutableHandleValue rval)2794 JS_CallFunction(JSContext* cx, HandleObject obj, HandleFunction fun, const HandleValueArray& args,
2795                 MutableHandleValue rval)
2796 {
2797     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
2798     AssertHeapIsIdle(cx);
2799     CHECK_REQUEST(cx);
2800     assertSameCompartment(cx, obj, fun, args);
2801     AutoLastFrameCheck lfc(cx);
2802 
2803     return Invoke(cx, ObjectOrNullValue(obj), ObjectValue(*fun), args.length(), args.begin(), rval);
2804 }
2805 
2806 JS_PUBLIC_API(bool)
JS_CallFunctionName(JSContext * cx,HandleObject obj,const char * name,const HandleValueArray & args,MutableHandleValue rval)2807 JS_CallFunctionName(JSContext* cx, HandleObject obj, const char* name, const HandleValueArray& args,
2808                     MutableHandleValue rval)
2809 {
2810     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
2811     AssertHeapIsIdle(cx);
2812     CHECK_REQUEST(cx);
2813     assertSameCompartment(cx, obj, args);
2814     AutoLastFrameCheck lfc(cx);
2815 
2816     JSAtom* atom = Atomize(cx, name, strlen(name));
2817     if (!atom)
2818         return false;
2819 
2820     RootedValue v(cx);
2821     RootedId id(cx, AtomToId(atom));
2822     if (!GetProperty(cx, obj, obj, id, &v))
2823         return false;
2824 
2825     return Invoke(cx, ObjectOrNullValue(obj), v, args.length(), args.begin(), rval);
2826 }
2827 
JS_PUBLIC_API(bool)2828 JS_PUBLIC_API(bool)
2829 JS::Call(JSContext* cx, HandleValue thisv, HandleValue fval, const JS::HandleValueArray& args,
2830          MutableHandleValue rval)
2831 {
2832     AssertHeapIsIdle(cx);
2833     CHECK_REQUEST(cx);
2834     assertSameCompartment(cx, thisv, fval, args);
2835     AutoLastFrameCheck lfc(cx);
2836 
2837     return Invoke(cx, thisv, fval, args.length(), args.begin(), rval);
2838 }
2839 
JS_PUBLIC_API(bool)2840 JS_PUBLIC_API(bool)
2841 JS::Construct(JSContext* cx, HandleValue fval, HandleObject newTarget, const JS::HandleValueArray& args,
2842               MutableHandleValue rval)
2843 {
2844     AssertHeapIsIdle(cx);
2845     CHECK_REQUEST(cx);
2846     assertSameCompartment(cx, fval, newTarget, args);
2847     AutoLastFrameCheck lfc(cx);
2848 
2849     if (!IsConstructor(fval)) {
2850         ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_IGNORE_STACK, fval, nullptr);
2851         return false;
2852     }
2853 
2854     RootedValue newTargetVal(cx, ObjectValue(*newTarget));
2855     if (!IsConstructor(newTargetVal)) {
2856         ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_IGNORE_STACK, newTargetVal, nullptr);
2857         return false;
2858     }
2859 
2860     ConstructArgs cargs(cx);
2861     if (!FillArgumentsFromArraylike(cx, cargs, args))
2862         return false;
2863 
2864     return js::Construct(cx, fval, cargs, newTargetVal, rval);
2865 }
2866 
JS_PUBLIC_API(bool)2867 JS_PUBLIC_API(bool)
2868 JS::Construct(JSContext* cx, HandleValue fval, const JS::HandleValueArray& args,
2869               MutableHandleValue rval)
2870 {
2871     AssertHeapIsIdle(cx);
2872     CHECK_REQUEST(cx);
2873     assertSameCompartment(cx, fval, args);
2874     AutoLastFrameCheck lfc(cx);
2875 
2876     if (!IsConstructor(fval)) {
2877         ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_IGNORE_STACK, fval, nullptr);
2878         return false;
2879     }
2880 
2881     ConstructArgs cargs(cx);
2882     if (!FillArgumentsFromArraylike(cx, cargs, args))
2883         return false;
2884 
2885     return js::Construct(cx, fval, cargs, fval, rval);
2886 }
2887 
2888 
2889 /* * */
2890 
2891 JS_PUBLIC_API(bool)
JS_AlreadyHasOwnPropertyById(JSContext * cx,HandleObject obj,HandleId id,bool * foundp)2892 JS_AlreadyHasOwnPropertyById(JSContext* cx, HandleObject obj, HandleId id, bool* foundp)
2893 {
2894     AssertHeapIsIdle(cx);
2895     CHECK_REQUEST(cx);
2896     assertSameCompartment(cx, obj, id);
2897 
2898     if (!obj->isNative())
2899         return js::HasOwnProperty(cx, obj, id, foundp);
2900 
2901     RootedNativeObject nativeObj(cx, &obj->as<NativeObject>());
2902     RootedShape prop(cx);
2903     NativeLookupOwnPropertyNoResolve(cx, nativeObj, id, &prop);
2904     *foundp = !!prop;
2905     return true;
2906 }
2907 
2908 JS_PUBLIC_API(bool)
JS_AlreadyHasOwnProperty(JSContext * cx,HandleObject obj,const char * name,bool * foundp)2909 JS_AlreadyHasOwnProperty(JSContext* cx, HandleObject obj, const char* name, bool* foundp)
2910 {
2911     JSAtom* atom = Atomize(cx, name, strlen(name));
2912     if (!atom)
2913         return false;
2914     RootedId id(cx, AtomToId(atom));
2915     return JS_AlreadyHasOwnPropertyById(cx, obj, id, foundp);
2916 }
2917 
2918 JS_PUBLIC_API(bool)
JS_AlreadyHasOwnUCProperty(JSContext * cx,HandleObject obj,const char16_t * name,size_t namelen,bool * foundp)2919 JS_AlreadyHasOwnUCProperty(JSContext* cx, HandleObject obj, const char16_t* name, size_t namelen,
2920                            bool* foundp)
2921 {
2922     JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
2923     if (!atom)
2924         return false;
2925     RootedId id(cx, AtomToId(atom));
2926     return JS_AlreadyHasOwnPropertyById(cx, obj, id, foundp);
2927 }
2928 
2929 JS_PUBLIC_API(bool)
JS_AlreadyHasOwnElement(JSContext * cx,HandleObject obj,uint32_t index,bool * foundp)2930 JS_AlreadyHasOwnElement(JSContext* cx, HandleObject obj, uint32_t index, bool* foundp)
2931 {
2932     AssertHeapIsIdle(cx);
2933     CHECK_REQUEST(cx);
2934     RootedId id(cx);
2935     if (!IndexToId(cx, index, &id))
2936         return false;
2937     return JS_AlreadyHasOwnPropertyById(cx, obj, id, foundp);
2938 }
2939 
2940 JS_PUBLIC_API(bool)
JS_FreezeObject(JSContext * cx,HandleObject obj)2941 JS_FreezeObject(JSContext* cx, HandleObject obj)
2942 {
2943     AssertHeapIsIdle(cx);
2944     CHECK_REQUEST(cx);
2945     assertSameCompartment(cx, obj);
2946     return FreezeObject(cx, obj);
2947 }
2948 
2949 JS_PUBLIC_API(bool)
JS_DeepFreezeObject(JSContext * cx,HandleObject obj)2950 JS_DeepFreezeObject(JSContext* cx, HandleObject obj)
2951 {
2952     AssertHeapIsIdle(cx);
2953     CHECK_REQUEST(cx);
2954     assertSameCompartment(cx, obj);
2955 
2956     /* Assume that non-extensible objects are already deep-frozen, to avoid divergence. */
2957     bool extensible;
2958     if (!IsExtensible(cx, obj, &extensible))
2959         return false;
2960     if (!extensible)
2961         return true;
2962 
2963     if (!FreezeObject(cx, obj))
2964         return false;
2965 
2966     /* Walk slots in obj and if any value is a non-null object, seal it. */
2967     if (obj->isNative()) {
2968         for (uint32_t i = 0, n = obj->as<NativeObject>().slotSpan(); i < n; ++i) {
2969             const Value& v = obj->as<NativeObject>().getSlot(i);
2970             if (v.isPrimitive())
2971                 continue;
2972             RootedObject obj(cx, &v.toObject());
2973             if (!JS_DeepFreezeObject(cx, obj))
2974                 return false;
2975         }
2976     }
2977 
2978     return true;
2979 }
2980 
2981 static bool
DefineSelfHostedProperty(JSContext * cx,HandleObject obj,HandleId id,const char * getterName,const char * setterName,unsigned attrs,unsigned flags)2982 DefineSelfHostedProperty(JSContext* cx, HandleObject obj, HandleId id,
2983                          const char* getterName, const char* setterName,
2984                          unsigned attrs, unsigned flags)
2985 {
2986     JSAtom* getterNameAtom = Atomize(cx, getterName, strlen(getterName));
2987     if (!getterNameAtom)
2988         return false;
2989     RootedPropertyName getterNameName(cx, getterNameAtom->asPropertyName());
2990 
2991     RootedAtom name(cx, IdToFunctionName(cx, id));
2992     if (!name)
2993         return false;
2994 
2995     RootedValue getterValue(cx);
2996     if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), getterNameName, name, 0,
2997                                              &getterValue))
2998     {
2999         return false;
3000     }
3001     MOZ_ASSERT(getterValue.isObject() && getterValue.toObject().is<JSFunction>());
3002     RootedFunction getterFunc(cx, &getterValue.toObject().as<JSFunction>());
3003     JSNative getterOp = JS_DATA_TO_FUNC_PTR(JSNative, getterFunc.get());
3004 
3005     RootedFunction setterFunc(cx);
3006     if (setterName) {
3007         JSAtom* setterNameAtom = Atomize(cx, setterName, strlen(setterName));
3008         if (!setterNameAtom)
3009             return false;
3010         RootedPropertyName setterNameName(cx, setterNameAtom->asPropertyName());
3011 
3012         RootedValue setterValue(cx);
3013         if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), setterNameName, name, 0,
3014                                                  &setterValue))
3015         {
3016             return false;
3017         }
3018         MOZ_ASSERT(setterValue.isObject() && setterValue.toObject().is<JSFunction>());
3019         setterFunc = &getterValue.toObject().as<JSFunction>();
3020     }
3021     JSNative setterOp = JS_DATA_TO_FUNC_PTR(JSNative, setterFunc.get());
3022 
3023     return DefinePropertyById(cx, obj, id, JS::UndefinedHandleValue,
3024                               NativeOpWrapper(getterOp), NativeOpWrapper(setterOp),
3025                               attrs, flags);
3026 }
3027 
3028 JS_PUBLIC_API(JSObject*)
JS_DefineObject(JSContext * cx,HandleObject obj,const char * name,const JSClass * jsclasp,unsigned attrs)3029 JS_DefineObject(JSContext* cx, HandleObject obj, const char* name, const JSClass* jsclasp,
3030                 unsigned attrs)
3031 {
3032     AssertHeapIsIdle(cx);
3033     CHECK_REQUEST(cx);
3034     assertSameCompartment(cx, obj);
3035 
3036     const Class* clasp = Valueify(jsclasp);
3037     if (!clasp)
3038         clasp = &PlainObject::class_;    /* default class is Object */
3039 
3040     RootedObject nobj(cx, NewObjectWithClassProto(cx, clasp, nullptr));
3041     if (!nobj)
3042         return nullptr;
3043 
3044     RootedValue nobjValue(cx, ObjectValue(*nobj));
3045     if (!DefineProperty(cx, obj, name, nobjValue, NativeOpWrapper(nullptr), NativeOpWrapper(nullptr),
3046                         attrs, 0)) {
3047         return nullptr;
3048     }
3049 
3050     return nobj;
3051 }
3052 
3053 static inline Value
ValueFromScalar(double x)3054 ValueFromScalar(double x)
3055 {
3056     return DoubleValue(x);
3057 }
3058 static inline Value
ValueFromScalar(int32_t x)3059 ValueFromScalar(int32_t x)
3060 {
3061     return Int32Value(x);
3062 }
3063 
3064 template<typename T>
3065 static bool
DefineConstScalar(JSContext * cx,HandleObject obj,const JSConstScalarSpec<T> * cds)3066 DefineConstScalar(JSContext* cx, HandleObject obj, const JSConstScalarSpec<T>* cds)
3067 {
3068     AssertHeapIsIdle(cx);
3069     CHECK_REQUEST(cx);
3070     JSNativeWrapper noget = NativeOpWrapper(nullptr);
3071     JSNativeWrapper noset = NativeOpWrapper(nullptr);
3072     unsigned attrs = JSPROP_READONLY | JSPROP_PERMANENT;
3073     for (; cds->name; cds++) {
3074         RootedValue value(cx, ValueFromScalar(cds->val));
3075         if (!DefineProperty(cx, obj, cds->name, value, noget, noset, attrs, 0))
3076             return false;
3077     }
3078     return true;
3079 }
3080 
3081 JS_PUBLIC_API(bool)
JS_DefineConstDoubles(JSContext * cx,HandleObject obj,const JSConstDoubleSpec * cds)3082 JS_DefineConstDoubles(JSContext* cx, HandleObject obj, const JSConstDoubleSpec* cds)
3083 {
3084     return DefineConstScalar(cx, obj, cds);
3085 }
3086 JS_PUBLIC_API(bool)
JS_DefineConstIntegers(JSContext * cx,HandleObject obj,const JSConstIntegerSpec * cis)3087 JS_DefineConstIntegers(JSContext* cx, HandleObject obj, const JSConstIntegerSpec* cis)
3088 {
3089     return DefineConstScalar(cx, obj, cis);
3090 }
3091 
3092 static JS::SymbolCode
PropertySpecNameToSymbolCode(const char * name)3093 PropertySpecNameToSymbolCode(const char* name)
3094 {
3095     MOZ_ASSERT(JS::PropertySpecNameIsSymbol(name));
3096     uintptr_t u = reinterpret_cast<uintptr_t>(name);
3097     return JS::SymbolCode(u - 1);
3098 }
3099 
3100 static bool
PropertySpecNameToId(JSContext * cx,const char * name,MutableHandleId id,js::PinningBehavior pin=js::DoNotPinAtom)3101 PropertySpecNameToId(JSContext* cx, const char* name, MutableHandleId id,
3102                      js::PinningBehavior pin = js::DoNotPinAtom)
3103 {
3104     if (JS::PropertySpecNameIsSymbol(name)) {
3105         JS::SymbolCode which = PropertySpecNameToSymbolCode(name);
3106         id.set(SYMBOL_TO_JSID(cx->wellKnownSymbols().get(which)));
3107     } else {
3108         JSAtom* atom = Atomize(cx, name, strlen(name), pin);
3109         if (!atom)
3110             return false;
3111         id.set(AtomToId(atom));
3112     }
3113     return true;
3114 }
3115 
JS_PUBLIC_API(bool)3116 JS_PUBLIC_API(bool)
3117 JS::PropertySpecNameToPermanentId(JSContext* cx, const char* name, jsid* idp)
3118 {
3119     // We are calling fromMarkedLocation(idp) even though idp points to a
3120     // location that will never be marked. This is OK because the whole point
3121     // of this API is to populate *idp with a jsid that does not need to be
3122     // marked.
3123     return PropertySpecNameToId(cx, name, MutableHandleId::fromMarkedLocation(idp),
3124                                 js::PinAtom);
3125 }
3126 
3127 JS_PUBLIC_API(bool)
JS_DefineProperties(JSContext * cx,HandleObject obj,const JSPropertySpec * ps)3128 JS_DefineProperties(JSContext* cx, HandleObject obj, const JSPropertySpec* ps)
3129 {
3130     RootedId id(cx);
3131 
3132     for (; ps->name; ps++) {
3133         if (!PropertySpecNameToId(cx, ps->name, &id))
3134             return false;
3135 
3136         if (ps->isSelfHosted()) {
3137             if (!DefineSelfHostedProperty(cx, obj, id,
3138                                           ps->getter.selfHosted.funname,
3139                                           ps->setter.selfHosted.funname,
3140                                           ps->flags, 0))
3141             {
3142                 return false;
3143             }
3144         } else {
3145             if (!DefinePropertyById(cx, obj, id, JS::UndefinedHandleValue,
3146                                     ps->getter.native, ps->setter.native, ps->flags, 0))
3147             {
3148                 return false;
3149             }
3150         }
3151     }
3152     return true;
3153 }
3154 
JS_PUBLIC_API(bool)3155 JS_PUBLIC_API(bool)
3156 JS::ObjectToCompletePropertyDescriptor(JSContext* cx,
3157                                        HandleObject obj,
3158                                        HandleValue descObj,
3159                                        MutableHandle<JSPropertyDescriptor> desc)
3160 {
3161     if (!ToPropertyDescriptor(cx, descObj, true, desc))
3162         return false;
3163     CompletePropertyDescriptor(desc);
3164     desc.object().set(obj);
3165     return true;
3166 }
3167 
3168 JS_PUBLIC_API(void)
JS_SetAllNonReservedSlotsToUndefined(JSContext * cx,JSObject * objArg)3169 JS_SetAllNonReservedSlotsToUndefined(JSContext* cx, JSObject* objArg)
3170 {
3171     RootedObject obj(cx, objArg);
3172     AssertHeapIsIdle(cx);
3173     CHECK_REQUEST(cx);
3174     assertSameCompartment(cx, obj);
3175 
3176     if (!obj->isNative())
3177         return;
3178 
3179     const Class* clasp = obj->getClass();
3180     unsigned numReserved = JSCLASS_RESERVED_SLOTS(clasp);
3181     unsigned numSlots = obj->as<NativeObject>().slotSpan();
3182     for (unsigned i = numReserved; i < numSlots; i++)
3183         obj->as<NativeObject>().setSlot(i, UndefinedValue());
3184 }
3185 
3186 JS_PUBLIC_API(Value)
JS_GetReservedSlot(JSObject * obj,uint32_t index)3187 JS_GetReservedSlot(JSObject* obj, uint32_t index)
3188 {
3189     return obj->as<NativeObject>().getReservedSlot(index);
3190 }
3191 
3192 JS_PUBLIC_API(void)
JS_SetReservedSlot(JSObject * obj,uint32_t index,Value value)3193 JS_SetReservedSlot(JSObject* obj, uint32_t index, Value value)
3194 {
3195     obj->as<NativeObject>().setReservedSlot(index, value);
3196 }
3197 
3198 JS_PUBLIC_API(JSObject*)
JS_NewArrayObject(JSContext * cx,const JS::HandleValueArray & contents)3199 JS_NewArrayObject(JSContext* cx, const JS::HandleValueArray& contents)
3200 {
3201     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
3202     AssertHeapIsIdle(cx);
3203     CHECK_REQUEST(cx);
3204 
3205     assertSameCompartment(cx, contents);
3206     return NewDenseCopiedArray(cx, contents.length(), contents.begin());
3207 }
3208 
3209 JS_PUBLIC_API(JSObject*)
JS_NewArrayObject(JSContext * cx,size_t length)3210 JS_NewArrayObject(JSContext* cx, size_t length)
3211 {
3212     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
3213     AssertHeapIsIdle(cx);
3214     CHECK_REQUEST(cx);
3215 
3216     return NewDenseFullyAllocatedArray(cx, length);
3217 }
3218 
3219 JS_PUBLIC_API(bool)
JS_IsArrayObject(JSContext * cx,JS::HandleObject obj,bool * isArray)3220 JS_IsArrayObject(JSContext* cx, JS::HandleObject obj, bool* isArray)
3221 {
3222     assertSameCompartment(cx, obj);
3223 
3224     ESClassValue cls;
3225     if (!GetBuiltinClass(cx, obj, &cls))
3226         return false;
3227 
3228     *isArray = cls == ESClass_Array;
3229     return true;
3230 }
3231 
3232 JS_PUBLIC_API(bool)
JS_IsArrayObject(JSContext * cx,JS::HandleValue value,bool * isArray)3233 JS_IsArrayObject(JSContext* cx, JS::HandleValue value, bool* isArray)
3234 {
3235     if (!value.isObject()) {
3236         *isArray = false;
3237         return true;
3238     }
3239 
3240     RootedObject obj(cx, &value.toObject());
3241     return JS_IsArrayObject(cx, obj, isArray);
3242 }
3243 
3244 JS_PUBLIC_API(bool)
JS_GetArrayLength(JSContext * cx,HandleObject obj,uint32_t * lengthp)3245 JS_GetArrayLength(JSContext* cx, HandleObject obj, uint32_t* lengthp)
3246 {
3247     AssertHeapIsIdle(cx);
3248     CHECK_REQUEST(cx);
3249     assertSameCompartment(cx, obj);
3250     return GetLengthProperty(cx, obj, lengthp);
3251 }
3252 
3253 JS_PUBLIC_API(bool)
JS_SetArrayLength(JSContext * cx,HandleObject obj,uint32_t length)3254 JS_SetArrayLength(JSContext* cx, HandleObject obj, uint32_t length)
3255 {
3256     AssertHeapIsIdle(cx);
3257     CHECK_REQUEST(cx);
3258     assertSameCompartment(cx, obj);
3259     return SetLengthProperty(cx, obj, length);
3260 }
3261 
3262 JS_PUBLIC_API(void)
JS_HoldPrincipals(JSPrincipals * principals)3263 JS_HoldPrincipals(JSPrincipals* principals)
3264 {
3265     ++principals->refcount;
3266 }
3267 
3268 JS_PUBLIC_API(void)
JS_DropPrincipals(JSRuntime * rt,JSPrincipals * principals)3269 JS_DropPrincipals(JSRuntime* rt, JSPrincipals* principals)
3270 {
3271     int rc = --principals->refcount;
3272     if (rc == 0)
3273         rt->destroyPrincipals(principals);
3274 }
3275 
3276 JS_PUBLIC_API(void)
JS_SetSecurityCallbacks(JSRuntime * rt,const JSSecurityCallbacks * scb)3277 JS_SetSecurityCallbacks(JSRuntime* rt, const JSSecurityCallbacks* scb)
3278 {
3279     MOZ_ASSERT(scb != &NullSecurityCallbacks);
3280     rt->securityCallbacks = scb ? scb : &NullSecurityCallbacks;
3281 }
3282 
3283 JS_PUBLIC_API(const JSSecurityCallbacks*)
JS_GetSecurityCallbacks(JSRuntime * rt)3284 JS_GetSecurityCallbacks(JSRuntime* rt)
3285 {
3286     return (rt->securityCallbacks != &NullSecurityCallbacks) ? rt->securityCallbacks : nullptr;
3287 }
3288 
3289 JS_PUBLIC_API(void)
JS_SetTrustedPrincipals(JSRuntime * rt,JSPrincipals * prin)3290 JS_SetTrustedPrincipals(JSRuntime* rt, JSPrincipals* prin)
3291 {
3292     rt->setTrustedPrincipals(prin);
3293 }
3294 
3295 extern JS_PUBLIC_API(void)
JS_InitDestroyPrincipalsCallback(JSRuntime * rt,JSDestroyPrincipalsOp destroyPrincipals)3296 JS_InitDestroyPrincipalsCallback(JSRuntime* rt, JSDestroyPrincipalsOp destroyPrincipals)
3297 {
3298     MOZ_ASSERT(destroyPrincipals);
3299     MOZ_ASSERT(!rt->destroyPrincipals);
3300     rt->destroyPrincipals = destroyPrincipals;
3301 }
3302 
3303 extern JS_PUBLIC_API(void)
JS_InitReadPrincipalsCallback(JSRuntime * rt,JSReadPrincipalsOp read)3304 JS_InitReadPrincipalsCallback(JSRuntime* rt, JSReadPrincipalsOp read)
3305 {
3306     MOZ_ASSERT(read);
3307     MOZ_ASSERT(!rt->readPrincipals);
3308     rt->readPrincipals = read;
3309 }
3310 
3311 JS_PUBLIC_API(JSFunction*)
JS_NewFunction(JSContext * cx,JSNative native,unsigned nargs,unsigned flags,const char * name)3312 JS_NewFunction(JSContext* cx, JSNative native, unsigned nargs, unsigned flags,
3313                const char* name)
3314 {
3315     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
3316 
3317     AssertHeapIsIdle(cx);
3318     CHECK_REQUEST(cx);
3319 
3320     RootedAtom atom(cx);
3321     if (name) {
3322         atom = Atomize(cx, name, strlen(name));
3323         if (!atom)
3324             return nullptr;
3325     }
3326 
3327     return (flags & JSFUN_CONSTRUCTOR)
3328            ? NewNativeConstructor(cx, native, nargs, atom)
3329            : NewNativeFunction(cx, native, nargs, atom);
3330 }
3331 
JS_PUBLIC_API(JSFunction *)3332 JS_PUBLIC_API(JSFunction*)
3333 JS::GetSelfHostedFunction(JSContext* cx, const char* selfHostedName, HandleId id, unsigned nargs)
3334 {
3335     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
3336     AssertHeapIsIdle(cx);
3337     CHECK_REQUEST(cx);
3338 
3339     RootedAtom name(cx, IdToFunctionName(cx, id));
3340     if (!name)
3341         return nullptr;
3342 
3343     JSAtom* shAtom = Atomize(cx, selfHostedName, strlen(selfHostedName));
3344     if (!shAtom)
3345         return nullptr;
3346     RootedPropertyName shName(cx, shAtom->asPropertyName());
3347     RootedValue funVal(cx);
3348     if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), shName, name, nargs, &funVal))
3349         return nullptr;
3350     return &funVal.toObject().as<JSFunction>();
3351 }
3352 
JS_PUBLIC_API(JSFunction *)3353 JS_PUBLIC_API(JSFunction*)
3354 JS::NewFunctionFromSpec(JSContext* cx, const JSFunctionSpec* fs, HandleId id)
3355 {
3356     // Delay cloning self-hosted functions until they are called. This is
3357     // achieved by passing DefineFunction a nullptr JSNative which produces an
3358     // interpreted JSFunction where !hasScript. Interpreted call paths then
3359     // call InitializeLazyFunctionScript if !hasScript.
3360     if (fs->selfHostedName) {
3361         MOZ_ASSERT(!fs->call.op);
3362         MOZ_ASSERT(!fs->call.info);
3363 
3364         JSAtom* shAtom = Atomize(cx, fs->selfHostedName, strlen(fs->selfHostedName));
3365         if (!shAtom)
3366             return nullptr;
3367         RootedPropertyName shName(cx, shAtom->asPropertyName());
3368         RootedAtom name(cx, IdToFunctionName(cx, id));
3369         if (!name)
3370             return nullptr;
3371         RootedValue funVal(cx);
3372         if (!GlobalObject::getSelfHostedFunction(cx, cx->global(), shName, name, fs->nargs,
3373                                                  &funVal))
3374         {
3375             return nullptr;
3376         }
3377         return &funVal.toObject().as<JSFunction>();
3378     }
3379 
3380     RootedAtom atom(cx, IdToFunctionName(cx, id));
3381     if (!atom)
3382         return nullptr;
3383 
3384     JSFunction* fun;
3385     if (!fs->call.op)
3386         fun = NewScriptedFunction(cx, fs->nargs, JSFunction::INTERPRETED_LAZY, atom);
3387     else if (fs->flags & JSFUN_CONSTRUCTOR)
3388         fun = NewNativeConstructor(cx, fs->call.op, fs->nargs, atom);
3389     else
3390         fun = NewNativeFunction(cx, fs->call.op, fs->nargs, atom);
3391     if (!fun)
3392         return nullptr;
3393 
3394     if (fs->call.info)
3395         fun->setJitInfo(fs->call.info);
3396     return fun;
3397 }
3398 
3399 static bool
CreateNonSyntacticScopeChain(JSContext * cx,AutoObjectVector & scopeChain,MutableHandleObject dynamicScopeObj,MutableHandle<ScopeObject * > staticScopeObj)3400 CreateNonSyntacticScopeChain(JSContext* cx, AutoObjectVector& scopeChain,
3401                              MutableHandleObject dynamicScopeObj,
3402                              MutableHandle<ScopeObject*> staticScopeObj)
3403 {
3404     Rooted<ClonedBlockObject*> globalLexical(cx, &cx->global()->lexicalScope());
3405     if (!js::CreateScopeObjectsForScopeChain(cx, scopeChain, globalLexical, dynamicScopeObj))
3406         return false;
3407 
3408     staticScopeObj.set(&globalLexical->staticBlock());
3409     if (!scopeChain.empty()) {
3410         staticScopeObj.set(StaticNonSyntacticScopeObjects::create(cx, staticScopeObj));
3411         if (!staticScopeObj)
3412             return false;
3413 
3414         // The XPConnect subscript loader, which may pass in its own dynamic
3415         // scopes to load scripts in, expects the dynamic scope chain to be
3416         // the holder of "var" declarations. In SpiderMonkey, such objects are
3417         // called "qualified varobjs", the "qualified" part meaning the
3418         // declaration was qualified by "var". There is only sadness.
3419         //
3420         // See JSObject::isQualifiedVarObj.
3421         if (!dynamicScopeObj->setQualifiedVarObj(cx))
3422             return false;
3423 
3424         // Also get a non-syntactic lexical scope to capture 'let' and 'const'
3425         // bindings. To persist lexical bindings, we have a 1-1 mapping with
3426         // the final unwrapped dynamic scope object (the scope that stores the
3427         // 'var' bindings) and the lexical scope.
3428         //
3429         // TODOshu: disallow the subscript loader from using non-distinguished
3430         // objects as dynamic scopes.
3431         dynamicScopeObj.set(
3432             cx->compartment()->getOrCreateNonSyntacticLexicalScope(cx, staticScopeObj,
3433                                                                    dynamicScopeObj));
3434         if (!dynamicScopeObj)
3435             return false;
3436     }
3437 
3438     return true;
3439 }
3440 
3441 static bool
IsFunctionCloneable(HandleFunction fun)3442 IsFunctionCloneable(HandleFunction fun)
3443 {
3444     if (!fun->isInterpreted())
3445         return true;
3446 
3447     // If a function was compiled to be lexically nested inside some other
3448     // script, we cannot clone it without breaking the compiler's assumptions.
3449     if (JSObject* scope = fun->nonLazyScript()->enclosingStaticScope()) {
3450         // If the script is directly under the global scope, we can clone it.
3451         if (IsStaticGlobalLexicalScope(scope))
3452             return true;
3453 
3454         // If the script already deals with non-syntactic scopes, we can clone
3455         // it.
3456         if (scope->is<StaticNonSyntacticScopeObjects>())
3457             return true;
3458 
3459         // 'eval' scopes are always scoped immediately under a non-extensible
3460         // lexical scope.
3461         if (scope->is<StaticBlockObject>()) {
3462             StaticBlockObject& block = scope->as<StaticBlockObject>();
3463             if (block.needsClone())
3464                 return false;
3465 
3466             JSObject* enclosing = block.enclosingStaticScope();
3467 
3468             // If the script is an indirect eval that is immediately scoped
3469             // under the global, we can clone it.
3470             if (enclosing->is<StaticEvalObject>())
3471                 return !enclosing->as<StaticEvalObject>().isNonGlobal();
3472         }
3473 
3474         // Any other enclosing static scope (e.g., function, block) cannot be
3475         // cloned.
3476         return false;
3477     }
3478 
3479     return true;
3480 }
3481 
3482 static JSObject*
CloneFunctionObject(JSContext * cx,HandleObject funobj,HandleObject dynamicScope,Handle<ScopeObject * > staticScope)3483 CloneFunctionObject(JSContext* cx, HandleObject funobj, HandleObject dynamicScope,
3484                     Handle<ScopeObject*> staticScope)
3485 {
3486     AssertHeapIsIdle(cx);
3487     CHECK_REQUEST(cx);
3488     assertSameCompartment(cx, dynamicScope);
3489     MOZ_ASSERT(dynamicScope);
3490     // Note that funobj can be in a different compartment.
3491 
3492     if (!funobj->is<JSFunction>()) {
3493         AutoCompartment ac(cx, funobj);
3494         RootedValue v(cx, ObjectValue(*funobj));
3495         ReportIsNotFunction(cx, v);
3496         return nullptr;
3497     }
3498 
3499     RootedFunction fun(cx, &funobj->as<JSFunction>());
3500     if (fun->isInterpretedLazy()) {
3501         AutoCompartment ac(cx, funobj);
3502         if (!fun->getOrCreateScript(cx))
3503             return nullptr;
3504     }
3505 
3506     if (!IsFunctionCloneable(fun)) {
3507         JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_BAD_CLONE_FUNOBJ_SCOPE);
3508         return nullptr;
3509     }
3510 
3511     if (fun->isBoundFunction()) {
3512         JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_CANT_CLONE_OBJECT);
3513         return nullptr;
3514     }
3515 
3516     if (fun->isNative() && IsAsmJSModuleNative(fun->native())) {
3517         JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_CANT_CLONE_OBJECT);
3518         return nullptr;
3519     }
3520 
3521     if (CanReuseScriptForClone(cx->compartment(), fun, dynamicScope)) {
3522         // If the script is to be reused, either the script can already handle
3523         // non-syntactic scopes, or there is only the standard global lexical
3524         // scope.
3525 #ifdef DEBUG
3526         // Fail here if we OOM during debug asserting.
3527         // CloneFunctionReuseScript will delazify the script anyways, so we
3528         // are not creating an extra failure condition for DEBUG builds.
3529         if (!fun->getOrCreateScript(cx))
3530             return nullptr;
3531         MOZ_ASSERT(IsStaticGlobalLexicalScope(staticScope) ||
3532                    fun->nonLazyScript()->hasNonSyntacticScope());
3533 #endif
3534         return CloneFunctionReuseScript(cx, fun, dynamicScope, fun->getAllocKind());
3535     }
3536 
3537     JSFunction* clone = CloneFunctionAndScript(cx, fun, dynamicScope, staticScope,
3538                                                fun->getAllocKind());
3539 
3540 #ifdef DEBUG
3541     // The cloned function should itself be cloneable.
3542     RootedFunction cloneRoot(cx, clone);
3543     MOZ_ASSERT_IF(cloneRoot, IsFunctionCloneable(cloneRoot));
3544 #endif
3545 
3546     return clone;
3547 }
3548 
3549 namespace JS {
3550 
3551 JS_PUBLIC_API(JSObject*)
CloneFunctionObject(JSContext * cx,JS::Handle<JSObject * > funobj)3552 CloneFunctionObject(JSContext* cx, JS::Handle<JSObject*> funobj)
3553 {
3554     Rooted<ClonedBlockObject*> globalLexical(cx, &cx->global()->lexicalScope());
3555     Rooted<ScopeObject*> staticLexical(cx, &globalLexical->staticBlock());
3556     return CloneFunctionObject(cx, funobj, globalLexical, staticLexical);
3557 }
3558 
3559 extern JS_PUBLIC_API(JSObject*)
CloneFunctionObject(JSContext * cx,HandleObject funobj,AutoObjectVector & scopeChain)3560 CloneFunctionObject(JSContext* cx, HandleObject funobj, AutoObjectVector& scopeChain)
3561 {
3562     RootedObject dynamicScope(cx);
3563     Rooted<ScopeObject*> staticScope(cx);
3564     if (!CreateNonSyntacticScopeChain(cx, scopeChain, &dynamicScope, &staticScope))
3565         return nullptr;
3566 
3567     return CloneFunctionObject(cx, funobj, dynamicScope, staticScope);
3568 }
3569 
3570 } // namespace JS
3571 
3572 JS_PUBLIC_API(JSObject*)
JS_GetFunctionObject(JSFunction * fun)3573 JS_GetFunctionObject(JSFunction* fun)
3574 {
3575     return fun;
3576 }
3577 
3578 JS_PUBLIC_API(JSString*)
JS_GetFunctionId(JSFunction * fun)3579 JS_GetFunctionId(JSFunction* fun)
3580 {
3581     return fun->atom();
3582 }
3583 
3584 JS_PUBLIC_API(JSString*)
JS_GetFunctionDisplayId(JSFunction * fun)3585 JS_GetFunctionDisplayId(JSFunction* fun)
3586 {
3587     return fun->displayAtom();
3588 }
3589 
3590 JS_PUBLIC_API(uint16_t)
JS_GetFunctionArity(JSFunction * fun)3591 JS_GetFunctionArity(JSFunction* fun)
3592 {
3593     return fun->nargs();
3594 }
3595 
3596 JS_PUBLIC_API(bool)
JS_ObjectIsFunction(JSContext * cx,JSObject * obj)3597 JS_ObjectIsFunction(JSContext* cx, JSObject* obj)
3598 {
3599     return obj->is<JSFunction>();
3600 }
3601 
3602 JS_PUBLIC_API(bool)
JS_IsNativeFunction(JSObject * funobj,JSNative call)3603 JS_IsNativeFunction(JSObject* funobj, JSNative call)
3604 {
3605     if (!funobj->is<JSFunction>())
3606         return false;
3607     JSFunction* fun = &funobj->as<JSFunction>();
3608     return fun->isNative() && fun->native() == call;
3609 }
3610 
3611 extern JS_PUBLIC_API(bool)
JS_IsConstructor(JSFunction * fun)3612 JS_IsConstructor(JSFunction* fun)
3613 {
3614     return fun->isConstructor();
3615 }
3616 
3617 static bool
GenericNativeMethodDispatcher(JSContext * cx,unsigned argc,Value * vp)3618 GenericNativeMethodDispatcher(JSContext* cx, unsigned argc, Value* vp)
3619 {
3620     CallArgs args = CallArgsFromVp(argc, vp);
3621 
3622     const JSFunctionSpec* fs = (JSFunctionSpec*)
3623         args.callee().as<JSFunction>().getExtendedSlot(0).toPrivate();
3624     MOZ_ASSERT((fs->flags & JSFUN_GENERIC_NATIVE) != 0);
3625 
3626     if (argc < 1) {
3627         ReportMissingArg(cx, args.calleev(), 0);
3628         return false;
3629     }
3630 
3631     /*
3632      * Copy all actual (argc) arguments down over our |this| parameter, vp[1],
3633      * which is almost always the class constructor object, e.g. Array.  Then
3634      * call the corresponding prototype native method with our first argument
3635      * passed as |this|.
3636      */
3637     memmove(vp + 1, vp + 2, argc * sizeof(Value));
3638 
3639     /* Clear the last parameter in case too few arguments were passed. */
3640     vp[2 + --argc].setUndefined();
3641 
3642     return fs->call.op(cx, argc, vp);
3643 }
3644 
3645 static bool
DefineFunctionFromSpec(JSContext * cx,HandleObject obj,const JSFunctionSpec * fs,unsigned flags)3646 DefineFunctionFromSpec(JSContext* cx, HandleObject obj, const JSFunctionSpec* fs, unsigned flags)
3647 {
3648     GetterOp gop;
3649     SetterOp sop;
3650     if (flags & JSFUN_STUB_GSOPS) {
3651         // JSFUN_STUB_GSOPS is a request flag only, not stored in fun->flags or
3652         // the defined property's attributes.
3653         flags &= ~JSFUN_STUB_GSOPS;
3654         gop = nullptr;
3655         sop = nullptr;
3656     } else {
3657         gop = obj->getClass()->getProperty;
3658         sop = obj->getClass()->setProperty;
3659         MOZ_ASSERT(gop != JS_PropertyStub);
3660         MOZ_ASSERT(sop != JS_StrictPropertyStub);
3661     }
3662 
3663     RootedId id(cx);
3664     if (!PropertySpecNameToId(cx, fs->name, &id))
3665         return false;
3666 
3667     // Define a generic arity N+1 static method for the arity N prototype
3668     // method if flags contains JSFUN_GENERIC_NATIVE.
3669     if (flags & JSFUN_GENERIC_NATIVE) {
3670         // We require that any consumers using JSFUN_GENERIC_NATIVE stash
3671         // the prototype and constructor in the global slots before invoking
3672         // JS_DefineFunctions on the proto.
3673         JSProtoKey key = JSCLASS_CACHED_PROTO_KEY(obj->getClass());
3674         MOZ_ASSERT(obj == &obj->global().getPrototype(key).toObject());
3675         RootedObject ctor(cx, &obj->global().getConstructor(key).toObject());
3676 
3677         flags &= ~JSFUN_GENERIC_NATIVE;
3678         JSFunction* fun = DefineFunction(cx, ctor, id,
3679                                          GenericNativeMethodDispatcher,
3680                                          fs->nargs + 1, flags,
3681                                          gc::AllocKind::FUNCTION_EXTENDED);
3682         if (!fun)
3683             return false;
3684 
3685         // As jsapi.h notes, fs must point to storage that lives as long
3686         // as fun->object lives.
3687         fun->setExtendedSlot(0, PrivateValue(const_cast<JSFunctionSpec*>(fs)));
3688     }
3689 
3690     JSFunction* fun = NewFunctionFromSpec(cx, fs, id);
3691     if (!fun)
3692         return false;
3693 
3694     RootedValue funVal(cx, ObjectValue(*fun));
3695     return DefineProperty(cx, obj, id, funVal, gop, sop, flags & ~JSFUN_FLAGS_MASK);
3696 }
3697 
3698 JS_PUBLIC_API(bool)
JS_DefineFunctions(JSContext * cx,HandleObject obj,const JSFunctionSpec * fs,PropertyDefinitionBehavior behavior)3699 JS_DefineFunctions(JSContext* cx, HandleObject obj, const JSFunctionSpec* fs,
3700                    PropertyDefinitionBehavior behavior)
3701 {
3702     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
3703     AssertHeapIsIdle(cx);
3704     CHECK_REQUEST(cx);
3705     assertSameCompartment(cx, obj);
3706 
3707     for (; fs->name; fs++) {
3708         unsigned flags = fs->flags;
3709         switch (behavior) {
3710           case DefineAllProperties:
3711             break;
3712           case OnlyDefineLateProperties:
3713             if (!(flags & JSPROP_DEFINE_LATE))
3714                 continue;
3715             break;
3716           default:
3717             MOZ_ASSERT(behavior == DontDefineLateProperties);
3718             if (flags & JSPROP_DEFINE_LATE)
3719                 continue;
3720         }
3721 
3722         if (!DefineFunctionFromSpec(cx, obj, fs, flags & ~JSPROP_DEFINE_LATE))
3723             return false;
3724     }
3725     return true;
3726 }
3727 
3728 JS_PUBLIC_API(JSFunction*)
JS_DefineFunction(JSContext * cx,HandleObject obj,const char * name,JSNative call,unsigned nargs,unsigned attrs)3729 JS_DefineFunction(JSContext* cx, HandleObject obj, const char* name, JSNative call,
3730                   unsigned nargs, unsigned attrs)
3731 {
3732     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
3733     AssertHeapIsIdle(cx);
3734     CHECK_REQUEST(cx);
3735     assertSameCompartment(cx, obj);
3736     JSAtom* atom = Atomize(cx, name, strlen(name));
3737     if (!atom)
3738         return nullptr;
3739     Rooted<jsid> id(cx, AtomToId(atom));
3740     return DefineFunction(cx, obj, id, call, nargs, attrs);
3741 }
3742 
3743 JS_PUBLIC_API(JSFunction*)
JS_DefineUCFunction(JSContext * cx,HandleObject obj,const char16_t * name,size_t namelen,JSNative call,unsigned nargs,unsigned attrs)3744 JS_DefineUCFunction(JSContext* cx, HandleObject obj,
3745                     const char16_t* name, size_t namelen, JSNative call,
3746                     unsigned nargs, unsigned attrs)
3747 {
3748     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
3749     AssertHeapIsIdle(cx);
3750     CHECK_REQUEST(cx);
3751     assertSameCompartment(cx, obj);
3752     JSAtom* atom = AtomizeChars(cx, name, AUTO_NAMELEN(name, namelen));
3753     if (!atom)
3754         return nullptr;
3755     Rooted<jsid> id(cx, AtomToId(atom));
3756     return DefineFunction(cx, obj, id, call, nargs, attrs);
3757 }
3758 
3759 extern JS_PUBLIC_API(JSFunction*)
JS_DefineFunctionById(JSContext * cx,HandleObject obj,HandleId id,JSNative call,unsigned nargs,unsigned attrs)3760 JS_DefineFunctionById(JSContext* cx, HandleObject obj, HandleId id, JSNative call,
3761                       unsigned nargs, unsigned attrs)
3762 {
3763     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
3764     AssertHeapIsIdle(cx);
3765     CHECK_REQUEST(cx);
3766     assertSameCompartment(cx, obj);
3767     return DefineFunction(cx, obj, id, call, nargs, attrs);
3768 }
3769 
3770 /* Use the fastest available getc. */
3771 #if defined(HAVE_GETC_UNLOCKED)
3772 # define fast_getc getc_unlocked
3773 #elif defined(HAVE__GETC_NOLOCK)
3774 # define fast_getc _getc_nolock
3775 #else
3776 # define fast_getc getc
3777 #endif
3778 
3779 typedef Vector<char, 8, TempAllocPolicy> FileContents;
3780 
3781 static bool
ReadCompleteFile(JSContext * cx,FILE * fp,FileContents & buffer)3782 ReadCompleteFile(JSContext* cx, FILE* fp, FileContents& buffer)
3783 {
3784     /* Get the complete length of the file, if possible. */
3785     struct stat st;
3786     int ok = fstat(fileno(fp), &st);
3787     if (ok != 0)
3788         return false;
3789     if (st.st_size > 0) {
3790         if (!buffer.reserve(st.st_size))
3791             return false;
3792     }
3793 
3794     // Read in the whole file. Note that we can't assume the data's length
3795     // is actually st.st_size, because 1) some files lie about their size
3796     // (/dev/zero and /dev/random), and 2) reading files in text mode on
3797     // Windows collapses "\r\n" pairs to single \n characters.
3798     for (;;) {
3799         int c = fast_getc(fp);
3800         if (c == EOF)
3801             break;
3802         if (!buffer.append(c))
3803             return false;
3804     }
3805 
3806     return true;
3807 }
3808 
3809 namespace {
3810 
3811 class AutoFile
3812 {
3813     FILE* fp_;
3814   public:
AutoFile()3815     AutoFile()
3816       : fp_(nullptr)
3817     {}
~AutoFile()3818     ~AutoFile()
3819     {
3820         if (fp_ && fp_ != stdin)
3821             fclose(fp_);
3822     }
fp() const3823     FILE* fp() const { return fp_; }
3824     bool open(JSContext* cx, const char* filename);
readAll(JSContext * cx,FileContents & buffer)3825     bool readAll(JSContext* cx, FileContents& buffer)
3826     {
3827         MOZ_ASSERT(fp_);
3828         return ReadCompleteFile(cx, fp_, buffer);
3829     }
3830 };
3831 
3832 } /* anonymous namespace */
3833 
3834 /*
3835  * Open a source file for reading. Supports "-" and nullptr to mean stdin. The
3836  * return value must be fclosed unless it is stdin.
3837  */
3838 bool
open(JSContext * cx,const char * filename)3839 AutoFile::open(JSContext* cx, const char* filename)
3840 {
3841     if (!filename || strcmp(filename, "-") == 0) {
3842         fp_ = stdin;
3843     } else {
3844         fp_ = fopen(filename, "r");
3845         if (!fp_) {
3846             JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_CANT_OPEN,
3847                                  filename, "No such file or directory");
3848             return false;
3849         }
3850     }
3851     return true;
3852 }
3853 
3854 void
copyPODTransitiveOptions(const TransitiveCompileOptions & rhs)3855 JS::TransitiveCompileOptions::copyPODTransitiveOptions(const TransitiveCompileOptions& rhs)
3856 {
3857     mutedErrors_ = rhs.mutedErrors_;
3858     version = rhs.version;
3859     versionSet = rhs.versionSet;
3860     utf8 = rhs.utf8;
3861     selfHostingMode = rhs.selfHostingMode;
3862     canLazilyParse = rhs.canLazilyParse;
3863     strictOption = rhs.strictOption;
3864     extraWarningsOption = rhs.extraWarningsOption;
3865     werrorOption = rhs.werrorOption;
3866     asmJSOption = rhs.asmJSOption;
3867     throwOnAsmJSValidationFailureOption = rhs.throwOnAsmJSValidationFailureOption;
3868     forceAsync = rhs.forceAsync;
3869     installedFile = rhs.installedFile;
3870     sourceIsLazy = rhs.sourceIsLazy;
3871     introductionType = rhs.introductionType;
3872     introductionLineno = rhs.introductionLineno;
3873     introductionOffset = rhs.introductionOffset;
3874     hasIntroductionInfo = rhs.hasIntroductionInfo;
3875 };
3876 
3877 void
copyPODOptions(const ReadOnlyCompileOptions & rhs)3878 JS::ReadOnlyCompileOptions::copyPODOptions(const ReadOnlyCompileOptions& rhs)
3879 {
3880     copyPODTransitiveOptions(rhs);
3881     lineno = rhs.lineno;
3882     column = rhs.column;
3883     isRunOnce = rhs.isRunOnce;
3884     forEval = rhs.forEval;
3885     noScriptRval = rhs.noScriptRval;
3886 }
3887 
OwningCompileOptions(JSContext * cx)3888 JS::OwningCompileOptions::OwningCompileOptions(JSContext* cx)
3889     : ReadOnlyCompileOptions(),
3890       runtime(GetRuntime(cx)),
3891       elementRoot(cx),
3892       elementAttributeNameRoot(cx),
3893       introductionScriptRoot(cx)
3894 {
3895 }
3896 
~OwningCompileOptions()3897 JS::OwningCompileOptions::~OwningCompileOptions()
3898 {
3899     // OwningCompileOptions always owns these, so these casts are okay.
3900     js_free(const_cast<char*>(filename_));
3901     js_free(const_cast<char16_t*>(sourceMapURL_));
3902     js_free(const_cast<char*>(introducerFilename_));
3903 }
3904 
3905 bool
copy(JSContext * cx,const ReadOnlyCompileOptions & rhs)3906 JS::OwningCompileOptions::copy(JSContext* cx, const ReadOnlyCompileOptions& rhs)
3907 {
3908     copyPODOptions(rhs);
3909 
3910     setElement(rhs.element());
3911     setElementAttributeName(rhs.elementAttributeName());
3912     setIntroductionScript(rhs.introductionScript());
3913 
3914     return setFileAndLine(cx, rhs.filename(), rhs.lineno) &&
3915            setSourceMapURL(cx, rhs.sourceMapURL()) &&
3916            setIntroducerFilename(cx, rhs.introducerFilename());
3917 }
3918 
3919 bool
setFile(JSContext * cx,const char * f)3920 JS::OwningCompileOptions::setFile(JSContext* cx, const char* f)
3921 {
3922     char* copy = nullptr;
3923     if (f) {
3924         copy = JS_strdup(cx, f);
3925         if (!copy)
3926             return false;
3927     }
3928 
3929     // OwningCompileOptions always owns filename_, so this cast is okay.
3930     js_free(const_cast<char*>(filename_));
3931 
3932     filename_ = copy;
3933     return true;
3934 }
3935 
3936 bool
setFileAndLine(JSContext * cx,const char * f,unsigned l)3937 JS::OwningCompileOptions::setFileAndLine(JSContext* cx, const char* f, unsigned l)
3938 {
3939     if (!setFile(cx, f))
3940         return false;
3941 
3942     lineno = l;
3943     return true;
3944 }
3945 
3946 bool
setSourceMapURL(JSContext * cx,const char16_t * s)3947 JS::OwningCompileOptions::setSourceMapURL(JSContext* cx, const char16_t* s)
3948 {
3949     UniquePtr<char16_t[], JS::FreePolicy> copy;
3950     if (s) {
3951         copy = DuplicateString(cx, s);
3952         if (!copy)
3953             return false;
3954     }
3955 
3956     // OwningCompileOptions always owns sourceMapURL_, so this cast is okay.
3957     js_free(const_cast<char16_t*>(sourceMapURL_));
3958 
3959     sourceMapURL_ = copy.release();
3960     return true;
3961 }
3962 
3963 bool
setIntroducerFilename(JSContext * cx,const char * s)3964 JS::OwningCompileOptions::setIntroducerFilename(JSContext* cx, const char* s)
3965 {
3966     char* copy = nullptr;
3967     if (s) {
3968         copy = JS_strdup(cx, s);
3969         if (!copy)
3970             return false;
3971     }
3972 
3973     // OwningCompileOptions always owns introducerFilename_, so this cast is okay.
3974     js_free(const_cast<char*>(introducerFilename_));
3975 
3976     introducerFilename_ = copy;
3977     return true;
3978 }
3979 
CompileOptions(JSContext * cx,JSVersion version)3980 JS::CompileOptions::CompileOptions(JSContext* cx, JSVersion version)
3981     : ReadOnlyCompileOptions(), elementRoot(cx), elementAttributeNameRoot(cx),
3982       introductionScriptRoot(cx)
3983 {
3984     this->version = (version != JSVERSION_UNKNOWN) ? version : cx->findVersion();
3985 
3986     strictOption = cx->runtime()->options().strictMode();
3987     extraWarningsOption = cx->compartment()->options().extraWarnings(cx);
3988     werrorOption = cx->runtime()->options().werror();
3989     if (!cx->runtime()->options().asmJS())
3990         asmJSOption = AsmJSOption::Disabled;
3991     else if (cx->compartment()->debuggerObservesAsmJS())
3992         asmJSOption = AsmJSOption::DisabledByDebugger;
3993     else
3994         asmJSOption = AsmJSOption::Enabled;
3995     throwOnAsmJSValidationFailureOption = cx->runtime()->options().throwOnAsmJSValidationFailure();
3996 }
3997 
3998 enum SyntacticScopeOption { HasSyntacticScope, HasNonSyntacticScope };
3999 
4000 static bool
Compile(JSContext * cx,const ReadOnlyCompileOptions & options,SyntacticScopeOption scopeOption,SourceBufferHolder & srcBuf,MutableHandleScript script)4001 Compile(JSContext* cx, const ReadOnlyCompileOptions& options, SyntacticScopeOption scopeOption,
4002         SourceBufferHolder& srcBuf, MutableHandleScript script)
4003 {
4004     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
4005     AssertHeapIsIdle(cx);
4006     CHECK_REQUEST(cx);
4007     AutoLastFrameCheck lfc(cx);
4008 
4009     Rooted<ScopeObject*> staticScope(cx, &cx->global()->lexicalScope().staticBlock());
4010     if (scopeOption == HasNonSyntacticScope) {
4011         staticScope = StaticNonSyntacticScopeObjects::create(cx, staticScope);
4012         if (!staticScope)
4013             return false;
4014     }
4015 
4016     RootedObject globalLexical(cx, &cx->global()->lexicalScope());
4017     script.set(frontend::CompileScript(cx, &cx->tempLifoAlloc(), globalLexical,
4018                                        staticScope, nullptr, options, srcBuf));
4019     return !!script;
4020 }
4021 
4022 static bool
Compile(JSContext * cx,const ReadOnlyCompileOptions & options,SyntacticScopeOption scopeOption,const char16_t * chars,size_t length,MutableHandleScript script)4023 Compile(JSContext* cx, const ReadOnlyCompileOptions& options, SyntacticScopeOption scopeOption,
4024         const char16_t* chars, size_t length, MutableHandleScript script)
4025 {
4026     SourceBufferHolder srcBuf(chars, length, SourceBufferHolder::NoOwnership);
4027     return ::Compile(cx, options, scopeOption, srcBuf, script);
4028 }
4029 
4030 static bool
Compile(JSContext * cx,const ReadOnlyCompileOptions & options,SyntacticScopeOption scopeOption,const char * bytes,size_t length,MutableHandleScript script)4031 Compile(JSContext* cx, const ReadOnlyCompileOptions& options, SyntacticScopeOption scopeOption,
4032         const char* bytes, size_t length, MutableHandleScript script)
4033 {
4034     mozilla::UniquePtr<char16_t, JS::FreePolicy> chars;
4035     if (options.utf8)
4036         chars.reset(UTF8CharsToNewTwoByteCharsZ(cx, UTF8Chars(bytes, length), &length).get());
4037     else
4038         chars.reset(InflateString(cx, bytes, &length));
4039     if (!chars)
4040         return false;
4041 
4042     return ::Compile(cx, options, scopeOption, chars.get(), length, script);
4043 }
4044 
4045 static bool
Compile(JSContext * cx,const ReadOnlyCompileOptions & options,SyntacticScopeOption scopeOption,FILE * fp,MutableHandleScript script)4046 Compile(JSContext* cx, const ReadOnlyCompileOptions& options, SyntacticScopeOption scopeOption,
4047         FILE* fp, MutableHandleScript script)
4048 {
4049     FileContents buffer(cx);
4050     if (!ReadCompleteFile(cx, fp, buffer))
4051         return false;
4052 
4053     return ::Compile(cx, options, scopeOption, buffer.begin(), buffer.length(), script);
4054 }
4055 
4056 static bool
Compile(JSContext * cx,const ReadOnlyCompileOptions & optionsArg,SyntacticScopeOption scopeOption,const char * filename,MutableHandleScript script)4057 Compile(JSContext* cx, const ReadOnlyCompileOptions& optionsArg, SyntacticScopeOption scopeOption,
4058         const char* filename, MutableHandleScript script)
4059 {
4060     AutoFile file;
4061     if (!file.open(cx, filename))
4062         return false;
4063     CompileOptions options(cx, optionsArg);
4064     options.setFileAndLine(filename, 1);
4065     return ::Compile(cx, options, scopeOption, file.fp(), script);
4066 }
4067 
4068 bool
Compile(JSContext * cx,const ReadOnlyCompileOptions & options,SourceBufferHolder & srcBuf,JS::MutableHandleScript script)4069 JS::Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
4070             SourceBufferHolder& srcBuf, JS::MutableHandleScript script)
4071 {
4072     return ::Compile(cx, options, HasSyntacticScope, srcBuf, script);
4073 }
4074 
4075 bool
Compile(JSContext * cx,const ReadOnlyCompileOptions & options,const char * bytes,size_t length,JS::MutableHandleScript script)4076 JS::Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
4077             const char* bytes, size_t length, JS::MutableHandleScript script)
4078 {
4079     return ::Compile(cx, options, HasSyntacticScope, bytes, length, script);
4080 }
4081 
4082 bool
Compile(JSContext * cx,const ReadOnlyCompileOptions & options,const char16_t * chars,size_t length,JS::MutableHandleScript script)4083 JS::Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
4084             const char16_t* chars, size_t length, JS::MutableHandleScript script)
4085 {
4086     return ::Compile(cx, options, HasSyntacticScope, chars, length, script);
4087 }
4088 
4089 bool
Compile(JSContext * cx,const ReadOnlyCompileOptions & options,FILE * file,JS::MutableHandleScript script)4090 JS::Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
4091             FILE* file, JS::MutableHandleScript script)
4092 {
4093     return ::Compile(cx, options, HasSyntacticScope, file, script);
4094 }
4095 
4096 bool
Compile(JSContext * cx,const ReadOnlyCompileOptions & options,const char * filename,JS::MutableHandleScript script)4097 JS::Compile(JSContext* cx, const ReadOnlyCompileOptions& options,
4098             const char* filename, JS::MutableHandleScript script)
4099 {
4100     return ::Compile(cx, options, HasSyntacticScope, filename, script);
4101 }
4102 
4103 bool
CompileForNonSyntacticScope(JSContext * cx,const ReadOnlyCompileOptions & options,SourceBufferHolder & srcBuf,JS::MutableHandleScript script)4104 JS::CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options,
4105                                 SourceBufferHolder& srcBuf, JS::MutableHandleScript script)
4106 {
4107     return ::Compile(cx, options, HasNonSyntacticScope, srcBuf, script);
4108 }
4109 
4110 bool
CompileForNonSyntacticScope(JSContext * cx,const ReadOnlyCompileOptions & options,const char * bytes,size_t length,JS::MutableHandleScript script)4111 JS::CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options,
4112                                 const char* bytes, size_t length, JS::MutableHandleScript script)
4113 {
4114     return ::Compile(cx, options, HasNonSyntacticScope, bytes, length, script);
4115 }
4116 
4117 bool
CompileForNonSyntacticScope(JSContext * cx,const ReadOnlyCompileOptions & options,const char16_t * chars,size_t length,JS::MutableHandleScript script)4118 JS::CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options,
4119                                 const char16_t* chars, size_t length,
4120                                 JS::MutableHandleScript script)
4121 {
4122     return ::Compile(cx, options, HasNonSyntacticScope, chars, length, script);
4123 }
4124 
4125 bool
CompileForNonSyntacticScope(JSContext * cx,const ReadOnlyCompileOptions & options,FILE * file,JS::MutableHandleScript script)4126 JS::CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options,
4127                                 FILE* file, JS::MutableHandleScript script)
4128 {
4129     return ::Compile(cx, options, HasNonSyntacticScope, file, script);
4130 }
4131 
4132 bool
CompileForNonSyntacticScope(JSContext * cx,const ReadOnlyCompileOptions & options,const char * filename,JS::MutableHandleScript script)4133 JS::CompileForNonSyntacticScope(JSContext* cx, const ReadOnlyCompileOptions& options,
4134                                 const char* filename, JS::MutableHandleScript script)
4135 {
4136     return ::Compile(cx, options, HasNonSyntacticScope, filename, script);
4137 }
4138 
JS_PUBLIC_API(bool)4139 JS_PUBLIC_API(bool)
4140 JS::CanCompileOffThread(JSContext* cx, const ReadOnlyCompileOptions& options, size_t length)
4141 {
4142     static const size_t TINY_LENGTH = 5 * 1000;
4143     static const size_t HUGE_LENGTH = 100 * 1000;
4144 
4145     // These are heuristics which the caller may choose to ignore (e.g., for
4146     // testing purposes).
4147     if (!options.forceAsync) {
4148         // Compiling off the main thread inolves creating a new Zone and other
4149         // significant overheads.  Don't bother if the script is tiny.
4150         if (length < TINY_LENGTH)
4151             return false;
4152 
4153         // If the parsing task would have to wait for GC to complete, it'll probably
4154         // be faster to just start it synchronously on the main thread unless the
4155         // script is huge.
4156         if (OffThreadParsingMustWaitForGC(cx->runtime()) && length < HUGE_LENGTH)
4157             return false;
4158     }
4159 
4160     return cx->runtime()->canUseParallelParsing() && CanUseExtraThreads();
4161 }
4162 
JS_PUBLIC_API(bool)4163 JS_PUBLIC_API(bool)
4164 JS::CompileOffThread(JSContext* cx, const ReadOnlyCompileOptions& options,
4165                      const char16_t* chars, size_t length,
4166                      OffThreadCompileCallback callback, void* callbackData)
4167 {
4168     MOZ_ASSERT(CanCompileOffThread(cx, options, length));
4169     return StartOffThreadParseScript(cx, options, chars, length, callback, callbackData);
4170 }
4171 
JS_PUBLIC_API(JSScript *)4172 JS_PUBLIC_API(JSScript*)
4173 JS::FinishOffThreadScript(JSContext* maybecx, JSRuntime* rt, void* token)
4174 {
4175     MOZ_ASSERT(CurrentThreadCanAccessRuntime(rt));
4176 
4177     if (maybecx) {
4178         RootedScript script(maybecx);
4179         {
4180             AutoLastFrameCheck lfc(maybecx);
4181             script = HelperThreadState().finishParseTask(maybecx, rt, token);
4182         }
4183         return script;
4184     } else {
4185         return HelperThreadState().finishParseTask(maybecx, rt, token);
4186     }
4187 }
4188 
4189 JS_PUBLIC_API(bool)
JS_CompileScript(JSContext * cx,const char * ascii,size_t length,const JS::CompileOptions & options,MutableHandleScript script)4190 JS_CompileScript(JSContext* cx, const char* ascii, size_t length,
4191                  const JS::CompileOptions& options, MutableHandleScript script)
4192 {
4193     return Compile(cx, options, ascii, length, script);
4194 }
4195 
4196 JS_PUBLIC_API(bool)
JS_CompileUCScript(JSContext * cx,const char16_t * chars,size_t length,const JS::CompileOptions & options,MutableHandleScript script)4197 JS_CompileUCScript(JSContext* cx, const char16_t* chars, size_t length,
4198                    const JS::CompileOptions& options, MutableHandleScript script)
4199 {
4200     return Compile(cx, options, chars, length, script);
4201 }
4202 
4203 JS_PUBLIC_API(bool)
JS_BufferIsCompilableUnit(JSContext * cx,HandleObject obj,const char * utf8,size_t length)4204 JS_BufferIsCompilableUnit(JSContext* cx, HandleObject obj, const char* utf8, size_t length)
4205 {
4206     AssertHeapIsIdle(cx);
4207     CHECK_REQUEST(cx);
4208     assertSameCompartment(cx, obj);
4209 
4210     cx->clearPendingException();
4211 
4212     char16_t* chars = JS::UTF8CharsToNewTwoByteCharsZ(cx, JS::UTF8Chars(utf8, length), &length).get();
4213     if (!chars)
4214         return true;
4215 
4216     // Return true on any out-of-memory error or non-EOF-related syntax error, so our
4217     // caller doesn't try to collect more buffered source.
4218     bool result = true;
4219 
4220     CompileOptions options(cx);
4221     Parser<frontend::FullParseHandler> parser(cx, &cx->tempLifoAlloc(),
4222                                               options, chars, length,
4223                                               /* foldConstants = */ true, nullptr, nullptr);
4224     JSErrorReporter older = JS_SetErrorReporter(cx->runtime(), nullptr);
4225     if (!parser.checkOptions() || !parser.parse()) {
4226         // We ran into an error. If it was because we ran out of source, we
4227         // return false so our caller knows to try to collect more buffered
4228         // source.
4229         if (parser.isUnexpectedEOF())
4230             result = false;
4231 
4232         cx->clearPendingException();
4233     }
4234     JS_SetErrorReporter(cx->runtime(), older);
4235 
4236     js_free(chars);
4237     return result;
4238 }
4239 
4240 JS_PUBLIC_API(JSObject*)
JS_GetGlobalFromScript(JSScript * script)4241 JS_GetGlobalFromScript(JSScript* script)
4242 {
4243     MOZ_ASSERT(!script->isCachedEval());
4244     return &script->global();
4245 }
4246 
4247 JS_PUBLIC_API(const char*)
JS_GetScriptFilename(JSScript * script)4248 JS_GetScriptFilename(JSScript* script)
4249 {
4250     // This is called from ThreadStackHelper which can be called from another
4251     // thread or inside a signal hander, so we need to be careful in case a
4252     // copmacting GC is currently moving things around.
4253     return script->maybeForwardedFilename();
4254 }
4255 
4256 JS_PUBLIC_API(unsigned)
JS_GetScriptBaseLineNumber(JSContext * cx,JSScript * script)4257 JS_GetScriptBaseLineNumber(JSContext* cx, JSScript* script)
4258 {
4259     return script->lineno();
4260 }
4261 
4262 JS_PUBLIC_API(JSScript*)
JS_GetFunctionScript(JSContext * cx,HandleFunction fun)4263 JS_GetFunctionScript(JSContext* cx, HandleFunction fun)
4264 {
4265     if (fun->isNative())
4266         return nullptr;
4267     if (fun->isInterpretedLazy()) {
4268         AutoCompartment funCompartment(cx, fun);
4269         JSScript* script = fun->getOrCreateScript(cx);
4270         if (!script)
4271             MOZ_CRASH();
4272         return script;
4273     }
4274     return fun->nonLazyScript();
4275 }
4276 
4277 /*
4278  * enclosingStaticScope is a static enclosing scope, if any (e.g. a
4279  * StaticWithObject).  If the enclosing scope is the global scope, this must be
4280  * null.
4281  *
4282  * enclosingDynamicScope is a dynamic scope to use, if it's not the global.
4283  */
4284 static bool
CompileFunction(JSContext * cx,const ReadOnlyCompileOptions & optionsArg,const char * name,unsigned nargs,const char * const * argnames,SourceBufferHolder & srcBuf,HandleObject enclosingDynamicScope,Handle<ScopeObject * > enclosingStaticScope,MutableHandleFunction fun)4285 CompileFunction(JSContext* cx, const ReadOnlyCompileOptions& optionsArg,
4286                 const char* name, unsigned nargs, const char* const* argnames,
4287                 SourceBufferHolder& srcBuf,
4288                 HandleObject enclosingDynamicScope,
4289                 Handle<ScopeObject*> enclosingStaticScope,
4290                 MutableHandleFunction fun)
4291 {
4292     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
4293     AssertHeapIsIdle(cx);
4294     CHECK_REQUEST(cx);
4295     assertSameCompartment(cx, enclosingDynamicScope);
4296     assertSameCompartment(cx, enclosingStaticScope);
4297     RootedAtom funAtom(cx);
4298     AutoLastFrameCheck lfc(cx);
4299 
4300     if (name) {
4301         funAtom = Atomize(cx, name, strlen(name));
4302         if (!funAtom)
4303             return false;
4304     }
4305 
4306     Rooted<PropertyNameVector> formals(cx, PropertyNameVector(cx));
4307     for (unsigned i = 0; i < nargs; i++) {
4308         RootedAtom argAtom(cx, Atomize(cx, argnames[i], strlen(argnames[i])));
4309         if (!argAtom || !formals.append(argAtom->asPropertyName()))
4310             return false;
4311     }
4312 
4313     fun.set(NewScriptedFunction(cx, 0, JSFunction::INTERPRETED_NORMAL, funAtom,
4314                                 gc::AllocKind::FUNCTION, TenuredObject,
4315                                 enclosingDynamicScope));
4316     if (!fun)
4317         return false;
4318 
4319     // Make sure the static scope chain matches up when we have a
4320     // non-syntactic scope.
4321     MOZ_ASSERT_IF(!IsGlobalLexicalScope(enclosingDynamicScope),
4322                   HasNonSyntacticStaticScopeChain(enclosingStaticScope));
4323 
4324     if (!frontend::CompileFunctionBody(cx, fun, optionsArg, formals, srcBuf, enclosingStaticScope))
4325         return false;
4326 
4327     return true;
4328 }
4329 
JS_PUBLIC_API(bool)4330 JS_PUBLIC_API(bool)
4331 JS::CompileFunction(JSContext* cx, AutoObjectVector& scopeChain,
4332                     const ReadOnlyCompileOptions& options,
4333                     const char* name, unsigned nargs, const char* const* argnames,
4334                     SourceBufferHolder& srcBuf, MutableHandleFunction fun)
4335 {
4336     RootedObject dynamicScopeObj(cx);
4337     Rooted<ScopeObject*> staticScopeObj(cx);
4338     if (!CreateNonSyntacticScopeChain(cx, scopeChain, &dynamicScopeObj, &staticScopeObj))
4339         return false;
4340 
4341     return CompileFunction(cx, options, name, nargs, argnames,
4342                            srcBuf, dynamicScopeObj, staticScopeObj, fun);
4343 }
4344 
JS_PUBLIC_API(bool)4345 JS_PUBLIC_API(bool)
4346 JS::CompileFunction(JSContext* cx, AutoObjectVector& scopeChain,
4347                     const ReadOnlyCompileOptions& options,
4348                     const char* name, unsigned nargs, const char* const* argnames,
4349                     const char16_t* chars, size_t length, MutableHandleFunction fun)
4350 {
4351     SourceBufferHolder srcBuf(chars, length, SourceBufferHolder::NoOwnership);
4352     return CompileFunction(cx, scopeChain, options, name, nargs, argnames,
4353                            srcBuf, fun);
4354 }
4355 
JS_PUBLIC_API(bool)4356 JS_PUBLIC_API(bool)
4357 JS::CompileFunction(JSContext* cx, AutoObjectVector& scopeChain,
4358                     const ReadOnlyCompileOptions& options,
4359                     const char* name, unsigned nargs, const char* const* argnames,
4360                     const char* bytes, size_t length, MutableHandleFunction fun)
4361 {
4362     mozilla::UniquePtr<char16_t, JS::FreePolicy> chars;
4363     if (options.utf8)
4364         chars.reset(UTF8CharsToNewTwoByteCharsZ(cx, UTF8Chars(bytes, length), &length).get());
4365     else
4366         chars.reset(InflateString(cx, bytes, &length));
4367     if (!chars)
4368         return false;
4369 
4370     return CompileFunction(cx, scopeChain, options, name, nargs, argnames,
4371                            chars.get(), length, fun);
4372 }
4373 
4374 JS_PUBLIC_API(JSString*)
JS_DecompileScript(JSContext * cx,HandleScript script,const char * name,unsigned indent)4375 JS_DecompileScript(JSContext* cx, HandleScript script, const char* name, unsigned indent)
4376 {
4377     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
4378 
4379     AssertHeapIsIdle(cx);
4380     CHECK_REQUEST(cx);
4381     script->ensureNonLazyCanonicalFunction(cx);
4382     RootedFunction fun(cx, script->functionNonDelazifying());
4383     if (fun)
4384         return JS_DecompileFunction(cx, fun, indent);
4385     bool haveSource = script->scriptSource()->hasSourceData();
4386     if (!haveSource && !JSScript::loadSource(cx, script->scriptSource(), &haveSource))
4387         return nullptr;
4388     return haveSource ? script->sourceData(cx) : NewStringCopyZ<CanGC>(cx, "[no source]");
4389 }
4390 
4391 JS_PUBLIC_API(JSString*)
JS_DecompileFunction(JSContext * cx,HandleFunction fun,unsigned indent)4392 JS_DecompileFunction(JSContext* cx, HandleFunction fun, unsigned indent)
4393 {
4394     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
4395     AssertHeapIsIdle(cx);
4396     CHECK_REQUEST(cx);
4397     assertSameCompartment(cx, fun);
4398     return FunctionToString(cx, fun, !(indent & JS_DONT_PRETTY_PRINT));
4399 }
4400 
4401 MOZ_NEVER_INLINE static bool
ExecuteScript(JSContext * cx,HandleObject scope,HandleScript script,Value * rval)4402 ExecuteScript(JSContext* cx, HandleObject scope, HandleScript script, Value* rval)
4403 {
4404     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
4405     AssertHeapIsIdle(cx);
4406     CHECK_REQUEST(cx);
4407     assertSameCompartment(cx, scope, script);
4408     MOZ_ASSERT_IF(!IsGlobalLexicalScope(scope), script->hasNonSyntacticScope());
4409     AutoLastFrameCheck lfc(cx);
4410     return Execute(cx, script, *scope, rval);
4411 }
4412 
4413 static bool
ExecuteScript(JSContext * cx,AutoObjectVector & scopeChain,HandleScript scriptArg,Value * rval)4414 ExecuteScript(JSContext* cx, AutoObjectVector& scopeChain, HandleScript scriptArg, Value* rval)
4415 {
4416     RootedObject dynamicScope(cx);
4417     Rooted<ScopeObject*> staticScope(cx);
4418     if (!CreateNonSyntacticScopeChain(cx, scopeChain, &dynamicScope, &staticScope))
4419         return false;
4420 
4421     RootedScript script(cx, scriptArg);
4422     if (!script->hasNonSyntacticScope() && !IsGlobalLexicalScope(dynamicScope)) {
4423         script = CloneGlobalScript(cx, staticScope, script);
4424         if (!script)
4425             return false;
4426         js::Debugger::onNewScript(cx, script);
4427     }
4428 
4429     return ExecuteScript(cx, dynamicScope, script, rval);
4430 }
4431 
JS_PUBLIC_API(bool)4432 MOZ_NEVER_INLINE JS_PUBLIC_API(bool)
4433 JS_ExecuteScript(JSContext* cx, HandleScript scriptArg, MutableHandleValue rval)
4434 {
4435     RootedObject globalLexical(cx, &cx->global()->lexicalScope());
4436     return ExecuteScript(cx, globalLexical, scriptArg, rval.address());
4437 }
4438 
JS_PUBLIC_API(bool)4439 MOZ_NEVER_INLINE JS_PUBLIC_API(bool)
4440 JS_ExecuteScript(JSContext* cx, HandleScript scriptArg)
4441 {
4442     RootedObject globalLexical(cx, &cx->global()->lexicalScope());
4443     return ExecuteScript(cx, globalLexical, scriptArg, nullptr);
4444 }
4445 
JS_PUBLIC_API(bool)4446 MOZ_NEVER_INLINE JS_PUBLIC_API(bool)
4447 JS_ExecuteScript(JSContext* cx, AutoObjectVector& scopeChain,
4448                  HandleScript scriptArg, MutableHandleValue rval)
4449 {
4450     return ExecuteScript(cx, scopeChain, scriptArg, rval.address());
4451 }
4452 
JS_PUBLIC_API(bool)4453 MOZ_NEVER_INLINE JS_PUBLIC_API(bool)
4454 JS_ExecuteScript(JSContext* cx, AutoObjectVector& scopeChain, HandleScript scriptArg)
4455 {
4456     return ExecuteScript(cx, scopeChain, scriptArg, nullptr);
4457 }
4458 
JS_PUBLIC_API(bool)4459 JS_PUBLIC_API(bool)
4460 JS::CloneAndExecuteScript(JSContext* cx, HandleScript scriptArg)
4461 {
4462     CHECK_REQUEST(cx);
4463     RootedScript script(cx, scriptArg);
4464     Rooted<ClonedBlockObject*> globalLexical(cx, &cx->global()->lexicalScope());
4465     if (script->compartment() != cx->compartment()) {
4466         Rooted<ScopeObject*> staticLexical(cx, &globalLexical->staticBlock());
4467         script = CloneGlobalScript(cx, staticLexical, script);
4468         if (!script)
4469             return false;
4470 
4471         js::Debugger::onNewScript(cx, script);
4472     }
4473     return ExecuteScript(cx, globalLexical, script, nullptr);
4474 }
4475 
4476 static const unsigned LARGE_SCRIPT_LENGTH = 500*1024;
4477 
4478 static bool
Evaluate(JSContext * cx,HandleObject scope,Handle<ScopeObject * > staticScope,const ReadOnlyCompileOptions & optionsArg,SourceBufferHolder & srcBuf,MutableHandleValue rval)4479 Evaluate(JSContext* cx, HandleObject scope, Handle<ScopeObject*> staticScope,
4480          const ReadOnlyCompileOptions& optionsArg,
4481          SourceBufferHolder& srcBuf, MutableHandleValue rval)
4482 {
4483     CompileOptions options(cx, optionsArg);
4484     MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
4485     AssertHeapIsIdle(cx);
4486     CHECK_REQUEST(cx);
4487     assertSameCompartment(cx, scope);
4488 
4489     AutoLastFrameCheck lfc(cx);
4490 
4491     MOZ_ASSERT_IF(!IsGlobalLexicalScope(scope), HasNonSyntacticStaticScopeChain(staticScope));
4492 
4493     options.setIsRunOnce(true);
4494     SourceCompressionTask sct(cx);
4495     RootedScript script(cx, frontend::CompileScript(cx, &cx->tempLifoAlloc(),
4496                                                     scope, staticScope,
4497                                                     /* evalCaller = */ nullptr, options,
4498                                                     srcBuf, /* source = */ nullptr, &sct));
4499     if (!script)
4500         return false;
4501 
4502     MOZ_ASSERT(script->getVersion() == options.version);
4503 
4504     bool result = Execute(cx, script, *scope,
4505                           options.noScriptRval ? nullptr : rval.address());
4506     if (!sct.complete())
4507         result = false;
4508 
4509     // After evaluation, the compiled script will not be run again.
4510     // script->ensureRanAnalysis allocated 1 analyze::Bytecode for every opcode
4511     // which for large scripts means significant memory. Perform a GC eagerly
4512     // to clear out this analysis data before anything happens to inhibit the
4513     // flushing of this memory (such as setting requestAnimationFrame).
4514     if (script->length() > LARGE_SCRIPT_LENGTH) {
4515         script = nullptr;
4516         PrepareZoneForGC(cx->zone());
4517         cx->runtime()->gc.gc(GC_NORMAL, JS::gcreason::FINISH_LARGE_EVALUATE);
4518     }
4519 
4520     return result;
4521 }
4522 
4523 static bool
Evaluate(JSContext * cx,AutoObjectVector & scopeChain,const ReadOnlyCompileOptions & optionsArg,SourceBufferHolder & srcBuf,MutableHandleValue rval)4524 Evaluate(JSContext* cx, AutoObjectVector& scopeChain, const ReadOnlyCompileOptions& optionsArg,
4525          SourceBufferHolder& srcBuf, MutableHandleValue rval)
4526 {
4527     RootedObject dynamicScope(cx);
4528     Rooted<ScopeObject*> staticScope(cx);
4529     if (!CreateNonSyntacticScopeChain(cx, scopeChain, &dynamicScope, &staticScope))
4530         return false;
4531     return ::Evaluate(cx, dynamicScope, staticScope, optionsArg, srcBuf, rval);
4532 }
4533 
4534 static bool
Evaluate(JSContext * cx,const ReadOnlyCompileOptions & optionsArg,const char16_t * chars,size_t length,MutableHandleValue rval)4535 Evaluate(JSContext* cx, const ReadOnlyCompileOptions& optionsArg,
4536          const char16_t* chars, size_t length, MutableHandleValue rval)
4537 {
4538   SourceBufferHolder srcBuf(chars, length, SourceBufferHolder::NoOwnership);
4539   Rooted<ClonedBlockObject*> globalLexical(cx, &cx->global()->lexicalScope());
4540   Rooted<ScopeObject*> staticLexical(cx, &globalLexical->staticBlock());
4541   return ::Evaluate(cx, globalLexical, staticLexical, optionsArg, srcBuf, rval);
4542 }
4543 
JS_PUBLIC_API(bool)4544 extern JS_PUBLIC_API(bool)
4545 JS::Evaluate(JSContext* cx, const ReadOnlyCompileOptions& options,
4546              const char* bytes, size_t length, MutableHandleValue rval)
4547 {
4548     char16_t* chars;
4549     if (options.utf8)
4550         chars = UTF8CharsToNewTwoByteCharsZ(cx, JS::UTF8Chars(bytes, length), &length).get();
4551     else
4552         chars = InflateString(cx, bytes, &length);
4553     if (!chars)
4554         return false;
4555 
4556     SourceBufferHolder srcBuf(chars, length, SourceBufferHolder::GiveOwnership);
4557     Rooted<ClonedBlockObject*> globalLexical(cx, &cx->global()->lexicalScope());
4558     Rooted<ScopeObject*> staticLexical(cx, &globalLexical->staticBlock());
4559     bool ok = ::Evaluate(cx, globalLexical, staticLexical, options, srcBuf, rval);
4560     return ok;
4561 }
4562 
4563 static bool
Evaluate(JSContext * cx,const ReadOnlyCompileOptions & optionsArg,const char * filename,MutableHandleValue rval)4564 Evaluate(JSContext* cx, const ReadOnlyCompileOptions& optionsArg,
4565          const char* filename, MutableHandleValue rval)
4566 {
4567     FileContents buffer(cx);
4568     {
4569         AutoFile file;
4570         if (!file.open(cx, filename) || !file.readAll(cx, buffer))
4571             return false;
4572     }
4573 
4574     CompileOptions options(cx, optionsArg);
4575     options.setFileAndLine(filename, 1);
4576     return Evaluate(cx, options, buffer.begin(), buffer.length(), rval);
4577 }
4578 
JS_PUBLIC_API(bool)4579 JS_PUBLIC_API(bool)
4580 JS::Evaluate(JSContext* cx, const ReadOnlyCompileOptions& optionsArg,
4581              SourceBufferHolder& srcBuf, MutableHandleValue rval)
4582 {
4583     Rooted<ClonedBlockObject*> globalLexical(cx, &cx->global()->lexicalScope());
4584     Rooted<ScopeObject*> staticLexical(cx, &globalLexical->staticBlock());
4585     return ::Evaluate(cx, globalLexical, staticLexical, optionsArg, srcBuf, rval);
4586 }
4587 
JS_PUBLIC_API(bool)4588 JS_PUBLIC_API(bool)
4589 JS::Evaluate(JSContext* cx, AutoObjectVector& scopeChain, const ReadOnlyCompileOptions& optionsArg,
4590              SourceBufferHolder& srcBuf, MutableHandleValue rval)
4591 {
4592     return ::Evaluate(cx, scopeChain, optionsArg, srcBuf, rval);
4593 }
4594 
JS_PUBLIC_API(bool)4595 JS_PUBLIC_API(bool)
4596 JS::Evaluate(JSContext* cx, const ReadOnlyCompileOptions& optionsArg,
4597              const char16_t* chars, size_t length, MutableHandleValue rval)
4598 {
4599     return ::Evaluate(cx, optionsArg, chars, length, rval);
4600 }
4601 
JS_PUBLIC_API(bool)4602 JS_PUBLIC_API(bool)
4603 JS::Evaluate(JSContext* cx, AutoObjectVector& scopeChain, const ReadOnlyCompileOptions& optionsArg,
4604              const char16_t* chars, size_t length, MutableHandleValue rval)
4605 {
4606     SourceBufferHolder srcBuf(chars, length, SourceBufferHolder::NoOwnership);
4607     return ::Evaluate(cx, scopeChain, optionsArg, srcBuf, rval);
4608 }
4609 
JS_PUBLIC_API(bool)4610 JS_PUBLIC_API(bool)
4611 JS::Evaluate(JSContext* cx, const ReadOnlyCompileOptions& optionsArg,
4612              const char* filename, MutableHandleValue rval)
4613 {
4614     return ::Evaluate(cx, optionsArg, filename, rval);
4615 }
4616 
4617 static JSObject*
JS_NewHelper(JSContext * cx,HandleObject ctor,const JS::HandleValueArray & inputArgs)4618 JS_NewHelper(JSContext* cx, HandleObject ctor, const JS::HandleValueArray& inputArgs)
4619 {
4620     AssertHeapIsIdle(cx);
4621     CHECK_REQUEST(cx);
4622     assertSameCompartment(cx, ctor, inputArgs);
4623 
4624     RootedValue ctorVal(cx, ObjectValue(*ctor));
4625     if (!IsConstructor(ctorVal)) {
4626         ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_IGNORE_STACK, ctorVal, nullptr);
4627         return nullptr;
4628     }
4629 
4630     ConstructArgs args(cx);
4631     if (!FillArgumentsFromArraylike(cx, args, inputArgs))
4632         return nullptr;
4633 
4634     RootedValue rval(cx);
4635     if (!js::Construct(cx, ctorVal, args, ctorVal, &rval))
4636         return nullptr;
4637 
4638     return &rval.toObject();
4639 }
4640 
4641 JS_PUBLIC_API(JSObject*)
JS_New(JSContext * cx,HandleObject ctor,const JS::HandleValueArray & inputArgs)4642 JS_New(JSContext* cx, HandleObject ctor, const JS::HandleValueArray& inputArgs)
4643 {
4644     RootedObject obj(cx);
4645     {
4646         AutoLastFrameCheck lfc(cx);
4647         obj = JS_NewHelper(cx, ctor, inputArgs);
4648     }
4649     return obj;
4650 }
4651 
4652 JS_PUBLIC_API(bool)
JS_CheckForInterrupt(JSContext * cx)4653 JS_CheckForInterrupt(JSContext* cx)
4654 {
4655     return js::CheckForInterrupt(cx);
4656 }
4657 
4658 JS_PUBLIC_API(JSInterruptCallback)
JS_SetInterruptCallback(JSRuntime * rt,JSInterruptCallback callback)4659 JS_SetInterruptCallback(JSRuntime* rt, JSInterruptCallback callback)
4660 {
4661     JSInterruptCallback old = rt->interruptCallback;
4662     rt->interruptCallback = callback;
4663     return old;
4664 }
4665 
4666 JS_PUBLIC_API(JSInterruptCallback)
JS_GetInterruptCallback(JSRuntime * rt)4667 JS_GetInterruptCallback(JSRuntime* rt)
4668 {
4669     return rt->interruptCallback;
4670 }
4671 
4672 JS_PUBLIC_API(void)
JS_RequestInterruptCallback(JSRuntime * rt)4673 JS_RequestInterruptCallback(JSRuntime* rt)
4674 {
4675     rt->requestInterrupt(JSRuntime::RequestInterruptUrgent);
4676 }
4677 
4678 JS_PUBLIC_API(bool)
JS_IsRunning(JSContext * cx)4679 JS_IsRunning(JSContext* cx)
4680 {
4681     return cx->currentlyRunning();
4682 }
4683 
4684 JS_PUBLIC_API(bool)
JS_SaveFrameChain(JSContext * cx)4685 JS_SaveFrameChain(JSContext* cx)
4686 {
4687     AssertHeapIsIdleOrIterating(cx);
4688     CHECK_REQUEST(cx);
4689     return cx->saveFrameChain();
4690 }
4691 
4692 JS_PUBLIC_API(void)
JS_RestoreFrameChain(JSContext * cx)4693 JS_RestoreFrameChain(JSContext* cx)
4694 {
4695     AssertHeapIsIdleOrIterating(cx);
4696     CHECK_REQUEST(cx);
4697     cx->restoreFrameChain();
4698 }
4699 
AutoSetAsyncStackForNewCalls(JSContext * cx,HandleObject stack,HandleString asyncCause,JS::AutoSetAsyncStackForNewCalls::AsyncCallKind kind)4700 JS::AutoSetAsyncStackForNewCalls::AutoSetAsyncStackForNewCalls(
4701   JSContext* cx, HandleObject stack, HandleString asyncCause,
4702   JS::AutoSetAsyncStackForNewCalls::AsyncCallKind kind)
4703   : cx(cx),
4704     oldAsyncStack(cx, cx->runtime()->asyncStackForNewActivations),
4705     oldAsyncCause(cx, cx->runtime()->asyncCauseForNewActivations),
4706     oldAsyncCallIsExplicit(cx->runtime()->asyncCallIsExplicit)
4707 {
4708     CHECK_REQUEST(cx);
4709 
4710     // The option determines whether we actually use the new values at this
4711     // point. It will not affect restoring the previous values when the object
4712     // is destroyed, so if the option changes it won't cause consistency issues.
4713     if (!cx->runtime()->options().asyncStack())
4714         return;
4715 
4716     SavedFrame* asyncStack = &stack->as<SavedFrame>();
4717     MOZ_ASSERT(!asyncCause->empty());
4718 
4719     cx->runtime()->asyncStackForNewActivations = asyncStack;
4720     cx->runtime()->asyncCauseForNewActivations = asyncCause;
4721     cx->runtime()->asyncCallIsExplicit = kind == AsyncCallKind::EXPLICIT;
4722 }
4723 
~AutoSetAsyncStackForNewCalls()4724 JS::AutoSetAsyncStackForNewCalls::~AutoSetAsyncStackForNewCalls()
4725 {
4726     cx->runtime()->asyncCauseForNewActivations = oldAsyncCause;
4727     cx->runtime()->asyncStackForNewActivations =
4728       oldAsyncStack ? &oldAsyncStack->as<SavedFrame>() : nullptr;
4729     cx->runtime()->asyncCallIsExplicit = oldAsyncCallIsExplicit;
4730 }
4731 
4732 /************************************************************************/
4733 JS_PUBLIC_API(JSString*)
JS_NewStringCopyN(JSContext * cx,const char * s,size_t n)4734 JS_NewStringCopyN(JSContext* cx, const char* s, size_t n)
4735 {
4736     AssertHeapIsIdle(cx);
4737     CHECK_REQUEST(cx);
4738     if (!n)
4739         return cx->names().empty;
4740     return NewStringCopyN<CanGC>(cx, s, n);
4741 }
4742 
4743 JS_PUBLIC_API(JSString*)
JS_NewStringCopyZ(JSContext * cx,const char * s)4744 JS_NewStringCopyZ(JSContext* cx, const char* s)
4745 {
4746     AssertHeapIsIdle(cx);
4747     CHECK_REQUEST(cx);
4748     if (!s || !*s)
4749         return cx->runtime()->emptyString;
4750     return NewStringCopyZ<CanGC>(cx, s);
4751 }
4752 
4753 JS_PUBLIC_API(bool)
JS_StringHasBeenPinned(JSContext * cx,JSString * str)4754 JS_StringHasBeenPinned(JSContext* cx, JSString* str)
4755 {
4756     AssertHeapIsIdle(cx);
4757     CHECK_REQUEST(cx);
4758 
4759     if (!str->isAtom())
4760         return false;
4761 
4762     return AtomIsPinned(cx, &str->asAtom());
4763 }
4764 
4765 JS_PUBLIC_API(jsid)
INTERNED_STRING_TO_JSID(JSContext * cx,JSString * str)4766 INTERNED_STRING_TO_JSID(JSContext* cx, JSString* str)
4767 {
4768     MOZ_ASSERT(str);
4769     MOZ_ASSERT(((size_t)str & JSID_TYPE_MASK) == 0);
4770     MOZ_ASSERT_IF(cx, JS_StringHasBeenPinned(cx, str));
4771     return AtomToId(&str->asAtom());
4772 }
4773 
4774 JS_PUBLIC_API(JSString*)
JS_AtomizeAndPinJSString(JSContext * cx,HandleString str)4775 JS_AtomizeAndPinJSString(JSContext* cx, HandleString str)
4776 {
4777     AssertHeapIsIdle(cx);
4778     CHECK_REQUEST(cx);
4779     JSAtom* atom = AtomizeString(cx, str, PinAtom);
4780     MOZ_ASSERT_IF(atom, JS_StringHasBeenPinned(cx, atom));
4781     return atom;
4782 }
4783 
4784 JS_PUBLIC_API(JSString*)
JS_AtomizeAndPinString(JSContext * cx,const char * s)4785 JS_AtomizeAndPinString(JSContext* cx, const char* s)
4786 {
4787     return JS_AtomizeAndPinStringN(cx, s, strlen(s));
4788 }
4789 
4790 JS_PUBLIC_API(JSString*)
JS_AtomizeAndPinStringN(JSContext * cx,const char * s,size_t length)4791 JS_AtomizeAndPinStringN(JSContext* cx, const char* s, size_t length)
4792 {
4793     AssertHeapIsIdle(cx);
4794     CHECK_REQUEST(cx);
4795     JSAtom* atom = Atomize(cx, s, length, PinAtom);
4796     MOZ_ASSERT_IF(atom, JS_StringHasBeenPinned(cx, atom));
4797     return atom;
4798 }
4799 
4800 JS_PUBLIC_API(JSString*)
JS_NewUCString(JSContext * cx,char16_t * chars,size_t length)4801 JS_NewUCString(JSContext* cx, char16_t* chars, size_t length)
4802 {
4803     AssertHeapIsIdle(cx);
4804     CHECK_REQUEST(cx);
4805     return NewString<CanGC>(cx, chars, length);
4806 }
4807 
4808 JS_PUBLIC_API(JSString*)
JS_NewUCStringCopyN(JSContext * cx,const char16_t * s,size_t n)4809 JS_NewUCStringCopyN(JSContext* cx, const char16_t* s, size_t n)
4810 {
4811     AssertHeapIsIdle(cx);
4812     CHECK_REQUEST(cx);
4813     if (!n)
4814         return cx->names().empty;
4815     return NewStringCopyN<CanGC>(cx, s, n);
4816 }
4817 
4818 JS_PUBLIC_API(JSString*)
JS_NewUCStringCopyZ(JSContext * cx,const char16_t * s)4819 JS_NewUCStringCopyZ(JSContext* cx, const char16_t* s)
4820 {
4821     AssertHeapIsIdle(cx);
4822     CHECK_REQUEST(cx);
4823     if (!s)
4824         return cx->runtime()->emptyString;
4825     return NewStringCopyZ<CanGC>(cx, s);
4826 }
4827 
4828 JS_PUBLIC_API(JSString*)
JS_AtomizeAndPinUCStringN(JSContext * cx,const char16_t * s,size_t length)4829 JS_AtomizeAndPinUCStringN(JSContext* cx, const char16_t* s, size_t length)
4830 {
4831     AssertHeapIsIdle(cx);
4832     CHECK_REQUEST(cx);
4833     JSAtom* atom = AtomizeChars(cx, s, length, PinAtom);
4834     MOZ_ASSERT_IF(atom, JS_StringHasBeenPinned(cx, atom));
4835     return atom;
4836 }
4837 
4838 JS_PUBLIC_API(JSString*)
JS_AtomizeAndPinUCString(JSContext * cx,const char16_t * s)4839 JS_AtomizeAndPinUCString(JSContext* cx, const char16_t* s)
4840 {
4841     return JS_AtomizeAndPinUCStringN(cx, s, js_strlen(s));
4842 }
4843 
4844 JS_PUBLIC_API(size_t)
JS_GetStringLength(JSString * str)4845 JS_GetStringLength(JSString* str)
4846 {
4847     return str->length();
4848 }
4849 
4850 JS_PUBLIC_API(bool)
JS_StringIsFlat(JSString * str)4851 JS_StringIsFlat(JSString* str)
4852 {
4853     return str->isFlat();
4854 }
4855 
4856 JS_PUBLIC_API(bool)
JS_StringHasLatin1Chars(JSString * str)4857 JS_StringHasLatin1Chars(JSString* str)
4858 {
4859     return str->hasLatin1Chars();
4860 }
4861 
4862 JS_PUBLIC_API(const JS::Latin1Char*)
JS_GetLatin1StringCharsAndLength(JSContext * cx,const JS::AutoCheckCannotGC & nogc,JSString * str,size_t * plength)4863 JS_GetLatin1StringCharsAndLength(JSContext* cx, const JS::AutoCheckCannotGC& nogc, JSString* str,
4864                                  size_t* plength)
4865 {
4866     MOZ_ASSERT(plength);
4867     AssertHeapIsIdleOrStringIsFlat(cx, str);
4868     CHECK_REQUEST(cx);
4869     assertSameCompartment(cx, str);
4870     JSLinearString* linear = str->ensureLinear(cx);
4871     if (!linear)
4872         return nullptr;
4873     *plength = linear->length();
4874     return linear->latin1Chars(nogc);
4875 }
4876 
4877 JS_PUBLIC_API(const char16_t*)
JS_GetTwoByteStringCharsAndLength(JSContext * cx,const JS::AutoCheckCannotGC & nogc,JSString * str,size_t * plength)4878 JS_GetTwoByteStringCharsAndLength(JSContext* cx, const JS::AutoCheckCannotGC& nogc, JSString* str,
4879                                   size_t* plength)
4880 {
4881     MOZ_ASSERT(plength);
4882     AssertHeapIsIdleOrStringIsFlat(cx, str);
4883     CHECK_REQUEST(cx);
4884     assertSameCompartment(cx, str);
4885     JSLinearString* linear = str->ensureLinear(cx);
4886     if (!linear)
4887         return nullptr;
4888     *plength = linear->length();
4889     return linear->twoByteChars(nogc);
4890 }
4891 
4892 JS_PUBLIC_API(const char16_t*)
JS_GetTwoByteExternalStringChars(JSString * str)4893 JS_GetTwoByteExternalStringChars(JSString* str)
4894 {
4895     return str->asExternal().twoByteChars();
4896 }
4897 
4898 JS_PUBLIC_API(bool)
JS_GetStringCharAt(JSContext * cx,JSString * str,size_t index,char16_t * res)4899 JS_GetStringCharAt(JSContext* cx, JSString* str, size_t index, char16_t* res)
4900 {
4901     AssertHeapIsIdleOrStringIsFlat(cx, str);
4902     CHECK_REQUEST(cx);
4903     assertSameCompartment(cx, str);
4904 
4905     JSLinearString* linear = str->ensureLinear(cx);
4906     if (!linear)
4907         return false;
4908 
4909     *res = linear->latin1OrTwoByteChar(index);
4910     return true;
4911 }
4912 
4913 JS_PUBLIC_API(char16_t)
JS_GetFlatStringCharAt(JSFlatString * str,size_t index)4914 JS_GetFlatStringCharAt(JSFlatString* str, size_t index)
4915 {
4916     return str->latin1OrTwoByteChar(index);
4917 }
4918 
4919 JS_PUBLIC_API(bool)
JS_CopyStringChars(JSContext * cx,mozilla::Range<char16_t> dest,JSString * str)4920 JS_CopyStringChars(JSContext* cx, mozilla::Range<char16_t> dest, JSString* str)
4921 {
4922     AssertHeapIsIdleOrStringIsFlat(cx, str);
4923     CHECK_REQUEST(cx);
4924     assertSameCompartment(cx, str);
4925 
4926     JSLinearString* linear = str->ensureLinear(cx);
4927     if (!linear)
4928         return false;
4929 
4930     MOZ_ASSERT(linear->length() <= dest.length());
4931     CopyChars(dest.start().get(), *linear);
4932     return true;
4933 }
4934 
4935 JS_PUBLIC_API(const Latin1Char*)
JS_GetLatin1InternedStringChars(const JS::AutoCheckCannotGC & nogc,JSString * str)4936 JS_GetLatin1InternedStringChars(const JS::AutoCheckCannotGC& nogc, JSString* str)
4937 {
4938     MOZ_ASSERT(str->isAtom());
4939     JSFlatString* flat = str->ensureFlat(nullptr);
4940     if (!flat)
4941         return nullptr;
4942     return flat->latin1Chars(nogc);
4943 }
4944 
4945 JS_PUBLIC_API(const char16_t*)
JS_GetTwoByteInternedStringChars(const JS::AutoCheckCannotGC & nogc,JSString * str)4946 JS_GetTwoByteInternedStringChars(const JS::AutoCheckCannotGC& nogc, JSString* str)
4947 {
4948     MOZ_ASSERT(str->isAtom());
4949     JSFlatString* flat = str->ensureFlat(nullptr);
4950     if (!flat)
4951         return nullptr;
4952     return flat->twoByteChars(nogc);
4953 }
4954 
4955 extern JS_PUBLIC_API(JSFlatString*)
JS_FlattenString(JSContext * cx,JSString * str)4956 JS_FlattenString(JSContext* cx, JSString* str)
4957 {
4958     AssertHeapIsIdle(cx);
4959     CHECK_REQUEST(cx);
4960     assertSameCompartment(cx, str);
4961     JSFlatString* flat = str->ensureFlat(cx);
4962     if (!flat)
4963         return nullptr;
4964     return flat;
4965 }
4966 
4967 extern JS_PUBLIC_API(const Latin1Char*)
JS_GetLatin1FlatStringChars(const JS::AutoCheckCannotGC & nogc,JSFlatString * str)4968 JS_GetLatin1FlatStringChars(const JS::AutoCheckCannotGC& nogc, JSFlatString* str)
4969 {
4970     return str->latin1Chars(nogc);
4971 }
4972 
4973 extern JS_PUBLIC_API(const char16_t*)
JS_GetTwoByteFlatStringChars(const JS::AutoCheckCannotGC & nogc,JSFlatString * str)4974 JS_GetTwoByteFlatStringChars(const JS::AutoCheckCannotGC& nogc, JSFlatString* str)
4975 {
4976     return str->twoByteChars(nogc);
4977 }
4978 
4979 JS_PUBLIC_API(bool)
JS_CompareStrings(JSContext * cx,JSString * str1,JSString * str2,int32_t * result)4980 JS_CompareStrings(JSContext* cx, JSString* str1, JSString* str2, int32_t* result)
4981 {
4982     AssertHeapIsIdle(cx);
4983     CHECK_REQUEST(cx);
4984 
4985     return CompareStrings(cx, str1, str2, result);
4986 }
4987 
4988 JS_PUBLIC_API(bool)
JS_StringEqualsAscii(JSContext * cx,JSString * str,const char * asciiBytes,bool * match)4989 JS_StringEqualsAscii(JSContext* cx, JSString* str, const char* asciiBytes, bool* match)
4990 {
4991     AssertHeapIsIdle(cx);
4992     CHECK_REQUEST(cx);
4993 
4994     JSLinearString* linearStr = str->ensureLinear(cx);
4995     if (!linearStr)
4996         return false;
4997     *match = StringEqualsAscii(linearStr, asciiBytes);
4998     return true;
4999 }
5000 
5001 JS_PUBLIC_API(bool)
JS_FlatStringEqualsAscii(JSFlatString * str,const char * asciiBytes)5002 JS_FlatStringEqualsAscii(JSFlatString* str, const char* asciiBytes)
5003 {
5004     return StringEqualsAscii(str, asciiBytes);
5005 }
5006 
5007 JS_PUBLIC_API(size_t)
JS_PutEscapedFlatString(char * buffer,size_t size,JSFlatString * str,char quote)5008 JS_PutEscapedFlatString(char* buffer, size_t size, JSFlatString* str, char quote)
5009 {
5010     return PutEscapedString(buffer, size, str, quote);
5011 }
5012 
5013 JS_PUBLIC_API(size_t)
JS_PutEscapedString(JSContext * cx,char * buffer,size_t size,JSString * str,char quote)5014 JS_PutEscapedString(JSContext* cx, char* buffer, size_t size, JSString* str, char quote)
5015 {
5016     AssertHeapIsIdle(cx);
5017     JSLinearString* linearStr = str->ensureLinear(cx);
5018     if (!linearStr)
5019         return size_t(-1);
5020     return PutEscapedString(buffer, size, linearStr, quote);
5021 }
5022 
5023 JS_PUBLIC_API(bool)
JS_FileEscapedString(FILE * fp,JSString * str,char quote)5024 JS_FileEscapedString(FILE* fp, JSString* str, char quote)
5025 {
5026     JSLinearString* linearStr = str->ensureLinear(nullptr);
5027     return linearStr && FileEscapedString(fp, linearStr, quote);
5028 }
5029 
5030 JS_PUBLIC_API(JSString*)
JS_NewDependentString(JSContext * cx,HandleString str,size_t start,size_t length)5031 JS_NewDependentString(JSContext* cx, HandleString str, size_t start, size_t length)
5032 {
5033     AssertHeapIsIdle(cx);
5034     CHECK_REQUEST(cx);
5035     return NewDependentString(cx, str, start, length);
5036 }
5037 
5038 JS_PUBLIC_API(JSString*)
JS_ConcatStrings(JSContext * cx,HandleString left,HandleString right)5039 JS_ConcatStrings(JSContext* cx, HandleString left, HandleString right)
5040 {
5041     AssertHeapIsIdle(cx);
5042     CHECK_REQUEST(cx);
5043     return ConcatStrings<CanGC>(cx, left, right);
5044 }
5045 
5046 JS_PUBLIC_API(bool)
JS_DecodeBytes(JSContext * cx,const char * src,size_t srclen,char16_t * dst,size_t * dstlenp)5047 JS_DecodeBytes(JSContext* cx, const char* src, size_t srclen, char16_t* dst, size_t* dstlenp)
5048 {
5049     AssertHeapIsIdle(cx);
5050     CHECK_REQUEST(cx);
5051 
5052     if (!dst) {
5053         *dstlenp = srclen;
5054         return true;
5055     }
5056 
5057     size_t dstlen = *dstlenp;
5058 
5059     if (srclen > dstlen) {
5060         CopyAndInflateChars(dst, src, dstlen);
5061 
5062         AutoSuppressGC suppress(cx);
5063         JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_BUFFER_TOO_SMALL);
5064         return false;
5065     }
5066 
5067     CopyAndInflateChars(dst, src, srclen);
5068     *dstlenp = srclen;
5069     return true;
5070 }
5071 
5072 static char*
EncodeLatin1(ExclusiveContext * cx,JSString * str)5073 EncodeLatin1(ExclusiveContext* cx, JSString* str)
5074 {
5075     JSLinearString* linear = str->ensureLinear(cx);
5076     if (!linear)
5077         return nullptr;
5078 
5079     JS::AutoCheckCannotGC nogc;
5080     if (linear->hasTwoByteChars())
5081         return JS::LossyTwoByteCharsToNewLatin1CharsZ(cx, linear->twoByteRange(nogc)).c_str();
5082 
5083     size_t len = str->length();
5084     Latin1Char* buf = cx->pod_malloc<Latin1Char>(len + 1);
5085     if (!buf) {
5086         ReportOutOfMemory(cx);
5087         return nullptr;
5088     }
5089 
5090     mozilla::PodCopy(buf, linear->latin1Chars(nogc), len);
5091     buf[len] = '\0';
5092     return reinterpret_cast<char*>(buf);
5093 }
5094 
5095 JS_PUBLIC_API(char*)
JS_EncodeString(JSContext * cx,JSString * str)5096 JS_EncodeString(JSContext* cx, JSString* str)
5097 {
5098     AssertHeapIsIdle(cx);
5099     CHECK_REQUEST(cx);
5100 
5101     return EncodeLatin1(cx, str);
5102 }
5103 
5104 JS_PUBLIC_API(char*)
JS_EncodeStringToUTF8(JSContext * cx,HandleString str)5105 JS_EncodeStringToUTF8(JSContext* cx, HandleString str)
5106 {
5107     AssertHeapIsIdle(cx);
5108     CHECK_REQUEST(cx);
5109 
5110     JSLinearString* linear = str->ensureLinear(cx);
5111     if (!linear)
5112         return nullptr;
5113 
5114     JS::AutoCheckCannotGC nogc;
5115     return linear->hasLatin1Chars()
5116            ? JS::CharsToNewUTF8CharsZ(cx, linear->latin1Range(nogc)).c_str()
5117            : JS::CharsToNewUTF8CharsZ(cx, linear->twoByteRange(nogc)).c_str();
5118 }
5119 
5120 JS_PUBLIC_API(size_t)
JS_GetStringEncodingLength(JSContext * cx,JSString * str)5121 JS_GetStringEncodingLength(JSContext* cx, JSString* str)
5122 {
5123     AssertHeapIsIdle(cx);
5124     CHECK_REQUEST(cx);
5125 
5126     if (!str->ensureLinear(cx))
5127         return size_t(-1);
5128     return str->length();
5129 }
5130 
5131 JS_PUBLIC_API(size_t)
JS_EncodeStringToBuffer(JSContext * cx,JSString * str,char * buffer,size_t length)5132 JS_EncodeStringToBuffer(JSContext* cx, JSString* str, char* buffer, size_t length)
5133 {
5134     AssertHeapIsIdle(cx);
5135     CHECK_REQUEST(cx);
5136 
5137     /*
5138      * FIXME bug 612141 - fix DeflateStringToBuffer interface so the result
5139      * would allow to distinguish between insufficient buffer and encoding
5140      * error.
5141      */
5142     size_t writtenLength = length;
5143     JSLinearString* linear = str->ensureLinear(cx);
5144     if (!linear)
5145          return size_t(-1);
5146 
5147     bool res;
5148     if (linear->hasLatin1Chars()) {
5149         JS::AutoCheckCannotGC nogc;
5150         res = DeflateStringToBuffer(nullptr, linear->latin1Chars(nogc), linear->length(), buffer,
5151                                     &writtenLength);
5152     } else {
5153         JS::AutoCheckCannotGC nogc;
5154         res = DeflateStringToBuffer(nullptr, linear->twoByteChars(nogc), linear->length(), buffer,
5155                                     &writtenLength);
5156     }
5157     if (res) {
5158         MOZ_ASSERT(writtenLength <= length);
5159         return writtenLength;
5160     }
5161     MOZ_ASSERT(writtenLength <= length);
5162     size_t necessaryLength = str->length();
5163     if (necessaryLength == size_t(-1))
5164         return size_t(-1);
5165     MOZ_ASSERT(writtenLength == length); // C strings are NOT encoded.
5166     return necessaryLength;
5167 }
5168 
JS_PUBLIC_API(JS::Symbol *)5169 JS_PUBLIC_API(JS::Symbol*)
5170 JS::NewSymbol(JSContext* cx, HandleString description)
5171 {
5172     AssertHeapIsIdle(cx);
5173     CHECK_REQUEST(cx);
5174     if (description)
5175         assertSameCompartment(cx, description);
5176 
5177     return Symbol::new_(cx, SymbolCode::UniqueSymbol, description);
5178 }
5179 
JS_PUBLIC_API(JS::Symbol *)5180 JS_PUBLIC_API(JS::Symbol*)
5181 JS::GetSymbolFor(JSContext* cx, HandleString key)
5182 {
5183     AssertHeapIsIdle(cx);
5184     CHECK_REQUEST(cx);
5185     assertSameCompartment(cx, key);
5186 
5187     return Symbol::for_(cx, key);
5188 }
5189 
JS_PUBLIC_API(JSString *)5190 JS_PUBLIC_API(JSString*)
5191 JS::GetSymbolDescription(HandleSymbol symbol)
5192 {
5193     return symbol->description();
5194 }
5195 
JS_PUBLIC_API(JS::SymbolCode)5196 JS_PUBLIC_API(JS::SymbolCode)
5197 JS::GetSymbolCode(Handle<Symbol*> symbol)
5198 {
5199     return symbol->code();
5200 }
5201 
JS_PUBLIC_API(JS::Symbol *)5202 JS_PUBLIC_API(JS::Symbol*)
5203 JS::GetWellKnownSymbol(JSContext* cx, JS::SymbolCode which)
5204 {
5205     return cx->wellKnownSymbols().get(uint32_t(which));
5206 }
5207 
5208 #ifdef DEBUG
5209 static bool
PropertySpecNameIsDigits(const char * s)5210 PropertySpecNameIsDigits(const char* s) {
5211     if (JS::PropertySpecNameIsSymbol(s))
5212         return false;
5213     if (!*s)
5214         return false;
5215     for (; *s; s++) {
5216         if (*s < '0' || *s > '9')
5217             return false;
5218     }
5219     return true;
5220 }
5221 #endif // DEBUG
5222 
JS_PUBLIC_API(bool)5223 JS_PUBLIC_API(bool)
5224 JS::PropertySpecNameEqualsId(const char* name, HandleId id)
5225 {
5226     if (JS::PropertySpecNameIsSymbol(name)) {
5227         if (!JSID_IS_SYMBOL(id))
5228             return false;
5229         Symbol* sym = JSID_TO_SYMBOL(id);
5230         return sym->isWellKnownSymbol() && sym->code() == PropertySpecNameToSymbolCode(name);
5231     }
5232 
5233     MOZ_ASSERT(!PropertySpecNameIsDigits(name));
5234     return JSID_IS_ATOM(id) && JS_FlatStringEqualsAscii(JSID_TO_ATOM(id), name);
5235 }
5236 
5237 JS_PUBLIC_API(bool)
JS_Stringify(JSContext * cx,MutableHandleValue vp,HandleObject replacer,HandleValue space,JSONWriteCallback callback,void * data)5238 JS_Stringify(JSContext* cx, MutableHandleValue vp, HandleObject replacer,
5239              HandleValue space, JSONWriteCallback callback, void* data)
5240 {
5241     AssertHeapIsIdle(cx);
5242     CHECK_REQUEST(cx);
5243     assertSameCompartment(cx, replacer, space);
5244     StringBuffer sb(cx);
5245     if (!sb.ensureTwoByteChars())
5246         return false;
5247     if (!Stringify(cx, vp, replacer, space, sb))
5248         return false;
5249     if (sb.empty() && !sb.append(cx->names().null))
5250         return false;
5251     return callback(sb.rawTwoByteBegin(), sb.length(), data);
5252 }
5253 
5254 JS_PUBLIC_API(bool)
JS_ParseJSON(JSContext * cx,const char16_t * chars,uint32_t len,MutableHandleValue vp)5255 JS_ParseJSON(JSContext* cx, const char16_t* chars, uint32_t len, MutableHandleValue vp)
5256 {
5257     AssertHeapIsIdle(cx);
5258     CHECK_REQUEST(cx);
5259     return ParseJSONWithReviver(cx, mozilla::Range<const char16_t>(chars, len), NullHandleValue, vp);
5260 }
5261 
5262 JS_PUBLIC_API(bool)
JS_ParseJSON(JSContext * cx,HandleString str,MutableHandleValue vp)5263 JS_ParseJSON(JSContext* cx, HandleString str, MutableHandleValue vp)
5264 {
5265     return JS_ParseJSONWithReviver(cx, str, NullHandleValue, vp);
5266 }
5267 
5268 JS_PUBLIC_API(bool)
JS_ParseJSONWithReviver(JSContext * cx,const char16_t * chars,uint32_t len,HandleValue reviver,MutableHandleValue vp)5269 JS_ParseJSONWithReviver(JSContext* cx, const char16_t* chars, uint32_t len, HandleValue reviver, MutableHandleValue vp)
5270 {
5271     AssertHeapIsIdle(cx);
5272     CHECK_REQUEST(cx);
5273     return ParseJSONWithReviver(cx, mozilla::Range<const char16_t>(chars, len), reviver, vp);
5274 }
5275 
5276 JS_PUBLIC_API(bool)
JS_ParseJSONWithReviver(JSContext * cx,HandleString str,HandleValue reviver,MutableHandleValue vp)5277 JS_ParseJSONWithReviver(JSContext* cx, HandleString str, HandleValue reviver, MutableHandleValue vp)
5278 {
5279     AssertHeapIsIdle(cx);
5280     CHECK_REQUEST(cx);
5281     assertSameCompartment(cx, str);
5282 
5283     AutoStableStringChars stableChars(cx);
5284     if (!stableChars.init(cx, str))
5285         return false;
5286 
5287     return stableChars.isLatin1()
5288            ? ParseJSONWithReviver(cx, stableChars.latin1Range(), reviver, vp)
5289            : ParseJSONWithReviver(cx, stableChars.twoByteRange(), reviver, vp);
5290 }
5291 
5292 /************************************************************************/
5293 
5294 JS_PUBLIC_API(void)
JS_ReportError(JSContext * cx,const char * format,...)5295 JS_ReportError(JSContext* cx, const char* format, ...)
5296 {
5297     va_list ap;
5298 
5299     AssertHeapIsIdle(cx);
5300     va_start(ap, format);
5301     ReportErrorVA(cx, JSREPORT_ERROR, format, ap);
5302     va_end(ap);
5303 }
5304 
5305 JS_PUBLIC_API(void)
JS_ReportErrorNumber(JSContext * cx,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,...)5306 JS_ReportErrorNumber(JSContext* cx, JSErrorCallback errorCallback,
5307                      void* userRef, const unsigned errorNumber, ...)
5308 {
5309     va_list ap;
5310     va_start(ap, errorNumber);
5311     JS_ReportErrorNumberVA(cx, errorCallback, userRef, errorNumber, ap);
5312     va_end(ap);
5313 }
5314 
5315 JS_PUBLIC_API(void)
JS_ReportErrorNumberVA(JSContext * cx,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,va_list ap)5316 JS_ReportErrorNumberVA(JSContext* cx, JSErrorCallback errorCallback,
5317                        void* userRef, const unsigned errorNumber,
5318                        va_list ap)
5319 {
5320     AssertHeapIsIdle(cx);
5321     ReportErrorNumberVA(cx, JSREPORT_ERROR, errorCallback, userRef,
5322                         errorNumber, ArgumentsAreASCII, ap);
5323 }
5324 
5325 JS_PUBLIC_API(void)
JS_ReportErrorNumberUC(JSContext * cx,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,...)5326 JS_ReportErrorNumberUC(JSContext* cx, JSErrorCallback errorCallback,
5327                        void* userRef, const unsigned errorNumber, ...)
5328 {
5329     va_list ap;
5330 
5331     AssertHeapIsIdle(cx);
5332     va_start(ap, errorNumber);
5333     ReportErrorNumberVA(cx, JSREPORT_ERROR, errorCallback, userRef,
5334                         errorNumber, ArgumentsAreUnicode, ap);
5335     va_end(ap);
5336 }
5337 
5338 JS_PUBLIC_API(void)
JS_ReportErrorNumberUCArray(JSContext * cx,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,const char16_t ** args)5339 JS_ReportErrorNumberUCArray(JSContext* cx, JSErrorCallback errorCallback,
5340                             void* userRef, const unsigned errorNumber,
5341                             const char16_t** args)
5342 {
5343     AssertHeapIsIdle(cx);
5344     ReportErrorNumberUCArray(cx, JSREPORT_ERROR, errorCallback, userRef,
5345                              errorNumber, args);
5346 }
5347 
5348 JS_PUBLIC_API(bool)
JS_ReportWarning(JSContext * cx,const char * format,...)5349 JS_ReportWarning(JSContext* cx, const char* format, ...)
5350 {
5351     va_list ap;
5352     bool ok;
5353 
5354     AssertHeapIsIdle(cx);
5355     va_start(ap, format);
5356     ok = ReportErrorVA(cx, JSREPORT_WARNING, format, ap);
5357     va_end(ap);
5358     return ok;
5359 }
5360 
5361 JS_PUBLIC_API(bool)
JS_ReportErrorFlagsAndNumber(JSContext * cx,unsigned flags,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,...)5362 JS_ReportErrorFlagsAndNumber(JSContext* cx, unsigned flags,
5363                              JSErrorCallback errorCallback, void* userRef,
5364                              const unsigned errorNumber, ...)
5365 {
5366     va_list ap;
5367     bool ok;
5368 
5369     AssertHeapIsIdle(cx);
5370     va_start(ap, errorNumber);
5371     ok = ReportErrorNumberVA(cx, flags, errorCallback, userRef,
5372                              errorNumber, ArgumentsAreASCII, ap);
5373     va_end(ap);
5374     return ok;
5375 }
5376 
5377 JS_PUBLIC_API(bool)
JS_ReportErrorFlagsAndNumberUC(JSContext * cx,unsigned flags,JSErrorCallback errorCallback,void * userRef,const unsigned errorNumber,...)5378 JS_ReportErrorFlagsAndNumberUC(JSContext* cx, unsigned flags,
5379                                JSErrorCallback errorCallback, void* userRef,
5380                                const unsigned errorNumber, ...)
5381 {
5382     va_list ap;
5383     bool ok;
5384 
5385     AssertHeapIsIdle(cx);
5386     va_start(ap, errorNumber);
5387     ok = ReportErrorNumberVA(cx, flags, errorCallback, userRef,
5388                              errorNumber, ArgumentsAreUnicode, ap);
5389     va_end(ap);
5390     return ok;
5391 }
5392 
5393 JS_PUBLIC_API(void)
JS_ReportOutOfMemory(JSContext * cx)5394 JS_ReportOutOfMemory(JSContext* cx)
5395 {
5396     ReportOutOfMemory(cx);
5397 }
5398 
5399 JS_PUBLIC_API(void)
JS_ReportAllocationOverflow(JSContext * cx)5400 JS_ReportAllocationOverflow(JSContext* cx)
5401 {
5402     ReportAllocationOverflow(cx);
5403 }
5404 
5405 JS_PUBLIC_API(JSErrorReporter)
JS_GetErrorReporter(JSRuntime * rt)5406 JS_GetErrorReporter(JSRuntime* rt)
5407 {
5408     return rt->errorReporter;
5409 }
5410 
5411 JS_PUBLIC_API(JSErrorReporter)
JS_SetErrorReporter(JSRuntime * rt,JSErrorReporter er)5412 JS_SetErrorReporter(JSRuntime* rt, JSErrorReporter er)
5413 {
5414     JSErrorReporter older;
5415 
5416     older = rt->errorReporter;
5417     rt->errorReporter = er;
5418     return older;
5419 }
5420 
5421 /************************************************************************/
5422 
5423 /*
5424  * Dates.
5425  */
5426 JS_PUBLIC_API(JSObject*)
JS_NewDateObject(JSContext * cx,int year,int mon,int mday,int hour,int min,int sec)5427 JS_NewDateObject(JSContext* cx, int year, int mon, int mday, int hour, int min, int sec)
5428 {
5429     AssertHeapIsIdle(cx);
5430     CHECK_REQUEST(cx);
5431     return NewDateObject(cx, year, mon, mday, hour, min, sec);
5432 }
5433 
JS_PUBLIC_API(JSObject *)5434 JS_PUBLIC_API(JSObject*)
5435 JS::NewDateObject(JSContext* cx, JS::ClippedTime time)
5436 {
5437     AssertHeapIsIdle(cx);
5438     CHECK_REQUEST(cx);
5439     return NewDateObjectMsec(cx, time);
5440 }
5441 
5442 JS_PUBLIC_API(bool)
JS_ObjectIsDate(JSContext * cx,HandleObject obj,bool * isDate)5443 JS_ObjectIsDate(JSContext* cx, HandleObject obj, bool* isDate)
5444 {
5445     assertSameCompartment(cx, obj);
5446 
5447     ESClassValue cls;
5448     if (!GetBuiltinClass(cx, obj, &cls))
5449         return false;
5450 
5451     *isDate = cls == ESClass_Date;
5452     return true;
5453 }
5454 
5455 /************************************************************************/
5456 
5457 /*
5458  * Regular Expressions.
5459  */
5460 JS_PUBLIC_API(JSObject*)
JS_NewRegExpObject(JSContext * cx,HandleObject obj,const char * bytes,size_t length,unsigned flags)5461 JS_NewRegExpObject(JSContext* cx, HandleObject obj, const char* bytes, size_t length, unsigned flags)
5462 {
5463     AssertHeapIsIdle(cx);
5464     CHECK_REQUEST(cx);
5465     ScopedJSFreePtr<char16_t> chars(InflateString(cx, bytes, &length));
5466     if (!chars)
5467         return nullptr;
5468 
5469     RegExpStatics* res = obj->as<GlobalObject>().getRegExpStatics(cx);
5470     if (!res)
5471         return nullptr;
5472 
5473     RegExpObject* reobj = RegExpObject::create(cx, res, chars, length,
5474                                                RegExpFlag(flags), nullptr, cx->tempLifoAlloc());
5475     return reobj;
5476 }
5477 
5478 JS_PUBLIC_API(JSObject*)
JS_NewUCRegExpObject(JSContext * cx,HandleObject obj,const char16_t * chars,size_t length,unsigned flags)5479 JS_NewUCRegExpObject(JSContext* cx, HandleObject obj, const char16_t* chars, size_t length,
5480                      unsigned flags)
5481 {
5482     AssertHeapIsIdle(cx);
5483     CHECK_REQUEST(cx);
5484     RegExpStatics* res = obj->as<GlobalObject>().getRegExpStatics(cx);
5485     if (!res)
5486         return nullptr;
5487 
5488     return RegExpObject::create(cx, res, chars, length,
5489                                 RegExpFlag(flags), nullptr, cx->tempLifoAlloc());
5490 }
5491 
5492 JS_PUBLIC_API(bool)
JS_SetRegExpInput(JSContext * cx,HandleObject obj,HandleString input,bool multiline)5493 JS_SetRegExpInput(JSContext* cx, HandleObject obj, HandleString input, bool multiline)
5494 {
5495     AssertHeapIsIdle(cx);
5496     CHECK_REQUEST(cx);
5497     assertSameCompartment(cx, input);
5498 
5499     RegExpStatics* res = obj->as<GlobalObject>().getRegExpStatics(cx);
5500     if (!res)
5501         return false;
5502 
5503     res->reset(cx, input, !!multiline);
5504     return true;
5505 }
5506 
5507 JS_PUBLIC_API(bool)
JS_ClearRegExpStatics(JSContext * cx,HandleObject obj)5508 JS_ClearRegExpStatics(JSContext* cx, HandleObject obj)
5509 {
5510     AssertHeapIsIdle(cx);
5511     CHECK_REQUEST(cx);
5512     MOZ_ASSERT(obj);
5513 
5514     RegExpStatics* res = obj->as<GlobalObject>().getRegExpStatics(cx);
5515     if (!res)
5516         return false;
5517 
5518     res->clear();
5519     return true;
5520 }
5521 
5522 JS_PUBLIC_API(bool)
JS_ExecuteRegExp(JSContext * cx,HandleObject obj,HandleObject reobj,char16_t * chars,size_t length,size_t * indexp,bool test,MutableHandleValue rval)5523 JS_ExecuteRegExp(JSContext* cx, HandleObject obj, HandleObject reobj, char16_t* chars,
5524                  size_t length, size_t* indexp, bool test, MutableHandleValue rval)
5525 {
5526     AssertHeapIsIdle(cx);
5527     CHECK_REQUEST(cx);
5528 
5529     RegExpStatics* res = obj->as<GlobalObject>().getRegExpStatics(cx);
5530     if (!res)
5531         return false;
5532 
5533     RootedLinearString input(cx, NewStringCopyN<CanGC>(cx, chars, length));
5534     if (!input)
5535         return false;
5536 
5537     return ExecuteRegExpLegacy(cx, res, reobj->as<RegExpObject>(), input, indexp, test, rval);
5538 }
5539 
5540 JS_PUBLIC_API(JSObject*)
JS_NewRegExpObjectNoStatics(JSContext * cx,char * bytes,size_t length,unsigned flags)5541 JS_NewRegExpObjectNoStatics(JSContext* cx, char* bytes, size_t length, unsigned flags)
5542 {
5543     AssertHeapIsIdle(cx);
5544     CHECK_REQUEST(cx);
5545     char16_t* chars = InflateString(cx, bytes, &length);
5546     if (!chars)
5547         return nullptr;
5548     RegExpObject* reobj = RegExpObject::createNoStatics(cx, chars, length,
5549                                                         RegExpFlag(flags), nullptr, cx->tempLifoAlloc());
5550     js_free(chars);
5551     return reobj;
5552 }
5553 
5554 JS_PUBLIC_API(JSObject*)
JS_NewUCRegExpObjectNoStatics(JSContext * cx,char16_t * chars,size_t length,unsigned flags)5555 JS_NewUCRegExpObjectNoStatics(JSContext* cx, char16_t* chars, size_t length, unsigned flags)
5556 {
5557     AssertHeapIsIdle(cx);
5558     CHECK_REQUEST(cx);
5559     return RegExpObject::createNoStatics(cx, chars, length,
5560                                          RegExpFlag(flags), nullptr, cx->tempLifoAlloc());
5561 }
5562 
5563 JS_PUBLIC_API(bool)
JS_ExecuteRegExpNoStatics(JSContext * cx,HandleObject obj,char16_t * chars,size_t length,size_t * indexp,bool test,MutableHandleValue rval)5564 JS_ExecuteRegExpNoStatics(JSContext* cx, HandleObject obj, char16_t* chars, size_t length,
5565                           size_t* indexp, bool test, MutableHandleValue rval)
5566 {
5567     AssertHeapIsIdle(cx);
5568     CHECK_REQUEST(cx);
5569 
5570     RootedLinearString input(cx, NewStringCopyN<CanGC>(cx, chars, length));
5571     if (!input)
5572         return false;
5573 
5574     return ExecuteRegExpLegacy(cx, nullptr, obj->as<RegExpObject>(), input, indexp, test,
5575                                rval);
5576 }
5577 
5578 JS_PUBLIC_API(bool)
JS_ObjectIsRegExp(JSContext * cx,HandleObject obj,bool * isRegExp)5579 JS_ObjectIsRegExp(JSContext* cx, HandleObject obj, bool* isRegExp)
5580 {
5581     assertSameCompartment(cx, obj);
5582 
5583     ESClassValue cls;
5584     if (!GetBuiltinClass(cx, obj, &cls))
5585         return false;
5586 
5587     *isRegExp = cls == ESClass_RegExp;
5588     return true;
5589 }
5590 
5591 JS_PUBLIC_API(unsigned)
JS_GetRegExpFlags(JSContext * cx,HandleObject obj)5592 JS_GetRegExpFlags(JSContext* cx, HandleObject obj)
5593 {
5594     AssertHeapIsIdle(cx);
5595     CHECK_REQUEST(cx);
5596 
5597     RegExpGuard shared(cx);
5598     if (!RegExpToShared(cx, obj, &shared))
5599         return false;
5600     return shared.re()->getFlags();
5601 }
5602 
5603 JS_PUBLIC_API(JSString*)
JS_GetRegExpSource(JSContext * cx,HandleObject obj)5604 JS_GetRegExpSource(JSContext* cx, HandleObject obj)
5605 {
5606     AssertHeapIsIdle(cx);
5607     CHECK_REQUEST(cx);
5608 
5609     RegExpGuard shared(cx);
5610     if (!RegExpToShared(cx, obj, &shared))
5611         return nullptr;
5612     return shared.re()->getSource();
5613 }
5614 
5615 /************************************************************************/
5616 
5617 JS_PUBLIC_API(bool)
JS_SetDefaultLocale(JSRuntime * rt,const char * locale)5618 JS_SetDefaultLocale(JSRuntime* rt, const char* locale)
5619 {
5620     AssertHeapIsIdle(rt);
5621     return rt->setDefaultLocale(locale);
5622 }
5623 
5624 JS_PUBLIC_API(void)
JS_ResetDefaultLocale(JSRuntime * rt)5625 JS_ResetDefaultLocale(JSRuntime* rt)
5626 {
5627     AssertHeapIsIdle(rt);
5628     rt->resetDefaultLocale();
5629 }
5630 
5631 JS_PUBLIC_API(void)
JS_SetLocaleCallbacks(JSRuntime * rt,const JSLocaleCallbacks * callbacks)5632 JS_SetLocaleCallbacks(JSRuntime* rt, const JSLocaleCallbacks* callbacks)
5633 {
5634     AssertHeapIsIdle(rt);
5635     rt->localeCallbacks = callbacks;
5636 }
5637 
5638 JS_PUBLIC_API(const JSLocaleCallbacks*)
JS_GetLocaleCallbacks(JSRuntime * rt)5639 JS_GetLocaleCallbacks(JSRuntime* rt)
5640 {
5641     /* This function can be called by a finalizer. */
5642     return rt->localeCallbacks;
5643 }
5644 
5645 /************************************************************************/
5646 
5647 JS_PUBLIC_API(bool)
JS_IsExceptionPending(JSContext * cx)5648 JS_IsExceptionPending(JSContext* cx)
5649 {
5650     /* This function can be called by a finalizer. */
5651     return (bool) cx->isExceptionPending();
5652 }
5653 
5654 JS_PUBLIC_API(bool)
JS_GetPendingException(JSContext * cx,MutableHandleValue vp)5655 JS_GetPendingException(JSContext* cx, MutableHandleValue vp)
5656 {
5657     AssertHeapIsIdle(cx);
5658     CHECK_REQUEST(cx);
5659     if (!cx->isExceptionPending())
5660         return false;
5661     return cx->getPendingException(vp);
5662 }
5663 
5664 JS_PUBLIC_API(void)
JS_SetPendingException(JSContext * cx,HandleValue value)5665 JS_SetPendingException(JSContext* cx, HandleValue value)
5666 {
5667     AssertHeapIsIdle(cx);
5668     CHECK_REQUEST(cx);
5669     assertSameCompartment(cx, value);
5670     cx->setPendingException(value);
5671 }
5672 
5673 JS_PUBLIC_API(void)
JS_ClearPendingException(JSContext * cx)5674 JS_ClearPendingException(JSContext* cx)
5675 {
5676     AssertHeapIsIdle(cx);
5677     cx->clearPendingException();
5678 }
5679 
5680 JS_PUBLIC_API(bool)
JS_ReportPendingException(JSContext * cx)5681 JS_ReportPendingException(JSContext* cx)
5682 {
5683     AssertHeapIsIdle(cx);
5684     CHECK_REQUEST(cx);
5685 
5686     // This can only fail due to oom.
5687     bool ok = ReportUncaughtException(cx);
5688     MOZ_ASSERT(!cx->isExceptionPending());
5689     return ok;
5690 }
5691 
AutoSaveExceptionState(JSContext * cx)5692 JS::AutoSaveExceptionState::AutoSaveExceptionState(JSContext* cx)
5693   : context(cx),
5694     wasPropagatingForcedReturn(cx->propagatingForcedReturn_),
5695     wasOverRecursed(cx->overRecursed_),
5696     wasThrowing(cx->throwing),
5697     exceptionValue(cx)
5698 {
5699     AssertHeapIsIdle(cx);
5700     CHECK_REQUEST(cx);
5701     if (wasPropagatingForcedReturn)
5702         cx->clearPropagatingForcedReturn();
5703     if (wasOverRecursed)
5704         cx->overRecursed_ = false;
5705     if (wasThrowing) {
5706         exceptionValue = cx->unwrappedException_;
5707         cx->clearPendingException();
5708     }
5709 }
5710 
5711 void
restore()5712 JS::AutoSaveExceptionState::restore()
5713 {
5714     context->propagatingForcedReturn_ = wasPropagatingForcedReturn;
5715     context->overRecursed_ = wasOverRecursed;
5716     context->throwing = wasThrowing;
5717     context->unwrappedException_ = exceptionValue;
5718     drop();
5719 }
5720 
~AutoSaveExceptionState()5721 JS::AutoSaveExceptionState::~AutoSaveExceptionState()
5722 {
5723     if (!context->isExceptionPending()) {
5724         if (wasPropagatingForcedReturn)
5725             context->setPropagatingForcedReturn();
5726         if (wasThrowing) {
5727             context->overRecursed_ = wasOverRecursed;
5728             context->throwing = true;
5729             context->unwrappedException_ = exceptionValue;
5730         }
5731     }
5732 }
5733 
5734 struct JSExceptionState {
JSExceptionStateJSExceptionState5735     explicit JSExceptionState(JSContext* cx) : exception(cx) {}
5736     bool throwing;
5737     PersistentRootedValue exception;
5738 };
5739 
5740 JS_PUBLIC_API(JSExceptionState*)
JS_SaveExceptionState(JSContext * cx)5741 JS_SaveExceptionState(JSContext* cx)
5742 {
5743     JSExceptionState* state;
5744 
5745     AssertHeapIsIdle(cx);
5746     CHECK_REQUEST(cx);
5747     state = cx->new_<JSExceptionState>(cx);
5748     if (state)
5749         state->throwing = JS_GetPendingException(cx, &state->exception);
5750     return state;
5751 }
5752 
5753 JS_PUBLIC_API(void)
JS_RestoreExceptionState(JSContext * cx,JSExceptionState * state)5754 JS_RestoreExceptionState(JSContext* cx, JSExceptionState* state)
5755 {
5756     AssertHeapIsIdle(cx);
5757     CHECK_REQUEST(cx);
5758     if (state) {
5759         if (state->throwing)
5760             JS_SetPendingException(cx, state->exception);
5761         else
5762             JS_ClearPendingException(cx);
5763         JS_DropExceptionState(cx, state);
5764     }
5765 }
5766 
5767 JS_PUBLIC_API(void)
JS_DropExceptionState(JSContext * cx,JSExceptionState * state)5768 JS_DropExceptionState(JSContext* cx, JSExceptionState* state)
5769 {
5770     AssertHeapIsIdle(cx);
5771     CHECK_REQUEST(cx);
5772     js_delete(state);
5773 }
5774 
5775 JS_PUBLIC_API(JSErrorReport*)
JS_ErrorFromException(JSContext * cx,HandleObject obj)5776 JS_ErrorFromException(JSContext* cx, HandleObject obj)
5777 {
5778     AssertHeapIsIdle(cx);
5779     CHECK_REQUEST(cx);
5780     assertSameCompartment(cx, obj);
5781     return ErrorFromException(cx, obj);
5782 }
5783 
5784 void
initLinebuf(const char16_t * linebuf,size_t linebufLength,size_t tokenOffset)5785 JSErrorReport::initLinebuf(const char16_t* linebuf, size_t linebufLength, size_t tokenOffset)
5786 {
5787     MOZ_ASSERT(linebuf);
5788     MOZ_ASSERT(tokenOffset <= linebufLength);
5789     MOZ_ASSERT(linebuf[linebufLength] == '\0');
5790 
5791     linebuf_ = linebuf;
5792     linebufLength_ = linebufLength;
5793     tokenOffset_ = tokenOffset;
5794 }
5795 
5796 JS_PUBLIC_API(bool)
JS_ThrowStopIteration(JSContext * cx)5797 JS_ThrowStopIteration(JSContext* cx)
5798 {
5799     AssertHeapIsIdle(cx);
5800     return ThrowStopIteration(cx);
5801 }
5802 
5803 JS_PUBLIC_API(bool)
JS_IsStopIteration(Value v)5804 JS_IsStopIteration(Value v)
5805 {
5806     return v.isObject() && v.toObject().is<StopIterationObject>();
5807 }
5808 
5809 JS_PUBLIC_API(intptr_t)
JS_GetCurrentThread()5810 JS_GetCurrentThread()
5811 {
5812     return reinterpret_cast<intptr_t>(PR_GetCurrentThread());
5813 }
5814 
JS_PUBLIC_API(void)5815 extern MOZ_NEVER_INLINE JS_PUBLIC_API(void)
5816 JS_AbortIfWrongThread(JSRuntime* rt)
5817 {
5818     if (!CurrentThreadCanAccessRuntime(rt))
5819         MOZ_CRASH();
5820     if (!js::TlsPerThreadData.get()->associatedWith(rt))
5821         MOZ_CRASH();
5822 }
5823 
5824 #ifdef JS_GC_ZEAL
5825 JS_PUBLIC_API(void)
JS_GetGCZeal(JSContext * cx,uint8_t * zeal,uint32_t * frequency,uint32_t * nextScheduled)5826 JS_GetGCZeal(JSContext* cx, uint8_t* zeal, uint32_t* frequency, uint32_t* nextScheduled)
5827 {
5828     cx->runtime()->gc.getZeal(zeal, frequency, nextScheduled);
5829 }
5830 
5831 JS_PUBLIC_API(void)
JS_SetGCZeal(JSContext * cx,uint8_t zeal,uint32_t frequency)5832 JS_SetGCZeal(JSContext* cx, uint8_t zeal, uint32_t frequency)
5833 {
5834     cx->runtime()->gc.setZeal(zeal, frequency);
5835 }
5836 
5837 JS_PUBLIC_API(void)
JS_ScheduleGC(JSContext * cx,uint32_t count)5838 JS_ScheduleGC(JSContext* cx, uint32_t count)
5839 {
5840     cx->runtime()->gc.setNextScheduled(count);
5841 }
5842 #endif
5843 
5844 JS_PUBLIC_API(void)
JS_SetParallelParsingEnabled(JSRuntime * rt,bool enabled)5845 JS_SetParallelParsingEnabled(JSRuntime* rt, bool enabled)
5846 {
5847     rt->setParallelParsingEnabled(enabled);
5848 }
5849 
5850 JS_PUBLIC_API(void)
JS_SetOffthreadIonCompilationEnabled(JSRuntime * rt,bool enabled)5851 JS_SetOffthreadIonCompilationEnabled(JSRuntime* rt, bool enabled)
5852 {
5853     rt->setOffthreadIonCompilationEnabled(enabled);
5854 }
5855 
5856 JS_PUBLIC_API(void)
JS_SetGlobalJitCompilerOption(JSRuntime * rt,JSJitCompilerOption opt,uint32_t value)5857 JS_SetGlobalJitCompilerOption(JSRuntime* rt, JSJitCompilerOption opt, uint32_t value)
5858 {
5859     switch (opt) {
5860       case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER:
5861         if (value == uint32_t(-1)) {
5862             jit::DefaultJitOptions defaultValues;
5863             value = defaultValues.baselineWarmUpThreshold;
5864         }
5865         jit::JitOptions.baselineWarmUpThreshold = value;
5866         break;
5867       case JSJITCOMPILER_ION_WARMUP_TRIGGER:
5868         if (value == uint32_t(-1)) {
5869             jit::JitOptions.resetCompilerWarmUpThreshold();
5870             break;
5871         }
5872         jit::JitOptions.setCompilerWarmUpThreshold(value);
5873         if (value == 0)
5874             jit::JitOptions.setEagerCompilation();
5875         break;
5876       case JSJITCOMPILER_ION_GVN_ENABLE:
5877         if (value == 0) {
5878             jit::JitOptions.enableGvn(false);
5879             JitSpew(js::jit::JitSpew_IonScripts, "Disable ion's GVN");
5880         } else {
5881             jit::JitOptions.enableGvn(true);
5882             JitSpew(js::jit::JitSpew_IonScripts, "Enable ion's GVN");
5883         }
5884         break;
5885       case JSJITCOMPILER_ION_FORCE_IC:
5886         if (value == 0) {
5887             jit::JitOptions.forceInlineCaches = false;
5888             JitSpew(js::jit::JitSpew_IonScripts, "IonBuilder: Enable non-IC optimizations.");
5889         } else {
5890             jit::JitOptions.forceInlineCaches = true;
5891             JitSpew(js::jit::JitSpew_IonScripts, "IonBuilder: Disable non-IC optimizations.");
5892         }
5893         break;
5894       case JSJITCOMPILER_ION_ENABLE:
5895         if (value == 1) {
5896             JS::RuntimeOptionsRef(rt).setIon(true);
5897             JitSpew(js::jit::JitSpew_IonScripts, "Enable ion");
5898         } else if (value == 0) {
5899             JS::RuntimeOptionsRef(rt).setIon(false);
5900             JitSpew(js::jit::JitSpew_IonScripts, "Disable ion");
5901         }
5902         break;
5903       case JSJITCOMPILER_BASELINE_ENABLE:
5904         if (value == 1) {
5905             JS::RuntimeOptionsRef(rt).setBaseline(true);
5906             ReleaseAllJITCode(rt->defaultFreeOp());
5907             JitSpew(js::jit::JitSpew_BaselineScripts, "Enable baseline");
5908         } else if (value == 0) {
5909             JS::RuntimeOptionsRef(rt).setBaseline(false);
5910             ReleaseAllJITCode(rt->defaultFreeOp());
5911             JitSpew(js::jit::JitSpew_BaselineScripts, "Disable baseline");
5912         }
5913         break;
5914       case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE:
5915         if (value == 1) {
5916             rt->setOffthreadIonCompilationEnabled(true);
5917             JitSpew(js::jit::JitSpew_IonScripts, "Enable offthread compilation");
5918         } else if (value == 0) {
5919             rt->setOffthreadIonCompilationEnabled(false);
5920             JitSpew(js::jit::JitSpew_IonScripts, "Disable offthread compilation");
5921         }
5922         break;
5923       case JSJITCOMPILER_SIGNALS_ENABLE:
5924         if (value == 1) {
5925             rt->setCanUseSignalHandlers(true);
5926             JitSpew(js::jit::JitSpew_IonScripts, "Enable signals");
5927         } else if (value == 0) {
5928             rt->setCanUseSignalHandlers(false);
5929             JitSpew(js::jit::JitSpew_IonScripts, "Disable signals");
5930         }
5931         break;
5932       default:
5933         break;
5934     }
5935 }
5936 
5937 JS_PUBLIC_API(int)
JS_GetGlobalJitCompilerOption(JSRuntime * rt,JSJitCompilerOption opt)5938 JS_GetGlobalJitCompilerOption(JSRuntime* rt, JSJitCompilerOption opt)
5939 {
5940 #ifndef JS_CODEGEN_NONE
5941     switch (opt) {
5942       case JSJITCOMPILER_BASELINE_WARMUP_TRIGGER:
5943         return jit::JitOptions.baselineWarmUpThreshold;
5944       case JSJITCOMPILER_ION_WARMUP_TRIGGER:
5945         return jit::JitOptions.forcedDefaultIonWarmUpThreshold.isSome()
5946              ? jit::JitOptions.forcedDefaultIonWarmUpThreshold.ref()
5947              : jit::OptimizationInfo::CompilerWarmupThreshold;
5948       case JSJITCOMPILER_ION_FORCE_IC:
5949         return jit::JitOptions.forceInlineCaches;
5950       case JSJITCOMPILER_ION_ENABLE:
5951         return JS::RuntimeOptionsRef(rt).ion();
5952       case JSJITCOMPILER_BASELINE_ENABLE:
5953         return JS::RuntimeOptionsRef(rt).baseline();
5954       case JSJITCOMPILER_OFFTHREAD_COMPILATION_ENABLE:
5955         return rt->canUseOffthreadIonCompilation();
5956       case JSJITCOMPILER_SIGNALS_ENABLE:
5957         return rt->canUseSignalHandlers();
5958       default:
5959         break;
5960     }
5961 #endif
5962     return 0;
5963 }
5964 
5965 /************************************************************************/
5966 
5967 #if !defined(STATIC_EXPORTABLE_JS_API) && !defined(STATIC_JS_API) && defined(XP_WIN)
5968 
5969 #include "jswin.h"
5970 
5971 /*
5972  * Initialization routine for the JS DLL.
5973  */
DllMain(HINSTANCE hDLL,DWORD dwReason,LPVOID lpReserved)5974 BOOL WINAPI DllMain (HINSTANCE hDLL, DWORD dwReason, LPVOID lpReserved)
5975 {
5976     return TRUE;
5977 }
5978 
5979 #endif
5980 
5981 JS_PUBLIC_API(bool)
JS_IndexToId(JSContext * cx,uint32_t index,MutableHandleId id)5982 JS_IndexToId(JSContext* cx, uint32_t index, MutableHandleId id)
5983 {
5984     return IndexToId(cx, index, id);
5985 }
5986 
5987 JS_PUBLIC_API(bool)
JS_CharsToId(JSContext * cx,JS::TwoByteChars chars,MutableHandleId idp)5988 JS_CharsToId(JSContext* cx, JS::TwoByteChars chars, MutableHandleId idp)
5989 {
5990     RootedAtom atom(cx, AtomizeChars(cx, chars.start().get(), chars.length()));
5991     if (!atom)
5992         return false;
5993 #ifdef DEBUG
5994     uint32_t dummy;
5995     MOZ_ASSERT(!atom->isIndex(&dummy), "API misuse: |chars| must not encode an index");
5996 #endif
5997     idp.set(AtomToId(atom));
5998     return true;
5999 }
6000 
6001 JS_PUBLIC_API(bool)
JS_IsIdentifier(JSContext * cx,HandleString str,bool * isIdentifier)6002 JS_IsIdentifier(JSContext* cx, HandleString str, bool* isIdentifier)
6003 {
6004     assertSameCompartment(cx, str);
6005 
6006     JSLinearString* linearStr = str->ensureLinear(cx);
6007     if (!linearStr)
6008         return false;
6009 
6010     *isIdentifier = js::frontend::IsIdentifier(linearStr);
6011     return true;
6012 }
6013 
6014 JS_PUBLIC_API(bool)
JS_IsIdentifier(const char16_t * chars,size_t length)6015 JS_IsIdentifier(const char16_t* chars, size_t length)
6016 {
6017     return js::frontend::IsIdentifier(chars, length);
6018 }
6019 
6020 namespace JS {
6021 
6022 void
reset(void * newScriptSource)6023 AutoFilename::reset(void* newScriptSource)
6024 {
6025     if (newScriptSource)
6026         reinterpret_cast<ScriptSource*>(newScriptSource)->incref();
6027     if (scriptSource_)
6028         reinterpret_cast<ScriptSource*>(scriptSource_)->decref();
6029     scriptSource_ = newScriptSource;
6030 }
6031 
6032 const char*
get() const6033 AutoFilename::get() const
6034 {
6035     return scriptSource_ ? reinterpret_cast<ScriptSource*>(scriptSource_)->filename() : nullptr;
6036 }
6037 
6038 JS_PUBLIC_API(bool)
DescribeScriptedCaller(JSContext * cx,AutoFilename * filename,unsigned * lineno,unsigned * column)6039 DescribeScriptedCaller(JSContext* cx, AutoFilename* filename, unsigned* lineno,
6040                        unsigned* column)
6041 {
6042     if (lineno)
6043         *lineno = 0;
6044     if (column)
6045         *column = 0;
6046 
6047     NonBuiltinFrameIter i(cx);
6048     if (i.done())
6049         return false;
6050 
6051     // If the caller is hidden, the embedding wants us to return false here so
6052     // that it can check its own stack (see HideScriptedCaller).
6053     if (i.activation()->scriptedCallerIsHidden())
6054         return false;
6055 
6056     if (filename)
6057         filename->reset(i.scriptSource());
6058 
6059     if (lineno)
6060         *lineno = i.computeLine(column);
6061     else if (column)
6062         i.computeLine(column);
6063 
6064     return true;
6065 }
6066 
6067 JS_PUBLIC_API(JSObject*)
GetScriptedCallerGlobal(JSContext * cx)6068 GetScriptedCallerGlobal(JSContext* cx)
6069 {
6070     NonBuiltinFrameIter i(cx);
6071     if (i.done())
6072         return nullptr;
6073 
6074     // If the caller is hidden, the embedding wants us to return null here so
6075     // that it can check its own stack (see HideScriptedCaller).
6076     if (i.activation()->scriptedCallerIsHidden())
6077         return nullptr;
6078 
6079     GlobalObject* global = i.activation()->compartment()->maybeGlobal();
6080 
6081     // Noone should be running code in the atoms compartment or running code in
6082     // a compartment without any live objects, so there should definitely be a
6083     // live global.
6084     MOZ_ASSERT(global);
6085 
6086     return global;
6087 }
6088 
6089 JS_PUBLIC_API(void)
HideScriptedCaller(JSContext * cx)6090 HideScriptedCaller(JSContext* cx)
6091 {
6092     MOZ_ASSERT(cx);
6093 
6094     // If there's no accessible activation on the stack, we'll return null from
6095     // DescribeScriptedCaller anyway, so there's no need to annotate anything.
6096     Activation* act = cx->runtime()->activation();
6097     if (!act)
6098         return;
6099     act->hideScriptedCaller();
6100 }
6101 
6102 JS_PUBLIC_API(void)
UnhideScriptedCaller(JSContext * cx)6103 UnhideScriptedCaller(JSContext* cx)
6104 {
6105     Activation* act = cx->runtime()->activation();
6106     if (!act)
6107         return;
6108     act->unhideScriptedCaller();
6109 }
6110 
6111 } /* namespace JS */
6112 
6113 static PRStatus
CallOnce(void * func)6114 CallOnce(void* func)
6115 {
6116     JSInitCallback init = JS_DATA_TO_FUNC_PTR(JSInitCallback, func);
6117     return init() ? PR_SUCCESS : PR_FAILURE;
6118 }
6119 
6120 JS_PUBLIC_API(bool)
JS_CallOnce(JSCallOnceType * once,JSInitCallback func)6121 JS_CallOnce(JSCallOnceType* once, JSInitCallback func)
6122 {
6123     return PR_CallOnceWithArg(once, CallOnce, JS_FUNC_TO_DATA_PTR(void*, func)) == PR_SUCCESS;
6124 }
6125 
AutoGCRooter(JSContext * cx,ptrdiff_t tag)6126 AutoGCRooter::AutoGCRooter(JSContext* cx, ptrdiff_t tag)
6127   : down(ContextFriendFields::get(cx)->roots.autoGCRooters_),
6128     tag_(tag),
6129     stackTop(&ContextFriendFields::get(cx)->roots.autoGCRooters_)
6130 {
6131     MOZ_ASSERT(this != *stackTop);
6132     *stackTop = this;
6133 }
6134 
AutoGCRooter(ContextFriendFields * cx,ptrdiff_t tag)6135 AutoGCRooter::AutoGCRooter(ContextFriendFields* cx, ptrdiff_t tag)
6136   : down(cx->roots.autoGCRooters_),
6137     tag_(tag),
6138     stackTop(&cx->roots.autoGCRooters_)
6139 {
6140     MOZ_ASSERT(this != *stackTop);
6141     *stackTop = this;
6142 }
6143 
6144 #ifdef JS_DEBUG
JS_PUBLIC_API(void)6145 JS_PUBLIC_API(void)
6146 JS::detail::AssertArgumentsAreSane(JSContext* cx, HandleValue value)
6147 {
6148     AssertHeapIsIdle(cx);
6149     CHECK_REQUEST(cx);
6150     assertSameCompartment(cx, value);
6151 }
6152 #endif /* JS_DEBUG */
6153 
6154 JS_PUBLIC_API(void*)
JS_EncodeScript(JSContext * cx,HandleScript scriptArg,uint32_t * lengthp)6155 JS_EncodeScript(JSContext* cx, HandleScript scriptArg, uint32_t* lengthp)
6156 {
6157     XDREncoder encoder(cx);
6158     RootedScript script(cx, scriptArg);
6159     if (!encoder.codeScript(&script))
6160         return nullptr;
6161     return encoder.forgetData(lengthp);
6162 }
6163 
6164 JS_PUBLIC_API(void*)
JS_EncodeInterpretedFunction(JSContext * cx,HandleObject funobjArg,uint32_t * lengthp)6165 JS_EncodeInterpretedFunction(JSContext* cx, HandleObject funobjArg, uint32_t* lengthp)
6166 {
6167     XDREncoder encoder(cx);
6168     RootedFunction funobj(cx, &funobjArg->as<JSFunction>());
6169     if (!encoder.codeFunction(&funobj))
6170         return nullptr;
6171     return encoder.forgetData(lengthp);
6172 }
6173 
6174 JS_PUBLIC_API(JSScript*)
JS_DecodeScript(JSContext * cx,const void * data,uint32_t length)6175 JS_DecodeScript(JSContext* cx, const void* data, uint32_t length)
6176 {
6177     XDRDecoder decoder(cx, data, length);
6178     RootedScript script(cx);
6179     if (!decoder.codeScript(&script))
6180         return nullptr;
6181     return script;
6182 }
6183 
6184 JS_PUBLIC_API(JSObject*)
JS_DecodeInterpretedFunction(JSContext * cx,const void * data,uint32_t length)6185 JS_DecodeInterpretedFunction(JSContext* cx, const void* data, uint32_t length)
6186 {
6187     XDRDecoder decoder(cx, data, length);
6188     RootedFunction funobj(cx);
6189     if (!decoder.codeFunction(&funobj))
6190         return nullptr;
6191     return funobj;
6192 }
6193 
JS_PUBLIC_API(void)6194 JS_PUBLIC_API(void)
6195 JS::SetAsmJSCacheOps(JSRuntime* rt, const JS::AsmJSCacheOps* ops)
6196 {
6197     rt->asmJSCacheOps = *ops;
6198 }
6199 
6200 char*
encodeLatin1(ExclusiveContext * cx,JSString * str)6201 JSAutoByteString::encodeLatin1(ExclusiveContext* cx, JSString* str)
6202 {
6203     mBytes = EncodeLatin1(cx, str);
6204     return mBytes;
6205 }
6206 
JS_PUBLIC_API(void)6207 JS_PUBLIC_API(void)
6208 JS::SetLargeAllocationFailureCallback(JSRuntime* rt, JS::LargeAllocationFailureCallback lafc,
6209                                       void* data)
6210 {
6211     rt->largeAllocationFailureCallback = lafc;
6212     rt->largeAllocationFailureCallbackData = data;
6213 }
6214 
JS_PUBLIC_API(void)6215 JS_PUBLIC_API(void)
6216 JS::SetOutOfMemoryCallback(JSRuntime* rt, OutOfMemoryCallback cb, void* data)
6217 {
6218     rt->oomCallback = cb;
6219     rt->oomCallbackData = data;
6220 }
6221 
JS_PUBLIC_API(bool)6222 JS_PUBLIC_API(bool)
6223 JS::CaptureCurrentStack(JSContext* cx, JS::MutableHandleObject stackp, unsigned maxFrameCount)
6224 {
6225     JSCompartment* compartment = cx->compartment();
6226     MOZ_ASSERT(compartment);
6227     Rooted<SavedFrame*> frame(cx);
6228     if (!compartment->savedStacks().saveCurrentStack(cx, &frame, maxFrameCount))
6229         return false;
6230     stackp.set(frame.get());
6231     return true;
6232 }
6233 
JS_PUBLIC_API(bool)6234 JS_PUBLIC_API(bool)
6235 JS::CopyAsyncStack(JSContext* cx, JS::HandleObject asyncStack,
6236                    JS::HandleString asyncCause, JS::MutableHandleObject stackp,
6237                    unsigned maxFrameCount)
6238 {
6239     js::AssertObjectIsSavedFrameOrWrapper(cx, asyncStack);
6240     JSCompartment* compartment = cx->compartment();
6241     MOZ_ASSERT(compartment);
6242     Rooted<SavedFrame*> frame(cx);
6243     if (!compartment->savedStacks().copyAsyncStack(cx, asyncStack, asyncCause,
6244                                                    &frame, maxFrameCount))
6245         return false;
6246     stackp.set(frame.get());
6247     return true;
6248 }
6249 
JS_PUBLIC_API(Zone *)6250 JS_PUBLIC_API(Zone*)
6251 JS::GetObjectZone(JSObject* obj)
6252 {
6253     return obj->zone();
6254 }
6255