CallStack.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 <cstdio>
  33. #include <cstdlib>
  34. #include <string>
  35. #include <vector>
  36. #if defined(_WIN32)
  37. #include <imagehlp.h>
  38. #include <windows.h>
  39. #if defined(__MINGW32__)
  40. #define PACKAGE 1
  41. #define PACKAGE_VERSION 1
  42. #include <bfd.h>
  43. #include <cxxabi.h>
  44. #endif
  45. #else
  46. #include <cxxabi.h>
  47. #include <execinfo.h>
  48. #endif
  49. using namespace WallpaperEngine::Debugging;
  50. using namespace std;
  51. const char* CallStack::Unknown_Function = "[unknown function]";
  52. const char* CallStack::Unknown_Module = "[unknown module]";
  53. CallStack::CallStack (void) { }
  54. CallStack::~CallStack (void) { }
  55. string CallStack::Demangle (const char* name) {
  56. #if defined(_MSC_VER)
  57. return string (name);
  58. #else
  59. string dname;
  60. int status = 0;
  61. char* pdname = abi::__cxa_demangle (name, NULL, 0, &status);
  62. if (status == 0) {
  63. dname.assign (pdname);
  64. free (pdname);
  65. } else {
  66. dname.assign (CallStack::Unknown_Function);
  67. }
  68. return dname;
  69. #endif
  70. }
  71. #if defined(_WIN32)
  72. class noncopyable {
  73. protected:
  74. noncopyable (void) { }
  75. private:
  76. noncopyable (const noncopyable&);
  77. noncopyable& operator= (const noncopyable&);
  78. };
  79. class mutex : noncopyable {
  80. public:
  81. mutex (void) { InitializeCriticalSection (&cs); }
  82. ~mutex (void) { DeleteCriticalSection (&cs); }
  83. void lock (void) { EnterCriticalSection (&cs); }
  84. void unlock (void) { LeaveCriticalSection (&cs); }
  85. private:
  86. CRITICAL_SECTION cs;
  87. } cs;
  88. #if defined(__MINGW32__)
  89. class bfd_usage : noncopyable {
  90. public:
  91. bfd_usage (void) : abfd (NULL), sec (NULL), symbol_table (NULL) {
  92. char procname[MAX_PATH];
  93. GetModuleFileName (NULL, procname, sizeof (procname));
  94. bfd_init ();
  95. abfd = bfd_openr (procname, NULL);
  96. if (abfd == NULL) {
  97. fprintf (stderr, "Error: Failed to parse the executable format.\n");
  98. return;
  99. }
  100. char** matching = NULL;
  101. if (!(bfd_check_format (abfd, bfd_object) && bfd_check_format_matches (abfd, bfd_object, &matching)
  102. && (bfd_get_file_flags (abfd) & HAS_SYMS))) {
  103. bfd_close (abfd);
  104. free (matching);
  105. fprintf (stderr, "Error: Failed to parse the executable format.\n");
  106. return;
  107. }
  108. free (matching);
  109. unsigned int dummy = 0;
  110. if (bfd_read_minisymbols (abfd, FALSE, reinterpret_cast<void**> (&symbol_table), &dummy) == 0
  111. && bfd_read_minisymbols (abfd, TRUE, reinterpret_cast<void**> (&symbol_table), &dummy) < 0) {
  112. free (symbol_table);
  113. bfd_close (abfd);
  114. fprintf (stderr, "Error: Failed to obtain the symbol table from the executable.\n");
  115. return;
  116. }
  117. }
  118. ~bfd_usage (void) {
  119. free (symbol_table);
  120. bfd_close (abfd);
  121. }
  122. string get_function_name (DWORD offset) {
  123. fnis_para para;
  124. para.symbol_table = symbol_table;
  125. para.counter = offset;
  126. bfd_map_over_sections (abfd, &find_function_name_in_section, &para);
  127. return para.function;
  128. }
  129. private:
  130. bfd* abfd;
  131. asection* sec;
  132. asymbol** symbol_table;
  133. class fnis_para {
  134. public:
  135. string function;
  136. asymbol** symbol_table;
  137. bfd_vma counter;
  138. };
  139. static void find_function_name_in_section (bfd* tabfd, asection* tsec, void* tpara) {
  140. fnis_para& para = *static_cast<fnis_para*> (tpara);
  141. if (!para.function.empty ()) {
  142. return;
  143. }
  144. if (!(bfd_get_section_flags (tabfd, tsec) & SEC_ALLOC)) {
  145. return;
  146. }
  147. bfd_vma vma = bfd_get_section_vma (tabfd, tsec);
  148. if (para.counter < vma || vma + bfd_get_section_size (tsec) <= para.counter) {
  149. return;
  150. }
  151. const char* function = NULL;
  152. const char* file = NULL;
  153. unsigned int line = 0;
  154. if (bfd_find_nearest_line (tabfd, tsec, para.symbol_table, para.counter - vma, &file, &function, &line)
  155. && function) {
  156. para.function = CallStack::Demangle (function);
  157. }
  158. }
  159. };
  160. #endif
  161. #endif
  162. void CallStack::GetCalls (vector<CallStack::CallInfo>& calls) {
  163. #if defined(_WIN32)
  164. cs.lock ();
  165. if (!SymInitialize (GetCurrentProcess (), 0, TRUE)) {
  166. fprintf (stderr, "Error: Failed to initialize symbol context.\n");
  167. return;
  168. }
  169. #ifdef __MINGW32__
  170. bfd_usage bfdu;
  171. #endif
  172. #if defined(_M_AMD64)
  173. const DWORD machine = IMAGE_FILE_MACHINE_AMD64;
  174. #else
  175. const DWORD machine = IMAGE_FILE_MACHINE_I386;
  176. #endif
  177. const HANDLE process = GetCurrentProcess ();
  178. const HANDLE thread = GetCurrentThread ();
  179. STACKFRAME frame = { 0 };
  180. CONTEXT context = { 0 };
  181. context.ContextFlags = CONTEXT_FULL;
  182. RtlCaptureContext (&context);
  183. #if defined(_M_AMD64)
  184. frame.AddrPC.Offset = context.Rip;
  185. frame.AddrPC.Mode = AddrModeFlat;
  186. frame.AddrStack.Offset = context.Rsp;
  187. frame.AddrStack.Mode = AddrModeFlat;
  188. frame.AddrFrame.Offset = context.Rbp;
  189. frame.AddrFrame.Mode = AddrModeFlat;
  190. #else
  191. frame.AddrPC.Offset = context.Eip;
  192. frame.AddrPC.Mode = AddrModeFlat;
  193. frame.AddrStack.Offset = context.Esp;
  194. frame.AddrStack.Mode = AddrModeFlat;
  195. frame.AddrFrame.Offset = context.Ebp;
  196. frame.AddrFrame.Mode = AddrModeFlat;
  197. #endif
  198. int limit = 0;
  199. const bool has_limit = (limit != 0);
  200. char symbol_buffer[sizeof (IMAGEHLP_SYMBOL) + 255];
  201. char module_name_raw[MAX_PATH];
  202. calls.clear ();
  203. while (StackWalk (machine, process, thread, &frame, &context, 0, SymFunctionTableAccess, SymGetModuleBase, 0)) {
  204. if (has_limit && limit == 0) {
  205. break;
  206. }
  207. --limit;
  208. IMAGEHLP_SYMBOL* symbol = reinterpret_cast<IMAGEHLP_SYMBOL*> (symbol_buffer);
  209. symbol->SizeOfStruct = (sizeof (*symbol)) + 255;
  210. symbol->MaxNameLength = 254;
  211. #if defined(_WIN64)
  212. const DWORD64 module_base = SymGetModuleBase (process, frame.AddrPC.Offset);
  213. #else
  214. const DWORD module_base = SymGetModuleBase (process, frame.AddrPC.Offset);
  215. #endif
  216. string module_name = Unknown_Module;
  217. if (module_base && GetModuleFileNameA (reinterpret_cast<HINSTANCE> (module_base), module_name_raw, MAX_PATH)) {
  218. module_name = module_name_raw;
  219. }
  220. #if defined(__MINGW32__)
  221. string function = bfdu.get_function_name (frame.AddrPC.Offset);
  222. if (function.empty ()) {
  223. DWORD64 dummy = 0;
  224. const bool got_symbol = SymGetSymFromAddr (process, frame.AddrPC.Offset, &dummy, symbol);
  225. function = (got_symbol) ? (symbol->Name) : Unknown_Function;
  226. }
  227. #else
  228. #if defined(_WIN64)
  229. DWORD64 dummy = 0;
  230. #else
  231. DWORD dummy = 0;
  232. #endif
  233. const bool got_symbol = SymGetSymFromAddr (process, frame.AddrPC.Offset, &dummy, symbol);
  234. const string function = (got_symbol) ? symbol->Name : Unknown_Function;
  235. #endif
  236. calls.push_back (CallInfo (frame.AddrPC.Offset, function, module_name));
  237. }
  238. SymCleanup (GetCurrentProcess ());
  239. cs.unlock ();
  240. #else
  241. const int BufferSize = 256;
  242. void* buffer[BufferSize];
  243. const int ncalls = backtrace (buffer, sizeof (buffer));
  244. char** callstrings = backtrace_symbols (buffer, ncalls);
  245. if (callstrings == NULL) {
  246. fprintf (stderr, "Error: Failed to obtain the symbol table from the executable.\n");
  247. return;
  248. }
  249. calls.clear ();
  250. for (int i = 0; i < ncalls; ++i) {
  251. const string funinfo (callstrings[i]);
  252. const int posleftparenthesis = funinfo.rfind ('(');
  253. const int posplus = funinfo.rfind ('+');
  254. const int posleftbracket = funinfo.rfind ('[');
  255. const int posrightbracket = funinfo.rfind (']');
  256. long long unsigned int offset
  257. = strtoull (funinfo.substr (posleftbracket + 1, posrightbracket - posleftbracket - 1).c_str (), NULL, 0);
  258. const string module_name = funinfo.substr (0, posleftparenthesis);
  259. const string function
  260. = Demangle (funinfo.substr (posleftparenthesis + 1, posplus - posleftparenthesis - 1).c_str ());
  261. calls.push_back (CallInfo (offset, function, module_name));
  262. }
  263. free (callstrings);
  264. #endif
  265. }