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/>
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/.
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
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
29 ** ex.h: exception handling (pre-processor part)
35 #include <xbt/sysdep.h>
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);
42 /* required ISO-C standard facilities */
47 /*-*-* Emergency debuging: define this when the exceptions get crazy *-*-*/
51 int gras_os_getpid(void);
52 # define MAYDAY_SAVE(m) printf("%d %s:%d save %p\n", \
53 gras_os_getpid(),__FILE__,__LINE__, \
56 # define MAYDAY_RESTORE(m) printf("%d %s:%d restore %p\n", \
57 gras_os_getpid(),__FILE__,__LINE__, \
60 # define MAYDAY_CATCH(e) printf("%d %s:%d Catched '%s'\n", \
61 gras_os_getpid(),__FILE__,__LINE__, \
65 # define MAYDAY_SAVE(m)
66 # define MAYDAY_RESTORE(m)
67 # define MAYDAY_CATCH(e)
70 /*-*-* end of debugging stuff *-*-*/
73 /* the machine context */
74 #if defined(__EX_MCTX_MCSC__)
75 #include <ucontext.h> /* POSIX.1 ucontext(3) */
76 #define __ex_mctx_struct ucontext_t uc;
77 #define __ex_mctx_save(mctx) (getcontext(&(mctx)->uc) == 0)
78 #define __ex_mctx_restored(mctx) /* noop */
79 #define __ex_mctx_restore(mctx) (void)setcontext(&(mctx)->uc)
81 #elif defined(__EX_MCTX_SSJLJ__)
82 #include <setjmp.h> /* POSIX.1 sigjmp_buf(3) */
83 #define __ex_mctx_struct sigjmp_buf jb;
84 #define __ex_mctx_save(mctx) (sigsetjmp((mctx)->jb, 1) == 0)
85 #define __ex_mctx_restored(mctx) /* noop */
86 #define __ex_mctx_restore(mctx) (void)siglongjmp((mctx)->jb, 1)
88 #elif defined(__EX_MCTX_SJLJ__) || !defined(__EX_MCTX_CUSTOM__) || defined(__EX_MAYDAY)
89 #include <setjmp.h> /* ISO-C jmp_buf(3) */
90 #define __ex_mctx_struct jmp_buf jb;
91 #define __ex_mctx_save(mctx) ( MAYDAY_SAVE(mctx) setjmp((mctx)->jb) == 0)
92 #define __ex_mctx_restored(mctx) /* noop */
93 #define __ex_mctx_restore(mctx) ( MAYDAY_RESTORE(mctx) (void)longjmp((mctx)->jb, 1))
96 /* declare the machine context type */
97 typedef struct { __ex_mctx_struct } __ex_mctx_t;
99 /** @addtogroup XBT_ex
100 * @brief A set of macros providing exception a la C++ in ANSI C (grounding feature)
102 * This module is a small ISO-C++ style exception handling library
103 * for use in the ISO-C language. It allows you to use the paradigm
104 * of throwing and catching exceptions in order to reduce the amount
105 * of error handling code without hindering program robustness.
107 * This is achieved by directly transferring exceptional return codes
108 * (and the program control flow) from the location where the exception
109 * is raised (throw point) to the location where it is handled (catch
110 * point) -- usually from a deeply nested sub-routine to a parent
111 * routine. All intermediate routines no longer have to make sure that
112 * the exceptional return codes from sub-routines are correctly passed
113 * back to the parent.
115 * These features are brought to you by a modified version of the libex
116 * library, one of the numerous masterpiece of Ralf S. Engelschall.
118 * \htmlonly <div class="toc">\endhtmlonly
120 * @section XBT_ex_toc TABLE OF CONTENTS
122 * - \ref XBT_ex_intro
124 * - \ref XBT_ex_pitfalls
126 * \htmlonly </div> \endhtmlonly
128 * @section XBT_ex_intro DESCRIPTION
130 * In SimGrid, an exception is a triple <\a msg , \a category , \a value>
131 * where \a msg is a human-readable text describing the exceptional
132 * condition, \a code an integer describing what went wrong and \a value
133 * providing a sort of sub-category. (this is different in the original libex).
135 * @section XBT_ex_base BASIC USAGE
137 * \em TRY \b TRIED_BLOCK [\em CLEANUP \b CLEANUP_BLOCK] \em CATCH (variable) \b CATCH_BLOCK
139 * This is the primary syntactical construct provided. It is modeled after the
140 * ISO-C++ try-catch clause and should sound familiar to most of you.
142 * Any exception thrown directly from the TRIED_BLOCK block or from called
143 * subroutines is caught. Cleanups which must be done after this block
144 * (whenever an exception arised or not) should be placed into the optionnal
145 * CLEANUP_BLOCK. The code dealing with the exceptions when they arise should
146 * be placed into the (mandatory) CATCH_BLOCK.
149 * In absence of exception, the control flow goes into the blocks TRIED_BLOCK
150 * and CLEANUP_BLOCK (if present); The CATCH_BLOCK block is then ignored.
152 * When an exception is thrown, the control flow goes through the following
153 * blocks: TRIED_BLOCK (up to the statement throwing the exception),
154 * CLEANUP_BLOCK (if any) and CATCH_BLOCK. The exception is stored in a
155 * variable for inspection inside the CATCH_BLOCK. This variable must be
156 * declared in the outter scope, but its value is only valid within the
160 * - TRY, CLEANUP and CATCH cannot be used separately, they work
161 * only in combination and form a language clause as a whole.
162 * - In contrast to the syntax of other languages (such as C++ or Jave) there
163 * is only one CATCH block and not multiple ones (all exceptions are
164 * of the same \em xbt_ex_t C type).
165 * - the variable of CATCH can naturally be reused in subsequent
167 * - it is possible to nest TRY clauses.
169 * The TRY block is a regular ISO-C language statement block, but
171 * <center><b>it is not
172 * allowed to jump into it via "goto" or longjmp(3) or out of it via "break",
173 * "return", "goto" or longjmp(3)</b>.</center>
175 * This is because there is some hidden setup and
176 * cleanup that needs to be done regardless of whether an exception is
177 * caught. Bypassing these steps will break the exception handling facility.
179 * The CLEANUP and CATCH blocks are regular ISO-C language statement
180 * blocks without any restrictions. You are even allowed to throw (and, in the
181 * CATCH block, to re-throw) exceptions.
183 * There is one subtle detail you should remember about TRY blocks:
184 * Variables used in the CLEANUP or CATCH clauses must be declared with
185 * the storage class "volatile", otherwise they might contain outdated
186 * information if an exception it thrown.
189 * This is because you usually do not know which commands in the TRY
190 * were already successful before the exception was thrown (logically speaking)
191 * and because the underlying ISO-C setjmp(3) facility applies those
192 * restrictions (technically speaking). As a matter of fact, value changes
193 * between the TRY and the THROW may be discarded if you forget the
194 * "volatile" keyword.
196 * \section XBT_ex_pitfalls PROGRAMMING PITFALLS
198 * Exception handling is a very elegant and efficient way of dealing with
199 * exceptional situation. Nevertheless it requires additional discipline in
200 * programming and there are a few pitfalls one must be aware of. Look the
201 * following code which shows some pitfalls and contains many errors (assuming
202 * a mallocex() function which throws an exception if malloc(3) fails):
206 * \until end_of_bad_example
208 * This example raises a few issues:
209 * -# \b variable \b scope \n
210 * Variables which are used in the CLEANUP or CATCH clauses must be
211 * declared before the TRY clause, otherwise they only exist inside the
212 * TRY block. In the example above, cp1, cp2 and cp3 only exist in the
213 * TRY block and are invisible from the CLEANUP and CATCH
215 * -# \b variable \b initialization \n
216 * Variables which are used in the CLEANUP or CATCH clauses must
217 * be initialized before the point of the first possible THROW is
218 * reached. In the example above, CLEANUP would have trouble using cp3
219 * if mallocex() throws a exception when allocating a TOOBIG buffer.
220 * -# \b volatile \b variable \n
221 * Variables which are used in the CLEANUP or CATCH clauses MUST BE
222 * DECLARED AS "volatile", otherwise they might contain outdated
223 * information when an exception is thrown.
224 * -# \b clean \b before \b catch \n
225 * The CLEANUP clause is not only place before the 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 CATCH block. In the
228 * example, c3 gets freed before the printf placed in CATCH.
229 * -# \b variable \b uninitialization \n
230 * If resources are passed out of the scope of the
231 * TRY/CLEANUP/CATCH construct, they naturally shouldn't get
232 * cleaned up. The example above does free(3) cp1 in CLEANUP although
233 * its value was affected to globalcontext->first, invalidating this
236 * The following is fixed version of the code (annotated with the pitfall items
240 * \until end_of_good_example
245 /** @brief different kind of errors */
247 unknown_error=0, /**< unknown error */
248 arg_error, /**< Invalid argument */
249 mismatch_error, /**< The provided ID does not match */
250 not_found_error, /**< The searched element was not found */
252 system_error, /**< a syscall did fail */
253 network_error, /**< error while sending/receiving data */
254 timeout_error, /**< not quick enough, dude */
255 thread_error /**< error while [un]locking */
258 const char * xbt_ex_catname(xbt_errcat_t cat);
260 /** @brief Structure describing an exception */
262 char *msg; /**< human readable message; to be freed */
263 xbt_errcat_t category; /**< category like HTTP (what went wrong) */
264 int value; /**< like errno (why did it went wrong) */
266 short int remote; /* whether it was raised remotely */
267 char *host; /* NULL for localhost; hostname if remote */
268 /* FIXME: host should be hostname:port[#thread] */
270 char *file; /**< to be freed only for remote exceptions */
272 char *func; /**< to be freed only for remote exceptions */
275 char **bt_strings; /* only filed on display (or before the network propagation) */
276 void *bt[XBT_BACKTRACE_SIZE];
279 /* declare the context type (private) */
281 __ex_mctx_t *ctx_mctx; /* permanent machine context of enclosing try/catch */
282 volatile int ctx_caught; /* temporary flag whether exception was caught */
283 volatile xbt_ex_t ctx_ex; /* temporary exception storage */
286 /* the static and dynamic initializers for a context structure */
287 #define XBT_CTX_INITIALIZER \
288 { NULL, 0, { /* content */ NULL, unknown_error, 0, \
289 /* throw point*/ 0,NULL, NULL, NULL, 0, NULL,\
290 /* backtrace */ 0,NULL,{NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL} } }
291 #define XBT_CTX_INITIALIZE(ctx) \
293 (ctx)->ctx_mctx = NULL; \
294 (ctx)->ctx_caught = 0; \
295 (ctx)->ctx_ex.msg = NULL; \
296 (ctx)->ctx_ex.category = 0; \
297 (ctx)->ctx_ex.value = 0; \
298 (ctx)->ctx_ex.remote = 0; \
299 (ctx)->ctx_ex.host = NULL; \
300 (ctx)->ctx_ex.procname = NULL; \
301 (ctx)->ctx_ex.file = NULL; \
302 (ctx)->ctx_ex.line = 0; \
303 (ctx)->ctx_ex.func = NULL; \
304 (ctx)->ctx_ex.bt[0] = NULL; \
305 (ctx)->ctx_ex.bt[1] = NULL; \
306 (ctx)->ctx_ex.bt[2] = NULL; \
307 (ctx)->ctx_ex.bt[3] = NULL; \
308 (ctx)->ctx_ex.bt[4] = NULL; \
309 (ctx)->ctx_ex.bt[5] = NULL; \
310 (ctx)->ctx_ex.bt[6] = NULL; \
311 (ctx)->ctx_ex.bt[7] = NULL; \
312 (ctx)->ctx_ex.bt[8] = NULL; \
313 (ctx)->ctx_ex.bt[9] = NULL; \
314 (ctx)->ctx_ex.used = 0; \
315 (ctx)->ctx_ex.bt_strings = NULL; \
318 /* the exception context */
319 typedef ex_ctx_t *(*ex_ctx_cb_t)(void);
320 extern ex_ctx_cb_t __xbt_ex_ctx;
321 extern ex_ctx_t *__xbt_ex_ctx_default(void);
323 /* the termination handler */
324 typedef void (*ex_term_cb_t)(xbt_ex_t *);
325 extern ex_term_cb_t __xbt_ex_terminate;
326 extern void __xbt_ex_terminate_default(xbt_ex_t *e);
328 /** @brief Introduce a block where exception may be dealed with
333 ex_ctx_t *__xbt_ex_ctx_ptr = __xbt_ex_ctx(); \
334 int __ex_cleanup = 0; \
335 __ex_mctx_t *__ex_mctx_en; \
336 __ex_mctx_t __ex_mctx_me; \
337 __ex_mctx_en = __xbt_ex_ctx_ptr->ctx_mctx; \
338 __xbt_ex_ctx_ptr->ctx_mctx = &__ex_mctx_me; \
339 if (__ex_mctx_save(&__ex_mctx_me)) { \
342 /** @brief optional(!) block for cleanup
348 __xbt_ex_ctx_ptr->ctx_caught = 0; \
350 __ex_mctx_restored(&__ex_mctx_me); \
351 __xbt_ex_ctx_ptr->ctx_caught = 1; \
353 __xbt_ex_ctx_ptr->ctx_mctx = __ex_mctx_en; \
360 # define XBT_EX_T_CPLUSPLUSCAST (xbt_ex_t&)
362 # define XBT_EX_T_CPLUSPLUSCAST
366 /** @brief the block for catching (ie, deal with) an exception
372 if (!(__ex_cleanup)) \
373 __xbt_ex_ctx_ptr->ctx_caught = 0; \
375 if (!(__ex_cleanup)) { \
376 __ex_mctx_restored(&__ex_mctx_me); \
377 __xbt_ex_ctx_ptr->ctx_caught = 1; \
380 __xbt_ex_ctx_ptr->ctx_mctx = __ex_mctx_en; \
382 if ( !(__xbt_ex_ctx()->ctx_caught) \
383 || ((e) = XBT_EX_T_CPLUSPLUSCAST __xbt_ex_ctx()->ctx_ex, MAYDAY_CATCH(e) 0)) { \
387 #define DO_THROW(e) \
388 /* deal with the exception */ \
389 if (__xbt_ex_ctx()->ctx_mctx == NULL) \
390 __xbt_ex_terminate((xbt_ex_t *)&(e)); /* not catched */\
392 __ex_mctx_restore(__xbt_ex_ctx()->ctx_mctx); /* catched somewhere */ \
393 abort()/* nope, stupid GCC, we won't survive a THROW (this won't be reached) */
395 /** @brief Helper macro for THROWS0-6
398 * @param c: category code (integer)
399 * @param v: value (integer)
400 * @param m: message text
402 * If called from within a TRY/CATCH construct, this exception
403 * is copied into the CATCH relevant variable program control flow
404 * is derouted to the CATCH (after the optional sg_cleanup).
406 * If no TRY/CATCH construct embeeds this call, the program calls
409 * The THROW can be performed everywhere, including inside TRY,
410 * CLEANUP and CATCH blocks.
413 #define _THROW(c,v,m) \
414 do { /* change this sequence into one block */ \
415 /* build the exception */ \
416 __xbt_ex_ctx()->ctx_ex.msg = (m); \
417 __xbt_ex_ctx()->ctx_ex.category = (xbt_errcat_t)(c); \
418 __xbt_ex_ctx()->ctx_ex.value = (v); \
419 __xbt_ex_ctx()->ctx_ex.remote = 0; \
420 __xbt_ex_ctx()->ctx_ex.host = (char*)NULL; \
421 __xbt_ex_ctx()->ctx_ex.procname = (char*)xbt_procname(); \
422 __xbt_ex_ctx()->ctx_ex.file = (char*)__FILE__; \
423 __xbt_ex_ctx()->ctx_ex.line = __LINE__; \
424 __xbt_ex_ctx()->ctx_ex.func = (char*)_XBT_FUNCTION; \
425 __xbt_ex_ctx()->ctx_ex.used = backtrace((void**)__xbt_ex_ctx()->ctx_ex.bt,XBT_BACKTRACE_SIZE);\
426 __xbt_ex_ctx()->ctx_ex.bt_strings = NULL; \
427 DO_THROW(__xbt_ex_ctx()->ctx_ex);\
430 /** @brief Builds and throws an exception with a string taking no arguments
432 #define THROW0(c,v,m) _THROW(c,v,(m?bprintf(m):NULL))
433 /** @brief Builds and throws an exception with a string taking one argument
435 #define THROW1(c,v,m,a1) _THROW(c,v,bprintf(m,a1))
436 /** @brief Builds and throws an exception with a string taking two arguments
438 #define THROW2(c,v,m,a1,a2) _THROW(c,v,bprintf(m,a1,a2))
439 /** @brief Builds and throws an exception with a string taking three arguments
441 #define THROW3(c,v,m,a1,a2,a3) _THROW(c,v,bprintf(m,a1,a2,a3))
442 /** @brief Builds and throws an exception with a string taking four arguments
444 #define THROW4(c,v,m,a1,a2,a3,a4) _THROW(c,v,bprintf(m,a1,a2,a3,a4))
445 /** @brief Builds and throws an exception with a string taking five arguments
447 #define THROW5(c,v,m,a1,a2,a3,a4,a5) _THROW(c,v,bprintf(m,a1,a2,a3,a4,a5))
448 /** @brief Builds and throws an exception with a string taking six arguments
450 #define THROW6(c,v,m,a1,a2,a3,a4,a5,a6) _THROW(c,v,bprintf(m,a1,a2,a3,a4,a5,a6))
452 #define THROW_IMPOSSIBLE THROW0(unknown_error,0,"The Impossible Did Happen (yet again)")
453 #define THROW_UNIMPLEMENTED THROW1(unknown_error,0,"Function %s unimplemented",__FUNCTION__)
456 # define DIE_IMPOSSIBLE xbt_assert0(0,"The Impossible Did Happen (yet again)")
458 # define DIE_IMPOSSIBLE exit(1);
461 /** @brief re-throwing of an already caught exception (ie, pass it to the upper catch block)
466 if (__xbt_ex_ctx()->ctx_mctx == NULL) \
467 __xbt_ex_terminate((xbt_ex_t *)&(__xbt_ex_ctx()->ctx_ex)); \
469 __ex_mctx_restore(__xbt_ex_ctx()->ctx_mctx); \
475 #define _XBT_PRE_RETHROW \
477 char *_xbt_ex_internal_msg = __xbt_ex_ctx()->ctx_ex.msg; \
478 __xbt_ex_ctx()->ctx_ex.msg = bprintf(
479 #define _XBT_POST_RETHROW \
480 _xbt_ex_internal_msg); \
481 free(_xbt_ex_internal_msg); \
486 /** @brief like THROW0, but adding some details to the message of an existing exception
489 #define RETHROW0(msg) _XBT_PRE_RETHROW msg, _XBT_POST_RETHROW
490 /** @brief like THROW1, but adding some details to the message of an existing exception
493 #define RETHROW1(msg,a) _XBT_PRE_RETHROW msg,a, _XBT_POST_RETHROW
494 /** @brief like THROW2, but adding some details to the message of an existing exception
497 #define RETHROW2(msg,a,b) _XBT_PRE_RETHROW msg,a,b, _XBT_POST_RETHROW
498 /** @brief like THROW3, but adding some details to the message of an existing exception
501 #define RETHROW3(msg,a,b,c) _XBT_PRE_RETHROW msg,a,b,c, _XBT_POST_RETHROW
502 /** @brief like THROW4, but adding some details to the message of an existing exception
505 #define RETHROW4(msg,a,b,c,d) _XBT_PRE_RETHROW msg,a,b,c, _XBT_POST_RETHROW
506 /** @brief like THROW5, but adding some details to the message of an existing exception
509 #define RETHROW5(msg,a,b,c,d,e) _XBT_PRE_RETHROW msg,a,b,c,d,e _XBT_POST_RETHROW
511 /** @brief Exception destructor */
512 void xbt_ex_free(xbt_ex_t *e);
514 void xbt_ex_display(xbt_ex_t *e);
517 #endif /* __XBT_EX_H__ */