Logo AND Algorithmique Numérique Distribuée

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