Logo AND Algorithmique Numérique Distribuée

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