pool: Support null 'pool' argument in pool_vasprintf().
[pspp] / src / libpspp / pool.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2000, 2010, 2011, 2012 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "libpspp/pool.h"
20
21 #include <stdint.h>
22 #include <stdlib.h>
23
24 #include "libpspp/assertion.h"
25 #include "libpspp/message.h"
26 #include "libpspp/temp-file.h"
27 #include "libpspp/str.h"
28
29 #include "gl/xalloc-oversized.h"
30 #include "gl/xalloc.h"
31
32 /* Fast, low-overhead memory block suballocator. */
33 struct pool
34   {
35     struct pool *parent;        /* Pool of which this pool is a subpool. */
36     struct pool_block *blocks;  /* Blocks owned by the pool. */
37     struct pool_gizmo *gizmos;  /* Other stuff owned by the pool. */
38   };
39
40 /* Pool block. */
41 struct pool_block
42   {
43     struct pool_block *prev;
44     struct pool_block *next;
45     size_t ofs;
46   };
47
48 /* Gizmo types. */
49 enum
50   {
51     POOL_GIZMO_MALLOC,
52     POOL_GIZMO_FILE,
53     POOL_GIZMO_TEMP_FILE,
54     POOL_GIZMO_SUBPOOL,
55     POOL_GIZMO_REGISTERED,
56   };
57
58 /* Pool routines can maintain objects (`gizmos') as well as doing
59    suballocation.
60    This structure is used to keep track of them. */
61 struct pool_gizmo
62   {
63     struct pool *pool;
64     struct pool_gizmo *prev;
65     struct pool_gizmo *next;
66
67     long serial;                /* Serial number. */
68     int type;                   /* Type of this gizmo. */
69
70     /* Type-dependent info. */
71     union
72       {
73         FILE *file;             /* POOL_GIZMO_FILE, POOL_GIZMO_TEMP_FILE. */
74         struct pool *subpool;   /* POOL_GIZMO_SUBPOOL. */
75
76         /* POOL_GIZMO_REGISTERED. */
77         struct
78           {
79             void (*free) (void *p);
80             void *p;
81           }
82         registered;
83       }
84     p;
85   };
86
87 /* Rounds X up to the next multiple of Y. */
88 #ifndef ROUND_UP
89 #define ROUND_UP(X, Y)                          \
90         (((X) + ((Y) - 1)) / (Y) * (Y))
91 #endif
92
93 /* Types that provide typically useful alignment sizes. */
94 union align
95   {
96     void *op;
97     void (*fp) (void);
98     long l;
99     double d;
100
101     /* glibc jmp_buf on ia64 requires 16-byte alignment.  This ensures it. */
102     size_t s[2];
103   };
104
105 /* This should be the alignment size used by malloc().  The size of
106    the union above is correct, if not optimal, in all known cases.
107
108    This is normally 8 bytes for 32-bit architectures and 16 bytes for 64-bit
109    architectures. */
110 #define ALIGN_SIZE sizeof (union align)
111
112 /* DISCRETE_BLOCKS may be declared as nonzero to prevent
113    suballocation of blocks.  This is useful under memory
114    debuggers like valgrind because it allows the source location
115    of bugs to be more accurately pinpointed.
116
117    On the other hand, if we're testing the library, then we want to
118    test the library's real functionality, not its crippled, slow,
119    simplified functionality. */
120 /*#define DISCRETE_BLOCKS 1*/
121
122 /* Size of each block allocated in the pool, in bytes.
123    Should be at least 1k. */
124 #ifndef BLOCK_SIZE
125 #define BLOCK_SIZE 1024
126 #endif
127
128
129 /* Sizes of some structures with alignment padding included. */
130 #define POOL_BLOCK_SIZE ROUND_UP (sizeof (struct pool_block), ALIGN_SIZE)
131 #define POOL_GIZMO_SIZE ROUND_UP (sizeof (struct pool_gizmo), ALIGN_SIZE)
132 #define POOL_SIZE ROUND_UP (sizeof (struct pool), ALIGN_SIZE)
133
134 /* Serial number used to keep track of gizmos for mark/release. */
135 static long serial = 0;
136
137 /* Prototypes. */
138 static void add_gizmo (struct pool *, struct pool_gizmo *);
139 static void free_gizmo (struct pool_gizmo *);
140 static void free_all_gizmos (struct pool *pool);
141 static void delete_gizmo (struct pool *, struct pool_gizmo *);
142 static void check_gizmo (struct pool *, struct pool_gizmo *);
143 \f
144 /* General routines. */
145
146 /* Creates and returns a new memory pool, which allows malloc()'d
147    blocks to be suballocated in a time- and space-efficient manner.
148    The entire contents of the memory pool are freed at once.
149
150    In addition, other objects can be associated with a memory pool.
151    These are released when the pool is destroyed. */
152 struct pool *
153 pool_create (void)
154 {
155   struct pool_block *block;
156   struct pool *pool;
157
158   block = xmalloc (BLOCK_SIZE);
159   block->prev = block->next = block;
160   block->ofs = POOL_BLOCK_SIZE + POOL_SIZE;
161
162   pool = (struct pool *) (((char *) block) + POOL_BLOCK_SIZE);
163   pool->parent = NULL;
164   pool->blocks = block;
165   pool->gizmos = NULL;
166
167   return pool;
168 }
169
170 /* Creates a pool, allocates a block STRUCT_SIZE bytes in
171    length from it, stores the pool's address at offset
172    POOL_MEMBER_OFFSET within the block, and returns the allocated
173    block.
174
175    Meant for use indirectly via pool_create_container(). */
176 void *
177 pool_create_at_offset (size_t struct_size, size_t pool_member_offset)
178 {
179   struct pool *pool;
180   char *struct_;
181
182   assert (struct_size >= sizeof pool);
183   assert (pool_member_offset <= struct_size - sizeof pool);
184
185   pool = pool_create ();
186   struct_ = pool_alloc (pool, struct_size);
187   *(struct pool **) (struct_ + pool_member_offset) = pool;
188   return struct_;
189 }
190
191 /* Destroy the specified pool, including all subpools. */
192 void
193 pool_destroy (struct pool *pool)
194 {
195   if (pool == NULL)
196     return;
197
198   /* Remove this pool from its parent's list of gizmos. */
199   if (pool->parent)
200     delete_gizmo (pool->parent, (void *) (((char *) pool) + POOL_SIZE));
201
202   free_all_gizmos (pool);
203
204   /* Free all the memory. */
205   {
206     struct pool_block *cur, *next;
207
208     pool->blocks->prev->next = NULL;
209     for (cur = pool->blocks; cur; cur = next)
210       {
211         next = cur->next;
212         free (cur);
213       }
214   }
215 }
216
217 /* Release all the memory and gizmos in POOL.
218    Blocks are not given back with free() but kept for later
219    allocations.  To give back memory, use a subpool instead. */
220 void
221 pool_clear (struct pool *pool)
222 {
223   free_all_gizmos (pool);
224
225   /* Zero out block sizes. */
226   {
227     struct pool_block *cur;
228
229     cur = pool->blocks;
230     do
231       {
232         cur->ofs = POOL_BLOCK_SIZE;
233         if ((char *) cur + POOL_BLOCK_SIZE == (char *) pool)
234           {
235             cur->ofs += POOL_SIZE;
236             if (pool->parent != NULL)
237               cur->ofs += POOL_GIZMO_SIZE;
238           }
239         cur = cur->next;
240       }
241     while (cur != pool->blocks);
242   }
243 }
244 \f
245 /* Suballocation routines. */
246
247 /* Allocates a memory region AMT bytes in size from POOL and returns a
248    pointer to the region's start.
249    The region is properly aligned for storing any object. */
250 void *
251 pool_alloc (struct pool *pool, size_t amt)
252 {
253   assert (pool != NULL);
254
255   if (amt == 0)
256     return NULL;
257
258 #ifndef DISCRETE_BLOCKS
259   if (amt <= MAX_SUBALLOC)
260     {
261       /* If there is space in this block, take it. */
262       struct pool_block *b = pool->blocks;
263       b->ofs = ROUND_UP (b->ofs, ALIGN_SIZE);
264       if (b->ofs + amt <= BLOCK_SIZE)
265         {
266           void *const p = ((char *) b) + b->ofs;
267           b->ofs += amt;
268           return p;
269         }
270
271       /* No space in this block, so we must make other
272          arrangements. */
273       if (b->next->ofs == 0)
274         {
275           /* The next block is empty.  Use it. */
276           b = b->next;
277           b->ofs = POOL_BLOCK_SIZE;
278           if ((char *) b + POOL_BLOCK_SIZE == (char *) pool)
279             b->ofs += POOL_SIZE;
280         }
281       else
282         {
283           /* Create a new block at the start of the list. */
284           b = xmalloc (BLOCK_SIZE);
285           b->next = pool->blocks;
286           b->prev = pool->blocks->prev;
287           b->ofs = POOL_BLOCK_SIZE;
288           pool->blocks->prev->next = b;
289           pool->blocks->prev = b;
290         }
291       pool->blocks = b;
292
293       /* Allocate space from B. */
294       b->ofs += amt;
295       return ((char *) b) + b->ofs - amt;
296     }
297   else
298 #endif
299     return pool_malloc (pool, amt);
300 }
301
302 /* Allocates a memory region AMT bytes in size from POOL and
303    returns a pointer to the region's start.  The region is not
304    necessarily aligned, so it is most suitable for storing
305    strings. */
306 void *
307 pool_alloc_unaligned (struct pool *pool, size_t amt)
308 {
309   if (pool == NULL)
310     return xmalloc (amt);
311
312 #ifndef DISCRETE_BLOCKS
313   /* Strings need not be aligned on any boundary, but some
314      operations may be more efficient when they are.  However,
315      that's only going to help with reasonably long strings. */
316   if (amt < ALIGN_SIZE)
317     {
318       if (amt == 0)
319         return NULL;
320       else
321         {
322           struct pool_block *const b = pool->blocks;
323
324           if (b->ofs + amt <= BLOCK_SIZE)
325             {
326               void *p = ((char *) b) + b->ofs;
327               b->ofs += amt;
328               return p;
329             }
330         }
331     }
332 #endif
333
334   return pool_alloc (pool, amt);
335 }
336
337 /* Allocates a memory region N * S bytes in size from POOL and
338    returns a pointer to the region's start.
339    N must be nonnegative, S must be positive.
340    Terminates the program if the memory cannot be obtained,
341    including the case where N * S overflows the range of size_t. */
342 void *
343 pool_nalloc (struct pool *pool, size_t n, size_t s)
344 {
345   if (xalloc_oversized (n, s))
346     xalloc_die ();
347   return pool_alloc (pool, n * s);
348 }
349
350 /* Allocates SIZE bytes in POOL, copies BUFFER into it, and
351    returns the new copy. */
352 void *
353 pool_clone (struct pool *pool, const void *buffer, size_t size)
354 {
355   void *block = pool_alloc (pool, size);
356   memcpy (block, buffer, size);
357   return block;
358 }
359
360 /* Allocates SIZE bytes of unaligned data in POOL, copies BUFFER
361    into it, and returns the new copy. */
362 void *
363 pool_clone_unaligned (struct pool *pool, const void *buffer, size_t size)
364 {
365   void *block = pool_alloc_unaligned (pool, size);
366   memcpy (block, buffer, size);
367   return block;
368 }
369
370 /* Duplicates null-terminated STRING, within POOL, and returns a
371    pointer to the duplicate.  For use only with strings, because
372    the returned pointere may not be aligned properly for other
373    types. */
374 char *
375 pool_strdup (struct pool *pool, const char *string)
376 {
377   return pool_clone_unaligned (pool, string, strlen (string) + 1);
378 }
379
380 /* Duplicates the SIZE bytes of STRING, plus a trailing 0 byte,
381    and returns a pointer to the duplicate.  For use only with
382    strings, because the returned pointere may not be aligned
383    properly for other types. */
384 char *
385 pool_memdup0 (struct pool *pool, const char *string, size_t size)
386 {
387   char *new_string = pool_alloc_unaligned (pool, size + 1);
388   memcpy (new_string, string, size);
389   new_string[size] = '\0';
390   return new_string;
391 }
392
393 /* Formats FORMAT with the given ARGS in memory allocated from
394    POOL and returns the formatted string. */
395 char *
396 pool_vasprintf (struct pool *pool, const char *format, va_list args_)
397 {
398   if (!pool)
399     return xvasprintf (format, args_);
400
401   struct pool_block *b;
402   va_list args;
403   int needed, avail;
404   char *s;
405
406   va_copy (args, args_);
407   b = pool->blocks;
408   avail = BLOCK_SIZE - b->ofs;
409   s = ((char *) b) + b->ofs;
410   needed = vsnprintf (s, avail, format, args);
411   va_end (args);
412
413   if (needed >= 0)
414     {
415       if (needed < avail)
416         {
417           /* Success.  Reserve the space that was actually used. */
418           b->ofs += needed + 1;
419         }
420       else
421         {
422           /* Failure, but now we know how much space is needed.
423              Allocate that much and reformat. */
424           s = pool_alloc (pool, needed + 1);
425
426           va_copy (args, args_);
427           vsprintf (s, format, args);
428           va_end (args);
429         }
430     }
431   else
432     {
433       /* Some old libc's returned -1 when the destination string
434          was too short.  This should be uncommon these days and
435          it's a rare case anyhow.  Use the easiest solution: punt
436          to dynamic allocation. */
437       va_copy (args, args_);
438       s = xvasprintf (format, args);
439       va_end (args);
440
441       pool_register (pool, free, s);
442     }
443
444   return s;
445 }
446
447 /* Formats FORMAT in memory allocated from POOL
448    and returns the formatted string. */
449 char *
450 pool_asprintf (struct pool *pool, const char *format, ...)
451 {
452   va_list args;
453   char *string;
454
455   va_start (args, format);
456   string = pool_vasprintf (pool, format, args);
457   va_end (args);
458
459   return string;
460 }
461 \f
462 /* Standard allocation routines. */
463
464 /* Allocates AMT bytes using malloc(), to be managed by POOL, and
465    returns a pointer to the beginning of the block.
466    If POOL is a null pointer, then allocates a normal memory block
467    with xmalloc().  */
468 void *
469 pool_malloc (struct pool *pool, size_t amt)
470 {
471   if (pool != NULL)
472     {
473       if (amt != 0)
474         {
475           struct pool_gizmo *g = xmalloc (amt + POOL_GIZMO_SIZE);
476           g->type = POOL_GIZMO_MALLOC;
477           add_gizmo (pool, g);
478
479           return ((char *) g) + POOL_GIZMO_SIZE;
480         }
481       else
482         return NULL;
483     }
484   else
485     return xmalloc (amt);
486 }
487
488 /* Allocates and returns N elements of S bytes each, to be
489    managed by POOL.
490    If POOL is a null pointer, then allocates a normal memory block
491    with malloc().
492    N must be nonnegative, S must be positive.
493    Terminates the program if the memory cannot be obtained,
494    including the case where N * S overflows the range of size_t. */
495 void *
496 pool_nmalloc (struct pool *pool, size_t n, size_t s)
497 {
498   if (xalloc_oversized (n, s))
499     xalloc_die ();
500   return pool_malloc (pool, n * s);
501 }
502
503 /* Allocates AMT bytes using malloc(), to be managed by POOL,
504    zeros the block, and returns a pointer to the beginning of the
505    block.
506    If POOL is a null pointer, then allocates a normal memory block
507    with xmalloc().  */
508 void *
509 pool_zalloc (struct pool *pool, size_t amt)
510 {
511   void *p = pool_malloc (pool, amt);
512   memset (p, 0, amt);
513   return p;
514 }
515
516 /* Allocates and returns N elements of S bytes each, to be
517    managed by POOL, and zeros the block.
518    If POOL is a null pointer, then allocates a normal memory block
519    with malloc().
520    N must be nonnegative, S must be positive.
521    Terminates the program if the memory cannot be obtained,
522    including the case where N * S overflows the range of size_t. */
523 void *
524 pool_calloc (struct pool *pool, size_t n, size_t s)
525 {
526   void *p = pool_nmalloc (pool, n, s);
527   memset (p, 0, n * s);
528   return p;
529 }
530
531 /* Changes the allocation size of the specified memory block P managed
532    by POOL to AMT bytes and returns a pointer to the beginning of the
533    block.
534    If POOL is a null pointer, then the block is reallocated in the
535    usual way with realloc(). */
536 void *
537 pool_realloc (struct pool *pool, void *p, size_t amt)
538 {
539   if (pool != NULL)
540     {
541       if (p != NULL)
542         {
543           if (amt != 0)
544             {
545               struct pool_gizmo *g = (void *) (((char *) p) - POOL_GIZMO_SIZE);
546               check_gizmo (pool, g);
547
548               g = xrealloc (g, amt + POOL_GIZMO_SIZE);
549               if (g->next)
550                 g->next->prev = g;
551               if (g->prev)
552                 g->prev->next = g;
553               else
554                 pool->gizmos = g;
555               check_gizmo (pool, g);
556
557               return ((char *) g) + POOL_GIZMO_SIZE;
558             }
559           else
560             {
561               pool_free (pool, p);
562               return NULL;
563             }
564         }
565       else
566         return pool_malloc (pool, amt);
567     }
568   else
569     return xrealloc (p, amt);
570 }
571
572 /* Changes the allocation size of the specified memory block P
573    managed by POOL to N * S bytes and returns a pointer to the
574    beginning of the block.
575    N must be nonnegative, S must be positive.
576    If POOL is a null pointer, then the block is reallocated in
577    the usual way with xrealloc().
578    Terminates the program if the memory cannot be obtained,
579    including the case where N * S overflows the range of size_t. */
580 void *
581 pool_nrealloc (struct pool *pool, void *p, size_t n, size_t s)
582 {
583   if (xalloc_oversized (n, s))
584     xalloc_die ();
585   return pool_realloc (pool, p, n * s);
586 }
587
588 /* If P is null, allocate a block of at least *PN such objects;
589    otherwise, reallocate P so that it contains more than *PN
590    objects each of S bytes.  *PN must be nonzero unless P is
591    null, and S must be nonzero.  Set *PN to the new number of
592    objects, and return the pointer to the new block.  *PN is
593    never set to zero, and the returned pointer is never null.
594
595    The block returned is managed by POOL.  If POOL is a null
596    pointer, then the block is reallocated in the usual way with
597    x2nrealloc().
598
599    Terminates the program if the memory cannot be obtained,
600    including the case where the memory required overflows the
601    range of size_t.
602
603    Repeated reallocations are guaranteed to make progress, either by
604    allocating an initial block with a nonzero size, or by allocating a
605    larger block.
606
607    In the following implementation, nonzero sizes are doubled so that
608    repeated reallocations have O(N log N) overall cost rather than
609    O(N**2) cost, but the specification for this function does not
610    guarantee that sizes are doubled.
611
612    Here is an example of use:
613
614      int *p = NULL;
615      struct pool *pool;
616      size_t used = 0;
617      size_t allocated = 0;
618
619      void
620      append_int (int value)
621        {
622          if (used == allocated)
623            p = pool_2nrealloc (pool, p, &allocated, sizeof *p);
624          p[used++] = value;
625        }
626
627    This causes x2nrealloc to allocate a block of some nonzero size the
628    first time it is called.
629
630    To have finer-grained control over the initial size, set *PN to a
631    nonzero value before calling this function with P == NULL.  For
632    example:
633
634      int *p = NULL;
635      struct pool *pool;
636      size_t used = 0;
637      size_t allocated = 0;
638      size_t allocated1 = 1000;
639
640      void
641      append_int (int value)
642        {
643          if (used == allocated)
644            {
645              p = pool_2nrealloc (pool, p, &allocated1, sizeof *p);
646              allocated = allocated1;
647            }
648          p[used++] = value;
649        }
650
651    This function implementation is from gnulib. */
652 void *
653 pool_2nrealloc (struct pool *pool, void *p, size_t *pn, size_t s)
654 {
655   size_t n = *pn;
656
657   if (p == NULL)
658     {
659       if (n == 0)
660         {
661           /* The approximate size to use for initial small allocation
662              requests, when the invoking code specifies an old size of
663              zero.  64 bytes is the largest "small" request for the
664              GNU C library malloc.  */
665           enum { DEFAULT_MXFAST = 64 };
666
667           n = DEFAULT_MXFAST / s;
668           n += !n;
669         }
670     }
671   else
672     {
673       if (SIZE_MAX / 2 / s < n)
674         xalloc_die ();
675       n *= 2;
676     }
677
678   *pn = n;
679   return pool_realloc (pool, p, n * s);
680 }
681
682 /* Frees block P managed by POOL.
683    If POOL is a null pointer, then the block is freed as usual with
684    free(). */
685 void
686 pool_free (struct pool *pool, void *p)
687 {
688   if (pool != NULL && p != NULL)
689     {
690       struct pool_gizmo *g = (void *) (((char *) p) - POOL_GIZMO_SIZE);
691       check_gizmo (pool, g);
692       delete_gizmo (pool, g);
693       free (g);
694     }
695   else
696     free (p);
697 }
698 \f
699 /* Gizmo allocations. */
700
701 /* Creates and returns a pool as a subpool of POOL.
702    The subpool will be destroyed automatically when POOL is destroyed.
703    It may also be destroyed explicitly in advance. */
704 struct pool *
705 pool_create_subpool (struct pool *pool)
706 {
707   struct pool *subpool;
708   struct pool_gizmo *g;
709
710   assert (pool != NULL);
711   subpool = pool_create ();
712   subpool->parent = pool;
713
714   g = (void *) (((char *) subpool->blocks) + subpool->blocks->ofs);
715   subpool->blocks->ofs += POOL_GIZMO_SIZE;
716
717   g->type = POOL_GIZMO_SUBPOOL;
718   g->p.subpool = subpool;
719
720   add_gizmo (pool, g);
721
722   return subpool;
723 }
724
725 /* Makes SUBPOOL a subpool of POOL.
726    SUBPOOL must not already have a parent pool.
727    The subpool will be destroyed automatically when POOL is destroyed.
728    It may also be destroyed explicitly in advance. */
729 void
730 pool_add_subpool (struct pool *pool, struct pool *subpool)
731 {
732   struct pool_gizmo *g;
733
734   assert (pool != NULL);
735   assert (subpool != NULL);
736   assert (subpool->parent == NULL);
737
738   g = pool_alloc (subpool, sizeof *g);
739   g->type = POOL_GIZMO_SUBPOOL;
740   g->p.subpool = subpool;
741   add_gizmo (pool, g);
742
743   subpool->parent = pool;
744 }
745
746 /* Opens file FILE_NAME with mode MODE and returns a handle to it
747    if successful or a null pointer if not.
748    The file will be closed automatically when POOL is destroyed, or it
749    may be closed explicitly in advance using pool_fclose(), or
750    detached from the pool with pool_detach_file(). */
751 FILE *
752 pool_fopen (struct pool *pool, const char *file_name, const char *mode)
753 {
754   FILE *f;
755
756   assert (pool && file_name && mode);
757   f = fopen (file_name, mode);
758   if (f != NULL)
759     pool_attach_file (pool, f);
760
761   return f;
762 }
763
764 /* Closes file FILE managed by POOL.
765    Returns 0 if successful, EOF if an I/O error occurred. */
766 int
767 pool_fclose (struct pool *pool, FILE *file)
768 {
769   assert (pool && file);
770   pool_detach_file (pool, file);
771   return fclose (file);
772 }
773
774 /* Attaches FILE to POOL.
775    The file will be closed automatically when POOL is destroyed, or it
776    may be closed explicitly in advance using pool_fclose(), or
777    detached from the pool with pool_detach_file(). */
778 void
779 pool_attach_file (struct pool *pool, FILE *file)
780 {
781   struct pool_gizmo *g = pool_alloc (pool, sizeof *g);
782   g->type = POOL_GIZMO_FILE;
783   g->p.file = file;
784   add_gizmo (pool, g);
785 }
786
787 /* Detaches FILE from POOL. */
788 void
789 pool_detach_file (struct pool *pool, FILE *file)
790 {
791   struct pool_gizmo *g;
792
793   for (g = pool->gizmos; g; g = g->next)
794     if (g->type == POOL_GIZMO_FILE && g->p.file == file)
795       {
796         delete_gizmo (pool, g);
797         return;
798       }
799 }
800
801 /* Creates a temporary file with create_temp_file() and returns a handle to it
802    if successful or a null pointer if not.
803    The file will be closed automatically when POOL is destroyed, or it
804    may be closed explicitly in advance using pool_fclose_temp_file(), or
805    detached from the pool with pool_detach_temp_file(). */
806 FILE *
807 pool_create_temp_file (struct pool *pool)
808 {
809   FILE *file = create_temp_file ();
810   if (file != NULL)
811     pool_attach_temp_file (pool, file);
812   return file;
813 }
814
815 /* Closes file FILE managed by POOL.
816    FILE must have been opened with create_temp_file(). */
817 void
818 pool_fclose_temp_file (struct pool *pool, FILE *file)
819 {
820   assert (pool && file);
821   pool_detach_temp_file (pool, file);
822   close_temp_file (file);
823 }
824
825 /* Attaches FILE, which must have been opened with create_temp_file(), to POOL.
826    The file will be closed automatically when POOL is destroyed, or it
827    may be closed explicitly in advance using pool_fclose_temp_file(), or
828    detached from the pool with pool_detach_temp_file(). */
829 void
830 pool_attach_temp_file (struct pool *pool, FILE *file)
831 {
832   struct pool_gizmo *g = pool_alloc (pool, sizeof *g);
833   g->type = POOL_GIZMO_TEMP_FILE;
834   g->p.file = file;
835   add_gizmo (pool, g);
836 }
837
838 /* Detaches FILE that was opened with create_temp_file() from POOL. */
839 void
840 pool_detach_temp_file (struct pool *pool, FILE *file)
841 {
842   struct pool_gizmo *g;
843
844   for (g = pool->gizmos; g; g = g->next)
845     if (g->type == POOL_GIZMO_TEMP_FILE && g->p.file == file)
846       {
847         delete_gizmo (pool, g);
848         return;
849       }
850 }
851 \f
852 /* Registers FREE to be called with argument P.
853    P should be unique among those registered in POOL so that it can be
854    uniquely identified by pool_unregister().
855    If not unregistered, FREE will be called with argument P when POOL
856    is destroyed. */
857 void
858 pool_register (struct pool *pool, void (*free) (void *), void *p)
859 {
860   assert (pool && free && p);
861
862   {
863     struct pool_gizmo *g = pool_alloc (pool, sizeof *g);
864     g->type = POOL_GIZMO_REGISTERED;
865     g->p.registered.free = free;
866     g->p.registered.p = p;
867     add_gizmo (pool, g);
868   }
869 }
870
871 /* Unregisters previously registered P from POOL.
872    Returns true only if P was found to be registered in POOL. */
873 bool
874 pool_unregister (struct pool *pool, void *p)
875 {
876   assert (pool && p);
877
878   {
879     struct pool_gizmo *g;
880
881     for (g = pool->gizmos; g; g = g->next)
882       if (g->type == POOL_GIZMO_REGISTERED && g->p.registered.p == p)
883         {
884           delete_gizmo (pool, g);
885           return true;
886         }
887   }
888
889   return false;
890 }
891 \f
892 /* Partial freeing. */
893
894 /* Notes the state of POOL into MARK so that it may be restored
895    by a call to pool_release(). */
896 void
897 pool_mark (struct pool *pool, struct pool_mark *mark)
898 {
899   assert (pool && mark);
900
901   mark->block = pool->blocks;
902   mark->ofs = pool->blocks->ofs;
903
904   mark->serial = serial;
905 }
906
907 /* Restores to POOL the state recorded in MARK.
908    Emptied blocks are not given back with free() but kept for
909    later allocations.  To get that behavior, use a subpool
910    instead. */
911 void
912 pool_release (struct pool *pool, const struct pool_mark *mark)
913 {
914   assert (pool && mark);
915
916   {
917     struct pool_gizmo *cur, *next;
918
919     for (cur = pool->gizmos; cur && cur->serial >= mark->serial; cur = next)
920       {
921         next = cur->next;
922         free_gizmo (cur);
923       }
924
925     if (cur != NULL)
926       {
927         cur->prev = NULL;
928         pool->gizmos = cur;
929       }
930     else
931       pool->gizmos = NULL;
932   }
933
934   {
935     struct pool_block *cur;
936
937     for (cur = pool->blocks; cur != mark->block; cur = cur->next)
938       {
939         cur->ofs = POOL_BLOCK_SIZE;
940         if ((char *) cur + POOL_BLOCK_SIZE == (char *) pool)
941           {
942             cur->ofs += POOL_SIZE;
943             if (pool->parent != NULL)
944               cur->ofs += POOL_GIZMO_SIZE;
945           }
946       }
947     pool->blocks = mark->block;
948     pool->blocks->ofs = mark->ofs;
949   }
950 }
951 \f
952 /* Private functions. */
953
954 /* Adds GIZMO at the beginning of POOL's gizmo list. */
955 static void
956 add_gizmo (struct pool *pool, struct pool_gizmo *gizmo)
957 {
958   assert (pool && gizmo);
959
960   gizmo->pool = pool;
961   gizmo->next = pool->gizmos;
962   gizmo->prev = NULL;
963   if (pool->gizmos)
964     pool->gizmos->prev = gizmo;
965   pool->gizmos = gizmo;
966
967   gizmo->serial = serial++;
968
969   check_gizmo (pool, gizmo);
970 }
971
972 /* Removes GIZMO from POOL's gizmo list. */
973 static void
974 delete_gizmo (struct pool *pool, struct pool_gizmo *gizmo)
975 {
976   assert (pool && gizmo);
977
978   check_gizmo (pool, gizmo);
979
980   if (gizmo->prev)
981     gizmo->prev->next = gizmo->next;
982   else
983     pool->gizmos = gizmo->next;
984   if (gizmo->next)
985     gizmo->next->prev = gizmo->prev;
986 }
987
988 /* Frees any of GIZMO's internal state.
989    GIZMO's data must not be referenced after calling this function. */
990 static void
991 free_gizmo (struct pool_gizmo *gizmo)
992 {
993   assert (gizmo != NULL);
994
995   switch (gizmo->type)
996     {
997     case POOL_GIZMO_MALLOC:
998       free (gizmo);
999       break;
1000     case POOL_GIZMO_FILE:
1001       fclose (gizmo->p.file);   /* Ignore errors. */
1002       break;
1003     case POOL_GIZMO_TEMP_FILE:
1004       close_temp_file (gizmo->p.file); /* Ignore errors. */
1005       break;
1006     case POOL_GIZMO_SUBPOOL:
1007       gizmo->p.subpool->parent = NULL;
1008       pool_destroy (gizmo->p.subpool);
1009       break;
1010     case POOL_GIZMO_REGISTERED:
1011       gizmo->p.registered.free (gizmo->p.registered.p);
1012       break;
1013     default:
1014       NOT_REACHED ();
1015     }
1016 }
1017
1018 /* Free all the gizmos in POOL. */
1019 static void
1020 free_all_gizmos (struct pool *pool)
1021 {
1022   struct pool_gizmo *cur, *next;
1023
1024   for (cur = pool->gizmos; cur; cur = next)
1025     {
1026       next = cur->next;
1027       free_gizmo (cur);
1028     }
1029   pool->gizmos = NULL;
1030 }
1031
1032 static void
1033 check_gizmo (struct pool *p, struct pool_gizmo *g)
1034 {
1035   assert (g->pool == p);
1036   assert (g->next == NULL || g->next->prev == g);
1037   assert ((g->prev != NULL && g->prev->next == g)
1038           || (g->prev == NULL && p->gizmos == g));
1039
1040 }