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 */
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)
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)
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)
69 /* declare the machine context type */
70 typedef struct { __ex_mctx_struct } __ex_mctx_t;
72 /** @addtogroup XBT_ex
73 * @brief A set of macros providing exception a la C++ in ANSI C (grounding feature)
75 * This module is a small ISO-C++ style exception handling library
76 * for use in the ISO-C language. It allows you to use the paradigm
77 * of throwing and catching exceptions in order to reduce the amount
78 * of error handling code without hindering program robustness.
80 * This is achieved by directly transferring exceptional return codes
81 * (and the program control flow) from the location where the exception
82 * is raised (throw point) to the location where it is handled (catch
83 * point) -- usually from a deeply nested sub-routine to a parent
84 * routine. All intermediate routines no longer have to make sure that
85 * the exceptional return codes from sub-routines are correctly passed
88 * These features are brought to you by a modified version of the libex
89 * library, one of the numerous masterpiece of Ralf S. Engelschall.
91 * \htmlonly <div class="toc">\endhtmlonly
93 * @section XBT_ex_toc TABLE OF CONTENTS
97 * - \ref XBT_ex_pitfalls
99 * \htmlonly </div> \endhtmlonly
101 * @section XBT_ex_intro DESCRIPTION
103 * In SimGrid, an exception is a triple <\a msg , \a category , \a value>
104 * where \a msg is a human-readable text describing the exceptional
105 * condition, \a code an integer describing what went wrong and \a value
106 * providing a sort of sub-category. (this is different in the original libex).
108 * @section XBT_ex_base BASIC USAGE
110 * \em TRY \b TRIED_BLOCK [\em CLEANUP \b CLEANUP_BLOCK] \em CATCH (variable) \b CATCH_BLOCK
112 * This is the primary syntactical construct provided. It is modeled after the
113 * ISO-C++ try-catch clause and should sound familiar to most of you.
115 * Any exception thrown directly from the TRIED_BLOCK block or from called
116 * subroutines is caught. Cleanups which must be done after this block
117 * (whenever an exception arised or not) should be placed into the optionnal
118 * CLEANUP_BLOCK. The code dealing with the exceptions when they arise should
119 * be placed into the (mandatory) CATCH_BLOCK.
122 * In absence of exception, the control flow goes into the blocks TRIED_BLOCK
123 * and CLEANUP_BLOCK (if present); The CATCH_BLOCK block is then ignored.
125 * When an exception is thrown, the control flow goes through the following
126 * blocks: TRIED_BLOCK (up to the statement throwing the exception),
127 * CLEANUP_BLOCK (if any) and CATCH_BLOCK. The exception is stored in a
128 * variable for inspection inside the CATCH_BLOCK. This variable must be
129 * declared in the outter scope, but its value is only valid within the
133 * - TRY, CLEANUP and CATCH cannot be used separately, they work
134 * only in combination and form a language clause as a whole.
135 * - In contrast to the syntax of other languages (such as C++ or Jave) there
136 * is only one CATCH block and not multiple ones (all exceptions are
137 * of the same \em xbt_ex_t C type).
138 * - the variable of CATCH can naturally be reused in subsequent
140 * - it is possible to nest TRY clauses.
142 * The TRY block is a regular ISO-C language statement block, but it is not
143 * allowed to jump into it via "goto" or longjmp(3) or out of it via "break",
144 * "return", "goto" or longjmp(3) because there is some hidden setup and
145 * cleanup that needs to be done regardless of whether an exception is
146 * caught. Bypassing these steps will break the exception handling facility.
148 * The CLEANUP and CATCH blocks are regular ISO-C language statement
149 * blocks without any restrictions. You are even allowed to throw (and, in the
150 * CATCH block, to re-throw) exceptions.
152 * There is one subtle detail you should remember about TRY blocks:
153 * Variables used in the CLEANUP or CATCH clauses must be declared with
154 * the storage class "volatile", otherwise they might contain outdated
155 * information if an exception it thrown.
158 * This is because you usually do not know which commands in the TRY
159 * were already successful before the exception was thrown (logically speaking)
160 * and because the underlying ISO-C setjmp(3) facility applies those
161 * restrictions (technically speaking). As a matter of fact, value changes
162 * between the TRY and the THROW may be discarded if you forget the
163 * "volatile" keyword.
165 * \section XBT_ex_pitfalls PROGRAMMING PITFALLS
167 * Exception handling is a very elegant and efficient way of dealing with
168 * exceptional situation. Nevertheless it requires additional discipline in
169 * programming and there are a few pitfalls one must be aware of. Look the
170 * following code which shows some pitfalls and contains many errors (assuming
171 * a mallocex() function which throws an exception if malloc(3) fails):
175 * \until end_of_bad_example
177 * This example raises a few issues:
178 * -# \b variable \b scope \n
179 * Variables which are used in the CLEANUP or CATCH clauses must be
180 * declared before the TRY clause, otherwise they only exist inside the
181 * TRY block. In the example above, cp1, cp2 and cp3 only exist in the
182 * TRY block and are invisible from the CLEANUP and CATCH
184 * -# \b variable \b initialization \n
185 * Variables which are used in the CLEANUP or CATCH clauses must
186 * be initialized before the point of the first possible THROW is
187 * reached. In the example above, CLEANUP would have trouble using cp3
188 * if mallocex() throws a exception when allocating a TOOBIG buffer.
189 * -# \b volatile \b variable \n
190 * Variables which are used in the CLEANUP or CATCH clauses MUST BE
191 * DECLARED AS "volatile", otherwise they might contain outdated
192 * information when an exception is thrown.
193 * -# \b clean \b before \b catch \n
194 * The CLEANUP clause is not only place before the CATCH clause in
195 * the source code, it also occures before in the control flow. So,
196 * resources being cleaned up cannot be used in the CATCH block. In the
197 * example, c3 gets freed before the printf placed in CATCH.
198 * -# \b variable \b uninitialization \n
199 * If resources are passed out of the scope of the
200 * TRY/CLEANUP/CATCH construct, they naturally shouldn't get
201 * cleaned up. The example above does free(3) cp1 in CLEANUP although
202 * its value was affected to globalcontext->first, invalidating this
205 * The following is fixed version of the code (annotated with the pitfall items
209 * \until end_of_good_example
214 /** @brief different kind of errors */
216 unknown_error=0, /**< unknown error */
217 arg_error, /**< Invalid argument */
218 mismatch_error, /**< The provided ID does not match */
219 not_found_error, /**< The searched element was not found */
221 system_error, /**< a syscall did fail */
222 network_error, /**< error while sending/receiving data */
223 timeout_error, /**< not quick enough, dude */
224 thread_error /**< error while [un]locking */
227 const char * xbt_ex_catname(xbt_errcat_t cat);
229 /** @brief Structure describing an exception */
231 char *msg; /**< human readable message; to be freed */
232 xbt_errcat_t category; /**< category like HTTP (what went wrong) */
233 int value; /**< like errno (why did it went wrong) */
235 short remote; /* whether it was raised remotely */
236 char *host; /* NULL for localhost; hostname if remote */
237 /* FIXME: host should be hostname:port[#thread] */
239 char *file; /**< to be freed only for remote exceptions */
241 char *func; /**< to be freed only for remote exceptions */
244 char **bt_strings; /* only filed on display (or before the network propagation) */
245 void *bt[XBT_BACKTRACE_SIZE];
248 /* declare the context type (private) */
250 __ex_mctx_t *ctx_mctx; /* permanent machine context of enclosing try/catch */
251 volatile int ctx_caught; /* temporary flag whether exception was caught */
252 volatile xbt_ex_t ctx_ex; /* temporary exception storage */
255 /* the static and dynamic initializers for a context structure */
256 #define XBT_CTX_INITIALIZER \
257 { NULL, 0, { /* content */ NULL, unknown_error, 0, \
258 /* throw point*/ 0,NULL, NULL, NULL, 0, NULL,\
259 /* backtrace */ 0,NULL,{NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL} } }
260 #define XBT_CTX_INITIALIZE(ctx) \
262 (ctx)->ctx_mctx = NULL; \
263 (ctx)->ctx_caught = 0; \
264 (ctx)->ctx_ex.msg = NULL; \
265 (ctx)->ctx_ex.category = 0; \
266 (ctx)->ctx_ex.value = 0; \
267 (ctx)->ctx_ex.remote = 0; \
268 (ctx)->ctx_ex.host = NULL; \
269 (ctx)->ctx_ex.procname = NULL; \
270 (ctx)->ctx_ex.file = NULL; \
271 (ctx)->ctx_ex.line = 0; \
272 (ctx)->ctx_ex.func = NULL; \
273 (ctx)->ctx_ex.bt[0] = NULL; \
274 (ctx)->ctx_ex.bt[1] = NULL; \
275 (ctx)->ctx_ex.bt[2] = NULL; \
276 (ctx)->ctx_ex.bt[3] = NULL; \
277 (ctx)->ctx_ex.bt[4] = NULL; \
278 (ctx)->ctx_ex.bt[5] = NULL; \
279 (ctx)->ctx_ex.bt[6] = NULL; \
280 (ctx)->ctx_ex.bt[7] = NULL; \
281 (ctx)->ctx_ex.bt[8] = NULL; \
282 (ctx)->ctx_ex.bt[9] = NULL; \
283 (ctx)->ctx_ex.used = 0; \
284 (ctx)->ctx_ex.bt_strings = NULL; \
287 /* the exception context */
288 typedef ex_ctx_t *(*ex_ctx_cb_t)(void);
289 extern ex_ctx_cb_t __xbt_ex_ctx;
290 extern ex_ctx_t *__xbt_ex_ctx_default(void);
292 /* the termination handler */
293 typedef void (*ex_term_cb_t)(xbt_ex_t *);
294 extern ex_term_cb_t __xbt_ex_terminate;
295 extern void __xbt_ex_terminate_default(xbt_ex_t *e);
297 /** @brief Introduce a block where exception may be dealed with
302 ex_ctx_t *__xbt_ex_ctx_ptr = __xbt_ex_ctx(); \
303 int __ex_cleanup = 0; \
304 __ex_mctx_t *__ex_mctx_en; \
305 __ex_mctx_t __ex_mctx_me; \
306 __ex_mctx_en = __xbt_ex_ctx_ptr->ctx_mctx; \
307 __xbt_ex_ctx_ptr->ctx_mctx = &__ex_mctx_me; \
308 if (__ex_mctx_save(&__ex_mctx_me)) { \
311 /** @brief optional(!) block for cleanup
317 __xbt_ex_ctx_ptr->ctx_caught = 0; \
319 __ex_mctx_restored(&__ex_mctx_me); \
320 __xbt_ex_ctx_ptr->ctx_caught = 1; \
322 __xbt_ex_ctx_ptr->ctx_mctx = __ex_mctx_en; \
329 # define XBT_EX_T_CPLUSPLUSCAST (xbt_ex_t&)
331 # define XBT_EX_T_CPLUSPLUSCAST
335 /** @brief the block for catching (ie, deal with) an exception
341 if (!(__ex_cleanup)) \
342 __xbt_ex_ctx_ptr->ctx_caught = 0; \
344 if (!(__ex_cleanup)) { \
345 __ex_mctx_restored(&__ex_mctx_me); \
346 __xbt_ex_ctx_ptr->ctx_caught = 1; \
349 __xbt_ex_ctx_ptr->ctx_mctx = __ex_mctx_en; \
351 if ( !(__xbt_ex_ctx()->ctx_caught) \
352 || ((e) = XBT_EX_T_CPLUSPLUSCAST __xbt_ex_ctx()->ctx_ex, 0)) { \
356 #define DO_THROW(e) \
357 /* deal with the exception */ \
358 if (__xbt_ex_ctx()->ctx_mctx == NULL) \
359 __xbt_ex_terminate((xbt_ex_t *)&(e)); /* not catched */\
361 __ex_mctx_restore(__xbt_ex_ctx()->ctx_mctx); /* catched somewhere */ \
362 abort()/* nope, stupid GCC, we won't survive a THROW (this won't be reached) */
364 /** @brief Helper macro for THROWS0-6
367 * @param c: category code (integer)
368 * @param v: value (integer)
369 * @param m: message text
371 * If called from within a TRY/CATCH construct, this exception
372 * is copied into the CATCH relevant variable program control flow
373 * is derouted to the CATCH (after the optional sg_cleanup).
375 * If no TRY/CATCH construct embeeds this call, the program calls
378 * The THROW can be performed everywhere, including inside TRY,
379 * CLEANUP and CATCH blocks.
382 #define _THROW(c,v,m) \
383 do { /* change this sequence into one block */ \
384 /* build the exception */ \
385 __xbt_ex_ctx()->ctx_ex.msg = (m); \
386 __xbt_ex_ctx()->ctx_ex.category = (xbt_errcat_t)(c); \
387 __xbt_ex_ctx()->ctx_ex.value = (v); \
388 __xbt_ex_ctx()->ctx_ex.remote = 0; \
389 __xbt_ex_ctx()->ctx_ex.host = (char*)NULL; \
390 __xbt_ex_ctx()->ctx_ex.procname = strdup(xbt_procname()); \
391 __xbt_ex_ctx()->ctx_ex.file = (char*)__FILE__; \
392 __xbt_ex_ctx()->ctx_ex.line = __LINE__; \
393 __xbt_ex_ctx()->ctx_ex.func = (char*)_XBT_FUNCTION; \
394 __xbt_ex_ctx()->ctx_ex.used = backtrace((void**)__xbt_ex_ctx()->ctx_ex.bt,XBT_BACKTRACE_SIZE);\
395 DO_THROW(__xbt_ex_ctx()->ctx_ex);\
398 /** @brief Builds and throws an exception with a string taking no arguments
400 #define THROW0(c,v,m) _THROW(c,v,(m?bprintf(m):NULL))
401 /** @brief Builds and throws an exception with a string taking one argument
403 #define THROW1(c,v,m,a1) _THROW(c,v,bprintf(m,a1))
404 /** @brief Builds and throws an exception with a string taking two arguments
406 #define THROW2(c,v,m,a1,a2) _THROW(c,v,bprintf(m,a1,a2))
407 /** @brief Builds and throws an exception with a string taking three arguments
409 #define THROW3(c,v,m,a1,a2,a3) _THROW(c,v,bprintf(m,a1,a2,a3))
410 /** @brief Builds and throws an exception with a string taking four arguments
412 #define THROW4(c,v,m,a1,a2,a3,a4) _THROW(c,v,bprintf(m,a1,a2,a3,a4))
413 /** @brief Builds and throws an exception with a string taking five arguments
415 #define THROW5(c,v,m,a1,a2,a3,a4,a5) _THROW(c,v,bprintf(m,a1,a2,a3,a4,a5))
416 /** @brief Builds and throws an exception with a string taking six arguments
418 #define THROW6(c,v,m,a1,a2,a3,a4,a5,a6) _THROW(c,v,bprintf(m,a1,a2,a3,a4,a5,a6))
420 #define THROW_IMPOSSIBLE THROW0(unknown_error,0,"The Impossible Did Happen (yet again)")
421 #define THROW_UNIMPLEMENTED THROW1(unknown_error,0,"Function %s unimplemented",__FUNCTION__)
424 # define DIE_IMPOSSIBLE xbt_assert0(0,"The Impossible Did Happen (yet again)")
426 # define DIE_IMPOSSIBLE exit(1);
429 /** @brief re-throwing of an already caught exception (ie, pass it to the upper catch block)
434 if (__xbt_ex_ctx()->ctx_mctx == NULL) \
435 __xbt_ex_terminate((xbt_ex_t *)&(__xbt_ex_ctx()->ctx_ex)); \
437 __ex_mctx_restore(__xbt_ex_ctx()->ctx_mctx); \
443 #define _XBT_PRE_RETHROW \
445 char *_xbt_ex_internal_msg = __xbt_ex_ctx()->ctx_ex.msg; \
446 __xbt_ex_ctx()->ctx_ex.msg = bprintf(
447 #define _XBT_POST_RETHROW \
448 _xbt_ex_internal_msg); \
449 free(_xbt_ex_internal_msg); \
454 /** @brief like THROW0, but adding some details to the message of an existing exception
457 #define RETHROW0(msg) _XBT_PRE_RETHROW msg, _XBT_POST_RETHROW
458 /** @brief like THROW1, but adding some details to the message of an existing exception
461 #define RETHROW1(msg,a) _XBT_PRE_RETHROW msg,a, _XBT_POST_RETHROW
462 /** @brief like THROW2, but adding some details to the message of an existing exception
465 #define RETHROW2(msg,a,b) _XBT_PRE_RETHROW msg,a,b, _XBT_POST_RETHROW
466 /** @brief like THROW3, but adding some details to the message of an existing exception
469 #define RETHROW3(msg,a,b,c) _XBT_PRE_RETHROW msg,a,b,c, _XBT_POST_RETHROW
470 /** @brief like THROW4, but adding some details to the message of an existing exception
473 #define RETHROW4(msg,a,b,c,d) _XBT_PRE_RETHROW msg,a,b,c, _XBT_POST_RETHROW
474 /** @brief like THROW5, but adding some details to the message of an existing exception
477 #define RETHROW5(msg,a,b,c,d,e) _XBT_PRE_RETHROW msg,a,b,c,d,e _XBT_POST_RETHROW
479 /** @brief Exception destructor */
480 void xbt_ex_free(xbt_ex_t e);
482 void xbt_ex_display(xbt_ex_t *e);
485 #endif /* __XBT_EX_H__ */