Logo AND Algorithmique Numérique Distribuée

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