CallStack.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /*
  2. * https://github.com/ZhangJunQCC/CallStack-for-Windows-and-Linux
  3. BSD 3-Clause License
  4. Copyright (c) 2017, Jun Zhang
  5. All rights reserved.
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions are met:
  8. * Redistributions of source code must retain the above copyright notice, this
  9. list of conditions and the following disclaimer.
  10. * Redistributions in binary form must reproduce the above copyright notice,
  11. this list of conditions and the following disclaimer in the documentation
  12. and/or other materials provided with the distribution.
  13. * Neither the name of the copyright holder nor the names of its
  14. contributors may be used to endorse or promote products derived from
  15. this software without specific prior written permission.
  16. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. //
  28. // Author: Jun Zhang
  29. // mailto: zhangjunqcc@gmail.com
  30. //
  31. #include "CallStack.h"
  32. #include <cassert>
  33. #include <cstdio>
  34. #include <cstdlib>
  35. #include <string>
  36. #include <vector>
  37. #if defined(_WIN32)
  38. #include <imagehlp.h>
  39. #include <windows.h>
  40. #if defined(__MINGW32__)
  41. #define PACKAGE 1 // Supress cmake error.
  42. #define PACKAGE_VERSION 1 // Supress cmake error.
  43. #include <bfd.h>
  44. #include <cxxabi.h>
  45. #endif
  46. #else
  47. #include <cxxabi.h>
  48. #include <execinfo.h>
  49. #endif
  50. using namespace WallpaperEngine::Debugging;
  51. using namespace std;
  52. const char* CallStack::Unknown_Function = "[unknown function]";
  53. const char* CallStack::Unknown_Module = "[unknown module]";
  54. CallStack::CallStack (void) { /* Nothing to do */ }
  55. CallStack::~CallStack (void) { /* Nothing to do */ }
  56. string CallStack::Demangle (const char* name) {
  57. #if defined(_MSC_VER)
  58. return string (name);
  59. #else
  60. string dname;
  61. int status = 0;
  62. char* pdname = abi::__cxa_demangle (name, NULL, 0, &status);
  63. if (status == 0) {
  64. dname.assign (pdname);
  65. free (pdname);
  66. } else {
  67. dname.assign (CallStack::Unknown_Function);
  68. }
  69. return dname;
  70. #endif
  71. }
  72. #if defined(_WIN32)
  73. class noncopyable // Like the one in boost.
  74. {
  75. protected:
  76. noncopyable (void) { /* Nothing to do */ }
  77. private:
  78. noncopyable (const noncopyable&);
  79. noncopyable& operator= (const noncopyable&);
  80. };
  81. // A global thread mutex class.
  82. class mutex : noncopyable {
  83. public:
  84. mutex (void) { InitializeCriticalSection (&cs); }
  85. ~mutex (void) { DeleteCriticalSection (&cs); }
  86. void lock (void) { EnterCriticalSection (&cs); }
  87. void unlock (void) { LeaveCriticalSection (&cs); }
  88. private:
  89. CRITICAL_SECTION cs;
  90. } cs;
  91. #if defined(__MINGW32__)
  92. class bfd_usage : noncopyable {
  93. public:
  94. bfd_usage (void) : abfd (NULL), sec (NULL), symbol_table (NULL) {
  95. char procname[MAX_PATH];
  96. GetModuleFileName (NULL, procname, sizeof (procname));
  97. bfd_init ();
  98. abfd = bfd_openr (procname, NULL); // Obtain the bfd pointer.
  99. if (abfd == NULL) {
  100. fprintf (stderr, "Error: Failed to parse the executable format.\n");
  101. return;
  102. }
  103. char** matching = NULL;
  104. if (!(bfd_check_format (abfd, bfd_object) && // Whether the executable format is supported.
  105. bfd_check_format_matches (abfd, bfd_object, &matching) && // Whether the executable format is supported.
  106. (bfd_get_file_flags (abfd) & HAS_SYMS))) // Whether BFD has symbols
  107. {
  108. bfd_close (abfd);
  109. free (matching);
  110. fprintf (stderr, "Error: Failed to parse the executable format.\n");
  111. return;
  112. }
  113. free (matching);
  114. // Obtain the symbol table.
  115. unsigned int dummy = 0;
  116. if (bfd_read_minisymbols (abfd, FALSE, reinterpret_cast<void**> (&symbol_table), &dummy) == 0
  117. && bfd_read_minisymbols (abfd, TRUE, reinterpret_cast<void**> (&symbol_table), &dummy) < 0) {
  118. free (symbol_table);
  119. bfd_close (abfd);
  120. fprintf (stderr, "Error: Failed to obtain the symbol table from the executable.\n");
  121. return;
  122. }
  123. }
  124. ~bfd_usage (void) {
  125. free (symbol_table);
  126. bfd_close (abfd);
  127. }
  128. string get_function_name (DWORD offset) {
  129. fnis_para para;
  130. para.symbol_table = symbol_table;
  131. para.counter = offset;
  132. bfd_map_over_sections (abfd, &find_function_name_in_section, &para); // Call the corresponding functions.
  133. return para.function;
  134. }
  135. private:
  136. bfd* abfd;
  137. asection* sec;
  138. asymbol** symbol_table;
  139. class fnis_para {
  140. public:
  141. string function;
  142. asymbol** symbol_table;
  143. bfd_vma counter;
  144. };
  145. static void find_function_name_in_section (bfd* tabfd, asection* tsec, void* tpara) {
  146. fnis_para& para = *static_cast<fnis_para*> (tpara);
  147. if (!para.function.empty ()) {
  148. return; // We have got the name.
  149. }
  150. if (!(bfd_get_section_flags (tabfd, tsec) & SEC_ALLOC)) {
  151. return; // Allocate space for this section.
  152. }
  153. bfd_vma vma = bfd_get_section_vma (tabfd, tsec);
  154. if (para.counter < vma || vma + bfd_get_section_size (tsec) <= para.counter) {
  155. return;
  156. }
  157. const char* function = NULL;
  158. const char* file = NULL;
  159. unsigned int line = 0;
  160. // Get corresponding file and function name, and line number.
  161. if (bfd_find_nearest_line (tabfd, tsec, para.symbol_table, para.counter - vma, &file, &function, &line)
  162. && function) {
  163. para.function = CallStack::Demangle (function);
  164. }
  165. }
  166. };
  167. #endif // __MINGW32__
  168. #endif // _WIN32
  169. void CallStack::GetCalls (vector<CallStack::CallInfo>& calls) {
  170. #if defined(_WIN32)
  171. // Prepare context.
  172. cs.lock ();
  173. if (!SymInitialize (GetCurrentProcess (), 0, TRUE)) {
  174. fprintf (stderr, "Error: Failed to initialize symbol context.\n");
  175. return;
  176. }
  177. #ifdef __MINGW32__
  178. bfd_usage bfdu;
  179. #endif
  180. // Prepare variables.
  181. #if defined(_M_AMD64)
  182. const DWORD machine = IMAGE_FILE_MACHINE_AMD64;
  183. #else
  184. const DWORD machine = IMAGE_FILE_MACHINE_I386;
  185. #endif
  186. const HANDLE process = GetCurrentProcess ();
  187. const HANDLE thread = GetCurrentThread ();
  188. STACKFRAME frame = { 0 };
  189. CONTEXT context = { 0 };
  190. context.ContextFlags = CONTEXT_FULL;
  191. RtlCaptureContext (&context);
  192. #if defined(_M_AMD64)
  193. frame.AddrPC.Offset = context.Rip;
  194. frame.AddrPC.Mode = AddrModeFlat;
  195. frame.AddrStack.Offset = context.Rsp;
  196. frame.AddrStack.Mode = AddrModeFlat;
  197. frame.AddrFrame.Offset = context.Rbp;
  198. frame.AddrFrame.Mode = AddrModeFlat;
  199. #else
  200. frame.AddrPC.Offset = context.Eip;
  201. frame.AddrPC.Mode = AddrModeFlat;
  202. frame.AddrStack.Offset = context.Esp;
  203. frame.AddrStack.Mode = AddrModeFlat;
  204. frame.AddrFrame.Offset = context.Ebp;
  205. frame.AddrFrame.Mode = AddrModeFlat;
  206. #endif
  207. int limit = 0;
  208. const bool has_limit = (limit != 0);
  209. char symbol_buffer[sizeof (IMAGEHLP_SYMBOL) + 255];
  210. char module_name_raw[MAX_PATH];
  211. // Go over stack.
  212. calls.clear ();
  213. while (StackWalk (machine, process, thread, &frame, &context, 0, SymFunctionTableAccess, SymGetModuleBase, 0)) {
  214. if (has_limit && limit == 0) {
  215. break;
  216. }
  217. --limit;
  218. IMAGEHLP_SYMBOL* symbol = reinterpret_cast<IMAGEHLP_SYMBOL*> (symbol_buffer);
  219. symbol->SizeOfStruct = (sizeof (*symbol)) + 255;
  220. symbol->MaxNameLength = 254;
  221. #if defined(_WIN64)
  222. const DWORD64 module_base = SymGetModuleBase (process, frame.AddrPC.Offset);
  223. #else
  224. const DWORD module_base = SymGetModuleBase (process, frame.AddrPC.Offset);
  225. #endif
  226. string module_name = Unknown_Module;
  227. if (module_base && GetModuleFileNameA (reinterpret_cast<HINSTANCE> (module_base), module_name_raw, MAX_PATH)) {
  228. module_name = module_name_raw;
  229. }
  230. #if defined(__MINGW32__)
  231. string function = bfdu.get_function_name (frame.AddrPC.Offset);
  232. if (function.empty ()) {
  233. DWORD64 dummy = 0;
  234. const bool got_symbol = SymGetSymFromAddr (process, frame.AddrPC.Offset, &dummy, symbol);
  235. function = (got_symbol) ? (symbol->Name) : Unknown_Function;
  236. }
  237. #else
  238. #if defined(_WIN64)
  239. DWORD64 dummy = 0;
  240. #else
  241. DWORD dummy = 0;
  242. #endif
  243. const bool got_symbol = SymGetSymFromAddr (process, frame.AddrPC.Offset, &dummy, symbol);
  244. const string function = (got_symbol) ? symbol->Name : Unknown_Function;
  245. #endif
  246. calls.push_back (CallInfo (frame.AddrPC.Offset, function, module_name));
  247. }
  248. SymCleanup (GetCurrentProcess ());
  249. cs.unlock ();
  250. #else // For Linux and Unix.
  251. const int BufferSize = 256;
  252. void* buffer[BufferSize];
  253. const int ncalls = backtrace (buffer, sizeof (buffer));
  254. char** callstrings = backtrace_symbols (buffer, ncalls);
  255. if (callstrings == NULL) {
  256. fprintf (stderr, "Error: Failed to obtain the symbol table from the executable.\n");
  257. return;
  258. }
  259. calls.clear ();
  260. for (int i = 0; i < ncalls; ++i) {
  261. const string funinfo (callstrings[i]);
  262. const int posleftparenthesis = funinfo.rfind ('(');
  263. const int posplus = funinfo.rfind ('+');
  264. const int posleftbracket = funinfo.rfind ('[');
  265. const int posrightbracket = funinfo.rfind (']');
  266. long long unsigned int offset
  267. = strtoull (funinfo.substr (posleftbracket + 1, posrightbracket - posleftbracket - 1).c_str (), NULL, 0);
  268. const string module_name = funinfo.substr (0, posleftparenthesis);
  269. const string function
  270. = Demangle (funinfo.substr (posleftparenthesis + 1, posplus - posleftparenthesis - 1).c_str ());
  271. calls.push_back (CallInfo (offset, function, module_name));
  272. }
  273. free (callstrings);
  274. #endif // _WIN32
  275. }