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
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::string get_function_name(DWORD offset)
133 data.symbol_table = symbol_table_;
134 data.counter = offset;
136 bfd_map_over_sections(abfd_, &find_function_name_in_section, &data);
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);
166 asymbol **symbol_table_;
169 #endif // __MINGW32__
171 // g++ spouts warnings if you use {0} to initialize PODs. So we use this instead:
174 template<typename POD>
175 operator POD () const { POD p; std::memset(&p, 0, sizeof p); return p; }
179 // Wraps a FARPROC. Implicitly convertible to any kind of pointer-to-function.
180 // Avoids having reinterpret casts all over the place.
181 struct auto_cast_function_ptr
183 auto_cast_function_ptr(FARPROC f) : fptr_(f) { }
185 template<typename FuncPtr>
186 operator FuncPtr() const { return reinterpret_cast<FuncPtr>(fptr_); }
191 // A wrapper around a DLL. Can dynamically get function pointers with the function() function!
192 class windows_dll : uncopyable
195 explicit windows_dll(const std::string &libname) :
197 lib_(LoadLibraryA(name_.c_str()))
199 if (!lib_) throw std::runtime_error("Failed to load dll " + name_);
202 ~windows_dll() { FreeLibrary(lib_); }
204 const std::string &name() const { return name_; }
206 auto_cast_function_ptr function(const char *func_name) const
208 FARPROC proc = GetProcAddress(lib_, func_name);
209 if (!proc) throw std::runtime_error(std::string("failed to load function ") + func_name + " from library " + name_);
219 // An object that makes sure debugging symbols are available
220 class symbol_context : uncopyable
225 if (!SymInitialize(GetCurrentProcess(), 0, TRUE))
226 throw std::runtime_error("Failed to initialize symbol context");
228 ~symbol_context() { SymCleanup(GetCurrentProcess()); }
231 // A simple Windows mutex class. Use a lock object to lock the mutex for the duration of a scope.
232 class mutex : uncopyable
235 mutex() { InitializeCriticalSection(&cs_); }
236 ~mutex() { DeleteCriticalSection(&cs_); }
240 void lock() { EnterCriticalSection(&cs_); }
241 void unlock() { LeaveCriticalSection(&cs_); }
243 CRITICAL_SECTION cs_;
247 // A lock for the mutex
248 class lock : uncopyable
251 lock(mutex &m) : m_(m) { m.lock(); }
252 ~lock() { m_.unlock(); }
258 void fill_frames(std::list<dbg::stack_frame> &frames, dbg::stack::depth_type limit)
260 lock lk(g_fill_frames_mtx);
267 STACKFRAME frame = empty_pod;
268 CONTEXT context = empty_pod;
269 context.ContextFlags = CONTEXT_FULL;
271 windows_dll kernel32("kernel32.dll");
272 void (WINAPI *RtlCaptureContext_)(CONTEXT*) = kernel32.function("RtlCaptureContext");
274 RtlCaptureContext_(&context);
276 #if defined(_M_AMD64)
277 frame.AddrPC.Offset = context.Rip;
278 frame.AddrPC.Mode = AddrModeFlat;
279 frame.AddrStack.Offset = context.Rsp;
280 frame.AddrStack.Mode = AddrModeFlat;
281 frame.AddrFrame.Offset = context.Rbp;
282 frame.AddrFrame.Mode = AddrModeFlat;
284 frame.AddrPC.Offset = context.Eip;
285 frame.AddrPC.Mode = AddrModeFlat;
286 frame.AddrStack.Offset = context.Esp;
287 frame.AddrStack.Mode = AddrModeFlat;
288 frame.AddrFrame.Offset = context.Ebp;
289 frame.AddrFrame.Mode = AddrModeFlat;
292 HANDLE process = GetCurrentProcess();
293 HANDLE thread = GetCurrentThread();
296 bool has_limit = limit != 0;
297 char symbol_buffer[sizeof(IMAGEHLP_SYMBOL) + 255];
298 char module_name_raw[MAX_PATH];
300 #if defined(_M_AMD64)
301 const DWORD machine = IMAGE_FILE_MACHINE_AMD64;
303 const DWORD machine = IMAGE_FILE_MACHINE_I386;
306 while(StackWalk(machine, process, thread, &frame, &context, 0, SymFunctionTableAccess, SymGetModuleBase, 0))
314 if (has_limit && limit-- == 0) break;
316 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(symbol_buffer);
317 symbol->SizeOfStruct = (sizeof *symbol) + 255;
318 symbol->MaxNameLength = 254;
321 DWORD64 module_base = SymGetModuleBase(process, frame.AddrPC.Offset);
323 DWORD module_base = SymGetModuleBase(process, frame.AddrPC.Offset);
325 std::string module_name = unknown_module;
326 if (module_base && GetModuleFileNameA(reinterpret_cast<HINSTANCE>(module_base), module_name_raw, MAX_PATH))
327 module_name = module_name_raw;
329 #if defined(__MINGW32__)
330 std::string func = bfdc.get_function_name(frame.AddrPC.Offset);
339 BOOL got_symbol = SymGetSymFromAddr(process, frame.AddrPC.Offset, &dummy, symbol);
340 func = got_symbol ? symbol->Name : unknown_function;
344 BOOL got_symbol = SymGetSymFromAddr(process, frame.AddrPC.Offset, &dummy, symbol);
345 std::string func = got_symbol ? symbol->Name : unknown_function;
348 dbg::stack_frame f(reinterpret_cast<const void *>(frame.AddrPC.Offset), func, module_name);
352 #elif defined(__GNUC__)
353 # if defined(__i386__) || defined(__amd64__)
355 void fill_frames(std::list<dbg::stack_frame> &frames, dbg::stack::depth_type limit)
357 // Based on code found at:
358 // http://www.tlug.org.za/wiki/index.php/Obtaining_a_stack_trace_in_C_upon_SIGSEGV
361 void **frame = static_cast<void **>(__builtin_frame_address(0));
362 void **bp = static_cast<void **>(*frame);
365 bool has_limit = limit != 0;
368 while(bp && ip && dladdr(ip, &info))
374 if (has_limit && limit-- == 0) break;
375 frames.push_back(dbg::stack_frame(ip, demangle(info.dli_sname), info.dli_fname));
377 if(info.dli_sname && !std::strcmp(info.dli_sname, "main")) break;
381 bp = static_cast<void**>(bp[0]);
385 # elif defined(__ppc__)
387 void fill_frames(std::list<dbg::stack_frame> &frames, dbg::stack::depth_type limit)
389 // Based on code found at:
390 // http://www.informit.com/articles/article.aspx?p=606582&seqNum=4&rl=1
392 void *ip = __builtin_return_address(0);
393 void **frame = static_cast<void **>(__builtin_frame_address(1));
394 bool has_limit = limit != 0;
399 if (has_limit && limit-- == 0) break;
401 if (dladdr(ip, &info))
402 frames.push_back(dbg::stack_frame(ip, demangle(info.dli_sname), info.dli_fname));
404 if (frame && (frame = static_cast<void**>(*frame))) ip = *(frame + 2);
410 // GNU, but not x86, x64 nor PPC
411 # error "Sorry but dbg::stack is not supported on this architecture"
414 // Unsupported compiler
415 # error "Sorry but dbg::stack is not supported on this compiler"
418 } // close anonymous namespace
424 stack_frame::stack_frame(const void *instruction, const std::string &function, const std::string &module) :
425 instruction(instruction),
431 std::ostream &operator<< (std::ostream &out, const stack_frame &frame)
433 return out << frame.instruction << ": " << frame.function << " in " << frame.module;
436 stack::stack(depth_type limit)
438 fill_frames(frames_, limit);
441 stack::const_iterator stack::begin() const
443 return frames_.begin();
446 stack::const_iterator stack::end() const
448 return frames_.end();
451 stack::depth_type stack::depth() const
453 return frames_.size();
456 } // close namespace dbg