Logo AND Algorithmique Numérique Distribuée

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