Home | History | Annotate | Download | only in lib
      1 /* obstack.c - subroutines used implicitly by object stack macros
      2 
      3    Copyright (C) 1988-1994, 1996-2006, 2009-2012 Free Software Foundation, Inc.
      4 
      5    This program is free software: you can redistribute it and/or modify
      6    it under the terms of the GNU General Public License as published by
      7    the Free Software Foundation; either version 3 of the License, or
      8    (at your option) any later version.
      9 
     10    This program is distributed in the hope that it will be useful,
     11    but WITHOUT ANY WARRANTY; without even the implied warranty of
     12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     13    GNU General Public License for more details.
     14 
     15    You should have received a copy of the GNU General Public License
     16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
     17 
     18 #ifdef _LIBC
     19 # include <obstack.h>
     20 # include <shlib-compat.h>
     21 #else
     22 # include <config.h>
     23 # include "obstack.h"
     24 #endif
     25 
     26 /* NOTE BEFORE MODIFYING THIS FILE: This version number must be
     27    incremented whenever callers compiled using an old obstack.h can no
     28    longer properly call the functions in this obstack.c.  */
     29 #define OBSTACK_INTERFACE_VERSION 1
     30 
     31 /* Comment out all this code if we are using the GNU C Library, and are not
     32    actually compiling the library itself, and the installed library
     33    supports the same library interface we do.  This code is part of the GNU
     34    C Library, but also included in many other GNU distributions.  Compiling
     35    and linking in this code is a waste when using the GNU C library
     36    (especially if it is a shared library).  Rather than having every GNU
     37    program understand 'configure --with-gnu-libc' and omit the object
     38    files, it is simpler to just do this in the source for each such file.  */
     39 
     40 #include <stdio.h>              /* Random thing to get __GNU_LIBRARY__.  */
     41 #if !defined _LIBC && defined __GNU_LIBRARY__ && __GNU_LIBRARY__ > 1
     42 # include <gnu-versions.h>
     43 # if _GNU_OBSTACK_INTERFACE_VERSION == OBSTACK_INTERFACE_VERSION
     44 #  define ELIDE_CODE
     45 # endif
     46 #endif
     47 
     48 #include <stddef.h>
     49 
     50 #ifndef ELIDE_CODE
     51 
     52 # include <stdint.h>
     53 
     54 /* Determine default alignment.  */
     55 union fooround
     56 {
     57   uintmax_t i;
     58   long double d;
     59   void *p;
     60 };
     61 struct fooalign
     62 {
     63   char c;
     64   union fooround u;
     65 };
     66 /* If malloc were really smart, it would round addresses to DEFAULT_ALIGNMENT.
     67    But in fact it might be less smart and round addresses to as much as
     68    DEFAULT_ROUNDING.  So we prepare for it to do that.  */
     69 enum
     70   {
     71     DEFAULT_ALIGNMENT = offsetof (struct fooalign, u),
     72     DEFAULT_ROUNDING = sizeof (union fooround)
     73   };
     74 
     75 /* When we copy a long block of data, this is the unit to do it with.
     76    On some machines, copying successive ints does not work;
     77    in such a case, redefine COPYING_UNIT to 'long' (if that works)
     78    or 'char' as a last resort.  */
     79 # ifndef COPYING_UNIT
     80 #  define COPYING_UNIT int
     81 # endif
     82 
     83 
     84 /* The functions allocating more room by calling 'obstack_chunk_alloc'
     85    jump to the handler pointed to by 'obstack_alloc_failed_handler'.
     86    This can be set to a user defined function which should either
     87    abort gracefully or use longjump - but shouldn't return.  This
     88    variable by default points to the internal function
     89    'print_and_abort'.  */
     90 static _Noreturn void print_and_abort (void);
     91 void (*obstack_alloc_failed_handler) (void) = print_and_abort;
     92 
     93 /* Exit value used when 'print_and_abort' is used.  */
     94 # include <stdlib.h>
     95 # ifdef _LIBC
     96 int obstack_exit_failure = EXIT_FAILURE;
     97 # else
     98 #  include "exitfail.h"
     99 #  define obstack_exit_failure exit_failure
    100 # endif
    101 
    102 # ifdef _LIBC
    103 #  if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_3_4)
    104 /* A looong time ago (before 1994, anyway; we're not sure) this global variable
    105    was used by non-GNU-C macros to avoid multiple evaluation.  The GNU C
    106    library still exports it because somebody might use it.  */
    107 struct obstack *_obstack_compat;
    108 compat_symbol (libc, _obstack_compat, _obstack, GLIBC_2_0);
    109 #  endif
    110 # endif
    111 
    112 /* Define a macro that either calls functions with the traditional malloc/free
    113    calling interface, or calls functions with the mmalloc/mfree interface
    114    (that adds an extra first argument), based on the state of use_extra_arg.
    115    For free, do not use ?:, since some compilers, like the MIPS compilers,
    116    do not allow (expr) ? void : void.  */
    117 
    118 # define CALL_CHUNKFUN(h, size) \
    119   (((h) -> use_extra_arg) \
    120    ? (*(h)->chunkfun) ((h)->extra_arg, (size)) \
    121    : (*(struct _obstack_chunk *(*) (long)) (h)->chunkfun) ((size)))
    122 
    123 # define CALL_FREEFUN(h, old_chunk) \
    124   do { \
    125     if ((h) -> use_extra_arg) \
    126       (*(h)->freefun) ((h)->extra_arg, (old_chunk)); \
    127     else \
    128       (*(void (*) (void *)) (h)->freefun) ((old_chunk)); \
    129   } while (0)
    130 
    131 
    132 /* Initialize an obstack H for use.  Specify chunk size SIZE (0 means default).
    134    Objects start on multiples of ALIGNMENT (0 means use default).
    135    CHUNKFUN is the function to use to allocate chunks,
    136    and FREEFUN the function to free them.
    137 
    138    Return nonzero if successful, calls obstack_alloc_failed_handler if
    139    allocation fails.  */
    140 
    141 int
    142 _obstack_begin (struct obstack *h,
    143                 int size, int alignment,
    144                 void *(*chunkfun) (long),
    145                 void (*freefun) (void *))
    146 {
    147   register struct _obstack_chunk *chunk; /* points to new chunk */
    148 
    149   if (alignment == 0)
    150     alignment = DEFAULT_ALIGNMENT;
    151   if (size == 0)
    152     /* Default size is what GNU malloc can fit in a 4096-byte block.  */
    153     {
    154       /* 12 is sizeof (mhead) and 4 is EXTRA from GNU malloc.
    155          Use the values for range checking, because if range checking is off,
    156          the extra bytes won't be missed terribly, but if range checking is on
    157          and we used a larger request, a whole extra 4096 bytes would be
    158          allocated.
    159 
    160          These number are irrelevant to the new GNU malloc.  I suspect it is
    161          less sensitive to the size of the request.  */
    162       int extra = ((((12 + DEFAULT_ROUNDING - 1) & ~(DEFAULT_ROUNDING - 1))
    163                     + 4 + DEFAULT_ROUNDING - 1)
    164                    & ~(DEFAULT_ROUNDING - 1));
    165       size = 4096 - extra;
    166     }
    167 
    168   h->chunkfun = (struct _obstack_chunk * (*)(void *, long)) chunkfun;
    169   h->freefun = (void (*) (void *, struct _obstack_chunk *)) freefun;
    170   h->chunk_size = size;
    171   h->alignment_mask = alignment - 1;
    172   h->use_extra_arg = 0;
    173 
    174   chunk = h->chunk = CALL_CHUNKFUN (h, h -> chunk_size);
    175   if (!chunk)
    176     (*obstack_alloc_failed_handler) ();
    177   h->next_free = h->object_base = __PTR_ALIGN ((char *) chunk, chunk->contents,
    178                                                alignment - 1);
    179   h->chunk_limit = chunk->limit
    180     = (char *) chunk + h->chunk_size;
    181   chunk->prev = 0;
    182   /* The initial chunk now contains no empty object.  */
    183   h->maybe_empty_object = 0;
    184   h->alloc_failed = 0;
    185   return 1;
    186 }
    187 
    188 int
    189 _obstack_begin_1 (struct obstack *h, int size, int alignment,
    190                   void *(*chunkfun) (void *, long),
    191                   void (*freefun) (void *, void *),
    192                   void *arg)
    193 {
    194   register struct _obstack_chunk *chunk; /* points to new chunk */
    195 
    196   if (alignment == 0)
    197     alignment = DEFAULT_ALIGNMENT;
    198   if (size == 0)
    199     /* Default size is what GNU malloc can fit in a 4096-byte block.  */
    200     {
    201       /* 12 is sizeof (mhead) and 4 is EXTRA from GNU malloc.
    202          Use the values for range checking, because if range checking is off,
    203          the extra bytes won't be missed terribly, but if range checking is on
    204          and we used a larger request, a whole extra 4096 bytes would be
    205          allocated.
    206 
    207          These number are irrelevant to the new GNU malloc.  I suspect it is
    208          less sensitive to the size of the request.  */
    209       int extra = ((((12 + DEFAULT_ROUNDING - 1) & ~(DEFAULT_ROUNDING - 1))
    210                     + 4 + DEFAULT_ROUNDING - 1)
    211                    & ~(DEFAULT_ROUNDING - 1));
    212       size = 4096 - extra;
    213     }
    214 
    215   h->chunkfun = (struct _obstack_chunk * (*)(void *,long)) chunkfun;
    216   h->freefun = (void (*) (void *, struct _obstack_chunk *)) freefun;
    217   h->chunk_size = size;
    218   h->alignment_mask = alignment - 1;
    219   h->extra_arg = arg;
    220   h->use_extra_arg = 1;
    221 
    222   chunk = h->chunk = CALL_CHUNKFUN (h, h -> chunk_size);
    223   if (!chunk)
    224     (*obstack_alloc_failed_handler) ();
    225   h->next_free = h->object_base = __PTR_ALIGN ((char *) chunk, chunk->contents,
    226                                                alignment - 1);
    227   h->chunk_limit = chunk->limit
    228     = (char *) chunk + h->chunk_size;
    229   chunk->prev = 0;
    230   /* The initial chunk now contains no empty object.  */
    231   h->maybe_empty_object = 0;
    232   h->alloc_failed = 0;
    233   return 1;
    234 }
    235 
    236 /* Allocate a new current chunk for the obstack *H
    237    on the assumption that LENGTH bytes need to be added
    238    to the current object, or a new object of length LENGTH allocated.
    239    Copies any partial object from the end of the old chunk
    240    to the beginning of the new one.  */
    241 
    242 void
    243 _obstack_newchunk (struct obstack *h, int length)
    244 {
    245   register struct _obstack_chunk *old_chunk = h->chunk;
    246   register struct _obstack_chunk *new_chunk;
    247   register long new_size;
    248   register long obj_size = h->next_free - h->object_base;
    249   register long i;
    250   long already;
    251   char *object_base;
    252 
    253   /* Compute size for new chunk.  */
    254   new_size = (obj_size + length) + (obj_size >> 3) + h->alignment_mask + 100;
    255   if (new_size < h->chunk_size)
    256     new_size = h->chunk_size;
    257 
    258   /* Allocate and initialize the new chunk.  */
    259   new_chunk = CALL_CHUNKFUN (h, new_size);
    260   if (!new_chunk)
    261     (*obstack_alloc_failed_handler) ();
    262   h->chunk = new_chunk;
    263   new_chunk->prev = old_chunk;
    264   new_chunk->limit = h->chunk_limit = (char *) new_chunk + new_size;
    265 
    266   /* Compute an aligned object_base in the new chunk */
    267   object_base =
    268     __PTR_ALIGN ((char *) new_chunk, new_chunk->contents, h->alignment_mask);
    269 
    270   /* Move the existing object to the new chunk.
    271      Word at a time is fast and is safe if the object
    272      is sufficiently aligned.  */
    273   if (h->alignment_mask + 1 >= DEFAULT_ALIGNMENT)
    274     {
    275       for (i = obj_size / sizeof (COPYING_UNIT) - 1;
    276            i >= 0; i--)
    277         ((COPYING_UNIT *)object_base)[i]
    278           = ((COPYING_UNIT *)h->object_base)[i];
    279       /* We used to copy the odd few remaining bytes as one extra COPYING_UNIT,
    280          but that can cross a page boundary on a machine
    281          which does not do strict alignment for COPYING_UNITS.  */
    282       already = obj_size / sizeof (COPYING_UNIT) * sizeof (COPYING_UNIT);
    283     }
    284   else
    285     already = 0;
    286   /* Copy remaining bytes one by one.  */
    287   for (i = already; i < obj_size; i++)
    288     object_base[i] = h->object_base[i];
    289 
    290   /* If the object just copied was the only data in OLD_CHUNK,
    291      free that chunk and remove it from the chain.
    292      But not if that chunk might contain an empty object.  */
    293   if (! h->maybe_empty_object
    294       && (h->object_base
    295           == __PTR_ALIGN ((char *) old_chunk, old_chunk->contents,
    296                           h->alignment_mask)))
    297     {
    298       new_chunk->prev = old_chunk->prev;
    299       CALL_FREEFUN (h, old_chunk);
    300     }
    301 
    302   h->object_base = object_base;
    303   h->next_free = h->object_base + obj_size;
    304   /* The new chunk certainly contains no empty object yet.  */
    305   h->maybe_empty_object = 0;
    306 }
    307 # ifdef _LIBC
    308 libc_hidden_def (_obstack_newchunk)
    309 # endif
    310 
    311 /* Return nonzero if object OBJ has been allocated from obstack H.
    312    This is here for debugging.
    313    If you use it in a program, you are probably losing.  */
    314 
    315 /* Suppress -Wmissing-prototypes warning.  We don't want to declare this in
    316    obstack.h because it is just for debugging.  */
    317 int _obstack_allocated_p (struct obstack *h, void *obj);
    318 
    319 int
    320 _obstack_allocated_p (struct obstack *h, void *obj)
    321 {
    322   register struct _obstack_chunk *lp;   /* below addr of any objects in this chunk */
    323   register struct _obstack_chunk *plp;  /* point to previous chunk if any */
    324 
    325   lp = (h)->chunk;
    326   /* We use >= rather than > since the object cannot be exactly at
    327      the beginning of the chunk but might be an empty object exactly
    328      at the end of an adjacent chunk.  */
    329   while (lp != 0 && ((void *) lp >= obj || (void *) (lp)->limit < obj))
    330     {
    331       plp = lp->prev;
    332       lp = plp;
    333     }
    334   return lp != 0;
    335 }
    336 
    337 /* Free objects in obstack H, including OBJ and everything allocate
    339    more recently than OBJ.  If OBJ is zero, free everything in H.  */
    340 
    341 # undef obstack_free
    342 
    343 void
    344 __obstack_free (struct obstack *h, void *obj)
    345 {
    346   register struct _obstack_chunk *lp;   /* below addr of any objects in this chunk */
    347   register struct _obstack_chunk *plp;  /* point to previous chunk if any */
    348 
    349   lp = h->chunk;
    350   /* We use >= because there cannot be an object at the beginning of a chunk.
    351      But there can be an empty object at that address
    352      at the end of another chunk.  */
    353   while (lp != 0 && ((void *) lp >= obj || (void *) (lp)->limit < obj))
    354     {
    355       plp = lp->prev;
    356       CALL_FREEFUN (h, lp);
    357       lp = plp;
    358       /* If we switch chunks, we can't tell whether the new current
    359          chunk contains an empty object, so assume that it may.  */
    360       h->maybe_empty_object = 1;
    361     }
    362   if (lp)
    363     {
    364       h->object_base = h->next_free = (char *) (obj);
    365       h->chunk_limit = lp->limit;
    366       h->chunk = lp;
    367     }
    368   else if (obj != 0)
    369     /* obj is not in any of the chunks! */
    370     abort ();
    371 }
    372 
    373 # ifdef _LIBC
    374 /* Older versions of libc used a function _obstack_free intended to be
    375    called by non-GCC compilers.  */
    376 strong_alias (obstack_free, _obstack_free)
    377 # endif
    378 
    379 int
    381 _obstack_memory_used (struct obstack *h)
    382 {
    383   register struct _obstack_chunk* lp;
    384   register int nbytes = 0;
    385 
    386   for (lp = h->chunk; lp != 0; lp = lp->prev)
    387     {
    388       nbytes += lp->limit - (char *) lp;
    389     }
    390   return nbytes;
    391 }
    392 
    393 /* Define the error handler.  */
    395 # ifdef _LIBC
    396 #  include <libintl.h>
    397 # else
    398 #  include "gettext.h"
    399 # endif
    400 # ifndef _
    401 #  define _(msgid) gettext (msgid)
    402 # endif
    403 
    404 # ifdef _LIBC
    405 #  include <libio/iolibio.h>
    406 # endif
    407 
    408 static _Noreturn void
    409 print_and_abort (void)
    410 {
    411   /* Don't change any of these strings.  Yes, it would be possible to add
    412      the newline to the string and use fputs or so.  But this must not
    413      happen because the "memory exhausted" message appears in other places
    414      like this and the translation should be reused instead of creating
    415      a very similar string which requires a separate translation.  */
    416 # ifdef _LIBC
    417   (void) __fxprintf (NULL, "%s\n", _("memory exhausted"));
    418 # else
    419   fprintf (stderr, "%s\n", _("memory exhausted"));
    420 # endif
    421   exit (obstack_exit_failure);
    422 }
    423 
    424 #endif  /* !ELIDE_CODE */
    425