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