Logo AND Algorithmique Numérique Distribuée

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