Bug 1856663 - Add more chunks for Android mochitest-plain. r=jmaher,taskgraph-reviewe...
[gecko.git] / dom / bindings / Exceptions.cpp
blobeceddee9cfdb9cf1f83847a83426524a1fa945fb
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
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/. */
7 #include "mozilla/dom/Exceptions.h"
9 #include "js/ColumnNumber.h" // JS::TaggedColumnNumberOneOrigin
10 #include "js/RootingAPI.h"
11 #include "js/TypeDecls.h"
12 #include "jsapi.h"
13 #include "js/SavedFrameAPI.h"
14 #include "xpcpublic.h"
15 #include "mozilla/CycleCollectedJSContext.h"
16 #include "mozilla/HoldDropJSObjects.h"
17 #include "mozilla/dom/BindingUtils.h"
18 #include "mozilla/dom/DOMException.h"
19 #include "mozilla/dom/ScriptSettings.h"
20 #include "nsJSPrincipals.h"
21 #include "nsPIDOMWindow.h"
22 #include "nsServiceManagerUtils.h"
23 #include "nsThreadUtils.h"
24 #include "XPCWrapper.h"
25 #include "WorkerPrivate.h"
26 #include "nsContentUtils.h"
28 namespace mozilla::dom {
30 // Throw the given exception value if it's safe. If it's not safe, then
31 // synthesize and throw a new exception value for NS_ERROR_UNEXPECTED. The
32 // incoming value must be in the compartment of aCx. This function guarantees
33 // that an exception is pending on aCx when it returns.
34 static void ThrowExceptionValueIfSafe(JSContext* aCx,
35 JS::Handle<JS::Value> exnVal,
36 Exception* aOriginalException) {
37 MOZ_ASSERT(aOriginalException);
39 if (!exnVal.isObject()) {
40 JS_SetPendingException(aCx, exnVal);
41 return;
44 JS::Rooted<JSObject*> exnObj(aCx, &exnVal.toObject());
45 MOZ_ASSERT(js::IsObjectInContextCompartment(exnObj, aCx),
46 "exnObj needs to be in the right compartment for the "
47 "CheckedUnwrapDynamic thing to make sense");
49 // aCx's current Realm is where we're throwing, so using it in the
50 // CheckedUnwrapDynamic check makes sense.
51 if (js::CheckedUnwrapDynamic(exnObj, aCx)) {
52 // This is an object we're allowed to work with, so just go ahead and throw
53 // it.
54 JS_SetPendingException(aCx, exnVal);
55 return;
58 // We could probably Throw(aCx, NS_ERROR_UNEXPECTED) here, and it would do the
59 // right thing due to there not being an existing exception on the runtime at
60 // this point, but it's clearer to explicitly do the thing we want done. This
61 // is also why we don't just call ThrowExceptionObject on the Exception we
62 // create: it would do the right thing, but that fact is not obvious.
63 RefPtr<Exception> syntheticException = CreateException(NS_ERROR_UNEXPECTED);
64 JS::Rooted<JS::Value> syntheticVal(aCx);
65 if (!GetOrCreateDOMReflector(aCx, syntheticException, &syntheticVal)) {
66 return;
68 MOZ_ASSERT(
69 syntheticVal.isObject() && !js::IsWrapper(&syntheticVal.toObject()),
70 "Must have a reflector here, not a wrapper");
71 JS_SetPendingException(aCx, syntheticVal);
74 void ThrowExceptionObject(JSContext* aCx, Exception* aException) {
75 JS::Rooted<JS::Value> thrown(aCx);
77 // If we stored the original thrown JS value in the exception
78 // (see XPCConvert::ConstructException) and we are in a web context
79 // (i.e., not chrome), rethrow the original value. This only applies to JS
80 // implemented components so we only need to check for this on the main
81 // thread.
82 if (NS_IsMainThread() && !nsContentUtils::IsCallerChrome() &&
83 aException->StealJSVal(thrown.address())) {
84 // Now check for the case when thrown is a number which matches
85 // aException->GetResult(). This would indicate that what actually got
86 // thrown was an nsresult value. In that situation, we should go back
87 // through dom::Throw with that nsresult value, because it will make sure to
88 // create the right sort of Exception or DOMException, with the right
89 // global.
90 if (thrown.isNumber()) {
91 nsresult exceptionResult = aException->GetResult();
92 if (double(exceptionResult) == thrown.toNumber()) {
93 Throw(aCx, exceptionResult);
94 return;
97 if (!JS_WrapValue(aCx, &thrown)) {
98 return;
100 ThrowExceptionValueIfSafe(aCx, thrown, aException);
101 return;
104 if (!GetOrCreateDOMReflector(aCx, aException, &thrown)) {
105 return;
108 ThrowExceptionValueIfSafe(aCx, thrown, aException);
111 bool Throw(JSContext* aCx, nsresult aRv, const nsACString& aMessage) {
112 if (aRv == NS_ERROR_UNCATCHABLE_EXCEPTION) {
113 // Nuke any existing exception on aCx, to make sure we're uncatchable.
114 JS_ClearPendingException(aCx);
115 return false;
118 if (JS_IsExceptionPending(aCx)) {
119 // Don't clobber the existing exception.
120 return false;
123 CycleCollectedJSContext* context = CycleCollectedJSContext::Get();
124 RefPtr<Exception> existingException = context->GetPendingException();
125 // Make sure to clear the pending exception now. Either we're going to reuse
126 // it (and we already grabbed it), or we plan to throw something else and this
127 // pending exception is no longer relevant.
128 context->SetPendingException(nullptr);
130 // Ignore the pending exception if we have a non-default message passed in.
131 if (aMessage.IsEmpty() && existingException) {
132 if (aRv == existingException->GetResult()) {
133 // Reuse the existing exception.
134 ThrowExceptionObject(aCx, existingException);
135 return false;
139 RefPtr<Exception> finalException = CreateException(aRv, aMessage);
140 MOZ_ASSERT(finalException);
142 ThrowExceptionObject(aCx, finalException);
143 return false;
146 void ThrowAndReport(nsPIDOMWindowInner* aWindow, nsresult aRv) {
147 MOZ_ASSERT(aRv != NS_ERROR_UNCATCHABLE_EXCEPTION,
148 "Doesn't make sense to report uncatchable exceptions!");
149 AutoJSAPI jsapi;
150 if (NS_WARN_IF(!jsapi.Init(aWindow))) {
151 return;
154 Throw(jsapi.cx(), aRv);
157 already_AddRefed<Exception> CreateException(nsresult aRv,
158 const nsACString& aMessage) {
159 // Do we use DOM exceptions for this error code?
160 switch (NS_ERROR_GET_MODULE(aRv)) {
161 case NS_ERROR_MODULE_DOM:
162 case NS_ERROR_MODULE_SVG:
163 case NS_ERROR_MODULE_DOM_FILE:
164 case NS_ERROR_MODULE_DOM_XPATH:
165 case NS_ERROR_MODULE_DOM_INDEXEDDB:
166 case NS_ERROR_MODULE_DOM_FILEHANDLE:
167 case NS_ERROR_MODULE_DOM_ANIM:
168 case NS_ERROR_MODULE_DOM_PUSH:
169 case NS_ERROR_MODULE_DOM_MEDIA:
170 if (aMessage.IsEmpty()) {
171 return DOMException::Create(aRv);
173 return DOMException::Create(aRv, aMessage);
174 default:
175 break;
178 // If not, use the default.
179 RefPtr<Exception> exception =
180 new Exception(aMessage, aRv, ""_ns, nullptr, nullptr);
181 return exception.forget();
184 already_AddRefed<nsIStackFrame> GetCurrentJSStack(int32_t aMaxDepth) {
185 // is there a current context available?
186 JSContext* cx = nsContentUtils::GetCurrentJSContext();
188 if (!cx || !js::GetContextRealm(cx)) {
189 return nullptr;
192 static const unsigned MAX_FRAMES = 100;
193 if (aMaxDepth < 0) {
194 aMaxDepth = MAX_FRAMES;
197 JS::StackCapture captureMode =
198 aMaxDepth == 0 ? JS::StackCapture(JS::AllFrames())
199 : JS::StackCapture(JS::MaxFrames(aMaxDepth));
201 return dom::exceptions::CreateStack(cx, std::move(captureMode));
204 namespace exceptions {
206 class JSStackFrame final : public nsIStackFrame, public xpc::JSStackFrameBase {
207 public:
208 NS_DECL_CYCLE_COLLECTING_ISUPPORTS
209 NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(JSStackFrame)
210 NS_DECL_NSISTACKFRAME
212 // aStack must not be null.
213 explicit JSStackFrame(JS::Handle<JSObject*> aStack);
215 private:
216 virtual ~JSStackFrame();
218 void Clear() override { mStack = nullptr; }
220 // Remove this frame from the per-realm list of live frames,
221 // and clear out the stack pointer.
222 void UnregisterAndClear();
224 JS::Heap<JSObject*> mStack;
225 nsString mFormattedStack;
227 nsCOMPtr<nsIStackFrame> mCaller;
228 nsCOMPtr<nsIStackFrame> mAsyncCaller;
229 nsString mFilename;
230 nsString mFunname;
231 nsString mAsyncCause;
232 int32_t mSourceId;
233 int32_t mLineno;
234 int32_t mColNo;
236 bool mFilenameInitialized;
237 bool mFunnameInitialized;
238 bool mSourceIdInitialized;
239 bool mLinenoInitialized;
240 bool mColNoInitialized;
241 bool mAsyncCauseInitialized;
242 bool mAsyncCallerInitialized;
243 bool mCallerInitialized;
244 bool mFormattedStackInitialized;
247 JSStackFrame::JSStackFrame(JS::Handle<JSObject*> aStack)
248 : mStack(aStack),
249 mSourceId(0),
250 mLineno(0),
251 mColNo(0),
252 mFilenameInitialized(false),
253 mFunnameInitialized(false),
254 mSourceIdInitialized(false),
255 mLinenoInitialized(false),
256 mColNoInitialized(false),
257 mAsyncCauseInitialized(false),
258 mAsyncCallerInitialized(false),
259 mCallerInitialized(false),
260 mFormattedStackInitialized(false) {
261 MOZ_ASSERT(mStack);
262 MOZ_ASSERT(JS::IsUnwrappedSavedFrame(mStack));
264 mozilla::HoldJSObjects(this);
266 xpc::RegisterJSStackFrame(js::GetNonCCWObjectRealm(aStack), this);
269 JSStackFrame::~JSStackFrame() {
270 UnregisterAndClear();
271 mozilla::DropJSObjects(this);
274 void JSStackFrame::UnregisterAndClear() {
275 if (!mStack) {
276 return;
279 xpc::UnregisterJSStackFrame(js::GetNonCCWObjectRealm(mStack), this);
280 Clear();
283 NS_IMPL_CYCLE_COLLECTION_CLASS(JSStackFrame)
284 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(JSStackFrame)
285 NS_IMPL_CYCLE_COLLECTION_UNLINK(mCaller)
286 NS_IMPL_CYCLE_COLLECTION_UNLINK(mAsyncCaller)
287 tmp->UnregisterAndClear();
288 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
289 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(JSStackFrame)
290 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCaller)
291 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAsyncCaller)
292 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
293 NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(JSStackFrame)
294 NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mStack)
295 NS_IMPL_CYCLE_COLLECTION_TRACE_END
297 NS_IMPL_CYCLE_COLLECTING_ADDREF(JSStackFrame)
298 NS_IMPL_CYCLE_COLLECTING_RELEASE(JSStackFrame)
300 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(JSStackFrame)
301 NS_INTERFACE_MAP_ENTRY(nsIStackFrame)
302 NS_INTERFACE_MAP_ENTRY(nsISupports)
303 NS_INTERFACE_MAP_END
305 // Helper method to determine the JSPrincipals* to pass to JS SavedFrame APIs.
307 // @argument aStack the stack we're working with; must be non-null.
308 // @argument [out] aCanCache whether we can use cached JSStackFrame values.
309 static JSPrincipals* GetPrincipalsForStackGetter(JSContext* aCx,
310 JS::Handle<JSObject*> aStack,
311 bool* aCanCache) {
312 MOZ_ASSERT(JS::IsUnwrappedSavedFrame(aStack));
314 JSPrincipals* currentPrincipals =
315 JS::GetRealmPrincipals(js::GetContextRealm(aCx));
316 JSPrincipals* stackPrincipals =
317 JS::GetRealmPrincipals(js::GetNonCCWObjectRealm(aStack));
319 // Fast path for when the principals are equal. This check is also necessary
320 // for workers: no nsIPrincipal there so we can't use the code below.
321 if (currentPrincipals == stackPrincipals) {
322 *aCanCache = true;
323 return stackPrincipals;
326 MOZ_ASSERT(NS_IsMainThread());
328 if (nsJSPrincipals::get(currentPrincipals)
329 ->Subsumes(nsJSPrincipals::get(stackPrincipals))) {
330 // The current principals subsume the stack's principals. In this case use
331 // the stack's principals: the idea is that this way devtools code that's
332 // asking an exception object for a stack to display will end up with the
333 // stack the web developer would see via doing .stack in a web page, with
334 // Firefox implementation details excluded.
336 // Because we use the stack's principals and don't rely on the current
337 // context realm, we can use cached values.
338 *aCanCache = true;
339 return stackPrincipals;
342 // The stack was captured in more-privileged code, so use the less privileged
343 // principals. Don't use cached values because we don't want these values to
344 // depend on the current realm/principals.
345 *aCanCache = false;
346 return currentPrincipals;
349 // Helper method to get the value of a stack property, if it's not already
350 // cached. This will make sure we skip the cache if the property value depends
351 // on the (current) context's realm/principals.
353 // @argument aStack the stack we're working with; must be non-null.
354 // @argument aPropGetter the getter function to call.
355 // @argument aIsCached whether we've cached this property's value before.
357 // @argument [out] aCanCache whether the value can get cached.
358 // @argument [out] aUseCachedValue if true, just use the cached value.
359 // @argument [out] aValue the value we got from the stack.
360 template <typename ReturnType, typename GetterOutParamType>
361 static void GetValueIfNotCached(
362 JSContext* aCx, const JS::Heap<JSObject*>& aStack,
363 JS::SavedFrameResult (*aPropGetter)(JSContext*, JSPrincipals*,
364 JS::Handle<JSObject*>,
365 GetterOutParamType,
366 JS::SavedFrameSelfHosted),
367 bool aIsCached, bool* aCanCache, bool* aUseCachedValue, ReturnType aValue) {
368 MOZ_ASSERT(aStack);
369 MOZ_ASSERT(JS::IsUnwrappedSavedFrame(aStack));
371 JS::Rooted<JSObject*> stack(aCx, aStack);
373 JSPrincipals* principals = GetPrincipalsForStackGetter(aCx, stack, aCanCache);
374 if (*aCanCache && aIsCached) {
375 *aUseCachedValue = true;
376 return;
379 *aUseCachedValue = false;
381 aPropGetter(aCx, principals, stack, aValue,
382 JS::SavedFrameSelfHosted::Exclude);
385 NS_IMETHODIMP JSStackFrame::GetFilenameXPCOM(JSContext* aCx,
386 nsAString& aFilename) {
387 GetFilename(aCx, aFilename);
388 return NS_OK;
391 void JSStackFrame::GetFilename(JSContext* aCx, nsAString& aFilename) {
392 if (!mStack) {
393 aFilename.Truncate();
394 return;
397 JS::Rooted<JSString*> filename(aCx);
398 bool canCache = false, useCachedValue = false;
399 GetValueIfNotCached(aCx, mStack, JS::GetSavedFrameSource,
400 mFilenameInitialized, &canCache, &useCachedValue,
401 &filename);
402 if (useCachedValue) {
403 aFilename = mFilename;
404 return;
407 nsAutoJSString str;
408 if (!str.init(aCx, filename)) {
409 JS_ClearPendingException(aCx);
410 aFilename.Truncate();
411 return;
413 aFilename = str;
415 if (canCache) {
416 mFilename = str;
417 mFilenameInitialized = true;
421 NS_IMETHODIMP
422 JSStackFrame::GetNameXPCOM(JSContext* aCx, nsAString& aFunction) {
423 GetName(aCx, aFunction);
424 return NS_OK;
427 void JSStackFrame::GetName(JSContext* aCx, nsAString& aFunction) {
428 if (!mStack) {
429 aFunction.Truncate();
430 return;
433 JS::Rooted<JSString*> name(aCx);
434 bool canCache = false, useCachedValue = false;
435 GetValueIfNotCached(aCx, mStack, JS::GetSavedFrameFunctionDisplayName,
436 mFunnameInitialized, &canCache, &useCachedValue, &name);
438 if (useCachedValue) {
439 aFunction = mFunname;
440 return;
443 if (name) {
444 nsAutoJSString str;
445 if (!str.init(aCx, name)) {
446 JS_ClearPendingException(aCx);
447 aFunction.Truncate();
448 return;
450 aFunction = str;
451 } else {
452 aFunction.SetIsVoid(true);
455 if (canCache) {
456 mFunname = aFunction;
457 mFunnameInitialized = true;
461 int32_t JSStackFrame::GetSourceId(JSContext* aCx) {
462 if (!mStack) {
463 return 0;
466 uint32_t id;
467 bool canCache = false, useCachedValue = false;
468 GetValueIfNotCached(aCx, mStack, JS::GetSavedFrameSourceId,
469 mSourceIdInitialized, &canCache, &useCachedValue, &id);
471 if (useCachedValue) {
472 return mSourceId;
475 if (canCache) {
476 mSourceId = id;
477 mSourceIdInitialized = true;
480 return id;
483 NS_IMETHODIMP
484 JSStackFrame::GetSourceIdXPCOM(JSContext* aCx, int32_t* aSourceId) {
485 *aSourceId = GetSourceId(aCx);
486 return NS_OK;
489 int32_t JSStackFrame::GetLineNumber(JSContext* aCx) {
490 if (!mStack) {
491 return 0;
494 uint32_t line;
495 bool canCache = false, useCachedValue = false;
496 GetValueIfNotCached(aCx, mStack, JS::GetSavedFrameLine, mLinenoInitialized,
497 &canCache, &useCachedValue, &line);
499 if (useCachedValue) {
500 return mLineno;
503 if (canCache) {
504 mLineno = line;
505 mLinenoInitialized = true;
508 return line;
511 NS_IMETHODIMP
512 JSStackFrame::GetLineNumberXPCOM(JSContext* aCx, int32_t* aLineNumber) {
513 *aLineNumber = GetLineNumber(aCx);
514 return NS_OK;
517 int32_t JSStackFrame::GetColumnNumber(JSContext* aCx) {
518 if (!mStack) {
519 return 0;
522 JS::TaggedColumnNumberOneOrigin col;
523 bool canCache = false, useCachedValue = false;
524 GetValueIfNotCached(aCx, mStack, JS::GetSavedFrameColumn, mColNoInitialized,
525 &canCache, &useCachedValue, &col);
527 if (useCachedValue) {
528 return mColNo;
531 if (canCache) {
532 mColNo = col.oneOriginValue();
533 mColNoInitialized = true;
536 return col.oneOriginValue();
539 NS_IMETHODIMP
540 JSStackFrame::GetColumnNumberXPCOM(JSContext* aCx, int32_t* aColumnNumber) {
541 *aColumnNumber = GetColumnNumber(aCx);
542 return NS_OK;
545 NS_IMETHODIMP JSStackFrame::GetSourceLine(nsACString& aSourceLine) {
546 aSourceLine.Truncate();
547 return NS_OK;
550 NS_IMETHODIMP
551 JSStackFrame::GetAsyncCauseXPCOM(JSContext* aCx, nsAString& aAsyncCause) {
552 GetAsyncCause(aCx, aAsyncCause);
553 return NS_OK;
556 void JSStackFrame::GetAsyncCause(JSContext* aCx, nsAString& aAsyncCause) {
557 if (!mStack) {
558 aAsyncCause.Truncate();
559 return;
562 JS::Rooted<JSString*> asyncCause(aCx);
563 bool canCache = false, useCachedValue = false;
564 GetValueIfNotCached(aCx, mStack, JS::GetSavedFrameAsyncCause,
565 mAsyncCauseInitialized, &canCache, &useCachedValue,
566 &asyncCause);
568 if (useCachedValue) {
569 aAsyncCause = mAsyncCause;
570 return;
573 if (asyncCause) {
574 nsAutoJSString str;
575 if (!str.init(aCx, asyncCause)) {
576 JS_ClearPendingException(aCx);
577 aAsyncCause.Truncate();
578 return;
580 aAsyncCause = str;
581 } else {
582 aAsyncCause.SetIsVoid(true);
585 if (canCache) {
586 mAsyncCause = aAsyncCause;
587 mAsyncCauseInitialized = true;
591 NS_IMETHODIMP
592 JSStackFrame::GetAsyncCallerXPCOM(JSContext* aCx,
593 nsIStackFrame** aAsyncCaller) {
594 *aAsyncCaller = GetAsyncCaller(aCx).take();
595 return NS_OK;
598 already_AddRefed<nsIStackFrame> JSStackFrame::GetAsyncCaller(JSContext* aCx) {
599 if (!mStack) {
600 return nullptr;
603 JS::Rooted<JSObject*> asyncCallerObj(aCx);
604 bool canCache = false, useCachedValue = false;
605 GetValueIfNotCached(aCx, mStack, JS::GetSavedFrameAsyncParent,
606 mAsyncCallerInitialized, &canCache, &useCachedValue,
607 &asyncCallerObj);
609 if (useCachedValue) {
610 nsCOMPtr<nsIStackFrame> asyncCaller = mAsyncCaller;
611 return asyncCaller.forget();
614 nsCOMPtr<nsIStackFrame> asyncCaller =
615 asyncCallerObj ? new JSStackFrame(asyncCallerObj) : nullptr;
617 if (canCache) {
618 mAsyncCaller = asyncCaller;
619 mAsyncCallerInitialized = true;
622 return asyncCaller.forget();
625 NS_IMETHODIMP
626 JSStackFrame::GetCallerXPCOM(JSContext* aCx, nsIStackFrame** aCaller) {
627 *aCaller = GetCaller(aCx).take();
628 return NS_OK;
631 already_AddRefed<nsIStackFrame> JSStackFrame::GetCaller(JSContext* aCx) {
632 if (!mStack) {
633 return nullptr;
636 JS::Rooted<JSObject*> callerObj(aCx);
637 bool canCache = false, useCachedValue = false;
638 GetValueIfNotCached(aCx, mStack, JS::GetSavedFrameParent, mCallerInitialized,
639 &canCache, &useCachedValue, &callerObj);
641 if (useCachedValue) {
642 nsCOMPtr<nsIStackFrame> caller = mCaller;
643 return caller.forget();
646 nsCOMPtr<nsIStackFrame> caller =
647 callerObj ? new JSStackFrame(callerObj) : nullptr;
649 if (canCache) {
650 mCaller = caller;
651 mCallerInitialized = true;
654 return caller.forget();
657 NS_IMETHODIMP
658 JSStackFrame::GetFormattedStackXPCOM(JSContext* aCx, nsAString& aStack) {
659 GetFormattedStack(aCx, aStack);
660 return NS_OK;
663 void JSStackFrame::GetFormattedStack(JSContext* aCx, nsAString& aStack) {
664 if (!mStack) {
665 aStack.Truncate();
666 return;
669 // Sadly we can't use GetValueIfNotCached here, because our getter
670 // returns bool, not JS::SavedFrameResult. Maybe it's possible to
671 // make the templates more complicated to deal, but in the meantime
672 // let's just inline GetValueIfNotCached here.
674 JS::Rooted<JSObject*> stack(aCx, mStack);
676 bool canCache;
677 JSPrincipals* principals = GetPrincipalsForStackGetter(aCx, stack, &canCache);
678 if (canCache && mFormattedStackInitialized) {
679 aStack = mFormattedStack;
680 return;
683 JS::Rooted<JSString*> formattedStack(aCx);
684 if (!JS::BuildStackString(aCx, principals, stack, &formattedStack)) {
685 JS_ClearPendingException(aCx);
686 aStack.Truncate();
687 return;
690 nsAutoJSString str;
691 if (!str.init(aCx, formattedStack)) {
692 JS_ClearPendingException(aCx);
693 aStack.Truncate();
694 return;
697 aStack = str;
699 if (canCache) {
700 mFormattedStack = str;
701 mFormattedStackInitialized = true;
705 NS_IMETHODIMP JSStackFrame::GetNativeSavedFrame(
706 JS::MutableHandle<JS::Value> aSavedFrame) {
707 aSavedFrame.setObjectOrNull(mStack);
708 return NS_OK;
711 NS_IMETHODIMP
712 JSStackFrame::ToStringXPCOM(JSContext* aCx, nsACString& _retval) {
713 ToString(aCx, _retval);
714 return NS_OK;
717 void JSStackFrame::ToString(JSContext* aCx, nsACString& _retval) {
718 _retval.Truncate();
720 nsString filename;
721 GetFilename(aCx, filename);
723 if (filename.IsEmpty()) {
724 filename.AssignLiteral("<unknown filename>");
727 nsString funname;
728 GetName(aCx, funname);
730 if (funname.IsEmpty()) {
731 funname.AssignLiteral("<TOP_LEVEL>");
734 int32_t lineno = GetLineNumber(aCx);
736 static const char format[] = "JS frame :: %s :: %s :: line %d";
737 _retval.AppendPrintf(format, NS_ConvertUTF16toUTF8(filename).get(),
738 NS_ConvertUTF16toUTF8(funname).get(), lineno);
741 already_AddRefed<nsIStackFrame> CreateStack(JSContext* aCx,
742 JS::StackCapture&& aCaptureMode) {
743 JS::Rooted<JSObject*> stack(aCx);
744 if (!JS::CaptureCurrentStack(aCx, &stack, std::move(aCaptureMode))) {
745 return nullptr;
748 return CreateStack(aCx, stack);
751 already_AddRefed<nsIStackFrame> CreateStack(JSContext* aCx,
752 JS::Handle<JSObject*> aStack) {
753 if (aStack) {
754 return MakeAndAddRef<JSStackFrame>(aStack);
756 return nullptr;
759 } // namespace exceptions
760 } // namespace mozilla::dom