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 #include "jsfriendapi.h"
8
9 #include "mozilla/PodOperations.h"
10
11 #include <stdint.h>
12
13 #include "jscntxt.h"
14 #include "jscompartment.h"
15 #include "jsgc.h"
16 #include "jsobj.h"
17 #include "jsprf.h"
18 #include "jswatchpoint.h"
19 #include "jsweakmap.h"
20 #include "jswrapper.h"
21
22 #include "builtin/TestingFunctions.h"
23 #include "js/Proxy.h"
24 #include "proxy/DeadObjectProxy.h"
25 #include "vm/ArgumentsObject.h"
26 #include "vm/Time.h"
27 #include "vm/WrapperObject.h"
28
29 #include "jsobjinlines.h"
30 #include "jsscriptinlines.h"
31
32 #include "vm/NativeObject-inl.h"
33 #include "vm/ScopeObject-inl.h"
34
35 using namespace js;
36
37 using mozilla::Move;
38 using mozilla::PodArrayZero;
39 using mozilla::UniquePtr;
40
41 // Required by PerThreadDataFriendFields::getMainThread()
42 JS_STATIC_ASSERT(offsetof(JSRuntime, mainThread) ==
43 PerThreadDataFriendFields::RuntimeMainThreadOffset);
44
PerThreadDataFriendFields()45 PerThreadDataFriendFields::PerThreadDataFriendFields()
46 {
47 PodArrayZero(nativeStackLimit);
48 #if JS_STACK_GROWTH_DIRECTION > 0
49 for (int i=0; i<StackKindCount; i++)
50 nativeStackLimit[i] = UINTPTR_MAX;
51 #endif
52 }
53
JS_FRIEND_API(void)54 JS_FRIEND_API(void)
55 js::SetSourceHook(JSRuntime* rt, UniquePtr<SourceHook> hook)
56 {
57 rt->sourceHook = Move(hook);
58 }
59
JS_FRIEND_API(UniquePtr<SourceHook>)60 JS_FRIEND_API(UniquePtr<SourceHook>)
61 js::ForgetSourceHook(JSRuntime* rt)
62 {
63 return Move(rt->sourceHook);
64 }
65
66 JS_FRIEND_API(void)
JS_SetGrayGCRootsTracer(JSRuntime * rt,JSTraceDataOp traceOp,void * data)67 JS_SetGrayGCRootsTracer(JSRuntime* rt, JSTraceDataOp traceOp, void* data)
68 {
69 rt->gc.setGrayRootsTracer(traceOp, data);
70 }
71
72 JS_FRIEND_API(JSObject*)
JS_FindCompilationScope(JSContext * cx,HandleObject objArg)73 JS_FindCompilationScope(JSContext* cx, HandleObject objArg)
74 {
75 RootedObject obj(cx, objArg);
76
77 /*
78 * We unwrap wrappers here. This is a little weird, but it's what's being
79 * asked of us.
80 */
81 if (obj->is<WrapperObject>())
82 obj = UncheckedUnwrap(obj);
83
84 /*
85 * Get the Window if `obj` is a WindowProxy so that we compile in the
86 * correct (global) scope.
87 */
88 return ToWindowIfWindowProxy(obj);
89 }
90
91 JS_FRIEND_API(JSFunction*)
JS_GetObjectFunction(JSObject * obj)92 JS_GetObjectFunction(JSObject* obj)
93 {
94 if (obj->is<JSFunction>())
95 return &obj->as<JSFunction>();
96 return nullptr;
97 }
98
99 JS_FRIEND_API(bool)
JS_SplicePrototype(JSContext * cx,HandleObject obj,HandleObject proto)100 JS_SplicePrototype(JSContext* cx, HandleObject obj, HandleObject proto)
101 {
102 /*
103 * Change the prototype of an object which hasn't been used anywhere
104 * and does not share its type with another object. Unlike JS_SetPrototype,
105 * does not nuke type information for the object.
106 */
107 CHECK_REQUEST(cx);
108
109 if (!obj->isSingleton()) {
110 /*
111 * We can see non-singleton objects when trying to splice prototypes
112 * due to mutable __proto__ (ugh).
113 */
114 return JS_SetPrototype(cx, obj, proto);
115 }
116
117 Rooted<TaggedProto> tagged(cx, TaggedProto(proto));
118 return obj->splicePrototype(cx, obj->getClass(), tagged);
119 }
120
121 JS_FRIEND_API(JSObject*)
JS_NewObjectWithUniqueType(JSContext * cx,const JSClass * clasp,HandleObject proto)122 JS_NewObjectWithUniqueType(JSContext* cx, const JSClass* clasp, HandleObject proto)
123 {
124 /*
125 * Create our object with a null proto and then splice in the correct proto
126 * after we setSingleton, so that we don't pollute the default
127 * ObjectGroup attached to our proto with information about our object, since
128 * we're not going to be using that ObjectGroup anyway.
129 */
130 RootedObject obj(cx, NewObjectWithGivenProto(cx, (const js::Class*)clasp, nullptr,
131 SingletonObject));
132 if (!obj)
133 return nullptr;
134 if (!JS_SplicePrototype(cx, obj, proto))
135 return nullptr;
136 return obj;
137 }
138
139 JS_FRIEND_API(JSObject*)
JS_NewObjectWithoutMetadata(JSContext * cx,const JSClass * clasp,JS::Handle<JSObject * > proto)140 JS_NewObjectWithoutMetadata(JSContext* cx, const JSClass* clasp, JS::Handle<JSObject*> proto)
141 {
142 // Use an AutoEnterAnalysis to suppress invocation of the metadata callback.
143 AutoEnterAnalysis enter(cx);
144 return JS_NewObjectWithGivenProto(cx, clasp, proto);
145 }
146
147 JS_FRIEND_API(JSPrincipals*)
JS_GetCompartmentPrincipals(JSCompartment * compartment)148 JS_GetCompartmentPrincipals(JSCompartment* compartment)
149 {
150 return compartment->principals();
151 }
152
153 JS_FRIEND_API(void)
JS_SetCompartmentPrincipals(JSCompartment * compartment,JSPrincipals * principals)154 JS_SetCompartmentPrincipals(JSCompartment* compartment, JSPrincipals* principals)
155 {
156 // Short circuit if there's no change.
157 if (principals == compartment->principals())
158 return;
159
160 // Any compartment with the trusted principals -- and there can be
161 // multiple -- is a system compartment.
162 const JSPrincipals* trusted = compartment->runtimeFromMainThread()->trustedPrincipals();
163 bool isSystem = principals && principals == trusted;
164
165 // Clear out the old principals, if any.
166 if (compartment->principals()) {
167 JS_DropPrincipals(compartment->runtimeFromMainThread(), compartment->principals());
168 compartment->setPrincipals(nullptr);
169 // We'd like to assert that our new principals is always same-origin
170 // with the old one, but JSPrincipals doesn't give us a way to do that.
171 // But we can at least assert that we're not switching between system
172 // and non-system.
173 MOZ_ASSERT(compartment->isSystem() == isSystem);
174 }
175
176 // Set up the new principals.
177 if (principals) {
178 JS_HoldPrincipals(principals);
179 compartment->setPrincipals(principals);
180 }
181
182 // Update the system flag.
183 compartment->setIsSystem(isSystem);
184 }
185
186 JS_FRIEND_API(JSPrincipals*)
JS_GetScriptPrincipals(JSScript * script)187 JS_GetScriptPrincipals(JSScript* script)
188 {
189 return script->principals();
190 }
191
192 JS_FRIEND_API(bool)
JS_ScriptHasMutedErrors(JSScript * script)193 JS_ScriptHasMutedErrors(JSScript* script)
194 {
195 return script->mutedErrors();
196 }
197
198 JS_FRIEND_API(bool)
JS_WrapPropertyDescriptor(JSContext * cx,JS::MutableHandle<js::PropertyDescriptor> desc)199 JS_WrapPropertyDescriptor(JSContext* cx, JS::MutableHandle<js::PropertyDescriptor> desc)
200 {
201 return cx->compartment()->wrap(cx, desc);
202 }
203
204 JS_FRIEND_API(void)
JS_TraceShapeCycleCollectorChildren(JS::CallbackTracer * trc,JS::GCCellPtr shape)205 JS_TraceShapeCycleCollectorChildren(JS::CallbackTracer* trc, JS::GCCellPtr shape)
206 {
207 MOZ_ASSERT(shape.is<Shape>());
208 TraceCycleCollectorChildren(trc, &shape.as<Shape>());
209 }
210
211 JS_FRIEND_API(void)
JS_TraceObjectGroupCycleCollectorChildren(JS::CallbackTracer * trc,JS::GCCellPtr group)212 JS_TraceObjectGroupCycleCollectorChildren(JS::CallbackTracer* trc, JS::GCCellPtr group)
213 {
214 MOZ_ASSERT(group.is<ObjectGroup>());
215 TraceCycleCollectorChildren(trc, &group.as<ObjectGroup>());
216 }
217
218 static bool
DefineHelpProperty(JSContext * cx,HandleObject obj,const char * prop,const char * value)219 DefineHelpProperty(JSContext* cx, HandleObject obj, const char* prop, const char* value)
220 {
221 RootedAtom atom(cx, Atomize(cx, value, strlen(value)));
222 if (!atom)
223 return false;
224 return JS_DefineProperty(cx, obj, prop, atom,
225 JSPROP_READONLY | JSPROP_PERMANENT,
226 JS_STUBGETTER, JS_STUBSETTER);
227 }
228
229 JS_FRIEND_API(bool)
JS_DefineFunctionsWithHelp(JSContext * cx,HandleObject obj,const JSFunctionSpecWithHelp * fs)230 JS_DefineFunctionsWithHelp(JSContext* cx, HandleObject obj, const JSFunctionSpecWithHelp* fs)
231 {
232 MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
233
234 CHECK_REQUEST(cx);
235 assertSameCompartment(cx, obj);
236 for (; fs->name; fs++) {
237 JSAtom* atom = Atomize(cx, fs->name, strlen(fs->name));
238 if (!atom)
239 return false;
240
241 Rooted<jsid> id(cx, AtomToId(atom));
242 RootedFunction fun(cx, DefineFunction(cx, obj, id, fs->call, fs->nargs, fs->flags));
243 if (!fun)
244 return false;
245
246 if (fs->jitInfo)
247 fun->setJitInfo(fs->jitInfo);
248
249 if (fs->usage) {
250 if (!DefineHelpProperty(cx, fun, "usage", fs->usage))
251 return false;
252 }
253
254 if (fs->help) {
255 if (!DefineHelpProperty(cx, fun, "help", fs->help))
256 return false;
257 }
258 }
259
260 return true;
261 }
262
JS_FRIEND_API(bool)263 JS_FRIEND_API(bool)
264 js::GetBuiltinClass(JSContext* cx, HandleObject obj, ESClassValue* classValue)
265 {
266 if (MOZ_UNLIKELY(obj->is<ProxyObject>()))
267 return Proxy::getBuiltinClass(cx, obj, classValue);
268
269 if (obj->is<PlainObject>() || obj->is<UnboxedPlainObject>())
270 *classValue = ESClass_Object;
271 else if (obj->is<ArrayObject>() || obj->is<UnboxedArrayObject>())
272 *classValue = ESClass_Array;
273 else if (obj->is<NumberObject>())
274 *classValue = ESClass_Number;
275 else if (obj->is<StringObject>())
276 *classValue = ESClass_String;
277 else if (obj->is<BooleanObject>())
278 *classValue = ESClass_Boolean;
279 else if (obj->is<RegExpObject>())
280 *classValue = ESClass_RegExp;
281 else if (obj->is<ArrayBufferObject>())
282 *classValue = ESClass_ArrayBuffer;
283 else if (obj->is<SharedArrayBufferObject>())
284 *classValue = ESClass_SharedArrayBuffer;
285 else if (obj->is<DateObject>())
286 *classValue = ESClass_Date;
287 else if (obj->is<SetObject>())
288 *classValue = ESClass_Set;
289 else if (obj->is<MapObject>())
290 *classValue = ESClass_Map;
291 else
292 *classValue = ESClass_Other;
293
294 return true;
295 }
296
JS_FRIEND_API(const char *)297 JS_FRIEND_API(const char*)
298 js::ObjectClassName(JSContext* cx, HandleObject obj)
299 {
300 return GetObjectClassName(cx, obj);
301 }
302
JS_FRIEND_API(JS::Zone *)303 JS_FRIEND_API(JS::Zone*)
304 js::GetCompartmentZone(JSCompartment* comp)
305 {
306 return comp->zone();
307 }
308
JS_FRIEND_API(bool)309 JS_FRIEND_API(bool)
310 js::IsSystemCompartment(JSCompartment* comp)
311 {
312 return comp->isSystem();
313 }
314
JS_FRIEND_API(bool)315 JS_FRIEND_API(bool)
316 js::IsSystemZone(Zone* zone)
317 {
318 return zone->isSystem;
319 }
320
JS_FRIEND_API(bool)321 JS_FRIEND_API(bool)
322 js::IsAtomsCompartment(JSCompartment* comp)
323 {
324 return comp->runtimeFromAnyThread()->isAtomsCompartment(comp);
325 }
326
JS_FRIEND_API(bool)327 JS_FRIEND_API(bool)
328 js::IsAtomsZone(JS::Zone* zone)
329 {
330 return zone->runtimeFromAnyThread()->isAtomsZone(zone);
331 }
332
JS_FRIEND_API(bool)333 JS_FRIEND_API(bool)
334 js::IsFunctionObject(JSObject* obj)
335 {
336 return obj->is<JSFunction>();
337 }
338
JS_FRIEND_API(JSObject *)339 JS_FRIEND_API(JSObject*)
340 js::GetGlobalForObjectCrossCompartment(JSObject* obj)
341 {
342 return &obj->global();
343 }
344
JS_FRIEND_API(JSObject *)345 JS_FRIEND_API(JSObject*)
346 js::GetPrototypeNoProxy(JSObject* obj)
347 {
348 MOZ_ASSERT(!obj->is<js::ProxyObject>());
349 MOZ_ASSERT(!obj->getTaggedProto().isLazy());
350 return obj->getTaggedProto().toObjectOrNull();
351 }
352
JS_FRIEND_API(void)353 JS_FRIEND_API(void)
354 js::AssertSameCompartment(JSContext* cx, JSObject* obj)
355 {
356 assertSameCompartment(cx, obj);
357 }
358
359 #ifdef DEBUG
JS_FRIEND_API(void)360 JS_FRIEND_API(void)
361 js::AssertSameCompartment(JSObject* objA, JSObject* objB)
362 {
363 MOZ_ASSERT(objA->compartment() == objB->compartment());
364 }
365 #endif
366
JS_FRIEND_API(void)367 JS_FRIEND_API(void)
368 js::NotifyAnimationActivity(JSObject* obj)
369 {
370 int64_t timeNow = PRMJ_Now();
371 obj->compartment()->lastAnimationTime = timeNow;
372 obj->runtimeFromMainThread()->lastAnimationTime = timeNow;
373 }
374
JS_FRIEND_API(uint32_t)375 JS_FRIEND_API(uint32_t)
376 js::GetObjectSlotSpan(JSObject* obj)
377 {
378 return obj->as<NativeObject>().slotSpan();
379 }
380
JS_FRIEND_API(bool)381 JS_FRIEND_API(bool)
382 js::IsObjectInContextCompartment(JSObject* obj, const JSContext* cx)
383 {
384 return obj->compartment() == cx->compartment();
385 }
386
JS_FRIEND_API(bool)387 JS_FRIEND_API(bool)
388 js::RunningWithTrustedPrincipals(JSContext* cx)
389 {
390 return cx->runningWithTrustedPrincipals();
391 }
392
JS_FRIEND_API(JSFunction *)393 JS_FRIEND_API(JSFunction*)
394 js::GetOutermostEnclosingFunctionOfScriptedCaller(JSContext* cx)
395 {
396 ScriptFrameIter iter(cx);
397 if (iter.done())
398 return nullptr;
399
400 if (!iter.isFunctionFrame())
401 return nullptr;
402
403 RootedFunction curr(cx, iter.callee(cx));
404 for (StaticScopeIter<NoGC> i(curr); !i.done(); i++) {
405 if (i.type() == StaticScopeIter<NoGC>::Function)
406 curr = &i.fun();
407 }
408 return curr;
409 }
410
JS_FRIEND_API(JSFunction *)411 JS_FRIEND_API(JSFunction*)
412 js::DefineFunctionWithReserved(JSContext* cx, JSObject* objArg, const char* name, JSNative call,
413 unsigned nargs, unsigned attrs)
414 {
415 RootedObject obj(cx, objArg);
416 MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
417 CHECK_REQUEST(cx);
418 assertSameCompartment(cx, obj);
419 JSAtom* atom = Atomize(cx, name, strlen(name));
420 if (!atom)
421 return nullptr;
422 Rooted<jsid> id(cx, AtomToId(atom));
423 return DefineFunction(cx, obj, id, call, nargs, attrs, gc::AllocKind::FUNCTION_EXTENDED);
424 }
425
JS_FRIEND_API(JSFunction *)426 JS_FRIEND_API(JSFunction*)
427 js::NewFunctionWithReserved(JSContext* cx, JSNative native, unsigned nargs, unsigned flags,
428 const char* name)
429 {
430 MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
431
432 CHECK_REQUEST(cx);
433
434 RootedAtom atom(cx);
435 if (name) {
436 atom = Atomize(cx, name, strlen(name));
437 if (!atom)
438 return nullptr;
439 }
440
441 return (flags & JSFUN_CONSTRUCTOR) ?
442 NewNativeConstructor(cx, native, nargs, atom, gc::AllocKind::FUNCTION_EXTENDED) :
443 NewNativeFunction(cx, native, nargs, atom, gc::AllocKind::FUNCTION_EXTENDED);
444 }
445
JS_FRIEND_API(JSFunction *)446 JS_FRIEND_API(JSFunction*)
447 js::NewFunctionByIdWithReserved(JSContext* cx, JSNative native, unsigned nargs, unsigned flags,
448 jsid id)
449 {
450 MOZ_ASSERT(JSID_IS_STRING(id));
451 MOZ_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
452 CHECK_REQUEST(cx);
453
454 RootedAtom atom(cx, JSID_TO_ATOM(id));
455 return (flags & JSFUN_CONSTRUCTOR) ?
456 NewNativeConstructor(cx, native, nargs, atom, gc::AllocKind::FUNCTION_EXTENDED) :
457 NewNativeFunction(cx, native, nargs, atom, gc::AllocKind::FUNCTION_EXTENDED);
458 }
459
JS_FRIEND_API(const Value &)460 JS_FRIEND_API(const Value&)
461 js::GetFunctionNativeReserved(JSObject* fun, size_t which)
462 {
463 MOZ_ASSERT(fun->as<JSFunction>().isNative());
464 return fun->as<JSFunction>().getExtendedSlot(which);
465 }
466
JS_FRIEND_API(void)467 JS_FRIEND_API(void)
468 js::SetFunctionNativeReserved(JSObject* fun, size_t which, const Value& val)
469 {
470 MOZ_ASSERT(fun->as<JSFunction>().isNative());
471 MOZ_ASSERT_IF(val.isObject(), val.toObject().compartment() == fun->compartment());
472 fun->as<JSFunction>().setExtendedSlot(which, val);
473 }
474
JS_FRIEND_API(bool)475 JS_FRIEND_API(bool)
476 js::FunctionHasNativeReserved(JSObject* fun)
477 {
478 MOZ_ASSERT(fun->as<JSFunction>().isNative());
479 return fun->as<JSFunction>().isExtended();
480 }
481
JS_FRIEND_API(bool)482 JS_FRIEND_API(bool)
483 js::GetObjectProto(JSContext* cx, JS::Handle<JSObject*> obj, JS::MutableHandle<JSObject*> proto)
484 {
485 if (IsProxy(obj))
486 return JS_GetPrototype(cx, obj, proto);
487
488 proto.set(reinterpret_cast<const shadow::Object*>(obj.get())->group->proto);
489 return true;
490 }
491
JS_FRIEND_API(bool)492 JS_FRIEND_API(bool)
493 js::GetOriginalEval(JSContext* cx, HandleObject scope, MutableHandleObject eval)
494 {
495 assertSameCompartment(cx, scope);
496 Rooted<GlobalObject*> global(cx, &scope->global());
497 return GlobalObject::getOrCreateEval(cx, global, eval);
498 }
499
JS_FRIEND_API(void)500 JS_FRIEND_API(void)
501 js::SetReservedOrProxyPrivateSlotWithBarrier(JSObject* obj, size_t slot, const js::Value& value)
502 {
503 if (IsProxy(obj)) {
504 MOZ_ASSERT(slot == 0);
505 obj->as<ProxyObject>().setSameCompartmentPrivate(value);
506 } else {
507 obj->as<NativeObject>().setSlot(slot, value);
508 }
509 }
510
511 void
SetPreserveWrapperCallback(JSRuntime * rt,PreserveWrapperCallback callback)512 js::SetPreserveWrapperCallback(JSRuntime* rt, PreserveWrapperCallback callback)
513 {
514 rt->preserveWrapperCallback = callback;
515 }
516
517 /*
518 * The below code is for temporary telemetry use. It can be removed when
519 * sufficient data has been harvested.
520 */
521
522 namespace js {
523 // Defined in vm/GlobalObject.cpp.
524 extern size_t sSetProtoCalled;
525 } // namespace js
526
527 JS_FRIEND_API(size_t)
JS_SetProtoCalled(JSContext *)528 JS_SetProtoCalled(JSContext*)
529 {
530 return sSetProtoCalled;
531 }
532
533 // Defined in jsiter.cpp.
534 extern size_t sCustomIteratorCount;
535
536 JS_FRIEND_API(size_t)
JS_GetCustomIteratorCount(JSContext * cx)537 JS_GetCustomIteratorCount(JSContext* cx)
538 {
539 return sCustomIteratorCount;
540 }
541
542 JS_FRIEND_API(unsigned)
JS_PCToLineNumber(JSScript * script,jsbytecode * pc,unsigned * columnp)543 JS_PCToLineNumber(JSScript* script, jsbytecode* pc, unsigned* columnp)
544 {
545 return PCToLineNumber(script, pc, columnp);
546 }
547
548 JS_FRIEND_API(bool)
JS_IsDeadWrapper(JSObject * obj)549 JS_IsDeadWrapper(JSObject* obj)
550 {
551 return IsDeadProxyObject(obj);
552 }
553
554 void
TraceWeakMaps(WeakMapTracer * trc)555 js::TraceWeakMaps(WeakMapTracer* trc)
556 {
557 WeakMapBase::traceAllMappings(trc);
558 WatchpointMap::traceAll(trc);
559 }
560
JS_FRIEND_API(bool)561 extern JS_FRIEND_API(bool)
562 js::AreGCGrayBitsValid(JSRuntime* rt)
563 {
564 return rt->gc.areGrayBitsValid();
565 }
566
JS_FRIEND_API(bool)567 JS_FRIEND_API(bool)
568 js::ZoneGlobalsAreAllGray(JS::Zone* zone)
569 {
570 for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next()) {
571 JSObject* obj = comp->maybeGlobal();
572 if (!obj || !JS::ObjectIsMarkedGray(obj))
573 return false;
574 }
575 return true;
576 }
577
JS_FRIEND_API(JS::TraceKind)578 JS_FRIEND_API(JS::TraceKind)
579 js::GCThingTraceKind(void* thing)
580 {
581 MOZ_ASSERT(thing);
582 return static_cast<js::gc::Cell*>(thing)->getTraceKind();
583 }
584
JS_FRIEND_API(void)585 JS_FRIEND_API(void)
586 js::VisitGrayWrapperTargets(Zone* zone, GCThingCallback callback, void* closure)
587 {
588 for (CompartmentsInZoneIter comp(zone); !comp.done(); comp.next()) {
589 for (JSCompartment::WrapperEnum e(comp); !e.empty(); e.popFront()) {
590 gc::Cell* thing = e.front().key().wrapped;
591 if (thing->isTenured() && thing->asTenured().isMarked(gc::GRAY))
592 callback(closure, JS::GCCellPtr(thing, thing->asTenured().getTraceKind()));
593 }
594 }
595 }
596
JS_FRIEND_API(JSObject *)597 JS_FRIEND_API(JSObject*)
598 js::GetWeakmapKeyDelegate(JSObject* key)
599 {
600 if (JSWeakmapKeyDelegateOp op = key->getClass()->ext.weakmapKeyDelegateOp)
601 return op(key);
602 return nullptr;
603 }
604
JS_FRIEND_API(JSLinearString *)605 JS_FRIEND_API(JSLinearString*)
606 js::StringToLinearStringSlow(JSContext* cx, JSString* str)
607 {
608 return str->ensureLinear(cx);
609 }
610
611 JS_FRIEND_API(void)
JS_SetAccumulateTelemetryCallback(JSRuntime * rt,JSAccumulateTelemetryDataCallback callback)612 JS_SetAccumulateTelemetryCallback(JSRuntime* rt, JSAccumulateTelemetryDataCallback callback)
613 {
614 rt->setTelemetryCallback(rt, callback);
615 }
616
617 JS_FRIEND_API(JSObject*)
JS_CloneObject(JSContext * cx,HandleObject obj,HandleObject protoArg)618 JS_CloneObject(JSContext* cx, HandleObject obj, HandleObject protoArg)
619 {
620 Rooted<TaggedProto> proto(cx, TaggedProto(protoArg.get()));
621 return CloneObject(cx, obj, proto);
622 }
623
624 #ifdef DEBUG
JS_FRIEND_API(void)625 JS_FRIEND_API(void)
626 js::DumpString(JSString* str)
627 {
628 str->dump();
629 }
630
JS_FRIEND_API(void)631 JS_FRIEND_API(void)
632 js::DumpAtom(JSAtom* atom)
633 {
634 atom->dump();
635 }
636
JS_FRIEND_API(void)637 JS_FRIEND_API(void)
638 js::DumpChars(const char16_t* s, size_t n)
639 {
640 fprintf(stderr, "char16_t * (%p) = ", (void*) s);
641 JSString::dumpChars(s, n);
642 fputc('\n', stderr);
643 }
644
JS_FRIEND_API(void)645 JS_FRIEND_API(void)
646 js::DumpObject(JSObject* obj)
647 {
648 if (!obj) {
649 fprintf(stderr, "NULL\n");
650 return;
651 }
652 obj->dump();
653 }
654
655 #endif
656
657 static const char*
FormatValue(JSContext * cx,const Value & vArg,JSAutoByteString & bytes)658 FormatValue(JSContext* cx, const Value& vArg, JSAutoByteString& bytes)
659 {
660 RootedValue v(cx, vArg);
661
662 if (v.isMagic(JS_OPTIMIZED_OUT))
663 return "[unavailable]";
664
665 /*
666 * We could use Maybe<AutoCompartment> here, but G++ can't quite follow
667 * that, and warns about uninitialized members being used in the
668 * destructor.
669 */
670 RootedString str(cx);
671 if (v.isObject()) {
672 AutoCompartment ac(cx, &v.toObject());
673 str = ToString<CanGC>(cx, v);
674 } else {
675 str = ToString<CanGC>(cx, v);
676 }
677
678 if (!str)
679 return nullptr;
680 const char* buf = bytes.encodeLatin1(cx, str);
681 if (!buf)
682 return nullptr;
683 const char* found = strstr(buf, "function ");
684 if (found && (found - buf <= 2))
685 return "[function]";
686 return buf;
687 }
688
689 // Wrapper for JS_sprintf_append() that reports allocation failure to the
690 // context.
691 template <typename... Args>
692 static char*
sprintf_append(JSContext * cx,char * buf,Args &&...args)693 sprintf_append(JSContext* cx, char* buf, Args&&... args)
694 {
695 char* result = JS_sprintf_append(buf, mozilla::Forward<Args>(args)...);
696 if (!result) {
697 ReportOutOfMemory(cx);
698 return nullptr;
699 }
700
701 return result;
702 }
703
704 static char*
FormatFrame(JSContext * cx,const ScriptFrameIter & iter,char * buf,int num,bool showArgs,bool showLocals,bool showThisProps)705 FormatFrame(JSContext* cx, const ScriptFrameIter& iter, char* buf, int num,
706 bool showArgs, bool showLocals, bool showThisProps)
707 {
708 MOZ_ASSERT(!cx->isExceptionPending());
709 RootedScript script(cx, iter.script());
710 jsbytecode* pc = iter.pc();
711
712 RootedObject scopeChain(cx, iter.scopeChain(cx));
713 JSAutoCompartment ac(cx, scopeChain);
714
715 const char* filename = script->filename();
716 unsigned lineno = PCToLineNumber(script, pc);
717 RootedFunction fun(cx, iter.maybeCallee(cx));
718 RootedString funname(cx);
719 if (fun)
720 funname = fun->displayAtom();
721
722 RootedValue thisVal(cx);
723 if (iter.hasUsableAbstractFramePtr() &&
724 iter.isNonEvalFunctionFrame() &&
725 fun && !fun->isArrow() && !fun->isDerivedClassConstructor())
726 {
727 if (!GetFunctionThis(cx, iter.abstractFramePtr(), &thisVal))
728 return nullptr;
729 }
730
731 // print the frame number and function name
732 if (funname) {
733 JSAutoByteString funbytes;
734 char* str = funbytes.encodeLatin1(cx, funname);
735 if (!str)
736 return nullptr;
737 buf = sprintf_append(cx, buf, "%d %s(", num, str);
738 } else if (fun) {
739 buf = sprintf_append(cx, buf, "%d anonymous(", num);
740 } else {
741 buf = sprintf_append(cx, buf, "%d <TOP LEVEL>", num);
742 }
743 if (!buf)
744 return nullptr;
745
746 if (showArgs && iter.hasArgs()) {
747 BindingIter bi(script);
748 bool first = true;
749 for (unsigned i = 0; i < iter.numActualArgs(); i++) {
750 RootedValue arg(cx);
751 if (i < iter.numFormalArgs() && script->formalIsAliased(i)) {
752 for (AliasedFormalIter fi(script); ; fi++) {
753 if (fi.frameIndex() == i) {
754 arg = iter.callObj(cx).aliasedVar(fi);
755 break;
756 }
757 }
758 } else if (script->argsObjAliasesFormals() && iter.hasArgsObj()) {
759 arg = iter.argsObj().arg(i);
760 } else {
761 if (iter.hasUsableAbstractFramePtr())
762 arg = iter.unaliasedActual(i, DONT_CHECK_ALIASING);
763 else
764 arg = MagicValue(JS_OPTIMIZED_OUT);
765 }
766
767 JSAutoByteString valueBytes;
768 const char* value = FormatValue(cx, arg, valueBytes);
769 if (!value) {
770 if (cx->isThrowingOutOfMemory())
771 return nullptr;
772 cx->clearPendingException();
773 }
774
775 JSAutoByteString nameBytes;
776 const char* name = nullptr;
777
778 if (i < iter.numFormalArgs()) {
779 MOZ_ASSERT(i == bi.argIndex());
780 name = nameBytes.encodeLatin1(cx, bi->name());
781 if (!name)
782 return nullptr;
783 bi++;
784 }
785
786 if (value) {
787 buf = sprintf_append(cx, buf, "%s%s%s%s%s%s",
788 !first ? ", " : "",
789 name ? name :"",
790 name ? " = " : "",
791 arg.isString() ? "\"" : "",
792 value,
793 arg.isString() ? "\"" : "");
794 if (!buf)
795 return nullptr;
796
797 first = false;
798 } else {
799 buf = sprintf_append(cx, buf,
800 " <Failed to get argument while inspecting stack frame>\n");
801 if (!buf)
802 return nullptr;
803
804 }
805 }
806 }
807
808 // print filename and line number
809 buf = sprintf_append(cx, buf, "%s [\"%s\":%d]\n",
810 fun ? ")" : "",
811 filename ? filename : "<unknown>",
812 lineno);
813 if (!buf)
814 return nullptr;
815
816
817 // Note: Right now we don't dump the local variables anymore, because
818 // that is hard to support across all the JITs etc.
819
820 // print the value of 'this'
821 if (showLocals) {
822 if (!thisVal.isUndefined()) {
823 JSAutoByteString thisValBytes;
824 RootedString thisValStr(cx, ToString<CanGC>(cx, thisVal));
825 if (!thisValStr) {
826 if (cx->isThrowingOutOfMemory())
827 return nullptr;
828 cx->clearPendingException();
829 }
830 if (thisValStr) {
831 const char* str = thisValBytes.encodeLatin1(cx, thisValStr);
832 if (!str)
833 return nullptr;
834 buf = sprintf_append(cx, buf, " this = %s\n", str);
835 } else {
836 buf = sprintf_append(cx, buf, " <failed to get 'this' value>\n");
837 }
838 if (!buf)
839 return nullptr;
840 }
841 }
842
843 if (showThisProps && thisVal.isObject()) {
844 RootedObject obj(cx, &thisVal.toObject());
845
846 AutoIdVector keys(cx);
847 if (!GetPropertyKeys(cx, obj, JSITER_OWNONLY, &keys)) {
848 if (cx->isThrowingOutOfMemory())
849 return nullptr;
850 cx->clearPendingException();
851 }
852
853 RootedId id(cx);
854 for (size_t i = 0; i < keys.length(); i++) {
855 RootedId id(cx, keys[i]);
856 RootedValue key(cx, IdToValue(id));
857 RootedValue v(cx);
858
859 if (!GetProperty(cx, obj, obj, id, &v)) {
860 if (cx->isThrowingOutOfMemory())
861 return nullptr;
862 cx->clearPendingException();
863 buf = sprintf_append(cx, buf,
864 " <Failed to fetch property while inspecting stack frame>\n");
865 if (!buf)
866 return nullptr;
867 continue;
868 }
869
870 JSAutoByteString nameBytes;
871 const char* name = FormatValue(cx, key, nameBytes);
872 if (!name) {
873 if (cx->isThrowingOutOfMemory())
874 return nullptr;
875 cx->clearPendingException();
876 }
877
878 JSAutoByteString valueBytes;
879 const char* value = FormatValue(cx, v, valueBytes);
880 if (!value) {
881 if (cx->isThrowingOutOfMemory())
882 return nullptr;
883 cx->clearPendingException();
884 }
885
886 if (name && value) {
887 buf = sprintf_append(cx, buf, " this.%s = %s%s%s\n",
888 name,
889 v.isString() ? "\"" : "",
890 value,
891 v.isString() ? "\"" : "");
892 } else {
893 buf = sprintf_append(cx, buf,
894 " <Failed to format values while inspecting stack frame>\n");
895 }
896 if (!buf)
897 return nullptr;
898 }
899 }
900
901 MOZ_ASSERT(!cx->isExceptionPending());
902 return buf;
903 }
904
JS_FRIEND_API(char *)905 JS_FRIEND_API(char*)
906 JS::FormatStackDump(JSContext* cx, char* buf, bool showArgs, bool showLocals, bool showThisProps)
907 {
908 int num = 0;
909
910 for (AllFramesIter i(cx); !i.done(); ++i) {
911 buf = FormatFrame(cx, i, buf, num, showArgs, showLocals, showThisProps);
912 if (!buf)
913 return nullptr;
914 num++;
915 }
916
917 if (!num)
918 buf = JS_sprintf_append(buf, "JavaScript stack is empty\n");
919
920 return buf;
921 }
922
923 struct DumpHeapTracer : public JS::CallbackTracer, public WeakMapTracer
924 {
925 const char* prefix;
926 FILE* output;
927
DumpHeapTracerDumpHeapTracer928 DumpHeapTracer(FILE* fp, JSRuntime* rt)
929 : JS::CallbackTracer(rt, DoNotTraceWeakMaps),
930 js::WeakMapTracer(rt), prefix(""), output(fp)
931 {}
932
933 private:
traceDumpHeapTracer934 void trace(JSObject* map, JS::GCCellPtr key, JS::GCCellPtr value) override {
935 JSObject* kdelegate = nullptr;
936 if (key.is<JSObject>())
937 kdelegate = js::GetWeakmapKeyDelegate(&key.as<JSObject>());
938
939 fprintf(output, "WeakMapEntry map=%p key=%p keyDelegate=%p value=%p\n",
940 map, key.asCell(), kdelegate, value.asCell());
941 }
942
943 void onChild(const JS::GCCellPtr& thing) override;
944 };
945
946 static char
MarkDescriptor(void * thing)947 MarkDescriptor(void* thing)
948 {
949 gc::TenuredCell* cell = gc::TenuredCell::fromPointer(thing);
950 if (cell->isMarked(gc::BLACK))
951 return cell->isMarked(gc::GRAY) ? 'G' : 'B';
952 else
953 return cell->isMarked(gc::GRAY) ? 'X' : 'W';
954 }
955
956 static void
DumpHeapVisitZone(JSRuntime * rt,void * data,Zone * zone)957 DumpHeapVisitZone(JSRuntime* rt, void* data, Zone* zone)
958 {
959 DumpHeapTracer* dtrc = static_cast<DumpHeapTracer*>(data);
960 fprintf(dtrc->output, "# zone %p\n", (void*)zone);
961 }
962
963 static void
DumpHeapVisitCompartment(JSRuntime * rt,void * data,JSCompartment * comp)964 DumpHeapVisitCompartment(JSRuntime* rt, void* data, JSCompartment* comp)
965 {
966 char name[1024];
967 if (rt->compartmentNameCallback)
968 (*rt->compartmentNameCallback)(rt, comp, name, sizeof(name));
969 else
970 strcpy(name, "<unknown>");
971
972 DumpHeapTracer* dtrc = static_cast<DumpHeapTracer*>(data);
973 fprintf(dtrc->output, "# compartment %s [in zone %p]\n", name, (void*)comp->zone());
974 }
975
976 static void
DumpHeapVisitArena(JSRuntime * rt,void * data,gc::Arena * arena,JS::TraceKind traceKind,size_t thingSize)977 DumpHeapVisitArena(JSRuntime* rt, void* data, gc::Arena* arena,
978 JS::TraceKind traceKind, size_t thingSize)
979 {
980 DumpHeapTracer* dtrc = static_cast<DumpHeapTracer*>(data);
981 fprintf(dtrc->output, "# arena allockind=%u size=%u\n",
982 unsigned(arena->aheader.getAllocKind()), unsigned(thingSize));
983 }
984
985 static void
DumpHeapVisitCell(JSRuntime * rt,void * data,void * thing,JS::TraceKind traceKind,size_t thingSize)986 DumpHeapVisitCell(JSRuntime* rt, void* data, void* thing,
987 JS::TraceKind traceKind, size_t thingSize)
988 {
989 DumpHeapTracer* dtrc = static_cast<DumpHeapTracer*>(data);
990 char cellDesc[1024 * 32];
991 JS_GetTraceThingInfo(cellDesc, sizeof(cellDesc), dtrc, thing, traceKind, true);
992 fprintf(dtrc->output, "%p %c %s\n", thing, MarkDescriptor(thing), cellDesc);
993 js::TraceChildren(dtrc, thing, traceKind);
994 }
995
996 void
onChild(const JS::GCCellPtr & thing)997 DumpHeapTracer::onChild(const JS::GCCellPtr& thing)
998 {
999 if (gc::IsInsideNursery(thing.asCell()))
1000 return;
1001
1002 char buffer[1024];
1003 getTracingEdgeName(buffer, sizeof(buffer));
1004 fprintf(output, "%s%p %c %s\n", prefix, thing.asCell(), MarkDescriptor(thing.asCell()), buffer);
1005 }
1006
1007 void
DumpHeap(JSRuntime * rt,FILE * fp,js::DumpHeapNurseryBehaviour nurseryBehaviour)1008 js::DumpHeap(JSRuntime* rt, FILE* fp, js::DumpHeapNurseryBehaviour nurseryBehaviour)
1009 {
1010 if (nurseryBehaviour == js::CollectNurseryBeforeDump)
1011 rt->gc.evictNursery(JS::gcreason::API);
1012
1013 DumpHeapTracer dtrc(fp, rt);
1014 fprintf(dtrc.output, "# Roots.\n");
1015 TraceRuntime(&dtrc);
1016
1017 fprintf(dtrc.output, "# Weak maps.\n");
1018 WeakMapBase::traceAllMappings(&dtrc);
1019
1020 fprintf(dtrc.output, "==========\n");
1021
1022 dtrc.prefix = "> ";
1023 IterateZonesCompartmentsArenasCells(rt, &dtrc,
1024 DumpHeapVisitZone,
1025 DumpHeapVisitCompartment,
1026 DumpHeapVisitArena,
1027 DumpHeapVisitCell);
1028
1029 fflush(dtrc.output);
1030 }
1031
JS_FRIEND_API(bool)1032 JS_FRIEND_API(bool)
1033 js::ContextHasOutstandingRequests(const JSContext* cx)
1034 {
1035 return cx->outstandingRequests > 0;
1036 }
1037
JS_FRIEND_API(void)1038 JS_FRIEND_API(void)
1039 js::SetActivityCallback(JSRuntime* rt, ActivityCallback cb, void* arg)
1040 {
1041 rt->activityCallback = cb;
1042 rt->activityCallbackArg = arg;
1043 }
1044
JS_FRIEND_API(void)1045 JS_FRIEND_API(void)
1046 JS::NotifyDidPaint(JSRuntime* rt)
1047 {
1048 rt->gc.notifyDidPaint();
1049 }
1050
JS_FRIEND_API(void)1051 JS_FRIEND_API(void)
1052 JS::PokeGC(JSRuntime* rt)
1053 {
1054 rt->gc.poke();
1055 }
1056
JS_FRIEND_API(JSCompartment *)1057 JS_FRIEND_API(JSCompartment*)
1058 js::GetAnyCompartmentInZone(JS::Zone* zone)
1059 {
1060 CompartmentsInZoneIter comp(zone);
1061 MOZ_ASSERT(!comp.done());
1062 return comp.get();
1063 }
1064
1065 void
updateWeakPointerAfterGC()1066 JS::ObjectPtr::updateWeakPointerAfterGC()
1067 {
1068 if (js::gc::IsAboutToBeFinalizedUnbarriered(value.unsafeGet()))
1069 value = nullptr;
1070 }
1071
1072 void
trace(JSTracer * trc,const char * name)1073 JS::ObjectPtr::trace(JSTracer* trc, const char* name)
1074 {
1075 JS_CallObjectTracer(trc, &value, name);
1076 }
1077
JS_FRIEND_API(JSObject *)1078 JS_FRIEND_API(JSObject*)
1079 js::GetTestingFunctions(JSContext* cx)
1080 {
1081 RootedObject obj(cx, JS_NewPlainObject(cx));
1082 if (!obj)
1083 return nullptr;
1084
1085 if (!DefineTestingFunctions(cx, obj, false, false))
1086 return nullptr;
1087
1088 return obj;
1089 }
1090
1091 #ifdef DEBUG
JS_FRIEND_API(unsigned)1092 JS_FRIEND_API(unsigned)
1093 js::GetEnterCompartmentDepth(JSContext* cx)
1094 {
1095 return cx->getEnterCompartmentDepth();
1096 }
1097 #endif
1098
JS_FRIEND_API(void)1099 JS_FRIEND_API(void)
1100 js::SetDOMCallbacks(JSRuntime* rt, const DOMCallbacks* callbacks)
1101 {
1102 rt->DOMcallbacks = callbacks;
1103 }
1104
JS_FRIEND_API(const DOMCallbacks *)1105 JS_FRIEND_API(const DOMCallbacks*)
1106 js::GetDOMCallbacks(JSRuntime* rt)
1107 {
1108 return rt->DOMcallbacks;
1109 }
1110
1111 static const void* gDOMProxyHandlerFamily = nullptr;
1112 static uint32_t gDOMProxyExpandoSlot = 0;
1113 static DOMProxyShadowsCheck gDOMProxyShadowsCheck;
1114
JS_FRIEND_API(void)1115 JS_FRIEND_API(void)
1116 js::SetDOMProxyInformation(const void* domProxyHandlerFamily, uint32_t domProxyExpandoSlot,
1117 DOMProxyShadowsCheck domProxyShadowsCheck)
1118 {
1119 gDOMProxyHandlerFamily = domProxyHandlerFamily;
1120 gDOMProxyExpandoSlot = domProxyExpandoSlot;
1121 gDOMProxyShadowsCheck = domProxyShadowsCheck;
1122 }
1123
1124 const void*
GetDOMProxyHandlerFamily()1125 js::GetDOMProxyHandlerFamily()
1126 {
1127 return gDOMProxyHandlerFamily;
1128 }
1129
1130 uint32_t
GetDOMProxyExpandoSlot()1131 js::GetDOMProxyExpandoSlot()
1132 {
1133 return gDOMProxyExpandoSlot;
1134 }
1135
1136 DOMProxyShadowsCheck
GetDOMProxyShadowsCheck()1137 js::GetDOMProxyShadowsCheck()
1138 {
1139 return gDOMProxyShadowsCheck;
1140 }
1141
1142 bool
IdMatchesAtom(jsid id,JSAtom * atom)1143 js::detail::IdMatchesAtom(jsid id, JSAtom* atom)
1144 {
1145 return id == INTERNED_STRING_TO_JSID(nullptr, atom);
1146 }
1147
JS_FRIEND_API(void)1148 JS_FRIEND_API(void)
1149 js::PrepareScriptEnvironmentAndInvoke(JSContext* cx, HandleObject scope, ScriptEnvironmentPreparer::Closure& closure)
1150 {
1151 MOZ_ASSERT(!cx->isExceptionPending());
1152
1153 if (cx->runtime()->scriptEnvironmentPreparer) {
1154 cx->runtime()->scriptEnvironmentPreparer->invoke(scope, closure);
1155 return;
1156 }
1157
1158 JSAutoCompartment ac(cx, scope);
1159 bool ok = closure(cx);
1160
1161 MOZ_ASSERT_IF(ok, !cx->isExceptionPending());
1162
1163 // NB: This does not affect Gecko, which has a prepareScriptEnvironment
1164 // callback.
1165 if (!ok) {
1166 JS_ReportPendingException(cx);
1167 }
1168
1169 MOZ_ASSERT(!cx->isExceptionPending());
1170 }
1171
JS_FRIEND_API(void)1172 JS_FRIEND_API(void)
1173 js::SetScriptEnvironmentPreparer(JSRuntime* rt, ScriptEnvironmentPreparer* preparer)
1174 {
1175 rt->scriptEnvironmentPreparer = preparer;
1176 }
1177
1178 #ifdef DEBUG
JS_FRIEND_API(void)1179 JS_FRIEND_API(void)
1180 js::Debug_SetActiveJSContext(JSRuntime* rt, JSContext* cx)
1181 {
1182 rt->activeContext = cx;
1183 }
1184 #endif
1185
JS_FRIEND_API(void)1186 JS_FRIEND_API(void)
1187 js::SetCTypesActivityCallback(JSRuntime* rt, CTypesActivityCallback cb)
1188 {
1189 rt->ctypesActivityCallback = cb;
1190 }
1191
AutoCTypesActivityCallback(JSContext * cx,js::CTypesActivityType beginType,js::CTypesActivityType endType MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)1192 js::AutoCTypesActivityCallback::AutoCTypesActivityCallback(JSContext* cx,
1193 js::CTypesActivityType beginType,
1194 js::CTypesActivityType endType
1195 MOZ_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
1196 : cx(cx), callback(cx->runtime()->ctypesActivityCallback), endType(endType)
1197 {
1198 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
1199
1200 if (callback)
1201 callback(cx, beginType);
1202 }
1203
JS_FRIEND_API(void)1204 JS_FRIEND_API(void)
1205 js::SetObjectMetadataCallback(JSContext* cx, ObjectMetadataCallback callback)
1206 {
1207 cx->compartment()->setObjectMetadataCallback(callback);
1208 }
1209
JS_FRIEND_API(JSObject *)1210 JS_FRIEND_API(JSObject*)
1211 js::GetObjectMetadata(JSObject* obj)
1212 {
1213 ObjectWeakMap* map = obj->compartment()->objectMetadataTable;
1214 if (map)
1215 return map->lookup(obj);
1216 return nullptr;
1217 }
1218
JS_FRIEND_API(bool)1219 JS_FRIEND_API(bool)
1220 js::ReportIsNotFunction(JSContext* cx, HandleValue v)
1221 {
1222 return ReportIsNotFunction(cx, v, -1);
1223 }
1224
JS_FRIEND_API(void)1225 JS_FRIEND_API(void)
1226 js::ReportErrorWithId(JSContext* cx, const char* msg, HandleId id)
1227 {
1228 RootedValue idv(cx);
1229 if (!JS_IdToValue(cx, id, &idv))
1230 return;
1231 JSString* idstr = JS::ToString(cx, idv);
1232 if (!idstr)
1233 return;
1234 JSAutoByteString bytes(cx, idstr);
1235 if (!bytes)
1236 return;
1237 JS_ReportError(cx, msg, bytes.ptr());
1238 }
1239
1240 #ifdef DEBUG
1241 bool
HasObjectMovedOp(JSObject * obj)1242 js::HasObjectMovedOp(JSObject* obj) {
1243 return !!GetObjectClass(obj)->ext.objectMovedOp;
1244 }
1245 #endif
1246
1247 JS_FRIEND_API(void)
JS_StoreObjectPostBarrierCallback(JSContext * cx,void (* callback)(JSTracer * trc,JSObject * key,void * data),JSObject * key,void * data)1248 JS_StoreObjectPostBarrierCallback(JSContext* cx,
1249 void (*callback)(JSTracer* trc, JSObject* key, void* data),
1250 JSObject* key, void* data)
1251 {
1252 JSRuntime* rt = cx->runtime();
1253 if (IsInsideNursery(key))
1254 rt->gc.storeBuffer.putCallback(callback, key, data);
1255 }
1256
1257 extern JS_FRIEND_API(void)
JS_StoreStringPostBarrierCallback(JSContext * cx,void (* callback)(JSTracer * trc,JSString * key,void * data),JSString * key,void * data)1258 JS_StoreStringPostBarrierCallback(JSContext* cx,
1259 void (*callback)(JSTracer* trc, JSString* key, void* data),
1260 JSString* key, void* data)
1261 {
1262 JSRuntime* rt = cx->runtime();
1263 if (IsInsideNursery(key))
1264 rt->gc.storeBuffer.putCallback(callback, key, data);
1265 }
1266
1267 extern JS_FRIEND_API(void)
JS_ClearAllPostBarrierCallbacks(JSRuntime * rt)1268 JS_ClearAllPostBarrierCallbacks(JSRuntime* rt)
1269 {
1270 rt->gc.clearPostBarrierCallbacks();
1271 }
1272
JS_FRIEND_API(bool)1273 JS_FRIEND_API(bool)
1274 js::ForwardToNative(JSContext* cx, JSNative native, const CallArgs& args)
1275 {
1276 return native(cx, args.length(), args.base());
1277 }
1278
JS_FRIEND_API(JSObject *)1279 JS_FRIEND_API(JSObject*)
1280 js::ConvertArgsToArray(JSContext* cx, const CallArgs& args)
1281 {
1282 RootedObject argsArray(cx, NewDenseCopiedArray(cx, args.length(), args.array()));
1283 return argsArray;
1284 }
1285
JS_FRIEND_API(JSAtom *)1286 JS_FRIEND_API(JSAtom*)
1287 js::GetPropertyNameFromPC(JSScript* script, jsbytecode* pc)
1288 {
1289 if (!IsGetPropPC(pc) && !IsSetPropPC(pc))
1290 return nullptr;
1291 return script->getName(pc);
1292 }
1293
JS_FRIEND_API(void)1294 JS_FRIEND_API(void)
1295 js::SetWindowProxyClass(JSRuntime* rt, const js::Class* clasp)
1296 {
1297 MOZ_ASSERT(!rt->maybeWindowProxyClass());
1298 rt->setWindowProxyClass(clasp);
1299 }
1300
JS_FRIEND_API(void)1301 JS_FRIEND_API(void)
1302 js::SetWindowProxy(JSContext* cx, HandleObject global, HandleObject windowProxy)
1303 {
1304 AssertHeapIsIdle(cx);
1305 CHECK_REQUEST(cx);
1306
1307 assertSameCompartment(cx, global, windowProxy);
1308
1309 MOZ_ASSERT(IsWindowProxy(windowProxy));
1310 global->as<GlobalObject>().setWindowProxy(windowProxy);
1311 }
1312
JS_FRIEND_API(JSObject *)1313 JS_FRIEND_API(JSObject*)
1314 js::ToWindowIfWindowProxy(JSObject* obj)
1315 {
1316 if (IsWindowProxy(obj))
1317 return &obj->global();
1318 return obj;
1319 }
1320
JS_FRIEND_API(JSObject *)1321 JS_FRIEND_API(JSObject*)
1322 js::ToWindowProxyIfWindow(JSObject* obj)
1323 {
1324 if (IsWindow(obj))
1325 return obj->as<GlobalObject>().windowProxy();
1326 return obj;
1327 }
1328
JS_FRIEND_API(bool)1329 JS_FRIEND_API(bool)
1330 js::IsWindowProxy(JSObject* obj)
1331 {
1332 // Note: simply checking `obj == obj->global().windowProxy()` is not
1333 // sufficient: we may have transplanted the window proxy with a CCW.
1334 // Check the Class to ensure we really have a window proxy.
1335 return obj->getClass() == obj->runtimeFromAnyThread()->maybeWindowProxyClass();
1336 }
1337
JS_FRIEND_API(bool)1338 JS_FRIEND_API(bool)
1339 js::detail::IsWindowSlow(JSObject* obj)
1340 {
1341 return obj->as<GlobalObject>().maybeWindowProxy();
1342 }
1343