Logo AND Algorithmique Numérique Distribuée

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