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-2017. 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. */
13 #include <boost/algorithm/string.hpp>
19 /* 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 */
20 #include <xbt/string.hpp>
21 #include <xbt/backtrace.hpp>
25 #include "xbt/module.h" /* xbt_binary_name */
26 #include "src/xbt_modinter.h" /* backtrace initialization headers */
28 #define UNW_LOCAL_ONLY
29 #include <libunwind.h>
31 /* end of "useless" inclusions */
33 extern char **environ; /* the environment, as specified by the opengroup */
42 static _Unwind_Reason_Code
43 backtrace_helper (struct _Unwind_Context *ctx, void *a)
45 struct trace_arg *arg = (struct trace_arg *) a;
47 /* We are first called with address in the __backtrace function.
51 arg->array[arg->cnt] = (void *) _Unwind_GetIP(ctx);
53 /* Check whether we make any progress. */
54 if (arg->cnt > 0 && arg->array[arg->cnt - 1] == arg->array[arg->cnt])
55 return _URC_END_OF_STACK;
57 if (++arg->cnt == arg->size)
58 return _URC_END_OF_STACK;
59 return _URC_NO_REASON;
62 /** @brief reimplementation of glibc backtrace based directly on gcc library, without implicit malloc
64 * See http://people.irisa.fr/Martin.Quinson/blog/2012/0208/system_programming_fun_in_SimGrid/
65 * for the motivation behind this function
68 int xbt_backtrace_no_malloc(void **array, int size) {
70 for(i=0; i < size; i++)
79 _Unwind_Backtrace(backtrace_helper, &arg);
81 /* _Unwind_Backtrace on IA-64 seems to put nullptr address above
82 _start. Fix it up here. */
83 if (arg.cnt > 1 && arg.array[arg.cnt - 1] == nullptr)
85 return arg.cnt != -1 ? arg.cnt : 0;
88 size_t xbt_backtrace_current(xbt_backtrace_location_t* loc, std::size_t count)
90 std::size_t used = backtrace(loc, count);
92 std::fprintf(stderr, "The backtrace() function failed, which probably means that the memory is exhausted\n.");
93 std::fprintf(stderr, "Bailing out now since there is nothing I can do without a decent amount of memory\n.");
94 std::fprintf(stderr, "Please go fix the memleaks\n");
103 /** Find the path of the binary file from the name found in argv */
104 static std::string get_binary_path()
106 struct stat stat_buf;
108 if (xbt_binary_name == nullptr)
111 // We found it, we are happy:
112 if (stat(xbt_binary_name, &stat_buf) == 0)
113 return xbt_binary_name;
115 // Not found, look in the PATH:
116 char* path = getenv("PATH");
119 XBT_DEBUG("Looking in the PATH: %s\n", path);
120 std::vector<std::string> path_list;
121 // TODO, on Windows, this is ";"
122 boost::split(path_list, path, boost::is_any_of(":"));
123 for (std::string const& path_item : path_list) {
124 std::string binary_name = simgrid::xbt::string_printf(
125 "%s/%s", path_item.c_str(), xbt_binary_name);
126 bool found = (stat(binary_name.c_str(), &stat_buf) == 0);
127 XBT_DEBUG("Looked in the PATH for the binary. %s %s",
128 found ? "Found" : "Not found",
129 binary_name.c_str());
138 //FIXME: This code could be greatly improved/simplifyied with
139 // http://cairo.sourcearchive.com/documentation/1.9.4/backtrace-symbols_8c-source.html
140 std::vector<std::string> resolveBacktrace(
141 xbt_backtrace_location_t const* loc, std::size_t count)
143 std::vector<std::string> result;
148 if (xbt_binary_name == nullptr)
149 XBT_WARN("XBT not initialized, the backtrace will not be resolved.");
151 // Drop the first one:
154 char** backtrace_syms = backtrace_symbols(loc, count);
155 std::string binary_name = get_binary_path();
157 if (binary_name.empty()) {
158 for (std::size_t i = 0; i < count; i++)
159 result.push_back(simgrid::xbt::string_printf("%p", loc[i]));
163 // Create the system command for add2line:
164 std::ostringstream stream;
165 stream << ADDR2LINE << " -f -e " << binary_name << ' ';
166 std::vector<std::string> addrs(count);
167 for (std::size_t i = 0; i < count; i++) {
168 /* retrieve this address */
169 XBT_DEBUG("Retrieving address number %zd from '%s'", i, backtrace_syms[i]);
171 snprintf(buff, 256, "%s", strchr(backtrace_syms[i], '[') + 1);
172 char* p = strchr(buff, ']');
174 if (strcmp(buff, "(nil)"))
178 XBT_DEBUG("Set up a new address: %zd, '%s'", i, addrs[i].c_str());
179 /* Add it to the command line args */
180 stream << addrs[i] << ' ';
182 std::string cmd = stream.str();
184 /* size (in char) of pointers on this arch */
185 int addr_len = addrs[0].size();
187 XBT_VERB("Fire a first command: '%s'", cmd.c_str());
188 FILE* pipe = popen(cmd.c_str(), "r");
190 xbt_die("Cannot fork addr2line to display the backtrace");
193 /* To read the output of addr2line */
194 char line_func[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 */
226 /* let's look for the offset of this library in our addressing space */
227 char* maps_name = bprintf("/proc/%d/maps", (int) getpid());
228 FILE* maps = fopen(maps_name, "r");
230 long int addr = strtol(addrs[i].c_str(), &p, 16);
232 XBT_CRITICAL("Cannot parse backtrace address '%s' (addr=%#lx)",
233 addrs[i].c_str(), addr);
235 XBT_DEBUG("addr=%s (as string) =%#lx (as number)",
236 addrs[i].c_str(), addr);
242 if (fgets(maps_buff, 512, maps) == nullptr)
245 maps_buff[strlen(maps_buff) - 1] = '\0';
246 XBT_DEBUG("map line: %s", maps_buff);
248 sscanf(maps_buff, "%lx", &first);
249 p = strchr(maps_buff, '-') + 1;
250 sscanf(p, "%lx", &last);
251 if (first < addr && addr < last) {
256 XBT_DEBUG("%#lx in [%#lx-%#lx]", addr, first, last);
257 XBT_DEBUG("Symbol found, map lines not further displayed (even if looking for next ones)");
265 XBT_VERB("Problem while reading the maps file. Following backtrace will be mangled.");
266 XBT_DEBUG("No dynamic. Static symbol: %s", backtrace_syms[i]);
267 result.push_back(simgrid::xbt::string_printf("?? (%s)", backtrace_syms[i]));
271 /* Ok, Found the offset of the maps line containing the searched symbol.
272 We now need to substract this from the address we got from backtrace.
275 addrs[i] = simgrid::xbt::string_printf("0x%0*lx", addr_len - 2, addr - offset);
276 XBT_DEBUG("offset=%#lx new addr=%s", offset, addrs[i].c_str());
278 /* Got it. We have our new address. Let's get the library path and we are set */
279 p = xbt_strdup(backtrace_syms[i]);
281 /* library path not displayed in the map file either... */
283 snprintf(line_func,3, "??");
285 p2 = strrchr(p, '(');
288 p2 = strrchr(p, ' ');
292 /* Here we go, fire an addr2line up */
293 char* subcmd = bprintf("%s -f -e %s %s", ADDR2LINE, p, addrs[i].c_str());
295 XBT_VERB("Fire a new command: '%s'", subcmd);
296 FILE* subpipe = popen(subcmd, "r");
298 xbt_die("Cannot fork addr2line to display the backtrace");
300 if (fgets(line_func, 1024, subpipe)) {
301 line_func[strlen(line_func) - 1] = '\0';
303 XBT_VERB("Cannot read result of subcommand %s", subcmd);
304 strncpy(line_func, "???",3);
306 if (fgets(line_pos, 1024, subpipe)) {
307 line_pos[strlen(line_pos) - 1] = '\0';
309 XBT_VERB("Cannot read result of subcommand %s", subcmd);
310 strncpy(line_pos, backtrace_syms[i],1024);
316 /* check whether the trick worked */
317 if (strcmp("??", line_func)) {
318 auto name = simgrid::xbt::demangle(line_func);
319 XBT_DEBUG("Found dynamic symbol %s at %s", name.get(), line_pos);
320 result.push_back(simgrid::xbt::string_printf(
321 "%s at %s, %p", name.get(), line_pos, loc[i]));
323 /* damn, nothing to do here. Let's print the raw address */
324 XBT_DEBUG("Dynamic symbol not found. Raw address = %s", backtrace_syms[i]);
325 result.push_back(simgrid::xbt::string_printf(
326 "?? at %s", backtrace_syms[i]));
331 /* Mask the bottom of the stack */
332 if (not strncmp("main", line_func, strlen("main")) ||
333 not strncmp("xbt_thread_context_wrapper", line_func, strlen("xbt_thread_context_wrapper")) ||
334 not strncmp("smx_ctx_sysv_wrapper", line_func, strlen("smx_ctx_sysv_wrapper")))
338 free(backtrace_syms);
346 int xbt_libunwind_backtrace(void** bt, int size){
347 for (int i = 0; i < size; i++)
353 unw_getcontext (&uc);
354 unw_init_local (&c, &uc);
359 for (i = 0; unw_step(&c) >= 0 && i < size; i++) {
361 unw_get_reg(&c, UNW_REG_IP, &ip);
362 bt[i] = (void*)(long)ip;