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)
17 # include <imagehlp.h>
19 # if defined(__MINGW32__)
21 # define PACKAGE_VERSION 1
22 # include <bfd.h> // link against libbfd and libiberty
23 # include <psapi.h> // link against psapi
27 #elif defined(__GNUC__)
34 const char * const unknown_function = "[unknown function]";
35 const char * const unknown_module = "[unknown module]";
38 std::string demangle(const char *name)
41 return unknown_function;
45 std::string ret = name;
48 if ((d = abi::__cxa_demangle(name, 0, 0, &status)))
51 catch (const std::bad_alloc &) { }
60 // Derive from this to disallow copying of your class.
61 // c.f. boost::noncopyable
68 uncopyable(const uncopyable &);
69 uncopyable &operator= (const uncopyable &);
72 #if defined(__MINGW32__)
74 // Provides a means to translate a program counter offset in to the name of the corresponding function.
75 class bfd_context : uncopyable
82 asymbol **symbol_table;
92 char procname[MAX_PATH];
93 GetModuleFileNameA(NULL, procname, sizeof procname);
96 abfd_ = bfd_openr(procname, 0);
98 throw std::runtime_error("Failed to parse object data for the executable");
101 bool b1 = bfd_check_format(abfd_, bfd_object);
102 bool b2 = bfd_check_format_matches(abfd_, bfd_object, &formats);
103 bool b3 = bfd_get_file_flags(abfd_) & HAS_SYMS;
105 if (!(b1 && b2 && b3))
109 throw std::runtime_error("Failed to parse object data for the executable");
115 if (bfd_read_minisymbols(abfd_, FALSE, reinterpret_cast<void **>(&symbol_table_), &dummy) == 0 &&
116 bfd_read_minisymbols(abfd_, TRUE, reinterpret_cast<void **>(&symbol_table_), &dummy) < 0)
120 throw std::runtime_error("Failed to parse object data for the executable");
130 std::pair<std::string, unsigned int> get_function_name_and_line(DWORD offset)
133 data.symbol_table = symbol_table_;
134 data.counter = offset;
136 bfd_map_over_sections(abfd_, &find_function_name_in_section, &data);
138 return std::make_pair(data.func, data.line);
142 static void find_function_name_in_section(bfd *abfd, asection *sec, void *opaque_data)
146 find_data &data = *static_cast<find_data *>(opaque_data);
148 if (!data.func.empty()) return; // already found it
150 if (!(bfd_get_section_flags(abfd, sec) & SEC_ALLOC)) return;
152 bfd_vma vma = bfd_get_section_vma(abfd, sec);
153 if (data.counter < vma || vma + bfd_get_section_size(sec) <= data.counter) return;
155 const char *func = 0;
156 const char *file = 0;
159 if (bfd_find_nearest_line(abfd, sec, data.symbol_table, data.counter - vma, &file, &func, &line) && func) {
160 data.func = demangle(func);
168 asymbol **symbol_table_;
171 #endif // __MINGW32__
173 // g++ spouts warnings if you use {0} to initialize PODs. So we use this instead:
176 template<typename POD>
177 operator POD () const { POD p; std::memset(&p, 0, sizeof p); return p; }
181 // Wraps a FARPROC. Implicitly convertible to any kind of pointer-to-function.
182 // Avoids having reinterpret casts all over the place.
183 struct auto_cast_function_ptr
185 auto_cast_function_ptr(FARPROC f) : fptr_(f) { }
187 template<typename FuncPtr>
188 operator FuncPtr() const { return reinterpret_cast<FuncPtr>(fptr_); }
193 // A wrapper around a DLL. Can dynamically get function pointers with the function() function!
194 class windows_dll : uncopyable
197 explicit windows_dll(const std::string &libname) :
199 lib_(LoadLibraryA(name_.c_str()))
201 if (!lib_) throw std::runtime_error("Failed to load dll " + name_);
204 ~windows_dll() { FreeLibrary(lib_); }
206 const std::string &name() const { return name_; }
208 auto_cast_function_ptr function(const char *func_name) const
210 FARPROC proc = GetProcAddress(lib_, func_name);
211 if (!proc) throw std::runtime_error(std::string("failed to load function ") + func_name + " from library " + name_);
221 // An object that makes sure debugging symbols are available
222 class symbol_context : uncopyable
227 if (!SymInitialize(GetCurrentProcess(), 0, TRUE))
228 throw std::runtime_error("Failed to initialize symbol context");
230 ~symbol_context() { SymCleanup(GetCurrentProcess()); }
233 // A simple Windows mutex class. Use a lock object to lock the mutex for the duration of a scope.
234 class mutex : uncopyable
237 mutex() { InitializeCriticalSection(&cs_); }
238 ~mutex() { DeleteCriticalSection(&cs_); }
242 void lock() { EnterCriticalSection(&cs_); }
243 void unlock() { LeaveCriticalSection(&cs_); }
245 CRITICAL_SECTION cs_;
249 // A lock for the mutex
250 class lock : uncopyable
253 lock(mutex &m) : m_(m) { m.lock(); }
254 ~lock() { m_.unlock(); }
260 void fill_frames(std::list<dbg::stack_frame> &frames, dbg::stack::depth_type limit)
262 lock lk(g_fill_frames_mtx);
269 STACKFRAME frame = empty_pod;
270 CONTEXT context = empty_pod;
271 context.ContextFlags = CONTEXT_FULL;
273 windows_dll kernel32("kernel32.dll");
274 void (WINAPI *RtlCaptureContext_)(CONTEXT*) = kernel32.function("RtlCaptureContext");
276 RtlCaptureContext_(&context);
278 #if defined(_M_AMD64)
279 frame.AddrPC.Offset = context.Rip;
280 frame.AddrPC.Mode = AddrModeFlat;
281 frame.AddrStack.Offset = context.Rsp;
282 frame.AddrStack.Mode = AddrModeFlat;
283 frame.AddrFrame.Offset = context.Rbp;
284 frame.AddrFrame.Mode = AddrModeFlat;
286 frame.AddrPC.Offset = context.Eip;
287 frame.AddrPC.Mode = AddrModeFlat;
288 frame.AddrStack.Offset = context.Esp;
289 frame.AddrStack.Mode = AddrModeFlat;
290 frame.AddrFrame.Offset = context.Ebp;
291 frame.AddrFrame.Mode = AddrModeFlat;
294 HANDLE process = GetCurrentProcess();
295 HANDLE thread = GetCurrentThread();
298 bool has_limit = limit != 0;
299 char symbol_buffer[sizeof(IMAGEHLP_SYMBOL) + 255];
300 char module_name_raw[MAX_PATH];
302 #if defined(_M_AMD64)
303 const DWORD machine = IMAGE_FILE_MACHINE_AMD64;
305 const DWORD machine = IMAGE_FILE_MACHINE_I386;
308 while(StackWalk(machine, process, thread, &frame, &context, 0, SymFunctionTableAccess, SymGetModuleBase, 0))
316 if (has_limit && limit-- == 0) break;
318 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(symbol_buffer);
319 symbol->SizeOfStruct = (sizeof *symbol) + 255;
320 symbol->MaxNameLength = 254;
323 DWORD64 module_base = SymGetModuleBase(process, frame.AddrPC.Offset);
325 DWORD module_base = SymGetModuleBase(process, frame.AddrPC.Offset);
327 std::string module_name = unknown_module;
328 if (module_base && GetModuleFileNameA(reinterpret_cast<HINSTANCE>(module_base), module_name_raw, MAX_PATH))
329 module_name = module_name_raw;
331 #if defined(__MINGW32__)
332 std::pair<std::string, unsigned int> func_and_line = bfdc.get_function_name_and_line(frame.AddrPC.Offset);
334 if (func_and_line.first.empty())
341 BOOL got_symbol = SymGetSymFromAddr(process, frame.AddrPC.Offset, &dummy, symbol);
342 func_and_line.first = got_symbol ? symbol->Name : unknown_function;
346 BOOL got_symbol = SymGetSymFromAddr(process, frame.AddrPC.Offset, &dummy, symbol);
347 std::string func = got_symbol ? symbol->Name : unknown_function;
350 dbg::stack_frame f(reinterpret_cast<const void *>(frame.AddrPC.Offset), func_and_line.first, func_and_line.second, module_name);
354 #elif defined(__GNUC__)
355 # if defined(__i386__) || defined(__amd64__)
357 void fill_frames(std::list<dbg::stack_frame> &frames, dbg::stack::depth_type limit)
359 // Based on code found at:
360 // http://www.tlug.org.za/wiki/index.php/Obtaining_a_stack_trace_in_C_upon_SIGSEGV
363 void **frame = static_cast<void **>(__builtin_frame_address(0));
364 void **bp = static_cast<void **>(*frame);
367 bool has_limit = limit != 0;
370 while(bp && ip && dladdr(ip, &info))
376 if (has_limit && limit-- == 0) break;
377 frames.push_back(dbg::stack_frame(ip, demangle(info.dli_sname), info.dli_fname));
379 if(info.dli_sname && !std::strcmp(info.dli_sname, "main")) break;
383 bp = static_cast<void**>(bp[0]);
387 # elif defined(__ppc__)
389 void fill_frames(std::list<dbg::stack_frame> &frames, dbg::stack::depth_type limit)
391 // Based on code found at:
392 // http://www.informit.com/articles/article.aspx?p=606582&seqNum=4&rl=1
394 void *ip = __builtin_return_address(0);
395 void **frame = static_cast<void **>(__builtin_frame_address(1));
396 bool has_limit = limit != 0;
401 if (has_limit && limit-- == 0) break;
403 if (dladdr(ip, &info))
404 frames.push_back(dbg::stack_frame(ip, demangle(info.dli_sname), info.dli_fname));
406 if (frame && (frame = static_cast<void**>(*frame))) ip = *(frame + 2);
412 // GNU, but not x86, x64 nor PPC
413 # error "Sorry but dbg::stack is not supported on this architecture"
416 // Unsupported compiler
417 # error "Sorry but dbg::stack is not supported on this compiler"
420 } // close anonymous namespace
426 stack_frame::stack_frame(const void *instruction, const std::string &function, unsigned int line, const std::string &module) :
427 instruction(instruction),
434 std::ostream &operator<< (std::ostream &out, const stack_frame &frame)
436 return out << frame.instruction << ": " << frame.function << ":" << frame.line << " in " << frame.module;
439 stack::stack(depth_type limit)
441 fill_frames(frames_, limit);
444 stack::const_iterator stack::begin() const
446 return frames_.begin();
449 stack::const_iterator stack::end() const
451 return frames_.end();
454 stack::depth_type stack::depth() const
456 return frames_.size();
459 } // close namespace dbg