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