root/trunk/src/alloc.c

Revision 4229, 164.2 kB (checked in by miyoshi, 5 months ago)

(NSTATICS): Increased for the latest ImageMagick?.

  • Property svn:eol-style set to native
Line 
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
2    Copyright (C) 1985, 1986, 1988, 1993, 1994, 1995, 1997, 1998, 1999,
3       2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
4       Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs; see the file COPYING.  If not, write to
20 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA.  */
22
23 #include <config.h>
24 #include <stdio.h>
25 #include <limits.h>             /* For CHAR_BIT.  */
26
27 #ifdef STDC_HEADERS
28 #include <stddef.h>             /* For offsetof, used by PSEUDOVECSIZE. */
29 #endif
30
31 #ifdef ALLOC_DEBUG
32 #undef INLINE
33 #endif
34
35 /* Note that this declares bzero on OSF/1.  How dumb.  */
36
37 #include <signal.h>
38
39 #ifdef HAVE_GTK_AND_PTHREAD
40 #include <pthread.h>
41 #endif
42
43 /* This file is part of the core Lisp implementation, and thus must
44    deal with the real data structures.  If the Lisp implementation is
45    replaced, this file likely will not be used.  */
46
47 #undef HIDE_LISP_IMPLEMENTATION
48 #include "lisp.h"
49 #include "process.h"
50 #include "intervals.h"
51 #include "puresize.h"
52 #include "buffer.h"
53 #include "window.h"
54 #include "keyboard.h"
55 #include "frame.h"
56 #include "blockinput.h"
57 #include "charset.h"
58 #include "syssignal.h"
59 #include <setjmp.h>
60
61 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
62    memory.  Can do this only if using gmalloc.c.  */
63
64 #if defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC
65 #undef GC_MALLOC_CHECK
66 #endif
67
68 #ifdef HAVE_UNISTD_H
69 #include <unistd.h>
70 #else
71 extern POINTER_TYPE *sbrk ();
72 #endif
73
74 #ifdef HAVE_FCNTL_H
75 #define INCLUDED_FCNTL
76 #include <fcntl.h>
77 #endif
78 #ifndef O_WRONLY
79 #define O_WRONLY 1
80 #endif
81
82 #ifdef WINDOWSNT
83 #include <fcntl.h>
84 #include "w32.h"
85 #endif
86
87 #ifdef DOUG_LEA_MALLOC
88
89 #include <malloc.h>
90 /* malloc.h #defines this as size_t, at least in glibc2.  */
91 #ifndef __malloc_size_t
92 #define __malloc_size_t int
93 #endif
94
95 /* Specify maximum number of areas to mmap.  It would be nice to use a
96    value that explicitly means "no limit".  */
97
98 #define MMAP_MAX_AREAS 100000000
99
100 #else /* not DOUG_LEA_MALLOC */
101
102 /* The following come from gmalloc.c.  */
103
104 #define __malloc_size_t         size_t
105 extern __malloc_size_t _bytes_used;
106 extern __malloc_size_t __malloc_extra_blocks;
107
108 #endif /* not DOUG_LEA_MALLOC */
109
110 #if ! defined (SYSTEM_MALLOC) && defined (HAVE_GTK_AND_PTHREAD)
111
112 /* When GTK uses the file chooser dialog, different backends can be loaded
113    dynamically.  One such a backend is the Gnome VFS backend that gets loaded
114    if you run Gnome.  That backend creates several threads and also allocates
115    memory with malloc.
116
117    If Emacs sets malloc hooks (! SYSTEM_MALLOC) and the emacs_blocked_*
118    functions below are called from malloc, there is a chance that one
119    of these threads preempts the Emacs main thread and the hook variables
120    end up in an inconsistent state.  So we have a mutex to prevent that (note
121    that the backend handles concurrent access to malloc within its own threads
122    but Emacs code running in the main thread is not included in that control).
123
124    When UNBLOCK_INPUT is called, reinvoke_input_signal may be called.  If this
125    happens in one of the backend threads we will have two threads that tries
126    to run Emacs code at once, and the code is not prepared for that.
127    To prevent that, we only call BLOCK/UNBLOCK from the main thread.  */
128
129 static pthread_mutex_t alloc_mutex;
130
131 #define BLOCK_INPUT_ALLOC                               \
132   do                                                    \
133     {                                                   \
134       if (pthread_equal (pthread_self (), main_thread)) \
135         BLOCK_INPUT;                                    \
136       pthread_mutex_lock (&alloc_mutex);                \
137     }                                                   \
138   while (0)
139 #define UNBLOCK_INPUT_ALLOC                             \
140   do                                                    \
141     {                                                   \
142       pthread_mutex_unlock (&alloc_mutex);              \
143       if (pthread_equal (pthread_self (), main_thread)) \
144         UNBLOCK_INPUT;                                  \
145     }                                                   \
146   while (0)
147
148 #else /* SYSTEM_MALLOC || not HAVE_GTK_AND_PTHREAD */
149
150 #define BLOCK_INPUT_ALLOC BLOCK_INPUT
151 #define UNBLOCK_INPUT_ALLOC UNBLOCK_INPUT
152
153 #endif /* SYSTEM_MALLOC || not HAVE_GTK_AND_PTHREAD */
154
155 /* Value of _bytes_used, when spare_memory was freed.  */
156
157 static __malloc_size_t bytes_used_when_full;
158
159 static __malloc_size_t bytes_used_when_reconsidered;
160
161 /* Mark, unmark, query mark bit of a Lisp string.  S must be a pointer
162    to a struct Lisp_String.  */
163
164 #define MARK_STRING(S)          ((S)->size |= ARRAY_MARK_FLAG)
165 #define UNMARK_STRING(S)        ((S)->size &= ~ARRAY_MARK_FLAG)
166 #define STRING_MARKED_P(S)      (((S)->size & ARRAY_MARK_FLAG) != 0)
167
168 #define VECTOR_MARK(V)          ((V)->size |= ARRAY_MARK_FLAG)
169 #define VECTOR_UNMARK(V)        ((V)->size &= ~ARRAY_MARK_FLAG)
170 #define VECTOR_MARKED_P(V)      (((V)->size & ARRAY_MARK_FLAG) != 0)
171
172 /* Value is the number of bytes/chars of S, a pointer to a struct
173    Lisp_String.  This must be used instead of STRING_BYTES (S) or
174    S->size during GC, because S->size contains the mark bit for
175    strings.  */
176
177 #define GC_STRING_BYTES(S)      (STRING_BYTES (S))
178 #define GC_STRING_CHARS(S)      ((S)->size & ~ARRAY_MARK_FLAG)
179
180 /* Number of bytes of consing done since the last gc.  */
181
182 int consing_since_gc;
183
184 /* Count the amount of consing of various sorts of space.  */
185
186 EMACS_INT cons_cells_consed;
187 EMACS_INT floats_consed;
188 EMACS_INT vector_cells_consed;
189 EMACS_INT symbols_consed;
190 EMACS_INT string_chars_consed;
191 EMACS_INT misc_objects_consed;
192 EMACS_INT intervals_consed;
193 EMACS_INT strings_consed;
194
195 /* Minimum number of bytes of consing since GC before next GC. */
196
197 EMACS_INT gc_cons_threshold;
198
199 /* Similar minimum, computed from Vgc_cons_percentage.  */
200
201 EMACS_INT gc_relative_threshold;
202
203 static Lisp_Object Vgc_cons_percentage;
204
205 /* Minimum number of bytes of consing since GC before next GC,
206    when memory is full.  */
207
208 EMACS_INT memory_full_cons_threshold;
209
210 /* Nonzero during GC.  */
211
212 int gc_in_progress;
213
214 /* Nonzero means abort if try to GC.
215    This is for code which is written on the assumption that
216    no GC will happen, so as to verify that assumption.  */
217
218 int abort_on_gc;
219
220 /* Nonzero means display messages at beginning and end of GC.  */
221
222 int garbage_collection_messages;
223
224 #ifndef VIRT_ADDR_VARIES
225 extern
226 #endif /* VIRT_ADDR_VARIES */
227 int malloc_sbrk_used;
228
229 #ifndef VIRT_ADDR_VARIES
230 extern
231 #endif /* VIRT_ADDR_VARIES */
232 int malloc_sbrk_unused;
233
234 /* Number of live and free conses etc.  */
235
236 static int total_conses, total_markers, total_symbols, total_vector_size;
237 static int total_free_conses, total_free_markers, total_free_symbols;
238 static int total_free_floats, total_floats;
239
240 /* Points to memory space allocated as "spare", to be freed if we run
241    out of memory.  We keep one large block, four cons-blocks, and
242    two string blocks.  */
243
244 char *spare_memory[7];
245
246 /* Amount of spare memory to keep in large reserve block.  */
247
248 #define SPARE_MEMORY (1 << 14)
249
250 /* Number of extra blocks malloc should get when it needs more core.  */
251
252 static int malloc_hysteresis;
253
254 /* Non-nil means defun should do purecopy on the function definition.  */
255
256 Lisp_Object Vpurify_flag;
257
258 /* Non-nil means we are handling a memory-full error.  */
259
260 Lisp_Object Vmemory_full;
261
262 #ifndef HAVE_SHM
263
264 /* Initialize it to a nonzero value to force it into data space
265    (rather than bss space).  That way unexec will remap it into text
266    space (pure), on some systems.  We have not implemented the
267    remapping on more recent systems because this is less important
268    nowadays than in the days of small memories and timesharing.  */
269
270 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
271 #define PUREBEG (char *) pure
272
273 #else /* HAVE_SHM */
274
275 #define pure PURE_SEG_BITS   /* Use shared memory segment */
276 #define PUREBEG (char *)PURE_SEG_BITS
277
278 #endif /* HAVE_SHM */
279
280 /* Pointer to the pure area, and its size.  */
281
282 static char *purebeg;
283 static size_t pure_size;
284
285 /* Number of bytes of pure storage used before pure storage overflowed.
286    If this is non-zero, this implies that an overflow occurred.  */
287
288 static size_t pure_bytes_used_before_overflow;
289
290 /* Value is non-zero if P points into pure space.  */
291
292 #define PURE_POINTER_P(P)                                       \
293      (((PNTR_COMPARISON_TYPE) (P)                               \
294        < (PNTR_COMPARISON_TYPE) ((char *) purebeg + pure_size)) \
295       && ((PNTR_COMPARISON_TYPE) (P)                            \
296           >= (PNTR_COMPARISON_TYPE) purebeg))
297
298 /* Total number of bytes allocated in pure storage. */
299
300 EMACS_INT pure_bytes_used;
301
302 /* Index in pure at which next pure Lisp object will be allocated.. */
303
304 static EMACS_INT pure_bytes_used_lisp;
305
306 /* Number of bytes allocated for non-Lisp objects in pure storage.  */
307
308 static EMACS_INT pure_bytes_used_non_lisp;
309
310 /* If nonzero, this is a warning delivered by malloc and not yet
311    displayed.  */
312
313 char *pending_malloc_warning;
314
315 /* Pre-computed signal argument for use when memory is exhausted.  */
316
317 Lisp_Object Vmemory_signal_data;
318
319 /* Maximum amount of C stack to save when a GC happens.  */
320
321 #ifndef MAX_SAVE_STACK
322 #define MAX_SAVE_STACK 16000
323 #endif
324
325 /* Buffer in which we save a copy of the C stack at each GC.  */
326
327 char *stack_copy;
328 int stack_copy_size;
329
330 /* Non-zero means ignore malloc warnings.  Set during initialization.
331    Currently not used.  */
332
333 int ignore_warnings;
334
335 Lisp_Object Qgc_cons_threshold, Qchar_table_extra_slots;
336
337 /* Hook run after GC has finished.  */
338
339 Lisp_Object Vpost_gc_hook, Qpost_gc_hook;
340
341 Lisp_Object Vgc_elapsed;        /* accumulated elapsed time in GC  */
342 EMACS_INT gcs_done;             /* accumulated GCs  */
343
344 static void mark_buffer P_ ((Lisp_Object));
345 extern void mark_kboards P_ ((void));
346 extern void mark_backtrace P_ ((void));
347 static void gc_sweep P_ ((void));
348 static void mark_glyph_matrix P_ ((struct glyph_matrix *));
349 static void mark_face_cache P_ ((struct face_cache *));
350
351 #ifdef HAVE_WINDOW_SYSTEM
352 extern void mark_fringe_data P_ ((void));
353 static void mark_image P_ ((struct image *));
354 static void mark_image_cache P_ ((struct frame *));
355 #endif /* HAVE_WINDOW_SYSTEM */
356
357 static struct Lisp_String *allocate_string P_ ((void));
358 static void compact_small_strings P_ ((void));
359 static void free_large_strings P_ ((void));
360 static void sweep_strings P_ ((void));
361
362 extern int message_enable_multibyte;
363
364 /* When scanning the C stack for live Lisp objects, Emacs keeps track
365    of what memory allocated via lisp_malloc is intended for what
366    purpose.  This enumeration specifies the type of memory.  */
367
368 enum mem_type
369 {
370   MEM_TYPE_NON_LISP,
371   MEM_TYPE_BUFFER,
372   MEM_TYPE_CONS,
373   MEM_TYPE_STRING,
374   MEM_TYPE_MISC,
375   MEM_TYPE_SYMBOL,
376   MEM_TYPE_FLOAT,
377   /* Keep the following vector-like types together, with
378      MEM_TYPE_WINDOW being the last, and MEM_TYPE_VECTOR the
379      first.  Or change the code of live_vector_p, for instance.  */
380   MEM_TYPE_VECTOR,
381   MEM_TYPE_PROCESS,
382   MEM_TYPE_HASH_TABLE,
383   MEM_TYPE_FRAME,
384   MEM_TYPE_WINDOW
385 };
386
387 static POINTER_TYPE *lisp_align_malloc P_ ((size_t, enum mem_type));
388 static POINTER_TYPE *lisp_malloc P_ ((size_t, enum mem_type));
389 void refill_memory_reserve ();
390
391
392 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
393
394 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
395 #include <stdio.h>              /* For fprintf.  */
396 #endif
397
398 /* A unique object in pure space used to make some Lisp objects
399    on free lists recognizable in O(1).  */
400
401 Lisp_Object Vdead;
402
403 #ifdef GC_MALLOC_CHECK
404
405 enum mem_type allocated_mem_type;
406 int dont_register_blocks;
407
408 #endif /* GC_MALLOC_CHECK */
409
410 /* A node in the red-black tree describing allocated memory containing
411    Lisp data.  Each such block is recorded with its start and end
412    address when it is allocated, and removed from the tree when it
413    is freed.
414
415    A red-black tree is a balanced binary tree with the following
416    properties:
417
418    1. Every node is either red or black.
419    2. Every leaf is black.
420    3. If a node is red, then both of its children are black.
421    4. Every simple path from a node to a descendant leaf contains
422    the same number of black nodes.
423    5. The root is always black.
424
425    When nodes are inserted into the tree, or deleted from the tree,
426    the tree is "fixed" so that these properties are always true.
427
428    A red-black tree with N internal nodes has height at most 2
429    log(N+1).  Searches, insertions and deletions are done in O(log N).
430    Please see a text book about data structures for a detailed
431    description of red-black trees.  Any book worth its salt should
432    describe them.  */
433
434 struct mem_node
435 {
436   /* Children of this node.  These pointers are never NULL.  When there
437      is no child, the value is MEM_NIL, which points to a dummy node.  */
438   struct mem_node *left, *right;
439
440   /* The parent of this node.  In the root node, this is NULL.  */
441   struct mem_node *parent;
442
443   /* Start and end of allocated region.  */
444   void *start, *end;
445
446   /* Node color.  */
447   enum {MEM_BLACK, MEM_RED} color;
448
449   /* Memory type.  */
450   enum mem_type type;
451 };
452
453 /* Base address of stack.  Set in main.  */
454
455 Lisp_Object *stack_base;
456
457 /* Root of the tree describing allocated Lisp memory.  */
458
459 static struct mem_node *mem_root;
460
461 /* Lowest and highest known address in the heap.  */
462
463 static void *min_heap_address, *max_heap_address;
464
465 /* Sentinel node of the tree.  */
466
467 static struct mem_node mem_z;
468 #define MEM_NIL &mem_z
469
470 static POINTER_TYPE *lisp_malloc P_ ((size_t, enum mem_type));
471 static struct Lisp_Vector *allocate_vectorlike P_ ((EMACS_INT, enum mem_type));
472 static void lisp_free P_ ((POINTER_TYPE *));
473 static void mark_stack P_ ((void));
474 static int live_vector_p P_ ((struct mem_node *, void *));
475 static int live_buffer_p P_ ((struct mem_node *, void *));
476 static int live_string_p P_ ((struct mem_node *, void *));
477 static int live_cons_p P_ ((struct mem_node *, void *));
478 static int live_symbol_p P_ ((struct mem_node *, void *));
479 static int live_float_p P_ ((struct mem_node *, void *));
480 static int live_misc_p P_ ((struct mem_node *, void *));
481 static void mark_maybe_object P_ ((Lisp_Object));
482 static void mark_memory P_ ((void *, void *, int));
483 static void mem_init P_ ((void));
484 static struct mem_node *mem_insert P_ ((void *, void *, enum mem_type));
485 static void mem_insert_fixup P_ ((struct mem_node *));
486 static void mem_rotate_left P_ ((struct mem_node *));
487 static void mem_rotate_right P_ ((struct mem_node *));
488 static void mem_delete P_ ((struct mem_node *));
489 static void mem_delete_fixup P_ ((struct mem_node *));
490 static INLINE struct mem_node *mem_find P_ ((void *));
491
492
493 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
494 static void check_gcpros P_ ((void));
495 #endif
496
497 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
498
499 /* Recording what needs to be marked for gc.  */
500
501 struct gcpro *gcprolist;
502
503 /* Addresses of staticpro'd variables.  Initialize it to a nonzero
504    value; otherwise some compilers put it into BSS.  */
505
506 #ifdef MEADOW
507 #define NSTATICS 1540
508 #else
509 #define NSTATICS 1280
510 #endif
511 Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
512
513 /* Index of next unused slot in staticvec.  */
514
515 int staticidx = 0;
516
517 static POINTER_TYPE *pure_alloc P_ ((size_t, int));
518
519
520 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
521    ALIGNMENT must be a power of 2.  */
522
523 #define ALIGN(ptr, ALIGNMENT) \
524   ((POINTER_TYPE *) ((((EMACS_UINT)(ptr)) + (ALIGNMENT) - 1) \
525                      & ~((ALIGNMENT) - 1)))
526
527
528
529 /************************************************************************
530                                 Malloc
531  ************************************************************************/
532
533 /* Function malloc calls this if it finds we are near exhausting storage.  */
534
535 void
536 malloc_warning (str)
537      char *str;
538 {
539   pending_malloc_warning = str;
540 }
541
542
543 /* Display an already-pending malloc warning.  */
544
545 void
546 display_malloc_warning ()
547 {
548   call3 (intern ("display-warning"),
549          intern ("alloc"),
550          build_string (pending_malloc_warning),
551          intern ("emergency"));
552   pending_malloc_warning = 0;
553 }
554
555
556 #ifdef DOUG_LEA_MALLOC
557 #  define BYTES_USED (mallinfo ().uordblks)
558 #else
559 #  define BYTES_USED _bytes_used
560 #endif
561
562 /* Called if we can't allocate relocatable space for a buffer.  */
563
564 void
565 buffer_memory_full ()
566 {
567   /* If buffers use the relocating allocator, no need to free
568      spare_memory, because we may have plenty of malloc space left
569      that we could get, and if we don't, the malloc that fails will
570      itself cause spare_memory to be freed.  If buffers don't use the
571      relocating allocator, treat this like any other failing
572      malloc.  */
573
574 #ifndef REL_ALLOC
575   memory_full ();
576 #endif
577
578   /* This used to call error, but if we've run out of memory, we could
579      get infinite recursion trying to build the string.  */
580   xsignal (Qnil, Vmemory_signal_data);
581 }
582
583
584 #ifdef XMALLOC_OVERRUN_CHECK
585
586 /* Check for overrun in malloc'ed buffers by wrapping a 16 byte header
587    and a 16 byte trailer around each block.
588
589    The header consists of 12 fixed bytes + a 4 byte integer contaning the
590    original block size, while the trailer consists of 16 fixed bytes.
591
592    The header is used to detect whether this block has been allocated
593    through these functions -- as it seems that some low-level libc
594    functions may bypass the malloc hooks.
595 */
596
597
598 #define XMALLOC_OVERRUN_CHECK_SIZE 16
599
600 static char xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE-4] =
601   { 0x9a, 0x9b, 0xae, 0xaf,
602     0xbf, 0xbe, 0xce, 0xcf,
603     0xea, 0xeb, 0xec, 0xed };
604
605 static char xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
606   { 0xaa, 0xab, 0xac, 0xad,
607     0xba, 0xbb, 0xbc, 0xbd,
608     0xca, 0xcb, 0xcc, 0xcd,
609     0xda, 0xdb, 0xdc, 0xdd };
610
611 /* Macros to insert and extract the block size in the header.  */
612
613 #define XMALLOC_PUT_SIZE(ptr, size)     \
614   (ptr[-1] = (size & 0xff),             \
615    ptr[-2] = ((size >> 8) & 0xff),      \
616    ptr[-3] = ((size >> 16) & 0xff),     \
617    ptr[-4] = ((size >> 24) & 0xff))
618
619 #define XMALLOC_GET_SIZE(ptr)                   \
620   (size_t)((unsigned)(ptr[-1])          |       \
621            ((unsigned)(ptr[-2]) << 8)   |       \
622            ((unsigned)(ptr[-3]) << 16)  |       \
623            ((unsigned)(ptr[-4]) << 24))
624
625
626 /* The call depth in overrun_check functions.  For example, this might happen:
627    xmalloc()
628      overrun_check_malloc()
629        -> malloc -> (via hook)_-> emacs_blocked_malloc
630           -> overrun_check_malloc
631              call malloc  (hooks are NULL, so real malloc is called).
632              malloc returns 10000.
633              add overhead, return 10016.
634       <- (back in overrun_check_malloc)
635       add overhead again, return 10032
636    xmalloc returns 10032.
637
638    (time passes).
639
640    xfree(10032)
641      overrun_check_free(10032)
642        decrease overhed
643        free(10016)  <-  crash, because 10000 is the original pointer.  */
644
645 static int check_depth;
646
647 /* Like malloc, but wraps allocated block with header and trailer.  */
648
649 POINTER_TYPE *
650 overrun_check_malloc (size)
651      size_t size;
652 {
653   register unsigned char *val;
654   size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
655
656   val = (unsigned char *) malloc (size + overhead);
657   if (val && check_depth == 1)
658     {
659       bcopy (xmalloc_overrun_check_header, val, XMALLOC_OVERRUN_CHECK_SIZE - 4);
660       val += XMALLOC_OVERRUN_CHECK_SIZE;
661       XMALLOC_PUT_SIZE(val, size);
662       bcopy (xmalloc_overrun_check_trailer, val + size, XMALLOC_OVERRUN_CHECK_SIZE);
663     }
664   --check_depth;
665   return (POINTER_TYPE *)val;
666 }
667
668
669 /* Like realloc, but checks old block for overrun, and wraps new block
670    with header and trailer.  */
671
672 POINTER_TYPE *
673 overrun_check_realloc (block, size)
674      POINTER_TYPE *block;
675      size_t size;
676 {
677   register unsigned char *val = (unsigned char *)block;
678   size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
679
680   if (val
681       && check_depth == 1
682       && bcmp (xmalloc_overrun_check_header,
683                val - XMALLOC_OVERRUN_CHECK_SIZE,
684                XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
685     {
686       size_t osize = XMALLOC_GET_SIZE (val);
687       if (bcmp (xmalloc_overrun_check_trailer,
688                 val + osize,
689                 XMALLOC_OVERRUN_CHECK_SIZE))
690         abort ();
691       bzero (val + osize, XMALLOC_OVERRUN_CHECK_SIZE);
692       val -= XMALLOC_OVERRUN_CHECK_SIZE;
693       bzero (val, XMALLOC_OVERRUN_CHECK_SIZE);
694     }
695
696   val = (unsigned char *) realloc ((POINTER_TYPE *)val, size + overhead);
697
698   if (val && check_depth == 1)
699     {
700       bcopy (xmalloc_overrun_check_header, val, XMALLOC_OVERRUN_CHECK_SIZE - 4);
701       val += XMALLOC_OVERRUN_CHECK_SIZE;
702       XMALLOC_PUT_SIZE(val, size);
703       bcopy (xmalloc_overrun_check_trailer, val + size, XMALLOC_OVERRUN_CHECK_SIZE);
704     }
705   --check_depth;
706   return (POINTER_TYPE *)val;
707 }
708
709 /* Like free, but checks block for overrun.  */
710
711 void
712 overrun_check_free (block)
713      POINTER_TYPE *block;
714 {
715   unsigned char *val = (unsigned char *)block;
716
717   ++check_depth;
718   if (val
719       && check_depth == 1
720       && bcmp (xmalloc_overrun_check_header,
721                val - XMALLOC_OVERRUN_CHECK_SIZE,
722                XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
723     {
724       size_t osize = XMALLOC_GET_SIZE (val);
725       if (bcmp (xmalloc_overrun_check_trailer,
726                 val + osize,
727                 XMALLOC_OVERRUN_CHECK_SIZE))
728         abort ();
729 #ifdef XMALLOC_CLEAR_FREE_MEMORY
730       val -= XMALLOC_OVERRUN_CHECK_SIZE;
731       memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_SIZE*2);
732 #else
733       bzero (val + osize, XMALLOC_OVERRUN_CHECK_SIZE);
734       val -= XMALLOC_OVERRUN_CHECK_SIZE;
735       bzero (val, XMALLOC_OVERRUN_CHECK_SIZE);
736 #endif
737     }
738
739   free (val);
740   --check_depth;
741 }
742
743 #undef malloc
744 #undef realloc
745 #undef free
746 #define malloc overrun_check_malloc
747 #define realloc overrun_check_realloc
748 #define free overrun_check_free
749 #endif
750
751
752 /* Like malloc but check for no memory and block interrupt input..  */
753
754 POINTER_TYPE *
755 xmalloc (size)
756      size_t size;
757 {
758   register POINTER_TYPE *val;
759
760