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