Logo AND Algorithmique Numérique Distribuée

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