Logo AND Algorithmique Numérique Distribuée

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