Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
backtrace: kill two unused functions
[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-2018. 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 <cerrno>
10 #include <cstring>
11 #include <fstream>
12 #include <sstream>
13 #include <string>
14 #include <vector>
15
16 #include <boost/algorithm/string.hpp>
17
18 #include <unistd.h>
19 #include <execinfo.h>
20 #include <sys/stat.h>
21
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>
25 #include "xbt/ex.h"
26 #include "xbt/log.h"
27 #include "xbt/module.h"         /* xbt_binary_name */
28 #include "src/xbt_modinter.h"       /* backtrace initialization headers */
29 /* end of "useless" inclusions */
30
31 size_t xbt_backtrace_current(xbt_backtrace_location_t* loc, std::size_t count)
32 {
33   std::size_t used = backtrace(loc, count);
34   if (used == 0) {
35     std::fprintf(stderr, "The backtrace() function failed, which probably means that the memory is exhausted\n.");
36     std::fprintf(stderr, "Bailing out now since there is nothing I can do without a decent amount of memory\n.");
37     std::fprintf(stderr, "Please go fix the memleaks\n");
38     std::exit(1);
39   }
40   return used;
41 }
42
43 namespace simgrid {
44 namespace xbt {
45
46 /** Find the path of the binary file from the name found in argv */
47 static std::string get_binary_path()
48 {
49   struct stat stat_buf;
50
51   if (xbt_binary_name == nullptr)
52     return "";
53
54   // We found it, we are happy:
55   if (stat(xbt_binary_name, &stat_buf) == 0)
56     return xbt_binary_name;
57
58   // Not found, look in the PATH:
59   char* path = getenv("PATH");
60   if (path == nullptr)
61     return "";
62   XBT_DEBUG("Looking in the PATH: %s\n", path);
63   std::vector<std::string> path_list;
64   // TODO, on Windows, this is ";"
65   boost::split(path_list, path, boost::is_any_of(":"));
66   for (std::string const& path_item : path_list) {
67     std::string binary_name = simgrid::xbt::string_printf(
68       "%s/%s", path_item.c_str(), xbt_binary_name);
69     bool found = (stat(binary_name.c_str(), &stat_buf) == 0);
70     XBT_DEBUG("Looked in the PATH for the binary. %s %s",
71       found ? "Found" : "Not found",
72       binary_name.c_str());
73     if (found)
74       return binary_name;
75   }
76
77   // Not found at all:
78   return "";
79 }
80
81 //FIXME: This code could be greatly improved/simplifyied with
82 //   http://cairo.sourcearchive.com/documentation/1.9.4/backtrace-symbols_8c-source.html
83 std::vector<std::string> resolve_backtrace(xbt_backtrace_location_t const* loc, std::size_t count)
84 {
85   std::vector<std::string> result;
86
87   if (count == 0)
88     return result;
89
90   if (xbt_binary_name == nullptr)
91     XBT_WARN("XBT not initialized, the backtrace will not be resolved.");
92
93   // Drop the first one:
94   loc++; count--;
95
96   char** backtrace_syms = backtrace_symbols(loc, count);
97   std::string binary_name = get_binary_path();
98
99   if (binary_name.empty()) {
100     for (std::size_t i = 0; i < count; i++)
101       result.push_back(simgrid::xbt::string_printf("%p", loc[i]));
102     return result;
103   }
104
105   // Create the system command for add2line:
106   std::ostringstream stream;
107   stream << ADDR2LINE << " -f -e " << binary_name << ' ';
108   std::vector<std::string> addrs(count);
109   for (std::size_t i = 0; i < count; i++) {
110     /* retrieve this address */
111     XBT_DEBUG("Retrieving address number %zu from '%s'", i, backtrace_syms[i]);
112     char buff[256];
113     snprintf(buff, 256, "%s", strchr(backtrace_syms[i], '[') + 1);
114     char* p = strchr(buff, ']');
115     *p = '\0';
116     if (strcmp(buff, "(nil)"))
117       addrs[i] = buff;
118     else
119       addrs[i] = "0x0";
120     XBT_DEBUG("Set up a new address: %zu, '%s'", i, addrs[i].c_str());
121     /* Add it to the command line args */
122     stream << addrs[i] << ' ';
123   }
124   std::string cmd = stream.str();
125
126   /* size (in char) of pointers on this arch */
127   int addr_len = addrs[0].size();
128
129   XBT_VERB("Fire a first command: '%s'", cmd.c_str());
130   FILE* pipe = popen(cmd.c_str(), "r");
131   xbt_assert(pipe, "Cannot fork addr2line to display the backtrace");
132
133   /* To read the output of addr2line */
134   char line_func[1024];
135   char line_pos[1024];
136   for (std::size_t i = 0; i < count; i++) {
137     XBT_DEBUG("Looking for symbol %zu, addr = '%s'", i, addrs[i].c_str());
138     if (fgets(line_func, 1024, pipe)) {
139       line_func[strlen(line_func) - 1] = '\0';
140     } else {
141       XBT_VERB("Cannot run fgets to look for symbol %zu, addr %s", i, addrs[i].c_str());
142       strncpy(line_func, "???", 4);
143     }
144     if (fgets(line_pos, 1024, pipe)) {
145       line_pos[strlen(line_pos) - 1] = '\0';
146     } else {
147       XBT_VERB("Cannot run fgets to look for symbol %zu, addr %s", i, addrs[i].c_str());
148       strncpy(line_pos, backtrace_syms[i],1024);
149     }
150
151     if (strcmp("??", line_func) != 0) {
152       auto name = simgrid::xbt::demangle(line_func);
153       XBT_DEBUG("Found static symbol %s at %s", name.get(), line_pos);
154       result.push_back(simgrid::xbt::string_printf(
155         "%s at %s, %p", name.get(), line_pos, loc[i]
156       ));
157     } else {
158       /* Damn. The symbol is in a dynamic library. Let's get wild */
159
160       unsigned long int offset = 0;
161       int found = 0;
162
163       /* let's look for the offset of this library in our addressing space */
164       std::string maps_name = std::string("/proc/") + std::to_string(getpid()) + "/maps";
165       std::ifstream maps(maps_name);
166       if (not maps) {
167         XBT_CRITICAL("open(\"%s\") failed: %s", maps_name.c_str(), strerror(errno));
168         continue;
169       }
170       size_t pos;
171       unsigned long int addr = std::stoul(addrs[i], &pos, 16);
172       if (pos != addrs[i].length()) {
173         XBT_CRITICAL("Cannot parse backtrace address '%s' (addr=%#lx)", addrs[i].c_str(), addr);
174       }
175       XBT_DEBUG("addr=%s (as string) =%#lx (as number)", addrs[i].c_str(), addr);
176
177       while (not found) {
178         unsigned long int first;
179         unsigned long int last;
180
181         std::string maps_buff;
182         if (not std::getline(maps, maps_buff))
183           break;
184         if (i == 0) {
185           XBT_DEBUG("map line: %s", maps_buff.c_str());
186         }
187         first = std::stoul(maps_buff, &pos, 16);
188         maps_buff.erase(0, pos + 1);
189         last = std::stoul(maps_buff, nullptr, 16);
190         if (first < addr && addr < last) {
191           offset = first;
192           found = 1;
193         }
194         if (found) {
195           XBT_DEBUG("%#lx in [%#lx-%#lx]", addr, first, last);
196           XBT_DEBUG("Symbol found, map lines not further displayed (even if looking for next ones)");
197         }
198       }
199       maps.close();
200       addrs[i].clear();
201
202       if (not found) {
203         XBT_VERB("Problem while reading the maps file. Following backtrace will be mangled.");
204         XBT_DEBUG("No dynamic. Static symbol: %s", backtrace_syms[i]);
205         result.push_back(simgrid::xbt::string_printf("?? (%s)", backtrace_syms[i]));
206         continue;
207       }
208
209       /* Ok, Found the offset of the maps line containing the searched symbol.
210          We now need to substract this from the address we got from backtrace.
211        */
212
213       addrs[i] = simgrid::xbt::string_printf("0x%0*lx", addr_len - 2, addr - offset);
214       XBT_DEBUG("offset=%#lx new addr=%s", offset, addrs[i].c_str());
215
216       /* Got it. We have our new address. Let's get the library path and we are set */
217       std::string p(backtrace_syms[i]);
218       if (p[0] == '[') {
219         /* library path not displayed in the map file either... */
220         snprintf(line_func, 3, "??");
221       } else {
222         size_t p2 = p.find_first_of("( ");
223         if (p2 != std::string::npos)
224           p.erase(p2);
225
226         /* Here we go, fire an addr2line up */
227         std::string subcmd = std::string(ADDR2LINE) + " -f -e " + p + " " + addrs[i];
228         XBT_VERB("Fire another command: '%s'", subcmd.c_str());
229         FILE* subpipe = popen(subcmd.c_str(), "r");
230         if (not subpipe) {
231           xbt_die("Cannot fork addr2line to display the backtrace");
232         }
233         if (fgets(line_func, 1024, subpipe)) {
234           line_func[strlen(line_func) - 1] = '\0';
235         } else {
236           XBT_VERB("Cannot read result of subcommand %s", subcmd.c_str());
237           strncpy(line_func, "???", 4);
238         }
239         if (fgets(line_pos, 1024, subpipe)) {
240           line_pos[strlen(line_pos) - 1] = '\0';
241         } else {
242           XBT_VERB("Cannot read result of subcommand %s", subcmd.c_str());
243           strncpy(line_pos, backtrace_syms[i],1024);
244         }
245         pclose(subpipe);
246       }
247
248       /* check whether the trick worked */
249       if (strcmp("??", line_func)) {
250         auto name = simgrid::xbt::demangle(line_func);
251         XBT_DEBUG("Found dynamic symbol %s at %s", name.get(), line_pos);
252         result.push_back(simgrid::xbt::string_printf(
253           "%s at %s, %p", name.get(), line_pos, loc[i]));
254       } else {
255         /* damn, nothing to do here. Let's print the raw address */
256         XBT_DEBUG("Dynamic symbol not found. Raw address = %s", backtrace_syms[i]);
257         result.push_back(simgrid::xbt::string_printf(
258           "?? at %s", backtrace_syms[i]));
259       }
260     }
261     addrs[i].clear();
262
263     /* Mask the bottom of the stack */
264     const char* const breakers[] = {
265         "main",
266         "_ZN7simgrid6kernel7context13ThreadContext7wrapperE", // simgrid::kernel::context::ThreadContext::wrapper
267         "_ZN7simgrid6kernel7context8UContext7wrapperE"        // simgrid::kernel::context::UContext::wrapper
268     };
269     bool do_break = false;
270     for (const char* b : breakers) {
271       if (strncmp(b, line_func, strlen(b)) == 0) {
272         do_break = true;
273         break;
274       }
275     }
276     if (do_break)
277       break;
278   }
279   pclose(pipe);
280   free(backtrace_syms);
281   return result;
282 }
283
284 }
285 }