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