Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Reserve more room for writing pointer addresses to make it work on large architecture...
[simgrid.git] / src / xbt / ex.c
1 /* $Id$ */
2
3 /* ex - Exception Handling (modified to fit into SimGrid from OSSP version) */
4
5 /*  Copyright (c) 2005-2006 Martin Quinson                                  */
6 /*  Copyright (c) 2002-2004 Ralf S. Engelschall <rse@engelschall.com>       */
7 /*  Copyright (c) 2002-2004 The OSSP Project <http://www.ossp.org/>         */
8 /*  Copyright (c) 2002-2004 Cable & Wireless <http://www.cw.com/>           */
9 /*  All rights reserved.                                                    */
10
11 /* This program is free software; you can redistribute it and/or modify it
12  * under the terms of the license (GNU LGPL) which comes with this package. */
13
14 #include <stdio.h>
15 #include <stdlib.h>
16
17 #include "portable.h" /* execinfo when available */
18 #include "xbt/ex.h"
19 #include "xbt/module.h" /* xbt_binary_name */
20 #include "xbt/ex_interface.h"
21
22 #include "gras/Virtu/virtu_interface.h" /* gras_os_myname */
23
24 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_ex,xbt,"Exception mecanism");
25
26
27 /* default __ex_ctx callback function */
28 ex_ctx_t *__xbt_ex_ctx_default(void) {
29     static ex_ctx_t ctx = XBT_CTX_INITIALIZER;
30
31     return &ctx;
32 }
33
34
35 /** \brief show the backtrace of the current point (lovely while debuging) */
36 void xbt_backtrace_display(void) {
37 #if defined(HAVE_EXECINFO_H) && defined(HAVE_POPEN) && defined(ADDR2LINE)
38   xbt_ex_t e;
39   int i;
40
41   e.used     = backtrace((void**)e.bt,XBT_BACKTRACE_SIZE);
42   e.bt_strings = NULL;
43   xbt_ex_setup_backtrace(&e);
44   for (i=1; i<e.used; i++) /* no need to display "xbt_display_backtrace" */
45     fprintf(stderr,"%s\n",e.bt_strings[i]);
46
47   e.msg=NULL;
48   e.remote=0;
49   xbt_ex_free(e);
50 #else 
51   ERROR0("No backtrace on this arch");
52 #endif
53 }
54
55
56 void xbt_ex_setup_backtrace(xbt_ex_t *e)  {
57 #if defined(HAVE_EXECINFO_H) && defined(HAVE_POPEN) && defined(ADDR2LINE)
58   int i;
59   /* to get the backtrace from the libc */
60   char **backtrace = backtrace_symbols (e->bt, e->used);
61   
62   /* To build the commandline of addr2line */
63   char *cmd = xbt_new(char,strlen(ADDR2LINE)+25+strlen(xbt_binary_name)+32*e->used);
64   char *curr=cmd;
65   
66   /* to extract the addresses from the backtrace */
67   char **addrs=xbt_new(char*,e->used);
68   char buff[256],*p;
69   
70   /* To read the output of addr2line */
71   FILE *pipe;
72   char line_func[1024],line_pos[1024];
73
74   /* size (in char) of pointers on this arch */
75   int addr_len=0;
76
77   /* Some arches only have stubs of backtrace, no implementation (hppa comes to mind) */
78   if (!e->used)
79      return;
80    
81   /* build the commandline */
82   curr += sprintf(curr,"%s -f -e %s ",ADDR2LINE,xbt_binary_name);
83   for (i=0; i<e->used;i++) {
84     /* retrieve this address */
85     DEBUG2("Retrieving address number %d from '%s'", i, backtrace[i]);
86     snprintf(buff,256,"%s",strchr(backtrace[i],'[')+1);
87     p=strchr(buff,']');
88     *p='\0';
89     addrs[i]=bprintf("%s", buff);
90     DEBUG3("Set up a new address: %d, '%s'(%p)", i, addrs[i], addrs[i]);
91      
92     /* Add it to the command line args */
93     curr+=sprintf(curr,"%s ",addrs[i]);
94   }      
95   addr_len = strlen(addrs[0]);
96
97   /* parse the output and build a new backtrace */
98   e->bt_strings = xbt_new(char*,e->used);
99   
100   VERB1("Fire a first command: '%s'", cmd);
101   pipe = popen(cmd, "r");
102   if (!pipe) {
103     CRITICAL0("Cannot fork addr2line to display the backtrace");
104     abort();
105   }
106
107   for (i=0; i<e->used; i++) {
108     DEBUG2("Looking for symbol %d, addr = '%s'", i, addrs[i]); 
109     fgets(line_func,1024,pipe);
110     line_func[strlen(line_func)-1]='\0';
111     fgets(line_pos,1024,pipe);
112     line_pos[strlen(line_pos)-1]='\0';
113
114     if (strcmp("??",line_func)) {
115        DEBUG2("Found static symbol %s() at %s", line_func, line_pos);
116       e->bt_strings[i] = bprintf("**   In %s() at %s (static symbol)", line_func,line_pos);
117     } else {
118       /* Damn. The symbol is in a dynamic library. Let's get wild */
119       char *maps_name;
120       FILE *maps;
121       char maps_buff[512];
122
123       long int addr,offset=0;
124       char *p,*p2;
125
126       char *subcmd;
127       FILE *subpipe;
128       int found=0;
129
130       /* let's look for the offset of this library in our addressing space */
131       maps_name=bprintf("/proc/%d/maps",(int)getpid());
132       maps=fopen(maps_name,"r");
133
134       sscanf(addrs[i],"%lx",&addr);
135       sprintf(maps_buff,"%#lx",addr);
136       
137       if (strcmp(addrs[i],maps_buff)) {
138         CRITICAL2("Cannot parse backtrace address '%s' (addr=%#lx)",
139                   addrs[i], addr);
140       }
141       DEBUG2("addr=%s (as string) =%#lx (as number)",addrs[i],addr);
142
143       while (!found) {
144         long int first, last;
145         if (fgets(maps_buff,512,maps) == NULL) 
146           break;
147         if (i==0) {
148           maps_buff[strlen(maps_buff) -1]='\0';
149           DEBUG1("map line: %s", maps_buff);
150         }
151         sscanf(maps_buff,"%lx",&first);
152         p=strchr(maps_buff,'-')+1;
153         sscanf(p,"%lx",&last);
154         if (first < addr && addr < last) {
155           offset = first;
156           found=1;
157         }
158         DEBUG4("%#lx %s [%#lx-%#lx]",
159                addr, found? "in":"out of",first,last);
160       }
161       fclose(maps);
162       free(maps_name);
163
164       if (!found) {
165         VERB0("Problem while reading the maps file. Following backtrace will be mangled.");
166         DEBUG1("No dynamic. Static symbol: %s", backtrace[i]);
167         e->bt_strings[i] = bprintf("**   In ?? (%s)", backtrace[i]);
168         continue;
169       }
170
171       /* Ok, Found the offset of the maps line containing the searched symbol. 
172          We now need to substract this from the address we got from backtrace.
173       */
174       
175       free(addrs[i]);
176       addrs[i] = bprintf("0x%0*lx",addr_len-2,addr-offset);
177       DEBUG2("offset=%#lx new addr=%s",offset,addrs[i]);
178
179       /* Got it. We have our new address. Let's get the library path and we 
180          are set */ 
181       p  = xbt_strdup(backtrace[i]);
182       p2 = strrchr(p,'(');
183       if (p2) { 
184          *p2= '\0';
185       } else { 
186          p2 = strrchr(p,' ');
187          if(p2 == NULL) 
188            {
189              ERROR1("Couldn't parse %s to get the library path", backtrace[i]);
190              xbt_abort();
191            }
192          
193          *p2= '\0';
194       }
195       
196       /* Here we go, fire an addr2line up */
197       subcmd = bprintf("%s -f -e %s %s",ADDR2LINE,p, addrs[i]);
198       free(p);
199       VERB1("Fire a new command: '%s'",subcmd);
200       subpipe = popen(subcmd,"r");
201       if (!subpipe) {
202         CRITICAL0("Cannot fork addr2line to display the backtrace");
203         abort();
204       }
205       fgets(line_func,1024,subpipe);
206       line_func[strlen(line_func)-1]='\0';
207       fgets(line_pos,1024,subpipe);
208       line_pos[strlen(line_pos)-1]='\0';
209       pclose(subpipe);
210       free(subcmd);
211
212       /* check whether the trick worked */
213       if (strcmp("??",line_func)) {
214         DEBUG2("Found dynamic symbol %s() at %s", line_func, line_pos);
215         e->bt_strings[i] = bprintf("**   In %s() at %s (dynamic symbol)", line_func,line_pos);
216       } else {
217         /* damn, nothing to do here. Let's print the raw address */
218         DEBUG1("Dynamic symbol not found. Raw address = %s", backtrace[i]);
219         e->bt_strings[i] = bprintf("**   In ?? (%s)", backtrace[i]);
220       }
221     }
222     free(addrs[i]);
223   }
224   pclose(pipe);
225   free(addrs);
226   free(backtrace);
227   free(cmd);
228 #endif
229 }    
230
231 /** @brief shows an exception content and the associated stack if available */
232 void xbt_ex_display(xbt_ex_t *e)  {
233   char *thrower=NULL;
234
235   if (e->remote)
236     bprintf(" on host %s(%ld)",e->host,e->pid);
237
238   CRITICAL1("%s",e->msg);
239   fprintf(stderr,
240           "** SimGrid: UNCAUGHT EXCEPTION received on %s(%ld): category: %s; value: %d\n"
241           "** %s\n"
242           "** Thrown by %s()%s\n",
243           gras_os_myname(),gras_os_getpid(),
244           xbt_ex_catname(e->category), e->value, e->msg,
245           e->procname,thrower?thrower:" in this process");
246
247   if (thrower)
248     free(thrower);
249
250   if (!e->remote && !e->bt_strings)
251     xbt_ex_setup_backtrace(e);
252
253 #if defined(HAVE_EXECINFO_H) && defined(HAVE_POPEN) && defined(ADDR2LINE)
254   /* We have everything to build neat backtraces */
255   {
256     int i;
257     
258     fprintf(stderr,"\n");
259     for (i=0; i<e->used; i++)
260       fprintf(stderr,"%s\n",e->bt_strings[i]);
261     
262   }
263 #else
264   fprintf(stderr," at %s:%d:%s (no backtrace available on that arch)\n",  
265           e->file,e->line,e->func);
266 #endif
267   xbt_ex_free(*e);
268 }
269
270
271 /* default __ex_terminate callback function */
272 void __xbt_ex_terminate_default(xbt_ex_t *e)  {
273   xbt_ex_display(e);
274
275   abort();
276 }
277
278 /* the externally visible API */
279 ex_ctx_cb_t  __xbt_ex_ctx       = &__xbt_ex_ctx_default;
280 ex_term_cb_t __xbt_ex_terminate = &__xbt_ex_terminate_default;
281
282 void xbt_ex_free(xbt_ex_t e) {
283   int i;
284
285   if (e.msg) free(e.msg);
286   if (e.remote) {
287     free(e.procname);
288     free(e.file);
289     free(e.func);
290     free(e.host);
291   }
292
293   if (e.bt_strings) {   
294      for (i=0; i<e.used; i++) 
295        free((char*)e.bt_strings[i]);
296      free((char **)e.bt_strings);
297   }
298   /* memset(e,0,sizeof(xbt_ex_t)); */
299 }
300
301 /** \brief returns a short name for the given exception category */
302 const char * xbt_ex_catname(xbt_errcat_t cat) {
303   switch (cat) {
304   case unknown_error:   return  "unknown_err";
305   case arg_error:       return "invalid_arg";
306   case mismatch_error:  return "mismatch";
307   case not_found_error: return "not found";
308   case system_error:    return "system_err";
309   case network_error:   return "network_err";
310   case timeout_error:   return "timeout";
311   case thread_error:    return "thread_err";
312   default:              return "INVALID_ERR";
313   }
314 }
315
316 #ifndef HAVE_EXECINFO_H
317 /* dummy implementation. We won't use the result, but ex.h needs it to be defined */
318 int backtrace (void **__array, int __size) {
319   return 0;
320 }
321
322 #endif
323
324 #ifdef SIMGRID_TEST
325 #include "xbt/ex.h"
326
327 XBT_TEST_SUITE("xbt_ex","Exception Handling");
328
329 XBT_TEST_UNIT("controlflow",test_controlflow, "basic nested control flow") {
330     xbt_ex_t ex;
331     volatile int n=1;
332
333     xbt_test_add0("basic nested control flow");
334
335     TRY {
336         if (n != 1)
337             xbt_test_fail1("M1: n=%d (!= 1)", n);
338         n++;
339         TRY {
340             if (n != 2)
341                 xbt_test_fail1("M2: n=%d (!= 2)", n);
342             n++;
343             THROW0(unknown_error,0,"something");
344         } CATCH (ex) {
345             if (n != 3)
346                 xbt_test_fail1("M3: n=%d (!= 3)", n);
347             n++;
348             xbt_ex_free(ex);
349         }
350         n++;
351         TRY {
352             if (n != 5)
353                 xbt_test_fail1("M2: n=%d (!= 5)", n);
354             n++;
355             THROW0(unknown_error,0,"something");
356         } CATCH (ex) {
357             if (n != 6)
358                 xbt_test_fail1("M3: n=%d (!= 6)", n);
359             n++;
360             RETHROW;
361             n++;
362         }
363         xbt_test_fail1("MX: n=%d (shouldn't reach this point)", n);
364     }
365     CATCH(ex) {
366         if (n != 7)
367             xbt_test_fail1("M4: n=%d (!= 7)", n);
368         n++;
369         xbt_ex_free(ex);
370     }
371     if (n != 8)
372         xbt_test_fail1("M5: n=%d (!= 8)", n);
373 }
374
375 XBT_TEST_UNIT("value",test_value,"exception value passing") {
376     xbt_ex_t ex;
377
378     TRY {
379         THROW0(unknown_error, 2, "toto");
380     } CATCH(ex) {
381         xbt_test_add0("exception value passing");
382         if (ex.category != unknown_error)
383             xbt_test_fail1("category=%d (!= 1)", ex.category);
384         if (ex.value != 2)
385             xbt_test_fail1("value=%d (!= 2)", ex.value);
386         if (strcmp(ex.msg,"toto"))
387             xbt_test_fail1("message=%s (!= toto)", ex.msg);
388         xbt_ex_free(ex);
389     }
390 }
391
392 XBT_TEST_UNIT("variables",test_variables,"variable value preservation") {
393     xbt_ex_t ex;
394     int r1, r2;
395     volatile int v1, v2;
396
397     r1 = r2 = v1 = v2 = 1234;
398     TRY {
399         r2 = 5678;
400         v2 = 5678;
401         THROW0(unknown_error, 0, "toto");
402     } CATCH(ex) {
403         xbt_test_add0("variable preservation");
404         if (r1 != 1234)
405             xbt_test_fail1("r1=%d (!= 1234)", r1);
406         if (v1 != 1234)
407             xbt_test_fail1("v1=%d (!= 1234)", v1);
408         /* r2 is allowed to be destroyed because not volatile */
409         if (v2 != 5678)
410             xbt_test_fail1("v2=%d (!= 5678)", v2);
411         xbt_ex_free(ex);
412     }
413 }
414
415 XBT_TEST_UNIT("cleanup",test_cleanup,"cleanup handling") {
416     xbt_ex_t ex;
417     volatile int v1;
418     int c;
419
420     xbt_test_add0("cleanup handling");
421
422     v1 = 1234;
423     c = 0;
424     TRY {
425         v1 = 5678;
426         THROW0(1, 2, "blah");
427     } CLEANUP {
428         if (v1 != 5678)
429             xbt_test_fail1("v1 = %d (!= 5678)", v1);
430         c = 1;
431     } CATCH(ex) {
432         if (v1 != 5678)
433             xbt_test_fail1("v1 = %d (!= 5678)", v1);
434         if (!(ex.category == 1 && ex.value == 2 && !strcmp(ex.msg,"blah")))
435             xbt_test_fail0("unexpected exception contents");
436         xbt_ex_free(ex);
437     }
438     if (!c)
439         xbt_test_fail0("xbt_ex_free not executed");
440 }
441
442
443 /*
444  * The following is the example included in the documentation. It's a good 
445  * idea to check its syntax even if we don't try to run it.
446  * And actually, it allows to put comments in the code despite doxygen.
447  */ 
448 static char *mallocex(int size) {
449   return NULL;
450 }
451 #define SMALLAMOUNT 10
452 #define TOOBIG 100000000
453
454 #if 0 /* this contains syntax errors, actually */
455 static void bad_example(void) {
456   struct {char*first;} *globalcontext;
457   ex_t ex;
458
459   /* BAD_EXAMPLE */
460   TRY {
461     char *cp1, *cp2, *cp3;
462     
463     cp1 = mallocex(SMALLAMOUNT);
464     globalcontext->first = cp1;
465     cp2 = mallocex(TOOBIG);
466     cp3 = mallocex(SMALLAMOUNT);
467     strcpy(cp1, "foo");
468     strcpy(cp2, "bar");
469   } CLEANUP {
470     if (cp3 != NULL) free(cp3);
471     if (cp2 != NULL) free(cp2);
472     if (cp1 != NULL) free(cp1);
473   } CATCH(ex) {
474     printf("cp3=%s", cp3);
475     RETHROW;
476   }
477   /* end_of_bad_example */
478 }
479 #endif
480 typedef struct {char *first;} global_context_t;
481    
482 static void good_example(void) {
483   global_context_t *global_context=malloc(sizeof(global_context_t));
484   xbt_ex_t ex;
485
486   /* GOOD_EXAMPLE */
487   { /*01*/
488     char * volatile /*03*/ cp1 = NULL /*02*/;
489     char * volatile /*03*/ cp2 = NULL /*02*/;
490     char * volatile /*03*/ cp3 = NULL /*02*/;
491     TRY {
492       cp1 = mallocex(SMALLAMOUNT);
493       global_context->first = cp1;
494       cp1 = NULL /*05 give away*/;
495       cp2 = mallocex(TOOBIG);
496       cp3 = mallocex(SMALLAMOUNT);
497       strcpy(cp1, "foo");
498       strcpy(cp2, "bar");
499     } CLEANUP { /*04*/
500       printf("cp3=%s", cp3 == NULL /*02*/ ? "" : cp3);
501       if (cp3 != NULL)
502         free(cp3);
503       if (cp2 != NULL)
504         free(cp2);
505       /*05 cp1 was given away */
506     } CATCH(ex) {
507       /*05 global context untouched */
508       RETHROW;
509     }
510   }
511   /* end_of_good_example */
512 }
513 #endif /* SIMGRID_TEST */