Source code

Revision control

Copy as Markdown

Other Tools

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "vm/SavedStacks.h"
#include "mozilla/Attributes.h"
#include "mozilla/DebugOnly.h"
#include <algorithm>
#include <utility>
#include "jsapi.h"
#include "jsmath.h"
#include "jsnum.h"
#include "gc/GCContext.h"
#include "gc/HashUtil.h"
#include "js/CharacterEncoding.h"
#include "js/ColumnNumber.h" // JS::LimitedColumnNumberOneOrigin, JS::TaggedColumnNumberOneOrigin
#include "js/ErrorReport.h" // JSErrorBase
#include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
#include "js/PropertyAndElement.h" // JS_DefineProperty, JS_GetProperty
#include "js/PropertySpec.h"
#include "js/SavedFrameAPI.h"
#include "js/Stack.h"
#include "js/Vector.h"
#include "util/DifferentialTesting.h"
#include "util/StringBuilder.h"
#include "vm/Compartment.h"
#include "vm/FrameIter.h"
#include "vm/GeckoProfiler.h"
#include "vm/JSScript.h"
#include "vm/Realm.h"
#include "vm/SavedFrame.h"
#include "vm/WrapperObject.h"
#include "debugger/DebugAPI-inl.h"
#include "gc/StableCellHasher-inl.h"
#include "vm/GeckoProfiler-inl.h"
#include "vm/JSContext-inl.h"
using mozilla::AddToHash;
using mozilla::DebugOnly;
using mozilla::Maybe;
using mozilla::Nothing;
using mozilla::Some;
namespace js {
/**
* Maximum number of saved frames returned for an async stack.
*/
const uint32_t ASYNC_STACK_MAX_FRAME_COUNT = 60;
void LiveSavedFrameCache::trace(JSTracer* trc) {
if (!initialized()) {
return;
}
for (auto* entry = frames->begin(); entry < frames->end(); entry++) {
TraceEdge(trc, &entry->savedFrame,
"LiveSavedFrameCache::frames SavedFrame");
}
}
bool LiveSavedFrameCache::insert(JSContext* cx, FramePtr&& framePtr,
const jsbytecode* pc,
Handle<SavedFrame*> savedFrame) {
MOZ_ASSERT(savedFrame);
MOZ_ASSERT(initialized());
#ifdef DEBUG
// There should not already be an entry for this frame. Checking the full
// stack really slows down some tests, so just check the first and last five
// hundred.
size_t limit = std::min(frames->length() / 2, size_t(500));
for (size_t i = 0; i < limit; i++) {
MOZ_ASSERT(Key(framePtr) != (*frames)[i].key);
MOZ_ASSERT(Key(framePtr) != (*frames)[frames->length() - 1 - i].key);
}
#endif
if (!frames->emplaceBack(framePtr, pc, savedFrame)) {
ReportOutOfMemory(cx);
return false;
}
framePtr.setHasCachedSavedFrame();
return true;
}
void LiveSavedFrameCache::find(JSContext* cx, FramePtr& framePtr,
const jsbytecode* pc,
MutableHandle<SavedFrame*> frame) const {
MOZ_ASSERT(initialized());
MOZ_ASSERT(framePtr.hasCachedSavedFrame());
// The assertions here check that either 1) frames' hasCachedSavedFrame flags
// accurately indicate the presence of a cache entry for that frame (ignoring
// pc mismatches), or 2) the cache is completely empty, having been flushed
// for a realm mismatch.
// If we flushed the cache due to a realm mismatch, then we shouldn't
// expect to find any frames in the cache.
if (frames->empty()) {
frame.set(nullptr);
return;
}
// All our SavedFrames should be in the same realm. If the last
// entry's SavedFrame's realm doesn't match cx's, flush the cache.
if (frames->back().savedFrame->realm() != cx->realm()) {
#ifdef DEBUG
// Check that they are, indeed, all in the same realm.
auto realm = frames->back().savedFrame->realm();
for (const auto& f : (*frames)) {
MOZ_ASSERT(realm == f.savedFrame->realm());
}
#endif
frames->clear();
frame.set(nullptr);
return;
}
Key key(framePtr);
while (key != frames->back().key) {
MOZ_ASSERT(frames->back().savedFrame->realm() == cx->realm());
// framePtr must have an entry, but apparently it's below this one on the
// stack; frames->back() must correspond to a frame younger than framePtr's.
// SavedStacks::insertFrames is going to push new cache entries for
// everything younger than framePtr, so this entry should be popped.
frames->popBack();
// If the frame's bit was set, the frame should always have an entry in
// the cache. (If we purged the entire cache because its SavedFrames had
// been captured for a different realm, then we would have
// returned early above.)
MOZ_RELEASE_ASSERT(!frames->empty());
}
// The youngest valid frame may have run some code, so its current pc may
// not match its cache entry's pc. In this case, just treat it as a miss. No
// older frame has executed any code; it would have been necessary to pop
// this frame for that to happen, but this frame's bit is set.
if (pc != frames->back().pc) {
frames->popBack();
frame.set(nullptr);
return;
}
frame.set(frames->back().savedFrame);
}
void LiveSavedFrameCache::findWithoutInvalidation(
const FramePtr& framePtr, MutableHandle<SavedFrame*> frame) const {
MOZ_ASSERT(initialized());
MOZ_ASSERT(framePtr.hasCachedSavedFrame());
Key key(framePtr);
for (auto& entry : (*frames)) {
if (entry.key == key) {
frame.set(entry.savedFrame);
return;
}
}
frame.set(nullptr);
}
struct MOZ_STACK_CLASS SavedFrame::Lookup {
Lookup(JSAtom* source, uint32_t sourceId, uint32_t line,
JS::TaggedColumnNumberOneOrigin column, JSAtom* functionDisplayName,
JSAtom* asyncCause, SavedFrame* parent, JSPrincipals* principals,
bool mutedErrors,
const Maybe<LiveSavedFrameCache::FramePtr>& framePtr = Nothing(),
jsbytecode* pc = nullptr, Activation* activation = nullptr)
: source(source),
sourceId(sourceId),
line(line),
column(column),
functionDisplayName(functionDisplayName),
asyncCause(asyncCause),
parent(parent),
principals(principals),
mutedErrors(mutedErrors),
framePtr(framePtr),
pc(pc),
activation(activation) {
MOZ_ASSERT(source);
MOZ_ASSERT_IF(framePtr.isSome(), activation);
if (js::SupportDifferentialTesting()) {
this->column = JS::TaggedColumnNumberOneOrigin::forDifferentialTesting();
}
}
explicit Lookup(SavedFrame& savedFrame)
: source(savedFrame.getSource()),
sourceId(savedFrame.getSourceId()),
line(savedFrame.getLine()),
column(savedFrame.getColumn()),
functionDisplayName(savedFrame.getFunctionDisplayName()),
asyncCause(savedFrame.getAsyncCause()),
parent(savedFrame.getParent()),
principals(savedFrame.getPrincipals()),
mutedErrors(savedFrame.getMutedErrors()),
framePtr(Nothing()),
pc(nullptr),
activation(nullptr) {
MOZ_ASSERT(source);
}
JSAtom* source;
uint32_t sourceId;
// Line number (1-origin).
uint32_t line;
// Columm number in UTF-16 code units.
JS::TaggedColumnNumberOneOrigin column;
JSAtom* functionDisplayName;
JSAtom* asyncCause;
SavedFrame* parent;
JSPrincipals* principals;
bool mutedErrors;
// These are used only by the LiveSavedFrameCache and not used for identity or
// hashing.
Maybe<LiveSavedFrameCache::FramePtr> framePtr;
jsbytecode* pc;
Activation* activation;
void trace(JSTracer* trc) {
TraceRoot(trc, &source, "SavedFrame::Lookup::source");
TraceNullableRoot(trc, &functionDisplayName,
"SavedFrame::Lookup::functionDisplayName");
TraceNullableRoot(trc, &asyncCause, "SavedFrame::Lookup::asyncCause");
TraceNullableRoot(trc, &parent, "SavedFrame::Lookup::parent");
}
};
using GCLookupVector =
GCVector<SavedFrame::Lookup, ASYNC_STACK_MAX_FRAME_COUNT>;
template <class Wrapper>
class WrappedPtrOperations<SavedFrame::Lookup, Wrapper> {
const SavedFrame::Lookup& value() const {
return static_cast<const Wrapper*>(this)->get();
}
public:
JSAtom* source() { return value().source; }
uint32_t sourceId() { return value().sourceId; }
uint32_t line() { return value().line; }
JS::TaggedColumnNumberOneOrigin column() { return value().column; }
JSAtom* functionDisplayName() { return value().functionDisplayName; }
JSAtom* asyncCause() { return value().asyncCause; }
SavedFrame* parent() { return value().parent; }
JSPrincipals* principals() { return value().principals; }
bool mutedErrors() { return value().mutedErrors; }
Maybe<LiveSavedFrameCache::FramePtr> framePtr() { return value().framePtr; }
jsbytecode* pc() { return value().pc; }
Activation* activation() { return value().activation; }
};
template <typename Wrapper>
class MutableWrappedPtrOperations<SavedFrame::Lookup, Wrapper>
: public WrappedPtrOperations<SavedFrame::Lookup, Wrapper> {
SavedFrame::Lookup& value() { return static_cast<Wrapper*>(this)->get(); }
public:
void setParent(SavedFrame* parent) { value().parent = parent; }
void setAsyncCause(Handle<JSAtom*> asyncCause) {
value().asyncCause = asyncCause;
}
};
/* static */
bool SavedFrame::HashPolicy::maybeGetHash(const Lookup& l,
HashNumber* hashOut) {
HashNumber parentHash;
if (!SavedFramePtrHasher::maybeGetHash(l.parent, &parentHash)) {
return false;
}
*hashOut = calculateHash(l, parentHash);
return true;
}
/* static */
bool SavedFrame::HashPolicy::ensureHash(const Lookup& l, HashNumber* hashOut) {
HashNumber parentHash;
if (!SavedFramePtrHasher::ensureHash(l.parent, &parentHash)) {
return false;
}
*hashOut = calculateHash(l, parentHash);
return true;
}
/* static */
HashNumber SavedFrame::HashPolicy::hash(const Lookup& lookup) {
return calculateHash(lookup, SavedFramePtrHasher::hash(lookup.parent));
}
/* static */
HashNumber SavedFrame::HashPolicy::calculateHash(const Lookup& lookup,
HashNumber parentHash) {
JS::AutoCheckCannotGC nogc;
// Assume that we can take line mod 2^32 without losing anything of
// interest. If that assumption changes, we'll just need to start with 0
// and add another overload of AddToHash with more arguments.
return AddToHash(lookup.line, lookup.column.rawValue(), lookup.source,
lookup.functionDisplayName, lookup.asyncCause,
lookup.mutedErrors, parentHash,
JSPrincipalsPtrHasher::hash(lookup.principals));
}
/* static */
bool SavedFrame::HashPolicy::match(SavedFrame* existing, const Lookup& lookup) {
MOZ_ASSERT(existing);
if (existing->getLine() != lookup.line) {
return false;
}
if (existing->getColumn() != lookup.column) {
return false;
}
if (existing->getParent() != lookup.parent) {
return false;
}
if (existing->getPrincipals() != lookup.principals) {
return false;
}
JSAtom* source = existing->getSource();
if (source != lookup.source) {
return false;
}
JSAtom* functionDisplayName = existing->getFunctionDisplayName();
if (functionDisplayName != lookup.functionDisplayName) {
return false;
}
JSAtom* asyncCause = existing->getAsyncCause();
if (asyncCause != lookup.asyncCause) {
return false;
}
return true;
}
/* static */
void SavedFrame::HashPolicy::rekey(Key& key, const Key& newKey) {
key = newKey;
}
/* static */
bool SavedFrame::finishSavedFrameInit(JSContext* cx, HandleObject ctor,
HandleObject proto) {
return FreezeObject(cx, proto);
}
static const JSClassOps SavedFrameClassOps = {
nullptr, // addProperty
nullptr, // delProperty
nullptr, // enumerate
nullptr, // newEnumerate
nullptr, // resolve
nullptr, // mayResolve
SavedFrame::finalize, // finalize
nullptr, // call
nullptr, // construct
nullptr, // trace
};
const ClassSpec SavedFrame::classSpec_ = {
GenericCreateConstructor<SavedFrame::construct, 0, gc::AllocKind::FUNCTION>,
GenericCreatePrototype<SavedFrame>,
SavedFrame::staticFunctions,
nullptr,
SavedFrame::protoFunctions,
SavedFrame::protoAccessors,
SavedFrame::finishSavedFrameInit,
ClassSpec::DontDefineConstructor,
};
/* static */ const JSClass SavedFrame::class_ = {
"SavedFrame",
JSCLASS_HAS_RESERVED_SLOTS(SavedFrame::JSSLOT_COUNT) |
JSCLASS_HAS_CACHED_PROTO(JSProto_SavedFrame) |
JSCLASS_FOREGROUND_FINALIZE,
&SavedFrameClassOps,
&SavedFrame::classSpec_,
};
const JSClass SavedFrame::protoClass_ = {
"SavedFrame.prototype",
JSCLASS_HAS_CACHED_PROTO(JSProto_SavedFrame),
JS_NULL_CLASS_OPS,
&SavedFrame::classSpec_,
};
/* static */ const JSFunctionSpec SavedFrame::staticFunctions[] = {
JS_FS_END,
};
/* static */ const JSFunctionSpec SavedFrame::protoFunctions[] = {
JS_FN("constructor", SavedFrame::construct, 0, 0),
JS_FN("toString", SavedFrame::toStringMethod, 0, 0),
JS_FS_END,
};
/* static */ const JSPropertySpec SavedFrame::protoAccessors[] = {
JS_PSG("source", SavedFrame::sourceProperty, 0),
JS_PSG("sourceId", SavedFrame::sourceIdProperty, 0),
JS_PSG("line", SavedFrame::lineProperty, 0),
JS_PSG("column", SavedFrame::columnProperty, 0),
JS_PSG("functionDisplayName", SavedFrame::functionDisplayNameProperty, 0),
JS_PSG("asyncCause", SavedFrame::asyncCauseProperty, 0),
JS_PSG("asyncParent", SavedFrame::asyncParentProperty, 0),
JS_PSG("parent", SavedFrame::parentProperty, 0),
JS_STRING_SYM_PS(toStringTag, "SavedFrame", JSPROP_READONLY),
JS_PS_END,
};
/* static */
void SavedFrame::finalize(JS::GCContext* gcx, JSObject* obj) {
MOZ_ASSERT(gcx->onMainThread());
JSPrincipals* p = obj->as<SavedFrame>().getPrincipals();
if (p) {
JSRuntime* rt = obj->runtimeFromMainThread();
JS_DropPrincipals(rt->mainContextFromOwnThread(), p);
}
}
JSAtom* SavedFrame::getSource() {
const Value& v = getReservedSlot(JSSLOT_SOURCE);
JSString* s = v.toString();
return &s->asAtom();
}
uint32_t SavedFrame::getSourceId() {
const Value& v = getReservedSlot(JSSLOT_SOURCEID);
return v.toPrivateUint32();
}
uint32_t SavedFrame::getLine() {
const Value& v = getReservedSlot(JSSLOT_LINE);
return v.toPrivateUint32();
}
JS::TaggedColumnNumberOneOrigin SavedFrame::getColumn() {
const Value& v = getReservedSlot(JSSLOT_COLUMN);
return JS::TaggedColumnNumberOneOrigin::fromRaw(v.toPrivateUint32());
}
JSAtom* SavedFrame::getFunctionDisplayName() {
const Value& v = getReservedSlot(JSSLOT_FUNCTIONDISPLAYNAME);
if (v.isNull()) {
return nullptr;
}
JSString* s = v.toString();
return &s->asAtom();
}
JSAtom* SavedFrame::getAsyncCause() {
const Value& v = getReservedSlot(JSSLOT_ASYNCCAUSE);
if (v.isNull()) {
return nullptr;
}
JSString* s = v.toString();
return &s->asAtom();
}
SavedFrame* SavedFrame::getParent() const {
const Value& v = getReservedSlot(JSSLOT_PARENT);
return v.isObject() ? &v.toObject().as<SavedFrame>() : nullptr;
}
JSPrincipals* SavedFrame::getPrincipals() {
const Value& v = getReservedSlot(JSSLOT_PRINCIPALS);
if (v.isUndefined()) {
return nullptr;
}
return reinterpret_cast<JSPrincipals*>(uintptr_t(v.toPrivate()) & ~0b1);
}
bool SavedFrame::getMutedErrors() {
const Value& v = getReservedSlot(JSSLOT_PRINCIPALS);
if (v.isUndefined()) {
return true;
}
return bool(uintptr_t(v.toPrivate()) & 0b1);
}
void SavedFrame::initSource(JSAtom* source) {
MOZ_ASSERT(source);
initReservedSlot(JSSLOT_SOURCE, StringValue(source));
}
void SavedFrame::initSourceId(uint32_t sourceId) {
initReservedSlot(JSSLOT_SOURCEID, PrivateUint32Value(sourceId));
}
void SavedFrame::initLine(uint32_t line) {
initReservedSlot(JSSLOT_LINE, PrivateUint32Value(line));
}
void SavedFrame::initColumn(JS::TaggedColumnNumberOneOrigin column) {
if (js::SupportDifferentialTesting()) {
column = JS::TaggedColumnNumberOneOrigin::forDifferentialTesting();
}
initReservedSlot(JSSLOT_COLUMN, PrivateUint32Value(column.rawValue()));
}
void SavedFrame::initPrincipalsAndMutedErrors(JSPrincipals* principals,
bool mutedErrors) {
if (principals) {
JS_HoldPrincipals(principals);
}
initPrincipalsAlreadyHeldAndMutedErrors(principals, mutedErrors);
}
void SavedFrame::initPrincipalsAlreadyHeldAndMutedErrors(
JSPrincipals* principals, bool mutedErrors) {
MOZ_ASSERT_IF(principals, principals->refcount > 0);
uintptr_t ptr = uintptr_t(principals) | mutedErrors;
initReservedSlot(JSSLOT_PRINCIPALS,
PrivateValue(reinterpret_cast<void*>(ptr)));
}
void SavedFrame::initFunctionDisplayName(JSAtom* maybeName) {
initReservedSlot(JSSLOT_FUNCTIONDISPLAYNAME,
maybeName ? StringValue(maybeName) : NullValue());
}
void SavedFrame::initAsyncCause(JSAtom* maybeCause) {
initReservedSlot(JSSLOT_ASYNCCAUSE,
maybeCause ? StringValue(maybeCause) : NullValue());
}
void SavedFrame::initParent(SavedFrame* maybeParent) {
initReservedSlot(JSSLOT_PARENT, ObjectOrNullValue(maybeParent));
}
void SavedFrame::initFromLookup(JSContext* cx, Handle<Lookup> lookup) {
// Make sure any atoms used in the lookup are marked in the current zone.
// Normally we would try to keep these mark bits up to date around the
// points where the context moves between compartments, but Lookups live on
// the stack (where the atoms are kept alive regardless) and this is a
// more convenient pinchpoint.
if (lookup.source()) {
cx->markAtom(lookup.source());
}
if (lookup.functionDisplayName()) {
cx->markAtom(lookup.functionDisplayName());
}
if (lookup.asyncCause()) {
cx->markAtom(lookup.asyncCause());
}
initSource(lookup.source());
initSourceId(lookup.sourceId());
initLine(lookup.line());
initColumn(lookup.column());
initFunctionDisplayName(lookup.functionDisplayName());
initAsyncCause(lookup.asyncCause());
initParent(lookup.parent());
initPrincipalsAndMutedErrors(lookup.principals(), lookup.mutedErrors());
}
/* static */
SavedFrame* SavedFrame::create(JSContext* cx) {
Rooted<GlobalObject*> global(cx, cx->global());
cx->check(global);
// Ensure that we don't try to capture the stack again in the
// `SavedStacksMetadataBuilder` for this new SavedFrame object, and
// accidentally cause O(n^2) behavior.
SavedStacks::AutoReentrancyGuard guard(cx->realm()->savedStacks());
RootedObject proto(cx,
GlobalObject::getOrCreateSavedFramePrototype(cx, global));
if (!proto) {
return nullptr;
}
cx->check(proto);
return NewTenuredObjectWithGivenProto<SavedFrame>(cx, proto);
}
bool SavedFrame::isSelfHosted(JSContext* cx) {
JSAtom* source = getSource();
return source == cx->names().self_hosted_;
}
bool SavedFrame::isWasm() { return getColumn().isWasmFunctionIndex(); }
uint32_t SavedFrame::wasmFuncIndex() {
return getColumn().toWasmFunctionIndex().value();
}
uint32_t SavedFrame::wasmBytecodeOffset() {
MOZ_ASSERT(isWasm());
return getLine();
}
/* static */
bool SavedFrame::construct(JSContext* cx, unsigned argc, Value* vp) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_NO_CONSTRUCTOR,
"SavedFrame");
return false;
}
static bool SavedFrameSubsumedByPrincipals(JSContext* cx,
JSPrincipals* principals,
Handle<SavedFrame*> frame) {
auto subsumes = cx->runtime()->securityCallbacks->subsumes;
if (!subsumes) {
return true;
}
MOZ_ASSERT(!ReconstructedSavedFramePrincipals::is(principals));
auto framePrincipals = frame->getPrincipals();
// Handle SavedFrames that have been reconstructed from stacks in a heap
// snapshot.
if (framePrincipals == &ReconstructedSavedFramePrincipals::IsSystem) {
return cx->runningWithTrustedPrincipals();
}
if (framePrincipals == &ReconstructedSavedFramePrincipals::IsNotSystem) {
return true;
}
return subsumes(principals, framePrincipals);
}
// Return the first SavedFrame in the chain that starts with |frame| whose
// for which the given match function returns true. If there is no such frame,
// return nullptr. |skippedAsync| is set to true if any of the skipped frames
// had the |asyncCause| property set, otherwise it is explicitly set to false.
template <typename Matcher>
static SavedFrame* GetFirstMatchedFrame(JSContext* cx, JSPrincipals* principals,
Matcher& matches,
Handle<SavedFrame*> frame,
JS::SavedFrameSelfHosted selfHosted,
bool& skippedAsync) {
skippedAsync = false;
Rooted<SavedFrame*> rootedFrame(cx, frame);
while (rootedFrame) {
if ((selfHosted == JS::SavedFrameSelfHosted::Include ||
!rootedFrame->isSelfHosted(cx)) &&
matches(cx, principals, rootedFrame)) {
return rootedFrame;
}
if (rootedFrame->getAsyncCause()) {
skippedAsync = true;
}
rootedFrame = rootedFrame->getParent();
}
return nullptr;
}
// Return the first SavedFrame in the chain that starts with |frame| whose
// principals are subsumed by |principals|, according to |subsumes|. If there is
// no such frame, return nullptr. |skippedAsync| is set to true if any of the
// skipped frames had the |asyncCause| property set, otherwise it is explicitly
// set to false.
static SavedFrame* GetFirstSubsumedFrame(JSContext* cx,
JSPrincipals* principals,
Handle<SavedFrame*> frame,
JS::SavedFrameSelfHosted selfHosted,
bool& skippedAsync) {
return GetFirstMatchedFrame(cx, principals, SavedFrameSubsumedByPrincipals,
frame, selfHosted, skippedAsync);
}
JS_PUBLIC_API JSObject* GetFirstSubsumedSavedFrame(
JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
JS::SavedFrameSelfHosted selfHosted) {
if (!savedFrame) {
return nullptr;
}
auto subsumes = cx->runtime()->securityCallbacks->subsumes;
if (!subsumes) {
return nullptr;
}
auto matcher = [subsumes](JSContext* cx, JSPrincipals* principals,
Handle<SavedFrame*> frame) -> bool {
return subsumes(principals, frame->getPrincipals());
};
bool skippedAsync;
Rooted<SavedFrame*> frame(cx, &savedFrame->as<SavedFrame>());
return GetFirstMatchedFrame(cx, principals, matcher, frame, selfHosted,
skippedAsync);
}
[[nodiscard]] static bool SavedFrame_checkThis(JSContext* cx, CallArgs& args,
const char* fnName,
MutableHandleObject frame) {
const Value& thisValue = args.thisv();
if (!thisValue.isObject()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_OBJECT_REQUIRED,
InformalValueTypeName(thisValue));
return false;
}
if (!thisValue.toObject().canUnwrapAs<SavedFrame>()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_INCOMPATIBLE_PROTO, SavedFrame::class_.name,
fnName, "object");
return false;
}
// Now set "frame" to the actual object we were invoked in (which may be a
// wrapper), not the unwrapped version. Consumers will need to know what
// that original object was, and will do principal checks as needed.
frame.set(&thisValue.toObject());
return true;
}
// Get the SavedFrame * from the current this value and handle any errors that
// might occur therein.
//
// These parameters must already exist when calling this macro:
// - JSContext* cx
// - unsigned argc
// - Value* vp
// - const char* fnName
// These parameters will be defined after calling this macro:
// - CallArgs args
// - Rooted<SavedFrame*> frame (will be non-null)
#define THIS_SAVEDFRAME(cx, argc, vp, fnName, args, frame) \
CallArgs args = CallArgsFromVp(argc, vp); \
RootedObject frame(cx); \
if (!SavedFrame_checkThis(cx, args, fnName, &frame)) return false;
} /* namespace js */
js::SavedFrame* js::UnwrapSavedFrame(JSContext* cx, JSPrincipals* principals,
HandleObject obj,
JS::SavedFrameSelfHosted selfHosted,
bool& skippedAsync) {
if (!obj) {
return nullptr;
}
Rooted<SavedFrame*> frame(cx, obj->maybeUnwrapAs<SavedFrame>());
if (!frame) {
return nullptr;
}
return GetFirstSubsumedFrame(cx, principals, frame, selfHosted, skippedAsync);
}
namespace JS {
JS_PUBLIC_API SavedFrameResult GetSavedFrameSource(
JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
MutableHandleString sourcep,
SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */) {
js::AssertHeapIsIdle();
CHECK_THREAD(cx);
MOZ_RELEASE_ASSERT(cx->realm());
{
bool skippedAsync;
Rooted<js::SavedFrame*> frame(
cx,
UnwrapSavedFrame(cx, principals, savedFrame, selfHosted, skippedAsync));
if (!frame) {
sourcep.set(cx->runtime()->emptyString);
return SavedFrameResult::AccessDenied;
}
sourcep.set(frame->getSource());
}
if (sourcep->isAtom()) {
cx->markAtom(&sourcep->asAtom());
}
return SavedFrameResult::Ok;
}
JS_PUBLIC_API SavedFrameResult GetSavedFrameSourceId(
JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
uint32_t* sourceIdp,
SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */) {
js::AssertHeapIsIdle();
CHECK_THREAD(cx);
MOZ_RELEASE_ASSERT(cx->realm());
bool skippedAsync;
Rooted<js::SavedFrame*> frame(cx, UnwrapSavedFrame(cx, principals, savedFrame,
selfHosted, skippedAsync));
if (!frame) {
*sourceIdp = 0;
return SavedFrameResult::AccessDenied;
}
*sourceIdp = frame->getSourceId();
return SavedFrameResult::Ok;
}
JS_PUBLIC_API SavedFrameResult GetSavedFrameLine(
JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
uint32_t* linep,
SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */) {
js::AssertHeapIsIdle();
CHECK_THREAD(cx);
MOZ_RELEASE_ASSERT(cx->realm());
MOZ_ASSERT(linep);
bool skippedAsync;
Rooted<js::SavedFrame*> frame(cx, UnwrapSavedFrame(cx, principals, savedFrame,
selfHosted, skippedAsync));
if (!frame) {
*linep = 0;
return SavedFrameResult::AccessDenied;
}
*linep = frame->getLine();
return SavedFrameResult::Ok;
}
JS_PUBLIC_API SavedFrameResult GetSavedFrameColumn(
JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
JS::TaggedColumnNumberOneOrigin* columnp,
SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */) {
js::AssertHeapIsIdle();
CHECK_THREAD(cx);
MOZ_RELEASE_ASSERT(cx->realm());
MOZ_ASSERT(columnp);
bool skippedAsync;
Rooted<js::SavedFrame*> frame(cx, UnwrapSavedFrame(cx, principals, savedFrame,
selfHosted, skippedAsync));
if (!frame) {
*columnp = JS::TaggedColumnNumberOneOrigin();
return SavedFrameResult::AccessDenied;
}
*columnp = frame->getColumn();
return SavedFrameResult::Ok;
}
JS_PUBLIC_API SavedFrameResult GetSavedFrameFunctionDisplayName(
JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
MutableHandleString namep,
SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */) {
js::AssertHeapIsIdle();
CHECK_THREAD(cx);
MOZ_RELEASE_ASSERT(cx->realm());
{
bool skippedAsync;
Rooted<js::SavedFrame*> frame(
cx,
UnwrapSavedFrame(cx, principals, savedFrame, selfHosted, skippedAsync));
if (!frame) {
namep.set(nullptr);
return SavedFrameResult::AccessDenied;
}
namep.set(frame->getFunctionDisplayName());
}
if (namep && namep->isAtom()) {
cx->markAtom(&namep->asAtom());
}
return SavedFrameResult::Ok;
}
JS_PUBLIC_API SavedFrameResult GetSavedFrameAsyncCause(
JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
MutableHandleString asyncCausep,
SavedFrameSelfHosted unused_ /* = SavedFrameSelfHosted::Include */) {
js::AssertHeapIsIdle();
CHECK_THREAD(cx);
MOZ_RELEASE_ASSERT(cx->realm());
{
bool skippedAsync;
// This function is always called with self-hosted frames excluded by
// GetValueIfNotCached in dom/bindings/Exceptions.cpp. However, we want
// to include them because our Promise implementation causes us to have
// the async cause on a self-hosted frame. So we just ignore the
// parameter and always include self-hosted frames.
Rooted<js::SavedFrame*> frame(
cx, UnwrapSavedFrame(cx, principals, savedFrame,
SavedFrameSelfHosted::Include, skippedAsync));
if (!frame) {
asyncCausep.set(nullptr);
return SavedFrameResult::AccessDenied;
}
asyncCausep.set(frame->getAsyncCause());
if (!asyncCausep && skippedAsync) {
asyncCausep.set(cx->names().Async);
}
}
if (asyncCausep && asyncCausep->isAtom()) {
cx->markAtom(&asyncCausep->asAtom());
}
return SavedFrameResult::Ok;
}
JS_PUBLIC_API SavedFrameResult GetSavedFrameAsyncParent(
JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
MutableHandleObject asyncParentp,
SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */) {
js::AssertHeapIsIdle();
CHECK_THREAD(cx);
MOZ_RELEASE_ASSERT(cx->realm());
bool skippedAsync;
Rooted<js::SavedFrame*> frame(cx, UnwrapSavedFrame(cx, principals, savedFrame,
selfHosted, skippedAsync));
if (!frame) {
asyncParentp.set(nullptr);
return SavedFrameResult::AccessDenied;
}
Rooted<js::SavedFrame*> parent(cx, frame->getParent());
// The current value of |skippedAsync| is not interesting, because we are
// interested in whether we would cross any async parents to get from here
// to the first subsumed parent frame instead.
Rooted<js::SavedFrame*> subsumedParent(
cx,
GetFirstSubsumedFrame(cx, principals, parent, selfHosted, skippedAsync));
// Even if |parent| is not subsumed, we still want to return a pointer to it
// rather than |subsumedParent| so it can pick up any |asyncCause| from the
// inaccessible part of the chain.
if (subsumedParent && (subsumedParent->getAsyncCause() || skippedAsync)) {
asyncParentp.set(parent);
} else {
asyncParentp.set(nullptr);
}
return SavedFrameResult::Ok;
}
JS_PUBLIC_API SavedFrameResult GetSavedFrameParent(
JSContext* cx, JSPrincipals* principals, HandleObject savedFrame,
MutableHandleObject parentp,
SavedFrameSelfHosted selfHosted /* = SavedFrameSelfHosted::Include */) {
js::AssertHeapIsIdle();
CHECK_THREAD(cx);
MOZ_RELEASE_ASSERT(cx->realm());
bool skippedAsync;
Rooted<js::SavedFrame*> frame(cx, UnwrapSavedFrame(cx, principals, savedFrame,
selfHosted, skippedAsync));
if (!frame) {
parentp.set(nullptr);
return SavedFrameResult::AccessDenied;
}
Rooted<js::SavedFrame*> parent(cx, frame->getParent());
// The current value of |skippedAsync| is not interesting, because we are
// interested in whether we would cross any async parents to get from here
// to the first subsumed parent frame instead.
Rooted<js::SavedFrame*> subsumedParent(
cx,
GetFirstSubsumedFrame(cx, principals, parent, selfHosted, skippedAsync));
// Even if |parent| is not subsumed, we still want to return a pointer to it
// rather than |subsumedParent| so it can pick up any |asyncCause| from the
// inaccessible part of the chain.
if (subsumedParent && !(subsumedParent->getAsyncCause() || skippedAsync)) {
parentp.set(parent);
} else {
parentp.set(nullptr);
}
return SavedFrameResult::Ok;
}
static bool FormatStackFrameLine(js::StringBuilder& sb,
JS::Handle<js::SavedFrame*> frame) {
if (frame->isWasm()) {
// See comment in WasmFrameIter::computeLine().
return sb.append("wasm-function[") &&
NumberValueToStringBuilder(NumberValue(frame->wasmFuncIndex()),
sb) &&
sb.append(']');
}
return NumberValueToStringBuilder(NumberValue(frame->getLine()), sb);
}
static bool FormatStackFrameColumn(js::StringBuilder& sb,
JS::Handle<js::SavedFrame*> frame) {
if (frame->isWasm()) {
// See comment in WasmFrameIter::computeLine().
js::Int32ToCStringBuf cbuf;
size_t cstrlen;
const char* cstr =
Uint32ToHexCString(&cbuf, frame->wasmBytecodeOffset(), &cstrlen);
MOZ_ASSERT(cstr);
return sb.append("0x") && sb.append(cstr, cstrlen);
}
return NumberValueToStringBuilder(
NumberValue(frame->getColumn().oneOriginValue()), sb);
}
static bool FormatSpiderMonkeyStackFrame(JSContext* cx, js::StringBuilder& sb,
JS::Handle<js::SavedFrame*> frame,
size_t indent, bool skippedAsync) {
RootedString asyncCause(cx, frame->getAsyncCause());
if (!asyncCause && skippedAsync) {
asyncCause.set(cx->names().Async);
}
Rooted<JSAtom*> name(cx, frame->getFunctionDisplayName());
return (!indent || sb.appendN(' ', indent)) &&