Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Help doxygen to display this documentation.
[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 Introduction
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 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 Advanced usage
149  *
150  * @subsection xbt_defer DEFERING_BLOCK
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_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 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 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  \verbatim
189 // BAD EXAMPLE
190 xbt_try {
191   char *cp1, *cp2, cp3;
192
193   cp1 = mallocex(SMALLAMOUNT);
194   globalcontext->first = cp1;
195   cp2 = mallocex(TOOBIG);
196   cp3 = mallocex(SMALLAMOUNT);
197   strcpy(cp1, "foo");
198   strcpy(cp2, "bar");
199 } xbt_cleanup {
200   if (cp3 != NULL) free(cp3);
201   if (cp2 != NULL) free(cp2);
202   if (cp1 != NULL) free(cp1);
203 } xbt_catch(ex) {
204   printf("cp3=%s", cp3);
205   ex_rethrow;
206 }\endverbatim
207
208  * This example raises a few issues:
209  *  -# \b variable scope\n
210  *     Variables which are used in the xbt_cleanup or xbt_catch clauses must be
211  *     declared before the xbt_try clause, otherwise they only exist inside the
212  *     xbt_try block. In the example above, cp1, cp2 and cp3 only exist in the
213  *     xbt_try block and are invisible from the xbt_cleanup and xbt_catch
214  *     blocks.
215  *  -# \b variable initialization \n
216  *     Variables which are used in the xbt_cleanup or xbt_catch clauses must
217  *     be initialized before the point of the first possible xbt_throw is
218  *     reached. In the example above, xbt_cleanup would have trouble using cp3
219  *     if mallocex() throws a exception when allocating a TOOBIG buffer.
220  *  -# \b volatile variable \n
221  *     Variables which are used in the xbt_cleanup or xbt_catch clauses MUST BE
222  *     DECLARED AS "volatile", otherwise they might contain outdated
223  *     information when an exception is thrown. 
224  *  -# \b clean before catch \n
225  *     The xbt_cleanup clause is not only place before the xbt_catch clause in
226  *     the source code, it also occures before in the control flow. So,
227  *     resources being cleaned up cannot be used in the xbt_catch block. In the
228  *     example, c3 gets freed before the printf placed in xbt_catch.
229  *  -# \b variable uninitialization \n
230  *     If resources are passed out of the scope of the
231  *     xbt_try/xbt_cleanup/xbt_catch construct, they naturally shouldn't get
232  *     cleaned up. The example above does free(3) cp1 in xbt_cleanup although
233  *     its value was affected to globalcontext->first, invalidating this
234  *     pointer.
235
236  * The following is fixed version of the code (annotated with the pitfall items
237  * for reference):
238  \verbatim
239 // GOOD EXAMPLE
240 { / *01* /
241   char * volatile / *03* / cp1 = NULL / *02* /;
242   char * volatile / *03* / cp2 = NULL / *02* /;
243   char * volatile / *03* / cp3 = NULL / *02* /;
244   try {
245     cp1 = mallocex(SMALLAMOUNT);
246     globalcontext->first = cp1;
247     cp1 = NULL / *05 give away* /;
248     cp2 = mallocex(TOOBIG);
249     cp3 = mallocex(SMALLAMOUNT);
250     strcpy(cp1, "foo");
251     strcpy(cp2, "bar");
252   }
253   clean { / *04* /
254     printf("cp3=%s", cp3 == NULL / *02* / ? "" : cp3);
255     if (cp3 != NULL)
256       free(cp3);
257     if (cp2 != NULL)
258       free(cp2);
259     / *05 cp1 was given away * /
260   }
261   catch(ex) {
262     / *05 global context untouched * /
263     rethrow;
264   }
265 }\endverbatim
266
267  *
268  * @{
269  */
270
271 /** @brief Structure describing an exception */
272 typedef struct {
273   char *msg;      /**< human readable message; to be freed */
274   int   category; /**< category like HTTP (what went wrong) */
275   int   value;    /**< like errno (why did it went wrong) */
276   /* throw point */
277   char *host;     /* NULL for localhost; hostname:port if remote */
278   char *procname; 
279   char *file;     /**< to be freed only for remote exceptions */
280   int   line;     
281   char *func;     /**< to be freed only for remote exceptions */
282 } ex_t;
283
284 /* declare the context type (private) */
285 typedef struct {
286     __ex_mctx_t  *ctx_mctx;     /* permanent machine context of enclosing try/catch */
287     int           ctx_deferred; /* permanent flag whether exception is deferred */
288     int           ctx_deferring;/* permanent counter of exception deferring level */
289     int           ctx_defer;    /* temporary flag for exception deferring macro */
290     int           ctx_shielding;/* permanent counter of exception shielding level */
291     int           ctx_shield;   /* temporary flag for exception shielding macro */
292     int           ctx_caught;   /* temporary flag whether exception was caught */
293     volatile ex_t ctx_ex;       /* temporary exception storage */
294 } ex_ctx_t;
295
296 /* the static and dynamic initializers for a context structure */
297 #define XBT_CTX_INITIALIZER \
298     { NULL, 0, 0, 0, 0, 0, 0, { /* content */ NULL, 0, 0, \
299                                 /*throw point*/ NULL, NULL, NULL, 0, NULL } }
300 #define XBT_CTX_INITIALIZE(ctx) \
301     do { \
302         (ctx)->ctx_mctx        = NULL; \
303         (ctx)->ctx_deferred    = 0;    \
304         (ctx)->ctx_deferring   = 0;    \
305         (ctx)->ctx_defer       = 0;    \
306         (ctx)->ctx_shielding   = 0;    \
307         (ctx)->ctx_shield      = 0;    \
308         (ctx)->ctx_caught      = 0;    \
309         (ctx)->ctx_ex.msg      = NULL; \
310         (ctx)->ctx_ex.category = 0;    \
311         (ctx)->ctx_ex.value    = 0;    \
312         (ctx)->ctx_ex.host     = NULL; \
313         (ctx)->ctx_ex.procname = NULL; \
314         (ctx)->ctx_ex.file     = NULL; \
315         (ctx)->ctx_ex.line     = 0;    \
316         (ctx)->ctx_ex.func     = NULL; \
317     } while (0)
318
319 /* the exception context */
320 typedef ex_ctx_t *(*ex_ctx_cb_t)(void);
321 extern ex_ctx_cb_t __xbt_ex_ctx;
322 extern ex_ctx_t *__xbt_ex_ctx_default(void);
323
324 /* the termination handler */
325 typedef void (*ex_term_cb_t)(ex_t *);
326 extern ex_term_cb_t __xbt_ex_terminate;
327 extern void __xbt_ex_terminate_default(ex_t *e);
328
329 /** @brief Introduce a block where exception may be dealed with 
330  *  @hideinitializer
331  */
332 #define xbt_try \
333     { \
334         ex_ctx_t *__xbt_ex_ctx_ptr = __xbt_ex_ctx(); \
335         int __ex_cleanup = 0; \
336         __ex_mctx_t *__ex_mctx_en; \
337         __ex_mctx_t __ex_mctx_me; \
338         __ex_mctx_en = __xbt_ex_ctx_ptr->ctx_mctx; \
339         __xbt_ex_ctx_ptr->ctx_mctx = &__ex_mctx_me; \
340         if (__ex_mctx_save(&__ex_mctx_me)) { \
341             if (1)
342
343 /** @brief optional(!) block for cleanup 
344  *  @hideinitializer
345  */
346 #define xbt_cleanup \
347             else { \
348             } \
349             __xbt_ex_ctx_ptr->ctx_caught = 0; \
350         } \
351         else { \
352             __ex_mctx_restored(&__ex_mctx_me); \
353             __xbt_ex_ctx_ptr->ctx_caught = 1; \
354         } \
355         __xbt_ex_ctx_ptr->ctx_mctx = __ex_mctx_en; \
356         __ex_cleanup = 1; \
357         if (1) { \
358             if (1)
359
360 /** @brief the block for catching (ie, deal with) an exception 
361  *  @hideinitializer
362  */
363 #define xbt_catch(e) \
364             else { \
365             } \
366             if (!(__ex_cleanup)) \
367                 __xbt_ex_ctx_ptr->ctx_caught = 0; \
368         } \
369         else { \
370             if (!(__ex_cleanup)) { \
371                 __ex_mctx_restored(&__ex_mctx_me); \
372                 __xbt_ex_ctx_ptr->ctx_caught = 1; \
373             } \
374         } \
375         __xbt_ex_ctx_ptr->ctx_mctx = __ex_mctx_en; \
376     } \
377     if (   !(__xbt_ex_ctx()->ctx_caught) \
378         || ((e) = __xbt_ex_ctx()->ctx_ex, 0)) { \
379     } \
380     else
381
382 /** @brief Build an exception from the supplied arguments and throws it
383  *  @hideinitializer
384  *
385  * If called from within a sg_try/sg_catch construct, this exception 
386  * is copied into the sg_catch relevant variable program control flow 
387  * is derouted to the sg_catch (after the optional sg_cleanup). 
388  *
389  * If no sg_try/sg_catch conctruct embeeds this call, the program calls
390  * abort(3). 
391  *
392  * The sg_throw can be performed everywhere, including inside sg_try, 
393  * sg_cleanup and sg_catch blocks.
394  */
395 #define xbt_throw(c,v,m) \
396     ((   __xbt_ex_ctx()->ctx_shielding > 0 \
397       || (__xbt_ex_ctx()->ctx_deferring > 0 && __xbt_ex_ctx()->ctx_deferred == 1)) ? 0 : \
398      (__xbt_ex_ctx()->ctx_ex.msg      = bprintf(m), \
399       __xbt_ex_ctx()->ctx_ex.category = (c), \
400       __xbt_ex_ctx()->ctx_ex.value    = (v), \
401       __xbt_ex_ctx()->ctx_ex.host     = (char*)NULL, \
402       __xbt_ex_ctx()->ctx_ex.procname = strdup(xbt_procname()), \
403       __xbt_ex_ctx()->ctx_ex.file     = (char*)__FILE__, \
404       __xbt_ex_ctx()->ctx_ex.line     = __LINE__, \
405       __xbt_ex_ctx()->ctx_ex.func     = (char*)_XBT_FUNCTION, \
406       __xbt_ex_ctx()->ctx_deferred     = 1, \
407       (__xbt_ex_ctx()->ctx_deferring > 0 ? 0 : \
408        (__xbt_ex_ctx()->ctx_mctx == NULL \
409         ? (__xbt_ex_terminate((ex_t *)&(__xbt_ex_ctx()->ctx_ex)), -1) \
410         : (__ex_mctx_restore(__xbt_ex_ctx()->ctx_mctx), 1) ))))
411
412 /** @brief re-throwing of an already caught exception (ie, pass it to the upper catch block) 
413  *  @hideinitializer
414  */
415 #define xbt_rethrow \
416     ((   __xbt_ex_ctx()->ctx_shielding > 0 \
417       || __xbt_ex_ctx()->ctx_deferring > 0) ? 0 : \
418       (  __xbt_ex_ctx()->ctx_mctx == NULL \
419        ? (__xbt_ex_terminate((ex_t *)&(__xbt_ex_ctx()->ctx_ex)), -1) \
420        : (__ex_mctx_restore(__xbt_ex_ctx()->ctx_mctx), 1) ))
421
422 /** @brief shield an operation from exception handling 
423  *  @hideinitializer
424  */
425 #define xbt_shield \
426     for (__xbt_ex_ctx()->ctx_shielding++, \
427          __xbt_ex_ctx()->ctx_shield =  1; \
428          __xbt_ex_ctx()->ctx_shield == 1; \
429          __xbt_ex_ctx()->ctx_shield =  0, \
430          __xbt_ex_ctx()->ctx_shielding--)
431
432 /** @brief defer immediate exception handling 
433  *  @hideinitializer
434  */
435 #define xbt_defer \
436     for (((__xbt_ex_ctx()->ctx_deferring)++ == 0 ? __xbt_ex_ctx()->ctx_deferred = 0 : 0), \
437          __xbt_ex_ctx()->ctx_defer =  1;  \
438          __xbt_ex_ctx()->ctx_defer == 1;  \
439          __xbt_ex_ctx()->ctx_defer =  0,  \
440          ((--(__xbt_ex_ctx()->ctx_deferring) == 0 && __xbt_ex_ctx()->ctx_deferred == 1) ? xbt_rethrow : 0))
441
442 /** @brief exception handling tests 
443  *  @hideinitializer
444  */
445 #define xbt_catching \
446     (__xbt_ex_ctx()->ctx_mctx != NULL)
447 /** @brief exception handling tests 
448  *  @hideinitializer
449  */
450 #define xbt_shielding \
451     (__xbt_ex_ctx()->ctx_shielding > 0)
452 /** @brief exception handling tests 
453  *  @hideinitializer
454  */
455 #define xbt_deferring \
456     (__xbt_ex_ctx()->ctx_deferring > 0)
457
458 /* optional namespace mapping */
459 #if defined(__EX_NS_UCCXX__)
460 #define Try      xbt_try
461 #define Cleanup  xbt_cleanup
462 #define Catch    xbt_catch
463 #define Throw    xbt_throw
464 #define Rethrow  xbt_rethrow
465 #define Shield   xbt_shield
466 #define Defer    xbt_defer
467 #elif defined(__EX_NS_CXX__) || (!defined(__cplusplus) && !defined(__EX_NS_CUSTOM__))
468 #define try      xbt_try
469 #define cleanup  xbt_cleanup
470 #define catch    xbt_catch
471 #define throw    xbt_throw
472 #define rethrow  xbt_rethrow
473 #define shield   xbt_shield
474 #define defer    xbt_defer
475 #endif
476
477 /** @} */
478 #endif /* __XBT_EX_H__ */
479