Logo AND Algorithmique Numérique Distribuée

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