Logo AND Algorithmique Numérique Distribuée

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