Logo AND Algorithmique Numérique Distribuée

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