1 // Copyright 2007 Edd Dawson.
2 // Distributed under the Boost Software License, Version 1.0.
3 // (See accompanying file LICENSE_1_0.txt or copy at
4 // http://www.boost.org/LICENSE_1_0.txt)
18 # include <imagehlp.h>
20 # if defined(__MINGW32__)
22 # define PACKAGE_VERSION 1
23 # include <bfd.h> // link against libbfd and libiberty
24 # include <psapi.h> // link against psapi
28 #elif defined(__GNUC__)
35 const char * const unknown_function = "[unknown function]";
36 const char * const unknown_module = "[unknown module]";
39 std::string demangle(const char *name)
42 return unknown_function;
46 std::string ret = name;
49 if ((d = abi::__cxa_demangle(name, 0, 0, &status)))
52 catch (const std::bad_alloc &) { }
61 // Derive from this to disallow copying of your class.
62 // c.f. boost::noncopyable
69 uncopyable(const uncopyable &);
70 uncopyable &operator= (const uncopyable &);
73 #if defined(__MINGW32__)
75 // Provides a means to translate a program counter offset in to the name of the corresponding function.
76 class bfd_context : uncopyable
83 asymbol **symbol_table;
93 char procname[MAX_PATH];
94 GetModuleFileNameA(NULL, procname, sizeof procname);
97 abfd_ = bfd_openr(procname, 0);
99 throw std::runtime_error("Failed to parse object data for the executable");
102 bool b1 = bfd_check_format(abfd_, bfd_object);
103 bool b2 = bfd_check_format_matches(abfd_, bfd_object, &formats);
104 bool b3 = bfd_get_file_flags(abfd_) & HAS_SYMS;
106 if (!(b1 && b2 && b3))
110 throw std::runtime_error("Failed to parse object data for the executable");
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)
121 throw std::runtime_error("Failed to parse object data for the executable");
131 std::pair<std::string, unsigned int> get_function_name_and_line(DWORD offset)
134 data.symbol_table = symbol_table_;
135 data.counter = offset;
137 bfd_map_over_sections(abfd_, &find_function_name_in_section, &data);
139 return std::make_pair(data.func, data.line);
143 static void find_function_name_in_section(bfd *abfd, asection *sec, void *opaque_data)
147 find_data &data = *static_cast<find_data *>(opaque_data);
149 if (!data.func.empty()) return; // already found it
151 if (!(bfd_get_section_flags(abfd, sec) & SEC_ALLOC)) return;
153 bfd_vma vma = bfd_get_section_vma(abfd, sec);
154 if (data.counter < vma || vma + bfd_get_section_size(sec) <= data.counter) return;
156 const char *func = 0;
157 const char *file = 0;
160 if (bfd_find_nearest_line(abfd, sec, data.symbol_table, data.counter - vma, &file, &func, &line) && func) {
161 data.func = demangle(func);
169 asymbol **symbol_table_;
172 #endif // __MINGW32__
174 // g++ spouts warnings if you use {0} to initialize PODs. So we use this instead:
177 template<typename POD>
178 operator POD () const { POD p; std::memset(&p, 0, sizeof p); return p; }
182 // Wraps a FARPROC. Implicitly convertible to any kind of pointer-to-function.
183 // Avoids having reinterpret casts all over the place.
184 struct auto_cast_function_ptr
186 auto_cast_function_ptr(FARPROC f) : fptr_(f) { }
188 template<typename FuncPtr>
189 operator FuncPtr() const { return reinterpret_cast<FuncPtr>(fptr_); }
194 // A wrapper around a DLL. Can dynamically get function pointers with the function() function!
195 class windows_dll : uncopyable
198 explicit windows_dll(const std::string &libname) :
200 lib_(LoadLibraryA(name_.c_str()))
202 if (!lib_) throw std::runtime_error("Failed to load dll " + name_);
205 ~windows_dll() { FreeLibrary(lib_); }
207 const std::string &name() const { return name_; }
209 auto_cast_function_ptr function(const char *func_name) const
211 FARPROC proc = GetProcAddress(lib_, func_name);
212 if (!proc) throw std::runtime_error(std::string("failed to load function ") + func_name + " from library " + name_);
222 // An object that makes sure debugging symbols are available
223 class symbol_context : uncopyable
228 if (!SymInitialize(GetCurrentProcess(), 0, TRUE))
229 throw std::runtime_error("Failed to initialize symbol context");
231 ~symbol_context() { SymCleanup(GetCurrentProcess()); }
234 // A simple Windows mutex class. Use a lock object to lock the mutex for the duration of a scope.
235 class mutex : uncopyable
238 mutex() { InitializeCriticalSection(&cs_); }
239 ~mutex() { DeleteCriticalSection(&cs_); }
243 void lock() { EnterCriticalSection(&cs_); }
244 void unlock() { LeaveCriticalSection(&cs_); }
246 CRITICAL_SECTION cs_;
250 // A lock for the mutex
251 class lock : uncopyable
254 lock(mutex &m) : m_(m) { m.lock(); }
255 ~lock() { m_.unlock(); }
261 void fill_frames(std::list<dbg::stack_frame> &frames, dbg::stack::depth_type limit)
263 lock lk(g_fill_frames_mtx);
270 STACKFRAME frame = empty_pod;
271 CONTEXT context = empty_pod;
272 context.ContextFlags = CONTEXT_FULL;
274 windows_dll kernel32("kernel32.dll");
275 void (WINAPI *RtlCaptureContext_)(CONTEXT*) = kernel32.function("RtlCaptureContext");
277 RtlCaptureContext_(&context);
279 #if defined(_M_AMD64)
280 frame.AddrPC.Offset = context.Rip;
281 frame.AddrPC.Mode = AddrModeFlat;
282 frame.AddrStack.Offset = context.Rsp;
283 frame.AddrStack.Mode = AddrModeFlat;
284 frame.AddrFrame.Offset = context.Rbp;
285 frame.AddrFrame.Mode = AddrModeFlat;
287 frame.AddrPC.Offset = context.Eip;
288 frame.AddrPC.Mode = AddrModeFlat;
289 frame.AddrStack.Offset = context.Esp;
290 frame.AddrStack.Mode = AddrModeFlat;
291 frame.AddrFrame.Offset = context.Ebp;
292 frame.AddrFrame.Mode = AddrModeFlat;
295 HANDLE process = GetCurrentProcess();
296 HANDLE thread = GetCurrentThread();
299 bool has_limit = limit != 0;
300 char symbol_buffer[sizeof(IMAGEHLP_SYMBOL) + 255];
301 char module_name_raw[MAX_PATH];
303 #if defined(_M_AMD64)
304 const DWORD machine = IMAGE_FILE_MACHINE_AMD64;
306 const DWORD machine = IMAGE_FILE_MACHINE_I386;
309 while(StackWalk(machine, process, thread, &frame, &context, 0, SymFunctionTableAccess, SymGetModuleBase, 0))
317 if (has_limit && limit-- == 0) break;
319 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(symbol_buffer);
320 symbol->SizeOfStruct = (sizeof *symbol) + 255;
321 symbol->MaxNameLength = 254;
324 DWORD64 module_base = SymGetModuleBase(process, frame.AddrPC.Offset);
326 DWORD module_base = SymGetModuleBase(process, frame.AddrPC.Offset);
328 std::string module_name = unknown_module;
329 if (module_base && GetModuleFileNameA(reinterpret_cast<HINSTANCE>(module_base), module_name_raw, MAX_PATH))
330 module_name = module_name_raw;
332 #if defined(__MINGW32__)
333 std::pair<std::string, unsigned int> func_and_line = bfdc.get_function_name_and_line(frame.AddrPC.Offset);
335 if (func_and_line.first.empty())
342 BOOL got_symbol = SymGetSymFromAddr(process, frame.AddrPC.Offset, &dummy, symbol);
343 func_and_line.first = got_symbol ? symbol->Name : unknown_function;
347 BOOL got_symbol = SymGetSymFromAddr(process, frame.AddrPC.Offset, &dummy, symbol);
348 std::string func = got_symbol ? symbol->Name : unknown_function;
351 dbg::stack_frame f(reinterpret_cast<const void *>(frame.AddrPC.Offset), func_and_line.first, func_and_line.second, module_name);
355 #elif defined(__GNUC__)
356 # if defined(__i386__) || defined(__amd64__)
358 void fill_frames(std::list<dbg::stack_frame> &frames, dbg::stack::depth_type limit)
360 // Based on code found at:
361 // http://www.tlug.org.za/wiki/index.php/Obtaining_a_stack_trace_in_C_upon_SIGSEGV
364 void **frame = static_cast<void **>(__builtin_frame_address(0));
365 void **bp = static_cast<void **>(*frame);
368 bool has_limit = limit != 0;
371 while(bp && ip && dladdr(ip, &info))
377 if (has_limit && limit-- == 0) break;
378 frames.push_back(dbg::stack_frame(ip, demangle(info.dli_sname), info.dli_fname));
380 if(info.dli_sname && !std::strcmp(info.dli_sname, "main")) break;
384 bp = static_cast<void**>(bp[0]);
388 # elif defined(__ppc__)
390 void fill_frames(std::list<dbg::stack_frame> &frames, dbg::stack::depth_type limit)
392 // Based on code found at:
393 // http://www.informit.com/articles/article.aspx?p=606582&seqNum=4&rl=1
395 void *ip = __builtin_return_address(0);
396 void **frame = static_cast<void **>(__builtin_frame_address(1));
397 bool has_limit = limit != 0;
402 if (has_limit && limit-- == 0) break;
404 if (dladdr(ip, &info))
405 frames.push_back(dbg::stack_frame(ip, demangle(info.dli_sname), info.dli_fname));
407 if (frame && (frame = static_cast<void**>(*frame))) ip = *(frame + 2);
413 // GNU, but not x86, x64 nor PPC
414 # error "Sorry but dbg::stack is not supported on this architecture"
417 // Unsupported compiler
418 # error "Sorry but dbg::stack is not supported on this compiler"
421 } // close anonymous namespace
427 stack_frame::stack_frame(const void *instruction, const std::string &function, unsigned int line, const std::string &module) :
428 instruction(instruction),
435 std::ostream &operator<< (std::ostream &out, const stack_frame &frame)
437 return out << frame.instruction << ": " << frame.function << ":" << frame.line << " in " << frame.module;
440 stack::stack(depth_type limit)
442 fill_frames(frames_, limit);
445 stack::const_iterator stack::begin() const
447 return frames_.begin();
450 stack::const_iterator stack::end() const
452 return frames_.end();
455 stack::depth_type stack::depth() const
457 return frames_.size();
460 } // close namespace dbg