Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
5b23cb1974f5594d11ac223ad2825bb0777510df
[simgrid.git] / src / xbt / backtrace_linux.cpp
1 /* backtrace_linux - backtrace displaying on linux platform                 */
2 /* This file is included by ex.cpp on need (have execinfo.h, popen & addrline)*/
3
4 /* Copyright (c) 2008-2017. The SimGrid Team. All rights reserved.          */
5
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. */
8
9 #include <sstream>
10 #include <string>
11 #include <vector>
12
13 #include <boost/algorithm/string.hpp>
14
15 #include <unistd.h>
16 #include <execinfo.h>
17 #include <sys/stat.h>
18
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>
22 #include "xbt/ex.h"
23 #include "xbt/log.h"
24 #include "xbt/module.h"         /* xbt_binary_name */
25 #include "src/xbt_modinter.h"       /* backtrace initialization headers */
26 #if SIMGRID_HAVE_MC
27 #define UNW_LOCAL_ONLY
28 #include <libunwind.h>
29 #endif
30 /* end of "useless" inclusions */
31
32 extern char **environ;          /* the environment, as specified by the opengroup */
33
34 #include <unwind.h>
35 struct trace_arg {
36   void** array;
37   int cnt;
38   int size;
39 };
40
41 static _Unwind_Reason_Code backtrace_helper(_Unwind_Context* ctx, void* a)
42 {
43   trace_arg* arg = static_cast<trace_arg*>(a);
44
45   /* We are first called with address in the __backtrace function.
46      Skip it.  */
47   if (arg->cnt != -1)
48     {
49       arg->array[arg->cnt] = (void *) _Unwind_GetIP(ctx);
50
51       /* Check whether we make any progress.  */
52       if (arg->cnt > 0 && arg->array[arg->cnt - 1] == arg->array[arg->cnt])
53         return _URC_END_OF_STACK;
54     }
55   if (++arg->cnt == arg->size)
56     return _URC_END_OF_STACK;
57   return _URC_NO_REASON;
58 }
59
60 /** @brief reimplementation of glibc backtrace based directly on gcc library, without implicit malloc
61  *
62  * See http://people.irisa.fr/Martin.Quinson/blog/2012/0208/system_programming_fun_in_SimGrid/
63  * for the motivation behind this function
64  * */
65
66 int xbt_backtrace_no_malloc(void **array, int size) {
67   int i = 0;
68   for(i=0; i < size; i++)
69     array[i] = nullptr;
70
71   struct trace_arg arg;
72   arg .array = array;
73   arg.size = size;
74   arg.cnt = -1;
75
76   if (size >= 1)
77     _Unwind_Backtrace(backtrace_helper, &arg);
78
79   /* _Unwind_Backtrace on IA-64 seems to put nullptr address above
80      _start.  Fix it up here.  */
81   if (arg.cnt > 1 && arg.array[arg.cnt - 1] == nullptr)
82     --arg.cnt;
83   return arg.cnt != -1 ? arg.cnt : 0;
84 }
85
86 size_t xbt_backtrace_current(xbt_backtrace_location_t* loc, std::size_t count)
87 {
88   std::size_t used = backtrace(loc, count);
89   if (used == 0) {
90     std::fprintf(stderr, "The backtrace() function failed, which probably means that the memory is exhausted\n.");
91     std::fprintf(stderr, "Bailing out now since there is nothing I can do without a decent amount of memory\n.");
92     std::fprintf(stderr, "Please go fix the memleaks\n");
93     std::exit(1);
94   }
95   return used;
96 }
97
98 namespace simgrid {
99 namespace xbt {
100
101 /** Find the path of the binary file from the name found in argv */
102 static std::string get_binary_path()
103 {
104   struct stat stat_buf;
105
106   if (xbt_binary_name == nullptr)
107     return "";
108
109   // We found it, we are happy:
110   if (stat(xbt_binary_name, &stat_buf) == 0)
111     return xbt_binary_name;
112
113   // Not found, look in the PATH:
114   char* path = getenv("PATH");
115   if (path == nullptr)
116     return "";
117   XBT_DEBUG("Looking in the PATH: %s\n", path);
118   std::vector<std::string> path_list;
119   // TODO, on Windows, this is ";"
120   boost::split(path_list, path, boost::is_any_of(":"));
121   for (std::string const& path_item : path_list) {
122     std::string binary_name = simgrid::xbt::string_printf(
123       "%s/%s", path_item.c_str(), xbt_binary_name);
124     bool found = (stat(binary_name.c_str(), &stat_buf) == 0);
125     XBT_DEBUG("Looked in the PATH for the binary. %s %s",
126       found ? "Found" : "Not found",
127       binary_name.c_str());
128     if (found)
129       return binary_name;
130   }
131
132   // Not found at all:
133   return "";
134 }
135
136 //FIXME: This code could be greatly improved/simplifyied with
137 //   http://cairo.sourcearchive.com/documentation/1.9.4/backtrace-symbols_8c-source.html
138 std::vector<std::string> resolveBacktrace(
139   xbt_backtrace_location_t const* loc, std::size_t count)
140 {
141   std::vector<std::string> result;
142
143   if (count == 0)
144     return result;
145
146   if (xbt_binary_name == nullptr)
147     XBT_WARN("XBT not initialized, the backtrace will not be resolved.");
148
149   // Drop the first one:
150   loc++; count--;
151
152   char** backtrace_syms = backtrace_symbols(loc, count);
153   std::string binary_name = get_binary_path();
154
155   if (binary_name.empty()) {
156     for (std::size_t i = 0; i < count; i++)
157       result.push_back(simgrid::xbt::string_printf("%p", loc[i]));
158     return result;
159   }
160
161   // Create the system command for add2line:
162   std::ostringstream stream;
163   stream << ADDR2LINE << " -f -e " << binary_name << ' ';
164   std::vector<std::string> addrs(count);
165   for (std::size_t i = 0; i < count; i++) {
166     /* retrieve this address */
167     XBT_DEBUG("Retrieving address number %zu from '%s'", i, backtrace_syms[i]);
168     char buff[256];
169     snprintf(buff, 256, "%s", strchr(backtrace_syms[i], '[') + 1);
170     char* p = strchr(buff, ']');
171     *p = '\0';
172     if (strcmp(buff, "(nil)"))
173       addrs[i] = buff;
174     else
175       addrs[i] = "0x0";
176     XBT_DEBUG("Set up a new address: %zu, '%s'", i, addrs[i].c_str());
177     /* Add it to the command line args */
178     stream << addrs[i] << ' ';
179   }
180   std::string cmd = stream.str();
181
182   /* size (in char) of pointers on this arch */
183   int addr_len = addrs[0].size();
184
185   XBT_VERB("Fire a first command: '%s'", cmd.c_str());
186   FILE* pipe = popen(cmd.c_str(), "r");
187   if (not pipe) {
188     xbt_die("Cannot fork addr2line to display the backtrace");
189   }
190
191   /* To read the output of addr2line */
192   char line_func[1024];
193   char line_pos[1024];
194   for (std::size_t i = 0; i < count; i++) {
195     XBT_DEBUG("Looking for symbol %zu, addr = '%s'", i, addrs[i].c_str());
196     if (fgets(line_func, 1024, pipe)) {
197       line_func[strlen(line_func) - 1] = '\0';
198     } else {
199       XBT_VERB("Cannot run fgets to look for symbol %zu, addr %s", i, addrs[i].c_str());
200       strncpy(line_func, "???",3);
201     }
202     if (fgets(line_pos, 1024, pipe)) {
203       line_pos[strlen(line_pos) - 1] = '\0';
204     } else {
205       XBT_VERB("Cannot run fgets to look for symbol %zu, addr %s", i, addrs[i].c_str());
206       strncpy(line_pos, backtrace_syms[i],1024);
207     }
208
209     if (strcmp("??", line_func) != 0) {
210       auto name = simgrid::xbt::demangle(line_func);
211       XBT_DEBUG("Found static symbol %s at %s", name.get(), line_pos);
212       result.push_back(simgrid::xbt::string_printf(
213         "%s at %s, %p", name.get(), line_pos, loc[i]
214       ));
215     } else {
216       /* Damn. The symbol is in a dynamic library. Let's get wild */
217
218       char maps_buff[512];
219       unsigned long int offset = 0;
220       char* p;
221       int found = 0;
222
223       /* let's look for the offset of this library in our addressing space */
224       std::string maps_name = std::string("/proc/") + std::to_string(getpid()) + "maps";
225       FILE* maps            = fopen(maps_name.c_str(), "r");
226
227       unsigned long int addr = strtoul(addrs[i].c_str(), &p, 16);
228       if (*p != '\0') {
229         XBT_CRITICAL("Cannot parse backtrace address '%s' (addr=%#lx)", addrs[i].c_str(), addr);
230       }
231       XBT_DEBUG("addr=%s (as string) =%#lx (as number)", addrs[i].c_str(), addr);
232
233       while (not found) {
234         unsigned long int first;
235         unsigned long int last;
236
237         if (fgets(maps_buff, 512, maps) == nullptr)
238           break;
239         if (i == 0) {
240           maps_buff[strlen(maps_buff) - 1] = '\0';
241           XBT_DEBUG("map line: %s", maps_buff);
242         }
243         sscanf(maps_buff, "%lx", &first);
244         p = strchr(maps_buff, '-') + 1;
245         sscanf(p, "%lx", &last);
246         if (first < addr && addr < last) {
247           offset = first;
248           found = 1;
249         }
250         if (found) {
251           XBT_DEBUG("%#lx in [%#lx-%#lx]", addr, first, last);
252           XBT_DEBUG("Symbol found, map lines not further displayed (even if looking for next ones)");
253         }
254       }
255       fclose(maps);
256       addrs[i].clear();
257
258       if (not found) {
259         XBT_VERB("Problem while reading the maps file. Following backtrace will be mangled.");
260         XBT_DEBUG("No dynamic. Static symbol: %s", backtrace_syms[i]);
261         result.push_back(simgrid::xbt::string_printf("?? (%s)", backtrace_syms[i]));
262         continue;
263       }
264
265       /* Ok, Found the offset of the maps line containing the searched symbol.
266          We now need to substract this from the address we got from backtrace.
267        */
268
269       addrs[i] = simgrid::xbt::string_printf("0x%0*lx", addr_len - 2, addr - offset);
270       XBT_DEBUG("offset=%#lx new addr=%s", offset, addrs[i].c_str());
271
272       /* Got it. We have our new address. Let's get the library path and we are set */
273       p = xbt_strdup(backtrace_syms[i]);
274       if (p[0] == '[') {
275         /* library path not displayed in the map file either... */
276         free(p);
277         snprintf(line_func,3, "??");
278       } else {
279         char* p2 = strrchr(p, '(');
280         if (p2)
281           *p2 = '\0';
282         p2 = strrchr(p, ' ');
283         if (p2)
284           *p2 = '\0';
285
286         /* Here we go, fire an addr2line up */
287         std::string subcmd = std::string(ADDR2LINE) + " -f -e " + p + " " + addrs[i];
288         free(p);
289         XBT_VERB("Fire a new command: '%s'", subcmd.c_str());
290         FILE* subpipe = popen(subcmd.c_str(), "r");
291         if (not subpipe) {
292           xbt_die("Cannot fork addr2line to display the backtrace");
293         }
294         if (fgets(line_func, 1024, subpipe)) {
295           line_func[strlen(line_func) - 1] = '\0';
296         } else {
297           XBT_VERB("Cannot read result of subcommand %s", subcmd.c_str());
298           strncpy(line_func, "???",3);
299         }
300         if (fgets(line_pos, 1024, subpipe)) {
301           line_pos[strlen(line_pos) - 1] = '\0';
302         } else {
303           XBT_VERB("Cannot read result of subcommand %s", subcmd.c_str());
304           strncpy(line_pos, backtrace_syms[i],1024);
305         }
306         pclose(subpipe);
307       }
308
309       /* check whether the trick worked */
310       if (strcmp("??", line_func)) {
311         auto name = simgrid::xbt::demangle(line_func);
312         XBT_DEBUG("Found dynamic symbol %s at %s", name.get(), line_pos);
313         result.push_back(simgrid::xbt::string_printf(
314           "%s at %s, %p", name.get(), line_pos, loc[i]));
315       } else {
316         /* damn, nothing to do here. Let's print the raw address */
317         XBT_DEBUG("Dynamic symbol not found. Raw address = %s", backtrace_syms[i]);
318         result.push_back(simgrid::xbt::string_printf(
319           "?? at %s", backtrace_syms[i]));
320       }
321     }
322     addrs[i].clear();
323
324     /* Mask the bottom of the stack */
325     if (not strncmp("main", line_func, strlen("main")) ||
326         not strncmp("xbt_thread_context_wrapper", line_func, strlen("xbt_thread_context_wrapper")) ||
327         not strncmp("smx_ctx_sysv_wrapper", line_func, strlen("smx_ctx_sysv_wrapper")))
328       break;
329   }
330   pclose(pipe);
331   free(backtrace_syms);
332   return result;
333 }
334
335 }
336 }
337
338 #if SIMGRID_HAVE_MC
339 int xbt_libunwind_backtrace(void** bt, int size){
340   for (int i = 0; i < size; i++)
341     bt[i] = nullptr;
342
343   unw_cursor_t c;
344   unw_context_t uc;
345
346   unw_getcontext (&uc);
347   unw_init_local (&c, &uc);
348
349   unw_step(&c);
350
351   int i;
352   for (i = 0; unw_step(&c) >= 0 && i < size; i++) {
353     unw_word_t ip;
354     unw_get_reg(&c, UNW_REG_IP, &ip);
355     bt[i] = (void*)(long)ip;
356   }
357
358   return i;
359 }
360 #endif