Danny Robson
f6056153e3
This places, at long last, the core library code into the same namespace as the extended library code.
78 lines
2.1 KiB
C++
78 lines
2.1 KiB
C++
/*
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
*
|
|
* Copyright 2010-2014 Danny Robson <danny@nerdcruft.net>
|
|
*/
|
|
|
|
|
|
#include "backtrace.hpp"
|
|
|
|
#include "debug.hpp"
|
|
#include "exe.hpp"
|
|
#include "io.hpp"
|
|
#include "cast.hpp"
|
|
|
|
#include <sstream>
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <execinfo.h>
|
|
#include <memory>
|
|
|
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
debug::backtrace::backtrace (void):
|
|
m_frames (DEFAULT_DEPTH)
|
|
{
|
|
size_t last;
|
|
size_t size = m_frames.size ();
|
|
|
|
while ((last = ::backtrace (&m_frames[0], cruft::cast::lossless <int> (m_frames.size ()))) == size)
|
|
m_frames.resize (size = m_frames.size () * 2);
|
|
|
|
CHECK_GT (last, 0u);
|
|
m_frames.resize (last);
|
|
}
|
|
|
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
static std::string
|
|
addr2line (const void *addr)
|
|
{
|
|
#if defined(ADDR2LINE)
|
|
using pstream_t = std::unique_ptr<FILE,decltype(&::pclose)>;
|
|
|
|
std::ostringstream cmd;
|
|
cmd << ADDR2LINE << " -e " << cruft::image_path () << ' ' << std::hex << addr;
|
|
|
|
pstream_t stream (
|
|
::popen (cmd.str ().c_str (), "r"),
|
|
::pclose
|
|
);
|
|
|
|
// inefficient to copy from vector to string, but it's not a high priority path
|
|
auto data = cruft::slurp<char> (stream.get ());
|
|
return std::string (data.cbegin (), data.cend ());
|
|
|
|
#else
|
|
return "";
|
|
#endif
|
|
}
|
|
|
|
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
std::ostream&
|
|
debug::operator <<(std::ostream &os, const debug::backtrace &rhs) {
|
|
auto const &frames = rhs.frames ();
|
|
|
|
// We don't use the array form of unique_ptr as clang fails on ambigious constructors
|
|
typedef std::unique_ptr<char *, decltype(&std::free)> str_t;
|
|
str_t names (backtrace_symbols (frames.data (), cruft::cast::lossless <int> (frames.size ())), ::free);
|
|
|
|
for (unsigned int i = 0; i < frames.size (); ++i)
|
|
os << frames[i] << '\t' << names.get()[i] << '\t' << addr2line (frames[i]);
|
|
|
|
return os;
|
|
}
|