libcruft-util/backtrace_execinfo.cpp

64 lines
1.8 KiB
C++
Raw Normal View History

2014-09-17 18:20:28 +10:00
/*
* This file is part of libgim.
*
* libgim is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* libgim is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with libgim. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2010-2014 Danny Robson <danny@nerdcruft.net>
*/
2011-05-23 17:18:52 +10:00
#include "backtrace.hpp"
#include "debug.hpp"
#include "types/casts.hpp"
2011-05-23 17:18:52 +10:00
#include <cstdlib>
#include <execinfo.h>
#include <algorithm>
#include <memory>
2014-09-17 18:20:28 +10:00
2011-05-23 17:18:52 +10:00
using namespace std;
2014-09-17 18:20:28 +10:00
//-----------------------------------------------------------------------------
2011-05-23 17:18:52 +10:00
debug::backtrace::backtrace (void):
m_frames (DEFAULT_DEPTH) {
2014-07-02 15:38:05 +10:00
size_t last;
size_t size = m_frames.size ();
2011-05-23 17:18:52 +10:00
2014-07-02 15:38:05 +10:00
while ((last = ::backtrace (&m_frames[0], m_frames.size ())) == size)
m_frames.resize (size = m_frames.size () * 2);
CHECK_GT (last, 0);
2014-07-02 15:38:05 +10:00
m_frames.resize (last);
2011-05-23 17:18:52 +10:00
}
2014-09-17 18:20:28 +10:00
//-----------------------------------------------------------------------------
2011-05-23 17:18:52 +10:00
ostream&
2012-05-10 16:53:29 +10:00
debug::operator <<(ostream &os, const debug::backtrace &rhs) {
2011-05-23 17:18:52 +10:00
const auto frames = rhs.frames ();
// We don't use the array form of unique_ptr as clang fails on ambigious constructors
typedef unique_ptr<char *, decltype(&std::free)> unique_str;
unique_str names (backtrace_symbols (frames.data (), frames.size ()), ::free);
2011-05-23 17:18:52 +10:00
for (unsigned int i = 0; i < frames.size (); ++i)
os << frames[i] << "\t" << names.get()[i] << "\n";
2011-05-23 17:18:52 +10:00
return os;
}