libcruft-util/backtrace_execinfo.cpp

69 lines
1.6 KiB
C++
Raw Normal View History

2014-09-17 18:20:28 +10:00
/*
2018-08-04 15:14:06 +10:00
* 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/.
2014-09-17 18:20:28 +10:00
*
* Copyright 2019, Danny Robson <danny@nerdcruft.net>
2014-09-17 18:20:28 +10:00
*/
2011-05-23 17:18:52 +10:00
#include "backtrace.hpp"
#include "cast.hpp"
#include "iterator/zip.hpp"
2011-05-23 17:18:52 +10:00
#include <ostream>
2011-05-23 17:18:52 +10:00
#include <memory>
#include <execinfo.h>
using cruft::backtrace;
static constexpr std::size_t DEFAULT_DEPTH = 16;
2014-09-17 18:20:28 +10:00
2016-03-11 13:28:56 +11:00
///////////////////////////////////////////////////////////////////////////////
backtrace::backtrace (void)
: m_frames (DEFAULT_DEPTH)
{
do {
int const target = static_cast<int> (m_frames.size ());
int const last = ::backtrace (
m_frames.data (), target
);
2011-05-23 17:18:52 +10:00
if (last < target) {
m_frames.resize (last);
break;
}
2014-07-02 15:38:05 +10:00
m_frames.resize (m_frames.size () * 2);
} while (1);
2011-05-23 17:18:52 +10:00
}
2016-03-11 13:28:56 +11:00
///////////////////////////////////////////////////////////////////////////////
2016-04-05 11:09:28 +10:00
std::ostream&
cruft::operator <<(std::ostream &os, backtrace const &rhs) {
os << "[ ";
2018-07-24 15:46:28 +10:00
auto const &frames = rhs.frames ();
2011-05-23 17:18:52 +10:00
using strings_t = std::unique_ptr<char *, decltype(&std::free)>;
strings_t const names (
backtrace_symbols (
frames.data (),
cruft::cast::lossless <int> (frames.size ())
),
::free
);
2011-05-23 17:18:52 +10:00
for (auto const [idx,addr]: cruft::iterator::izip (frames)) {
os << "{ addr: " << frames[idx]
<< ", name: '" << names.get()[idx] << '\''
<< " }, ";
}
2011-05-23 17:18:52 +10:00
os << " ]";
2011-05-23 17:18:52 +10:00
return os;
}