Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Get the simulated exceptions as verbose as real ones
[simgrid.git] / include / xbt / ex.h
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.h: exception handling (pre-processor part)
30 */
31
32 #ifndef __XBT_EX_H__
33 #define __XBT_EX_H__
34
35 #include <xbt/misc.h>
36 #include <xbt/sysdep.h>
37
38 /* do not include execinfo.h directly since it's not always available. 
39    Instead, copy the parts we need (and fake when it's not there) */
40 extern int backtrace (void **__array, int __size);
41
42 /* required ISO-C standard facilities */
43 #include <errno.h>
44 #include <stdio.h>
45
46 /* the machine context */
47 #if defined(__EX_MCTX_MCSC__)
48 #include <ucontext.h>            /* POSIX.1 ucontext(3) */
49 #define __ex_mctx_struct         ucontext_t uc;
50 #define __ex_mctx_save(mctx)     (getcontext(&(mctx)->uc) == 0)
51 #define __ex_mctx_restored(mctx) /* noop */
52 #define __ex_mctx_restore(mctx)  (void)setcontext(&(mctx)->uc)
53
54 #elif defined(__EX_MCTX_SSJLJ__)
55 #include <setjmp.h>              /* POSIX.1 sigjmp_buf(3) */
56 #define __ex_mctx_struct         sigjmp_buf jb;
57 #define __ex_mctx_save(mctx)     (sigsetjmp((mctx)->jb, 1) == 0)
58 #define __ex_mctx_restored(mctx) /* noop */
59 #define __ex_mctx_restore(mctx)  (void)siglongjmp((mctx)->jb, 1)
60
61 #elif defined(__EX_MCTX_SJLJ__) || !defined(__EX_MCTX_CUSTOM__)
62 #include <setjmp.h>              /* ISO-C jmp_buf(3) */
63 #define __ex_mctx_struct         jmp_buf jb;
64 #define __ex_mctx_save(mctx)     (setjmp((mctx)->jb) == 0)
65 #define __ex_mctx_restored(mctx) /* noop */
66 #define __ex_mctx_restore(mctx)  (void)longjmp((mctx)->jb, 1)
67 #endif
68
69 /* declare the machine context type */
70 typedef struct { __ex_mctx_struct } __ex_mctx_t;
71  
72 /** @addtogroup XBT_ex
73  *
74  * This module is a small ISO-C++ style exception handling library
75  * for use in the ISO-C language. It allows you to use the paradigm 
76  * of throwing and catching exceptions in order to reduce the amount
77  * of error handling code without hindering program robustness.
78  *               
79  * This is achieved by directly transferring exceptional return codes
80  * (and the program control flow) from the location where the exception
81  * is raised (throw point) to the location where it is handled (catch
82  * point) -- usually from a deeply nested sub-routine to a parent 
83  * routine. All intermediate routines no longer have to make sure that 
84  * the exceptional return codes from sub-routines are correctly passed 
85  * back to the parent.
86  *
87  * These features are brought to you by a modified version of the libex 
88  * library, one of the numerous masterpiece of Ralf S. Engelschall.
89  *
90  * @section XBT_ex_intro DESCRIPTION
91  * 
92  * In SimGrid, exceptions is a triple <\a msg , \a category , \a value> 
93  * where \a msg is a human-readable text describing the exceptional 
94  * condition, \a code an integer describing what went wrong and \a value
95  * providing a sort of sub-category. (this is different in the original libex).
96  *
97  * @section XBT_ex_base BASIC USAGE
98  *
99  * \em TRY \b TRIED_BLOCK [\em CLEANUP \b CLEANUP_BLOCK] \em CATCH (variable) \b CATCH_BLOCK
100  *
101  * This is the primary syntactical construct provided. It is modeled after the
102  * ISO-C++ try-catch clause and should sound familiar to most of you.
103  *
104  * Any exception thrown directly from the TRIED_BLOCK block or from called
105  * subroutines is caught. Cleanups which must be done after this block
106  * (whenever an exception arised or not) should be placed into the optionnal
107  * CLEANUP_BLOCK. The code dealing with the exceptions when they arise should
108  * be placed into the (mandatory) CATCH_BLOCK.
109  *
110  * 
111  * In absence of exception, the control flow goes into the blocks TRIED_BLOCK
112  * and CLEANUP_BLOCK (if present); The CATCH_BLOCK block is then ignored. 
113  *
114  * When an exception is thrown, the control flow goes through the following
115  * blocks: TRIED_BLOCK (up to the statement throwing the exception),
116  * CLEANUP_BLOCK (if any) and CATCH_BLOCK. The exception is stored in a
117  * variable for inspection inside the CATCH_BLOCK. This variable must be
118  * declared in the outter scope, but its value is only valid within the
119  * CATCH_BLOCK block. 
120  *
121  * Some notes:
122  *  - TRY, CLEANUP and CATCH cannot be used separately, they work
123  *    only in combination and form a language clause as a whole.
124  *  - In contrast to the syntax of other languages (such as C++ or Jave) there
125  *    is only one CATCH block and not multiple ones (all exceptions are
126  *    of the same \em xbt_ex_t C type). 
127  *  - the variable of CATCH can naturally be reused in subsequent 
128  *    CATCH clauses.
129  *  - it is possible to nest TRY clauses.
130  *
131  * The TRY block is a regular ISO-C language statement block, but it is not
132  * allowed to jump into it via "goto" or longjmp(3) or out of it via "break",
133  * "return", "goto" or longjmp(3) because there is some hidden setup and
134  * cleanup that needs to be done regardless of whether an exception is
135  * caught. Bypassing these steps will break the exception handling facility.
136  *     
137  * The CLEANUP and CATCH blocks are regular ISO-C language statement
138  * blocks without any restrictions. You are even allowed to throw (and, in the
139  * CATCH block, to re-throw) exceptions.
140  *
141  * There is one subtle detail you should remember about TRY blocks:
142  * Variables used in the CLEANUP or CATCH clauses must be declared with
143  * the storage class "volatile", otherwise they might contain outdated
144  * information if an exception it thrown.
145  *
146  *
147  * This is because you usually do not know which commands in the TRY
148  * were already successful before the exception was thrown (logically speaking)
149  * and because the underlying ISO-C setjmp(3) facility applies those
150  * restrictions (technically speaking). As a matter of fact, value changes
151  * between the TRY and the THROW may be discarded if you forget the
152  * "volatile" keyword. 
153  * 
154  * \section XBT_ex_pitfalls PROGRAMMING PITFALLS 
155  *
156  * Exception handling is a very elegant and efficient way of dealing with
157  * exceptional situation. Nevertheless it requires additional discipline in
158  * programming and there are a few pitfalls one must be aware of. Look the
159  * following code which shows some pitfalls and contains many errors (assuming
160  * a mallocex() function which throws an exception if malloc(3) fails):
161  *
162  * \dontinclude ex_test.c
163  * \skip BAD_EXAMPLE
164  * \until end_of_bad_example
165  *
166  * This example raises a few issues:
167  *  -# \b variable \b scope \n
168  *     Variables which are used in the CLEANUP or CATCH clauses must be
169  *     declared before the TRY clause, otherwise they only exist inside the
170  *     TRY block. In the example above, cp1, cp2 and cp3 only exist in the
171  *     TRY block and are invisible from the CLEANUP and CATCH
172  *     blocks.
173  *  -# \b variable \b initialization \n
174  *     Variables which are used in the CLEANUP or CATCH clauses must
175  *     be initialized before the point of the first possible THROW is
176  *     reached. In the example above, CLEANUP would have trouble using cp3
177  *     if mallocex() throws a exception when allocating a TOOBIG buffer.
178  *  -# \b volatile \b variable \n
179  *     Variables which are used in the CLEANUP or CATCH clauses MUST BE
180  *     DECLARED AS "volatile", otherwise they might contain outdated
181  *     information when an exception is thrown. 
182  *  -# \b clean \b before \b catch \n
183  *     The CLEANUP clause is not only place before the CATCH clause in
184  *     the source code, it also occures before in the control flow. So,
185  *     resources being cleaned up cannot be used in the CATCH block. In the
186  *     example, c3 gets freed before the printf placed in CATCH.
187  *  -# \b variable \b uninitialization \n
188  *     If resources are passed out of the scope of the
189  *     TRY/CLEANUP/CATCH construct, they naturally shouldn't get
190  *     cleaned up. The example above does free(3) cp1 in CLEANUP although
191  *     its value was affected to globalcontext->first, invalidating this
192  *     pointer.
193
194  * The following is fixed version of the code (annotated with the pitfall items
195  * for reference): 
196  *
197  * \skip GOOD_EXAMPLE
198  * \until end_of_good_example
199  *
200  * @{
201  */
202
203 typedef enum {
204   unknown_error=0,  /**< unknown error */
205   arg_error,        /**< Invalid argument */
206   mismatch_error,   /**< The provided ID does not match */
207   not_found_error,  /**< The searched element was not found */
208   
209   system_error,   /**< a syscall did fail */
210   network_error,  /**< error while sending/receiving data */
211   timeout_error,  /**< not quick enough, dude */
212   thread_error    /**< error while [un]locking */
213 } xbt_errcat_t;
214
215 const char *xbt_errcat_name(xbt_errcat_t errcode);
216
217 /** @brief Structure describing an exception */
218 typedef struct {
219   char        *msg;      /**< human readable message; to be freed */
220   xbt_errcat_t category; /**< category like HTTP (what went wrong) */
221   int          value;    /**< like errno (why did it went wrong) */
222   /* throw point */
223   char *host;     /* NULL for localhost; hostname:port if remote */
224   char *procname; 
225   char *file;     /**< to be freed only for remote exceptions */
226   int   line;     
227   char *func;     /**< to be freed only for remote exceptions */
228   /* Backtrace */
229   void *bt[10];
230   int   used;
231 } xbt_ex_t;
232
233 /* declare the context type (private) */
234 typedef struct {
235     __ex_mctx_t  *ctx_mctx;     /* permanent machine context of enclosing try/catch */
236     int           ctx_caught;   /* temporary flag whether exception was caught */
237     volatile xbt_ex_t ctx_ex;       /* temporary exception storage */
238 } ex_ctx_t;
239
240 /* the static and dynamic initializers for a context structure */
241 #define XBT_CTX_INITIALIZER \
242     { NULL, 0, { /* content */ NULL, 0, 0, \
243                  /* throw point*/ NULL, NULL, NULL, 0, NULL,\
244                  /* backtrace */ {NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL},0 } }
245 #define XBT_CTX_INITIALIZE(ctx) \
246     do { \
247         (ctx)->ctx_mctx        = NULL; \
248         (ctx)->ctx_caught      = 0;    \
249         (ctx)->ctx_ex.msg      = NULL; \
250         (ctx)->ctx_ex.category = 0;    \
251         (ctx)->ctx_ex.value    = 0;    \
252         (ctx)->ctx_ex.host     = NULL; \
253         (ctx)->ctx_ex.procname = NULL; \
254         (ctx)->ctx_ex.file     = NULL; \
255         (ctx)->ctx_ex.line     = 0;    \
256         (ctx)->ctx_ex.func     = NULL; \
257         (ctx)->ctx_ex.bt[0]    = NULL; \
258         (ctx)->ctx_ex.bt[1]    = NULL; \
259         (ctx)->ctx_ex.bt[2]    = NULL; \
260         (ctx)->ctx_ex.bt[3]    = NULL; \
261         (ctx)->ctx_ex.bt[4]    = NULL; \
262         (ctx)->ctx_ex.bt[5]    = NULL; \
263         (ctx)->ctx_ex.bt[6]    = NULL; \
264         (ctx)->ctx_ex.bt[7]    = NULL; \
265         (ctx)->ctx_ex.bt[8]    = NULL; \
266         (ctx)->ctx_ex.bt[9]    = NULL; \
267         (ctx)->ctx_ex.used     = 0; \
268     } while (0)
269
270 /* the exception context */
271 typedef ex_ctx_t *(*ex_ctx_cb_t)(void);
272 extern ex_ctx_cb_t __xbt_ex_ctx;
273 extern ex_ctx_t *__xbt_ex_ctx_default(void);
274
275 /* the termination handler */
276 typedef void (*ex_term_cb_t)(xbt_ex_t *);
277 extern ex_term_cb_t __xbt_ex_terminate;
278 extern void __xbt_ex_terminate_default(xbt_ex_t *e);
279
280 /** @brief Introduce a block where exception may be dealed with 
281  *  @hideinitializer
282  */
283 #define TRY \
284     { \
285         ex_ctx_t *__xbt_ex_ctx_ptr = __xbt_ex_ctx(); \
286         int __ex_cleanup = 0; \
287         __ex_mctx_t *__ex_mctx_en; \
288         __ex_mctx_t __ex_mctx_me; \
289         __ex_mctx_en = __xbt_ex_ctx_ptr->ctx_mctx; \
290         __xbt_ex_ctx_ptr->ctx_mctx = &__ex_mctx_me; \
291         if (__ex_mctx_save(&__ex_mctx_me)) { \
292             if (1)
293
294 /** @brief optional(!) block for cleanup 
295  *  @hideinitializer
296  */
297 #define CLEANUP \
298             else { \
299             } \
300             __xbt_ex_ctx_ptr->ctx_caught = 0; \
301         } else { \
302             __ex_mctx_restored(&__ex_mctx_me); \
303             __xbt_ex_ctx_ptr->ctx_caught = 1; \
304         } \
305         __xbt_ex_ctx_ptr->ctx_mctx = __ex_mctx_en; \
306         __ex_cleanup = 1; \
307         if (1) { \
308             if (1)
309
310 /** @brief the block for catching (ie, deal with) an exception 
311  *  @hideinitializer
312  */
313 #define CATCH(e) \
314             else { \
315             } \
316             if (!(__ex_cleanup)) \
317                 __xbt_ex_ctx_ptr->ctx_caught = 0; \
318         } else { \
319             if (!(__ex_cleanup)) { \
320                 __ex_mctx_restored(&__ex_mctx_me); \
321                 __xbt_ex_ctx_ptr->ctx_caught = 1; \
322             } \
323         } \
324         __xbt_ex_ctx_ptr->ctx_mctx = __ex_mctx_en; \
325     } \
326     if (   !(__xbt_ex_ctx()->ctx_caught) \
327         || ((e) = __xbt_ex_ctx()->ctx_ex, 0)) { \
328     } \
329     else
330
331 /** @brief Build an exception from the supplied arguments and throws it
332  *  @hideinitializer
333  *
334  *  @param c: category code (integer)
335  *  @param v: value (integer)
336  *  @param m: message text
337  *
338  * If called from within a TRY/CATCH construct, this exception 
339  * is copied into the CATCH relevant variable program control flow 
340  * is derouted to the CATCH (after the optional sg_cleanup). 
341  *
342  * If no TRY/CATCH construct embeeds this call, the program calls
343  * abort(3). 
344  *
345  * The THROW can be performed everywhere, including inside TRY, 
346  * CLEANUP and CATCH blocks.
347  */
348
349 #define _THROW(c,v,m) \
350   do { /* change this sequence into one block */                               \
351      /* build the exception */ \
352      __xbt_ex_ctx()->ctx_ex.msg      = (m); \
353      __xbt_ex_ctx()->ctx_ex.category = (c); \
354      __xbt_ex_ctx()->ctx_ex.value    = (v);  \
355      __xbt_ex_ctx()->ctx_ex.host     = (char*)NULL;                            \
356      __xbt_ex_ctx()->ctx_ex.procname = strdup(xbt_procname());                 \
357      __xbt_ex_ctx()->ctx_ex.file     = (char*)__FILE__;                        \
358      __xbt_ex_ctx()->ctx_ex.line     = __LINE__;                               \
359      __xbt_ex_ctx()->ctx_ex.func     = (char*)_XBT_FUNCTION;                   \
360      __xbt_ex_ctx()->ctx_ex.used     = backtrace((void**)__xbt_ex_ctx()->ctx_ex.bt,10);\
361      /* deal with the exception */                                             \
362      if (__xbt_ex_ctx()->ctx_mctx == NULL)                                     \
363        __xbt_ex_terminate((xbt_ex_t *)&(__xbt_ex_ctx()->ctx_ex)); /* not catched */\
364      else                                                                      \
365        __ex_mctx_restore(__xbt_ex_ctx()->ctx_mctx); /* catched somewhere */    \
366      abort();/* nope, stupid GCC, we won't survive a THROW (this won't be reached) */ \
367   } while (0)
368
369 #define THROW0(c,v,m)                   _THROW(c,v,(m?bprintf(m):NULL))
370 #define THROW1(c,v,m,a1)                _THROW(c,v,bprintf(m,a1))
371 #define THROW2(c,v,m,a1,a2)             _THROW(c,v,bprintf(m,a1,a2))
372 #define THROW3(c,v,m,a1,a2,a3)          _THROW(c,v,bprintf(m,a1,a2,a3))
373 #define THROW4(c,v,m,a1,a2,a3,a4)       _THROW(c,v,bprintf(m,a1,a2,a3,a4))
374 #define THROW5(c,v,m,a1,a2,a3,a4,a5)    _THROW(c,v,bprintf(m,a1,a2,a3,a4,a5))
375 #define THROW6(c,v,m,a1,a2,a3,a4,a5,a6) _THROW(c,v,bprintf(m,a1,a2,a3,a4,a5,a6))
376
377 #define THROW_IMPOSSIBLE     THROW0(unknown_error,0,"The Impossible Did Happen (yet again)")
378 #define DIE_IMPOSSIBLE       xbt_assert0(0,"The Impossible Did Happen (yet again)")
379 #define THROW_UNIMPLEMENTED  THROW1(unknown_error,0,"Function %s unimplemented",__FUNCTION__)
380
381 /** @brief re-throwing of an already caught exception (ie, pass it to the upper catch block) 
382  *  @hideinitializer
383  */
384 #define RETHROW \
385   do { \
386    if (__xbt_ex_ctx()->ctx_mctx == NULL) \
387      __xbt_ex_terminate((xbt_ex_t *)&(__xbt_ex_ctx()->ctx_ex)); \
388    else \
389      __ex_mctx_restore(__xbt_ex_ctx()->ctx_mctx); \
390    abort();\
391   } while(0)
392
393 /** @brief like RETHROW, but adding some details to the message
394  *  @hideinitializer
395  */
396
397
398 #define _XBT_PRE_RETHROW \
399   do {                                                               \
400     char *_xbt_ex_internal_msg = __xbt_ex_ctx()->ctx_ex.msg;         \
401     __xbt_ex_ctx()->ctx_ex.msg = bprintf(
402 #define _XBT_POST_RETHROW \
403  _xbt_ex_internal_msg); \
404     free(_xbt_ex_internal_msg);                                      \
405     RETHROW;                                                         \
406   } while (0)
407
408 #define RETHROW0(msg)           _XBT_PRE_RETHROW msg,          _XBT_POST_RETHROW
409 #define RETHROW1(msg,a)         _XBT_PRE_RETHROW msg,a,        _XBT_POST_RETHROW
410 #define RETHROW2(msg,a,b)       _XBT_PRE_RETHROW msg,a,b,      _XBT_POST_RETHROW
411 #define RETHROW3(msg,a,b,c)     _XBT_PRE_RETHROW msg,a,b,c,    _XBT_POST_RETHROW
412 #define RETHROW4(msg,a,b,c,d)   _XBT_PRE_RETHROW msg,a,b,c,    _XBT_POST_RETHROW
413 #define RETHROW5(msg,a,b,c,d,e) _XBT_PRE_RETHROW msg,a,b,c,d,e _XBT_POST_RETHROW
414
415 void xbt_ex_free(xbt_ex_t e);
416 const char * xbt_ex_catname(xbt_errcat_t cat);
417
418 void xbt_ex_display(xbt_ex_t *e);
419
420 /** @} */
421 #endif /* __XBT_EX_H__ */
422