(CHAR_TO_CHARC): New inline function.
[chise/xemacs-chise.git-] / src / alloc.c
1 /* Storage allocation and gc for XEmacs Lisp interpreter.
2    Copyright (C) 1985-1998 Free Software Foundation, Inc.
3    Copyright (C) 1995 Sun Microsystems, Inc.
4    Copyright (C) 1995, 1996 Ben Wing.
5
6 This file is part of XEmacs.
7
8 XEmacs is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
11 later version.
12
13 XEmacs is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with XEmacs; see the file COPYING.  If not, write to
20 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 Boston, MA 02111-1307, USA.  */
22
23 /* Synched up with: FSF 19.28, Mule 2.0.  Substantially different from
24    FSF. */
25
26 /* Authorship:
27
28    FSF: Original version; a long time ago.
29    Mly: Significantly rewritten to use new 3-bit tags and
30         nicely abstracted object definitions, for 19.8.
31    JWZ: Improved code to keep track of purespace usage and
32         issue nice purespace and GC stats.
33    Ben Wing: Cleaned up frob-block lrecord code, added error-checking
34         and various changes for Mule, for 19.12.
35         Added bit vectors for 19.13.
36         Added lcrecord lists for 19.14.
37    slb: Lots of work on the purification and dump time code.
38         Synched Doug Lea malloc support from Emacs 20.2.
39    og:  Killed the purespace.  Portable dumper (moved to dumper.c)
40 */
41
42 #include <config.h>
43 #include "lisp.h"
44
45 #include "alloc.h"
46 #include "backtrace.h"
47 #include "buffer.h"
48 #include "bytecode.h"
49 #include "chartab.h"
50 #include "device.h"
51 #include "elhash.h"
52 #include "events.h"
53 #include "extents.h"
54 #include "frame.h"
55 #include "glyphs.h"
56 #include "opaque.h"
57 #include "redisplay.h"
58 #include "specifier.h"
59 #include "sysfile.h"
60 #include "sysdep.h"
61 #include "window.h"
62 #include "console-stream.h"
63
64 #ifdef DOUG_LEA_MALLOC
65 #include <malloc.h>
66 #endif
67
68 #ifdef PDUMP
69 #include "dumper.h"
70 #endif
71
72 EXFUN (Fgarbage_collect, 0);
73
74 #if 0 /* this is _way_ too slow to be part of the standard debug options */
75 #if defined(DEBUG_XEMACS) && defined(MULE)
76 #define VERIFY_STRING_CHARS_INTEGRITY
77 #endif
78 #endif
79
80 /* Define this to use malloc/free with no freelist for all datatypes,
81    the hope being that some debugging tools may help detect
82    freed memory references */
83 #ifdef USE_DEBUG_MALLOC /* Taking the above comment at face value -slb */
84 #include <dmalloc.h>
85 #define ALLOC_NO_POOLS
86 #endif
87
88 #ifdef DEBUG_XEMACS
89 static int debug_allocation;
90 static int debug_allocation_backtrace_length;
91 #endif
92
93 /* Number of bytes of consing done since the last gc */
94 EMACS_INT consing_since_gc;
95 #define INCREMENT_CONS_COUNTER_1(size) (consing_since_gc += (size))
96
97 #define debug_allocation_backtrace()                            \
98 do {                                                            \
99   if (debug_allocation_backtrace_length > 0)                    \
100     debug_short_backtrace (debug_allocation_backtrace_length);  \
101 } while (0)
102
103 #ifdef DEBUG_XEMACS
104 #define INCREMENT_CONS_COUNTER(foosize, type)                   \
105   do {                                                          \
106     if (debug_allocation)                                       \
107       {                                                         \
108         stderr_out ("allocating %s (size %ld)\n", type, (long)foosize); \
109         debug_allocation_backtrace ();                          \
110       }                                                         \
111     INCREMENT_CONS_COUNTER_1 (foosize);                         \
112   } while (0)
113 #define NOSEEUM_INCREMENT_CONS_COUNTER(foosize, type)           \
114   do {                                                          \
115     if (debug_allocation > 1)                                   \
116       {                                                         \
117         stderr_out ("allocating noseeum %s (size %ld)\n", type, (long)foosize); \
118         debug_allocation_backtrace ();                          \
119       }                                                         \
120     INCREMENT_CONS_COUNTER_1 (foosize);                         \
121   } while (0)
122 #else
123 #define INCREMENT_CONS_COUNTER(size, type) INCREMENT_CONS_COUNTER_1 (size)
124 #define NOSEEUM_INCREMENT_CONS_COUNTER(size, type) \
125   INCREMENT_CONS_COUNTER_1 (size)
126 #endif
127
128 #define DECREMENT_CONS_COUNTER(size) do {       \
129   consing_since_gc -= (size);                   \
130   if (consing_since_gc < 0)                     \
131     consing_since_gc = 0;                       \
132 } while (0)
133
134 /* Number of bytes of consing since gc before another gc should be done. */
135 EMACS_INT gc_cons_threshold;
136
137 /* Nonzero during gc */
138 int gc_in_progress;
139
140 /* Number of times GC has happened at this level or below.
141  * Level 0 is most volatile, contrary to usual convention.
142  *  (Of course, there's only one level at present) */
143 EMACS_INT gc_generation_number[1];
144
145 /* This is just for use by the printer, to allow things to print uniquely */
146 static int lrecord_uid_counter;
147
148 /* Nonzero when calling certain hooks or doing other things where
149    a GC would be bad */
150 int gc_currently_forbidden;
151
152 /* Hooks. */
153 Lisp_Object Vpre_gc_hook, Qpre_gc_hook;
154 Lisp_Object Vpost_gc_hook, Qpost_gc_hook;
155
156 /* "Garbage collecting" */
157 Lisp_Object Vgc_message;
158 Lisp_Object Vgc_pointer_glyph;
159 static const char gc_default_message[] = "Garbage collecting";
160 Lisp_Object Qgarbage_collecting;
161
162 #ifndef VIRT_ADDR_VARIES
163 extern
164 #endif /* VIRT_ADDR_VARIES */
165  EMACS_INT malloc_sbrk_used;
166
167 #ifndef VIRT_ADDR_VARIES
168 extern
169 #endif /* VIRT_ADDR_VARIES */
170  EMACS_INT malloc_sbrk_unused;
171
172 /* Non-zero means we're in the process of doing the dump */
173 int purify_flag;
174
175 #ifdef ERROR_CHECK_TYPECHECK
176
177 Error_behavior ERROR_ME, ERROR_ME_NOT, ERROR_ME_WARN;
178
179 #endif
180
181 int
182 c_readonly (Lisp_Object obj)
183 {
184   return POINTER_TYPE_P (XTYPE (obj)) && C_READONLY (obj);
185 }
186
187 int
188 lisp_readonly (Lisp_Object obj)
189 {
190   return POINTER_TYPE_P (XTYPE (obj)) && LISP_READONLY (obj);
191 }
192
193 \f
194 /* Maximum amount of C stack to save when a GC happens.  */
195
196 #ifndef MAX_SAVE_STACK
197 #define MAX_SAVE_STACK 0 /* 16000 */
198 #endif
199
200 /* Non-zero means ignore malloc warnings.  Set during initialization.  */
201 int ignore_malloc_warnings;
202
203 \f
204 static void *breathing_space;
205
206 void
207 release_breathing_space (void)
208 {
209   if (breathing_space)
210     {
211       void *tmp = breathing_space;
212       breathing_space = 0;
213       xfree (tmp);
214     }
215 }
216
217 /* malloc calls this if it finds we are near exhausting storage */
218 void
219 malloc_warning (const char *str)
220 {
221   if (ignore_malloc_warnings)
222     return;
223
224   warn_when_safe
225     (Qmemory, Qcritical,
226      "%s\n"
227      "Killing some buffers may delay running out of memory.\n"
228      "However, certainly by the time you receive the 95%% warning,\n"
229      "you should clean up, kill this Emacs, and start a new one.",
230      str);
231 }
232
233 /* Called if malloc returns zero */
234 DOESNT_RETURN
235 memory_full (void)
236 {
237   /* Force a GC next time eval is called.
238      It's better to loop garbage-collecting (we might reclaim enough
239      to win) than to loop beeping and barfing "Memory exhausted"
240    */
241   consing_since_gc = gc_cons_threshold + 1;
242   release_breathing_space ();
243
244   /* Flush some histories which might conceivably contain garbalogical
245      inhibitors.  */
246   if (!NILP (Fboundp (Qvalues)))
247     Fset (Qvalues, Qnil);
248   Vcommand_history = Qnil;
249
250   error ("Memory exhausted");
251 }
252
253 /* like malloc and realloc but check for no memory left, and block input. */
254
255 #undef xmalloc
256 void *
257 xmalloc (size_t size)
258 {
259   void *val = malloc (size);
260
261   if (!val && (size != 0)) memory_full ();
262   return val;
263 }
264
265 #undef xcalloc
266 static void *
267 xcalloc (size_t nelem, size_t elsize)
268 {
269   void *val = calloc (nelem, elsize);
270
271   if (!val && (nelem != 0)) memory_full ();
272   return val;
273 }
274
275 void *
276 xmalloc_and_zero (size_t size)
277 {
278   return xcalloc (size, sizeof (char));
279 }
280
281 #undef xrealloc
282 void *
283 xrealloc (void *block, size_t size)
284 {
285   /* We must call malloc explicitly when BLOCK is 0, since some
286      reallocs don't do this.  */
287   void *val = block ? realloc (block, size) : malloc (size);
288
289   if (!val && (size != 0)) memory_full ();
290   return val;
291 }
292
293 void
294 #ifdef ERROR_CHECK_MALLOC
295 xfree_1 (void *block)
296 #else
297 xfree (void *block)
298 #endif
299 {
300 #ifdef ERROR_CHECK_MALLOC
301   /* Unbelievably, calling free() on 0xDEADBEEF doesn't cause an
302      error until much later on for many system mallocs, such as
303      the one that comes with Solaris 2.3.  FMH!! */
304   assert (block != (void *) 0xDEADBEEF);
305   assert (block);
306 #endif /* ERROR_CHECK_MALLOC */
307   free (block);
308 }
309
310 #ifdef ERROR_CHECK_GC
311
312 #if SIZEOF_INT == 4
313 typedef unsigned int four_byte_t;
314 #elif SIZEOF_LONG == 4
315 typedef unsigned long four_byte_t;
316 #elif SIZEOF_SHORT == 4
317 typedef unsigned short four_byte_t;
318 #else
319 What kind of strange-ass system are we running on?
320 #endif
321
322 static void
323 deadbeef_memory (void *ptr, size_t size)
324 {
325   four_byte_t *ptr4 = (four_byte_t *) ptr;
326   size_t beefs = size >> 2;
327
328   /* In practice, size will always be a multiple of four.  */
329   while (beefs--)
330     (*ptr4++) = 0xDEADBEEF;
331 }
332
333 #else /* !ERROR_CHECK_GC */
334
335
336 #define deadbeef_memory(ptr, size)
337
338 #endif /* !ERROR_CHECK_GC */
339
340 #undef xstrdup
341 char *
342 xstrdup (const char *str)
343 {
344   int len = strlen (str) + 1;   /* for stupid terminating 0 */
345
346   void *val = xmalloc (len);
347   if (val == 0) return 0;
348   return (char *) memcpy (val, str, len);
349 }
350
351 #ifdef NEED_STRDUP
352 char *
353 strdup (const char *s)
354 {
355   return xstrdup (s);
356 }
357 #endif /* NEED_STRDUP */
358
359 \f
360 static void *
361 allocate_lisp_storage (size_t size)
362 {
363   return xmalloc (size);
364 }
365
366
367 /* lcrecords are chained together through their "next" field.
368    After doing the mark phase, GC will walk this linked list
369    and free any lcrecord which hasn't been marked. */
370 static struct lcrecord_header *all_lcrecords;
371 #ifdef UTF2000
372 static struct lcrecord_header *all_older_lcrecords;
373 #endif
374
375 void *
376 alloc_lcrecord (size_t size, const struct lrecord_implementation *implementation)
377 {
378   struct lcrecord_header *lcheader;
379
380   type_checking_assert
381     ((implementation->static_size == 0 ?
382       implementation->size_in_bytes_method != NULL :
383       implementation->static_size == size)
384      &&
385      (! implementation->basic_p)
386      &&
387      (! (implementation->hash == NULL && implementation->equal != NULL)));
388
389   lcheader = (struct lcrecord_header *) allocate_lisp_storage (size);
390   set_lheader_implementation (&lcheader->lheader, implementation);
391   lcheader->next = all_lcrecords;
392 #if 1                           /* mly prefers to see small ID numbers */
393   lcheader->uid = lrecord_uid_counter++;
394 #else                           /* jwz prefers to see real addrs */
395   lcheader->uid = (int) &lcheader;
396 #endif
397   lcheader->free = 0;
398   all_lcrecords = lcheader;
399   INCREMENT_CONS_COUNTER (size, implementation->name);
400   return lcheader;
401 }
402
403 #ifdef UTF2000
404 void *
405 alloc_older_lcrecord (size_t size,
406                       const struct lrecord_implementation *implementation)
407 {
408   struct lcrecord_header *lcheader;
409
410   type_checking_assert
411     ((implementation->static_size == 0 ?
412       implementation->size_in_bytes_method != NULL :
413       implementation->static_size == size)
414      &&
415      (! implementation->basic_p)
416      &&
417      (! (implementation->hash == NULL && implementation->equal != NULL)));
418
419   lcheader = (struct lcrecord_header *) allocate_lisp_storage (size);
420   set_lheader_older_implementation (&lcheader->lheader, implementation);
421   lcheader->next = all_older_lcrecords;
422 #if 1                           /* mly prefers to see small ID numbers */
423   lcheader->uid = lrecord_uid_counter++;
424 #else                           /* jwz prefers to see real addrs */
425   lcheader->uid = (int) &lcheader;
426 #endif
427   lcheader->free = 0;
428   all_older_lcrecords = lcheader;
429   INCREMENT_CONS_COUNTER (size, implementation->name);
430   return lcheader;
431 }
432 #endif
433
434 #if 0 /* Presently unused */
435 /* Very, very poor man's EGC?
436  * This may be slow and thrash pages all over the place.
437  *  Only call it if you really feel you must (and if the
438  *  lrecord was fairly recently allocated).
439  * Otherwise, just let the GC do its job -- that's what it's there for
440  */
441 void
442 free_lcrecord (struct lcrecord_header *lcrecord)
443 {
444   if (all_lcrecords == lcrecord)
445     {
446       all_lcrecords = lcrecord->next;
447     }
448   else
449     {
450       struct lrecord_header *header = all_lcrecords;
451       for (;;)
452         {
453           struct lrecord_header *next = header->next;
454           if (next == lcrecord)
455             {
456               header->next = lrecord->next;
457               break;
458             }
459           else if (next == 0)
460             abort ();
461           else
462             header = next;
463         }
464     }
465   if (lrecord->implementation->finalizer)
466     lrecord->implementation->finalizer (lrecord, 0);
467   xfree (lrecord);
468   return;
469 }
470 #endif /* Unused */
471
472
473 static void
474 disksave_object_finalization_1 (void)
475 {
476   struct lcrecord_header *header;
477
478   for (header = all_lcrecords; header; header = header->next)
479     {
480       if (LHEADER_IMPLEMENTATION (&header->lheader)->finalizer &&
481           !header->free)
482         LHEADER_IMPLEMENTATION (&header->lheader)->finalizer (header, 1);
483     }
484 #ifdef UTF2000
485   for (header = all_older_lcrecords; header; header = header->next)
486     {
487       if (LHEADER_IMPLEMENTATION (&header->lheader)->finalizer &&
488           !header->free)
489         LHEADER_IMPLEMENTATION (&header->lheader)->finalizer (header, 1);
490     }
491 #endif
492 }
493
494 \f
495 /************************************************************************/
496 /*                        Debugger support                              */
497 /************************************************************************/
498 /* Give gdb/dbx enough information to decode Lisp Objects.  We make
499    sure certain symbols are always defined, so gdb doesn't complain
500    about expressions in src/.gdbinit.  See src/.gdbinit or src/.dbxrc
501    to see how this is used.  */
502
503 EMACS_UINT dbg_valmask = ((1UL << VALBITS) - 1) << GCBITS;
504 EMACS_UINT dbg_typemask = (1UL << GCTYPEBITS) - 1;
505
506 #ifdef USE_UNION_TYPE
507 unsigned char dbg_USE_UNION_TYPE = 1;
508 #else
509 unsigned char dbg_USE_UNION_TYPE = 0;
510 #endif
511
512 unsigned char dbg_valbits = VALBITS;
513 unsigned char dbg_gctypebits = GCTYPEBITS;
514
515 /* Macros turned into functions for ease of debugging.
516    Debuggers don't know about macros! */
517 int dbg_eq (Lisp_Object obj1, Lisp_Object obj2);
518 int
519 dbg_eq (Lisp_Object obj1, Lisp_Object obj2)
520 {
521   return EQ (obj1, obj2);
522 }
523
524 \f
525 /************************************************************************/
526 /*                        Fixed-size type macros                        */
527 /************************************************************************/
528
529 /* For fixed-size types that are commonly used, we malloc() large blocks
530    of memory at a time and subdivide them into chunks of the correct
531    size for an object of that type.  This is more efficient than
532    malloc()ing each object separately because we save on malloc() time
533    and overhead due to the fewer number of malloc()ed blocks, and
534    also because we don't need any extra pointers within each object
535    to keep them threaded together for GC purposes.  For less common
536    (and frequently large-size) types, we use lcrecords, which are
537    malloc()ed individually and chained together through a pointer
538    in the lcrecord header.  lcrecords do not need to be fixed-size
539    (i.e. two objects of the same type need not have the same size;
540    however, the size of a particular object cannot vary dynamically).
541    It is also much easier to create a new lcrecord type because no
542    additional code needs to be added to alloc.c.  Finally, lcrecords
543    may be more efficient when there are only a small number of them.
544
545    The types that are stored in these large blocks (or "frob blocks")
546    are cons, float, compiled-function, symbol, marker, extent, event,
547    and string.
548
549    Note that strings are special in that they are actually stored in
550    two parts: a structure containing information about the string, and
551    the actual data associated with the string.  The former structure
552    (a struct Lisp_String) is a fixed-size structure and is managed the
553    same way as all the other such types.  This structure contains a
554    pointer to the actual string data, which is stored in structures of
555    type struct string_chars_block.  Each string_chars_block consists
556    of a pointer to a struct Lisp_String, followed by the data for that
557    string, followed by another pointer to a Lisp_String, followed by
558    the data for that string, etc.  At GC time, the data in these
559    blocks is compacted by searching sequentially through all the
560    blocks and compressing out any holes created by unmarked strings.
561    Strings that are more than a certain size (bigger than the size of
562    a string_chars_block, although something like half as big might
563    make more sense) are malloc()ed separately and not stored in
564    string_chars_blocks.  Furthermore, no one string stretches across
565    two string_chars_blocks.
566
567    Vectors are each malloc()ed separately, similar to lcrecords.
568
569    In the following discussion, we use conses, but it applies equally
570    well to the other fixed-size types.
571
572    We store cons cells inside of cons_blocks, allocating a new
573    cons_block with malloc() whenever necessary.  Cons cells reclaimed
574    by GC are put on a free list to be reallocated before allocating
575    any new cons cells from the latest cons_block.  Each cons_block is
576    just under 2^n - MALLOC_OVERHEAD bytes long, since malloc (at least
577    the versions in malloc.c and gmalloc.c) really allocates in units
578    of powers of two and uses 4 bytes for its own overhead.
579
580    What GC actually does is to search through all the cons_blocks,
581    from the most recently allocated to the oldest, and put all
582    cons cells that are not marked (whether or not they're already
583    free) on a cons_free_list.  The cons_free_list is a stack, and
584    so the cons cells in the oldest-allocated cons_block end up
585    at the head of the stack and are the first to be reallocated.
586    If any cons_block is entirely free, it is freed with free()
587    and its cons cells removed from the cons_free_list.  Because
588    the cons_free_list ends up basically in memory order, we have
589    a high locality of reference (assuming a reasonable turnover
590    of allocating and freeing) and have a reasonable probability
591    of entirely freeing up cons_blocks that have been more recently
592    allocated.  This stage is called the "sweep stage" of GC, and
593    is executed after the "mark stage", which involves starting
594    from all places that are known to point to in-use Lisp objects
595    (e.g. the obarray, where are all symbols are stored; the
596    current catches and condition-cases; the backtrace list of
597    currently executing functions; the gcpro list; etc.) and
598    recursively marking all objects that are accessible.
599
600    At the beginning of the sweep stage, the conses in the cons
601    blocks are in one of three states: in use and marked, in use
602    but not marked, and not in use (already freed).  Any conses
603    that are marked have been marked in the mark stage just
604    executed, because as part of the sweep stage we unmark any
605    marked objects.  The way we tell whether or not a cons cell
606    is in use is through the FREE_STRUCT_P macro.  This basically
607    looks at the first 4 bytes (or however many bytes a pointer
608    fits in) to see if all the bits in those bytes are 1.  The
609    resulting value (0xFFFFFFFF) is not a valid pointer and is
610    not a valid Lisp_Object.  All current fixed-size types have
611    a pointer or Lisp_Object as their first element with the
612    exception of strings; they have a size value, which can
613    never be less than zero, and so 0xFFFFFFFF is invalid for
614    strings as well.  Now assuming that a cons cell is in use,
615    the way we tell whether or not it is marked is to look at
616    the mark bit of its car (each Lisp_Object has one bit
617    reserved as a mark bit, in case it's needed).  Note that
618    different types of objects use different fields to indicate
619    whether the object is marked, but the principle is the same.
620
621    Conses on the free_cons_list are threaded through a pointer
622    stored in the bytes directly after the bytes that are set
623    to 0xFFFFFFFF (we cannot overwrite these because the cons
624    is still in a cons_block and needs to remain marked as
625    not in use for the next time that GC happens).  This
626    implies that all fixed-size types must be at least big
627    enough to store two pointers, which is indeed the case
628    for all current fixed-size types.
629
630    Some types of objects need additional "finalization" done
631    when an object is converted from in use to not in use;
632    this is the purpose of the ADDITIONAL_FREE_type macro.
633    For example, markers need to be removed from the chain
634    of markers that is kept in each buffer.  This is because
635    markers in a buffer automatically disappear if the marker
636    is no longer referenced anywhere (the same does not
637    apply to extents, however).
638
639    WARNING: Things are in an extremely bizarre state when
640    the ADDITIONAL_FREE_type macros are called, so beware!
641
642    When ERROR_CHECK_GC is defined, we do things differently
643    so as to maximize our chances of catching places where
644    there is insufficient GCPROing.  The thing we want to
645    avoid is having an object that we're using but didn't
646    GCPRO get freed by GC and then reallocated while we're
647    in the process of using it -- this will result in something
648    seemingly unrelated getting trashed, and is extremely
649    difficult to track down.  If the object gets freed but
650    not reallocated, we can usually catch this because we
651    set all bytes of a freed object to 0xDEADBEEF. (The
652    first four bytes, however, are 0xFFFFFFFF, and the next
653    four are a pointer used to chain freed objects together;
654    we play some tricks with this pointer to make it more
655    bogus, so crashes are more likely to occur right away.)
656
657    We want freed objects to stay free as long as possible,
658    so instead of doing what we do above, we maintain the
659    free objects in a first-in first-out queue.  We also
660    don't recompute the free list each GC, unlike above;
661    this ensures that the queue ordering is preserved.
662    [This means that we are likely to have worse locality
663    of reference, and that we can never free a frob block
664    once it's allocated. (Even if we know that all cells
665    in it are free, there's no easy way to remove all those
666    cells from the free list because the objects on the
667    free list are unlikely to be in memory order.)]
668    Furthermore, we never take objects off the free list
669    unless there's a large number (usually 1000, but
670    varies depending on type) of them already on the list.
671    This way, we ensure that an object that gets freed will
672    remain free for the next 1000 (or whatever) times that
673    an object of that type is allocated.  */
674
675 #ifndef MALLOC_OVERHEAD
676 #ifdef GNU_MALLOC
677 #define MALLOC_OVERHEAD 0
678 #elif defined (rcheck)
679 #define MALLOC_OVERHEAD 20
680 #else
681 #define MALLOC_OVERHEAD 8
682 #endif
683 #endif /* MALLOC_OVERHEAD */
684
685 #if !defined(HAVE_MMAP) || defined(DOUG_LEA_MALLOC)
686 /* If we released our reserve (due to running out of memory),
687    and we have a fair amount free once again,
688    try to set aside another reserve in case we run out once more.
689
690    This is called when a relocatable block is freed in ralloc.c.  */
691 void refill_memory_reserve (void);
692 void
693 refill_memory_reserve (void)
694 {
695   if (breathing_space == 0)
696     breathing_space = (char *) malloc (4096 - MALLOC_OVERHEAD);
697 }
698 #endif
699
700 #ifdef ALLOC_NO_POOLS
701 # define TYPE_ALLOC_SIZE(type, structtype) 1
702 #else
703 # define TYPE_ALLOC_SIZE(type, structtype)                      \
704     ((2048 - MALLOC_OVERHEAD - sizeof (struct type##_block *))  \
705      / sizeof (structtype))
706 #endif /* ALLOC_NO_POOLS */
707
708 #define DECLARE_FIXED_TYPE_ALLOC(type, structtype)      \
709                                                         \
710 struct type##_block                                     \
711 {                                                       \
712   struct type##_block *prev;                            \
713   structtype block[TYPE_ALLOC_SIZE (type, structtype)]; \
714 };                                                      \
715                                                         \
716 static struct type##_block *current_##type##_block;     \
717 static int current_##type##_block_index;                \
718                                                         \
719 static structtype *type##_free_list;                    \
720 static structtype *type##_free_list_tail;               \
721                                                         \
722 static void                                             \
723 init_##type##_alloc (void)                              \
724 {                                                       \
725   current_##type##_block = 0;                           \
726   current_##type##_block_index =                        \
727     countof (current_##type##_block->block);            \
728   type##_free_list = 0;                                 \
729   type##_free_list_tail = 0;                            \
730 }                                                       \
731                                                         \
732 static int gc_count_num_##type##_in_use;                \
733 static int gc_count_num_##type##_freelist
734
735 #define ALLOCATE_FIXED_TYPE_FROM_BLOCK(type, result) do {               \
736   if (current_##type##_block_index                                      \
737       == countof (current_##type##_block->block))                       \
738     {                                                                   \
739       struct type##_block *AFTFB_new = (struct type##_block *)          \
740         allocate_lisp_storage (sizeof (struct type##_block));           \
741       AFTFB_new->prev = current_##type##_block;                         \
742       current_##type##_block = AFTFB_new;                               \
743       current_##type##_block_index = 0;                                 \
744     }                                                                   \
745   (result) =                                                            \
746     &(current_##type##_block->block[current_##type##_block_index++]);   \
747 } while (0)
748
749 /* Allocate an instance of a type that is stored in blocks.
750    TYPE is the "name" of the type, STRUCTTYPE is the corresponding
751    structure type. */
752
753 #ifdef ERROR_CHECK_GC
754
755 /* Note: if you get crashes in this function, suspect incorrect calls
756    to free_cons() and friends.  This happened once because the cons
757    cell was not GC-protected and was getting collected before
758    free_cons() was called. */
759
760 #define ALLOCATE_FIXED_TYPE_1(type, structtype, result)                  \
761 do                                                                       \
762 {                                                                        \
763   if (gc_count_num_##type##_freelist >                                   \
764       MINIMUM_ALLOWED_FIXED_TYPE_CELLS_##type)                           \
765     {                                                                    \
766       result = type##_free_list;                                         \
767       /* Before actually using the chain pointer, we complement all its  \
768          bits; see FREE_FIXED_TYPE(). */                                 \
769       type##_free_list =                                                 \
770         (structtype *) ~(unsigned long)                                  \
771           (* (structtype **) ((char *) result + sizeof (void *)));       \
772       gc_count_num_##type##_freelist--;                                  \
773     }                                                                    \
774   else                                                                   \
775     ALLOCATE_FIXED_TYPE_FROM_BLOCK (type, result);                       \
776   MARK_STRUCT_AS_NOT_FREE (result);                                      \
777 } while (0)
778
779 #else /* !ERROR_CHECK_GC */
780
781 #define ALLOCATE_FIXED_TYPE_1(type, structtype, result)         \
782 do                                                              \
783 {                                                               \
784   if (type##_free_list)                                         \
785     {                                                           \
786       result = type##_free_list;                                \
787       type##_free_list =                                        \
788         * (structtype **) ((char *) result + sizeof (void *));  \
789     }                                                           \
790   else                                                          \
791     ALLOCATE_FIXED_TYPE_FROM_BLOCK (type, result);              \
792   MARK_STRUCT_AS_NOT_FREE (result);                             \
793 } while (0)
794
795 #endif /* !ERROR_CHECK_GC */
796
797 #define ALLOCATE_FIXED_TYPE(type, structtype, result)   \
798 do                                                      \
799 {                                                       \
800   ALLOCATE_FIXED_TYPE_1 (type, structtype, result);     \
801   INCREMENT_CONS_COUNTER (sizeof (structtype), #type);  \
802 } while (0)
803
804 #define NOSEEUM_ALLOCATE_FIXED_TYPE(type, structtype, result)   \
805 do                                                              \
806 {                                                               \
807   ALLOCATE_FIXED_TYPE_1 (type, structtype, result);             \
808   NOSEEUM_INCREMENT_CONS_COUNTER (sizeof (structtype), #type);  \
809 } while (0)
810
811 /* INVALID_POINTER_VALUE should be a value that is invalid as a pointer
812    to a Lisp object and invalid as an actual Lisp_Object value.  We have
813    to make sure that this value cannot be an integer in Lisp_Object form.
814    0xFFFFFFFF could be so on a 64-bit system, so we extend it to 64 bits.
815    On a 32-bit system, the type bits will be non-zero, making the value
816    be a pointer, and the pointer will be misaligned.
817
818    Even if Emacs is run on some weirdo system that allows and allocates
819    byte-aligned pointers, this pointer is at the very top of the address
820    space and so it's almost inconceivable that it could ever be valid. */
821
822 #if INTBITS == 32
823 # define INVALID_POINTER_VALUE 0xFFFFFFFF
824 #elif INTBITS == 48
825 # define INVALID_POINTER_VALUE 0xFFFFFFFFFFFF
826 #elif INTBITS == 64
827 # define INVALID_POINTER_VALUE 0xFFFFFFFFFFFFFFFF
828 #else
829 You have some weird system and need to supply a reasonable value here.
830 #endif
831
832 /* The construct (* (void **) (ptr)) would cause aliasing problems
833    with modern optimizing compilers like `gcc -O3 -fstrict-aliasing'.
834    But `char *' can legally alias any pointer.  Hence this union trick. */
835 typedef union { char c; void *p; } *aliasing_voidpp;
836 #define ALIASING_VOIDPP_DEREFERENCE(ptr) \
837   (((aliasing_voidpp) (ptr))->p)
838 #define FREE_STRUCT_P(ptr) \
839   (ALIASING_VOIDPP_DEREFERENCE (ptr) == (void *) INVALID_POINTER_VALUE)
840 #define MARK_STRUCT_AS_FREE(ptr) \
841   (ALIASING_VOIDPP_DEREFERENCE (ptr) = (void *) INVALID_POINTER_VALUE)
842 #define MARK_STRUCT_AS_NOT_FREE(ptr) \
843   (ALIASING_VOIDPP_DEREFERENCE (ptr) = 0)
844
845 #ifdef ERROR_CHECK_GC
846
847 #define PUT_FIXED_TYPE_ON_FREE_LIST(type, structtype, ptr)              \
848 do { if (type##_free_list_tail)                                         \
849        {                                                                \
850          /* When we store the chain pointer, we complement all          \
851             its bits; this should significantly increase its            \
852             bogosity in case someone tries to use the value, and        \
853             should make us dump faster if someone stores something      \
854             over the pointer because when it gets un-complemented in    \
855             ALLOCATED_FIXED_TYPE(), the resulting pointer will be       \
856             extremely bogus. */                                         \
857          * (structtype **)                                              \
858            ((char *) type##_free_list_tail + sizeof (void *)) =         \
859              (structtype *) ~(unsigned long) ptr;                       \
860        }                                                                \
861      else                                                               \
862        type##_free_list = ptr;                                          \
863      type##_free_list_tail = ptr;                                       \
864    } while (0)
865
866 #else /* !ERROR_CHECK_GC */
867
868 #define PUT_FIXED_TYPE_ON_FREE_LIST(type, structtype, ptr)      \
869 do { * (structtype **) ((char *) (ptr) + sizeof (void *)) =     \
870        type##_free_list;                                        \
871      type##_free_list = (ptr);                                  \
872    } while (0)
873
874 #endif /* !ERROR_CHECK_GC */
875
876 /* TYPE and STRUCTTYPE are the same as in ALLOCATE_FIXED_TYPE(). */
877
878 #define FREE_FIXED_TYPE(type, structtype, ptr) do {             \
879   structtype *FFT_ptr = (ptr);                                  \
880   ADDITIONAL_FREE_##type (FFT_ptr);                             \
881   deadbeef_memory (FFT_ptr, sizeof (structtype));               \
882   PUT_FIXED_TYPE_ON_FREE_LIST (type, structtype, FFT_ptr);      \
883   MARK_STRUCT_AS_FREE (FFT_ptr);                                \
884 } while (0)
885
886 /* Like FREE_FIXED_TYPE() but used when we are explicitly
887    freeing a structure through free_cons(), free_marker(), etc.
888    rather than through the normal process of sweeping.
889    We attempt to undo the changes made to the allocation counters
890    as a result of this structure being allocated.  This is not
891    completely necessary but helps keep things saner: e.g. this way,
892    repeatedly allocating and freeing a cons will not result in
893    the consing-since-gc counter advancing, which would cause a GC
894    and somewhat defeat the purpose of explicitly freeing. */
895
896 #define FREE_FIXED_TYPE_WHEN_NOT_IN_GC(type, structtype, ptr)   \
897 do { FREE_FIXED_TYPE (type, structtype, ptr);                   \
898      DECREMENT_CONS_COUNTER (sizeof (structtype));              \
899      gc_count_num_##type##_freelist++;                          \
900    } while (0)
901
902
903 \f
904 /************************************************************************/
905 /*                         Cons allocation                              */
906 /************************************************************************/
907
908 DECLARE_FIXED_TYPE_ALLOC (cons, Lisp_Cons);
909 /* conses are used and freed so often that we set this really high */
910 /* #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_cons 20000 */
911 #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_cons 2000
912
913 static Lisp_Object
914 mark_cons (Lisp_Object obj)
915 {
916   if (NILP (XCDR (obj)))
917     return XCAR (obj);
918
919   mark_object (XCAR (obj));
920   return XCDR (obj);
921 }
922
923 static int
924 cons_equal (Lisp_Object ob1, Lisp_Object ob2, int depth)
925 {
926   depth++;
927   while (internal_equal (XCAR (ob1), XCAR (ob2), depth))
928     {
929       ob1 = XCDR (ob1);
930       ob2 = XCDR (ob2);
931       if (! CONSP (ob1) || ! CONSP (ob2))
932         return internal_equal (ob1, ob2, depth);
933     }
934   return 0;
935 }
936
937 static const struct lrecord_description cons_description[] = {
938   { XD_LISP_OBJECT, offsetof (Lisp_Cons, car) },
939   { XD_LISP_OBJECT, offsetof (Lisp_Cons, cdr) },
940   { XD_END }
941 };
942
943 DEFINE_BASIC_LRECORD_IMPLEMENTATION ("cons", cons,
944                                      mark_cons, print_cons, 0,
945                                      cons_equal,
946                                      /*
947                                       * No `hash' method needed.
948                                       * internal_hash knows how to
949                                       * handle conses.
950                                       */
951                                      0,
952                                      cons_description,
953                                      Lisp_Cons);
954
955 DEFUN ("cons", Fcons, 2, 2, 0, /*
956 Create a new cons, give it CAR and CDR as components, and return it.
957 */
958        (car, cdr))
959 {
960   /* This cannot GC. */
961   Lisp_Object val;
962   Lisp_Cons *c;
963
964   ALLOCATE_FIXED_TYPE (cons, Lisp_Cons, c);
965   set_lheader_implementation (&c->lheader, &lrecord_cons);
966   XSETCONS (val, c);
967   c->car = car;
968   c->cdr = cdr;
969   return val;
970 }
971
972 /* This is identical to Fcons() but it used for conses that we're
973    going to free later, and is useful when trying to track down
974    "real" consing. */
975 Lisp_Object
976 noseeum_cons (Lisp_Object car, Lisp_Object cdr)
977 {
978   Lisp_Object val;
979   Lisp_Cons *c;
980
981   NOSEEUM_ALLOCATE_FIXED_TYPE (cons, Lisp_Cons, c);
982   set_lheader_implementation (&c->lheader, &lrecord_cons);
983   XSETCONS (val, c);
984   XCAR (val) = car;
985   XCDR (val) = cdr;
986   return val;
987 }
988
989 DEFUN ("list", Flist, 0, MANY, 0, /*
990 Return a newly created list with specified arguments as elements.
991 Any number of arguments, even zero arguments, are allowed.
992 */
993        (int nargs, Lisp_Object *args))
994 {
995   Lisp_Object val = Qnil;
996   Lisp_Object *argp = args + nargs;
997
998   while (argp > args)
999     val = Fcons (*--argp, val);
1000   return val;
1001 }
1002
1003 Lisp_Object
1004 list1 (Lisp_Object obj0)
1005 {
1006   /* This cannot GC. */
1007   return Fcons (obj0, Qnil);
1008 }
1009
1010 Lisp_Object
1011 list2 (Lisp_Object obj0, Lisp_Object obj1)
1012 {
1013   /* This cannot GC. */
1014   return Fcons (obj0, Fcons (obj1, Qnil));
1015 }
1016
1017 Lisp_Object
1018 list3 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2)
1019 {
1020   /* This cannot GC. */
1021   return Fcons (obj0, Fcons (obj1, Fcons (obj2, Qnil)));
1022 }
1023
1024 Lisp_Object
1025 cons3 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2)
1026 {
1027   /* This cannot GC. */
1028   return Fcons (obj0, Fcons (obj1, obj2));
1029 }
1030
1031 Lisp_Object
1032 acons (Lisp_Object key, Lisp_Object value, Lisp_Object alist)
1033 {
1034   return Fcons (Fcons (key, value), alist);
1035 }
1036
1037 Lisp_Object
1038 list4 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2, Lisp_Object obj3)
1039 {
1040   /* This cannot GC. */
1041   return Fcons (obj0, Fcons (obj1, Fcons (obj2, Fcons (obj3, Qnil))));
1042 }
1043
1044 Lisp_Object
1045 list5 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2, Lisp_Object obj3,
1046        Lisp_Object obj4)
1047 {
1048   /* This cannot GC. */
1049   return Fcons (obj0, Fcons (obj1, Fcons (obj2, Fcons (obj3, Fcons (obj4, Qnil)))));
1050 }
1051
1052 Lisp_Object
1053 list6 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2, Lisp_Object obj3,
1054        Lisp_Object obj4, Lisp_Object obj5)
1055 {
1056   /* This cannot GC. */
1057   return Fcons (obj0, Fcons (obj1, Fcons (obj2, Fcons (obj3, Fcons (obj4, Fcons (obj5, Qnil))))));
1058 }
1059
1060 DEFUN ("make-list", Fmake_list, 2, 2, 0, /*
1061 Return a new list of length LENGTH, with each element being INIT.
1062 */
1063        (length, init))
1064 {
1065   CHECK_NATNUM (length);
1066
1067   {
1068     Lisp_Object val = Qnil;
1069     size_t size = XINT (length);
1070
1071     while (size--)
1072       val = Fcons (init, val);
1073     return val;
1074   }
1075 }
1076
1077 \f
1078 /************************************************************************/
1079 /*                        Float allocation                              */
1080 /************************************************************************/
1081
1082 #ifdef LISP_FLOAT_TYPE
1083
1084 DECLARE_FIXED_TYPE_ALLOC (float, Lisp_Float);
1085 #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_float 1000
1086
1087 Lisp_Object
1088 make_float (double float_value)
1089 {
1090   Lisp_Object val;
1091   Lisp_Float *f;
1092
1093   ALLOCATE_FIXED_TYPE (float, Lisp_Float, f);
1094
1095   /* Avoid dump-time `uninitialized memory read' purify warnings. */
1096   if (sizeof (struct lrecord_header) + sizeof (double) != sizeof (*f))
1097     xzero (*f);
1098
1099   set_lheader_implementation (&f->lheader, &lrecord_float);
1100   float_data (f) = float_value;
1101   XSETFLOAT (val, f);
1102   return val;
1103 }
1104
1105 #endif /* LISP_FLOAT_TYPE */
1106
1107 \f
1108 /************************************************************************/
1109 /*                         Vector allocation                            */
1110 /************************************************************************/
1111
1112 static Lisp_Object
1113 mark_vector (Lisp_Object obj)
1114 {
1115   Lisp_Vector *ptr = XVECTOR (obj);
1116   int len = vector_length (ptr);
1117   int i;
1118
1119   for (i = 0; i < len - 1; i++)
1120     mark_object (ptr->contents[i]);
1121   return (len > 0) ? ptr->contents[len - 1] : Qnil;
1122 }
1123
1124 static size_t
1125 size_vector (const void *lheader)
1126 {
1127   return FLEXIBLE_ARRAY_STRUCT_SIZEOF (Lisp_Vector, contents,
1128                                        ((Lisp_Vector *) lheader)->size);
1129 }
1130
1131 static int
1132 vector_equal (Lisp_Object obj1, Lisp_Object obj2, int depth)
1133 {
1134   int len = XVECTOR_LENGTH (obj1);
1135   if (len != XVECTOR_LENGTH (obj2))
1136     return 0;
1137
1138   {
1139     Lisp_Object *ptr1 = XVECTOR_DATA (obj1);
1140     Lisp_Object *ptr2 = XVECTOR_DATA (obj2);
1141     while (len--)
1142       if (!internal_equal (*ptr1++, *ptr2++, depth + 1))
1143         return 0;
1144   }
1145   return 1;
1146 }
1147
1148 static hashcode_t
1149 vector_hash (Lisp_Object obj, int depth)
1150 {
1151   return HASH2 (XVECTOR_LENGTH (obj),
1152                 internal_array_hash (XVECTOR_DATA (obj),
1153                                      XVECTOR_LENGTH (obj),
1154                                      depth + 1));
1155 }
1156
1157 static const struct lrecord_description vector_description[] = {
1158   { XD_LONG,              offsetof (Lisp_Vector, size) },
1159   { XD_LISP_OBJECT_ARRAY, offsetof (Lisp_Vector, contents), XD_INDIRECT(0, 0) },
1160   { XD_END }
1161 };
1162
1163 DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION("vector", vector,
1164                                        mark_vector, print_vector, 0,
1165                                        vector_equal,
1166                                        vector_hash,
1167                                        vector_description,
1168                                        size_vector, Lisp_Vector);
1169
1170 /* #### should allocate `small' vectors from a frob-block */
1171 static Lisp_Vector *
1172 make_vector_internal (size_t sizei)
1173 {
1174   /* no vector_next */
1175   size_t sizem = FLEXIBLE_ARRAY_STRUCT_SIZEOF (Lisp_Vector, contents, sizei);
1176   Lisp_Vector *p = (Lisp_Vector *) alloc_lcrecord (sizem, &lrecord_vector);
1177
1178   p->size = sizei;
1179   return p;
1180 }
1181
1182 Lisp_Object
1183 make_vector (size_t length, Lisp_Object init)
1184 {
1185   Lisp_Vector *vecp = make_vector_internal (length);
1186   Lisp_Object *p = vector_data (vecp);
1187
1188   while (length--)
1189     *p++ = init;
1190
1191   {
1192     Lisp_Object vector;
1193     XSETVECTOR (vector, vecp);
1194     return vector;
1195   }
1196 }
1197
1198 #ifdef UTF2000
1199 Lisp_Object
1200 make_older_vector (size_t length, Lisp_Object init)
1201 {
1202   struct lcrecord_header* orig_all_lcrecords = all_lcrecords;
1203   Lisp_Object obj;
1204
1205   all_lcrecords = all_older_lcrecords;
1206   obj = make_vector (length, init);
1207   all_older_lcrecords = all_lcrecords;
1208   all_lcrecords = orig_all_lcrecords;
1209   return obj;
1210 }
1211 #endif
1212
1213 DEFUN ("make-vector", Fmake_vector, 2, 2, 0, /*
1214 Return a new vector of length LENGTH, with each element being INIT.
1215 See also the function `vector'.
1216 */
1217        (length, init))
1218 {
1219   CONCHECK_NATNUM (length);
1220   return make_vector (XINT (length), init);
1221 }
1222
1223 DEFUN ("vector", Fvector, 0, MANY, 0, /*
1224 Return a newly created vector with specified arguments as elements.
1225 Any number of arguments, even zero arguments, are allowed.
1226 */
1227        (int nargs, Lisp_Object *args))
1228 {
1229   Lisp_Vector *vecp = make_vector_internal (nargs);
1230   Lisp_Object *p = vector_data (vecp);
1231
1232   while (nargs--)
1233     *p++ = *args++;
1234
1235   {
1236     Lisp_Object vector;
1237     XSETVECTOR (vector, vecp);
1238     return vector;
1239   }
1240 }
1241
1242 Lisp_Object
1243 vector1 (Lisp_Object obj0)
1244 {
1245   return Fvector (1, &obj0);
1246 }
1247
1248 Lisp_Object
1249 vector2 (Lisp_Object obj0, Lisp_Object obj1)
1250 {
1251   Lisp_Object args[2];
1252   args[0] = obj0;
1253   args[1] = obj1;
1254   return Fvector (2, args);
1255 }
1256
1257 Lisp_Object
1258 vector3 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2)
1259 {
1260   Lisp_Object args[3];
1261   args[0] = obj0;
1262   args[1] = obj1;
1263   args[2] = obj2;
1264   return Fvector (3, args);
1265 }
1266
1267 #if 0 /* currently unused */
1268
1269 Lisp_Object
1270 vector4 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2,
1271          Lisp_Object obj3)
1272 {
1273   Lisp_Object args[4];
1274   args[0] = obj0;
1275   args[1] = obj1;
1276   args[2] = obj2;
1277   args[3] = obj3;
1278   return Fvector (4, args);
1279 }
1280
1281 Lisp_Object
1282 vector5 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2,
1283          Lisp_Object obj3, Lisp_Object obj4)
1284 {
1285   Lisp_Object args[5];
1286   args[0] = obj0;
1287   args[1] = obj1;
1288   args[2] = obj2;
1289   args[3] = obj3;
1290   args[4] = obj4;
1291   return Fvector (5, args);
1292 }
1293
1294 Lisp_Object
1295 vector6 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2,
1296          Lisp_Object obj3, Lisp_Object obj4, Lisp_Object obj5)
1297 {
1298   Lisp_Object args[6];
1299   args[0] = obj0;
1300   args[1] = obj1;
1301   args[2] = obj2;
1302   args[3] = obj3;
1303   args[4] = obj4;
1304   args[5] = obj5;
1305   return Fvector (6, args);
1306 }
1307
1308 Lisp_Object
1309 vector7 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2,
1310          Lisp_Object obj3, Lisp_Object obj4, Lisp_Object obj5,
1311          Lisp_Object obj6)
1312 {
1313   Lisp_Object args[7];
1314   args[0] = obj0;
1315   args[1] = obj1;
1316   args[2] = obj2;
1317   args[3] = obj3;
1318   args[4] = obj4;
1319   args[5] = obj5;
1320   args[6] = obj6;
1321   return Fvector (7, args);
1322 }
1323
1324 Lisp_Object
1325 vector8 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2,
1326          Lisp_Object obj3, Lisp_Object obj4, Lisp_Object obj5,
1327          Lisp_Object obj6, Lisp_Object obj7)
1328 {
1329   Lisp_Object args[8];
1330   args[0] = obj0;
1331   args[1] = obj1;
1332   args[2] = obj2;
1333   args[3] = obj3;
1334   args[4] = obj4;
1335   args[5] = obj5;
1336   args[6] = obj6;
1337   args[7] = obj7;
1338   return Fvector (8, args);
1339 }
1340 #endif /* unused */
1341
1342 /************************************************************************/
1343 /*                       Bit Vector allocation                          */
1344 /************************************************************************/
1345
1346 static Lisp_Object all_bit_vectors;
1347
1348 /* #### should allocate `small' bit vectors from a frob-block */
1349 static Lisp_Bit_Vector *
1350 make_bit_vector_internal (size_t sizei)
1351 {
1352   size_t num_longs = BIT_VECTOR_LONG_STORAGE (sizei);
1353   size_t sizem = FLEXIBLE_ARRAY_STRUCT_SIZEOF (Lisp_Bit_Vector, bits, num_longs);
1354   Lisp_Bit_Vector *p = (Lisp_Bit_Vector *) allocate_lisp_storage (sizem);
1355   set_lheader_implementation (&p->lheader, &lrecord_bit_vector);
1356
1357   INCREMENT_CONS_COUNTER (sizem, "bit-vector");
1358
1359   bit_vector_length (p) = sizei;
1360   bit_vector_next   (p) = all_bit_vectors;
1361   /* make sure the extra bits in the last long are 0; the calling
1362      functions might not set them. */
1363   p->bits[num_longs - 1] = 0;
1364   XSETBIT_VECTOR (all_bit_vectors, p);
1365   return p;
1366 }
1367
1368 Lisp_Object
1369 make_bit_vector (size_t length, Lisp_Object init)
1370 {
1371   Lisp_Bit_Vector *p = make_bit_vector_internal (length);
1372   size_t num_longs = BIT_VECTOR_LONG_STORAGE (length);
1373
1374   CHECK_BIT (init);
1375
1376   if (ZEROP (init))
1377     memset (p->bits, 0, num_longs * sizeof (long));
1378   else
1379     {
1380       size_t bits_in_last = length & (LONGBITS_POWER_OF_2 - 1);
1381       memset (p->bits, ~0, num_longs * sizeof (long));
1382       /* But we have to make sure that the unused bits in the
1383          last long are 0, so that equal/hash is easy. */
1384       if (bits_in_last)
1385         p->bits[num_longs - 1] &= (1 << bits_in_last) - 1;
1386     }
1387
1388   {
1389     Lisp_Object bit_vector;
1390     XSETBIT_VECTOR (bit_vector, p);
1391     return bit_vector;
1392   }
1393 }
1394
1395 Lisp_Object
1396 make_bit_vector_from_byte_vector (unsigned char *bytevec, size_t length)
1397 {
1398   int i;
1399   Lisp_Bit_Vector *p = make_bit_vector_internal (length);
1400
1401   for (i = 0; i < length; i++)
1402     set_bit_vector_bit (p, i, bytevec[i]);
1403
1404   {
1405     Lisp_Object bit_vector;
1406     XSETBIT_VECTOR (bit_vector, p);
1407     return bit_vector;
1408   }
1409 }
1410
1411 DEFUN ("make-bit-vector", Fmake_bit_vector, 2, 2, 0, /*
1412 Return a new bit vector of length LENGTH. with each bit being INIT.
1413 Each element is set to INIT.  See also the function `bit-vector'.
1414 */
1415        (length, init))
1416 {
1417   CONCHECK_NATNUM (length);
1418
1419   return make_bit_vector (XINT (length), init);
1420 }
1421
1422 DEFUN ("bit-vector", Fbit_vector, 0, MANY, 0, /*
1423 Return a newly created bit vector with specified arguments as elements.
1424 Any number of arguments, even zero arguments, are allowed.
1425 */
1426        (int nargs, Lisp_Object *args))
1427 {
1428   int i;
1429   Lisp_Bit_Vector *p = make_bit_vector_internal (nargs);
1430
1431   for (i = 0; i < nargs; i++)
1432     {
1433       CHECK_BIT (args[i]);
1434       set_bit_vector_bit (p, i, !ZEROP (args[i]));
1435     }
1436
1437   {
1438     Lisp_Object bit_vector;
1439     XSETBIT_VECTOR (bit_vector, p);
1440     return bit_vector;
1441   }
1442 }
1443
1444 \f
1445 /************************************************************************/
1446 /*                   Compiled-function allocation                       */
1447 /************************************************************************/
1448
1449 DECLARE_FIXED_TYPE_ALLOC (compiled_function, Lisp_Compiled_Function);
1450 #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_compiled_function 1000
1451
1452 static Lisp_Object
1453 make_compiled_function (void)
1454 {
1455   Lisp_Compiled_Function *f;
1456   Lisp_Object fun;
1457
1458   ALLOCATE_FIXED_TYPE (compiled_function, Lisp_Compiled_Function, f);
1459   set_lheader_implementation (&f->lheader, &lrecord_compiled_function);
1460
1461   f->stack_depth = 0;
1462   f->specpdl_depth = 0;
1463   f->flags.documentationp = 0;
1464   f->flags.interactivep = 0;
1465   f->flags.domainp = 0; /* I18N3 */
1466   f->instructions = Qzero;
1467   f->constants = Qzero;
1468   f->arglist = Qnil;
1469   f->doc_and_interactive = Qnil;
1470 #ifdef COMPILED_FUNCTION_ANNOTATION_HACK
1471   f->annotated = Qnil;
1472 #endif
1473   XSETCOMPILED_FUNCTION (fun, f);
1474   return fun;
1475 }
1476
1477 DEFUN ("make-byte-code", Fmake_byte_code, 4, MANY, 0, /*
1478 Return a new compiled-function object.
1479 Usage: (arglist instructions constants stack-depth
1480         &optional doc-string interactive)
1481 Note that, unlike all other emacs-lisp functions, calling this with five
1482 arguments is NOT the same as calling it with six arguments, the last of
1483 which is nil.  If the INTERACTIVE arg is specified as nil, then that means
1484 that this function was defined with `(interactive)'.  If the arg is not
1485 specified, then that means the function is not interactive.
1486 This is terrible behavior which is retained for compatibility with old
1487 `.elc' files which expect these semantics.
1488 */
1489        (int nargs, Lisp_Object *args))
1490 {
1491 /* In a non-insane world this function would have this arglist...
1492    (arglist instructions constants stack_depth &optional doc_string interactive)
1493  */
1494   Lisp_Object fun = make_compiled_function ();
1495   Lisp_Compiled_Function *f = XCOMPILED_FUNCTION (fun);
1496
1497   Lisp_Object arglist      = args[0];
1498   Lisp_Object instructions = args[1];
1499   Lisp_Object constants    = args[2];
1500   Lisp_Object stack_depth  = args[3];
1501   Lisp_Object doc_string   = (nargs > 4) ? args[4] : Qnil;
1502   Lisp_Object interactive  = (nargs > 5) ? args[5] : Qunbound;
1503
1504   if (nargs < 4 || nargs > 6)
1505     return Fsignal (Qwrong_number_of_arguments,
1506                     list2 (intern ("make-byte-code"), make_int (nargs)));
1507
1508   /* Check for valid formal parameter list now, to allow us to use
1509      SPECBIND_FAST_UNSAFE() later in funcall_compiled_function(). */
1510   {
1511     Lisp_Object symbol, tail;
1512     EXTERNAL_LIST_LOOP_3 (symbol, arglist, tail)
1513       {
1514         CHECK_SYMBOL (symbol);
1515         if (EQ (symbol, Qt)   ||
1516             EQ (symbol, Qnil) ||
1517             SYMBOL_IS_KEYWORD (symbol))
1518           signal_simple_error_2
1519             ("Invalid constant symbol in formal parameter list",
1520              symbol, arglist);
1521       }
1522   }
1523   f->arglist = arglist;
1524
1525   /* `instructions' is a string or a cons (string . int) for a
1526      lazy-loaded function. */
1527   if (CONSP (instructions))
1528     {
1529       CHECK_STRING (XCAR (instructions));
1530       CHECK_INT (XCDR (instructions));
1531     }
1532   else
1533     {
1534       CHECK_STRING (instructions);
1535     }
1536   f->instructions = instructions;
1537
1538   if (!NILP (constants))
1539     CHECK_VECTOR (constants);
1540   f->constants = constants;
1541
1542   CHECK_NATNUM (stack_depth);
1543   f->stack_depth = (unsigned short) XINT (stack_depth);
1544
1545 #ifdef COMPILED_FUNCTION_ANNOTATION_HACK
1546   if (!NILP (Vcurrent_compiled_function_annotation))
1547     f->annotated = Fcopy (Vcurrent_compiled_function_annotation);
1548   else if (!NILP (Vload_file_name_internal_the_purecopy))
1549     f->annotated = Vload_file_name_internal_the_purecopy;
1550   else if (!NILP (Vload_file_name_internal))
1551     {
1552       struct gcpro gcpro1;
1553       GCPRO1 (fun);             /* don't let fun get reaped */
1554       Vload_file_name_internal_the_purecopy =
1555         Ffile_name_nondirectory (Vload_file_name_internal);
1556       f->annotated = Vload_file_name_internal_the_purecopy;
1557       UNGCPRO;
1558     }
1559 #endif /* COMPILED_FUNCTION_ANNOTATION_HACK */
1560
1561   /* doc_string may be nil, string, int, or a cons (string . int).
1562      interactive may be list or string (or unbound). */
1563   f->doc_and_interactive = Qunbound;
1564 #ifdef I18N3
1565   if ((f->flags.domainp = !NILP (Vfile_domain)) != 0)
1566     f->doc_and_interactive = Vfile_domain;
1567 #endif
1568   if ((f->flags.interactivep = !UNBOUNDP (interactive)) != 0)
1569     {
1570       f->doc_and_interactive
1571         = (UNBOUNDP (f->doc_and_interactive) ? interactive :
1572            Fcons (interactive, f->doc_and_interactive));
1573     }
1574   if ((f->flags.documentationp = !NILP (doc_string)) != 0)
1575     {
1576       f->doc_and_interactive
1577         = (UNBOUNDP (f->doc_and_interactive) ? doc_string :
1578            Fcons (doc_string, f->doc_and_interactive));
1579     }
1580   if (UNBOUNDP (f->doc_and_interactive))
1581     f->doc_and_interactive = Qnil;
1582
1583   return fun;
1584 }
1585
1586 \f
1587 /************************************************************************/
1588 /*                          Symbol allocation                           */
1589 /************************************************************************/
1590
1591 DECLARE_FIXED_TYPE_ALLOC (symbol, Lisp_Symbol);
1592 #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_symbol 1000
1593
1594 DEFUN ("make-symbol", Fmake_symbol, 1, 1, 0, /*
1595 Return a newly allocated uninterned symbol whose name is NAME.
1596 Its value and function definition are void, and its property list is nil.
1597 */
1598        (name))
1599 {
1600   Lisp_Object val;
1601   Lisp_Symbol *p;
1602
1603   CHECK_STRING (name);
1604
1605   ALLOCATE_FIXED_TYPE (symbol, Lisp_Symbol, p);
1606   set_lheader_implementation (&p->lheader, &lrecord_symbol);
1607   p->name     = XSTRING (name);
1608   p->plist    = Qnil;
1609   p->value    = Qunbound;
1610   p->function = Qunbound;
1611   symbol_next (p) = 0;
1612   XSETSYMBOL (val, p);
1613   return val;
1614 }
1615
1616 \f
1617 /************************************************************************/
1618 /*                         Extent allocation                            */
1619 /************************************************************************/
1620
1621 DECLARE_FIXED_TYPE_ALLOC (extent, struct extent);
1622 #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_extent 1000
1623
1624 struct extent *
1625 allocate_extent (void)
1626 {
1627   struct extent *e;
1628
1629   ALLOCATE_FIXED_TYPE (extent, struct extent, e);
1630   set_lheader_implementation (&e->lheader, &lrecord_extent);
1631   extent_object (e) = Qnil;
1632   set_extent_start (e, -1);
1633   set_extent_end (e, -1);
1634   e->plist = Qnil;
1635
1636   xzero (e->flags);
1637
1638   extent_face (e) = Qnil;
1639   e->flags.end_open = 1;  /* default is for endpoints to behave like markers */
1640   e->flags.detachable = 1;
1641
1642   return e;
1643 }
1644
1645 \f
1646 /************************************************************************/
1647 /*                         Event allocation                             */
1648 /************************************************************************/
1649
1650 DECLARE_FIXED_TYPE_ALLOC (event, Lisp_Event);
1651 #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_event 1000
1652
1653 Lisp_Object
1654 allocate_event (void)
1655 {
1656   Lisp_Object val;
1657   Lisp_Event *e;
1658
1659   ALLOCATE_FIXED_TYPE (event, Lisp_Event, e);
1660   set_lheader_implementation (&e->lheader, &lrecord_event);
1661
1662   XSETEVENT (val, e);
1663   return val;
1664 }
1665
1666 \f
1667 /************************************************************************/
1668 /*                       Marker allocation                              */
1669 /************************************************************************/
1670
1671 DECLARE_FIXED_TYPE_ALLOC (marker, Lisp_Marker);
1672 #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_marker 1000
1673
1674 DEFUN ("make-marker", Fmake_marker, 0, 0, 0, /*
1675 Return a new marker which does not point at any place.
1676 */
1677        ())
1678 {
1679   Lisp_Object val;
1680   Lisp_Marker *p;
1681
1682   ALLOCATE_FIXED_TYPE (marker, Lisp_Marker, p);
1683   set_lheader_implementation (&p->lheader, &lrecord_marker);
1684   p->buffer = 0;
1685   p->memind = 0;
1686   marker_next (p) = 0;
1687   marker_prev (p) = 0;
1688   p->insertion_type = 0;
1689   XSETMARKER (val, p);
1690   return val;
1691 }
1692
1693 Lisp_Object
1694 noseeum_make_marker (void)
1695 {
1696   Lisp_Object val;
1697   Lisp_Marker *p;
1698
1699   NOSEEUM_ALLOCATE_FIXED_TYPE (marker, Lisp_Marker, p);
1700   set_lheader_implementation (&p->lheader, &lrecord_marker);
1701   p->buffer = 0;
1702   p->memind = 0;
1703   marker_next (p) = 0;
1704   marker_prev (p) = 0;
1705   p->insertion_type = 0;
1706   XSETMARKER (val, p);
1707   return val;
1708 }
1709
1710 \f
1711 /************************************************************************/
1712 /*                        String allocation                             */
1713 /************************************************************************/
1714
1715 /* The data for "short" strings generally resides inside of structs of type
1716    string_chars_block. The Lisp_String structure is allocated just like any
1717    other Lisp object (except for vectors), and these are freelisted when
1718    they get garbage collected. The data for short strings get compacted,
1719    but the data for large strings do not.
1720
1721    Previously Lisp_String structures were relocated, but this caused a lot
1722    of bus-errors because the C code didn't include enough GCPRO's for
1723    strings (since EVERY REFERENCE to a short string needed to be GCPRO'd so
1724    that the reference would get relocated).
1725
1726    This new method makes things somewhat bigger, but it is MUCH safer.  */
1727
1728 DECLARE_FIXED_TYPE_ALLOC (string, Lisp_String);
1729 /* strings are used and freed quite often */
1730 /* #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_string 10000 */
1731 #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_string 1000
1732
1733 static Lisp_Object
1734 mark_string (Lisp_Object obj)
1735 {
1736   Lisp_String *ptr = XSTRING (obj);
1737
1738   if (CONSP (ptr->plist) && EXTENT_INFOP (XCAR (ptr->plist)))
1739     flush_cached_extent_info (XCAR (ptr->plist));
1740   return ptr->plist;
1741 }
1742
1743 static int
1744 string_equal (Lisp_Object obj1, Lisp_Object obj2, int depth)
1745 {
1746   Bytecount len;
1747   return (((len = XSTRING_LENGTH (obj1)) == XSTRING_LENGTH (obj2)) &&
1748           !memcmp (XSTRING_DATA (obj1), XSTRING_DATA (obj2), len));
1749 }
1750
1751 static const struct lrecord_description string_description[] = {
1752   { XD_BYTECOUNT,       offsetof (Lisp_String, size) },
1753   { XD_OPAQUE_DATA_PTR, offsetof (Lisp_String, data), XD_INDIRECT(0, 1) },
1754   { XD_LISP_OBJECT,     offsetof (Lisp_String, plist) },
1755   { XD_END }
1756 };
1757
1758 /* We store the string's extent info as the first element of the string's
1759    property list; and the string's MODIFF as the first or second element
1760    of the string's property list (depending on whether the extent info
1761    is present), but only if the string has been modified.  This is ugly
1762    but it reduces the memory allocated for the string in the vast
1763    majority of cases, where the string is never modified and has no
1764    extent info.
1765
1766    #### This means you can't use an int as a key in a string's plist. */
1767
1768 static Lisp_Object *
1769 string_plist_ptr (Lisp_Object string)
1770 {
1771   Lisp_Object *ptr = &XSTRING (string)->plist;
1772
1773   if (CONSP (*ptr) && EXTENT_INFOP (XCAR (*ptr)))
1774     ptr = &XCDR (*ptr);
1775   if (CONSP (*ptr) && INTP (XCAR (*ptr)))
1776     ptr = &XCDR (*ptr);
1777   return ptr;
1778 }
1779
1780 static Lisp_Object
1781 string_getprop (Lisp_Object string, Lisp_Object property)
1782 {
1783   return external_plist_get (string_plist_ptr (string), property, 0, ERROR_ME);
1784 }
1785
1786 static int
1787 string_putprop (Lisp_Object string, Lisp_Object property, Lisp_Object value)
1788 {
1789   external_plist_put (string_plist_ptr (string), property, value, 0, ERROR_ME);
1790   return 1;
1791 }
1792
1793 static int
1794 string_remprop (Lisp_Object string, Lisp_Object property)
1795 {
1796   return external_remprop (string_plist_ptr (string), property, 0, ERROR_ME);
1797 }
1798
1799 static Lisp_Object
1800 string_plist (Lisp_Object string)
1801 {
1802   return *string_plist_ptr (string);
1803 }
1804
1805 /* No `finalize', or `hash' methods.
1806    internal_hash() already knows how to hash strings and finalization
1807    is done with the ADDITIONAL_FREE_string macro, which is the
1808    standard way to do finalization when using
1809    SWEEP_FIXED_TYPE_BLOCK(). */
1810 DEFINE_BASIC_LRECORD_IMPLEMENTATION_WITH_PROPS ("string", string,
1811                                                 mark_string, print_string,
1812                                                 0, string_equal, 0,
1813                                                 string_description,
1814                                                 string_getprop,
1815                                                 string_putprop,
1816                                                 string_remprop,
1817                                                 string_plist,
1818                                                 Lisp_String);
1819
1820 /* String blocks contain this many useful bytes. */
1821 #define STRING_CHARS_BLOCK_SIZE                                 \
1822 ((Bytecount) (8192 - MALLOC_OVERHEAD -                          \
1823               ((2 * sizeof (struct string_chars_block *))       \
1824                + sizeof (EMACS_INT))))
1825 /* Block header for small strings. */
1826 struct string_chars_block
1827 {
1828   EMACS_INT pos;
1829   struct string_chars_block *next;
1830   struct string_chars_block *prev;
1831   /* Contents of string_chars_block->string_chars are interleaved
1832      string_chars structures (see below) and the actual string data */
1833   unsigned char string_chars[STRING_CHARS_BLOCK_SIZE];
1834 };
1835
1836 static struct string_chars_block *first_string_chars_block;
1837 static struct string_chars_block *current_string_chars_block;
1838
1839 /* If SIZE is the length of a string, this returns how many bytes
1840  *  the string occupies in string_chars_block->string_chars
1841  *  (including alignment padding).
1842  */
1843 #define STRING_FULLSIZE(size) \
1844    ALIGN_SIZE (((size) + 1 + sizeof (Lisp_String *)),\
1845                ALIGNOF (Lisp_String *))
1846
1847 #define BIG_STRING_FULLSIZE_P(fullsize) ((fullsize) >= STRING_CHARS_BLOCK_SIZE)
1848 #define BIG_STRING_SIZE_P(size) (BIG_STRING_FULLSIZE_P (STRING_FULLSIZE(size)))
1849
1850 struct string_chars
1851 {
1852   Lisp_String *string;
1853   unsigned char chars[1];
1854 };
1855
1856 struct unused_string_chars
1857 {
1858   Lisp_String *string;
1859   EMACS_INT fullsize;
1860 };
1861
1862 static void
1863 init_string_chars_alloc (void)
1864 {
1865   first_string_chars_block = xnew (struct string_chars_block);
1866   first_string_chars_block->prev = 0;
1867   first_string_chars_block->next = 0;
1868   first_string_chars_block->pos = 0;
1869   current_string_chars_block = first_string_chars_block;
1870 }
1871
1872 static struct string_chars *
1873 allocate_string_chars_struct (Lisp_String *string_it_goes_with,
1874                               EMACS_INT fullsize)
1875 {
1876   struct string_chars *s_chars;
1877
1878   if (fullsize <=
1879       (countof (current_string_chars_block->string_chars)
1880        - current_string_chars_block->pos))
1881     {
1882       /* This string can fit in the current string chars block */
1883       s_chars = (struct string_chars *)
1884         (current_string_chars_block->string_chars
1885          + current_string_chars_block->pos);
1886       current_string_chars_block->pos += fullsize;
1887     }
1888   else
1889     {
1890       /* Make a new current string chars block */
1891       struct string_chars_block *new_scb = xnew (struct string_chars_block);
1892
1893       current_string_chars_block->next = new_scb;
1894       new_scb->prev = current_string_chars_block;
1895       new_scb->next = 0;
1896       current_string_chars_block = new_scb;
1897       new_scb->pos = fullsize;
1898       s_chars = (struct string_chars *)
1899         current_string_chars_block->string_chars;
1900     }
1901
1902   s_chars->string = string_it_goes_with;
1903
1904   INCREMENT_CONS_COUNTER (fullsize, "string chars");
1905
1906   return s_chars;
1907 }
1908
1909 Lisp_Object
1910 make_uninit_string (Bytecount length)
1911 {
1912   Lisp_String *s;
1913   EMACS_INT fullsize = STRING_FULLSIZE (length);
1914   Lisp_Object val;
1915
1916   assert (length >= 0 && fullsize > 0);
1917
1918   /* Allocate the string header */
1919   ALLOCATE_FIXED_TYPE (string, Lisp_String, s);
1920   set_lheader_implementation (&s->lheader, &lrecord_string);
1921
1922   set_string_data (s, BIG_STRING_FULLSIZE_P (fullsize)
1923                    ? xnew_array (Bufbyte, length + 1)
1924                    : allocate_string_chars_struct (s, fullsize)->chars);
1925
1926   set_string_length (s, length);
1927   s->plist = Qnil;
1928
1929   set_string_byte (s, length, 0);
1930
1931   XSETSTRING (val, s);
1932   return val;
1933 }
1934
1935 #ifdef VERIFY_STRING_CHARS_INTEGRITY
1936 static void verify_string_chars_integrity (void);
1937 #endif
1938
1939 /* Resize the string S so that DELTA bytes can be inserted starting
1940    at POS.  If DELTA < 0, it means deletion starting at POS.  If
1941    POS < 0, resize the string but don't copy any characters.  Use
1942    this if you're planning on completely overwriting the string.
1943 */
1944
1945 void
1946 resize_string (Lisp_String *s, Bytecount pos, Bytecount delta)
1947 {
1948   Bytecount oldfullsize, newfullsize;
1949 #ifdef VERIFY_STRING_CHARS_INTEGRITY
1950   verify_string_chars_integrity ();
1951 #endif
1952
1953 #ifdef ERROR_CHECK_BUFPOS
1954   if (pos >= 0)
1955     {
1956       assert (pos <= string_length (s));
1957       if (delta < 0)
1958         assert (pos + (-delta) <= string_length (s));
1959     }
1960   else
1961     {
1962       if (delta < 0)
1963         assert ((-delta) <= string_length (s));
1964     }
1965 #endif /* ERROR_CHECK_BUFPOS */
1966
1967   if (delta == 0)
1968     /* simplest case: no size change. */
1969     return;
1970
1971   if (pos >= 0 && delta < 0)
1972     /* If DELTA < 0, the functions below will delete the characters
1973        before POS.  We want to delete characters *after* POS, however,
1974        so convert this to the appropriate form. */
1975     pos += -delta;
1976
1977   oldfullsize = STRING_FULLSIZE (string_length (s));
1978   newfullsize = STRING_FULLSIZE (string_length (s) + delta);
1979
1980   if (BIG_STRING_FULLSIZE_P (oldfullsize))
1981     {
1982       if (BIG_STRING_FULLSIZE_P (newfullsize))
1983         {
1984           /* Both strings are big.  We can just realloc().
1985              But careful!  If the string is shrinking, we have to
1986              memmove() _before_ realloc(), and if growing, we have to
1987              memmove() _after_ realloc() - otherwise the access is
1988              illegal, and we might crash. */
1989           Bytecount len = string_length (s) + 1 - pos;
1990
1991           if (delta < 0 && pos >= 0)
1992             memmove (string_data (s) + pos + delta, string_data (s) + pos, len);
1993           set_string_data (s, (Bufbyte *) xrealloc (string_data (s),
1994                                                     string_length (s) + delta + 1));
1995           if (delta > 0 && pos >= 0)
1996             memmove (string_data (s) + pos + delta, string_data (s) + pos, len);
1997         }
1998       else /* String has been demoted from BIG_STRING. */
1999         {
2000           Bufbyte *new_data =
2001             allocate_string_chars_struct (s, newfullsize)->chars;
2002           Bufbyte *old_data = string_data (s);
2003
2004           if (pos >= 0)
2005             {
2006               memcpy (new_data, old_data, pos);
2007               memcpy (new_data + pos + delta, old_data + pos,
2008                       string_length (s) + 1 - pos);
2009             }
2010           set_string_data (s, new_data);
2011           xfree (old_data);
2012         }
2013     }
2014   else /* old string is small */
2015     {
2016       if (oldfullsize == newfullsize)
2017         {
2018           /* special case; size change but the necessary
2019              allocation size won't change (up or down; code
2020              somewhere depends on there not being any unused
2021              allocation space, modulo any alignment
2022              constraints). */
2023           if (pos >= 0)
2024             {
2025               Bufbyte *addroff = pos + string_data (s);
2026
2027               memmove (addroff + delta, addroff,
2028                        /* +1 due to zero-termination. */
2029                        string_length (s) + 1 - pos);
2030             }
2031         }
2032       else
2033         {
2034           Bufbyte *old_data = string_data (s);
2035           Bufbyte *new_data =
2036             BIG_STRING_FULLSIZE_P (newfullsize)
2037             ? xnew_array (Bufbyte, string_length (s) + delta + 1)
2038             : allocate_string_chars_struct (s, newfullsize)->chars;
2039
2040           if (pos >= 0)
2041             {
2042               memcpy (new_data, old_data, pos);
2043               memcpy (new_data + pos + delta, old_data + pos,
2044                       string_length (s) + 1 - pos);
2045             }
2046           set_string_data (s, new_data);
2047
2048           {
2049             /* We need to mark this chunk of the string_chars_block
2050                as unused so that compact_string_chars() doesn't
2051                freak. */
2052             struct string_chars *old_s_chars = (struct string_chars *)
2053               ((char *) old_data - offsetof (struct string_chars, chars));
2054             /* Sanity check to make sure we aren't hosed by strange
2055                alignment/padding. */
2056             assert (old_s_chars->string == s);
2057             MARK_STRUCT_AS_FREE (old_s_chars);
2058             ((struct unused_string_chars *) old_s_chars)->fullsize =
2059               oldfullsize;
2060           }
2061         }
2062     }
2063
2064   set_string_length (s, string_length (s) + delta);
2065   /* If pos < 0, the string won't be zero-terminated.
2066      Terminate now just to make sure. */
2067   string_data (s)[string_length (s)] = '\0';
2068
2069   if (pos >= 0)
2070     {
2071       Lisp_Object string;
2072
2073       XSETSTRING (string, s);
2074       /* We also have to adjust all of the extent indices after the
2075          place we did the change.  We say "pos - 1" because
2076          adjust_extents() is exclusive of the starting position
2077          passed to it. */
2078       adjust_extents (string, pos - 1, string_length (s),
2079                       delta);
2080     }
2081
2082 #ifdef VERIFY_STRING_CHARS_INTEGRITY
2083   verify_string_chars_integrity ();
2084 #endif
2085 }
2086
2087 #ifdef MULE
2088
2089 void
2090 set_string_char (Lisp_String *s, Charcount i, Emchar c)
2091 {
2092   Bufbyte newstr[MAX_EMCHAR_LEN];
2093   Bytecount bytoff = charcount_to_bytecount (string_data (s), i);
2094   Bytecount oldlen = charcount_to_bytecount (string_data (s) + bytoff, 1);
2095   Bytecount newlen = set_charptr_emchar (newstr, c);
2096
2097   if (oldlen != newlen)
2098     resize_string (s, bytoff, newlen - oldlen);
2099   /* Remember, string_data (s) might have changed so we can't cache it. */
2100   memcpy (string_data (s) + bytoff, newstr, newlen);
2101 }
2102
2103 #endif /* MULE */
2104
2105 DEFUN ("make-string", Fmake_string, 2, 2, 0, /*
2106 Return a new string of length LENGTH, with each character being INIT.
2107 LENGTH must be an integer and INIT must be a character.
2108 */
2109        (length, init))
2110 {
2111   CHECK_NATNUM (length);
2112   CHECK_CHAR_COERCE_INT (init);
2113   {
2114     Bufbyte init_str[MAX_EMCHAR_LEN];
2115     int len = set_charptr_emchar (init_str, XCHAR (init));
2116     Lisp_Object val = make_uninit_string (len * XINT (length));
2117
2118     if (len == 1)
2119       /* Optimize the single-byte case */
2120       memset (XSTRING_DATA (val), XCHAR (init), XSTRING_LENGTH (val));
2121     else
2122       {
2123         size_t i;
2124         Bufbyte *ptr = XSTRING_DATA (val);
2125
2126         for (i = XINT (length); i; i--)
2127           {
2128             Bufbyte *init_ptr = init_str;
2129             switch (len)
2130               {
2131 #ifdef UTF2000
2132               case 6: *ptr++ = *init_ptr++;
2133               case 5: *ptr++ = *init_ptr++;
2134 #endif
2135               case 4: *ptr++ = *init_ptr++;
2136               case 3: *ptr++ = *init_ptr++;
2137               case 2: *ptr++ = *init_ptr++;
2138               case 1: *ptr++ = *init_ptr++;
2139               }
2140           }
2141       }
2142     return val;
2143   }
2144 }
2145
2146 DEFUN ("string", Fstring, 0, MANY, 0, /*
2147 Concatenate all the argument characters and make the result a string.
2148 */
2149        (int nargs, Lisp_Object *args))
2150 {
2151   Bufbyte *storage = alloca_array (Bufbyte, nargs * MAX_EMCHAR_LEN);
2152   Bufbyte *p = storage;
2153
2154   for (; nargs; nargs--, args++)
2155     {
2156       Lisp_Object lisp_char = *args;
2157       CHECK_CHAR_COERCE_INT (lisp_char);
2158       p += set_charptr_emchar (p, XCHAR (lisp_char));
2159     }
2160   return make_string (storage, p - storage);
2161 }
2162
2163
2164 /* Take some raw memory, which MUST already be in internal format,
2165    and package it up into a Lisp string. */
2166 Lisp_Object
2167 make_string (const Bufbyte *contents, Bytecount length)
2168 {
2169   Lisp_Object val;
2170
2171   /* Make sure we find out about bad make_string's when they happen */
2172 #if defined (ERROR_CHECK_BUFPOS) && defined (MULE)
2173   bytecount_to_charcount (contents, length); /* Just for the assertions */
2174 #endif
2175
2176   val = make_uninit_string (length);
2177   memcpy (XSTRING_DATA (val), contents, length);
2178   return val;
2179 }
2180
2181 /* Take some raw memory, encoded in some external data format,
2182    and convert it into a Lisp string. */
2183 Lisp_Object
2184 make_ext_string (const Extbyte *contents, EMACS_INT length,
2185                  Lisp_Object coding_system)
2186 {
2187   Lisp_Object string;
2188   TO_INTERNAL_FORMAT (DATA, (contents, length),
2189                       LISP_STRING, string,
2190                       coding_system);
2191   return string;
2192 }
2193
2194 Lisp_Object
2195 build_string (const char *str)
2196 {
2197   /* Some strlen's crash and burn if passed null. */
2198   return make_string ((const Bufbyte *) str, (str ? strlen(str) : 0));
2199 }
2200
2201 Lisp_Object
2202 build_ext_string (const char *str, Lisp_Object coding_system)
2203 {
2204   /* Some strlen's crash and burn if passed null. */
2205   return make_ext_string ((const Extbyte *) str, (str ? strlen(str) : 0),
2206                           coding_system);
2207 }
2208
2209 Lisp_Object
2210 build_translated_string (const char *str)
2211 {
2212   return build_string (GETTEXT (str));
2213 }
2214
2215 Lisp_Object
2216 make_string_nocopy (const Bufbyte *contents, Bytecount length)
2217 {
2218   Lisp_String *s;
2219   Lisp_Object val;
2220
2221   /* Make sure we find out about bad make_string_nocopy's when they happen */
2222 #if defined (ERROR_CHECK_BUFPOS) && defined (MULE)
2223   bytecount_to_charcount (contents, length); /* Just for the assertions */
2224 #endif
2225
2226   /* Allocate the string header */
2227   ALLOCATE_FIXED_TYPE (string, Lisp_String, s);
2228   set_lheader_implementation (&s->lheader, &lrecord_string);
2229   SET_C_READONLY_RECORD_HEADER (&s->lheader);
2230   s->plist = Qnil;
2231   set_string_data (s, (Bufbyte *)contents);
2232   set_string_length (s, length);
2233
2234   XSETSTRING (val, s);
2235   return val;
2236 }
2237
2238 \f
2239 /************************************************************************/
2240 /*                           lcrecord lists                             */
2241 /************************************************************************/
2242
2243 /* Lcrecord lists are used to manage the allocation of particular
2244    sorts of lcrecords, to avoid calling alloc_lcrecord() (and thus
2245    malloc() and garbage-collection junk) as much as possible.
2246    It is similar to the Blocktype class.
2247
2248    It works like this:
2249
2250    1) Create an lcrecord-list object using make_lcrecord_list().
2251       This is often done at initialization.  Remember to staticpro_nodump
2252       this object!  The arguments to make_lcrecord_list() are the
2253       same as would be passed to alloc_lcrecord().
2254    2) Instead of calling alloc_lcrecord(), call allocate_managed_lcrecord()
2255       and pass the lcrecord-list earlier created.
2256    3) When done with the lcrecord, call free_managed_lcrecord().
2257       The standard freeing caveats apply: ** make sure there are no
2258       pointers to the object anywhere! **
2259    4) Calling free_managed_lcrecord() is just like kissing the
2260       lcrecord goodbye as if it were garbage-collected.  This means:
2261       -- the contents of the freed lcrecord are undefined, and the
2262          contents of something produced by allocate_managed_lcrecord()
2263          are undefined, just like for alloc_lcrecord().
2264       -- the mark method for the lcrecord's type will *NEVER* be called
2265          on freed lcrecords.
2266       -- the finalize method for the lcrecord's type will be called
2267          at the time that free_managed_lcrecord() is called.
2268
2269    */
2270
2271 static Lisp_Object
2272 mark_lcrecord_list (Lisp_Object obj)
2273 {
2274   struct lcrecord_list *list = XLCRECORD_LIST (obj);
2275   Lisp_Object chain = list->free;
2276
2277   while (!NILP (chain))
2278     {
2279       struct lrecord_header *lheader = XRECORD_LHEADER (chain);
2280       struct free_lcrecord_header *free_header =
2281         (struct free_lcrecord_header *) lheader;
2282
2283       gc_checking_assert
2284         (/* There should be no other pointers to the free list. */
2285          ! MARKED_RECORD_HEADER_P (lheader)
2286          &&
2287          /* Only lcrecords should be here. */
2288          ! LHEADER_IMPLEMENTATION (lheader)->basic_p
2289          &&
2290          /* Only free lcrecords should be here. */
2291          free_header->lcheader.free
2292          &&
2293          /* The type of the lcrecord must be right. */
2294          LHEADER_IMPLEMENTATION (lheader) == list->implementation
2295          &&
2296          /* So must the size. */
2297          (LHEADER_IMPLEMENTATION (lheader)->static_size == 0 ||
2298           LHEADER_IMPLEMENTATION (lheader)->static_size == list->size)
2299          );
2300
2301       MARK_RECORD_HEADER (lheader);
2302       chain = free_header->chain;
2303     }
2304
2305   return Qnil;
2306 }
2307
2308 DEFINE_LRECORD_IMPLEMENTATION ("lcrecord-list", lcrecord_list,
2309                                mark_lcrecord_list, internal_object_printer,
2310                                0, 0, 0, 0, struct lcrecord_list);
2311 Lisp_Object
2312 make_lcrecord_list (size_t size,
2313                     const struct lrecord_implementation *implementation)
2314 {
2315   struct lcrecord_list *p = alloc_lcrecord_type (struct lcrecord_list,
2316                                                  &lrecord_lcrecord_list);
2317   Lisp_Object val;
2318
2319   p->implementation = implementation;
2320   p->size = size;
2321   p->free = Qnil;
2322   XSETLCRECORD_LIST (val, p);
2323   return val;
2324 }
2325
2326 Lisp_Object
2327 allocate_managed_lcrecord (Lisp_Object lcrecord_list)
2328 {
2329   struct lcrecord_list *list = XLCRECORD_LIST (lcrecord_list);
2330   if (!NILP (list->free))
2331     {
2332       Lisp_Object val = list->free;
2333       struct free_lcrecord_header *free_header =
2334         (struct free_lcrecord_header *) XPNTR (val);
2335
2336 #ifdef ERROR_CHECK_GC
2337       struct lrecord_header *lheader = &free_header->lcheader.lheader;
2338
2339       /* There should be no other pointers to the free list. */
2340       assert (! MARKED_RECORD_HEADER_P (lheader));
2341       /* Only lcrecords should be here. */
2342       assert (! LHEADER_IMPLEMENTATION (lheader)->basic_p);
2343       /* Only free lcrecords should be here. */
2344       assert (free_header->lcheader.free);
2345       /* The type of the lcrecord must be right. */
2346       assert (LHEADER_IMPLEMENTATION (lheader) == list->implementation);
2347       /* So must the size. */
2348       assert (LHEADER_IMPLEMENTATION (lheader)->static_size == 0 ||
2349               LHEADER_IMPLEMENTATION (lheader)->static_size == list->size);
2350 #endif /* ERROR_CHECK_GC */
2351
2352       list->free = free_header->chain;
2353       free_header->lcheader.free = 0;
2354       return val;
2355     }
2356   else
2357     {
2358       Lisp_Object val;
2359
2360       XSETOBJ (val, Lisp_Type_Record,
2361                alloc_lcrecord (list->size, list->implementation));
2362       return val;
2363     }
2364 }
2365
2366 void
2367 free_managed_lcrecord (Lisp_Object lcrecord_list, Lisp_Object lcrecord)
2368 {
2369   struct lcrecord_list *list = XLCRECORD_LIST (lcrecord_list);
2370   struct free_lcrecord_header *free_header =
2371     (struct free_lcrecord_header *) XPNTR (lcrecord);
2372   struct lrecord_header *lheader = &free_header->lcheader.lheader;
2373   const struct lrecord_implementation *implementation
2374     = LHEADER_IMPLEMENTATION (lheader);
2375
2376   /* Make sure the size is correct.  This will catch, for example,
2377      putting a window configuration on the wrong free list. */
2378   gc_checking_assert ((implementation->size_in_bytes_method ?
2379                        implementation->size_in_bytes_method (lheader) :
2380                        implementation->static_size)
2381                       == list->size);
2382
2383   if (implementation->finalizer)
2384     implementation->finalizer (lheader, 0);
2385   free_header->chain = list->free;
2386   free_header->lcheader.free = 1;
2387   list->free = lcrecord;
2388 }
2389
2390 \f
2391
2392 \f
2393 DEFUN ("purecopy", Fpurecopy, 1, 1, 0, /*
2394 Kept for compatibility, returns its argument.
2395 Old:
2396 Make a copy of OBJECT in pure storage.
2397 Recursively copies contents of vectors and cons cells.
2398 Does not copy symbols.
2399 */
2400        (obj))
2401 {
2402   return obj;
2403 }
2404
2405 \f
2406 /************************************************************************/
2407 /*                         Garbage Collection                           */
2408 /************************************************************************/
2409
2410 /* All the built-in lisp object types are enumerated in `enum lrecord_type'.
2411    Additional ones may be defined by a module (none yet).  We leave some
2412    room in `lrecord_implementations_table' for such new lisp object types. */
2413 #define MODULE_DEFINABLE_TYPE_COUNT 32
2414 const struct lrecord_implementation *lrecord_implementations_table[lrecord_type_count + MODULE_DEFINABLE_TYPE_COUNT];
2415
2416 /* Object marker functions are in the lrecord_implementation structure.
2417    But copying them to a parallel array is much more cache-friendly.
2418    This hack speeds up (garbage-collect) by about 5%. */
2419 Lisp_Object (*lrecord_markers[countof (lrecord_implementations_table)]) (Lisp_Object);
2420
2421 struct gcpro *gcprolist;
2422
2423 /* 415 used Mly 29-Jun-93 */
2424 /* 1327 used slb 28-Feb-98 */
2425 /* 1328 used og  03-Oct-99 (moving slowly, heh?) */
2426 #ifdef HAVE_SHLIB
2427 #define NSTATICS 4000
2428 #else
2429 #define NSTATICS 2000
2430 #endif
2431
2432 /* Not "static" because used by dumper.c */
2433 Lisp_Object *staticvec[NSTATICS];
2434 int staticidx;
2435
2436 /* Put an entry in staticvec, pointing at the variable whose address is given
2437  */
2438 void
2439 staticpro (Lisp_Object *varaddress)
2440 {
2441   /* #### This is now a dubious assert() since this routine may be called */
2442   /* by Lisp attempting to load a DLL. */
2443   assert (staticidx < countof (staticvec));
2444   staticvec[staticidx++] = varaddress;
2445 }
2446
2447
2448 Lisp_Object *staticvec_nodump[200];
2449 int staticidx_nodump;
2450
2451 /* Put an entry in staticvec_nodump, pointing at the variable whose address is given
2452  */
2453 void
2454 staticpro_nodump (Lisp_Object *varaddress)
2455 {
2456   /* #### This is now a dubious assert() since this routine may be called */
2457   /* by Lisp attempting to load a DLL. */
2458   assert (staticidx_nodump < countof (staticvec_nodump));
2459   staticvec_nodump[staticidx_nodump++] = varaddress;
2460 }
2461
2462
2463 struct pdump_dumpstructinfo dumpstructvec[200];
2464 int dumpstructidx;
2465
2466 /* Put an entry in dumpstructvec, pointing at the variable whose address is given
2467  */
2468 void
2469 dumpstruct (void *varaddress, const struct struct_description *desc)
2470 {
2471   assert (dumpstructidx < countof (dumpstructvec));
2472   dumpstructvec[dumpstructidx].data = varaddress;
2473   dumpstructvec[dumpstructidx].desc = desc;
2474   dumpstructidx++;
2475 }
2476
2477 struct pdump_dumpopaqueinfo dumpopaquevec[250];
2478 int dumpopaqueidx;
2479
2480 /* Put an entry in dumpopaquevec, pointing at the variable whose address is given
2481  */
2482 void
2483 dumpopaque (void *varaddress, size_t size)
2484 {
2485   assert (dumpopaqueidx < countof (dumpopaquevec));
2486
2487   dumpopaquevec[dumpopaqueidx].data = varaddress;
2488   dumpopaquevec[dumpopaqueidx].size = size;
2489   dumpopaqueidx++;
2490 }
2491
2492 Lisp_Object *pdump_wirevec[50];
2493 int pdump_wireidx;
2494
2495 /* Put an entry in pdump_wirevec, pointing at the variable whose address is given
2496  */
2497 void
2498 pdump_wire (Lisp_Object *varaddress)
2499 {
2500   assert (pdump_wireidx < countof (pdump_wirevec));
2501   pdump_wirevec[pdump_wireidx++] = varaddress;
2502 }
2503
2504
2505 Lisp_Object *pdump_wirevec_list[50];
2506 int pdump_wireidx_list;
2507
2508 /* Put an entry in pdump_wirevec_list, pointing at the variable whose address is given
2509  */
2510 void
2511 pdump_wire_list (Lisp_Object *varaddress)
2512 {
2513   assert (pdump_wireidx_list < countof (pdump_wirevec_list));
2514   pdump_wirevec_list[pdump_wireidx_list++] = varaddress;
2515 }
2516
2517 #ifdef ERROR_CHECK_GC
2518 #define GC_CHECK_LHEADER_INVARIANTS(lheader) do {               \
2519   struct lrecord_header * GCLI_lh = (lheader);                  \
2520   assert (GCLI_lh != 0);                                        \
2521   assert (GCLI_lh->type < lrecord_type_count);                  \
2522   assert (! C_READONLY_RECORD_HEADER_P (GCLI_lh) ||             \
2523           (MARKED_RECORD_HEADER_P (GCLI_lh) &&                  \
2524            LISP_READONLY_RECORD_HEADER_P (GCLI_lh)));           \
2525 } while (0)
2526 #else
2527 #define GC_CHECK_LHEADER_INVARIANTS(lheader)
2528 #endif
2529
2530 \f
2531 /* Mark reference to a Lisp_Object.  If the object referred to has not been
2532    seen yet, recursively mark all the references contained in it. */
2533
2534 void
2535 mark_object (Lisp_Object obj)
2536 {
2537  tail_recurse:
2538
2539   /* Checks we used to perform */
2540   /* if (EQ (obj, Qnull_pointer)) return; */
2541   /* if (!POINTER_TYPE_P (XGCTYPE (obj))) return; */
2542   /* if (PURIFIED (XPNTR (obj))) return; */
2543
2544   if (XTYPE (obj) == Lisp_Type_Record)
2545     {
2546       struct lrecord_header *lheader = XRECORD_LHEADER (obj);
2547
2548       GC_CHECK_LHEADER_INVARIANTS (lheader);
2549
2550       gc_checking_assert (LHEADER_IMPLEMENTATION (lheader)->basic_p ||
2551                           ! ((struct lcrecord_header *) lheader)->free);
2552
2553       /* All c_readonly objects have their mark bit set,
2554          so that we only need to check the mark bit here. */
2555       if ( (!MARKED_RECORD_HEADER_P (lheader))
2556 #ifdef UTF2000
2557            && (!OLDER_RECORD_HEADER_P (lheader))
2558 #endif
2559            )
2560         {
2561           MARK_RECORD_HEADER (lheader);
2562
2563           if (RECORD_MARKER (lheader))
2564             {
2565               obj = RECORD_MARKER (lheader) (obj);
2566               if (!NILP (obj)) goto tail_recurse;
2567             }
2568         }
2569     }
2570 }
2571
2572 /* mark all of the conses in a list and mark the final cdr; but
2573    DO NOT mark the cars.
2574
2575    Use only for internal lists!  There should never be other pointers
2576    to the cons cells, because if so, the cars will remain unmarked
2577    even when they maybe should be marked. */
2578 void
2579 mark_conses_in_list (Lisp_Object obj)
2580 {
2581   Lisp_Object rest;
2582
2583   for (rest = obj; CONSP (rest); rest = XCDR (rest))
2584     {
2585       if (CONS_MARKED_P (XCONS (rest)))
2586         return;
2587       MARK_CONS (XCONS (rest));
2588     }
2589
2590   mark_object (rest);
2591 }
2592
2593 \f
2594 /* Find all structures not marked, and free them. */
2595
2596 static int gc_count_num_bit_vector_used, gc_count_bit_vector_total_size;
2597 static int gc_count_bit_vector_storage;
2598 static int gc_count_num_short_string_in_use;
2599 static int gc_count_string_total_size;
2600 static int gc_count_short_string_total_size;
2601
2602 /* static int gc_count_total_records_used, gc_count_records_total_size; */
2603
2604 \f
2605 /* stats on lcrecords in use - kinda kludgy */
2606
2607 static struct
2608 {
2609   int instances_in_use;
2610   int bytes_in_use;
2611   int instances_freed;
2612   int bytes_freed;
2613   int instances_on_free_list;
2614 } lcrecord_stats [countof (lrecord_implementations_table)];
2615
2616 static void
2617 tick_lcrecord_stats (const struct lrecord_header *h, int free_p)
2618 {
2619   unsigned int type_index = h->type;
2620
2621   if (((struct lcrecord_header *) h)->free)
2622     {
2623       gc_checking_assert (!free_p);
2624       lcrecord_stats[type_index].instances_on_free_list++;
2625     }
2626   else
2627     {
2628       const struct lrecord_implementation *implementation =
2629         LHEADER_IMPLEMENTATION (h);
2630
2631       size_t sz = (implementation->size_in_bytes_method ?
2632                    implementation->size_in_bytes_method (h) :
2633                    implementation->static_size);
2634       if (free_p)
2635         {
2636           lcrecord_stats[type_index].instances_freed++;
2637           lcrecord_stats[type_index].bytes_freed += sz;
2638         }
2639       else
2640         {
2641           lcrecord_stats[type_index].instances_in_use++;
2642           lcrecord_stats[type_index].bytes_in_use += sz;
2643         }
2644     }
2645 }
2646
2647 \f
2648 /* Free all unmarked records */
2649 static void
2650 sweep_lcrecords_1 (struct lcrecord_header **prev, int *used)
2651 {
2652   struct lcrecord_header *header;
2653   int num_used = 0;
2654   /* int total_size = 0; */
2655
2656   xzero (lcrecord_stats); /* Reset all statistics to 0. */
2657
2658   /* First go through and call all the finalize methods.
2659      Then go through and free the objects.  There used to
2660      be only one loop here, with the call to the finalizer
2661      occurring directly before the xfree() below.  That
2662      is marginally faster but much less safe -- if the
2663      finalize method for an object needs to reference any
2664      other objects contained within it (and many do),
2665      we could easily be screwed by having already freed that
2666      other object. */
2667
2668   for (header = *prev; header; header = header->next)
2669     {
2670       struct lrecord_header *h = &(header->lheader);
2671
2672       GC_CHECK_LHEADER_INVARIANTS (h);
2673
2674       if (! MARKED_RECORD_HEADER_P (h) && ! header->free)
2675         {
2676           if (LHEADER_IMPLEMENTATION (h)->finalizer)
2677             LHEADER_IMPLEMENTATION (h)->finalizer (h, 0);
2678         }
2679     }
2680
2681   for (header = *prev; header; )
2682     {
2683       struct lrecord_header *h = &(header->lheader);
2684       if (MARKED_RECORD_HEADER_P (h))
2685         {
2686           if (! C_READONLY_RECORD_HEADER_P (h))
2687             UNMARK_RECORD_HEADER (h);
2688           num_used++;
2689           /* total_size += n->implementation->size_in_bytes (h);*/
2690           /* #### May modify header->next on a C_READONLY lcrecord */
2691           prev = &(header->next);
2692           header = *prev;
2693           tick_lcrecord_stats (h, 0);
2694         }
2695       else
2696         {
2697           struct lcrecord_header *next = header->next;
2698           *prev = next;
2699           tick_lcrecord_stats (h, 1);
2700           /* used to call finalizer right here. */
2701           xfree (header);
2702           header = next;
2703         }
2704     }
2705   *used = num_used;
2706   /* *total = total_size; */
2707 }
2708
2709
2710 static void
2711 sweep_bit_vectors_1 (Lisp_Object *prev,
2712                      int *used, int *total, int *storage)
2713 {
2714   Lisp_Object bit_vector;
2715   int num_used = 0;
2716   int total_size = 0;
2717   int total_storage = 0;
2718
2719   /* BIT_VECTORP fails because the objects are marked, which changes
2720      their implementation */
2721   for (bit_vector = *prev; !EQ (bit_vector, Qzero); )
2722     {
2723       Lisp_Bit_Vector *v = XBIT_VECTOR (bit_vector);
2724       int len = v->size;
2725       if (MARKED_RECORD_P (bit_vector))
2726         {
2727           if (! C_READONLY_RECORD_HEADER_P(&(v->lheader)))
2728             UNMARK_RECORD_HEADER (&(v->lheader));
2729           total_size += len;
2730           total_storage +=
2731             MALLOC_OVERHEAD +
2732             FLEXIBLE_ARRAY_STRUCT_SIZEOF (Lisp_Bit_Vector, bits,
2733                                           BIT_VECTOR_LONG_STORAGE (len));
2734           num_used++;
2735           /* #### May modify next on a C_READONLY bitvector */
2736           prev = &(bit_vector_next (v));
2737           bit_vector = *prev;
2738         }
2739       else
2740         {
2741           Lisp_Object next = bit_vector_next (v);
2742           *prev = next;
2743           xfree (v);
2744           bit_vector = next;
2745         }
2746     }
2747   *used = num_used;
2748   *total = total_size;
2749   *storage = total_storage;
2750 }
2751
2752 /* And the Lord said: Thou shalt use the `c-backslash-region' command
2753    to make macros prettier. */
2754
2755 #ifdef ERROR_CHECK_GC
2756
2757 #define SWEEP_FIXED_TYPE_BLOCK(typename, obj_type)                      \
2758 do {                                                                    \
2759   struct typename##_block *SFTB_current;                                \
2760   struct typename##_block **SFTB_prev;                                  \
2761   int SFTB_limit;                                                       \
2762   int num_free = 0, num_used = 0;                                       \
2763                                                                         \
2764   for (SFTB_prev = &current_##typename##_block,                         \
2765        SFTB_current = current_##typename##_block,                       \
2766        SFTB_limit = current_##typename##_block_index;                   \
2767        SFTB_current;                                                    \
2768        )                                                                \
2769     {                                                                   \
2770       int SFTB_iii;                                                     \
2771                                                                         \
2772       for (SFTB_iii = 0; SFTB_iii < SFTB_limit; SFTB_iii++)             \
2773         {                                                               \
2774           obj_type *SFTB_victim = &(SFTB_current->block[SFTB_iii]);     \
2775                                                                         \
2776           if (FREE_STRUCT_P (SFTB_victim))                              \
2777             {                                                           \
2778               num_free++;                                               \
2779             }                                                           \
2780           else if (C_READONLY_RECORD_HEADER_P (&SFTB_victim->lheader))  \
2781             {                                                           \
2782               num_used++;                                               \
2783             }                                                           \
2784           else if (! MARKED_RECORD_HEADER_P (&SFTB_victim->lheader))    \
2785             {                                                           \
2786               num_free++;                                               \
2787               FREE_FIXED_TYPE (typename, obj_type, SFTB_victim);        \
2788             }                                                           \
2789           else                                                          \
2790             {                                                           \
2791               num_used++;                                               \
2792               UNMARK_##typename (SFTB_victim);                          \
2793             }                                                           \
2794         }                                                               \
2795       SFTB_prev = &(SFTB_current->prev);                                \
2796       SFTB_current = SFTB_current->prev;                                \
2797       SFTB_limit = countof (current_##typename##_block->block);         \
2798     }                                                                   \
2799                                                                         \
2800   gc_count_num_##typename##_in_use = num_used;                          \
2801   gc_count_num_##typename##_freelist = num_free;                        \
2802 } while (0)
2803
2804 #else /* !ERROR_CHECK_GC */
2805
2806 #define SWEEP_FIXED_TYPE_BLOCK(typename, obj_type)                              \
2807 do {                                                                            \
2808   struct typename##_block *SFTB_current;                                        \
2809   struct typename##_block **SFTB_prev;                                          \
2810   int SFTB_limit;                                                               \
2811   int num_free = 0, num_used = 0;                                               \
2812                                                                                 \
2813   typename##_free_list = 0;                                                     \
2814                                                                                 \
2815   for (SFTB_prev = &current_##typename##_block,                                 \
2816        SFTB_current = current_##typename##_block,                               \
2817        SFTB_limit = current_##typename##_block_index;                           \
2818        SFTB_current;                                                            \
2819        )                                                                        \
2820     {                                                                           \
2821       int SFTB_iii;                                                             \
2822       int SFTB_empty = 1;                                                       \
2823       obj_type *SFTB_old_free_list = typename##_free_list;                      \
2824                                                                                 \
2825       for (SFTB_iii = 0; SFTB_iii < SFTB_limit; SFTB_iii++)                     \
2826         {                                                                       \
2827           obj_type *SFTB_victim = &(SFTB_current->block[SFTB_iii]);             \
2828                                                                                 \
2829           if (FREE_STRUCT_P (SFTB_victim))                                      \
2830             {                                                                   \
2831               num_free++;                                                       \
2832               PUT_FIXED_TYPE_ON_FREE_LIST (typename, obj_type, SFTB_victim);    \
2833             }                                                                   \
2834           else if (C_READONLY_RECORD_HEADER_P (&SFTB_victim->lheader))          \
2835             {                                                                   \
2836               SFTB_empty = 0;                                                   \
2837               num_used++;                                                       \
2838             }                                                                   \
2839           else if (! MARKED_RECORD_HEADER_P (&SFTB_victim->lheader))            \
2840             {                                                                   \
2841               num_free++;                                                       \
2842               FREE_FIXED_TYPE (typename, obj_type, SFTB_victim);                \
2843             }                                                                   \
2844           else                                                                  \
2845             {                                                                   \
2846               SFTB_empty = 0;                                                   \
2847               num_used++;                                                       \
2848               UNMARK_##typename (SFTB_victim);                                  \
2849             }                                                                   \
2850         }                                                                       \
2851       if (!SFTB_empty)                                                          \
2852         {                                                                       \
2853           SFTB_prev = &(SFTB_current->prev);                                    \
2854           SFTB_current = SFTB_current->prev;                                    \
2855         }                                                                       \
2856       else if (SFTB_current == current_##typename##_block                       \
2857                && !SFTB_current->prev)                                          \
2858         {                                                                       \
2859           /* No real point in freeing sole allocation block */                  \
2860           break;                                                                \
2861         }                                                                       \
2862       else                                                                      \
2863         {                                                                       \
2864           struct typename##_block *SFTB_victim_block = SFTB_current;            \
2865           if (SFTB_victim_block == current_##typename##_block)                  \
2866             current_##typename##_block_index                                    \
2867               = countof (current_##typename##_block->block);                    \
2868           SFTB_current = SFTB_current->prev;                                    \
2869           {                                                                     \
2870             *SFTB_prev = SFTB_current;                                          \
2871             xfree (SFTB_victim_block);                                          \
2872             /* Restore free list to what it was before victim was swept */      \
2873             typename##_free_list = SFTB_old_free_list;                          \
2874             num_free -= SFTB_limit;                                             \
2875           }                                                                     \
2876         }                                                                       \
2877       SFTB_limit = countof (current_##typename##_block->block);                 \
2878     }                                                                           \
2879                                                                                 \
2880   gc_count_num_##typename##_in_use = num_used;                                  \
2881   gc_count_num_##typename##_freelist = num_free;                                \
2882 } while (0)
2883
2884 #endif /* !ERROR_CHECK_GC */
2885
2886 \f
2887
2888
2889 static void
2890 sweep_conses (void)
2891 {
2892 #define UNMARK_cons(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
2893 #define ADDITIONAL_FREE_cons(ptr)
2894
2895   SWEEP_FIXED_TYPE_BLOCK (cons, Lisp_Cons);
2896 }
2897
2898 /* Explicitly free a cons cell.  */
2899 void
2900 free_cons (Lisp_Cons *ptr)
2901 {
2902 #ifdef ERROR_CHECK_GC
2903   /* If the CAR is not an int, then it will be a pointer, which will
2904      always be four-byte aligned.  If this cons cell has already been
2905      placed on the free list, however, its car will probably contain
2906      a chain pointer to the next cons on the list, which has cleverly
2907      had all its 0's and 1's inverted.  This allows for a quick
2908      check to make sure we're not freeing something already freed. */
2909   if (POINTER_TYPE_P (XTYPE (ptr->car)))
2910     ASSERT_VALID_POINTER (XPNTR (ptr->car));
2911 #endif /* ERROR_CHECK_GC */
2912
2913 #ifndef ALLOC_NO_POOLS
2914   FREE_FIXED_TYPE_WHEN_NOT_IN_GC (cons, Lisp_Cons, ptr);
2915 #endif /* ALLOC_NO_POOLS */
2916 }
2917
2918 /* explicitly free a list.  You **must make sure** that you have
2919    created all the cons cells that make up this list and that there
2920    are no pointers to any of these cons cells anywhere else.  If there
2921    are, you will lose. */
2922
2923 void
2924 free_list (Lisp_Object list)
2925 {
2926   Lisp_Object rest, next;
2927
2928   for (rest = list; !NILP (rest); rest = next)
2929     {
2930       next = XCDR (rest);
2931       free_cons (XCONS (rest));
2932     }
2933 }
2934
2935 /* explicitly free an alist.  You **must make sure** that you have
2936    created all the cons cells that make up this alist and that there
2937    are no pointers to any of these cons cells anywhere else.  If there
2938    are, you will lose. */
2939
2940 void
2941 free_alist (Lisp_Object alist)
2942 {
2943   Lisp_Object rest, next;
2944
2945   for (rest = alist; !NILP (rest); rest = next)
2946     {
2947       next = XCDR (rest);
2948       free_cons (XCONS (XCAR (rest)));
2949       free_cons (XCONS (rest));
2950     }
2951 }
2952
2953 static void
2954 sweep_compiled_functions (void)
2955 {
2956 #define UNMARK_compiled_function(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
2957 #define ADDITIONAL_FREE_compiled_function(ptr)
2958
2959   SWEEP_FIXED_TYPE_BLOCK (compiled_function, Lisp_Compiled_Function);
2960 }
2961
2962
2963 #ifdef LISP_FLOAT_TYPE
2964 static void
2965 sweep_floats (void)
2966 {
2967 #define UNMARK_float(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
2968 #define ADDITIONAL_FREE_float(ptr)
2969
2970   SWEEP_FIXED_TYPE_BLOCK (float, Lisp_Float);
2971 }
2972 #endif /* LISP_FLOAT_TYPE */
2973
2974 static void
2975 sweep_symbols (void)
2976 {
2977 #define UNMARK_symbol(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
2978 #define ADDITIONAL_FREE_symbol(ptr)
2979
2980   SWEEP_FIXED_TYPE_BLOCK (symbol, Lisp_Symbol);
2981 }
2982
2983 static void
2984 sweep_extents (void)
2985 {
2986 #define UNMARK_extent(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
2987 #define ADDITIONAL_FREE_extent(ptr)
2988
2989   SWEEP_FIXED_TYPE_BLOCK (extent, struct extent);
2990 }
2991
2992 static void
2993 sweep_events (void)
2994 {
2995 #define UNMARK_event(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
2996 #define ADDITIONAL_FREE_event(ptr)
2997
2998   SWEEP_FIXED_TYPE_BLOCK (event, Lisp_Event);
2999 }
3000
3001 static void
3002 sweep_markers (void)
3003 {
3004 #define UNMARK_marker(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
3005 #define ADDITIONAL_FREE_marker(ptr)                                     \
3006   do { Lisp_Object tem;                                                 \
3007        XSETMARKER (tem, ptr);                                           \
3008        unchain_marker (tem);                                            \
3009      } while (0)
3010
3011   SWEEP_FIXED_TYPE_BLOCK (marker, Lisp_Marker);
3012 }
3013
3014 /* Explicitly free a marker.  */
3015 void
3016 free_marker (Lisp_Marker *ptr)
3017 {
3018   /* Perhaps this will catch freeing an already-freed marker. */
3019   gc_checking_assert (ptr->lheader.type = lrecord_type_marker);
3020
3021 #ifndef ALLOC_NO_POOLS
3022   FREE_FIXED_TYPE_WHEN_NOT_IN_GC (marker, Lisp_Marker, ptr);
3023 #endif /* ALLOC_NO_POOLS */
3024 }
3025 \f
3026
3027 #if defined (MULE) && defined (VERIFY_STRING_CHARS_INTEGRITY)
3028
3029 static void
3030 verify_string_chars_integrity (void)
3031 {
3032   struct string_chars_block *sb;
3033
3034   /* Scan each existing string block sequentially, string by string.  */
3035   for (sb = first_string_chars_block; sb; sb = sb->next)
3036     {
3037       int pos = 0;
3038       /* POS is the index of the next string in the block.  */
3039       while (pos < sb->pos)
3040         {
3041           struct string_chars *s_chars =
3042             (struct string_chars *) &(sb->string_chars[pos]);
3043           Lisp_String *string;
3044           int size;
3045           int fullsize;
3046
3047           /* If the string_chars struct is marked as free (i.e. the STRING
3048              pointer is 0xFFFFFFFF) then this is an unused chunk of string
3049              storage. (See below.) */
3050
3051           if (FREE_STRUCT_P (s_chars))
3052             {
3053               fullsize = ((struct unused_string_chars *) s_chars)->fullsize;
3054               pos += fullsize;
3055               continue;
3056             }
3057
3058           string = s_chars->string;
3059           /* Must be 32-bit aligned. */
3060           assert ((((int) string) & 3) == 0);
3061
3062           size = string_length (string);
3063           fullsize = STRING_FULLSIZE (size);
3064
3065           assert (!BIG_STRING_FULLSIZE_P (fullsize));
3066           assert (string_data (string) == s_chars->chars);
3067           pos += fullsize;
3068         }
3069       assert (pos == sb->pos);
3070     }
3071 }
3072
3073 #endif /* MULE && ERROR_CHECK_GC */
3074
3075 /* Compactify string chars, relocating the reference to each --
3076    free any empty string_chars_block we see. */
3077 static void
3078 compact_string_chars (void)
3079 {
3080   struct string_chars_block *to_sb = first_string_chars_block;
3081   int to_pos = 0;
3082   struct string_chars_block *from_sb;
3083
3084   /* Scan each existing string block sequentially, string by string.  */
3085   for (from_sb = first_string_chars_block; from_sb; from_sb = from_sb->next)
3086     {
3087       int from_pos = 0;
3088       /* FROM_POS is the index of the next string in the block.  */
3089       while (from_pos < from_sb->pos)
3090         {
3091           struct string_chars *from_s_chars =
3092             (struct string_chars *) &(from_sb->string_chars[from_pos]);
3093           struct string_chars *to_s_chars;
3094           Lisp_String *string;
3095           int size;
3096           int fullsize;
3097
3098           /* If the string_chars struct is marked as free (i.e. the STRING
3099              pointer is 0xFFFFFFFF) then this is an unused chunk of string
3100              storage.  This happens under Mule when a string's size changes
3101              in such a way that its fullsize changes. (Strings can change
3102              size because a different-length character can be substituted
3103              for another character.) In this case, after the bogus string
3104              pointer is the "fullsize" of this entry, i.e. how many bytes
3105              to skip. */
3106
3107           if (FREE_STRUCT_P (from_s_chars))
3108             {
3109               fullsize = ((struct unused_string_chars *) from_s_chars)->fullsize;
3110               from_pos += fullsize;
3111               continue;
3112             }
3113
3114           string = from_s_chars->string;
3115           assert (!(FREE_STRUCT_P (string)));
3116
3117           size = string_length (string);
3118           fullsize = STRING_FULLSIZE (size);
3119
3120           gc_checking_assert (! BIG_STRING_FULLSIZE_P (fullsize));
3121
3122           /* Just skip it if it isn't marked.  */
3123           if (! MARKED_RECORD_HEADER_P (&(string->lheader)))
3124             {
3125               from_pos += fullsize;
3126               continue;
3127             }
3128
3129           /* If it won't fit in what's left of TO_SB, close TO_SB out
3130              and go on to the next string_chars_block.  We know that TO_SB
3131              cannot advance past FROM_SB here since FROM_SB is large enough
3132              to currently contain this string. */
3133           if ((to_pos + fullsize) > countof (to_sb->string_chars))
3134             {
3135               to_sb->pos = to_pos;
3136               to_sb = to_sb->next;
3137               to_pos = 0;
3138             }
3139
3140           /* Compute new address of this string
3141              and update TO_POS for the space being used.  */
3142           to_s_chars = (struct string_chars *) &(to_sb->string_chars[to_pos]);
3143
3144           /* Copy the string_chars to the new place.  */
3145           if (from_s_chars != to_s_chars)
3146             memmove (to_s_chars, from_s_chars, fullsize);
3147
3148           /* Relocate FROM_S_CHARS's reference */
3149           set_string_data (string, &(to_s_chars->chars[0]));
3150
3151           from_pos += fullsize;
3152           to_pos += fullsize;
3153         }
3154     }
3155
3156   /* Set current to the last string chars block still used and
3157      free any that follow. */
3158   {
3159     struct string_chars_block *victim;
3160
3161     for (victim = to_sb->next; victim; )
3162       {
3163         struct string_chars_block *next = victim->next;
3164         xfree (victim);
3165         victim = next;
3166       }
3167
3168     current_string_chars_block = to_sb;
3169     current_string_chars_block->pos = to_pos;
3170     current_string_chars_block->next = 0;
3171   }
3172 }
3173
3174 #if 1 /* Hack to debug missing purecopy's */
3175 static int debug_string_purity;
3176
3177 static void
3178 debug_string_purity_print (Lisp_String *p)
3179 {
3180   Charcount i;
3181   Charcount s = string_char_length (p);
3182   stderr_out ("\"");
3183   for (i = 0; i < s; i++)
3184   {
3185     Emchar ch = string_char (p, i);
3186     if (ch < 32 || ch >= 126)
3187       stderr_out ("\\%03o", ch);
3188     else if (ch == '\\' || ch == '\"')
3189       stderr_out ("\\%c", ch);
3190     else
3191       stderr_out ("%c", ch);
3192   }
3193   stderr_out ("\"\n");
3194 }
3195 #endif /* 1 */
3196
3197
3198 static void
3199 sweep_strings (void)
3200 {
3201   int num_small_used = 0, num_small_bytes = 0, num_bytes = 0;
3202   int debug = debug_string_purity;
3203
3204 #define UNMARK_string(ptr) do {                 \
3205     Lisp_String *p = (ptr);                     \
3206     size_t size = string_length (p);            \
3207     UNMARK_RECORD_HEADER (&(p->lheader));       \
3208     num_bytes += size;                          \
3209     if (!BIG_STRING_SIZE_P (size))              \
3210       {                                         \
3211         num_small_bytes += size;                \
3212         num_small_used++;                       \
3213       }                                         \
3214     if (debug)                                  \
3215       debug_string_purity_print (p);            \
3216   } while (0)
3217 #define ADDITIONAL_FREE_string(ptr) do {        \
3218     size_t size = string_length (ptr);          \
3219     if (BIG_STRING_SIZE_P (size))               \
3220       xfree (ptr->data);                        \
3221   } while (0)
3222
3223   SWEEP_FIXED_TYPE_BLOCK (string, Lisp_String);
3224
3225   gc_count_num_short_string_in_use = num_small_used;
3226   gc_count_string_total_size = num_bytes;
3227   gc_count_short_string_total_size = num_small_bytes;
3228 }
3229
3230
3231 /* I hate duplicating all this crap! */
3232 int
3233 marked_p (Lisp_Object obj)
3234 {
3235   /* Checks we used to perform. */
3236   /* if (EQ (obj, Qnull_pointer)) return 1; */
3237   /* if (!POINTER_TYPE_P (XGCTYPE (obj))) return 1; */
3238   /* if (PURIFIED (XPNTR (obj))) return 1; */
3239
3240   if (XTYPE (obj) == Lisp_Type_Record)
3241     {
3242       struct lrecord_header *lheader = XRECORD_LHEADER (obj);
3243
3244       GC_CHECK_LHEADER_INVARIANTS (lheader);
3245
3246       return MARKED_RECORD_HEADER_P (lheader);
3247     }
3248   return 1;
3249 }
3250
3251 static void
3252 gc_sweep (void)
3253 {
3254   /* Free all unmarked records.  Do this at the very beginning,
3255      before anything else, so that the finalize methods can safely
3256      examine items in the objects.  sweep_lcrecords_1() makes
3257      sure to call all the finalize methods *before* freeing anything,
3258      to complete the safety. */
3259   {
3260     int ignored;
3261     sweep_lcrecords_1 (&all_lcrecords, &ignored);
3262   }
3263
3264   compact_string_chars ();
3265
3266   /* Finalize methods below (called through the ADDITIONAL_FREE_foo
3267      macros) must be *extremely* careful to make sure they're not
3268      referencing freed objects.  The only two existing finalize
3269      methods (for strings and markers) pass muster -- the string
3270      finalizer doesn't look at anything but its own specially-
3271      created block, and the marker finalizer only looks at live
3272      buffers (which will never be freed) and at the markers before
3273      and after it in the chain (which, by induction, will never be
3274      freed because if so, they would have already removed themselves
3275      from the chain). */
3276
3277   /* Put all unmarked strings on free list, free'ing the string chars
3278      of large unmarked strings */
3279   sweep_strings ();
3280
3281   /* Put all unmarked conses on free list */
3282   sweep_conses ();
3283
3284   /* Free all unmarked bit vectors */
3285   sweep_bit_vectors_1 (&all_bit_vectors,
3286                        &gc_count_num_bit_vector_used,
3287                        &gc_count_bit_vector_total_size,
3288                        &gc_count_bit_vector_storage);
3289
3290   /* Free all unmarked compiled-function objects */
3291   sweep_compiled_functions ();
3292
3293 #ifdef LISP_FLOAT_TYPE
3294   /* Put all unmarked floats on free list */
3295   sweep_floats ();
3296 #endif
3297
3298   /* Put all unmarked symbols on free list */
3299   sweep_symbols ();
3300
3301   /* Put all unmarked extents on free list */
3302   sweep_extents ();
3303
3304   /* Put all unmarked markers on free list.
3305      Dechain each one first from the buffer into which it points. */
3306   sweep_markers ();
3307
3308   sweep_events ();
3309
3310 #ifdef PDUMP
3311   pdump_objects_unmark ();
3312 #endif
3313 }
3314 \f
3315 /* Clearing for disksave. */
3316
3317 void
3318 disksave_object_finalization (void)
3319 {
3320   /* It's important that certain information from the environment not get
3321      dumped with the executable (pathnames, environment variables, etc.).
3322      To make it easier to tell when this has happened with strings(1) we
3323      clear some known-to-be-garbage blocks of memory, so that leftover
3324      results of old evaluation don't look like potential problems.
3325      But first we set some notable variables to nil and do one more GC,
3326      to turn those strings into garbage.
3327   */
3328
3329   /* Yeah, this list is pretty ad-hoc... */
3330   Vprocess_environment = Qnil;
3331   Vexec_directory = Qnil;
3332   Vdata_directory = Qnil;
3333   Vsite_directory = Qnil;
3334   Vdoc_directory = Qnil;
3335   Vconfigure_info_directory = Qnil;
3336   Vexec_path = Qnil;
3337   Vload_path = Qnil;
3338   /* Vdump_load_path = Qnil; */
3339   /* Release hash tables for locate_file */
3340   Flocate_file_clear_hashing (Qt);
3341   uncache_home_directory();
3342
3343 #if defined(LOADHIST) && !(defined(LOADHIST_DUMPED) || \
3344                            defined(LOADHIST_BUILTIN))
3345   Vload_history = Qnil;
3346 #endif
3347   Vshell_file_name = Qnil;
3348
3349   garbage_collect_1 ();
3350
3351   /* Run the disksave finalization methods of all live objects. */
3352   disksave_object_finalization_1 ();
3353
3354   /* Zero out the uninitialized (really, unused) part of the containers
3355      for the live strings. */
3356   {
3357     struct string_chars_block *scb;
3358     for (scb = first_string_chars_block; scb; scb = scb->next)
3359       {
3360         int count = sizeof (scb->string_chars) - scb->pos;
3361
3362         assert (count >= 0 && count < STRING_CHARS_BLOCK_SIZE);
3363         if (count != 0)
3364           {
3365             /* from the block's fill ptr to the end */
3366             memset ((scb->string_chars + scb->pos), 0, count);
3367           }
3368       }
3369   }
3370
3371   /* There, that ought to be enough... */
3372
3373 }
3374
3375 \f
3376 Lisp_Object
3377 restore_gc_inhibit (Lisp_Object val)
3378 {
3379   gc_currently_forbidden = XINT (val);
3380   return val;
3381 }
3382
3383 /* Maybe we want to use this when doing a "panic" gc after memory_full()? */
3384 static int gc_hooks_inhibited;
3385
3386 \f
3387 void
3388 garbage_collect_1 (void)
3389 {
3390 #if MAX_SAVE_STACK > 0
3391   char stack_top_variable;
3392   extern char *stack_bottom;
3393 #endif
3394   struct frame *f;
3395   int speccount;
3396   int cursor_changed;
3397   Lisp_Object pre_gc_cursor;
3398   struct gcpro gcpro1;
3399
3400   if (gc_in_progress
3401       || gc_currently_forbidden
3402       || in_display
3403       || preparing_for_armageddon)
3404     return;
3405
3406   /* We used to call selected_frame() here.
3407
3408      The following functions cannot be called inside GC
3409      so we move to after the above tests. */
3410   {
3411     Lisp_Object frame;
3412     Lisp_Object device = Fselected_device (Qnil);
3413     if (NILP (device)) /* Could happen during startup, eg. if always_gc */
3414       return;
3415     frame = DEVICE_SELECTED_FRAME (XDEVICE (device));
3416     if (NILP (frame))
3417       signal_simple_error ("No frames exist on device", device);
3418     f = XFRAME (frame);
3419   }
3420
3421   pre_gc_cursor = Qnil;
3422   cursor_changed = 0;
3423
3424   GCPRO1 (pre_gc_cursor);
3425
3426   /* Very important to prevent GC during any of the following
3427      stuff that might run Lisp code; otherwise, we'll likely
3428      have infinite GC recursion. */
3429   speccount = specpdl_depth ();
3430   record_unwind_protect (restore_gc_inhibit,
3431                          make_int (gc_currently_forbidden));
3432   gc_currently_forbidden = 1;
3433
3434   if (!gc_hooks_inhibited)
3435     run_hook_trapping_errors ("Error in pre-gc-hook", Qpre_gc_hook);
3436
3437   /* Now show the GC cursor/message. */
3438   if (!noninteractive)
3439     {
3440       if (FRAME_WIN_P (f))
3441         {
3442           Lisp_Object frame = make_frame (f);
3443           Lisp_Object cursor = glyph_image_instance (Vgc_pointer_glyph,
3444                                                      FRAME_SELECTED_WINDOW (f),
3445                                                      ERROR_ME_NOT, 1);
3446           pre_gc_cursor = f->pointer;
3447           if (POINTER_IMAGE_INSTANCEP (cursor)
3448               /* don't change if we don't know how to change back. */
3449               && POINTER_IMAGE_INSTANCEP (pre_gc_cursor))
3450             {
3451               cursor_changed = 1;
3452               Fset_frame_pointer (frame, cursor);
3453             }
3454         }
3455
3456       /* Don't print messages to the stream device. */
3457       if (!cursor_changed && !FRAME_STREAM_P (f))
3458         {
3459           char *msg = (STRINGP (Vgc_message)
3460                        ? GETTEXT ((char *) XSTRING_DATA (Vgc_message))
3461                        : 0);
3462           Lisp_Object args[2], whole_msg;
3463           args[0] = build_string (msg ? msg :
3464                                   GETTEXT ((const char *) gc_default_message));
3465           args[1] = build_string ("...");
3466           whole_msg = Fconcat (2, args);
3467           echo_area_message (f, (Bufbyte *) 0, whole_msg, 0, -1,
3468                              Qgarbage_collecting);
3469         }
3470     }
3471
3472   /***** Now we actually start the garbage collection. */
3473
3474   gc_in_progress = 1;
3475
3476   gc_generation_number[0]++;
3477
3478 #if MAX_SAVE_STACK > 0
3479
3480   /* Save a copy of the contents of the stack, for debugging.  */
3481   if (!purify_flag)
3482     {
3483       /* Static buffer in which we save a copy of the C stack at each GC.  */
3484       static char *stack_copy;
3485       static size_t stack_copy_size;
3486
3487       ptrdiff_t stack_diff = &stack_top_variable - stack_bottom;
3488       size_t stack_size = (stack_diff > 0 ? stack_diff : -stack_diff);
3489       if (stack_size < MAX_SAVE_STACK)
3490         {
3491           if (stack_copy_size < stack_size)
3492             {
3493               stack_copy = (char *) xrealloc (stack_copy, stack_size);
3494               stack_copy_size = stack_size;
3495             }
3496
3497           memcpy (stack_copy,
3498                   stack_diff > 0 ? stack_bottom : &stack_top_variable,
3499                   stack_size);
3500         }
3501     }
3502 #endif /* MAX_SAVE_STACK > 0 */
3503
3504   /* Do some totally ad-hoc resource clearing. */
3505   /* #### generalize this? */
3506   clear_event_resource ();
3507   cleanup_specifiers ();
3508
3509   /* Mark all the special slots that serve as the roots of accessibility. */
3510
3511   { /* staticpro() */
3512     int i;
3513     for (i = 0; i < staticidx; i++)
3514       mark_object (*(staticvec[i]));
3515     for (i = 0; i < staticidx_nodump; i++)
3516       mark_object (*(staticvec_nodump[i]));
3517   }
3518
3519   { /* GCPRO() */
3520     struct gcpro *tail;
3521     int i;
3522     for (tail = gcprolist; tail; tail = tail->next)
3523       for (i = 0; i < tail->nvars; i++)
3524         mark_object (tail->var[i]);
3525   }
3526
3527   { /* specbind() */
3528     struct specbinding *bind;
3529     for (bind = specpdl; bind != specpdl_ptr; bind++)
3530       {
3531         mark_object (bind->symbol);
3532         mark_object (bind->old_value);
3533       }
3534   }
3535
3536   {
3537     struct catchtag *catch;
3538     for (catch = catchlist; catch; catch = catch->next)
3539       {
3540         mark_object (catch->tag);
3541         mark_object (catch->val);
3542       }
3543   }
3544
3545   {
3546     struct backtrace *backlist;
3547     for (backlist = backtrace_list; backlist; backlist = backlist->next)
3548       {
3549         int nargs = backlist->nargs;
3550         int i;
3551
3552         mark_object (*backlist->function);
3553         if (nargs == UNEVALLED || nargs == MANY)
3554           mark_object (backlist->args[0]);
3555         else
3556           for (i = 0; i < nargs; i++)
3557             mark_object (backlist->args[i]);
3558       }
3559   }
3560
3561   mark_redisplay ();
3562   mark_profiling_info ();
3563
3564   /* OK, now do the after-mark stuff.  This is for things that
3565      are only marked when something else is marked (e.g. weak hash tables).
3566      There may be complex dependencies between such objects -- e.g.
3567      a weak hash table might be unmarked, but after processing a later
3568      weak hash table, the former one might get marked.  So we have to
3569      iterate until nothing more gets marked. */
3570
3571   while (finish_marking_weak_hash_tables () > 0 ||
3572          finish_marking_weak_lists       () > 0)
3573     ;
3574
3575   /* And prune (this needs to be called after everything else has been
3576      marked and before we do any sweeping). */
3577   /* #### this is somewhat ad-hoc and should probably be an object
3578      method */
3579   prune_weak_hash_tables ();
3580   prune_weak_lists ();
3581   prune_specifiers ();
3582   prune_syntax_tables ();
3583
3584   gc_sweep ();
3585
3586   consing_since_gc = 0;
3587 #ifndef DEBUG_XEMACS
3588   /* Allow you to set it really fucking low if you really want ... */
3589   if (gc_cons_threshold < 10000)
3590     gc_cons_threshold = 10000;
3591 #endif
3592
3593   gc_in_progress = 0;
3594
3595   /******* End of garbage collection ********/
3596
3597   run_hook_trapping_errors ("Error in post-gc-hook", Qpost_gc_hook);
3598
3599   /* Now remove the GC cursor/message */
3600   if (!noninteractive)
3601     {
3602       if (cursor_changed)
3603         Fset_frame_pointer (make_frame (f), pre_gc_cursor);
3604       else if (!FRAME_STREAM_P (f))
3605         {
3606           char *msg = (STRINGP (Vgc_message)
3607                        ? GETTEXT ((char *) XSTRING_DATA (Vgc_message))
3608                        : 0);
3609
3610           /* Show "...done" only if the echo area would otherwise be empty. */
3611           if (NILP (clear_echo_area (selected_frame (),
3612                                      Qgarbage_collecting, 0)))
3613             {
3614               Lisp_Object args[2], whole_msg;
3615               args[0] = build_string (msg ? msg :
3616                                       GETTEXT ((const char *)
3617                                                gc_default_message));
3618               args[1] = build_string ("... done");
3619               whole_msg = Fconcat (2, args);
3620               echo_area_message (selected_frame (), (Bufbyte *) 0,
3621                                  whole_msg, 0, -1,
3622                                  Qgarbage_collecting);
3623             }
3624         }
3625     }
3626
3627   /* now stop inhibiting GC */
3628   unbind_to (speccount, Qnil);
3629
3630   if (!breathing_space)
3631     {
3632       breathing_space = malloc (4096 - MALLOC_OVERHEAD);
3633     }
3634
3635   UNGCPRO;
3636   return;
3637 }
3638
3639 /* Debugging aids.  */
3640
3641 static Lisp_Object
3642 gc_plist_hack (const char *name, int value, Lisp_Object tail)
3643 {
3644   /* C doesn't have local functions (or closures, or GC, or readable syntax,
3645      or portable numeric datatypes, or bit-vectors, or characters, or
3646      arrays, or exceptions, or ...) */
3647   return cons3 (intern (name), make_int (value), tail);
3648 }
3649
3650 #define HACK_O_MATIC(type, name, pl) do {                               \
3651   int s = 0;                                                            \
3652   struct type##_block *x = current_##type##_block;                      \
3653   while (x) { s += sizeof (*x) + MALLOC_OVERHEAD; x = x->prev; }        \
3654   (pl) = gc_plist_hack ((name), s, (pl));                               \
3655 } while (0)
3656
3657 DEFUN ("garbage-collect", Fgarbage_collect, 0, 0, "", /*
3658 Reclaim storage for Lisp objects no longer needed.
3659 Return info on amount of space in use:
3660  ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
3661   (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
3662   PLIST)
3663   where `PLIST' is a list of alternating keyword/value pairs providing
3664   more detailed information.
3665 Garbage collection happens automatically if you cons more than
3666 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
3667 */
3668        ())
3669 {
3670   Lisp_Object pl = Qnil;
3671   int i;
3672   int gc_count_vector_total_size = 0;
3673
3674   garbage_collect_1 ();
3675
3676   for (i = 0; i < lrecord_type_count; i++)
3677     {
3678       if (lcrecord_stats[i].bytes_in_use != 0
3679           || lcrecord_stats[i].bytes_freed != 0
3680           || lcrecord_stats[i].instances_on_free_list != 0)
3681         {
3682           char buf [255];
3683           const char *name = lrecord_implementations_table[i]->name;
3684           int len = strlen (name);
3685           /* save this for the FSFmacs-compatible part of the summary */
3686           if (i == lrecord_vector.lrecord_type_index)
3687             gc_count_vector_total_size =
3688               lcrecord_stats[i].bytes_in_use + lcrecord_stats[i].bytes_freed;
3689
3690           sprintf (buf, "%s-storage", name);
3691           pl = gc_plist_hack (buf, lcrecord_stats[i].bytes_in_use, pl);
3692           /* Okay, simple pluralization check for `symbol-value-varalias' */
3693           if (name[len-1] == 's')
3694             sprintf (buf, "%ses-freed", name);
3695           else
3696             sprintf (buf, "%ss-freed", name);
3697           if (lcrecord_stats[i].instances_freed != 0)
3698             pl = gc_plist_hack (buf, lcrecord_stats[i].instances_freed, pl);
3699           if (name[len-1] == 's')
3700             sprintf (buf, "%ses-on-free-list", name);
3701           else
3702             sprintf (buf, "%ss-on-free-list", name);
3703           if (lcrecord_stats[i].instances_on_free_list != 0)
3704             pl = gc_plist_hack (buf, lcrecord_stats[i].instances_on_free_list,
3705                                 pl);
3706           if (name[len-1] == 's')
3707             sprintf (buf, "%ses-used", name);
3708           else
3709             sprintf (buf, "%ss-used", name);
3710           pl = gc_plist_hack (buf, lcrecord_stats[i].instances_in_use, pl);
3711         }
3712     }
3713
3714   HACK_O_MATIC (extent, "extent-storage", pl);
3715   pl = gc_plist_hack ("extents-free", gc_count_num_extent_freelist, pl);
3716   pl = gc_plist_hack ("extents-used", gc_count_num_extent_in_use, pl);
3717   HACK_O_MATIC (event, "event-storage", pl);
3718   pl = gc_plist_hack ("events-free", gc_count_num_event_freelist, pl);
3719   pl = gc_plist_hack ("events-used", gc_count_num_event_in_use, pl);
3720   HACK_O_MATIC (marker, "marker-storage", pl);
3721   pl = gc_plist_hack ("markers-free", gc_count_num_marker_freelist, pl);
3722   pl = gc_plist_hack ("markers-used", gc_count_num_marker_in_use, pl);
3723 #ifdef LISP_FLOAT_TYPE
3724   HACK_O_MATIC (float, "float-storage", pl);
3725   pl = gc_plist_hack ("floats-free", gc_count_num_float_freelist, pl);
3726   pl = gc_plist_hack ("floats-used", gc_count_num_float_in_use, pl);
3727 #endif /* LISP_FLOAT_TYPE */
3728   HACK_O_MATIC (string, "string-header-storage", pl);
3729   pl = gc_plist_hack ("long-strings-total-length",
3730                       gc_count_string_total_size
3731                       - gc_count_short_string_total_size, pl);
3732   HACK_O_MATIC (string_chars, "short-string-storage", pl);
3733   pl = gc_plist_hack ("short-strings-total-length",
3734                       gc_count_short_string_total_size, pl);
3735   pl = gc_plist_hack ("strings-free", gc_count_num_string_freelist, pl);
3736   pl = gc_plist_hack ("long-strings-used",
3737                       gc_count_num_string_in_use
3738                       - gc_count_num_short_string_in_use, pl);
3739   pl = gc_plist_hack ("short-strings-used",
3740                       gc_count_num_short_string_in_use, pl);
3741
3742   HACK_O_MATIC (compiled_function, "compiled-function-storage", pl);
3743   pl = gc_plist_hack ("compiled-functions-free",
3744                       gc_count_num_compiled_function_freelist, pl);
3745   pl = gc_plist_hack ("compiled-functions-used",
3746                       gc_count_num_compiled_function_in_use, pl);
3747
3748   pl = gc_plist_hack ("bit-vector-storage", gc_count_bit_vector_storage, pl);
3749   pl = gc_plist_hack ("bit-vectors-total-length",
3750                       gc_count_bit_vector_total_size, pl);
3751   pl = gc_plist_hack ("bit-vectors-used", gc_count_num_bit_vector_used, pl);
3752
3753   HACK_O_MATIC (symbol, "symbol-storage", pl);
3754   pl = gc_plist_hack ("symbols-free", gc_count_num_symbol_freelist, pl);
3755   pl = gc_plist_hack ("symbols-used", gc_count_num_symbol_in_use, pl);
3756
3757   HACK_O_MATIC (cons, "cons-storage", pl);
3758   pl = gc_plist_hack ("conses-free", gc_count_num_cons_freelist, pl);
3759   pl = gc_plist_hack ("conses-used", gc_count_num_cons_in_use, pl);
3760
3761   /* The things we do for backwards-compatibility */
3762   return
3763     list6 (Fcons (make_int (gc_count_num_cons_in_use),
3764                   make_int (gc_count_num_cons_freelist)),
3765            Fcons (make_int (gc_count_num_symbol_in_use),
3766                   make_int (gc_count_num_symbol_freelist)),
3767            Fcons (make_int (gc_count_num_marker_in_use),
3768                   make_int (gc_count_num_marker_freelist)),
3769            make_int (gc_count_string_total_size),
3770            make_int (gc_count_vector_total_size),
3771            pl);
3772 }
3773 #undef HACK_O_MATIC
3774
3775 DEFUN ("consing-since-gc", Fconsing_since_gc, 0, 0, "", /*
3776 Return the number of bytes consed since the last garbage collection.
3777 \"Consed\" is a misnomer in that this actually counts allocation
3778 of all different kinds of objects, not just conses.
3779
3780 If this value exceeds `gc-cons-threshold', a garbage collection happens.
3781 */
3782        ())
3783 {
3784   return make_int (consing_since_gc);
3785 }
3786
3787 #if 0
3788 DEFUN ("memory-limit", Fmemory_limit, 0, 0, "", /*
3789 Return the address of the last byte Emacs has allocated, divided by 1024.
3790 This may be helpful in debugging Emacs's memory usage.
3791 The value is divided by 1024 to make sure it will fit in a lisp integer.
3792 */
3793        ())
3794 {
3795   return make_int ((EMACS_INT) sbrk (0) / 1024);
3796 }
3797 #endif
3798
3799 \f
3800 int
3801 object_dead_p (Lisp_Object obj)
3802 {
3803   return ((BUFFERP  (obj) && !BUFFER_LIVE_P  (XBUFFER  (obj))) ||
3804           (FRAMEP   (obj) && !FRAME_LIVE_P   (XFRAME   (obj))) ||
3805           (WINDOWP  (obj) && !WINDOW_LIVE_P  (XWINDOW  (obj))) ||
3806           (DEVICEP  (obj) && !DEVICE_LIVE_P  (XDEVICE  (obj))) ||
3807           (CONSOLEP (obj) && !CONSOLE_LIVE_P (XCONSOLE (obj))) ||
3808           (EVENTP   (obj) && !EVENT_LIVE_P   (XEVENT   (obj))) ||
3809           (EXTENTP  (obj) && !EXTENT_LIVE_P  (XEXTENT  (obj))));
3810 }
3811
3812 #ifdef MEMORY_USAGE_STATS
3813
3814 /* Attempt to determine the actual amount of space that is used for
3815    the block allocated starting at PTR, supposedly of size "CLAIMED_SIZE".
3816
3817    It seems that the following holds:
3818
3819    1. When using the old allocator (malloc.c):
3820
3821       -- blocks are always allocated in chunks of powers of two.  For
3822          each block, there is an overhead of 8 bytes if rcheck is not
3823          defined, 20 bytes if it is defined.  In other words, a
3824          one-byte allocation needs 8 bytes of overhead for a total of
3825          9 bytes, and needs to have 16 bytes of memory chunked out for
3826          it.
3827
3828    2. When using the new allocator (gmalloc.c):
3829
3830       -- blocks are always allocated in chunks of powers of two up
3831          to 4096 bytes.  Larger blocks are allocated in chunks of
3832          an integral multiple of 4096 bytes.  The minimum block
3833          size is 2*sizeof (void *), or 16 bytes if SUNOS_LOCALTIME_BUG
3834          is defined.  There is no per-block overhead, but there
3835          is an overhead of 3*sizeof (size_t) for each 4096 bytes
3836          allocated.
3837
3838     3. When using the system malloc, anything goes, but they are
3839        generally slower and more space-efficient than the GNU
3840        allocators.  One possibly reasonable assumption to make
3841        for want of better data is that sizeof (void *), or maybe
3842        2 * sizeof (void *), is required as overhead and that
3843        blocks are allocated in the minimum required size except
3844        that some minimum block size is imposed (e.g. 16 bytes). */
3845
3846 size_t
3847 malloced_storage_size (void *ptr, size_t claimed_size,
3848                        struct overhead_stats *stats)
3849 {
3850   size_t orig_claimed_size = claimed_size;
3851
3852 #ifdef GNU_MALLOC
3853
3854   if (claimed_size < 2 * sizeof (void *))
3855     claimed_size = 2 * sizeof (void *);
3856 # ifdef SUNOS_LOCALTIME_BUG
3857   if (claimed_size < 16)
3858     claimed_size = 16;
3859 # endif
3860   if (claimed_size < 4096)
3861     {
3862       int log = 1;
3863
3864       /* compute the log base two, more or less, then use it to compute
3865          the block size needed. */
3866       claimed_size--;
3867       /* It's big, it's heavy, it's wood! */
3868       while ((claimed_size /= 2) != 0)
3869         ++log;
3870       claimed_size = 1;
3871       /* It's better than bad, it's good! */
3872       while (log > 0)
3873         {
3874           claimed_size *= 2;
3875           log--;
3876         }
3877       /* We have to come up with some average about the amount of
3878          blocks used. */
3879       if ((size_t) (rand () & 4095) < claimed_size)
3880         claimed_size += 3 * sizeof (void *);
3881     }
3882   else
3883     {
3884       claimed_size += 4095;
3885       claimed_size &= ~4095;
3886       claimed_size += (claimed_size / 4096) * 3 * sizeof (size_t);
3887     }
3888
3889 #elif defined (SYSTEM_MALLOC)
3890
3891   if (claimed_size < 16)
3892     claimed_size = 16;
3893   claimed_size += 2 * sizeof (void *);
3894
3895 #else /* old GNU allocator */
3896
3897 # ifdef rcheck /* #### may not be defined here */
3898   claimed_size += 20;
3899 # else
3900   claimed_size += 8;
3901 # endif
3902   {
3903     int log = 1;
3904
3905     /* compute the log base two, more or less, then use it to compute
3906        the block size needed. */
3907     claimed_size--;
3908     /* It's big, it's heavy, it's wood! */
3909     while ((claimed_size /= 2) != 0)
3910       ++log;
3911     claimed_size = 1;
3912     /* It's better than bad, it's good! */
3913     while (log > 0)
3914       {
3915         claimed_size *= 2;
3916         log--;
3917       }
3918   }
3919
3920 #endif /* old GNU allocator */
3921
3922   if (stats)
3923     {
3924       stats->was_requested += orig_claimed_size;
3925       stats->malloc_overhead += claimed_size - orig_claimed_size;
3926     }
3927   return claimed_size;
3928 }
3929
3930 size_t
3931 fixed_type_block_overhead (size_t size)
3932 {
3933   size_t per_block = TYPE_ALLOC_SIZE (cons, unsigned char);
3934   size_t overhead = 0;
3935   size_t storage_size = malloced_storage_size (0, per_block, 0);
3936   while (size >= per_block)
3937     {
3938       size -= per_block;
3939       overhead += sizeof (void *) + per_block - storage_size;
3940     }
3941   if (rand () % per_block < size)
3942     overhead += sizeof (void *) + per_block - storage_size;
3943   return overhead;
3944 }
3945
3946 #endif /* MEMORY_USAGE_STATS */
3947
3948 \f
3949 /* Initialization */
3950 void
3951 reinit_alloc_once_early (void)
3952 {
3953   gc_generation_number[0] = 0;
3954   breathing_space = 0;
3955   XSETINT (all_bit_vectors, 0); /* Qzero may not be set yet. */
3956   XSETINT (Vgc_message, 0);
3957   all_lcrecords = 0;
3958 #ifdef UTF2000
3959   all_older_lcrecords = 0;
3960 #endif
3961   ignore_malloc_warnings = 1;
3962 #ifdef DOUG_LEA_MALLOC
3963   mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
3964   mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
3965 #if 0 /* Moved to emacs.c */
3966   mallopt (M_MMAP_MAX, 64); /* max. number of mmap'ed areas */
3967 #endif
3968 #endif
3969   init_string_alloc ();
3970   init_string_chars_alloc ();
3971   init_cons_alloc ();
3972   init_symbol_alloc ();
3973   init_compiled_function_alloc ();
3974 #ifdef LISP_FLOAT_TYPE
3975   init_float_alloc ();
3976 #endif /* LISP_FLOAT_TYPE */
3977   init_marker_alloc ();
3978   init_extent_alloc ();
3979   init_event_alloc ();
3980
3981   ignore_malloc_warnings = 0;
3982
3983   staticidx_nodump = 0;
3984   dumpstructidx = 0;
3985   pdump_wireidx = 0;
3986
3987   consing_since_gc = 0;
3988 #if 1
3989   gc_cons_threshold = 500000; /* XEmacs change */
3990 #else
3991   gc_cons_threshold = 15000; /* debugging */
3992 #endif
3993 #ifdef VIRT_ADDR_VARIES
3994   malloc_sbrk_unused = 1<<22;   /* A large number */
3995   malloc_sbrk_used = 100000;    /* as reasonable as any number */
3996 #endif /* VIRT_ADDR_VARIES */
3997   lrecord_uid_counter = 259;
3998   debug_string_purity = 0;
3999   gcprolist = 0;
4000
4001   gc_currently_forbidden = 0;
4002   gc_hooks_inhibited = 0;
4003
4004 #ifdef ERROR_CHECK_TYPECHECK
4005   ERROR_ME.really_unlikely_name_to_have_accidentally_in_a_non_errb_structure =
4006     666;
4007   ERROR_ME_NOT.
4008     really_unlikely_name_to_have_accidentally_in_a_non_errb_structure = 42;
4009   ERROR_ME_WARN.
4010     really_unlikely_name_to_have_accidentally_in_a_non_errb_structure =
4011       3333632;
4012 #endif /* ERROR_CHECK_TYPECHECK */
4013 }
4014
4015 void
4016 init_alloc_once_early (void)
4017 {
4018   reinit_alloc_once_early ();
4019
4020   {
4021     int i;
4022     for (i = 0; i < countof (lrecord_implementations_table); i++)
4023       lrecord_implementations_table[i] = 0;
4024   }
4025
4026   INIT_LRECORD_IMPLEMENTATION (cons);
4027   INIT_LRECORD_IMPLEMENTATION (vector);
4028   INIT_LRECORD_IMPLEMENTATION (string);
4029   INIT_LRECORD_IMPLEMENTATION (lcrecord_list);
4030
4031   staticidx = 0;
4032 }
4033
4034 int pure_bytes_used = 0;
4035
4036 void
4037 reinit_alloc (void)
4038 {
4039   gcprolist = 0;
4040 }
4041
4042 void
4043 syms_of_alloc (void)
4044 {
4045   defsymbol (&Qpre_gc_hook, "pre-gc-hook");
4046   defsymbol (&Qpost_gc_hook, "post-gc-hook");
4047   defsymbol (&Qgarbage_collecting, "garbage-collecting");
4048
4049   DEFSUBR (Fcons);
4050   DEFSUBR (Flist);
4051   DEFSUBR (Fvector);
4052   DEFSUBR (Fbit_vector);
4053   DEFSUBR (Fmake_byte_code);
4054   DEFSUBR (Fmake_list);
4055   DEFSUBR (Fmake_vector);
4056   DEFSUBR (Fmake_bit_vector);
4057   DEFSUBR (Fmake_string);
4058   DEFSUBR (Fstring);
4059   DEFSUBR (Fmake_symbol);
4060   DEFSUBR (Fmake_marker);
4061   DEFSUBR (Fpurecopy);
4062   DEFSUBR (Fgarbage_collect);
4063 #if 0
4064   DEFSUBR (Fmemory_limit);
4065 #endif
4066   DEFSUBR (Fconsing_since_gc);
4067 }
4068
4069 void
4070 vars_of_alloc (void)
4071 {
4072   DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold /*
4073 *Number of bytes of consing between garbage collections.
4074 \"Consing\" is a misnomer in that this actually counts allocation
4075 of all different kinds of objects, not just conses.
4076 Garbage collection can happen automatically once this many bytes have been
4077 allocated since the last garbage collection.  All data types count.
4078
4079 Garbage collection happens automatically when `eval' or `funcall' are
4080 called.  (Note that `funcall' is called implicitly as part of evaluation.)
4081 By binding this temporarily to a large number, you can effectively
4082 prevent garbage collection during a part of the program.
4083
4084 See also `consing-since-gc'.
4085 */ );
4086
4087   DEFVAR_INT ("pure-bytes-used", &pure_bytes_used /*
4088 Number of bytes of sharable Lisp data allocated so far.
4089 */ );
4090
4091 #if 0
4092   DEFVAR_INT ("data-bytes-used", &malloc_sbrk_used /*
4093 Number of bytes of unshared memory allocated in this session.
4094 */ );
4095
4096   DEFVAR_INT ("data-bytes-free", &malloc_sbrk_unused /*
4097 Number of bytes of unshared memory remaining available in this session.
4098 */ );
4099 #endif
4100
4101 #ifdef DEBUG_XEMACS
4102   DEFVAR_INT ("debug-allocation", &debug_allocation /*
4103 If non-zero, print out information to stderr about all objects allocated.
4104 See also `debug-allocation-backtrace-length'.
4105 */ );
4106   debug_allocation = 0;
4107
4108   DEFVAR_INT ("debug-allocation-backtrace-length",
4109               &debug_allocation_backtrace_length /*
4110 Length (in stack frames) of short backtrace printed out by `debug-allocation'.
4111 */ );
4112   debug_allocation_backtrace_length = 2;
4113 #endif
4114
4115   DEFVAR_BOOL ("purify-flag", &purify_flag /*
4116 Non-nil means loading Lisp code in order to dump an executable.
4117 This means that certain objects should be allocated in readonly space.
4118 */ );
4119
4120   DEFVAR_LISP ("pre-gc-hook", &Vpre_gc_hook /*
4121 Function or functions to be run just before each garbage collection.
4122 Interrupts, garbage collection, and errors are inhibited while this hook
4123 runs, so be extremely careful in what you add here.  In particular, avoid
4124 consing, and do not interact with the user.
4125 */ );
4126   Vpre_gc_hook = Qnil;
4127
4128   DEFVAR_LISP ("post-gc-hook", &Vpost_gc_hook /*
4129 Function or functions to be run just after each garbage collection.
4130 Interrupts, garbage collection, and errors are inhibited while this hook
4131 runs, so be extremely careful in what you add here.  In particular, avoid
4132 consing, and do not interact with the user.
4133 */ );
4134   Vpost_gc_hook = Qnil;
4135
4136   DEFVAR_LISP ("gc-message", &Vgc_message /*
4137 String to print to indicate that a garbage collection is in progress.
4138 This is printed in the echo area.  If the selected frame is on a
4139 window system and `gc-pointer-glyph' specifies a value (i.e. a pointer
4140 image instance) in the domain of the selected frame, the mouse pointer
4141 will change instead of this message being printed.
4142 */ );
4143   Vgc_message = build_string (gc_default_message);
4144
4145   DEFVAR_LISP ("gc-pointer-glyph", &Vgc_pointer_glyph /*
4146 Pointer glyph used to indicate that a garbage collection is in progress.
4147 If the selected window is on a window system and this glyph specifies a
4148 value (i.e. a pointer image instance) in the domain of the selected
4149 window, the pointer will be changed as specified during garbage collection.
4150 Otherwise, a message will be printed in the echo area, as controlled
4151 by `gc-message'.
4152 */ );
4153 }
4154
4155 void
4156 complex_vars_of_alloc (void)
4157 {
4158   Vgc_pointer_glyph = Fmake_glyph_internal (Qpointer);
4159 }