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