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/. */
6 
7 #include "xpcprivate.h"
8 #include "js/friend/DumpFunctions.h"  // JS::FormatStackDump
9 #include "nsThreadUtils.h"
10 #include "nsContentUtils.h"
11 
12 #include "mozilla/Sprintf.h"
13 
14 #ifdef XP_WIN
15 #  include <windows.h>
16 #  include "nsPrintfCString.h"
17 #endif
18 
19 #ifdef ANDROID
20 #  include <android/log.h>
21 #endif
22 
DebugDump(const char * str)23 static void DebugDump(const char* str) {
24 #ifdef XP_WIN
25   if (IsDebuggerPresent()) {
26     nsPrintfCString output("%s\n", str);
27     OutputDebugStringA(output.get());
28   }
29 #elif defined(ANDROID)
30   __android_log_print(ANDROID_LOG_DEBUG, "Gecko", "%s\n", str);
31 #endif
32   printf("%s\n", str);
33 }
34 
xpc_DumpJSStack(bool showArgs,bool showLocals,bool showThisProps)35 bool xpc_DumpJSStack(bool showArgs, bool showLocals, bool showThisProps) {
36   JSContext* cx = nsContentUtils::GetCurrentJSContext();
37   if (!cx) {
38     printf("there is no JSContext on the stack!\n");
39   } else if (JS::UniqueChars buf =
40                  xpc_PrintJSStack(cx, showArgs, showLocals, showThisProps)) {
41     DebugDump(buf.get());
42   }
43   return true;
44 }
45 
xpc_PrintJSStack(JSContext * cx,bool showArgs,bool showLocals,bool showThisProps)46 JS::UniqueChars xpc_PrintJSStack(JSContext* cx, bool showArgs, bool showLocals,
47                                  bool showThisProps) {
48   JS::AutoSaveExceptionState state(cx);
49 
50   JS::UniqueChars buf =
51       JS::FormatStackDump(cx, showArgs, showLocals, showThisProps);
52   if (!buf) {
53     DebugDump("Failed to format JavaScript stack for dump");
54   }
55 
56   state.restore();
57   return buf;
58 }
59