Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
New function: xbt_display_backtrace(). Sweet while debugging
[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=0; i<e.used; i++)
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   /* build the commandline */
89   curr += sprintf(curr,"%s -f -e %s ",ADDR2LINE,xbt_binary_name);
90   for (i=0; i<e->used;i++) {
91     /* retrieve this address */
92     snprintf(buff,256,"%s",strchr(backtrace[i],'[')+1);
93     p=strchr(buff,']');
94     *p='\0';
95     addrs[i]=bprintf("%s",buff);
96     
97     /* Add it to the command line args */
98     curr+=sprintf(curr,"%s ",addrs[i]);
99   }      
100   
101   /* parse the output and build a new backtrace */
102   e->bt_strings = xbt_new(char*,e->used);
103   
104   pipe = popen(cmd, "r");
105   //     xbt_assert(pipe);//,"Cannot fork addr2line to display the backtrace");
106   for (i=0; i<e->used; i++) {
107     fgets(line_func,1024,pipe);
108     line_func[strlen(line_func)-1]='\0';
109     fgets(line_pos,1024,pipe);
110     line_pos[strlen(line_pos)-1]='\0';
111
112     if (strcmp("??",line_func)) {
113       e->bt_strings[i] = bprintf("**   At %s: %s (%s)", addrs[i], line_func,line_pos);
114     } else {
115       char *p=bprintf("%s",backtrace[i]);
116       char *pos=strrchr(p,' ');
117       *pos = '\0';
118       e->bt_strings[i] = bprintf("**   At %s: ?? (%s)", addrs[i], p);
119       free(p);
120     }
121     free(addrs[i]);
122   }
123   free(addrs);
124   free(backtrace);
125   free(cmd);
126 #endif
127 }    
128
129 /** @brief shows an exception content and the associated stack if available */
130 void xbt_ex_display(xbt_ex_t *e)  {
131
132   fprintf(stderr,
133           "** SimGrid: UNCAUGHT EXCEPTION on %s: category: %s; value: %d\n"
134           "** %s\n"
135           "** Thrown by %s%s%s",
136           gras_os_myname(),
137           xbt_ex_catname(e->category), e->value, e->msg,
138           e->procname, (e->host?"@":""),(e->host?e->host:""));
139
140   if (!e->remote && !e->bt_strings)
141     xbt_ex_setup_backtrace(e);
142
143 #if defined(HAVE_EXECINFO_H) && defined(HAVE_POPEN) && defined(ADDR2LINE)
144   /* We have everything to build neat backtraces */
145   {
146     int i;
147     
148     fprintf(stderr,"\n");
149     for (i=0; i<e->used; i++)
150       fprintf(stderr,"%s\n",e->bt_strings[i]);
151     
152   }
153 #else
154   fprintf(stderr," at %s:%d:%s (no backtrace available on that arch)\n",  
155           e->file,e->line,e->func);
156 #endif
157   xbt_ex_free(e);
158 }
159
160
161 /* default __ex_terminate callback function */
162 void __xbt_ex_terminate_default(xbt_ex_t *e)  {
163   xbt_ex_display(e);
164
165   abort();
166 }
167
168 /* the externally visible API */
169 ex_ctx_cb_t  __xbt_ex_ctx       = &__xbt_ex_ctx_default;
170 ex_term_cb_t __xbt_ex_terminate = &__xbt_ex_terminate_default;
171
172 void xbt_ex_free(xbt_ex_t *e) {
173   int i;
174
175   if (e->msg) free(e->msg);
176   if (e->remote) {
177     free(e->procname);
178     free(e->file);
179     free(e->func);
180     free(e->host);
181   }
182
183   if (e->bt_strings) {  
184      for (i=0; i<e->used; i++) 
185        free((char*)e->bt_strings[i]);
186      free((char **)e->bt_strings);
187   }
188   memset(e,0,sizeof(xbt_ex_t));
189 }
190
191 /** \brief returns a short name for the given exception category */
192 const char * xbt_ex_catname(xbt_errcat_t cat) {
193   switch (cat) {
194   case unknown_error:   return  "unknown_err";
195   case arg_error:       return "invalid_arg";
196   case mismatch_error:  return "mismatch";
197   case not_found_error: return "not found";
198   case system_error:    return "system_err";
199   case network_error:   return "network_err";
200   case timeout_error:   return "timeout";
201   case thread_error:    return "thread_err";
202   default:              return "INVALID_ERR";
203   }
204 }
205
206 #ifndef HAVE_EXECINFO_H
207 /* dummy implementation. We won't use the result, but ex.h needs it to be defined */
208 int backtrace (void **__array, int __size) {
209   return 0;
210 }
211
212 #endif
213
214 #ifdef SIMGRID_TEST
215 #include "xbt/ex.h"
216
217 XBT_TEST_SUITE("xbt_ex","Exception Handling");
218
219 XBT_TEST_UNIT("controlflow",test_controlflow, "basic nested control flow") {
220     xbt_ex_t ex;
221     volatile int n=1;
222
223     xbt_test_add0("basic nested control flow");
224
225     TRY {
226         if (n != 1)
227             xbt_test_fail1("M1: n=%d (!= 1)", n);
228         n++;
229         TRY {
230             if (n != 2)
231                 xbt_test_fail1("M2: n=%d (!= 2)", n);
232             n++;
233             THROW0(unknown_error,0,"something");
234         } CATCH (ex) {
235             if (n != 3)
236                 xbt_test_fail1("M3: n=%d (!= 3)", n);
237             n++;
238             xbt_ex_free(&ex);
239         }
240         n++;
241         TRY {
242             if (n != 5)
243                 xbt_test_fail1("M2: n=%d (!= 5)", n);
244             n++;
245             THROW0(unknown_error,0,"something");
246         } CATCH (ex) {
247             if (n != 6)
248                 xbt_test_fail1("M3: n=%d (!= 6)", n);
249             n++;
250             RETHROW;
251             n++;
252         }
253         xbt_test_fail1("MX: n=%d (shouldn't reach this point)", n);
254     }
255     CATCH(ex) {
256         if (n != 7)
257             xbt_test_fail1("M4: n=%d (!= 7)", n);
258         n++;
259         xbt_ex_free(&ex);
260     }
261     if (n != 8)
262         xbt_test_fail1("M5: n=%d (!= 8)", n);
263 }
264
265 XBT_TEST_UNIT("value",test_value,"exception value passing") {
266     xbt_ex_t ex;
267
268     TRY {
269         THROW0(unknown_error, 2, "toto");
270     } CATCH(ex) {
271         xbt_test_add0("exception value passing");
272         if (ex.category != unknown_error)
273             xbt_test_fail1("category=%d (!= 1)", ex.category);
274         if (ex.value != 2)
275             xbt_test_fail1("value=%d (!= 2)", ex.value);
276         if (strcmp(ex.msg,"toto"))
277             xbt_test_fail1("message=%s (!= toto)", ex.msg);
278         xbt_ex_free(&ex);
279     }
280 }
281
282 XBT_TEST_UNIT("variables",test_variables,"variable value preservation") {
283     xbt_ex_t ex;
284     int r1, r2;
285     volatile int v1, v2;
286
287     r1 = r2 = v1 = v2 = 1234;
288     TRY {
289         r2 = 5678;
290         v2 = 5678;
291         THROW0(unknown_error, 0, "toto");
292     } CATCH(ex) {
293         xbt_test_add0("variable preservation");
294         if (r1 != 1234)
295             xbt_test_fail1("r1=%d (!= 1234)", r1);
296         if (v1 != 1234)
297             xbt_test_fail1("v1=%d (!= 1234)", v1);
298         /* r2 is allowed to be destroyed because not volatile */
299         if (v2 != 5678)
300             xbt_test_fail1("v2=%d (!= 5678)", v2);
301         xbt_ex_free(&ex);
302     }
303 }
304
305 XBT_TEST_UNIT("cleanup",test_cleanup,"cleanup handling") {
306     xbt_ex_t ex;
307     volatile int v1;
308     int c;
309
310     xbt_test_add0("cleanup handling");
311
312     v1 = 1234;
313     c = 0;
314     TRY {
315         v1 = 5678;
316         THROW0(1, 2, "blah");
317     } CLEANUP {
318         if (v1 != 5678)
319             xbt_test_fail1("v1 = %d (!= 5678)", v1);
320         c = 1;
321     } CATCH(ex) {
322         if (v1 != 5678)
323             xbt_test_fail1("v1 = %d (!= 5678)", v1);
324         if (!(ex.category == 1 && ex.value == 2 && !strcmp(ex.msg,"blah")))
325             xbt_test_fail0("unexpected exception contents");
326         xbt_ex_free(&ex);
327     }
328     if (!c)
329         xbt_test_fail0("xbt_ex_free not executed");
330 }
331
332
333 /*
334  * The following is the example included in the documentation. It's a good 
335  * idea to check its syntax even if we don't try to run it.
336  * And actually, it allows to put comments in the code despite doxygen.
337  */ 
338 static char *mallocex(int size) {
339   return NULL;
340 }
341 #define SMALLAMOUNT 10
342 #define TOOBIG 100000000
343
344 #if 0 /* this contains syntax errors, actually */
345 static void bad_example(void) {
346   struct {char*first;} *globalcontext;
347   ex_t ex;
348
349   /* BAD_EXAMPLE */
350   TRY {
351     char *cp1, *cp2, *cp3;
352     
353     cp1 = mallocex(SMALLAMOUNT);
354     globalcontext->first = cp1;
355     cp2 = mallocex(TOOBIG);
356     cp3 = mallocex(SMALLAMOUNT);
357     strcpy(cp1, "foo");
358     strcpy(cp2, "bar");
359   } CLEANUP {
360     if (cp3 != NULL) free(cp3);
361     if (cp2 != NULL) free(cp2);
362     if (cp1 != NULL) free(cp1);
363   } CATCH(ex) {
364     printf("cp3=%s", cp3);
365     RETHROW;
366   }
367   /* end_of_bad_example */
368 }
369 #endif
370
371 static void good_example(void) {
372   struct {char*first;} *globalcontext;
373   xbt_ex_t ex;
374
375   /* GOOD_EXAMPLE */
376   { /*01*/
377     char * volatile /*03*/ cp1 = NULL /*02*/;
378     char * volatile /*03*/ cp2 = NULL /*02*/;
379     char * volatile /*03*/ cp3 = NULL /*02*/;
380     TRY {
381       cp1 = mallocex(SMALLAMOUNT);
382       globalcontext->first = cp1;
383       cp1 = NULL /*05 give away*/;
384       cp2 = mallocex(TOOBIG);
385       cp3 = mallocex(SMALLAMOUNT);
386       strcpy(cp1, "foo");
387       strcpy(cp2, "bar");
388     } CLEANUP { /*04*/
389       printf("cp3=%s", cp3 == NULL /*02*/ ? "" : cp3);
390       if (cp3 != NULL)
391         free(cp3);
392       if (cp2 != NULL)
393         free(cp2);
394       /*05 cp1 was given away */
395     } CATCH(ex) {
396       /*05 global context untouched */
397       RETHROW;
398     }
399   }
400   /* end_of_good_example */
401 }
402 #endif /* SIMGRID_TEST */