1 /* Copyright (c) 2005-2018. The SimGrid Team. All rights reserved. */
3 /* This program is free software; you can redistribute it and/or modify it
4 * under the terms of the license (GNU LGPL) which comes with this package. */
6 #include "src/internal_config.h"
16 #include <boost/algorithm/string.hpp>
18 // Try to detect and use the C++ itanium ABI for name demangling:
19 #ifdef __GXX_ABI_VERSION
26 #include "simgrid/simix.h" /* SIMIX_process_self_get_name() */
27 #include <xbt/backtrace.hpp>
29 #include <xbt/string.hpp>
30 #include <xbt/sysdep.h>
32 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_backtrace, xbt, "Backtrace");
34 static bool startWith(std::string str, const char* prefix)
36 return strncmp(str.c_str(), prefix, strlen(prefix)) == 0;
39 void xbt_backtrace_display(xbt_backtrace_location_t* loc, std::size_t count)
41 std::vector<std::string> backtrace = simgrid::xbt::resolve_backtrace(loc, count);
42 if (backtrace.empty()) {
43 fprintf(stderr, "(backtrace not set -- maybe unavailable on this architecture?)\n");
46 fprintf(stderr, "Backtrace (displayed in process %s):\n", SIMIX_process_self_get_name());
47 for (std::string const& s : backtrace) {
48 if (startWith(s, "xbt_backtrace_display_current"))
51 std::fprintf(stderr, "---> '%s'\n", s.c_str());
52 if (startWith(s, "SIMIX_simcall_handle") ||
53 startWith(s, "simgrid::xbt::MainFunction") /* main used with thread factory */)
58 /** @brief show the backtrace of the current point (lovely while debugging) */
59 void xbt_backtrace_display_current()
61 const std::size_t size = 10;
62 xbt_backtrace_location_t bt[size];
63 size_t used = xbt_backtrace_current(bt, size);
64 xbt_backtrace_display(bt, used);
70 std::unique_ptr<char, void(*)(void*)> demangle(const char* name)
72 #ifdef __GXX_ABI_VERSION
74 auto res = std::unique_ptr<char, void(*)(void*)>(
75 abi::__cxa_demangle(name, nullptr, nullptr, &status),
80 // We did not manage to resolve this. Probably because this is not a mangled symbol:
83 return std::unique_ptr<char, void(*)(void*)>(xbt_strdup(name), std::free);
88 const std::size_t size = 10;
89 xbt_backtrace_location_t loc[size];
90 size_t used = xbt_backtrace_current(loc, size);
91 return Backtrace(loc, loc + used);
97 #if HAVE_BACKTRACE && HAVE_EXECINFO_H && HAVE_POPEN && defined(ADDR2LINE)
98 size_t xbt_backtrace_current(xbt_backtrace_location_t* loc, std::size_t count)
100 std::size_t used = backtrace(loc, count);
102 std::fprintf(stderr, "The backtrace() function failed, which probably means that the memory is exhausted\n.");
103 std::fprintf(stderr, "Bailing out now since there is nothing I can do without a decent amount of memory\n.");
104 std::fprintf(stderr, "Please go fix the memleaks\n");
113 /** Find the path of the binary file from the name found in argv */
114 static std::string get_binary_path()
116 struct stat stat_buf;
118 if (xbt_binary_name == nullptr)
121 // We found it, we are happy:
122 if (stat(xbt_binary_name, &stat_buf) == 0)
123 return xbt_binary_name;
125 // Not found, look in the PATH:
126 char* path = getenv("PATH");
129 XBT_DEBUG("Looking in the PATH: %s\n", path);
130 std::vector<std::string> path_list;
131 // TODO, on Windows, this is ";"
132 boost::split(path_list, path, boost::is_any_of(":"));
133 for (std::string const& path_item : path_list) {
134 std::string binary_name = simgrid::xbt::string_printf("%s/%s", path_item.c_str(), xbt_binary_name);
135 bool found = (stat(binary_name.c_str(), &stat_buf) == 0);
136 XBT_DEBUG("Looked in the PATH for the binary. %s %s", found ? "Found" : "Not found", binary_name.c_str());
145 // FIXME: This code could be greatly improved/simplifyied with
146 // http://cairo.sourcearchive.com/documentation/1.9.4/backtrace-symbols_8c-source.html
147 std::vector<std::string> resolve_backtrace(xbt_backtrace_location_t const* loc, std::size_t count)
149 std::vector<std::string> result;
154 if (xbt_binary_name == nullptr)
155 XBT_WARN("XBT not initialized, the backtrace will not be resolved.");
157 // Drop the first one:
161 char** backtrace_syms = backtrace_symbols(loc, count);
162 std::string binary_name = get_binary_path();
164 if (binary_name.empty()) {
165 for (std::size_t i = 0; i < count; i++)
166 result.push_back(simgrid::xbt::string_printf("%p", loc[i]));
170 // Create the system command for add2line:
171 std::ostringstream stream;
172 stream << ADDR2LINE << " -f -e " << binary_name << ' ';
173 std::vector<std::string> addrs(count);
174 for (std::size_t i = 0; i < count; i++) {
175 /* retrieve this address */
176 XBT_DEBUG("Retrieving address number %zu from '%s'", i, backtrace_syms[i]);
178 snprintf(buff, 256, "%s", strchr(backtrace_syms[i], '[') + 1);
179 char* p = strchr(buff, ']');
181 if (strcmp(buff, "(nil)"))
185 XBT_DEBUG("Set up a new address: %zu, '%s'", i, addrs[i].c_str());
186 /* Add it to the command line args */
187 stream << addrs[i] << ' ';
189 std::string cmd = stream.str();
191 /* size (in char) of pointers on this arch */
192 int addr_len = addrs[0].size();
194 XBT_VERB("Fire a first command: '%s'", cmd.c_str());
195 FILE* pipe = popen(cmd.c_str(), "r");
196 xbt_assert(pipe, "Cannot fork addr2line to display the backtrace");
198 /* To read the output of addr2line */
199 char line_func[1024];
201 for (std::size_t i = 0; i < count; i++) {
202 XBT_DEBUG("Looking for symbol %zu, addr = '%s'", i, addrs[i].c_str());
203 if (fgets(line_func, 1024, pipe)) {
204 line_func[strlen(line_func) - 1] = '\0';
206 XBT_VERB("Cannot run fgets to look for symbol %zu, addr %s", i, addrs[i].c_str());
207 strncpy(line_func, "???", 4);
209 if (fgets(line_pos, 1024, pipe)) {
210 line_pos[strlen(line_pos) - 1] = '\0';
212 XBT_VERB("Cannot run fgets to look for symbol %zu, addr %s", i, addrs[i].c_str());
213 strncpy(line_pos, backtrace_syms[i], 1024);
216 if (strcmp("??", line_func) != 0) {
217 auto name = simgrid::xbt::demangle(line_func);
218 XBT_DEBUG("Found static symbol %s at %s", name.get(), line_pos);
219 result.push_back(simgrid::xbt::string_printf("%s at %s, %p", name.get(), line_pos, loc[i]));
221 /* Damn. The symbol is in a dynamic library. Let's get wild */
223 unsigned long int offset = 0;
226 /* let's look for the offset of this library in our addressing space */
227 std::string maps_name = std::string("/proc/") + std::to_string(getpid()) + "/maps";
228 std::ifstream maps(maps_name);
230 XBT_CRITICAL("open(\"%s\") failed: %s", maps_name.c_str(), strerror(errno));
234 unsigned long int addr = std::stoul(addrs[i], &pos, 16);
235 if (pos != addrs[i].length()) {
236 XBT_CRITICAL("Cannot parse backtrace address '%s' (addr=%#lx)", addrs[i].c_str(), addr);
238 XBT_DEBUG("addr=%s (as string) =%#lx (as number)", addrs[i].c_str(), addr);
241 unsigned long int first;
242 unsigned long int last;
244 std::string maps_buff;
245 if (not std::getline(maps, maps_buff))
248 XBT_DEBUG("map line: %s", maps_buff.c_str());
250 first = std::stoul(maps_buff, &pos, 16);
251 maps_buff.erase(0, pos + 1);
252 last = std::stoul(maps_buff, nullptr, 16);
253 if (first < addr && addr < last) {
258 XBT_DEBUG("%#lx in [%#lx-%#lx]", addr, first, last);
259 XBT_DEBUG("Symbol found, map lines not further displayed (even if looking for next ones)");
266 XBT_VERB("Problem while reading the maps file. Following backtrace will be mangled.");
267 XBT_DEBUG("No dynamic. Static symbol: %s", backtrace_syms[i]);
268 result.push_back(simgrid::xbt::string_printf("?? (%s)", backtrace_syms[i]));
272 /* Ok, Found the offset of the maps line containing the searched symbol.
273 We now need to substract this from the address we got from backtrace.
276 addrs[i] = simgrid::xbt::string_printf("0x%0*lx", addr_len - 2, addr - offset);
277 XBT_DEBUG("offset=%#lx new addr=%s", offset, addrs[i].c_str());
279 /* Got it. We have our new address. Let's get the library path and we are set */
280 std::string p(backtrace_syms[i]);
282 /* library path not displayed in the map file either... */
283 snprintf(line_func, 3, "??");
285 size_t p2 = p.find_first_of("( ");
286 if (p2 != std::string::npos)
289 /* Here we go, fire an addr2line up */
290 std::string subcmd = std::string(ADDR2LINE) + " -f -e " + p + " " + addrs[i];
291 XBT_VERB("Fire another command: '%s'", subcmd.c_str());
292 FILE* subpipe = popen(subcmd.c_str(), "r");
294 xbt_die("Cannot fork addr2line to display the backtrace");
296 if (fgets(line_func, 1024, subpipe)) {
297 line_func[strlen(line_func) - 1] = '\0';
299 XBT_VERB("Cannot read result of subcommand %s", subcmd.c_str());
300 strncpy(line_func, "???", 4);
302 if (fgets(line_pos, 1024, subpipe)) {
303 line_pos[strlen(line_pos) - 1] = '\0';
305 XBT_VERB("Cannot read result of subcommand %s", subcmd.c_str());
306 strncpy(line_pos, backtrace_syms[i], 1024);
311 /* check whether the trick worked */
312 if (strcmp("??", line_func)) {
313 auto name = simgrid::xbt::demangle(line_func);
314 XBT_DEBUG("Found dynamic symbol %s at %s", name.get(), line_pos);
315 result.push_back(simgrid::xbt::string_printf("%s at %s, %p", name.get(), line_pos, loc[i]));
317 /* damn, nothing to do here. Let's print the raw address */
318 XBT_DEBUG("Dynamic symbol not found. Raw address = %s", backtrace_syms[i]);
319 result.push_back(simgrid::xbt::string_printf("?? at %s", backtrace_syms[i]));
324 /* Mask the bottom of the stack */
325 const char* const breakers[] = {
327 "_ZN7simgrid6kernel7context13ThreadContext7wrapperE", // simgrid::kernel::context::ThreadContext::wrapper
328 "_ZN7simgrid6kernel7context8UContext7wrapperE" // simgrid::kernel::context::UContext::wrapper
330 bool do_break = false;
331 for (const char* b : breakers) {
332 if (strncmp(b, line_func, strlen(b)) == 0) {
341 free(backtrace_syms);
346 } // namespace simgrid
347 #else /* We must use dummy backtraces because of missing dependencies */
348 /* create a backtrace in the given exception */
349 size_t xbt_backtrace_current(xbt_backtrace_location_t* loc, size_t count)
357 std::vector<std::string> resolve_backtrace(xbt_backtrace_location_t const* loc, std::size_t count)
359 return std::vector<std::string>();
363 } // namespace simgrid