Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
106602136a1a9f5c84e70d4292b1eef93738b03b
[simgrid.git] / src / xbt / backtrace_linux.c
1 /* $Id: ex.c 5173 2008-01-07 22:10:52Z mquinson $ */
2
3 /* backtrace_linux - backtrace displaying on linux platform                 */
4 /* This file is included by ex.c on need (have execinfo.h, popen & addrline)*/
5
6 /*  Copyright (c) 2007 The SimGrid team                                     */
7 /*  All rights reserved.                                                    */
8
9 /* This program is free software; you can redistribute it and/or modify it
10  * under the terms of the license (GNU LGPL) which comes with this package. */
11
12 extern char **environ; /* the environment, as specified by the opengroup */
13
14 void xbt_ex_setup_backtrace(xbt_ex_t *e)  {
15   int i;
16   /* to get the backtrace from the libc */
17   char **backtrace_syms = backtrace_symbols (e->bt, e->used);
18   
19   /* To build the commandline of addr2line */
20   char *cmd, *curr;
21   
22   /* to extract the addresses from the backtrace */
23   char **addrs=xbt_new(char*,e->used);
24   char buff[256],*p;
25   
26   /* To read the output of addr2line */
27   FILE *pipe;
28   char line_func[1024],line_pos[1024];
29
30   /* size (in char) of pointers on this arch */
31   int addr_len=0;
32
33   /* To search for the right executable path when not trivial */
34   struct stat stat_buf;
35   char *binary_name = NULL;
36    
37   e->used     = backtrace((void**)e->bt,XBT_BACKTRACE_SIZE);
38   e->bt_strings = NULL;
39
40   /* Some arches only have stubs of backtrace, no implementation (hppa comes to mind) */
41   if (!e->used)
42      return;
43    
44   /* build the commandline */
45   if (stat(xbt_binary_name,&stat_buf)) {
46     /* Damn. binary not in current dir. We'll have to dig the PATH to find it */
47     int i;
48     for (i=0; environ[i]; i++) {
49       if (!strncmp("PATH=",environ[i], 5)) {    
50         xbt_dynar_t path=xbt_str_split(environ[i] + 5, ":");
51         unsigned int cpt;
52         char *data;
53         xbt_dynar_foreach(path, cpt, data) {
54           if (binary_name)
55             free(binary_name);
56           binary_name = bprintf("%s/%s",data,xbt_binary_name);
57           if (!stat(binary_name,&stat_buf)) {
58             /* Found. */
59             DEBUG1("Looked in the PATH for the binary. Found %s",binary_name);
60             xbt_dynar_free(&path);
61             break;
62           } 
63         }
64         if (stat(binary_name,&stat_buf)) {
65           /* not found */
66           e->used = 1;
67           e->bt_strings = xbt_new(char*,1);
68           e->bt_strings[0] = bprintf("(binary '%s' not found the path)",xbt_binary_name);
69           return;
70         }
71         xbt_dynar_free(&path);
72         break;
73       } 
74     }
75   } else {
76     binary_name = xbt_strdup(xbt_binary_name);
77   }      
78   cmd = curr = xbt_new(char,strlen(ADDR2LINE)+25+strlen(binary_name)+32*e->used);
79    
80   curr += sprintf(curr,"%s -f -e %s ",ADDR2LINE,binary_name);
81   free(binary_name);
82    
83   for (i=0; i<e->used;i++) {
84     /* retrieve this address */
85     DEBUG2("Retrieving address number %d from '%s'", i, backtrace_syms[i]);
86     snprintf(buff,256,"%s",strchr(backtrace_syms[i],'[')+1);
87     p=strchr(buff,']');
88     *p='\0';
89     if (strcmp(buff,"(nil)"))
90        addrs[i]=bprintf("%s", buff);
91     else
92        addrs[i]=bprintf("0x0");
93     DEBUG3("Set up a new address: %d, '%s'(%p)", i, addrs[i], addrs[i]);
94      
95     /* Add it to the command line args */
96     curr+=sprintf(curr,"%s ",addrs[i]);
97   } 
98   addr_len = strlen(addrs[0]);
99
100   /* parse the output and build a new backtrace */
101   e->bt_strings = xbt_new(char*,e->used);
102   
103   VERB1("Fire a first command: '%s'", cmd);
104   pipe = popen(cmd, "r");
105   if (!pipe) {
106     CRITICAL0("Cannot fork addr2line to display the backtrace");
107     abort();
108   }
109
110   for (i=0; i<e->used; i++) {
111     DEBUG2("Looking for symbol %d, addr = '%s'", i, addrs[i]); 
112     fgets(line_func,1024,pipe);
113     line_func[strlen(line_func)-1]='\0';
114     fgets(line_pos,1024,pipe);
115     line_pos[strlen(line_pos)-1]='\0';
116
117     if (strcmp("??",line_func)) {
118       DEBUG2("Found static symbol %s() at %s", line_func, line_pos);
119       e->bt_strings[i] = bprintf("**   In %s() at %s", line_func,line_pos);
120     } else {
121       /* Damn. The symbol is in a dynamic library. Let's get wild */
122       char *maps_name;
123       FILE *maps;
124       char maps_buff[512];
125
126       long int addr,offset=0;
127       char *p,*p2;
128
129       char *subcmd;
130       FILE *subpipe;
131       int found=0;
132
133       /* let's look for the offset of this library in our addressing space */
134       maps_name=bprintf("/proc/%d/maps",(int)getpid());
135       maps=fopen(maps_name,"r");
136
137       sscanf(addrs[i],"%lx",&addr);
138       sprintf(maps_buff,"%#lx",addr);
139       
140       if (strcmp(addrs[i],maps_buff)) {
141         CRITICAL2("Cannot parse backtrace address '%s' (addr=%#lx)",
142                   addrs[i], addr);
143       }
144       DEBUG2("addr=%s (as string) =%#lx (as number)",addrs[i],addr);
145
146       while (!found) {
147         long int first, last;
148         if (fgets(maps_buff,512,maps) == NULL) 
149           break;
150         if (i==0) {
151           maps_buff[strlen(maps_buff) -1]='\0';
152           DEBUG1("map line: %s", maps_buff);
153         }
154         sscanf(maps_buff,"%lx",&first);
155         p=strchr(maps_buff,'-')+1;
156         sscanf(p,"%lx",&last);
157         if (first < addr && addr < last) {
158           offset = first;
159           found=1;
160         }
161         if (found) {          
162            DEBUG3("%#lx in [%#lx-%#lx]", addr, first,last);
163            DEBUG0("Symbol found, map lines not further displayed (even if looking for next ones)");
164         }
165       }
166       fclose(maps);
167       free(maps_name);
168
169       if (!found) {
170         VERB0("Problem while reading the maps file. Following backtrace will be mangled.");
171         DEBUG1("No dynamic. Static symbol: %s", backtrace_syms[i]);
172         e->bt_strings[i] = bprintf("**   In ?? (%s)", backtrace_syms[i]);
173         continue;
174       }
175
176       /* Ok, Found the offset of the maps line containing the searched symbol. 
177          We now need to substract this from the address we got from backtrace.
178       */
179       
180       free(addrs[i]);
181       addrs[i] = bprintf("0x%0*lx",addr_len-2,addr-offset);
182       DEBUG2("offset=%#lx new addr=%s",offset,addrs[i]);
183
184       /* Got it. We have our new address. Let's get the library path and we 
185          are set */ 
186       p  = xbt_strdup(backtrace_syms[i]);
187       if (p[0]=='[') {
188          /* library path not displayed in the map file either... */
189          free(p);
190          sprintf(line_func,"??");
191       } else {
192          p2 = strrchr(p,'(');
193          if (p2) *p2= '\0';
194          p2 = strrchr(p,' ');
195          if(p2) *p2= '\0';
196       
197          /* Here we go, fire an addr2line up */
198          subcmd = bprintf("%s -f -e %s %s",ADDR2LINE,p, addrs[i]);
199          free(p);
200          VERB1("Fire a new command: '%s'",subcmd);
201          subpipe = popen(subcmd,"r");
202          if (!subpipe) {
203             CRITICAL0("Cannot fork addr2line to display the backtrace");
204             abort();
205          }
206          fgets(line_func,1024,subpipe);
207          line_func[strlen(line_func)-1]='\0';
208          fgets(line_pos,1024,subpipe);
209          line_pos[strlen(line_pos)-1]='\0';
210          pclose(subpipe);
211          free(subcmd);
212       }
213
214       /* check whether the trick worked */
215       if (strcmp("??",line_func)) {
216         DEBUG2("Found dynamic symbol %s() at %s", line_func, line_pos);
217         e->bt_strings[i] = bprintf("**   In %s() at %s", line_func,line_pos);
218       } else {
219         /* damn, nothing to do here. Let's print the raw address */
220         DEBUG1("Dynamic symbol not found. Raw address = %s", backtrace_syms[i]);
221         e->bt_strings[i] = bprintf("**   In ?? at %s", backtrace_syms[i]);
222       }
223       
224     }
225     free(addrs[i]);
226      
227     /* Mask the bottom of the stack */    
228     if (!strncmp("main",line_func,strlen("main")) ||
229         !strncmp("xbt_thread_context_wrapper",line_func,strlen("xbt_thread_context_wrapper"))) {
230        int j;
231        for (j=i+1; j<e->used; j++)
232          free(addrs[j]);
233        e->used = i;
234
235        if (!strncmp("xbt_thread_context_wrapper",line_func,strlen("xbt_thread_context_wrapper"))) {
236           e->used++;
237           e->bt_strings[i] = bprintf("**   (in a separate thread)");
238        }       
239     }
240      
241     
242   }
243   pclose(pipe);
244   free(addrs);
245   free(backtrace_syms);
246   free(cmd);
247 }