2 * Copyright © 2014 Canonical Ltd.
4 * This program is free software: you can redistribute it and/or modify it
5 * under the terms of the GNU Lesser General Public License version 3,
6 * as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU Lesser General Public License for more details.
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 * Authored by: Thomas Voß <thomas.voss@canonical.com>
19 #include "backtrace.h"
25 namespace bt = core::posix::backtrace;
29 std::tuple<std::string, bool> demangle(const std::string& symbol)
32 auto result = abi::__cxa_demangle(symbol.c_str(),
37 if (!result || status != 0)
39 return std::make_tuple(std::string(), false);
42 std::string s{result};
45 return std::make_tuple(s, true);
48 struct Frame : public bt::Frame
50 struct Symbol : public bt::Frame::Symbol
52 Symbol(const char* symbol) : raw_(symbol)
54 auto first = raw_.find_first_of("(");
55 auto last = raw_.find_last_of(")");
57 if (first != std::string::npos && last != std::string::npos)
59 auto mangled_symbol = raw_.substr(first+1,
60 (last-1) - (first+1));
62 auto plus = mangled_symbol.find_first_of("+");
63 if (plus != std::string::npos)
64 mangled_symbol.erase(plus);
66 std::tie(demangled_, is_cxx_) = demangle(mangled_symbol);
77 std::string demangled() const
82 std::string raw() const
88 std::string demangled_;
96 Frame(std::size_t depth, void* frame_pointer, const char* symbol)
98 frame_pointer_(frame_pointer),
103 std::size_t depth() const
108 virtual void* frame_pointer() const
110 return frame_pointer_;
113 const Symbol& symbol() const
120 std::shared_ptr<bt::Frame::Symbol> bt::Frame::Symbol::for_testing_from_raw_symbol(const char* symbol)
122 return std::shared_ptr<bt::Frame::Symbol>(new impl::Frame::Symbol(symbol));
125 void bt::visit_with_handler(const bt::FrameHandler& handler)
127 static const unsigned int max_frames=64;
128 void *frames[max_frames];
130 auto frame_count = ::backtrace(frames, max_frames);
131 auto symbols = ::backtrace_symbols(frames, frame_count);
135 Scope(char** symbols) : symbols(symbols)
144 char** symbols = nullptr;
147 for (int i = 0; i < frame_count; i++)
149 impl::Frame frame(i, frames[i], symbols[i]);