1 /* backtrace_linux - backtrace displaying on linux platform */
2 /* This file is included by ex.cpp on need (have execinfo.h, popen & addrline)*/
4 /* Copyright (c) 2008-2018. The SimGrid Team. All rights reserved. */
6 /* This program is free software; you can redistribute it and/or modify it
7 * under the terms of the license (GNU LGPL) which comes with this package. */
16 #include <boost/algorithm/string.hpp>
22 /* This file is to be included in ex.cpp, so the following headers are not mandatory, but it's to make sure that eclipse see them too */
23 #include <xbt/string.hpp>
24 #include <xbt/backtrace.hpp>
27 #include "xbt/module.h" /* xbt_binary_name */
28 #include "src/xbt_modinter.h" /* backtrace initialization headers */
30 #define UNW_LOCAL_ONLY
31 #include <libunwind.h>
33 /* end of "useless" inclusions */
35 extern char **environ; /* the environment, as specified by the opengroup */
44 static _Unwind_Reason_Code backtrace_helper(_Unwind_Context* ctx, void* a)
46 trace_arg* arg = static_cast<trace_arg*>(a);
48 /* We are first called with address in the __backtrace function.
52 arg->array[arg->cnt] = (void *) _Unwind_GetIP(ctx);
54 /* Check whether we make any progress. */
55 if (arg->cnt > 0 && arg->array[arg->cnt - 1] == arg->array[arg->cnt])
56 return _URC_END_OF_STACK;
58 if (++arg->cnt == arg->size)
59 return _URC_END_OF_STACK;
60 return _URC_NO_REASON;
63 /** @brief reimplementation of glibc backtrace based directly on gcc library, without implicit malloc
65 * See http://people.irisa.fr/Martin.Quinson/blog/2012/0208/system_programming_fun_in_SimGrid/
66 * for the motivation behind this function
69 int xbt_backtrace_no_malloc(void **array, int size) {
71 for(i=0; i < size; i++)
80 _Unwind_Backtrace(backtrace_helper, &arg);
82 /* _Unwind_Backtrace on IA-64 seems to put nullptr address above
83 _start. Fix it up here. */
84 if (arg.cnt > 1 && arg.array[arg.cnt - 1] == nullptr)
86 return arg.cnt != -1 ? arg.cnt : 0;
89 size_t xbt_backtrace_current(xbt_backtrace_location_t* loc, std::size_t count)
91 std::size_t used = backtrace(loc, count);
93 std::fprintf(stderr, "The backtrace() function failed, which probably means that the memory is exhausted\n.");
94 std::fprintf(stderr, "Bailing out now since there is nothing I can do without a decent amount of memory\n.");
95 std::fprintf(stderr, "Please go fix the memleaks\n");
104 /** Find the path of the binary file from the name found in argv */
105 static std::string get_binary_path()
107 struct stat stat_buf;
109 if (xbt_binary_name == nullptr)
112 // We found it, we are happy:
113 if (stat(xbt_binary_name, &stat_buf) == 0)
114 return xbt_binary_name;
116 // Not found, look in the PATH:
117 char* path = getenv("PATH");
120 XBT_DEBUG("Looking in the PATH: %s\n", path);
121 std::vector<std::string> path_list;
122 // TODO, on Windows, this is ";"
123 boost::split(path_list, path, boost::is_any_of(":"));
124 for (std::string const& path_item : path_list) {
125 std::string binary_name = simgrid::xbt::string_printf(
126 "%s/%s", path_item.c_str(), xbt_binary_name);
127 bool found = (stat(binary_name.c_str(), &stat_buf) == 0);
128 XBT_DEBUG("Looked in the PATH for the binary. %s %s",
129 found ? "Found" : "Not found",
130 binary_name.c_str());
139 std::vector<std::string> resolveBacktrace(xbt_backtrace_location_t const* loc, std::size_t count) // deprecated
141 return resolve_backtrace(loc, count);
144 //FIXME: This code could be greatly improved/simplifyied with
145 // http://cairo.sourcearchive.com/documentation/1.9.4/backtrace-symbols_8c-source.html
146 std::vector<std::string> resolve_backtrace(xbt_backtrace_location_t const* loc, std::size_t count)
148 std::vector<std::string> result;
153 if (xbt_binary_name == nullptr)
154 XBT_WARN("XBT not initialized, the backtrace will not be resolved.");
156 // Drop the first one:
159 char** backtrace_syms = backtrace_symbols(loc, count);
160 std::string binary_name = get_binary_path();
162 if (binary_name.empty()) {
163 for (std::size_t i = 0; i < count; i++)
164 result.push_back(simgrid::xbt::string_printf("%p", loc[i]));
168 // Create the system command for add2line:
169 std::ostringstream stream;
170 stream << ADDR2LINE << " -f -e " << binary_name << ' ';
171 std::vector<std::string> addrs(count);
172 for (std::size_t i = 0; i < count; i++) {
173 /* retrieve this address */
174 XBT_DEBUG("Retrieving address number %zu from '%s'", i, backtrace_syms[i]);
176 snprintf(buff, 256, "%s", strchr(backtrace_syms[i], '[') + 1);
177 char* p = strchr(buff, ']');
179 if (strcmp(buff, "(nil)"))
183 XBT_DEBUG("Set up a new address: %zu, '%s'", i, addrs[i].c_str());
184 /* Add it to the command line args */
185 stream << addrs[i] << ' ';
187 std::string cmd = stream.str();
189 /* size (in char) of pointers on this arch */
190 int addr_len = addrs[0].size();
192 XBT_VERB("Fire a first command: '%s'", cmd.c_str());
193 FILE* pipe = popen(cmd.c_str(), "r");
194 xbt_assert(pipe, "Cannot fork addr2line to display the backtrace");
196 /* To read the output of addr2line */
197 char line_func[1024];
199 for (std::size_t i = 0; i < count; i++) {
200 XBT_DEBUG("Looking for symbol %zu, addr = '%s'", i, addrs[i].c_str());
201 if (fgets(line_func, 1024, pipe)) {
202 line_func[strlen(line_func) - 1] = '\0';
204 XBT_VERB("Cannot run fgets to look for symbol %zu, addr %s", i, addrs[i].c_str());
205 strncpy(line_func, "???", 4);
207 if (fgets(line_pos, 1024, pipe)) {
208 line_pos[strlen(line_pos) - 1] = '\0';
210 XBT_VERB("Cannot run fgets to look for symbol %zu, addr %s", i, addrs[i].c_str());
211 strncpy(line_pos, backtrace_syms[i],1024);
214 if (strcmp("??", line_func) != 0) {
215 auto name = simgrid::xbt::demangle(line_func);
216 XBT_DEBUG("Found static symbol %s at %s", name.get(), line_pos);
217 result.push_back(simgrid::xbt::string_printf(
218 "%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(
316 "%s at %s, %p", name.get(), line_pos, loc[i]));
318 /* damn, nothing to do here. Let's print the raw address */
319 XBT_DEBUG("Dynamic symbol not found. Raw address = %s", backtrace_syms[i]);
320 result.push_back(simgrid::xbt::string_printf(
321 "?? at %s", backtrace_syms[i]));
326 /* Mask the bottom of the stack */
327 const char* const breakers[] = {
329 "_ZN7simgrid6kernel7context13ThreadContext7wrapperE", // simgrid::kernel::context::ThreadContext::wrapper
330 "_ZN7simgrid6kernel7context8UContext7wrapperE" // simgrid::kernel::context::UContext::wrapper
332 bool do_break = false;
333 for (const char* b : breakers) {
334 if (strncmp(b, line_func, strlen(b)) == 0) {
343 free(backtrace_syms);
351 int xbt_libunwind_backtrace(void** bt, int size){
352 for (int i = 0; i < size; i++)
358 unw_getcontext (&uc);
359 unw_init_local (&c, &uc);
364 for (i = 0; unw_step(&c) >= 0 && i < size; i++) {
366 unw_get_reg(&c, UNW_REG_IP, &ip);
367 bt[i] = (void*)(long)ip;