Logo AND Algorithmique Numérique Distribuée

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