Files
palemoon27/dom/bindings/Exceptions.cpp
T
roytam1 5499b4356b import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1155371 - Include DOMMediaStream and MediaSource object URLs in memory reports. r=khuey (b62513f5c6)
- Bug 1187782 (part 1) - Replace nsBaseHashtable::EnumerateRead() calls in dom/base/ with iterators. r=khuey. (aa14b536c4)
- Bug 1187782 (part 2) - Replace nsBaseHashtable::EnumerateRead() calls in dom/base/ with iterators. r=khuey. (1645a9b910)
- Bug 1187782 (part 3) - Replace nsBaseHashtable::EnumerateRead() calls in dom/base/ with iterators. r=khuey. (67a83f37d5)
- Bug 1187782 (part 4) - Replace nsBaseHashtable::EnumerateRead() calls in dom/base/ with iterators. r=khuey. (bf1f7a8dfe)
- Bug 1187782 (part 5) - Replace nsBaseHashtable::EnumerateRead() calls in dom/base/ with iterators. r=khuey. (b76f1f34c8)
- Bug 1187782 (part 6) - Replace nsBaseHashtable::EnumerateRead() calls in dom/base/ with iterators. r=khuey. (f44312f3a9)
- Bug 1187782 (part 7) - Replace nsBaseHashtable::EnumerateRead() calls in dom/base/ with iterators. r=khuey. (33bb281955)
- Bug 1187782 (part 8) - Replace nsBaseHashtable::EnumerateRead() calls in dom/base/ with iterators. r=khuey. (52f7bc040e)
- Bug 1187782 (part 9) - Replace nsBaseHashtable::EnumerateRead() calls in dom/base/ with iterators. r=khuey. (7e797025a3)
- Bug 1207355 (Part 1) - Stop requesting decodes in nsDocument. r=tn (b2e6eb49c0)
- Bug 1202085 - Part 1: Remove imgICache::RemoveEntry(); r=seth (b5e4e2242f)
- Bug 1202085 - Part 2: Add an optional document argument to imgICache::FindEntryProperties(); r=seth (3f3138e5ba)
- Bug 1202085 - Part 3: Relax the assertion in ServiceWorkerManager::IsControlled to only happen when we think the document is controlled; r=jdm (6a829a6985)
- Bug 1202085 - Part 4: Add an ID for controlled document to the image cache key; r=seth (525ca69231)
- Bug 1202085 - Part 5: Add an automated test for the interaction of image cache with controlled documents; r=jdm (627e28d58d)
- Bug 1202085 - Part 6: Clear the entries in the image cache belonging to a controlled document when it gets destroyed; r=seth (935b858eac)
- Bug 1221279 Don't crash while clearing imgLoader cache when disconnected document is destroyed. r=smaug (040d3fa2be)
- Bug 1207084 - keep sheet level on tokenstream for use in ruledata when resolving variables, to fix hcm issues with CSS variables, r=heycam (2d8f5af005)
- Bug 1207084 - addendum: fix operator== for nsCSSValueTokenStream, implied-r=heycam (ee66d21638)
- Bug 1209124 - Bail out of nsStyleSet::GatherRuleProcessors and PresShell::Observe if we're called during/after shutdown. r=dbaron (7043eb3ee7)
- Bug 1216043 - Rename nsStyleSheet::sheetType and make it an enum class. r=dbaron (f03c5328e6)
- Bug 1168158 - Make URLValue::mString a smart pointer. r=heycam (06e37619be)
- Bug 1216038 - Deduce underlying integer type for MakeEnumeratedRange starting at 0. r=froydnj (883c74fb6b)
- Bug 1216040 - Make ArrayLength support mozilla::EnumeratedArray. r=froydnj (d1fc4aa43c)
- Bug 1216041 - Add ranged iterator support to mozilla::{Array,RangedArray,EnumerationArray}. r=froydnj (bf71f0ea1f)
- Bug 1128787 part.1 Add test r=ehsan (97016bbd85)
- Bug 1128787 part.2 nsHTMLDocument should clear focus before making itself editable when designMode is enabled and it makes the focused content non-focusable r=smaug+enndeakin (eccab99994)
- Bug 1171342 - Store contenteditable.css and designmode.css in the style sheet cache. r=jwatt (7e6aa290d2)
- Bug 1164279 - Disable font-variant-east-asian: ruby for <rt> on Windows. r=jfkthame (04117062d7)
- Bug 1126230 part 9 - Remove fullscreen override and related test. r=dbaron (18818d67fa)
- Bug 1126230 part 1 - Use delegated constructor to simplify constructor of nsFrameConstructorState. r=bz (5c1193f9f5)
- Bug 1126230 part 2 - Refactor part of nsFrameConstructorState::AddChild. r=bz (3c02f9e8c2)
- Bug 1126230 part 3 - Add :-moz-browser-frame pseudo class for HTML browser frame elements. r=dbaron (6a7b01f092)
- Bug 1211040 - Restrict -moz-window-{dragging,shadow} to be chrome-only. r=dbaron (005f02f673)
- Bug 1126230 part 4 - Add -moz-top-layer internal CSS property and set it for fullscreen elements. r=dbaron (02d841cab7)
- Bug 1203405 - Ignore order of abs/fixed-pos frames in the frame list. r=roc (d67696d0ea)
- Bug 1126230 part 5 - Give proper geometric parent for top layer frames. r=bz,dbaron (19504f223e)
- Bug 1126230 part 6 - Add nsIDocument::GetFullscreenStack() method. r=smaug (d401d534d1)
- Bug 1126230 part 7 - Add static method nsDisplayListBuilder::GetOutOfFlowData(). r=roc (3bdafef9b2)
- Bug 1126230 part 8 - Implement painting part for the top layer. r=roc (8875115dc1)
- Bug 1126230 part 10 - Add test for fullscreen top layer. r=dbaron (d095d85cd0)
- Bug 1069192 part 1 - Force users of nsCSSProps::IsEnabled() to pass in the enabled state. r=dbaron (38e40ebf1d)
- Bug 1195978 - set line number when re-parsing sheet. r=heycam (41cdf15319)
- Bug 1202095 - re-use @imported style sheets from inIDOMUtils.parseStyleSheet. r=heycam (2f54fdacf0)
- Bug 1099557 followup - Put the default setting for control-character visibility behind a runtime pref, and keep it off-by-default on release builds for now. r=dbaron (3ada076d9b)
- Bug 1069192 part 2 - Add a flag for chrome-only properties and change semantics of enabling flags. r=dbaron (2e887397ac)
- Bug 1220496 - Create PresHint/StyleAttr rule processors in nsStyleSet::Init and make DirtyRuleProcessors private. r=bzbarsky (0b538fe7cc)
- No bug - Cleanup the layout/style mochitest manifest. (e26676496f)
- Bug 1183461 part 1 - Move InitialAdvance to CSSAnimation; r=heycam (dac91a759a)
- Bug 1183461 part 2 - Reorder the parameters to EventInfo constructors; r=heycam (29fc1b2096)
- Bug 1183461 part 3 - Add Animation::AnimationTimeToTimeStamp; r=heycam (d3410ccc01)
- Bug 1183461 part 4 - Add CSSAnimation::ElapsedTimeToTimeStamp; r=heycam (10bac42e8e)
- Bug 1183461 part 5 - Store event TimeStamp along with event info; r=heycam (0250a63ee8)
- Bug 1220599 - Fix erroneous nsHTMLDocument::Open comment to note that we reuse the document rather than creating a new one. r=baku (5d492865d3)
- Bug 1220827 - Replace question comment in nsHTMLDocument::Open with an explanatory comment to explain why we create a new Window. r=smaug (69f16ef5dc)
- missing bits of  Bug 1170911 - Add pref for switching off execCommand("cut"/"copy"). r=ehsan (613644fa39)
- Bug 1183461 part 6 - Store the generating animation on the event; r=heycam (c490af70cc)
- Bug 1194037 part 4 - Remove ticking from FlushAnimations; r=dholbert (8df1f3eec4)
- Bug 1200568 - Don't create animations for elements that are not part of the document tree; r=dbaron (3027949d8b)
- Bug 1183461 part 7 - Add EventInfoComparator and sort events; r=heycam (550aad09bc)
- Bug 1183461 part 8 - Add tests for event order dispatch; r=heycam (964ee5fe23)
- Bug 978833 patch 1 - Add mochitest for bug 978833. r=heycam (4b4579d3f7)
- Bug 1208951 - Part 1: Split half of KeyframeValueEntry into a base class. r=birtles (32d7cbd477)
- Bug 1208951 - Part 2: Use a comparator object instead of operator< onKeyframeValueEntry. r=birtles (3b83723ef0)
- Bug 1209603 patch 1 - Add comments to RuleNodeCacheConditions.h . r=heycam (444eabdddc)
- Bug 1209603 patch 2 - Reduce calls to StyleVisibility() in WritingMode constructor. r=heycam (f079fb5765)
- Bug 1209603 patch 3 - Don't call SetFontSizeDependency for 0em. r=heycam (7a87fe5229)
- Bug 1209603 patch 4 - Add reftest for bug 1209603. r=heycam (1680144fc2)
- Bug 1209603 patch 5 - Move inline method nsStyleContext::GetCachedStyleData into header file, and make it public. r=heycam (32c38f790e)
- Bug 1209603 patch 6 - Prepare to use a different meaning of mBits when cached style data pointer is null. r=heycam (15e6471e58)
- Bug 1209603 patch 7 - Add assertions that we don't ask the rule node for data when we have cached data on the style context. r=heycam (0f27687446)
- Bug 1209603 patch 8 - Record in mBits when we have gotten a reset style struct that is cached on the rule node. r=heycam (b5e693a986)
- Bug 1209603 patch 9 - Cache inherited style structs on the style context when we found already-cached data in the rule tree. r=heycam (bfa6a169cb)
- Bug 1209603 patch 10 - Make PeekStyle* exact, i.e., guaranteed to return null if we haven't computed the data for this context. r=heycam (6ffdf7f0bf)
- Bug 1209603 patch 11 - Assert that PeekStyle* results don't change during difference computation. r=heycam (a3d7336dce)
- Bug 1193518 - Ensure that when we update a WritingMode after resolving dir=auto, we set the inline-dir bit appropriately as well as the inline-bidi bit. r=dholbert (072c062ddc)
- Bug 1216431 patch 1 - Give WritingMode an nsStyleVisibility* constructor. r=heycam (b7efb1204c)
- Bug 1216431 patch 2 - Pass nsStyleVisibility to nsStylePosition::CalcDifference to avoid computing new nsStyleVisibility during nsStyleContext::CalcStyleDifference. r=heycam (b842123d9b)
- Bug 1216431 patch 3 - Cache structs that are stored with conditions on the rule node all the time, rather than only when freshly computed. r=heycam (d4ea9adc19)
- Bug 1216431 patch 4 - Don't trigger computation of new structs via testing of conditions for conditionally-stored structs on the rule node. r=heycam (95cc7e8a52)
- Bug 1216431 patch 5 - Back out half of bug 1209603 patch 10. r=heycam (5949a2e9d0)
- Bug 1216431 patch 6 - Back out bug 1209603 patch 8. r=heycam (45a05ad60e)
- Bug 1209603 patch 6b - Rename nsStyleContext::HasCachedInheritedStyleData to HasCachedDependentStyleData. r=heycam (c4f52f00d0)
- Bug 1216431 patch 7 - Back out bug 1209603 patch 6. r=heycam (6eb8677af2)
- Bug 1216431 patch 8 - Fix whitespace error I made when addressing review comments. (19abf29215)
- Bug 1214958 - Add operators &=, |=, and ^= to mozilla::DebugOnly. r=froydnj (c76229e817)
- Bug 1208951 - Part 3: Expose nsCSSValue -> nsTimingFunction computation function. r=birtles (f0124bbbf2)
- Bug 1208951 - Part 4: Add an nsCSSParser entry point to parse a single longhand property and return an nsCSSValue. r=birtles (a317aa3255)
- Bug 1208951 - Part 5: Add nsCSSProps method to look a property by its IDL name. r=bzbarsky (1d0b78374d)
- Bug 1208951 - Part 6: Add method to compare nsCSSPropertySets for equality. r=birtles (9039197290)
- Bug 1208951 - Part 7: Add a StyleAnimationValue::ComputeValues method to compute components of a shorthand. r=birtles (36149d8c82)
- Bug 1208951 - Part 8: Don't warn if StyleAnimationValue::ComputeValue fails to parse a CSS property. r=birtles (12e06d0356)
- Bug 1208385 part 1 - Store a pointer to the owning animation on each KeyframeEffect; r=heycam (8f48533047)
- Bug 1208385 part 2 - Remove stored parent time from KeyframeEffectReadOnly and get the time directly from the owning animation; r=heycam (7bd25845be)
- Bug 1208951 - Part 9: Implement KeyframeEffectReadOnly constructor. r=bzbarsky r=birtles (49049edfac)
- Bug 1208951 - Part 10: Make GetFrames aware of initial/final zero-length segments and discontinuities between segments. r=birtles (71066c4941)
- Bug 1208951 - Part 11: Tests. r=birtles (308ad9ba9f)
- Bug 1210575 part 1: Rename CSS parser function "ParseWebkitPrefixedGradient()" to be more specific, now that we'll have several ways of parsing these expressions. r=heycam (060a01b43a)
- Bug 1210575 part 2: Refactor out the body of a long compound "if" expression into a helper function, IsFunctionTokenValidForBackgroundImage. r=heycam (ed784fb98d)
- Bug 1210575 part 3: Refactor CSS gradient-parsing code to use a flags bitfield instead of multiple bool args for customizing behavior. r=heycam (5c9df6466c)
- Bug 1210575 part 4: Prevent CSS parser from invoking CSSUnprefixingService if native webkit prefix support is enabled. r=heycam (d4c7997c94)
- Bug 1210575 part 5: Allow CSS -webkit-{linear|radial}-gradient expressions (& 'repeating' variants) to make it to our gradient-parsing code, if webkit prefix support is preffed on. r=heycam (4113bb47c4)
- Bug 1207002 - Use CSS property flag to restrict MathML-related internal properties. r=dbaron (9b021c7819)
- Bug 1199610 - Correctly handle parsing failures inside CSS functions. r=dbaron (5255fe445d)
- Bug 1210575 part 6: Implement -webkit-radial-gradient parse quirks with contain/cover keywords, sized shapes, "at" keyword, & angles. r=heycam (ba1002fbae)
- Bug 1210575 part 7: Refactor linear-gradient parsing code slightly & add/extend comments. r=heycam (1bd144ff04)
- Bug 1210575 part 8: Implement -webkit-linear-gradient parse quirks with "to", angles, and "center". r=heycam (97587d49ea)
- Bug 1210575 part 9: Remove some obsolete XXXdholbert comments from property_database.js. (no review, comment-only so DONTBUILD) (961a2c43e9)
- Bug 978833 patch 2 - Make css::Declaration reference-counted. r=heycam (4aab911856)
2022-11-10 09:36:53 +08:00

828 lines
20 KiB
C++

/* -*- 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 "mozilla/dom/Exceptions.h"
#include "js/GCAPI.h"
#include "js/TypeDecls.h"
#include "jsapi.h"
#include "jsprf.h"
#include "mozilla/CycleCollectedJSRuntime.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/DOMException.h"
#include "mozilla/dom/ScriptSettings.h"
#include "nsIProgrammingLanguage.h"
#include "nsPIDOMWindow.h"
#include "nsServiceManagerUtils.h"
#include "nsThreadUtils.h"
#include "XPCWrapper.h"
#include "WorkerPrivate.h"
#include "nsContentUtils.h"
namespace mozilla {
namespace dom {
bool
ThrowExceptionObject(JSContext* aCx, nsIException* aException)
{
// See if we really have an Exception.
nsCOMPtr<Exception> exception = do_QueryInterface(aException);
if (exception) {
return ThrowExceptionObject(aCx, exception);
}
// We only have an nsIException (probably an XPCWrappedJS). Fall back on old
// wrapping.
MOZ_ASSERT(NS_IsMainThread());
JS::Rooted<JSObject*> glob(aCx, JS::CurrentGlobalOrNull(aCx));
if (!glob) {
// XXXbz Can this really be null here?
return false;
}
JS::Rooted<JS::Value> val(aCx);
if (!WrapObject(aCx, aException, &NS_GET_IID(nsIException), &val)) {
return false;
}
JS_SetPendingException(aCx, val);
return true;
}
bool
ThrowExceptionObject(JSContext* aCx, Exception* aException)
{
JS::Rooted<JS::Value> thrown(aCx);
// If we stored the original thrown JS value in the exception
// (see XPCConvert::ConstructException) and we are in a web context
// (i.e., not chrome), rethrow the original value. This only applies to JS
// implemented components so we only need to check for this on the main
// thread.
if (NS_IsMainThread() && !nsContentUtils::IsCallerChrome() &&
aException->StealJSVal(thrown.address())) {
if (!JS_WrapValue(aCx, &thrown)) {
return false;
}
JS_SetPendingException(aCx, thrown);
return true;
}
JS::Rooted<JSObject*> glob(aCx, JS::CurrentGlobalOrNull(aCx));
if (!glob) {
// XXXbz Can this actually be null here?
return false;
}
if (!GetOrCreateDOMReflector(aCx, aException, &thrown)) {
return false;
}
JS_SetPendingException(aCx, thrown);
return true;
}
bool
Throw(JSContext* aCx, nsresult aRv, const nsACString& aMessage)
{
if (aRv == NS_ERROR_UNCATCHABLE_EXCEPTION) {
// Nuke any existing exception on aCx, to make sure we're uncatchable.
JS_ClearPendingException(aCx);
return false;
}
if (JS_IsExceptionPending(aCx)) {
// Don't clobber the existing exception.
return false;
}
CycleCollectedJSRuntime* runtime = CycleCollectedJSRuntime::Get();
nsCOMPtr<nsIException> existingException = runtime->GetPendingException();
if (existingException) {
nsresult nr;
if (NS_SUCCEEDED(existingException->GetResult(&nr)) &&
aRv == nr) {
// Reuse the existing exception.
// Clear pending exception
runtime->SetPendingException(nullptr);
if (!ThrowExceptionObject(aCx, existingException)) {
// If we weren't able to throw an exception we're
// most likely out of memory
JS_ReportOutOfMemory(aCx);
}
return false;
}
}
RefPtr<Exception> finalException = CreateException(aCx, aRv, aMessage);
MOZ_ASSERT(finalException);
if (!ThrowExceptionObject(aCx, finalException)) {
// If we weren't able to throw an exception we're
// most likely out of memory
JS_ReportOutOfMemory(aCx);
}
return false;
}
void
ThrowAndReport(nsPIDOMWindow* aWindow, nsresult aRv)
{
MOZ_ASSERT(aRv != NS_ERROR_UNCATCHABLE_EXCEPTION,
"Doesn't make sense to report uncatchable exceptions!");
AutoJSAPI jsapi;
if (NS_WARN_IF(!jsapi.InitWithLegacyErrorReporting(aWindow))) {
return;
}
jsapi.TakeOwnershipOfErrorReporting();
Throw(jsapi.cx(), aRv);
}
already_AddRefed<Exception>
CreateException(JSContext* aCx, nsresult aRv, const nsACString& aMessage)
{
// Do we use DOM exceptions for this error code?
switch (NS_ERROR_GET_MODULE(aRv)) {
case NS_ERROR_MODULE_DOM:
case NS_ERROR_MODULE_SVG:
case NS_ERROR_MODULE_DOM_XPATH:
case NS_ERROR_MODULE_DOM_INDEXEDDB:
case NS_ERROR_MODULE_DOM_FILEHANDLE:
case NS_ERROR_MODULE_DOM_BLUETOOTH:
case NS_ERROR_MODULE_DOM_ANIM:
if (aMessage.IsEmpty()) {
return DOMException::Create(aRv);
}
return DOMException::Create(aRv, aMessage);
default:
break;
}
// If not, use the default.
RefPtr<Exception> exception =
new Exception(aMessage, aRv, EmptyCString(), nullptr, nullptr);
return exception.forget();
}
already_AddRefed<nsIStackFrame>
GetCurrentJSStack()
{
// is there a current context available?
JSContext* cx = nullptr;
if (NS_IsMainThread()) {
MOZ_ASSERT(nsContentUtils::XPConnect());
cx = nsContentUtils::GetCurrentJSContext();
} else {
cx = workers::GetCurrentThreadJSContext();
}
if (!cx || !js::GetContextCompartment(cx)) {
return nullptr;
}
nsCOMPtr<nsIStackFrame> stack = exceptions::CreateStack(cx);
if (!stack) {
return nullptr;
}
// Note that CreateStack only returns JS frames, so we're done here.
return stack.forget();
}
AutoForceSetExceptionOnContext::AutoForceSetExceptionOnContext(JSContext* aCx)
: mCx(aCx)
{
mOldValue = JS::ContextOptionsRef(mCx).autoJSAPIOwnsErrorReporting();
JS::ContextOptionsRef(mCx).setAutoJSAPIOwnsErrorReporting(true);
}
AutoForceSetExceptionOnContext::~AutoForceSetExceptionOnContext()
{
JS::ContextOptionsRef(mCx).setAutoJSAPIOwnsErrorReporting(mOldValue);
}
namespace exceptions {
class StackFrame : public nsIStackFrame
{
public:
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_CYCLE_COLLECTION_CLASS(StackFrame)
NS_DECL_NSISTACKFRAME
StackFrame()
: mLineno(0)
, mColNo(0)
, mLanguage(nsIProgrammingLanguage::UNKNOWN)
{
}
protected:
virtual ~StackFrame();
virtual bool IsJSFrame() const
{
return false;
}
virtual int32_t GetLineno()
{
return mLineno;
}
virtual int32_t GetColNo()
{
return mColNo;
}
nsCOMPtr<nsIStackFrame> mCaller;
nsCOMPtr<nsIStackFrame> mAsyncCaller;
nsString mFilename;
nsString mFunname;
nsString mAsyncCause;
int32_t mLineno;
int32_t mColNo;
uint32_t mLanguage;
};
StackFrame::~StackFrame()
{
}
NS_IMPL_CYCLE_COLLECTION(StackFrame, mCaller, mAsyncCaller)
NS_IMPL_CYCLE_COLLECTING_ADDREF(StackFrame)
NS_IMPL_CYCLE_COLLECTING_RELEASE(StackFrame)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(StackFrame)
NS_INTERFACE_MAP_ENTRY(nsIStackFrame)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
class JSStackFrame : public StackFrame
{
public:
NS_DECL_ISUPPORTS_INHERITED
NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_INHERITED(JSStackFrame,
StackFrame)
// aStack must not be null.
explicit JSStackFrame(JS::Handle<JSObject*> aStack);
static already_AddRefed<nsIStackFrame>
CreateStack(JSContext* aCx, int32_t aMaxDepth = -1);
NS_IMETHOD GetLanguageName(nsACString& aLanguageName) override;
NS_IMETHOD GetFilename(nsAString& aFilename) override;
NS_IMETHOD GetName(nsAString& aFunction) override;
NS_IMETHOD GetAsyncCause(nsAString& aAsyncCause) override;
NS_IMETHOD GetAsyncCaller(nsIStackFrame** aAsyncCaller) override;
NS_IMETHOD GetCaller(nsIStackFrame** aCaller) override;
NS_IMETHOD GetFormattedStack(nsAString& aStack) override;
NS_IMETHOD GetNativeSavedFrame(JS::MutableHandle<JS::Value> aSavedFrame) override;
protected:
virtual bool IsJSFrame() const override {
return true;
}
virtual int32_t GetLineno() override;
virtual int32_t GetColNo() override;
private:
virtual ~JSStackFrame();
JS::Heap<JSObject*> mStack;
nsString mFormattedStack;
bool mFilenameInitialized;
bool mFunnameInitialized;
bool mLinenoInitialized;
bool mColNoInitialized;
bool mAsyncCauseInitialized;
bool mAsyncCallerInitialized;
bool mCallerInitialized;
bool mFormattedStackInitialized;
};
JSStackFrame::JSStackFrame(JS::Handle<JSObject*> aStack)
: mStack(aStack)
, mFilenameInitialized(false)
, mFunnameInitialized(false)
, mLinenoInitialized(false)
, mColNoInitialized(false)
, mAsyncCauseInitialized(false)
, mAsyncCallerInitialized(false)
, mCallerInitialized(false)
, mFormattedStackInitialized(false)
{
MOZ_ASSERT(mStack);
mozilla::HoldJSObjects(this);
mLineno = 0;
mLanguage = nsIProgrammingLanguage::JAVASCRIPT;
}
JSStackFrame::~JSStackFrame()
{
mozilla::DropJSObjects(this);
}
NS_IMPL_CYCLE_COLLECTION_CLASS(JSStackFrame)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(JSStackFrame, StackFrame)
tmp->mStack = nullptr;
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(JSStackFrame, StackFrame)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(JSStackFrame, StackFrame)
NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mStack)
NS_IMPL_CYCLE_COLLECTION_TRACE_END
NS_IMPL_ADDREF_INHERITED(JSStackFrame, StackFrame)
NS_IMPL_RELEASE_INHERITED(JSStackFrame, StackFrame)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(JSStackFrame)
NS_INTERFACE_MAP_END_INHERITING(StackFrame)
NS_IMETHODIMP StackFrame::GetLanguage(uint32_t* aLanguage)
{
*aLanguage = mLanguage;
return NS_OK;
}
NS_IMETHODIMP StackFrame::GetLanguageName(nsACString& aLanguageName)
{
aLanguageName.AssignLiteral("C++");
return NS_OK;
}
NS_IMETHODIMP JSStackFrame::GetLanguageName(nsACString& aLanguageName)
{
aLanguageName.AssignLiteral("JavaScript");
return NS_OK;
}
// Helper method to get the value of a stack property, if it's not already
// cached. This will make sure we skip the cache if the access is happening
// over Xrays.
//
// @argument aStack the stack we're working with; must be non-null.
// @argument aPropGetter the getter function to call.
// @argument aIsCached whether we've cached this property's value before.
//
// @argument [out] aCanCache whether the value can get cached.
// @argument [out] aUseCachedValue if true, just use the cached value.
// @argument [out] aValue the value we got from the stack.
template<typename ReturnType, typename GetterOutParamType>
static void
GetValueIfNotCached(JSContext* aCx, JSObject* aStack,
JS::SavedFrameResult (*aPropGetter)(JSContext*,
JS::Handle<JSObject*>,
GetterOutParamType,
JS::SavedFrameSelfHosted),
bool aIsCached, bool* aCanCache, bool* aUseCachedValue,
ReturnType aValue)
{
MOZ_ASSERT(aStack);
JS::Rooted<JSObject*> stack(aCx, aStack);
// Allow caching if aCx and stack are same-compartment. Otherwise take the
// slow path.
*aCanCache = js::GetContextCompartment(aCx) == js::GetObjectCompartment(stack);
if (*aCanCache && aIsCached) {
*aUseCachedValue = true;
return;
}
*aUseCachedValue = false;
JS::ExposeObjectToActiveJS(stack);
aPropGetter(aCx, stack, aValue, JS::SavedFrameSelfHosted::Exclude);
}
NS_IMETHODIMP JSStackFrame::GetFilename(nsAString& aFilename)
{
if (!mStack) {
aFilename.Truncate();
return NS_OK;
}
ThreadsafeAutoJSContext cx;
JS::Rooted<JSString*> filename(cx);
bool canCache = false, useCachedValue = false;
GetValueIfNotCached(cx, mStack, JS::GetSavedFrameSource, mFilenameInitialized,
&canCache, &useCachedValue, &filename);
if (useCachedValue) {
return StackFrame::GetFilename(aFilename);
}
nsAutoJSString str;
if (!str.init(cx, filename)) {
JS_ClearPendingException(cx);
aFilename.Truncate();
return NS_OK;
}
aFilename = str;
if (canCache) {
mFilename = str;
mFilenameInitialized = true;
}
return NS_OK;
}
NS_IMETHODIMP StackFrame::GetFilename(nsAString& aFilename)
{
// The filename must be set to null if empty.
if (mFilename.IsEmpty()) {
aFilename.SetIsVoid(true);
} else {
aFilename.Assign(mFilename);
}
return NS_OK;
}
NS_IMETHODIMP JSStackFrame::GetName(nsAString& aFunction)
{
if (!mStack) {
aFunction.Truncate();
return NS_OK;
}
ThreadsafeAutoJSContext cx;
JS::Rooted<JSString*> name(cx);
bool canCache = false, useCachedValue = false;
GetValueIfNotCached(cx, mStack, JS::GetSavedFrameFunctionDisplayName,
mFunnameInitialized, &canCache, &useCachedValue,
&name);
if (useCachedValue) {
return StackFrame::GetName(aFunction);
}
if (name) {
nsAutoJSString str;
if (!str.init(cx, name)) {
JS_ClearPendingException(cx);
aFunction.Truncate();
return NS_OK;
}
aFunction = str;
} else {
aFunction.SetIsVoid(true);
}
if (canCache) {
mFunname = aFunction;
mFunnameInitialized = true;
}
return NS_OK;
}
NS_IMETHODIMP StackFrame::GetName(nsAString& aFunction)
{
// The function name must be set to null if empty.
if (mFunname.IsEmpty()) {
aFunction.SetIsVoid(true);
} else {
aFunction.Assign(mFunname);
}
return NS_OK;
}
// virtual
int32_t
JSStackFrame::GetLineno()
{
if (!mStack) {
return 0;
}
ThreadsafeAutoJSContext cx;
uint32_t line;
bool canCache = false, useCachedValue = false;
GetValueIfNotCached(cx, mStack, JS::GetSavedFrameLine, mLinenoInitialized,
&canCache, &useCachedValue, &line);
if (useCachedValue) {
return StackFrame::GetLineno();
}
if (canCache) {
mLineno = line;
mLinenoInitialized = true;
}
return line;
}
NS_IMETHODIMP StackFrame::GetLineNumber(int32_t* aLineNumber)
{
*aLineNumber = GetLineno();
return NS_OK;
}
// virtual
int32_t
JSStackFrame::GetColNo()
{
if (!mStack) {
return 0;
}
ThreadsafeAutoJSContext cx;
uint32_t col;
bool canCache = false, useCachedValue = false;
GetValueIfNotCached(cx, mStack, JS::GetSavedFrameColumn, mColNoInitialized,
&canCache, &useCachedValue, &col);
if (useCachedValue) {
return StackFrame::GetColNo();
}
if (canCache) {
mColNo = col;
mColNoInitialized = true;
}
return col;
}
NS_IMETHODIMP StackFrame::GetColumnNumber(int32_t* aColumnNumber)
{
*aColumnNumber = GetColNo();
return NS_OK;
}
NS_IMETHODIMP StackFrame::GetSourceLine(nsACString& aSourceLine)
{
aSourceLine.Truncate();
return NS_OK;
}
NS_IMETHODIMP JSStackFrame::GetAsyncCause(nsAString& aAsyncCause)
{
if (!mStack) {
aAsyncCause.Truncate();
return NS_OK;
}
ThreadsafeAutoJSContext cx;
JS::Rooted<JSString*> asyncCause(cx);
bool canCache = false, useCachedValue = false;
GetValueIfNotCached(cx, mStack, JS::GetSavedFrameAsyncCause,
mAsyncCauseInitialized, &canCache, &useCachedValue,
&asyncCause);
if (useCachedValue) {
return StackFrame::GetAsyncCause(aAsyncCause);
}
if (asyncCause) {
nsAutoJSString str;
if (!str.init(cx, asyncCause)) {
JS_ClearPendingException(cx);
aAsyncCause.Truncate();
return NS_OK;
}
aAsyncCause = str;
} else {
aAsyncCause.SetIsVoid(true);
}
if (canCache) {
mAsyncCause = aAsyncCause;
mAsyncCauseInitialized = true;
}
return NS_OK;
}
NS_IMETHODIMP StackFrame::GetAsyncCause(nsAString& aAsyncCause)
{
// The async cause must be set to null if empty.
if (mAsyncCause.IsEmpty()) {
aAsyncCause.SetIsVoid(true);
} else {
aAsyncCause.Assign(mAsyncCause);
}
return NS_OK;
}
NS_IMETHODIMP JSStackFrame::GetAsyncCaller(nsIStackFrame** aAsyncCaller)
{
if (!mStack) {
*aAsyncCaller = nullptr;
return NS_OK;
}
ThreadsafeAutoJSContext cx;
JS::Rooted<JSObject*> asyncCallerObj(cx);
bool canCache = false, useCachedValue = false;
GetValueIfNotCached(cx, mStack, JS::GetSavedFrameAsyncParent,
mAsyncCallerInitialized, &canCache, &useCachedValue,
&asyncCallerObj);
if (useCachedValue) {
return StackFrame::GetAsyncCaller(aAsyncCaller);
}
nsCOMPtr<nsIStackFrame> asyncCaller =
asyncCallerObj ? new JSStackFrame(asyncCallerObj) : nullptr;
asyncCaller.forget(aAsyncCaller);
if (canCache) {
mAsyncCaller = *aAsyncCaller;
mAsyncCallerInitialized = true;
}
return NS_OK;
}
NS_IMETHODIMP StackFrame::GetAsyncCaller(nsIStackFrame** aAsyncCaller)
{
NS_IF_ADDREF(*aAsyncCaller = mAsyncCaller);
return NS_OK;
}
NS_IMETHODIMP JSStackFrame::GetCaller(nsIStackFrame** aCaller)
{
if (!mStack) {
*aCaller = nullptr;
return NS_OK;
}
ThreadsafeAutoJSContext cx;
JS::Rooted<JSObject*> callerObj(cx);
bool canCache = false, useCachedValue = false;
GetValueIfNotCached(cx, mStack, JS::GetSavedFrameParent, mCallerInitialized,
&canCache, &useCachedValue, &callerObj);
if (useCachedValue) {
return StackFrame::GetCaller(aCaller);
}
nsCOMPtr<nsIStackFrame> caller =
callerObj ? new JSStackFrame(callerObj) : nullptr;
caller.forget(aCaller);
if (canCache) {
mCaller = *aCaller;
mCallerInitialized = true;
}
return NS_OK;
}
NS_IMETHODIMP StackFrame::GetCaller(nsIStackFrame** aCaller)
{
NS_IF_ADDREF(*aCaller = mCaller);
return NS_OK;
}
NS_IMETHODIMP JSStackFrame::GetFormattedStack(nsAString& aStack)
{
if (!mStack) {
aStack.Truncate();
return NS_OK;
}
// Sadly we can't use GetValueIfNotCached here, because our getter
// returns bool, not JS::SavedFrameResult. Maybe it's possible to
// make the templates more complicated to deal, but in the meantime
// let's just inline GetValueIfNotCached here.
ThreadsafeAutoJSContext cx;
// Allow caching if cx and stack are same-compartment. Otherwise take the
// slow path.
bool canCache =
js::GetContextCompartment(cx) == js::GetObjectCompartment(mStack);
if (canCache && mFormattedStackInitialized) {
aStack = mFormattedStack;
return NS_OK;
}
JS::ExposeObjectToActiveJS(mStack);
JS::Rooted<JSObject*> stack(cx, mStack);
JS::Rooted<JSString*> formattedStack(cx);
if (!JS::BuildStackString(cx, stack, &formattedStack)) {
JS_ClearPendingException(cx);
aStack.Truncate();
return NS_OK;
}
nsAutoJSString str;
if (!str.init(cx, formattedStack)) {
JS_ClearPendingException(cx);
aStack.Truncate();
return NS_OK;
}
aStack = str;
if (canCache) {
mFormattedStack = str;
mFormattedStackInitialized = true;
}
return NS_OK;
}
NS_IMETHODIMP StackFrame::GetFormattedStack(nsAString& aStack)
{
aStack.Truncate();
return NS_OK;
}
NS_IMETHODIMP JSStackFrame::GetNativeSavedFrame(JS::MutableHandle<JS::Value> aSavedFrame)
{
aSavedFrame.setObjectOrNull(mStack);
return NS_OK;
}
NS_IMETHODIMP StackFrame::GetNativeSavedFrame(JS::MutableHandle<JS::Value> aSavedFrame)
{
aSavedFrame.setNull();
return NS_OK;
}
NS_IMETHODIMP StackFrame::ToString(nsACString& _retval)
{
_retval.Truncate();
const char* frametype = IsJSFrame() ? "JS" : "native";
nsString filename;
nsresult rv = GetFilename(filename);
NS_ENSURE_SUCCESS(rv, rv);
if (filename.IsEmpty()) {
filename.AssignLiteral("<unknown filename>");
}
nsString funname;
rv = GetName(funname);
NS_ENSURE_SUCCESS(rv, rv);
if (funname.IsEmpty()) {
funname.AssignLiteral("<TOP_LEVEL>");
}
int32_t lineno = GetLineno();
static const char format[] = "%s frame :: %s :: %s :: line %d";
_retval.AppendPrintf(format, frametype,
NS_ConvertUTF16toUTF8(filename).get(),
NS_ConvertUTF16toUTF8(funname).get(),
lineno);
return NS_OK;
}
/* static */ already_AddRefed<nsIStackFrame>
JSStackFrame::CreateStack(JSContext* aCx, int32_t aMaxDepth)
{
static const unsigned MAX_FRAMES = 100;
if (aMaxDepth < 0) {
aMaxDepth = MAX_FRAMES;
}
JS::Rooted<JSObject*> stack(aCx);
if (!JS::CaptureCurrentStack(aCx, &stack, aMaxDepth)) {
return nullptr;
}
nsCOMPtr<nsIStackFrame> first;
if (!stack) {
first = new StackFrame();
} else {
first = new JSStackFrame(stack);
}
return first.forget();
}
already_AddRefed<nsIStackFrame>
CreateStack(JSContext* aCx, int32_t aMaxDepth)
{
return JSStackFrame::CreateStack(aCx, aMaxDepth);
}
} // namespace exceptions
} // namespace dom
} // namespace mozilla