"Fossies" - the Fresh Open Source Software Archive

Member "pigz-2.8/try.h" (20 Aug 2023, 23043 Bytes) of package /linux/privat/pigz-2.8.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "try.h" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 2.7_vs_2.8.

    1 /* try.h -- try / catch / throw exception handling for C99
    2   Copyright (C) 2013, 2015, 2016, 2021 Mark Adler
    3   Version 1.5  10 April 2021
    4 
    5   This software is provided 'as-is', without any express or implied
    6   warranty.  In no event will the author be held liable for any damages
    7   arising from the use of this software.
    8 
    9   Permission is granted to anyone to use this software for any purpose,
   10   including commercial applications, and to alter it and redistribute it
   11   freely, subject to the following restrictions:
   12 
   13   1. The origin of this software must not be misrepresented; you must not
   14      claim that you wrote the original software. If you use this software
   15      in a product, an acknowledgment in the product documentation would be
   16      appreciated but is not required.
   17   2. Altered source versions must be plainly marked as such, and must not be
   18      misrepresented as being the original software.
   19   3. This notice may not be removed or altered from any source distribution.
   20 
   21   Mark Adler    madler@alumni.caltech.edu
   22  */
   23 
   24 /*
   25     Version History
   26     1.0    7 Jan 2013   - First version
   27     1.1    2 Nov 2013   - Use variadic macros and functions instead of partial
   28                           structure assignment, allowing arbitrary arguments
   29                           to printf()
   30     1.2   19 Jan 2015   - Obey setjmp() invocation limits from C standard
   31     1.3    1 Mar 2015   - Add preserve to avoid use of volatile, remove retry
   32     1.4    2 Jan 2016   - Add no-return attribute to throw()
   33     1.5   10 Apr 2021   - Portability improvements
   34  */
   35 
   36 /* To use, include try.h in all source files that use these operations, and
   37    compile and link try.c.  By default, pthread threads are used to make the
   38    exception handling thread-safe. If a different threads library is required,
   39    then try.h and try.c must be modified to use that environment's thread-local
   40    storage for the try_stack_ pointer.  try.h and try.c assume that the
   41    compiler and library conform to the C99 standard, at least with respect to
   42    the use of variadic macro and function arguments. */
   43 
   44 /*
   45    try.h provides a try / catch / throw exception handler, which allows
   46    catching exceptions across any number of levels of function calls.  try
   47    blocks can be nested as desired, with a throw going to the end of the
   48    innermost enclosing try, passing the thrown information to the associated
   49    catch block.  A global try stack is used, to avoid having to pass exception
   50    handler information through all of the functions down to the invocations of
   51    throw.  The try stack is thread-unique if pthread is made available.  In
   52    addition to the macros try, catch, and throw, the macros preserve, always,
   53    punt, and drop, and the type ball_t are created.  All other symbols are of
   54    the form try_*_ or TRY_*_, where the final underscore should avoid conflicts
   55    with application symbols. The eight exposed names can be changed easily in
   56    #defines below.
   57 
   58    A try block encloses code that may throw an exception with the throw()
   59    macro, either directly in the try block or in any function called directly
   60    or indirectly from the try block.  throw() must have at least one argument,
   61    which is an integer.  The try block is followed by a catch block whose code
   62    will be executed when throw() is called with a non-zero first argument.  If
   63    the first argument of throw() is zero, then execution continues after the
   64    catch block.  If the try block completes normally, with no throw() being
   65    called, then execution continues normally after the catch block.
   66 
   67    There can be only one catch block.  catch has one argument which must be a
   68    ball_t type variable declared in the current function or block containing
   69    the try and catch.  That variable is loaded with the information sent by the
   70    throw() for use in the catch block.
   71 
   72    throw() may optionally include more information that is passed to the catch
   73    block in the ball_t structure.  throw() can have one or more arguments,
   74    where the first (possibly only) argument is an integer code.  The second
   75    argument can be a pointer, which will be replaced by NULL in the ball_t
   76    structure if not provided.  The implementation of throw() in try.c assumes
   77    that if the second argument is present and is not NULL, that it is a string.
   78    If that string has any percent (%) signs in it, then throw() will run that
   79    string through vsnprintf() with any other arguments provided after the
   80    string in the throw() invocation, and save the resulting formatted string in
   81    the ball_t structure.  Information on whether or not the string was
   82    allocated is also maintained in the ball_t structure.
   83 
   84    throw() in try.c can be modified to not assume that the second argument is a
   85    string.  For example, an application may want to assume instead that the
   86    second argument is a pointer to a set of information for use in the catch
   87    block.
   88 
   89    The catch block may conditionally do a punt(), where the argument of punt()
   90    is the argument of catch.  This passes the exception on to the next
   91    enclosing try/catch handler.
   92 
   93    If a catch block does not always complete with a punt(), it should contain a
   94    drop(), where the argument of drop() is the argument of catch.  This frees
   95    the allocated string made if vsnprintf() was used by throw() to generate the
   96    string.  If printf() format strings are never used, then drop() is not
   97    required.
   98 
   99    An always block may be placed between the try and catch block.  The
  100    statements in that block will be executed regardless of whether or not the
  101    try block completed normally.  As indicated by the ordering, the always
  102    block will be executed before the catch block.  This block is not named
  103    "finally", since it is different from the finally block in other languages
  104    which is executed after the catch block.
  105 
  106    A naked break or continue in a try or always block will go directly to the
  107    end of that block.
  108 
  109    try is thread-safe when compiled with pthread.h.  A throw() in a thread can
  110    only be caught in the same thread.  If a throw() is attempted from a thread
  111    without an enclosing try in that thread, even if in another thread there is
  112    a try around the pthread_create() that spawned this thread, then the throw
  113    will fail on an assert.  Each thread has its own thread-unique try stack,
  114    which starts off empty.
  115 
  116    If an intermediate function does not have a need for operations in a catch
  117    block other than punt, and does not need an always block, then that function
  118    does not need a try block.  "try { block } catch (err) { punt(err); }" is
  119    the same as just "block".  More precisely, it's equivalent to "do { block }
  120    while (0);", which replicates the behavior of a naked break or continue in a
  121    block when it follows try.  throw() can be used from a function that has no
  122    try.  All that is necessary is that there is a try somewhere up the function
  123    chain that called the current function in the current thread.
  124 
  125    There must not be a return in any try block, nor a goto in any try block
  126    that leaves that block.  The always block does not catch a return from the
  127    try block.  There is no check or protection for an improper use of return or
  128    goto.  It is up to the user to assure that this doesn't happen.  If it does
  129    happen, then the reference to the current try block is left on the try
  130    stack, and the next throw which is supposed to go to an enclosing try would
  131    instead go to this try, possibly after the enclosing function has returned.
  132    Mayhem will then ensue.  This may be caught by the longjmp() implementation,
  133    which would report "longjmp botch" and then abort.
  134 
  135    Any local automatic storage variables that are modified in the try block and
  136    used in the catch or always block must be declared volatile.  Otherwise
  137    their value in the catch or always block is indeterminate.  Alternatively, a
  138    preserve block can be inserted after an automatic storage variable is
  139    changed in a try block.  The preserve block saves the state of those
  140    variables at the moment preserve is executed, and effectively continues the
  141    try block.  The same admonition then applies to variables modified in the
  142    preserve block.  The only assurance is that the catch and always block will
  143    have the values of the local automatic storage variables as they were at the
  144    time of the last try or preserve statement, but only if they have not been
  145    modified since the last try or preserve statement.  As many preserve blocks
  146    as desired are permitted.
  147 
  148    Any statements between try and always, between try and catch if there is no
  149    always, or between always and catch are part of those respective try or
  150    always blocks.  Use of { } to enclose those blocks is optional, but { }
  151    should be used anyway for clarity, style, and to inform smart source editors
  152    that the enclosed code is to be indented.  Enclosing the catch block with {
  153    } is not optional if there is more than one statement in the block.
  154    However, even if there is just one statement in the catch block, it should
  155    be enclosed in { } anyway for style and editing convenience.
  156 
  157    The contents of the ball_t structure after the first element (int code) can
  158    be customized for the application.  If ball_t is customized, then the code
  159    in try.c should be updated accordingly.  If there is no memory allocation in
  160    throw(), then drop() can be eliminated.
  161 
  162 
  163    Summary:
  164 
  165    Here is the permitted structure, where [] means an optional element
  166    permitted once, and []* means an optional element permitted more than once:
  167 
  168    try { body } [preserve { body }]* [always { clean }] catch (ball) { action }
  169 
  170    body must not contain a goto or return that exits body.  ball must be a
  171    variable of the type ball_t.  "action" must always execute either a
  172    drop(ball) or a punt(ball).
  173 
  174    A throw() may be executed in body or at any level of functions called by
  175    body, and will be processed by the innermost enclosing try in the same
  176    thread:
  177 
  178        throw(code);
  179 
  180    or,
  181 
  182        throw(code, "string");
  183 
  184    or,
  185 
  186        throw(code, "format string", ...);
  187 
  188    A throw() whose first argument is not zero, and that is caught by this try,
  189    will execute "clean" followed by "action".  Either a throw() whose first
  190    argument is zero and caught by this try, or the normal completion of body,
  191    results in the execution of just "clean", with execution continuing after
  192    the catch block.  If "action" does not execute a punt(ball), then execution
  193    continues after the catch block.  If "action" does execute a punt(ball),
  194    then what was caught is thrown to the next enclosing try.
  195 
  196    A '} preserve {' must be inserted in body after any local automatic storage
  197    variable is changed in body that can be used in the always or catch block.
  198    Alternatively, such variables may be declared volatile.  However the use of
  199    volatile can limit optimization, and has a tendency to propagate compiler
  200    warnings.
  201 
  202 
  203    Example usage:
  204 
  205     ball_t err;
  206     char *temp = NULL;
  207     try {
  208         ... do something ...
  209         if (ret == -1)
  210             throw(1, "bad thing happened to %s\n", me);
  211         temp = malloc(sizeof(me) + 1);
  212     }
  213     preserve {
  214         if (temp == NULL)
  215             throw(2, "out of memory");
  216         ... do more ...
  217         if (ret == -1)
  218             throw(3, "worse thing happened to %s\n", temp);
  219         ... some more code ...
  220     }
  221     always {
  222         free(temp);
  223     }
  224     catch (err) {
  225         fputs(err.why, stderr);
  226         drop(err);
  227         return err.code;
  228     }
  229     ... end up here if nothing bad happened ...
  230 
  231 
  232    More involved example:
  233 
  234     void check_part(void)
  235     {
  236         ball_t err;
  237 
  238         try {
  239             ...
  240             if (part == bad1)
  241                 throw(1);
  242             ...
  243             if (part == bad2)
  244                 throw(1);
  245             ...
  246         }
  247         catch (err) {
  248             drop(err);
  249             throw(3, "part was bad");
  250         }
  251     }
  252 
  253     void check_input(void)
  254     {
  255         ...
  256         if (input == wrong)
  257             throw(4, "input was wrong");
  258         ...
  259         if (input == stupid)
  260             throw(5, "input was stupid");
  261         ...
  262         check_part();
  263         ...
  264     }
  265 
  266     void *build_something(void)
  267     {
  268         ball_t err;
  269         volatile void *thing;
  270         try {
  271             thing = malloc(sizeof(struct thing));
  272             ... build up thing ...
  273             check_input();
  274             ... finish building it ...
  275         }
  276         catch (err) {
  277             free(thing);
  278             punt(err);
  279         }
  280         return thing;
  281     }
  282 
  283     int grand_central(void)
  284     {
  285         ball_t err;
  286         void *thing;
  287         try {
  288             thing = build_something();
  289         }
  290         catch (err) {
  291             fputs(err.why, stderr);
  292             drop(err);
  293             return err.code;
  294         }
  295         ... use thing ...
  296         free(thing);
  297         return 0;
  298     }
  299 
  300  */
  301 
  302 #ifndef _TRY_H
  303 #define _TRY_H
  304 
  305 #include <stdlib.h>
  306 #include <string.h>
  307 #include <assert.h>
  308 #include <setjmp.h>
  309 
  310 /* If a POSIX pthread library is not available, then compile with NOTHREAD
  311    defined. */
  312 #ifndef NOTHREAD
  313 #  include <pthread.h>
  314 #endif
  315 
  316 /* The exposed names can be changed here. */
  317 #define ball_t try_ball_t_
  318 #define try TRY_TRY_
  319 #define preserve TRY_PRESERVE_
  320 #define always TRY_ALWAYS_
  321 #define catch TRY_CATCH_
  322 #define throw TRY_THROW_
  323 #define punt TRY_PUNT_
  324 #define drop TRY_DROP_
  325 
  326 /* Package of an integer code and any other data to be thrown and caught. Here,
  327    why is a string with information to be displayed to indicate why an
  328    exception was thrown.  free is true if why was allocated and should be freed
  329    when no longer needed.  This structure can be customized as needed, but it
  330    must start with an int code.  If it is customized, the try_throw_() function
  331    in try.c must also be updated accordingly.  As an example, why could be a
  332    structure with information for use in the catch block. */
  333 typedef struct {
  334     int ret;            /* longjmp() return value */
  335     int code;           /* integer code (required) */
  336     int free;           /* if true, the message string was allocated */
  337     char *why;          /* informational string or NULL */
  338 } try_ball_t_;
  339 
  340 /* Element in the global try stack (a linked list). */
  341 typedef struct try_s_ try_t_;
  342 struct try_s_ {
  343     jmp_buf env;        /* state information for longjmp() to jump back */
  344     try_ball_t_ ball;   /* data passed from the throw() */
  345     try_t_ *next;       /* link to the next enclosing try_t, or NULL */
  346 };
  347 
  348 /* Global try stack.  try.c must be compiled and linked to provide the stack
  349    pointer.  Use thread-local storage if pthread.h is included before this.
  350    Note that a throw can only be caught within the same thread.  A new and
  351    unique try stack is created for each thread, so any attempt to throw across
  352    threads will fail with an assert, by virtue of reaching the end of the
  353    stack. */
  354 #ifdef PTHREAD_ONCE_INIT
  355     extern pthread_key_t try_key_;
  356     void try_setup_(void);
  357 #   define try_stack_ ((try_t_ *)pthread_getspecific(try_key_))
  358 #   define try_stack_set_(next) \
  359         do { \
  360             int ret = pthread_setspecific(try_key_, next); \
  361             assert(ret == 0 && "try: pthread_setspecific() failed"); \
  362         } while (0)
  363 #else /* !PTHREAD_ONCE_INIT */
  364     extern try_t_ *try_stack_;
  365 #   define try_setup_()
  366 #   define try_stack_set_(next) try_stack_ = (next)
  367 #endif /* PTHREAD_ONCE_INIT */
  368 
  369 /* Try a block.  The block should follow the invocation of try enclosed in { }.
  370    The block must be immediately followed by a preserve, always, or catch.  You
  371    must not goto or return out of the try block.  A naked break or continue in
  372    the try block will go to the end of the block. */
  373 #define TRY_TRY_ \
  374     do { \
  375         try_t_ try_this_; \
  376         volatile int try_pushed_ = 1; \
  377         try_this_.ball.ret = 0; \
  378         try_this_.ball.code = 0; \
  379         try_this_.ball.free = 0; \
  380         try_this_.ball.why = NULL; \
  381         try_setup_(); \
  382         try_this_.next = try_stack_; \
  383         try_stack_set_(&try_this_); \
  384         if (setjmp(try_this_.env) == 0) \
  385             do { \
  386 
  387 /* Preserve local automatic variables that were changed in the try block by
  388    reissuing the setjmp(), replacing the state for the next longjmp().  The
  389    preserve block should be enclosed in { }.  The block must be immediately
  390    followed by a preserve, always, or catch.  You must not goto or return out
  391    of the preserve block.  A naked break or continue in the preserve block will
  392    go to the end of the block.  This can only follow a try or another preserve.
  393    preserve effectively saves the state of local automatic variables at threat,
  394    i.e. the register state, at that point so that a subsequent throw() will
  395    restore those variables to that state for the always and catch blocks.
  396    Changes to those variables after the preserve statement may or may not be
  397    reflected in the always and catch blocks. */
  398 #define TRY_PRESERVE_ \
  399             } while (0); \
  400         if (try_this_.ball.ret == 0) if (setjmp(try_this_.env) == 0) \
  401             do { \
  402 
  403 /* Execute the code between always and catch, whether or not something was
  404    thrown.  An always block is optional.  If present, the always block must
  405    follow a try or preserve block and be followed by a catch block.  The always
  406    block should be enclosed in { }.  A naked break or continue in the always
  407    block will go to the end of the block.  It is permitted to use throw in the
  408    always block, which will fall up to the next enclosing try.  However this
  409    will result in a memory leak if the original throw() allocated space for the
  410    informational string.  So it's best to not throw() in an always block.  Keep
  411    the always block simple.
  412 
  413    Great care must be taken if the always block uses an automatic storage
  414    variable local to the enclosing function that can be modified in the try
  415    block.  Such variables must be declared volatile.  If such a variable is not
  416    declared volatile, and if the compiler elects to keep that variable in a
  417    register, then the throw will restore that variable to its state at the
  418    beginning of the try block, wiping out any change that occurred in the try
  419    block.  This can cause very confusing bugs until you remember that you
  420    didn't follow this rule. */
  421 #define TRY_ALWAYS_ \
  422             } while (0); \
  423         if (try_pushed_) { \
  424             try_stack_set_(try_this_.next); \
  425             try_pushed_ = 0; \
  426         } \
  427         if (1) \
  428             do {
  429 
  430 /* Catch an error thrown in the preceding try block.  The catch block must
  431    follow catch and its parameter, and must be enclosed in { }.  The catch must
  432    immediately follow a try, preserve, or always block.  It is permitted to use
  433    throw() in the catch block, which will fall up to the next enclosing try.
  434    However the ball_t passed by throw() must be freed using drop() before doing
  435    another throw, to avoid a potential memory leak. The parameter of catch must
  436    be a ball_t declared in the function or block containing the catch.  It is
  437    set to the parameters of the throw() that jumped to the catch.  The catch
  438    block is not executed if the first parameter of the throw() was zero.
  439 
  440    A catch block should end with either a punt() or a drop().
  441 
  442    Great care must be taken if the catch block uses an automatic storage
  443    variable local to the enclosing function that can be modified in the try
  444    block.  Such variables must be declared volatile or preserve must be used to
  445    save their state.  If such a variable is not declared volatile, and if the
  446    compiler elects to keep that variable in a register, then the throw will
  447    restore that variable to its state at the beginning of the most recent try
  448    or preserve block, wiping out any change that occurred after the start of
  449    that block.  This can cause very confusing bugs until you remember that you
  450    didn't follow this rule. */
  451 #define TRY_CATCH_(try_ball_) \
  452             } while (0); \
  453         if (try_pushed_) { \
  454             try_stack_set_(try_this_.next); \
  455             try_pushed_ = 0; \
  456         } \
  457         try_ball_ = try_this_.ball; \
  458     } while (0); \
  459     if (try_ball_.code)
  460 
  461 /* Throw an error.  This can be in the try block or in any function called from
  462    the try block, at any level of nesting.  This will fall back to the end of
  463    the first enclosing try block in the same thread, invoking the associated
  464    catch block with a ball_t set to the arguments of throw().  throw() will
  465    abort the program with an assert() if there is no nesting try.  Make sure
  466    that there's a nesting try!
  467 
  468    try may have one or more arguments, where the first argument is an int, the
  469    optional second argument is a string, and the remaining optional arguments
  470    are referred to by printf() formatting commands in the string.  If there are
  471    formatting commands in the string, i.e. any percent (%) signs, then
  472    vsnprintf() is used to generate the formatted string from the arguments
  473    before jumping to the enclosing try block.  This allows throw() to use
  474    information on the stack in the scope of the throw() statement, which will
  475    be lost after jumping back to the enclosing try block.  That formatted
  476    string will use allocated memory, which is why it is important to use drop()
  477    in catch blocks to free that memory, or punt() to pass the string on to
  478    another catch block.  Eventually some catch block down the chain will have
  479    to drop() it.
  480 
  481    If a memory allocation fails during the execution of a throw(), then the
  482    string provided to the catch block is not the formatted string at all, but
  483    rather the string: "try: out of memory", with the integer code from the
  484    throw() unchanged.
  485 
  486    If the first argument of throw is zero, then the catch block is not
  487    executed.  A throw(0) from a function called in the try block is equivalent
  488    to a break or continue in the try block.  A throw(0) should not have any
  489    other arguments, to avoid a potential memory leak.  There is no opportunity
  490    to make use of any arguments after the 0 anyway.
  491 
  492    try.c must be compiled and linked to provide the try_throw_() function. */
  493 void try_throw_(int code, char *fmt, ...)
  494 #if defined(__GNUC__) || defined(__has_builtin)
  495                                                 __attribute__((noreturn))
  496 #endif
  497     ;
  498 
  499 #define TRY_THROW_(...) try_throw_(__VA_ARGS__, NULL)
  500 
  501 /* Punt a caught error on to the next enclosing catcher.  This is normally used
  502    in a catch block with same argument as the catch. */
  503 #define TRY_PUNT_(try_ball_) \
  504     do { \
  505         try_setup_(); \
  506         assert(try_stack_ != NULL && "try: naked punt"); \
  507         try_stack_->ball = try_ball_; \
  508         longjmp(try_stack_->env, 1); \
  509     } while (0)
  510 
  511 /* Clean up at the end of the line in a catch (no more punts). */
  512 #define TRY_DROP_(try_ball_) \
  513     do { \
  514         if (try_ball_.free) { \
  515             free(try_ball_.why); \
  516             try_ball_.free = 0; \
  517             try_ball_.why = NULL; \
  518         } \
  519     } while (0)
  520 
  521 #endif /* _TRY_H */