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-2016. The SimGrid Team.
5 * All rights reserved. */
7 /* This program is free software; you can redistribute it and/or modify it
8 * under the terms of the license (GNU LGPL) which comes with this package. */
14 #include <boost/algorithm/string.hpp>
20 /* 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 */
21 #include <xbt/string.hpp>
22 #include <xbt/backtrace.hpp>
24 #include "src/xbt/ex_interface.h"
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 */
43 static _Unwind_Reason_Code
44 backtrace_helper (struct _Unwind_Context *ctx, void *a)
46 struct trace_arg *arg = (struct 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://webloria.loria.fr/~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 //FIXME: This code could be greatly improved/simplifyied with
140 // http://cairo.sourcearchive.com/documentation/1.9.4/backtrace-symbols_8c-source.html
141 std::vector<std::string> resolveBacktrace(
142 xbt_backtrace_location_t const* loc, std::size_t count)
144 std::vector<std::string> result;
149 if (xbt_binary_name == nullptr)
150 XBT_WARN("XBT not initialized, the backtrace will not be resolved.");
152 // Drop the first one:
155 char** backtrace_syms = backtrace_symbols(loc, count);
156 std::string binary_name = get_binary_path();
158 if (binary_name.empty()) {
159 for (std::size_t i = 0; i < count; i++)
160 result.push_back(simgrid::xbt::string_printf("%p", loc[i]));
164 // Create the system command for add2line:
165 std::ostringstream stream;
166 stream << ADDR2LINE << " -f -e " << binary_name << ' ';
167 std::vector<std::string> addrs(count);
168 for (std::size_t i = 0; i < count; i++) {
169 /* retrieve this address */
170 XBT_DEBUG("Retrieving address number %zd from '%s'", i, backtrace_syms[i]);
172 snprintf(buff, 256, "%s", strchr(backtrace_syms[i], '[') + 1);
173 char* p = strchr(buff, ']');
175 if (strcmp(buff, "(nil)"))
179 XBT_DEBUG("Set up a new address: %zd, '%s'", i, addrs[i].c_str());
180 /* Add it to the command line args */
181 stream << addrs[i] << ' ';
183 std::string cmd = stream.str();
185 /* size (in char) of pointers on this arch */
186 int addr_len = addrs[0].size();
188 XBT_VERB("Fire a first command: '%s'", cmd.c_str());
189 FILE* pipe = popen(cmd.c_str(), "r");
191 xbt_die("Cannot fork addr2line to display the backtrace");
194 /* To read the output of addr2line */
195 char line_func[1024], line_pos[1024];
196 for (std::size_t i = 0; i < count; i++) {
197 XBT_DEBUG("Looking for symbol %zd, addr = '%s'", i, addrs[i].c_str());
198 if (fgets(line_func, 1024, pipe)) {
199 line_func[strlen(line_func) - 1] = '\0';
201 XBT_VERB("Cannot run fgets to look for symbol %zd, addr %s", i, addrs[i].c_str());
202 strncpy(line_func, "???",3);
204 if (fgets(line_pos, 1024, pipe)) {
205 line_pos[strlen(line_pos) - 1] = '\0';
207 XBT_VERB("Cannot run fgets to look for symbol %zd, addr %s", i, addrs[i].c_str());
208 strncpy(line_pos, backtrace_syms[i],1024);
211 if (strcmp("??", line_func) != 0) {
212 auto name = simgrid::xbt::demangle(line_func);
213 XBT_DEBUG("Found static symbol %s at %s", name.get(), line_pos);
214 result.push_back(simgrid::xbt::string_printf(
215 "%s at %s, %p", name.get(), line_pos, loc[i]
218 /* Damn. The symbol is in a dynamic library. Let's get wild */
225 /* let's look for the offset of this library in our addressing space */
226 char* maps_name = bprintf("/proc/%d/maps", (int) getpid());
227 FILE* maps = fopen(maps_name, "r");
229 long int addr = strtol(addrs[i].c_str(), &p, 16);
231 XBT_CRITICAL("Cannot parse backtrace address '%s' (addr=%#lx)",
232 addrs[i].c_str(), addr);
234 XBT_DEBUG("addr=%s (as string) =%#lx (as number)",
235 addrs[i].c_str(), addr);
238 long int first, last;
240 if (fgets(maps_buff, 512, maps) == nullptr)
243 maps_buff[strlen(maps_buff) - 1] = '\0';
244 XBT_DEBUG("map line: %s", maps_buff);
246 sscanf(maps_buff, "%lx", &first);
247 p = strchr(maps_buff, '-') + 1;
248 sscanf(p, "%lx", &last);
249 if (first < addr && addr < last) {
254 XBT_DEBUG("%#lx in [%#lx-%#lx]", addr, first, last);
255 XBT_DEBUG("Symbol found, map lines not further displayed (even if looking for next ones)");
263 XBT_VERB("Problem while reading the maps file. Following backtrace will be mangled.");
264 XBT_DEBUG("No dynamic. Static symbol: %s", backtrace_syms[i]);
265 result.push_back(simgrid::xbt::string_printf("?? (%s)", backtrace_syms[i]));
269 /* Ok, Found the offset of the maps line containing the searched symbol.
270 We now need to substract this from the address we got from backtrace.
273 addrs[i] = simgrid::xbt::string_printf("0x%0*lx", addr_len - 2, addr - offset);
274 XBT_DEBUG("offset=%#lx new addr=%s", offset, addrs[i].c_str());
276 /* Got it. We have our new address. Let's get the library path and we are set */
277 p = xbt_strdup(backtrace_syms[i]);
279 /* library path not displayed in the map file either... */
281 snprintf(line_func,3, "??");
283 p2 = strrchr(p, '(');
286 p2 = strrchr(p, ' ');
290 /* Here we go, fire an addr2line up */
291 char* subcmd = bprintf("%s -f -e %s %s", ADDR2LINE, p, addrs[i].c_str());
293 XBT_VERB("Fire a new command: '%s'", subcmd);
294 FILE* subpipe = popen(subcmd, "r");
296 xbt_die("Cannot fork addr2line to display the backtrace");
298 if (fgets(line_func, 1024, subpipe)) {
299 line_func[strlen(line_func) - 1] = '\0';
301 XBT_VERB("Cannot read result of subcommand %s", subcmd);
302 strncpy(line_func, "???",3);
304 if (fgets(line_pos, 1024, subpipe)) {
305 line_pos[strlen(line_pos) - 1] = '\0';
307 XBT_VERB("Cannot read result of subcommand %s", subcmd);
308 strncpy(line_pos, backtrace_syms[i],1024);
314 /* check whether the trick worked */
315 if (strcmp("??", line_func)) {
316 auto name = simgrid::xbt::demangle(line_func);
317 XBT_DEBUG("Found dynamic symbol %s at %s", name.get(), line_pos);
318 result.push_back(simgrid::xbt::string_printf(
319 "%s at %s, %p", name.get(), line_pos, loc[i]));
321 /* damn, nothing to do here. Let's print the raw address */
322 XBT_DEBUG("Dynamic symbol not found. Raw address = %s", backtrace_syms[i]);
323 result.push_back(simgrid::xbt::string_printf(
324 "?? at %s", backtrace_syms[i]));
329 /* Mask the bottom of the stack */
330 if (!strncmp("main", line_func, strlen("main")) ||
331 !strncmp("xbt_thread_context_wrapper", line_func, strlen("xbt_thread_context_wrapper"))
332 || !strncmp("smx_ctx_sysv_wrapper", line_func, strlen("smx_ctx_sysv_wrapper")))
336 free(backtrace_syms);
344 int xbt_libunwind_backtrace(void** bt, int size){
345 for (int i = 0; i < size; i++)
351 unw_getcontext (&uc);
352 unw_init_local (&c, &uc);
357 for (i = 0; unw_step(&c) >= 0 && i < size; i++) {
359 unw_get_reg(&c, UNW_REG_IP, &ip);
360 bt[i] = (void*)(long)ip;