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)
14 #include "dbg/stack.hpp"
18 # include <imagehlp.h>
20 # if defined(__MINGW32__)
21 # include <bfd.h> // link against libbfd and libiberty
22 # include <psapi.h> // link against psapi
26 #elif defined(__GNUC__)
33 const char * const unknown_function = "[unknown function]";
34 const char * const unknown_module = "[unknown module]";
37 std::string demangle(const char *name)
40 return unknown_function;
44 std::string ret = name;
47 if ((d = abi::__cxa_demangle(name, 0, 0, &status)))
50 catch (const std::bad_alloc &) { }
59 // Derive from this to disallow copying of your class.
60 // c.f. boost::noncopyable
67 uncopyable(const uncopyable &);
68 uncopyable &operator= (const uncopyable &);
71 #if defined(__MINGW32__)
73 // Provides a means to translate a program counter offset in to the name of the corresponding function.
74 class bfd_context : uncopyable
80 asymbol **symbol_table;
90 char procname[MAX_PATH];
91 GetModuleFileNameA(NULL, procname, sizeof procname);
94 abfd_ = bfd_openr(procname, 0);
96 throw std::runtime_error("Failed to parse object data for the executable");
99 bool b1 = bfd_check_format(abfd_, bfd_object);
100 bool b2 = bfd_check_format_matches(abfd_, bfd_object, &formats);
101 bool b3 = bfd_get_file_flags(abfd_) & HAS_SYMS;
103 if (!(b1 && b2 && b3))
107 throw std::runtime_error("Failed to parse object data for the executable");
113 if (bfd_read_minisymbols(abfd_, FALSE, reinterpret_cast<void **>(&symbol_table_), &dummy) == 0 &&
114 bfd_read_minisymbols(abfd_, TRUE, reinterpret_cast<void **>(&symbol_table_), &dummy) < 0)
118 throw std::runtime_error("Failed to parse object data for the executable");
128 std::string get_function_name(DWORD offset)
131 data.symbol_table = symbol_table_;
132 data.counter = offset;
134 bfd_map_over_sections(abfd_, &find_function_name_in_section, &data);
140 static void find_function_name_in_section(bfd *abfd, asection *sec, void *opaque_data)
144 find_data &data = *static_cast<find_data *>(opaque_data);
146 if (!data.func.empty()) return; // already found it
148 if (!(bfd_get_section_flags(abfd, sec) & SEC_ALLOC)) return;
150 bfd_vma vma = bfd_get_section_vma(abfd, sec);
151 if (data.counter < vma || vma + bfd_get_section_size(sec) <= data.counter) return;
153 const char *func = 0;
154 const char *file = 0;
157 if (bfd_find_nearest_line(abfd, sec, data.symbol_table, data.counter - vma, &file, &func, &line) && func)
158 data.func = demangle(func);
164 asymbol **symbol_table_;
167 #endif // __MINGW32__
169 // g++ spouts warnings if you use {0} to initialize PODs. So we use this instead:
172 template<typename POD>
173 operator POD () const { POD p; std::memset(&p, 0, sizeof p); return p; }
177 // Wraps a FARPROC. Implicitly convertible to any kind of pointer-to-function.
178 // Avoids having reinterpret casts all over the place.
179 struct auto_cast_function_ptr
181 auto_cast_function_ptr(FARPROC f) : fptr_(f) { }
183 template<typename FuncPtr>
184 operator FuncPtr() const { return reinterpret_cast<FuncPtr>(fptr_); }
189 // A wrapper around a DLL. Can dynamically get function pointers with the function() function!
190 class windows_dll : uncopyable
193 explicit windows_dll(const std::string &libname) :
195 lib_(LoadLibrary(name_.c_str()))
197 if (!lib_) throw std::runtime_error("Failed to load dll " + name_);
200 ~windows_dll() { FreeLibrary(lib_); }
202 const std::string &name() const { return name_; }
204 auto_cast_function_ptr function(const char *func_name) const
206 FARPROC proc = GetProcAddress(lib_, func_name);
207 if (!proc) throw std::runtime_error(std::string("failed to load function ") + func_name + " from library " + name_);
217 // An object that makes sure debugging symbols are available
218 class symbol_context : uncopyable
223 if (!SymInitialize(GetCurrentProcess(), 0, TRUE))
224 throw std::runtime_error("Failed to initialize symbol context");
226 ~symbol_context() { SymCleanup(GetCurrentProcess()); }
229 // A simple Windows mutex class. Use a lock object to lock the mutex for the duration of a scope.
230 class mutex : uncopyable
233 mutex() { InitializeCriticalSection(&cs_); }
234 ~mutex() { DeleteCriticalSection(&cs_); }
238 void lock() { EnterCriticalSection(&cs_); }
239 void unlock() { LeaveCriticalSection(&cs_); }
241 CRITICAL_SECTION cs_;
245 // A lock for the mutex
246 class lock : uncopyable
249 lock(mutex &m) : m_(m) { m.lock(); }
250 ~lock() { m_.unlock(); }
256 void fill_frames(std::list<dbg::stack_frame> &frames, dbg::stack::depth_type limit)
258 lock lk(g_fill_frames_mtx);
265 STACKFRAME frame = empty_pod;
266 CONTEXT context = empty_pod;
267 context.ContextFlags = CONTEXT_FULL;
269 windows_dll kernel32("kernel32.dll");
270 void (WINAPI *RtlCaptureContext_)(CONTEXT*) = kernel32.function("RtlCaptureContext");
272 RtlCaptureContext_(&context);
274 #if defined(_M_AMD64)
275 frame.AddrPC.Offset = context.Rip;
276 frame.AddrPC.Mode = AddrModeFlat;
277 frame.AddrStack.Offset = context.Rsp;
278 frame.AddrStack.Mode = AddrModeFlat;
279 frame.AddrFrame.Offset = context.Rbp;
280 frame.AddrFrame.Mode = AddrModeFlat;
282 frame.AddrPC.Offset = context.Eip;
283 frame.AddrPC.Mode = AddrModeFlat;
284 frame.AddrStack.Offset = context.Esp;
285 frame.AddrStack.Mode = AddrModeFlat;
286 frame.AddrFrame.Offset = context.Ebp;
287 frame.AddrFrame.Mode = AddrModeFlat;
290 HANDLE process = GetCurrentProcess();
291 HANDLE thread = GetCurrentThread();
294 bool has_limit = limit != 0;
295 char symbol_buffer[sizeof(IMAGEHLP_SYMBOL) + 255];
296 char module_name_raw[MAX_PATH];
298 #if defined(_M_AMD64)
299 const DWORD machine = IMAGE_FILE_MACHINE_AMD64;
301 const DWORD machine = IMAGE_FILE_MACHINE_I386;
304 while(StackWalk(machine, process, thread, &frame, &context, 0, SymFunctionTableAccess, SymGetModuleBase, 0))
312 if (has_limit && limit-- == 0) break;
314 IMAGEHLP_SYMBOL *symbol = reinterpret_cast<IMAGEHLP_SYMBOL *>(symbol_buffer);
315 symbol->SizeOfStruct = (sizeof *symbol) + 255;
316 symbol->MaxNameLength = 254;
319 DWORD64 module_base = SymGetModuleBase(process, frame.AddrPC.Offset);
321 DWORD module_base = SymGetModuleBase(process, frame.AddrPC.Offset);
323 std::string module_name = unknown_module;
324 if (module_base && GetModuleFileNameA(reinterpret_cast<HINSTANCE>(module_base), module_name_raw, MAX_PATH))
325 module_name = module_name_raw;
327 #if defined(__MINGW32__)
328 std::string func = bfdc.get_function_name(frame.AddrPC.Offset);
333 BOOL got_symbol = SymGetSymFromAddr(process, frame.AddrPC.Offset, &dummy, symbol);
334 func = got_symbol ? symbol->Name : unknown_function;
338 BOOL got_symbol = SymGetSymFromAddr(process, frame.AddrPC.Offset, &dummy, symbol);
339 std::string func = got_symbol ? symbol->Name : unknown_function;
342 dbg::stack_frame f(reinterpret_cast<const void *>(frame.AddrPC.Offset), func, module_name);
346 #elif defined(__GNUC__)
347 # if defined(__i386__) || defined(__amd64__)
349 void fill_frames(std::list<dbg::stack_frame> &frames, dbg::stack::depth_type limit)
351 // Based on code found at:
352 // http://www.tlug.org.za/wiki/index.php/Obtaining_a_stack_trace_in_C_upon_SIGSEGV
355 void **frame = static_cast<void **>(__builtin_frame_address(0));
356 void **bp = static_cast<void **>(*frame);
359 bool has_limit = limit != 0;
362 while(bp && ip && dladdr(ip, &info))
368 if (has_limit && limit-- == 0) break;
369 frames.push_back(dbg::stack_frame(ip, demangle(info.dli_sname), info.dli_fname));
371 if(info.dli_sname && !std::strcmp(info.dli_sname, "main")) break;
375 bp = static_cast<void**>(bp[0]);
379 # elif defined(__ppc__)
381 void fill_frames(std::list<dbg::stack_frame> &frames, dbg::stack::depth_type limit)
383 // Based on code found at:
384 // http://www.informit.com/articles/article.aspx?p=606582&seqNum=4&rl=1
386 void *ip = __builtin_return_address(0);
387 void **frame = static_cast<void **>(__builtin_frame_address(1));
388 bool has_limit = limit != 0;
393 if (has_limit && limit-- == 0) break;
395 if (dladdr(ip, &info))
396 frames.push_back(dbg::stack_frame(ip, demangle(info.dli_sname), info.dli_fname));
398 if (frame && (frame = static_cast<void**>(*frame))) ip = *(frame + 2);
404 // GNU, but not x86, x64 nor PPC
405 # error "Sorry but dbg::stack is not supported on this architecture"
408 // Unsupported compiler
409 # error "Sorry but dbg::stack is not supported on this compiler"
412 } // close anonymous namespace
418 stack_frame::stack_frame(const void *instruction, const std::string &function, const std::string &module) :
419 instruction(instruction),
425 std::ostream &operator<< (std::ostream &out, const stack_frame &frame)
427 return out << frame.instruction << ": " << frame.function << " in " << frame.module;
430 stack::stack(depth_type limit)
432 fill_frames(frames_, limit);
435 stack::const_iterator stack::begin() const
437 return frames_.begin();
440 stack::const_iterator stack::end() const
442 return frames_.end();
445 stack::depth_type stack::depth() const
447 return frames_.size();
450 } // close namespace dbg