0c4325da73768046b741a16f9722a9955d2e5ff0
[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 offsetof (Lisp_Vector, contents[((Lisp_Vector *) lheader)->size]);
1086 }
1087
1088 static int
1089 vector_equal (Lisp_Object obj1, Lisp_Object obj2, int depth)
1090 {
1091   int len = XVECTOR_LENGTH (obj1);
1092   if (len != XVECTOR_LENGTH (obj2))
1093     return 0;
1094
1095   {
1096     Lisp_Object *ptr1 = XVECTOR_DATA (obj1);
1097     Lisp_Object *ptr2 = XVECTOR_DATA (obj2);
1098     while (len--)
1099       if (!internal_equal (*ptr1++, *ptr2++, depth + 1))
1100         return 0;
1101   }
1102   return 1;
1103 }
1104
1105 static hashcode_t
1106 vector_hash (Lisp_Object obj, int depth)
1107 {
1108   return HASH2 (XVECTOR_LENGTH (obj),
1109                 internal_array_hash (XVECTOR_DATA (obj),
1110                                      XVECTOR_LENGTH (obj),
1111                                      depth + 1));
1112 }
1113
1114 static const struct lrecord_description vector_description[] = {
1115   { XD_LONG,              offsetof (Lisp_Vector, size) },
1116   { XD_LISP_OBJECT_ARRAY, offsetof (Lisp_Vector, contents), XD_INDIRECT(0, 0) },
1117   { XD_END }
1118 };
1119
1120 DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION("vector", vector,
1121                                        mark_vector, print_vector, 0,
1122                                        vector_equal,
1123                                        vector_hash,
1124                                        vector_description,
1125                                        size_vector, Lisp_Vector);
1126
1127 /* #### should allocate `small' vectors from a frob-block */
1128 static Lisp_Vector *
1129 make_vector_internal (size_t sizei)
1130 {
1131   /* no vector_next */
1132   size_t sizem = offsetof (Lisp_Vector, contents[sizei]);
1133   Lisp_Vector *p = (Lisp_Vector *) alloc_lcrecord (sizem, &lrecord_vector);
1134
1135   p->size = sizei;
1136   return p;
1137 }
1138
1139 Lisp_Object
1140 make_vector (size_t length, Lisp_Object init)
1141 {
1142   Lisp_Vector *vecp = make_vector_internal (length);
1143   Lisp_Object *p = vector_data (vecp);
1144
1145   while (length--)
1146     *p++ = init;
1147
1148   {
1149     Lisp_Object vector;
1150     XSETVECTOR (vector, vecp);
1151     return vector;
1152   }
1153 }
1154
1155 DEFUN ("make-vector", Fmake_vector, 2, 2, 0, /*
1156 Return a new vector of length LENGTH, with each element being INIT.
1157 See also the function `vector'.
1158 */
1159        (length, init))
1160 {
1161   CONCHECK_NATNUM (length);
1162   return make_vector (XINT (length), init);
1163 }
1164
1165 DEFUN ("vector", Fvector, 0, MANY, 0, /*
1166 Return a newly created vector with specified arguments as elements.
1167 Any number of arguments, even zero arguments, are allowed.
1168 */
1169        (int nargs, Lisp_Object *args))
1170 {
1171   Lisp_Vector *vecp = make_vector_internal (nargs);
1172   Lisp_Object *p = vector_data (vecp);
1173
1174   while (nargs--)
1175     *p++ = *args++;
1176
1177   {
1178     Lisp_Object vector;
1179     XSETVECTOR (vector, vecp);
1180     return vector;
1181   }
1182 }
1183
1184 Lisp_Object
1185 vector1 (Lisp_Object obj0)
1186 {
1187   return Fvector (1, &obj0);
1188 }
1189
1190 Lisp_Object
1191 vector2 (Lisp_Object obj0, Lisp_Object obj1)
1192 {
1193   Lisp_Object args[2];
1194   args[0] = obj0;
1195   args[1] = obj1;
1196   return Fvector (2, args);
1197 }
1198
1199 Lisp_Object
1200 vector3 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2)
1201 {
1202   Lisp_Object args[3];
1203   args[0] = obj0;
1204   args[1] = obj1;
1205   args[2] = obj2;
1206   return Fvector (3, args);
1207 }
1208
1209 #if 0 /* currently unused */
1210
1211 Lisp_Object
1212 vector4 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2,
1213          Lisp_Object obj3)
1214 {
1215   Lisp_Object args[4];
1216   args[0] = obj0;
1217   args[1] = obj1;
1218   args[2] = obj2;
1219   args[3] = obj3;
1220   return Fvector (4, args);
1221 }
1222
1223 Lisp_Object
1224 vector5 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2,
1225          Lisp_Object obj3, Lisp_Object obj4)
1226 {
1227   Lisp_Object args[5];
1228   args[0] = obj0;
1229   args[1] = obj1;
1230   args[2] = obj2;
1231   args[3] = obj3;
1232   args[4] = obj4;
1233   return Fvector (5, args);
1234 }
1235
1236 Lisp_Object
1237 vector6 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2,
1238          Lisp_Object obj3, Lisp_Object obj4, Lisp_Object obj5)
1239 {
1240   Lisp_Object args[6];
1241   args[0] = obj0;
1242   args[1] = obj1;
1243   args[2] = obj2;
1244   args[3] = obj3;
1245   args[4] = obj4;
1246   args[5] = obj5;
1247   return Fvector (6, args);
1248 }
1249
1250 Lisp_Object
1251 vector7 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2,
1252          Lisp_Object obj3, Lisp_Object obj4, Lisp_Object obj5,
1253          Lisp_Object obj6)
1254 {
1255   Lisp_Object args[7];
1256   args[0] = obj0;
1257   args[1] = obj1;
1258   args[2] = obj2;
1259   args[3] = obj3;
1260   args[4] = obj4;
1261   args[5] = obj5;
1262   args[6] = obj6;
1263   return Fvector (7, args);
1264 }
1265
1266 Lisp_Object
1267 vector8 (Lisp_Object obj0, Lisp_Object obj1, Lisp_Object obj2,
1268          Lisp_Object obj3, Lisp_Object obj4, Lisp_Object obj5,
1269          Lisp_Object obj6, Lisp_Object obj7)
1270 {
1271   Lisp_Object args[8];
1272   args[0] = obj0;
1273   args[1] = obj1;
1274   args[2] = obj2;
1275   args[3] = obj3;
1276   args[4] = obj4;
1277   args[5] = obj5;
1278   args[6] = obj6;
1279   args[7] = obj7;
1280   return Fvector (8, args);
1281 }
1282 #endif /* unused */
1283
1284 /************************************************************************/
1285 /*                       Bit Vector allocation                          */
1286 /************************************************************************/
1287
1288 static Lisp_Object all_bit_vectors;
1289
1290 /* #### should allocate `small' bit vectors from a frob-block */
1291 static Lisp_Bit_Vector *
1292 make_bit_vector_internal (size_t sizei)
1293 {
1294   size_t num_longs = BIT_VECTOR_LONG_STORAGE (sizei);
1295   size_t sizem = offsetof (Lisp_Bit_Vector, bits[num_longs]);
1296   Lisp_Bit_Vector *p = (Lisp_Bit_Vector *) allocate_lisp_storage (sizem);
1297   set_lheader_implementation (&p->lheader, &lrecord_bit_vector);
1298
1299   INCREMENT_CONS_COUNTER (sizem, "bit-vector");
1300
1301   bit_vector_length (p) = sizei;
1302   bit_vector_next   (p) = all_bit_vectors;
1303   /* make sure the extra bits in the last long are 0; the calling
1304      functions might not set them. */
1305   p->bits[num_longs - 1] = 0;
1306   XSETBIT_VECTOR (all_bit_vectors, p);
1307   return p;
1308 }
1309
1310 Lisp_Object
1311 make_bit_vector (size_t length, Lisp_Object init)
1312 {
1313   Lisp_Bit_Vector *p = make_bit_vector_internal (length);
1314   size_t num_longs = BIT_VECTOR_LONG_STORAGE (length);
1315
1316   CHECK_BIT (init);
1317
1318   if (ZEROP (init))
1319     memset (p->bits, 0, num_longs * sizeof (long));
1320   else
1321     {
1322       size_t bits_in_last = length & (LONGBITS_POWER_OF_2 - 1);
1323       memset (p->bits, ~0, num_longs * sizeof (long));
1324       /* But we have to make sure that the unused bits in the
1325          last long are 0, so that equal/hash is easy. */
1326       if (bits_in_last)
1327         p->bits[num_longs - 1] &= (1 << bits_in_last) - 1;
1328     }
1329
1330   {
1331     Lisp_Object bit_vector;
1332     XSETBIT_VECTOR (bit_vector, p);
1333     return bit_vector;
1334   }
1335 }
1336
1337 Lisp_Object
1338 make_bit_vector_from_byte_vector (unsigned char *bytevec, size_t length)
1339 {
1340   int i;
1341   Lisp_Bit_Vector *p = make_bit_vector_internal (length);
1342
1343   for (i = 0; i < length; i++)
1344     set_bit_vector_bit (p, i, bytevec[i]);
1345
1346   {
1347     Lisp_Object bit_vector;
1348     XSETBIT_VECTOR (bit_vector, p);
1349     return bit_vector;
1350   }
1351 }
1352
1353 DEFUN ("make-bit-vector", Fmake_bit_vector, 2, 2, 0, /*
1354 Return a new bit vector of length LENGTH. with each bit being INIT.
1355 Each element is set to INIT.  See also the function `bit-vector'.
1356 */
1357        (length, init))
1358 {
1359   CONCHECK_NATNUM (length);
1360
1361   return make_bit_vector (XINT (length), init);
1362 }
1363
1364 DEFUN ("bit-vector", Fbit_vector, 0, MANY, 0, /*
1365 Return a newly created bit vector with specified arguments as elements.
1366 Any number of arguments, even zero arguments, are allowed.
1367 */
1368        (int nargs, Lisp_Object *args))
1369 {
1370   int i;
1371   Lisp_Bit_Vector *p = make_bit_vector_internal (nargs);
1372
1373   for (i = 0; i < nargs; i++)
1374     {
1375       CHECK_BIT (args[i]);
1376       set_bit_vector_bit (p, i, !ZEROP (args[i]));
1377     }
1378
1379   {
1380     Lisp_Object bit_vector;
1381     XSETBIT_VECTOR (bit_vector, p);
1382     return bit_vector;
1383   }
1384 }
1385
1386 \f
1387 /************************************************************************/
1388 /*                   Compiled-function allocation                       */
1389 /************************************************************************/
1390
1391 DECLARE_FIXED_TYPE_ALLOC (compiled_function, Lisp_Compiled_Function);
1392 #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_compiled_function 1000
1393
1394 static Lisp_Object
1395 make_compiled_function (void)
1396 {
1397   Lisp_Compiled_Function *f;
1398   Lisp_Object fun;
1399
1400   ALLOCATE_FIXED_TYPE (compiled_function, Lisp_Compiled_Function, f);
1401   set_lheader_implementation (&f->lheader, &lrecord_compiled_function);
1402
1403   f->stack_depth = 0;
1404   f->specpdl_depth = 0;
1405   f->flags.documentationp = 0;
1406   f->flags.interactivep = 0;
1407   f->flags.domainp = 0; /* I18N3 */
1408   f->instructions = Qzero;
1409   f->constants = Qzero;
1410   f->arglist = Qnil;
1411   f->doc_and_interactive = Qnil;
1412 #ifdef COMPILED_FUNCTION_ANNOTATION_HACK
1413   f->annotated = Qnil;
1414 #endif
1415   XSETCOMPILED_FUNCTION (fun, f);
1416   return fun;
1417 }
1418
1419 DEFUN ("make-byte-code", Fmake_byte_code, 4, MANY, 0, /*
1420 Return a new compiled-function object.
1421 Usage: (arglist instructions constants stack-depth
1422         &optional doc-string interactive)
1423 Note that, unlike all other emacs-lisp functions, calling this with five
1424 arguments is NOT the same as calling it with six arguments, the last of
1425 which is nil.  If the INTERACTIVE arg is specified as nil, then that means
1426 that this function was defined with `(interactive)'.  If the arg is not
1427 specified, then that means the function is not interactive.
1428 This is terrible behavior which is retained for compatibility with old
1429 `.elc' files which expect these semantics.
1430 */
1431        (int nargs, Lisp_Object *args))
1432 {
1433 /* In a non-insane world this function would have this arglist...
1434    (arglist instructions constants stack_depth &optional doc_string interactive)
1435  */
1436   Lisp_Object fun = make_compiled_function ();
1437   Lisp_Compiled_Function *f = XCOMPILED_FUNCTION (fun);
1438
1439   Lisp_Object arglist      = args[0];
1440   Lisp_Object instructions = args[1];
1441   Lisp_Object constants    = args[2];
1442   Lisp_Object stack_depth  = args[3];
1443   Lisp_Object doc_string   = (nargs > 4) ? args[4] : Qnil;
1444   Lisp_Object interactive  = (nargs > 5) ? args[5] : Qunbound;
1445
1446   if (nargs < 4 || nargs > 6)
1447     return Fsignal (Qwrong_number_of_arguments,
1448                     list2 (intern ("make-byte-code"), make_int (nargs)));
1449
1450   /* Check for valid formal parameter list now, to allow us to use
1451      SPECBIND_FAST_UNSAFE() later in funcall_compiled_function(). */
1452   {
1453     Lisp_Object symbol, tail;
1454     EXTERNAL_LIST_LOOP_3 (symbol, arglist, tail)
1455       {
1456         CHECK_SYMBOL (symbol);
1457         if (EQ (symbol, Qt)   ||
1458             EQ (symbol, Qnil) ||
1459             SYMBOL_IS_KEYWORD (symbol))
1460           signal_simple_error_2
1461             ("Invalid constant symbol in formal parameter list",
1462              symbol, arglist);
1463       }
1464   }
1465   f->arglist = arglist;
1466
1467   /* `instructions' is a string or a cons (string . int) for a
1468      lazy-loaded function. */
1469   if (CONSP (instructions))
1470     {
1471       CHECK_STRING (XCAR (instructions));
1472       CHECK_INT (XCDR (instructions));
1473     }
1474   else
1475     {
1476       CHECK_STRING (instructions);
1477     }
1478   f->instructions = instructions;
1479
1480   if (!NILP (constants))
1481     CHECK_VECTOR (constants);
1482   f->constants = constants;
1483
1484   CHECK_NATNUM (stack_depth);
1485   f->stack_depth = (unsigned short) XINT (stack_depth);
1486
1487 #ifdef COMPILED_FUNCTION_ANNOTATION_HACK
1488   if (!NILP (Vcurrent_compiled_function_annotation))
1489     f->annotated = Fcopy (Vcurrent_compiled_function_annotation);
1490   else if (!NILP (Vload_file_name_internal_the_purecopy))
1491     f->annotated = Vload_file_name_internal_the_purecopy;
1492   else if (!NILP (Vload_file_name_internal))
1493     {
1494       struct gcpro gcpro1;
1495       GCPRO1 (fun);             /* don't let fun get reaped */
1496       Vload_file_name_internal_the_purecopy =
1497         Ffile_name_nondirectory (Vload_file_name_internal);
1498       f->annotated = Vload_file_name_internal_the_purecopy;
1499       UNGCPRO;
1500     }
1501 #endif /* COMPILED_FUNCTION_ANNOTATION_HACK */
1502
1503   /* doc_string may be nil, string, int, or a cons (string . int).
1504      interactive may be list or string (or unbound). */
1505   f->doc_and_interactive = Qunbound;
1506 #ifdef I18N3
1507   if ((f->flags.domainp = !NILP (Vfile_domain)) != 0)
1508     f->doc_and_interactive = Vfile_domain;
1509 #endif
1510   if ((f->flags.interactivep = !UNBOUNDP (interactive)) != 0)
1511     {
1512       f->doc_and_interactive
1513         = (UNBOUNDP (f->doc_and_interactive) ? interactive :
1514            Fcons (interactive, f->doc_and_interactive));
1515     }
1516   if ((f->flags.documentationp = !NILP (doc_string)) != 0)
1517     {
1518       f->doc_and_interactive
1519         = (UNBOUNDP (f->doc_and_interactive) ? doc_string :
1520            Fcons (doc_string, f->doc_and_interactive));
1521     }
1522   if (UNBOUNDP (f->doc_and_interactive))
1523     f->doc_and_interactive = Qnil;
1524
1525   return fun;
1526 }
1527
1528 \f
1529 /************************************************************************/
1530 /*                          Symbol allocation                           */
1531 /************************************************************************/
1532
1533 DECLARE_FIXED_TYPE_ALLOC (symbol, Lisp_Symbol);
1534 #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_symbol 1000
1535
1536 DEFUN ("make-symbol", Fmake_symbol, 1, 1, 0, /*
1537 Return a newly allocated uninterned symbol whose name is NAME.
1538 Its value and function definition are void, and its property list is nil.
1539 */
1540        (name))
1541 {
1542   Lisp_Object val;
1543   Lisp_Symbol *p;
1544
1545   CHECK_STRING (name);
1546
1547   ALLOCATE_FIXED_TYPE (symbol, Lisp_Symbol, p);
1548   set_lheader_implementation (&p->lheader, &lrecord_symbol);
1549   p->name     = XSTRING (name);
1550   p->plist    = Qnil;
1551   p->value    = Qunbound;
1552   p->function = Qunbound;
1553   symbol_next (p) = 0;
1554   XSETSYMBOL (val, p);
1555   return val;
1556 }
1557
1558 \f
1559 /************************************************************************/
1560 /*                         Extent allocation                            */
1561 /************************************************************************/
1562
1563 DECLARE_FIXED_TYPE_ALLOC (extent, struct extent);
1564 #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_extent 1000
1565
1566 struct extent *
1567 allocate_extent (void)
1568 {
1569   struct extent *e;
1570
1571   ALLOCATE_FIXED_TYPE (extent, struct extent, e);
1572   set_lheader_implementation (&e->lheader, &lrecord_extent);
1573   extent_object (e) = Qnil;
1574   set_extent_start (e, -1);
1575   set_extent_end (e, -1);
1576   e->plist = Qnil;
1577
1578   xzero (e->flags);
1579
1580   extent_face (e) = Qnil;
1581   e->flags.end_open = 1;  /* default is for endpoints to behave like markers */
1582   e->flags.detachable = 1;
1583
1584   return e;
1585 }
1586
1587 \f
1588 /************************************************************************/
1589 /*                         Event allocation                             */
1590 /************************************************************************/
1591
1592 DECLARE_FIXED_TYPE_ALLOC (event, Lisp_Event);
1593 #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_event 1000
1594
1595 Lisp_Object
1596 allocate_event (void)
1597 {
1598   Lisp_Object val;
1599   Lisp_Event *e;
1600
1601   ALLOCATE_FIXED_TYPE (event, Lisp_Event, e);
1602   set_lheader_implementation (&e->lheader, &lrecord_event);
1603
1604   XSETEVENT (val, e);
1605   return val;
1606 }
1607
1608 \f
1609 /************************************************************************/
1610 /*                       Marker allocation                              */
1611 /************************************************************************/
1612
1613 DECLARE_FIXED_TYPE_ALLOC (marker, Lisp_Marker);
1614 #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_marker 1000
1615
1616 DEFUN ("make-marker", Fmake_marker, 0, 0, 0, /*
1617 Return a new marker which does not point at any place.
1618 */
1619        ())
1620 {
1621   Lisp_Object val;
1622   Lisp_Marker *p;
1623
1624   ALLOCATE_FIXED_TYPE (marker, Lisp_Marker, p);
1625   set_lheader_implementation (&p->lheader, &lrecord_marker);
1626   p->buffer = 0;
1627   p->memind = 0;
1628   marker_next (p) = 0;
1629   marker_prev (p) = 0;
1630   p->insertion_type = 0;
1631   XSETMARKER (val, p);
1632   return val;
1633 }
1634
1635 Lisp_Object
1636 noseeum_make_marker (void)
1637 {
1638   Lisp_Object val;
1639   Lisp_Marker *p;
1640
1641   NOSEEUM_ALLOCATE_FIXED_TYPE (marker, Lisp_Marker, p);
1642   set_lheader_implementation (&p->lheader, &lrecord_marker);
1643   p->buffer = 0;
1644   p->memind = 0;
1645   marker_next (p) = 0;
1646   marker_prev (p) = 0;
1647   p->insertion_type = 0;
1648   XSETMARKER (val, p);
1649   return val;
1650 }
1651
1652 \f
1653 /************************************************************************/
1654 /*                        String allocation                             */
1655 /************************************************************************/
1656
1657 /* The data for "short" strings generally resides inside of structs of type
1658    string_chars_block. The Lisp_String structure is allocated just like any
1659    other Lisp object (except for vectors), and these are freelisted when
1660    they get garbage collected. The data for short strings get compacted,
1661    but the data for large strings do not.
1662
1663    Previously Lisp_String structures were relocated, but this caused a lot
1664    of bus-errors because the C code didn't include enough GCPRO's for
1665    strings (since EVERY REFERENCE to a short string needed to be GCPRO'd so
1666    that the reference would get relocated).
1667
1668    This new method makes things somewhat bigger, but it is MUCH safer.  */
1669
1670 DECLARE_FIXED_TYPE_ALLOC (string, Lisp_String);
1671 /* strings are used and freed quite often */
1672 /* #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_string 10000 */
1673 #define MINIMUM_ALLOWED_FIXED_TYPE_CELLS_string 1000
1674
1675 static Lisp_Object
1676 mark_string (Lisp_Object obj)
1677 {
1678   Lisp_String *ptr = XSTRING (obj);
1679
1680   if (CONSP (ptr->plist) && EXTENT_INFOP (XCAR (ptr->plist)))
1681     flush_cached_extent_info (XCAR (ptr->plist));
1682   return ptr->plist;
1683 }
1684
1685 static int
1686 string_equal (Lisp_Object obj1, Lisp_Object obj2, int depth)
1687 {
1688   Bytecount len;
1689   return (((len = XSTRING_LENGTH (obj1)) == XSTRING_LENGTH (obj2)) &&
1690           !memcmp (XSTRING_DATA (obj1), XSTRING_DATA (obj2), len));
1691 }
1692
1693 static const struct lrecord_description string_description[] = {
1694   { XD_BYTECOUNT,       offsetof (Lisp_String, size) },
1695   { XD_OPAQUE_DATA_PTR, offsetof (Lisp_String, data), XD_INDIRECT(0, 1) },
1696   { XD_LISP_OBJECT,     offsetof (Lisp_String, plist) },
1697   { XD_END }
1698 };
1699
1700 /* We store the string's extent info as the first element of the string's
1701    property list; and the string's MODIFF as the first or second element
1702    of the string's property list (depending on whether the extent info
1703    is present), but only if the string has been modified.  This is ugly
1704    but it reduces the memory allocated for the string in the vast
1705    majority of cases, where the string is never modified and has no
1706    extent info.
1707
1708    #### This means you can't use an int as a key in a string's plist. */
1709
1710 static Lisp_Object *
1711 string_plist_ptr (Lisp_Object string)
1712 {
1713   Lisp_Object *ptr = &XSTRING (string)->plist;
1714
1715   if (CONSP (*ptr) && EXTENT_INFOP (XCAR (*ptr)))
1716     ptr = &XCDR (*ptr);
1717   if (CONSP (*ptr) && INTP (XCAR (*ptr)))
1718     ptr = &XCDR (*ptr);
1719   return ptr;
1720 }
1721
1722 static Lisp_Object
1723 string_getprop (Lisp_Object string, Lisp_Object property)
1724 {
1725   return external_plist_get (string_plist_ptr (string), property, 0, ERROR_ME);
1726 }
1727
1728 static int
1729 string_putprop (Lisp_Object string, Lisp_Object property, Lisp_Object value)
1730 {
1731   external_plist_put (string_plist_ptr (string), property, value, 0, ERROR_ME);
1732   return 1;
1733 }
1734
1735 static int
1736 string_remprop (Lisp_Object string, Lisp_Object property)
1737 {
1738   return external_remprop (string_plist_ptr (string), property, 0, ERROR_ME);
1739 }
1740
1741 static Lisp_Object
1742 string_plist (Lisp_Object string)
1743 {
1744   return *string_plist_ptr (string);
1745 }
1746
1747 /* No `finalize', or `hash' methods.
1748    internal_hash() already knows how to hash strings and finalization
1749    is done with the ADDITIONAL_FREE_string macro, which is the
1750    standard way to do finalization when using
1751    SWEEP_FIXED_TYPE_BLOCK(). */
1752 DEFINE_BASIC_LRECORD_IMPLEMENTATION_WITH_PROPS ("string", string,
1753                                                 mark_string, print_string,
1754                                                 0, string_equal, 0,
1755                                                 string_description,
1756                                                 string_getprop,
1757                                                 string_putprop,
1758                                                 string_remprop,
1759                                                 string_plist,
1760                                                 Lisp_String);
1761
1762 /* String blocks contain this many useful bytes. */
1763 #define STRING_CHARS_BLOCK_SIZE                                 \
1764 ((Bytecount) (8192 - MALLOC_OVERHEAD -                          \
1765               ((2 * sizeof (struct string_chars_block *))       \
1766                + sizeof (EMACS_INT))))
1767 /* Block header for small strings. */
1768 struct string_chars_block
1769 {
1770   EMACS_INT pos;
1771   struct string_chars_block *next;
1772   struct string_chars_block *prev;
1773   /* Contents of string_chars_block->string_chars are interleaved
1774      string_chars structures (see below) and the actual string data */
1775   unsigned char string_chars[STRING_CHARS_BLOCK_SIZE];
1776 };
1777
1778 static struct string_chars_block *first_string_chars_block;
1779 static struct string_chars_block *current_string_chars_block;
1780
1781 /* If SIZE is the length of a string, this returns how many bytes
1782  *  the string occupies in string_chars_block->string_chars
1783  *  (including alignment padding).
1784  */
1785 #define STRING_FULLSIZE(size) \
1786    ALIGN_SIZE (((size) + 1 + sizeof (Lisp_String *)),\
1787                ALIGNOF (Lisp_String *))
1788
1789 #define BIG_STRING_FULLSIZE_P(fullsize) ((fullsize) >= STRING_CHARS_BLOCK_SIZE)
1790 #define BIG_STRING_SIZE_P(size) (BIG_STRING_FULLSIZE_P (STRING_FULLSIZE(size)))
1791
1792 struct string_chars
1793 {
1794   Lisp_String *string;
1795   unsigned char chars[1];
1796 };
1797
1798 struct unused_string_chars
1799 {
1800   Lisp_String *string;
1801   EMACS_INT fullsize;
1802 };
1803
1804 static void
1805 init_string_chars_alloc (void)
1806 {
1807   first_string_chars_block = xnew (struct string_chars_block);
1808   first_string_chars_block->prev = 0;
1809   first_string_chars_block->next = 0;
1810   first_string_chars_block->pos = 0;
1811   current_string_chars_block = first_string_chars_block;
1812 }
1813
1814 static struct string_chars *
1815 allocate_string_chars_struct (Lisp_String *string_it_goes_with,
1816                               EMACS_INT fullsize)
1817 {
1818   struct string_chars *s_chars;
1819
1820   if (fullsize <=
1821       (countof (current_string_chars_block->string_chars)
1822        - current_string_chars_block->pos))
1823     {
1824       /* This string can fit in the current string chars block */
1825       s_chars = (struct string_chars *)
1826         (current_string_chars_block->string_chars
1827          + current_string_chars_block->pos);
1828       current_string_chars_block->pos += fullsize;
1829     }
1830   else
1831     {
1832       /* Make a new current string chars block */
1833       struct string_chars_block *new_scb = xnew (struct string_chars_block);
1834
1835       current_string_chars_block->next = new_scb;
1836       new_scb->prev = current_string_chars_block;
1837       new_scb->next = 0;
1838       current_string_chars_block = new_scb;
1839       new_scb->pos = fullsize;
1840       s_chars = (struct string_chars *)
1841         current_string_chars_block->string_chars;
1842     }
1843
1844   s_chars->string = string_it_goes_with;
1845
1846   INCREMENT_CONS_COUNTER (fullsize, "string chars");
1847
1848   return s_chars;
1849 }
1850
1851 Lisp_Object
1852 make_uninit_string (Bytecount length)
1853 {
1854   Lisp_String *s;
1855   EMACS_INT fullsize = STRING_FULLSIZE (length);
1856   Lisp_Object val;
1857
1858   assert (length >= 0 && fullsize > 0);
1859
1860   /* Allocate the string header */
1861   ALLOCATE_FIXED_TYPE (string, Lisp_String, s);
1862   set_lheader_implementation (&s->lheader, &lrecord_string);
1863
1864   set_string_data (s, BIG_STRING_FULLSIZE_P (fullsize)
1865                    ? xnew_array (Bufbyte, length + 1)
1866                    : allocate_string_chars_struct (s, fullsize)->chars);
1867
1868   set_string_length (s, length);
1869   s->plist = Qnil;
1870
1871   set_string_byte (s, length, 0);
1872
1873   XSETSTRING (val, s);
1874   return val;
1875 }
1876
1877 #ifdef VERIFY_STRING_CHARS_INTEGRITY
1878 static void verify_string_chars_integrity (void);
1879 #endif
1880
1881 /* Resize the string S so that DELTA bytes can be inserted starting
1882    at POS.  If DELTA < 0, it means deletion starting at POS.  If
1883    POS < 0, resize the string but don't copy any characters.  Use
1884    this if you're planning on completely overwriting the string.
1885 */
1886
1887 void
1888 resize_string (Lisp_String *s, Bytecount pos, Bytecount delta)
1889 {
1890   Bytecount oldfullsize, newfullsize;
1891 #ifdef VERIFY_STRING_CHARS_INTEGRITY
1892   verify_string_chars_integrity ();
1893 #endif
1894
1895 #ifdef ERROR_CHECK_BUFPOS
1896   if (pos >= 0)
1897     {
1898       assert (pos <= string_length (s));
1899       if (delta < 0)
1900         assert (pos + (-delta) <= string_length (s));
1901     }
1902   else
1903     {
1904       if (delta < 0)
1905         assert ((-delta) <= string_length (s));
1906     }
1907 #endif /* ERROR_CHECK_BUFPOS */
1908
1909   if (delta == 0)
1910     /* simplest case: no size change. */
1911     return;
1912
1913   if (pos >= 0 && delta < 0)
1914     /* If DELTA < 0, the functions below will delete the characters
1915        before POS.  We want to delete characters *after* POS, however,
1916        so convert this to the appropriate form. */
1917     pos += -delta;
1918
1919   oldfullsize = STRING_FULLSIZE (string_length (s));
1920   newfullsize = STRING_FULLSIZE (string_length (s) + delta);
1921
1922   if (BIG_STRING_FULLSIZE_P (oldfullsize))
1923     {
1924       if (BIG_STRING_FULLSIZE_P (newfullsize))
1925         {
1926           /* Both strings are big.  We can just realloc().
1927              But careful!  If the string is shrinking, we have to
1928              memmove() _before_ realloc(), and if growing, we have to
1929              memmove() _after_ realloc() - otherwise the access is
1930              illegal, and we might crash. */
1931           Bytecount len = string_length (s) + 1 - pos;
1932
1933           if (delta < 0 && pos >= 0)
1934             memmove (string_data (s) + pos + delta, string_data (s) + pos, len);
1935           set_string_data (s, (Bufbyte *) xrealloc (string_data (s),
1936                                                     string_length (s) + delta + 1));
1937           if (delta > 0 && pos >= 0)
1938             memmove (string_data (s) + pos + delta, string_data (s) + pos, len);
1939         }
1940       else /* String has been demoted from BIG_STRING. */
1941         {
1942           Bufbyte *new_data =
1943             allocate_string_chars_struct (s, newfullsize)->chars;
1944           Bufbyte *old_data = string_data (s);
1945
1946           if (pos >= 0)
1947             {
1948               memcpy (new_data, old_data, pos);
1949               memcpy (new_data + pos + delta, old_data + pos,
1950                       string_length (s) + 1 - pos);
1951             }
1952           set_string_data (s, new_data);
1953           xfree (old_data);
1954         }
1955     }
1956   else /* old string is small */
1957     {
1958       if (oldfullsize == newfullsize)
1959         {
1960           /* special case; size change but the necessary
1961              allocation size won't change (up or down; code
1962              somewhere depends on there not being any unused
1963              allocation space, modulo any alignment
1964              constraints). */
1965           if (pos >= 0)
1966             {
1967               Bufbyte *addroff = pos + string_data (s);
1968
1969               memmove (addroff + delta, addroff,
1970                        /* +1 due to zero-termination. */
1971                        string_length (s) + 1 - pos);
1972             }
1973         }
1974       else
1975         {
1976           Bufbyte *old_data = string_data (s);
1977           Bufbyte *new_data =
1978             BIG_STRING_FULLSIZE_P (newfullsize)
1979             ? xnew_array (Bufbyte, string_length (s) + delta + 1)
1980             : allocate_string_chars_struct (s, newfullsize)->chars;
1981
1982           if (pos >= 0)
1983             {
1984               memcpy (new_data, old_data, pos);
1985               memcpy (new_data + pos + delta, old_data + pos,
1986                       string_length (s) + 1 - pos);
1987             }
1988           set_string_data (s, new_data);
1989
1990           {
1991             /* We need to mark this chunk of the string_chars_block
1992                as unused so that compact_string_chars() doesn't
1993                freak. */
1994             struct string_chars *old_s_chars = (struct string_chars *)
1995               ((char *) old_data - offsetof (struct string_chars, chars));
1996             /* Sanity check to make sure we aren't hosed by strange
1997                alignment/padding. */
1998             assert (old_s_chars->string == s);
1999             MARK_STRUCT_AS_FREE (old_s_chars);
2000             ((struct unused_string_chars *) old_s_chars)->fullsize =
2001               oldfullsize;
2002           }
2003         }
2004     }
2005
2006   set_string_length (s, string_length (s) + delta);
2007   /* If pos < 0, the string won't be zero-terminated.
2008      Terminate now just to make sure. */
2009   string_data (s)[string_length (s)] = '\0';
2010
2011   if (pos >= 0)
2012     {
2013       Lisp_Object string;
2014
2015       XSETSTRING (string, s);
2016       /* We also have to adjust all of the extent indices after the
2017          place we did the change.  We say "pos - 1" because
2018          adjust_extents() is exclusive of the starting position
2019          passed to it. */
2020       adjust_extents (string, pos - 1, string_length (s),
2021                       delta);
2022     }
2023
2024 #ifdef VERIFY_STRING_CHARS_INTEGRITY
2025   verify_string_chars_integrity ();
2026 #endif
2027 }
2028
2029 #ifdef MULE
2030
2031 void
2032 set_string_char (Lisp_String *s, Charcount i, Emchar c)
2033 {
2034   Bufbyte newstr[MAX_EMCHAR_LEN];
2035   Bytecount bytoff = charcount_to_bytecount (string_data (s), i);
2036   Bytecount oldlen = charcount_to_bytecount (string_data (s) + bytoff, 1);
2037   Bytecount newlen = set_charptr_emchar (newstr, c);
2038
2039   if (oldlen != newlen)
2040     resize_string (s, bytoff, newlen - oldlen);
2041   /* Remember, string_data (s) might have changed so we can't cache it. */
2042   memcpy (string_data (s) + bytoff, newstr, newlen);
2043 }
2044
2045 #endif /* MULE */
2046
2047 DEFUN ("make-string", Fmake_string, 2, 2, 0, /*
2048 Return a new string of length LENGTH, with each character being INIT.
2049 LENGTH must be an integer and INIT must be a character.
2050 */
2051        (length, init))
2052 {
2053   CHECK_NATNUM (length);
2054   CHECK_CHAR_COERCE_INT (init);
2055   {
2056     Bufbyte init_str[MAX_EMCHAR_LEN];
2057     int len = set_charptr_emchar (init_str, XCHAR (init));
2058     Lisp_Object val = make_uninit_string (len * XINT (length));
2059
2060     if (len == 1)
2061       /* Optimize the single-byte case */
2062       memset (XSTRING_DATA (val), XCHAR (init), XSTRING_LENGTH (val));
2063     else
2064       {
2065         size_t i;
2066         Bufbyte *ptr = XSTRING_DATA (val);
2067
2068         for (i = XINT (length); i; i--)
2069           {
2070             Bufbyte *init_ptr = init_str;
2071             switch (len)
2072               {
2073               case 4: *ptr++ = *init_ptr++;
2074               case 3: *ptr++ = *init_ptr++;
2075               case 2: *ptr++ = *init_ptr++;
2076               case 1: *ptr++ = *init_ptr++;
2077               }
2078           }
2079       }
2080     return val;
2081   }
2082 }
2083
2084 DEFUN ("string", Fstring, 0, MANY, 0, /*
2085 Concatenate all the argument characters and make the result a string.
2086 */
2087        (int nargs, Lisp_Object *args))
2088 {
2089   Bufbyte *storage = alloca_array (Bufbyte, nargs * MAX_EMCHAR_LEN);
2090   Bufbyte *p = storage;
2091
2092   for (; nargs; nargs--, args++)
2093     {
2094       Lisp_Object lisp_char = *args;
2095       CHECK_CHAR_COERCE_INT (lisp_char);
2096       p += set_charptr_emchar (p, XCHAR (lisp_char));
2097     }
2098   return make_string (storage, p - storage);
2099 }
2100
2101
2102 /* Take some raw memory, which MUST already be in internal format,
2103    and package it up into a Lisp string. */
2104 Lisp_Object
2105 make_string (const Bufbyte *contents, Bytecount length)
2106 {
2107   Lisp_Object val;
2108
2109   /* Make sure we find out about bad make_string's when they happen */
2110 #if defined (ERROR_CHECK_BUFPOS) && defined (MULE)
2111   bytecount_to_charcount (contents, length); /* Just for the assertions */
2112 #endif
2113
2114   val = make_uninit_string (length);
2115   memcpy (XSTRING_DATA (val), contents, length);
2116   return val;
2117 }
2118
2119 /* Take some raw memory, encoded in some external data format,
2120    and convert it into a Lisp string. */
2121 Lisp_Object
2122 make_ext_string (const Extbyte *contents, EMACS_INT length,
2123                  Lisp_Object coding_system)
2124 {
2125   Lisp_Object string;
2126   TO_INTERNAL_FORMAT (DATA, (contents, length),
2127                       LISP_STRING, string,
2128                       coding_system);
2129   return string;
2130 }
2131
2132 Lisp_Object
2133 build_string (const char *str)
2134 {
2135   /* Some strlen's crash and burn if passed null. */
2136   return make_string ((const Bufbyte *) str, (str ? strlen(str) : 0));
2137 }
2138
2139 Lisp_Object
2140 build_ext_string (const char *str, Lisp_Object coding_system)
2141 {
2142   /* Some strlen's crash and burn if passed null. */
2143   return make_ext_string ((const Extbyte *) str, (str ? strlen(str) : 0),
2144                           coding_system);
2145 }
2146
2147 Lisp_Object
2148 build_translated_string (const char *str)
2149 {
2150   return build_string (GETTEXT (str));
2151 }
2152
2153 Lisp_Object
2154 make_string_nocopy (const Bufbyte *contents, Bytecount length)
2155 {
2156   Lisp_String *s;
2157   Lisp_Object val;
2158
2159   /* Make sure we find out about bad make_string_nocopy's when they happen */
2160 #if defined (ERROR_CHECK_BUFPOS) && defined (MULE)
2161   bytecount_to_charcount (contents, length); /* Just for the assertions */
2162 #endif
2163
2164   /* Allocate the string header */
2165   ALLOCATE_FIXED_TYPE (string, Lisp_String, s);
2166   set_lheader_implementation (&s->lheader, &lrecord_string);
2167   SET_C_READONLY_RECORD_HEADER (&s->lheader);
2168   s->plist = Qnil;
2169   set_string_data (s, (Bufbyte *)contents);
2170   set_string_length (s, length);
2171
2172   XSETSTRING (val, s);
2173   return val;
2174 }
2175
2176 \f
2177 /************************************************************************/
2178 /*                           lcrecord lists                             */
2179 /************************************************************************/
2180
2181 /* Lcrecord lists are used to manage the allocation of particular
2182    sorts of lcrecords, to avoid calling alloc_lcrecord() (and thus
2183    malloc() and garbage-collection junk) as much as possible.
2184    It is similar to the Blocktype class.
2185
2186    It works like this:
2187
2188    1) Create an lcrecord-list object using make_lcrecord_list().
2189       This is often done at initialization.  Remember to staticpro_nodump
2190       this object!  The arguments to make_lcrecord_list() are the
2191       same as would be passed to alloc_lcrecord().
2192    2) Instead of calling alloc_lcrecord(), call allocate_managed_lcrecord()
2193       and pass the lcrecord-list earlier created.
2194    3) When done with the lcrecord, call free_managed_lcrecord().
2195       The standard freeing caveats apply: ** make sure there are no
2196       pointers to the object anywhere! **
2197    4) Calling free_managed_lcrecord() is just like kissing the
2198       lcrecord goodbye as if it were garbage-collected.  This means:
2199       -- the contents of the freed lcrecord are undefined, and the
2200          contents of something produced by allocate_managed_lcrecord()
2201          are undefined, just like for alloc_lcrecord().
2202       -- the mark method for the lcrecord's type will *NEVER* be called
2203          on freed lcrecords.
2204       -- the finalize method for the lcrecord's type will be called
2205          at the time that free_managed_lcrecord() is called.
2206
2207    */
2208
2209 static Lisp_Object
2210 mark_lcrecord_list (Lisp_Object obj)
2211 {
2212   struct lcrecord_list *list = XLCRECORD_LIST (obj);
2213   Lisp_Object chain = list->free;
2214
2215   while (!NILP (chain))
2216     {
2217       struct lrecord_header *lheader = XRECORD_LHEADER (chain);
2218       struct free_lcrecord_header *free_header =
2219         (struct free_lcrecord_header *) lheader;
2220
2221       gc_checking_assert
2222         (/* There should be no other pointers to the free list. */
2223          ! MARKED_RECORD_HEADER_P (lheader)
2224          &&
2225          /* Only lcrecords should be here. */
2226          ! LHEADER_IMPLEMENTATION (lheader)->basic_p
2227          &&
2228          /* Only free lcrecords should be here. */
2229          free_header->lcheader.free
2230          &&
2231          /* The type of the lcrecord must be right. */
2232          LHEADER_IMPLEMENTATION (lheader) == list->implementation
2233          &&
2234          /* So must the size. */
2235          (LHEADER_IMPLEMENTATION (lheader)->static_size == 0 ||
2236           LHEADER_IMPLEMENTATION (lheader)->static_size == list->size)
2237          );
2238
2239       MARK_RECORD_HEADER (lheader);
2240       chain = free_header->chain;
2241     }
2242
2243   return Qnil;
2244 }
2245
2246 DEFINE_LRECORD_IMPLEMENTATION ("lcrecord-list", lcrecord_list,
2247                                mark_lcrecord_list, internal_object_printer,
2248                                0, 0, 0, 0, struct lcrecord_list);
2249 Lisp_Object
2250 make_lcrecord_list (size_t size,
2251                     const struct lrecord_implementation *implementation)
2252 {
2253   struct lcrecord_list *p = alloc_lcrecord_type (struct lcrecord_list,
2254                                                  &lrecord_lcrecord_list);
2255   Lisp_Object val;
2256
2257   p->implementation = implementation;
2258   p->size = size;
2259   p->free = Qnil;
2260   XSETLCRECORD_LIST (val, p);
2261   return val;
2262 }
2263
2264 Lisp_Object
2265 allocate_managed_lcrecord (Lisp_Object lcrecord_list)
2266 {
2267   struct lcrecord_list *list = XLCRECORD_LIST (lcrecord_list);
2268   if (!NILP (list->free))
2269     {
2270       Lisp_Object val = list->free;
2271       struct free_lcrecord_header *free_header =
2272         (struct free_lcrecord_header *) XPNTR (val);
2273
2274 #ifdef ERROR_CHECK_GC
2275       struct lrecord_header *lheader = &free_header->lcheader.lheader;
2276
2277       /* There should be no other pointers to the free list. */
2278       assert (! MARKED_RECORD_HEADER_P (lheader));
2279       /* Only lcrecords should be here. */
2280       assert (! LHEADER_IMPLEMENTATION (lheader)->basic_p);
2281       /* Only free lcrecords should be here. */
2282       assert (free_header->lcheader.free);
2283       /* The type of the lcrecord must be right. */
2284       assert (LHEADER_IMPLEMENTATION (lheader) == list->implementation);
2285       /* So must the size. */
2286       assert (LHEADER_IMPLEMENTATION (lheader)->static_size == 0 ||
2287               LHEADER_IMPLEMENTATION (lheader)->static_size == list->size);
2288 #endif /* ERROR_CHECK_GC */
2289
2290       list->free = free_header->chain;
2291       free_header->lcheader.free = 0;
2292       return val;
2293     }
2294   else
2295     {
2296       Lisp_Object val;
2297
2298       XSETOBJ (val, Lisp_Type_Record,
2299                alloc_lcrecord (list->size, list->implementation));
2300       return val;
2301     }
2302 }
2303
2304 void
2305 free_managed_lcrecord (Lisp_Object lcrecord_list, Lisp_Object lcrecord)
2306 {
2307   struct lcrecord_list *list = XLCRECORD_LIST (lcrecord_list);
2308   struct free_lcrecord_header *free_header =
2309     (struct free_lcrecord_header *) XPNTR (lcrecord);
2310   struct lrecord_header *lheader = &free_header->lcheader.lheader;
2311   const struct lrecord_implementation *implementation
2312     = LHEADER_IMPLEMENTATION (lheader);
2313
2314   /* Make sure the size is correct.  This will catch, for example,
2315      putting a window configuration on the wrong free list. */
2316   gc_checking_assert ((implementation->size_in_bytes_method ?
2317                        implementation->size_in_bytes_method (lheader) :
2318                        implementation->static_size)
2319                       == list->size);
2320
2321   if (implementation->finalizer)
2322     implementation->finalizer (lheader, 0);
2323   free_header->chain = list->free;
2324   free_header->lcheader.free = 1;
2325   list->free = lcrecord;
2326 }
2327
2328 \f
2329
2330 \f
2331 DEFUN ("purecopy", Fpurecopy, 1, 1, 0, /*
2332 Kept for compatibility, returns its argument.
2333 Old:
2334 Make a copy of OBJECT in pure storage.
2335 Recursively copies contents of vectors and cons cells.
2336 Does not copy symbols.
2337 */
2338        (obj))
2339 {
2340   return obj;
2341 }
2342
2343 \f
2344 /************************************************************************/
2345 /*                         Garbage Collection                           */
2346 /************************************************************************/
2347
2348 /* All the built-in lisp object types are enumerated in `enum lrecord_type'.
2349    Additional ones may be defined by a module (none yet).  We leave some
2350    room in `lrecord_implementations_table' for such new lisp object types. */
2351 #define MODULE_DEFINABLE_TYPE_COUNT 32
2352 const struct lrecord_implementation *lrecord_implementations_table[lrecord_type_count + MODULE_DEFINABLE_TYPE_COUNT];
2353
2354 /* Object marker functions are in the lrecord_implementation structure.
2355    But copying them to a parallel array is much more cache-friendly.
2356    This hack speeds up (garbage-collect) by about 5%. */
2357 Lisp_Object (*lrecord_markers[countof (lrecord_implementations_table)]) (Lisp_Object);
2358
2359 struct gcpro *gcprolist;
2360
2361 /* 415 used Mly 29-Jun-93 */
2362 /* 1327 used slb 28-Feb-98 */
2363 /* 1328 used og  03-Oct-99 (moving slowly, heh?) */
2364 #ifdef HAVE_SHLIB
2365 #define NSTATICS 4000
2366 #else
2367 #define NSTATICS 2000
2368 #endif
2369
2370 /* Not "static" because used by dumper.c */
2371 Lisp_Object *staticvec[NSTATICS];
2372 int staticidx;
2373
2374 /* Put an entry in staticvec, pointing at the variable whose address is given
2375  */
2376 void
2377 staticpro (Lisp_Object *varaddress)
2378 {
2379   /* #### This is now a dubious assert() since this routine may be called */
2380   /* by Lisp attempting to load a DLL. */
2381   assert (staticidx < countof (staticvec));
2382   staticvec[staticidx++] = varaddress;
2383 }
2384
2385
2386 Lisp_Object *staticvec_nodump[200];
2387 int staticidx_nodump;
2388
2389 /* Put an entry in staticvec_nodump, pointing at the variable whose address is given
2390  */
2391 void
2392 staticpro_nodump (Lisp_Object *varaddress)
2393 {
2394   /* #### This is now a dubious assert() since this routine may be called */
2395   /* by Lisp attempting to load a DLL. */
2396   assert (staticidx_nodump < countof (staticvec_nodump));
2397   staticvec_nodump[staticidx_nodump++] = varaddress;
2398 }
2399
2400
2401 struct pdump_dumpstructinfo dumpstructvec[200];
2402 int dumpstructidx;
2403
2404 /* Put an entry in dumpstructvec, pointing at the variable whose address is given
2405  */
2406 void
2407 dumpstruct (void *varaddress, const struct struct_description *desc)
2408 {
2409   assert (dumpstructidx < countof (dumpstructvec));
2410   dumpstructvec[dumpstructidx].data = varaddress;
2411   dumpstructvec[dumpstructidx].desc = desc;
2412   dumpstructidx++;
2413 }
2414
2415 struct pdump_dumpopaqueinfo dumpopaquevec[250];
2416 int dumpopaqueidx;
2417
2418 /* Put an entry in dumpopaquevec, pointing at the variable whose address is given
2419  */
2420 void
2421 dumpopaque (void *varaddress, size_t size)
2422 {
2423   assert (dumpopaqueidx < countof (dumpopaquevec));
2424
2425   dumpopaquevec[dumpopaqueidx].data = varaddress;
2426   dumpopaquevec[dumpopaqueidx].size = size;
2427   dumpopaqueidx++;
2428 }
2429
2430 Lisp_Object *pdump_wirevec[50];
2431 int pdump_wireidx;
2432
2433 /* Put an entry in pdump_wirevec, pointing at the variable whose address is given
2434  */
2435 void
2436 pdump_wire (Lisp_Object *varaddress)
2437 {
2438   assert (pdump_wireidx < countof (pdump_wirevec));
2439   pdump_wirevec[pdump_wireidx++] = varaddress;
2440 }
2441
2442
2443 Lisp_Object *pdump_wirevec_list[50];
2444 int pdump_wireidx_list;
2445
2446 /* Put an entry in pdump_wirevec_list, pointing at the variable whose address is given
2447  */
2448 void
2449 pdump_wire_list (Lisp_Object *varaddress)
2450 {
2451   assert (pdump_wireidx_list < countof (pdump_wirevec_list));
2452   pdump_wirevec_list[pdump_wireidx_list++] = varaddress;
2453 }
2454
2455 #ifdef ERROR_CHECK_GC
2456 #define GC_CHECK_LHEADER_INVARIANTS(lheader) do {               \
2457   struct lrecord_header * GCLI_lh = (lheader);                  \
2458   assert (GCLI_lh != 0);                                        \
2459   assert (GCLI_lh->type < lrecord_type_count);                  \
2460   assert (! C_READONLY_RECORD_HEADER_P (GCLI_lh) ||             \
2461           (MARKED_RECORD_HEADER_P (GCLI_lh) &&                  \
2462            LISP_READONLY_RECORD_HEADER_P (GCLI_lh)));           \
2463 } while (0)
2464 #else
2465 #define GC_CHECK_LHEADER_INVARIANTS(lheader)
2466 #endif
2467
2468 \f
2469 /* Mark reference to a Lisp_Object.  If the object referred to has not been
2470    seen yet, recursively mark all the references contained in it. */
2471
2472 void
2473 mark_object (Lisp_Object obj)
2474 {
2475  tail_recurse:
2476
2477   /* Checks we used to perform */
2478   /* if (EQ (obj, Qnull_pointer)) return; */
2479   /* if (!POINTER_TYPE_P (XGCTYPE (obj))) return; */
2480   /* if (PURIFIED (XPNTR (obj))) return; */
2481
2482   if (XTYPE (obj) == Lisp_Type_Record)
2483     {
2484       struct lrecord_header *lheader = XRECORD_LHEADER (obj);
2485
2486       GC_CHECK_LHEADER_INVARIANTS (lheader);
2487
2488       gc_checking_assert (LHEADER_IMPLEMENTATION (lheader)->basic_p ||
2489                           ! ((struct lcrecord_header *) lheader)->free);
2490
2491       /* All c_readonly objects have their mark bit set,
2492          so that we only need to check the mark bit here. */
2493       if (! MARKED_RECORD_HEADER_P (lheader))
2494         {
2495           MARK_RECORD_HEADER (lheader);
2496
2497           if (RECORD_MARKER (lheader))
2498             {
2499               obj = RECORD_MARKER (lheader) (obj);
2500               if (!NILP (obj)) goto tail_recurse;
2501             }
2502         }
2503     }
2504 }
2505
2506 /* mark all of the conses in a list and mark the final cdr; but
2507    DO NOT mark the cars.
2508
2509    Use only for internal lists!  There should never be other pointers
2510    to the cons cells, because if so, the cars will remain unmarked
2511    even when they maybe should be marked. */
2512 void
2513 mark_conses_in_list (Lisp_Object obj)
2514 {
2515   Lisp_Object rest;
2516
2517   for (rest = obj; CONSP (rest); rest = XCDR (rest))
2518     {
2519       if (CONS_MARKED_P (XCONS (rest)))
2520         return;
2521       MARK_CONS (XCONS (rest));
2522     }
2523
2524   mark_object (rest);
2525 }
2526
2527 \f
2528 /* Find all structures not marked, and free them. */
2529
2530 static int gc_count_num_bit_vector_used, gc_count_bit_vector_total_size;
2531 static int gc_count_bit_vector_storage;
2532 static int gc_count_num_short_string_in_use;
2533 static int gc_count_string_total_size;
2534 static int gc_count_short_string_total_size;
2535
2536 /* static int gc_count_total_records_used, gc_count_records_total_size; */
2537
2538 \f
2539 /* stats on lcrecords in use - kinda kludgy */
2540
2541 static struct
2542 {
2543   int instances_in_use;
2544   int bytes_in_use;
2545   int instances_freed;
2546   int bytes_freed;
2547   int instances_on_free_list;
2548 } lcrecord_stats [countof (lrecord_implementations_table)];
2549
2550 static void
2551 tick_lcrecord_stats (const struct lrecord_header *h, int free_p)
2552 {
2553   unsigned int type_index = h->type;
2554
2555   if (((struct lcrecord_header *) h)->free)
2556     {
2557       gc_checking_assert (!free_p);
2558       lcrecord_stats[type_index].instances_on_free_list++;
2559     }
2560   else
2561     {
2562       const struct lrecord_implementation *implementation =
2563         LHEADER_IMPLEMENTATION (h);
2564
2565       size_t sz = (implementation->size_in_bytes_method ?
2566                    implementation->size_in_bytes_method (h) :
2567                    implementation->static_size);
2568       if (free_p)
2569         {
2570           lcrecord_stats[type_index].instances_freed++;
2571           lcrecord_stats[type_index].bytes_freed += sz;
2572         }
2573       else
2574         {
2575           lcrecord_stats[type_index].instances_in_use++;
2576           lcrecord_stats[type_index].bytes_in_use += sz;
2577         }
2578     }
2579 }
2580
2581 \f
2582 /* Free all unmarked records */
2583 static void
2584 sweep_lcrecords_1 (struct lcrecord_header **prev, int *used)
2585 {
2586   struct lcrecord_header *header;
2587   int num_used = 0;
2588   /* int total_size = 0; */
2589
2590   xzero (lcrecord_stats); /* Reset all statistics to 0. */
2591
2592   /* First go through and call all the finalize methods.
2593      Then go through and free the objects.  There used to
2594      be only one loop here, with the call to the finalizer
2595      occurring directly before the xfree() below.  That
2596      is marginally faster but much less safe -- if the
2597      finalize method for an object needs to reference any
2598      other objects contained within it (and many do),
2599      we could easily be screwed by having already freed that
2600      other object. */
2601
2602   for (header = *prev; header; header = header->next)
2603     {
2604       struct lrecord_header *h = &(header->lheader);
2605
2606       GC_CHECK_LHEADER_INVARIANTS (h);
2607
2608       if (! MARKED_RECORD_HEADER_P (h) && ! header->free)
2609         {
2610           if (LHEADER_IMPLEMENTATION (h)->finalizer)
2611             LHEADER_IMPLEMENTATION (h)->finalizer (h, 0);
2612         }
2613     }
2614
2615   for (header = *prev; header; )
2616     {
2617       struct lrecord_header *h = &(header->lheader);
2618       if (MARKED_RECORD_HEADER_P (h))
2619         {
2620           if (! C_READONLY_RECORD_HEADER_P (h))
2621             UNMARK_RECORD_HEADER (h);
2622           num_used++;
2623           /* total_size += n->implementation->size_in_bytes (h);*/
2624           /* #### May modify header->next on a C_READONLY lcrecord */
2625           prev = &(header->next);
2626           header = *prev;
2627           tick_lcrecord_stats (h, 0);
2628         }
2629       else
2630         {
2631           struct lcrecord_header *next = header->next;
2632           *prev = next;
2633           tick_lcrecord_stats (h, 1);
2634           /* used to call finalizer right here. */
2635           xfree (header);
2636           header = next;
2637         }
2638     }
2639   *used = num_used;
2640   /* *total = total_size; */
2641 }
2642
2643
2644 static void
2645 sweep_bit_vectors_1 (Lisp_Object *prev,
2646                      int *used, int *total, int *storage)
2647 {
2648   Lisp_Object bit_vector;
2649   int num_used = 0;
2650   int total_size = 0;
2651   int total_storage = 0;
2652
2653   /* BIT_VECTORP fails because the objects are marked, which changes
2654      their implementation */
2655   for (bit_vector = *prev; !EQ (bit_vector, Qzero); )
2656     {
2657       Lisp_Bit_Vector *v = XBIT_VECTOR (bit_vector);
2658       int len = v->size;
2659       if (MARKED_RECORD_P (bit_vector))
2660         {
2661           if (! C_READONLY_RECORD_HEADER_P(&(v->lheader)))
2662             UNMARK_RECORD_HEADER (&(v->lheader));
2663           total_size += len;
2664           total_storage +=
2665             MALLOC_OVERHEAD +
2666             offsetof (Lisp_Bit_Vector, bits[BIT_VECTOR_LONG_STORAGE (len)]);
2667           num_used++;
2668           /* #### May modify next on a C_READONLY bitvector */
2669           prev = &(bit_vector_next (v));
2670           bit_vector = *prev;
2671         }
2672       else
2673         {
2674           Lisp_Object next = bit_vector_next (v);
2675           *prev = next;
2676           xfree (v);
2677           bit_vector = next;
2678         }
2679     }
2680   *used = num_used;
2681   *total = total_size;
2682   *storage = total_storage;
2683 }
2684
2685 /* And the Lord said: Thou shalt use the `c-backslash-region' command
2686    to make macros prettier. */
2687
2688 #ifdef ERROR_CHECK_GC
2689
2690 #define SWEEP_FIXED_TYPE_BLOCK(typename, obj_type)                      \
2691 do {                                                                    \
2692   struct typename##_block *SFTB_current;                                \
2693   struct typename##_block **SFTB_prev;                                  \
2694   int SFTB_limit;                                                       \
2695   int num_free = 0, num_used = 0;                                       \
2696                                                                         \
2697   for (SFTB_prev = &current_##typename##_block,                         \
2698        SFTB_current = current_##typename##_block,                       \
2699        SFTB_limit = current_##typename##_block_index;                   \
2700        SFTB_current;                                                    \
2701        )                                                                \
2702     {                                                                   \
2703       int SFTB_iii;                                                     \
2704                                                                         \
2705       for (SFTB_iii = 0; SFTB_iii < SFTB_limit; SFTB_iii++)             \
2706         {                                                               \
2707           obj_type *SFTB_victim = &(SFTB_current->block[SFTB_iii]);     \
2708                                                                         \
2709           if (FREE_STRUCT_P (SFTB_victim))                              \
2710             {                                                           \
2711               num_free++;                                               \
2712             }                                                           \
2713           else if (C_READONLY_RECORD_HEADER_P (&SFTB_victim->lheader))  \
2714             {                                                           \
2715               num_used++;                                               \
2716             }                                                           \
2717           else if (! MARKED_RECORD_HEADER_P (&SFTB_victim->lheader))    \
2718             {                                                           \
2719               num_free++;                                               \
2720               FREE_FIXED_TYPE (typename, obj_type, SFTB_victim);        \
2721             }                                                           \
2722           else                                                          \
2723             {                                                           \
2724               num_used++;                                               \
2725               UNMARK_##typename (SFTB_victim);                          \
2726             }                                                           \
2727         }                                                               \
2728       SFTB_prev = &(SFTB_current->prev);                                \
2729       SFTB_current = SFTB_current->prev;                                \
2730       SFTB_limit = countof (current_##typename##_block->block);         \
2731     }                                                                   \
2732                                                                         \
2733   gc_count_num_##typename##_in_use = num_used;                          \
2734   gc_count_num_##typename##_freelist = num_free;                        \
2735 } while (0)
2736
2737 #else /* !ERROR_CHECK_GC */
2738
2739 #define SWEEP_FIXED_TYPE_BLOCK(typename, obj_type)                              \
2740 do {                                                                            \
2741   struct typename##_block *SFTB_current;                                        \
2742   struct typename##_block **SFTB_prev;                                          \
2743   int SFTB_limit;                                                               \
2744   int num_free = 0, num_used = 0;                                               \
2745                                                                                 \
2746   typename##_free_list = 0;                                                     \
2747                                                                                 \
2748   for (SFTB_prev = &current_##typename##_block,                                 \
2749        SFTB_current = current_##typename##_block,                               \
2750        SFTB_limit = current_##typename##_block_index;                           \
2751        SFTB_current;                                                            \
2752        )                                                                        \
2753     {                                                                           \
2754       int SFTB_iii;                                                             \
2755       int SFTB_empty = 1;                                                       \
2756       obj_type *SFTB_old_free_list = typename##_free_list;                      \
2757                                                                                 \
2758       for (SFTB_iii = 0; SFTB_iii < SFTB_limit; SFTB_iii++)                     \
2759         {                                                                       \
2760           obj_type *SFTB_victim = &(SFTB_current->block[SFTB_iii]);             \
2761                                                                                 \
2762           if (FREE_STRUCT_P (SFTB_victim))                                      \
2763             {                                                                   \
2764               num_free++;                                                       \
2765               PUT_FIXED_TYPE_ON_FREE_LIST (typename, obj_type, SFTB_victim);    \
2766             }                                                                   \
2767           else if (C_READONLY_RECORD_HEADER_P (&SFTB_victim->lheader))          \
2768             {                                                                   \
2769               SFTB_empty = 0;                                                   \
2770               num_used++;                                                       \
2771             }                                                                   \
2772           else if (! MARKED_RECORD_HEADER_P (&SFTB_victim->lheader))            \
2773             {                                                                   \
2774               num_free++;                                                       \
2775               FREE_FIXED_TYPE (typename, obj_type, SFTB_victim);                \
2776             }                                                                   \
2777           else                                                                  \
2778             {                                                                   \
2779               SFTB_empty = 0;                                                   \
2780               num_used++;                                                       \
2781               UNMARK_##typename (SFTB_victim);                                  \
2782             }                                                                   \
2783         }                                                                       \
2784       if (!SFTB_empty)                                                          \
2785         {                                                                       \
2786           SFTB_prev = &(SFTB_current->prev);                                    \
2787           SFTB_current = SFTB_current->prev;                                    \
2788         }                                                                       \
2789       else if (SFTB_current == current_##typename##_block                       \
2790                && !SFTB_current->prev)                                          \
2791         {                                                                       \
2792           /* No real point in freeing sole allocation block */                  \
2793           break;                                                                \
2794         }                                                                       \
2795       else                                                                      \
2796         {                                                                       \
2797           struct typename##_block *SFTB_victim_block = SFTB_current;            \
2798           if (SFTB_victim_block == current_##typename##_block)                  \
2799             current_##typename##_block_index                                    \
2800               = countof (current_##typename##_block->block);                    \
2801           SFTB_current = SFTB_current->prev;                                    \
2802           {                                                                     \
2803             *SFTB_prev = SFTB_current;                                          \
2804             xfree (SFTB_victim_block);                                          \
2805             /* Restore free list to what it was before victim was swept */      \
2806             typename##_free_list = SFTB_old_free_list;                          \
2807             num_free -= SFTB_limit;                                             \
2808           }                                                                     \
2809         }                                                                       \
2810       SFTB_limit = countof (current_##typename##_block->block);                 \
2811     }                                                                           \
2812                                                                                 \
2813   gc_count_num_##typename##_in_use = num_used;                                  \
2814   gc_count_num_##typename##_freelist = num_free;                                \
2815 } while (0)
2816
2817 #endif /* !ERROR_CHECK_GC */
2818
2819 \f
2820
2821
2822 static void
2823 sweep_conses (void)
2824 {
2825 #define UNMARK_cons(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
2826 #define ADDITIONAL_FREE_cons(ptr)
2827
2828   SWEEP_FIXED_TYPE_BLOCK (cons, Lisp_Cons);
2829 }
2830
2831 /* Explicitly free a cons cell.  */
2832 void
2833 free_cons (Lisp_Cons *ptr)
2834 {
2835 #ifdef ERROR_CHECK_GC
2836   /* If the CAR is not an int, then it will be a pointer, which will
2837      always be four-byte aligned.  If this cons cell has already been
2838      placed on the free list, however, its car will probably contain
2839      a chain pointer to the next cons on the list, which has cleverly
2840      had all its 0's and 1's inverted.  This allows for a quick
2841      check to make sure we're not freeing something already freed. */
2842   if (POINTER_TYPE_P (XTYPE (ptr->car)))
2843     ASSERT_VALID_POINTER (XPNTR (ptr->car));
2844 #endif /* ERROR_CHECK_GC */
2845
2846 #ifndef ALLOC_NO_POOLS
2847   FREE_FIXED_TYPE_WHEN_NOT_IN_GC (cons, Lisp_Cons, ptr);
2848 #endif /* ALLOC_NO_POOLS */
2849 }
2850
2851 /* explicitly free a list.  You **must make sure** that you have
2852    created all the cons cells that make up this list and that there
2853    are no pointers to any of these cons cells anywhere else.  If there
2854    are, you will lose. */
2855
2856 void
2857 free_list (Lisp_Object list)
2858 {
2859   Lisp_Object rest, next;
2860
2861   for (rest = list; !NILP (rest); rest = next)
2862     {
2863       next = XCDR (rest);
2864       free_cons (XCONS (rest));
2865     }
2866 }
2867
2868 /* explicitly free an alist.  You **must make sure** that you have
2869    created all the cons cells that make up this alist and that there
2870    are no pointers to any of these cons cells anywhere else.  If there
2871    are, you will lose. */
2872
2873 void
2874 free_alist (Lisp_Object alist)
2875 {
2876   Lisp_Object rest, next;
2877
2878   for (rest = alist; !NILP (rest); rest = next)
2879     {
2880       next = XCDR (rest);
2881       free_cons (XCONS (XCAR (rest)));
2882       free_cons (XCONS (rest));
2883     }
2884 }
2885
2886 static void
2887 sweep_compiled_functions (void)
2888 {
2889 #define UNMARK_compiled_function(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
2890 #define ADDITIONAL_FREE_compiled_function(ptr)
2891
2892   SWEEP_FIXED_TYPE_BLOCK (compiled_function, Lisp_Compiled_Function);
2893 }
2894
2895
2896 #ifdef LISP_FLOAT_TYPE
2897 static void
2898 sweep_floats (void)
2899 {
2900 #define UNMARK_float(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
2901 #define ADDITIONAL_FREE_float(ptr)
2902
2903   SWEEP_FIXED_TYPE_BLOCK (float, Lisp_Float);
2904 }
2905 #endif /* LISP_FLOAT_TYPE */
2906
2907 static void
2908 sweep_symbols (void)
2909 {
2910 #define UNMARK_symbol(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
2911 #define ADDITIONAL_FREE_symbol(ptr)
2912
2913   SWEEP_FIXED_TYPE_BLOCK (symbol, Lisp_Symbol);
2914 }
2915
2916 static void
2917 sweep_extents (void)
2918 {
2919 #define UNMARK_extent(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
2920 #define ADDITIONAL_FREE_extent(ptr)
2921
2922   SWEEP_FIXED_TYPE_BLOCK (extent, struct extent);
2923 }
2924
2925 static void
2926 sweep_events (void)
2927 {
2928 #define UNMARK_event(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
2929 #define ADDITIONAL_FREE_event(ptr)
2930
2931   SWEEP_FIXED_TYPE_BLOCK (event, Lisp_Event);
2932 }
2933
2934 static void
2935 sweep_markers (void)
2936 {
2937 #define UNMARK_marker(ptr) UNMARK_RECORD_HEADER (&((ptr)->lheader))
2938 #define ADDITIONAL_FREE_marker(ptr)                                     \
2939   do { Lisp_Object tem;                                                 \
2940        XSETMARKER (tem, ptr);                                           \
2941        unchain_marker (tem);                                            \
2942      } while (0)
2943
2944   SWEEP_FIXED_TYPE_BLOCK (marker, Lisp_Marker);
2945 }
2946
2947 /* Explicitly free a marker.  */
2948 void
2949 free_marker (Lisp_Marker *ptr)
2950 {
2951   /* Perhaps this will catch freeing an already-freed marker. */
2952   gc_checking_assert (ptr->lheader.type = lrecord_type_marker);
2953
2954 #ifndef ALLOC_NO_POOLS
2955   FREE_FIXED_TYPE_WHEN_NOT_IN_GC (marker, Lisp_Marker, ptr);
2956 #endif /* ALLOC_NO_POOLS */
2957 }
2958 \f
2959
2960 #if defined (MULE) && defined (VERIFY_STRING_CHARS_INTEGRITY)
2961
2962 static void
2963 verify_string_chars_integrity (void)
2964 {
2965   struct string_chars_block *sb;
2966
2967   /* Scan each existing string block sequentially, string by string.  */
2968   for (sb = first_string_chars_block; sb; sb = sb->next)
2969     {
2970       int pos = 0;
2971       /* POS is the index of the next string in the block.  */
2972       while (pos < sb->pos)
2973         {
2974           struct string_chars *s_chars =
2975             (struct string_chars *) &(sb->string_chars[pos]);
2976           Lisp_String *string;
2977           int size;
2978           int fullsize;
2979
2980           /* If the string_chars struct is marked as free (i.e. the STRING
2981              pointer is 0xFFFFFFFF) then this is an unused chunk of string
2982              storage. (See below.) */
2983
2984           if (FREE_STRUCT_P (s_chars))
2985             {
2986               fullsize = ((struct unused_string_chars *) s_chars)->fullsize;
2987               pos += fullsize;
2988               continue;
2989             }
2990
2991           string = s_chars->string;
2992           /* Must be 32-bit aligned. */
2993           assert ((((int) string) & 3) == 0);
2994
2995           size = string_length (string);
2996           fullsize = STRING_FULLSIZE (size);
2997
2998           assert (!BIG_STRING_FULLSIZE_P (fullsize));
2999           assert (string_data (string) == s_chars->chars);
3000           pos += fullsize;
3001         }
3002       assert (pos == sb->pos);
3003     }
3004 }
3005
3006 #endif /* MULE && ERROR_CHECK_GC */
3007
3008 /* Compactify string chars, relocating the reference to each --
3009    free any empty string_chars_block we see. */
3010 static void
3011 compact_string_chars (void)
3012 {
3013   struct string_chars_block *to_sb = first_string_chars_block;
3014   int to_pos = 0;
3015   struct string_chars_block *from_sb;
3016
3017   /* Scan each existing string block sequentially, string by string.  */
3018   for (from_sb = first_string_chars_block; from_sb; from_sb = from_sb->next)
3019     {
3020       int from_pos = 0;
3021       /* FROM_POS is the index of the next string in the block.  */
3022       while (from_pos < from_sb->pos)
3023         {
3024           struct string_chars *from_s_chars =
3025             (struct string_chars *) &(from_sb->string_chars[from_pos]);
3026           struct string_chars *to_s_chars;
3027           Lisp_String *string;
3028           int size;
3029           int fullsize;
3030
3031           /* If the string_chars struct is marked as free (i.e. the STRING
3032              pointer is 0xFFFFFFFF) then this is an unused chunk of string
3033              storage.  This happens under Mule when a string's size changes
3034              in such a way that its fullsize changes. (Strings can change
3035              size because a different-length character can be substituted
3036              for another character.) In this case, after the bogus string
3037              pointer is the "fullsize" of this entry, i.e. how many bytes
3038              to skip. */
3039
3040           if (FREE_STRUCT_P (from_s_chars))
3041             {
3042               fullsize = ((struct unused_string_chars *) from_s_chars)->fullsize;
3043               from_pos += fullsize;
3044               continue;
3045             }
3046
3047           string = from_s_chars->string;
3048           assert (!(FREE_STRUCT_P (string)));
3049
3050           size = string_length (string);
3051           fullsize = STRING_FULLSIZE (size);
3052
3053           gc_checking_assert (! BIG_STRING_FULLSIZE_P (fullsize));
3054
3055           /* Just skip it if it isn't marked.  */
3056           if (! MARKED_RECORD_HEADER_P (&(string->lheader)))
3057             {
3058               from_pos += fullsize;
3059               continue;
3060             }
3061
3062           /* If it won't fit in what's left of TO_SB, close TO_SB out
3063              and go on to the next string_chars_block.  We know that TO_SB
3064              cannot advance past FROM_SB here since FROM_SB is large enough
3065              to currently contain this string. */
3066           if ((to_pos + fullsize) > countof (to_sb->string_chars))
3067             {
3068               to_sb->pos = to_pos;
3069               to_sb = to_sb->next;
3070               to_pos = 0;
3071             }
3072
3073           /* Compute new address of this string
3074              and update TO_POS for the space being used.  */
3075           to_s_chars = (struct string_chars *) &(to_sb->string_chars[to_pos]);
3076
3077           /* Copy the string_chars to the new place.  */
3078           if (from_s_chars != to_s_chars)
3079             memmove (to_s_chars, from_s_chars, fullsize);
3080
3081           /* Relocate FROM_S_CHARS's reference */
3082           set_string_data (string, &(to_s_chars->chars[0]));
3083
3084           from_pos += fullsize;
3085           to_pos += fullsize;
3086         }
3087     }
3088
3089   /* Set current to the last string chars block still used and
3090      free any that follow. */
3091   {
3092     struct string_chars_block *victim;
3093
3094     for (victim = to_sb->next; victim; )
3095       {
3096         struct string_chars_block *next = victim->next;
3097         xfree (victim);
3098         victim = next;
3099       }
3100
3101     current_string_chars_block = to_sb;
3102     current_string_chars_block->pos = to_pos;
3103     current_string_chars_block->next = 0;
3104   }
3105 }
3106
3107 #if 1 /* Hack to debug missing purecopy's */
3108 static int debug_string_purity;
3109
3110 static void
3111 debug_string_purity_print (Lisp_String *p)
3112 {
3113   Charcount i;
3114   Charcount s = string_char_length (p);
3115   stderr_out ("\"");
3116   for (i = 0; i < s; i++)
3117   {
3118     Emchar ch = string_char (p, i);
3119     if (ch < 32 || ch >= 126)
3120       stderr_out ("\\%03o", ch);
3121     else if (ch == '\\' || ch == '\"')
3122       stderr_out ("\\%c", ch);
3123     else
3124       stderr_out ("%c", ch);
3125   }
3126   stderr_out ("\"\n");
3127 }
3128 #endif /* 1 */
3129
3130
3131 static void
3132 sweep_strings (void)
3133 {
3134   int num_small_used = 0, num_small_bytes = 0, num_bytes = 0;
3135   int debug = debug_string_purity;
3136
3137 #define UNMARK_string(ptr) do {                 \
3138     Lisp_String *p = (ptr);                     \
3139     size_t size = string_length (p);            \
3140     UNMARK_RECORD_HEADER (&(p->lheader));       \
3141     num_bytes += size;                          \
3142     if (!BIG_STRING_SIZE_P (size))              \
3143       { num_small_bytes += size;                \
3144       num_small_used++;                         \
3145       }                                         \
3146     if (debug)                                  \
3147       debug_string_purity_print (p);            \
3148   } while (0)
3149 #define ADDITIONAL_FREE_string(ptr) do {        \
3150     size_t size = string_length (ptr);          \
3151     if (BIG_STRING_SIZE_P (size))               \
3152       xfree (ptr->data);                        \
3153   } while (0)
3154
3155   SWEEP_FIXED_TYPE_BLOCK (string, Lisp_String);
3156
3157   gc_count_num_short_string_in_use = num_small_used;
3158   gc_count_string_total_size = num_bytes;
3159   gc_count_short_string_total_size = num_small_bytes;
3160 }
3161
3162
3163 /* I hate duplicating all this crap! */
3164 int
3165 marked_p (Lisp_Object obj)
3166 {
3167   /* Checks we used to perform. */
3168   /* if (EQ (obj, Qnull_pointer)) return 1; */
3169   /* if (!POINTER_TYPE_P (XGCTYPE (obj))) return 1; */
3170   /* if (PURIFIED (XPNTR (obj))) return 1; */
3171
3172   if (XTYPE (obj) == Lisp_Type_Record)
3173     {
3174       struct lrecord_header *lheader = XRECORD_LHEADER (obj);
3175
3176       GC_CHECK_LHEADER_INVARIANTS (lheader);
3177
3178       return MARKED_RECORD_HEADER_P (lheader);
3179     }
3180   return 1;
3181 }
3182
3183 static void
3184 gc_sweep (void)
3185 {
3186   /* Free all unmarked records.  Do this at the very beginning,
3187      before anything else, so that the finalize methods can safely
3188      examine items in the objects.  sweep_lcrecords_1() makes
3189      sure to call all the finalize methods *before* freeing anything,
3190      to complete the safety. */
3191   {
3192     int ignored;
3193     sweep_lcrecords_1 (&all_lcrecords, &ignored);
3194   }
3195
3196   compact_string_chars ();
3197
3198   /* Finalize methods below (called through the ADDITIONAL_FREE_foo
3199      macros) must be *extremely* careful to make sure they're not
3200      referencing freed objects.  The only two existing finalize
3201      methods (for strings and markers) pass muster -- the string
3202      finalizer doesn't look at anything but its own specially-
3203      created block, and the marker finalizer only looks at live
3204      buffers (which will never be freed) and at the markers before
3205      and after it in the chain (which, by induction, will never be
3206      freed because if so, they would have already removed themselves
3207      from the chain). */
3208
3209   /* Put all unmarked strings on free list, free'ing the string chars
3210      of large unmarked strings */
3211   sweep_strings ();
3212
3213   /* Put all unmarked conses on free list */
3214   sweep_conses ();
3215
3216   /* Free all unmarked bit vectors */
3217   sweep_bit_vectors_1 (&all_bit_vectors,
3218                        &gc_count_num_bit_vector_used,
3219                        &gc_count_bit_vector_total_size,
3220                        &gc_count_bit_vector_storage);
3221
3222   /* Free all unmarked compiled-function objects */
3223   sweep_compiled_functions ();
3224
3225 #ifdef LISP_FLOAT_TYPE
3226   /* Put all unmarked floats on free list */
3227   sweep_floats ();
3228 #endif
3229
3230   /* Put all unmarked symbols on free list */
3231   sweep_symbols ();
3232
3233   /* Put all unmarked extents on free list */
3234   sweep_extents ();
3235
3236   /* Put all unmarked markers on free list.
3237      Dechain each one first from the buffer into which it points. */
3238   sweep_markers ();
3239
3240   sweep_events ();
3241
3242 #ifdef PDUMP
3243   pdump_objects_unmark ();
3244 #endif
3245 }
3246 \f
3247 /* Clearing for disksave. */
3248
3249 void
3250 disksave_object_finalization (void)
3251 {
3252   /* It's important that certain information from the environment not get
3253      dumped with the executable (pathnames, environment variables, etc.).
3254      To make it easier to tell when this has happened with strings(1) we
3255      clear some known-to-be-garbage blocks of memory, so that leftover
3256      results of old evaluation don't look like potential problems.
3257      But first we set some notable variables to nil and do one more GC,
3258      to turn those strings into garbage.
3259   */
3260
3261   /* Yeah, this list is pretty ad-hoc... */
3262   Vprocess_environment = Qnil;
3263   Vexec_directory = Qnil;
3264   Vdata_directory = Qnil;
3265   Vsite_directory = Qnil;
3266   Vdoc_directory = Qnil;
3267   Vconfigure_info_directory = Qnil;
3268   Vexec_path = Qnil;
3269   Vload_path = Qnil;
3270   /* Vdump_load_path = Qnil; */
3271   /* Release hash tables for locate_file */
3272   Flocate_file_clear_hashing (Qt);
3273   uncache_home_directory();
3274
3275 #if defined(LOADHIST) && !(defined(LOADHIST_DUMPED) || \
3276                            defined(LOADHIST_BUILTIN))
3277   Vload_history = Qnil;
3278 #endif
3279   Vshell_file_name = Qnil;
3280
3281   garbage_collect_1 ();
3282
3283   /* Run the disksave finalization methods of all live objects. */
3284   disksave_object_finalization_1 ();
3285
3286   /* Zero out the uninitialized (really, unused) part of the containers
3287      for the live strings. */
3288   {
3289     struct string_chars_block *scb;
3290     for (scb = first_string_chars_block; scb; scb = scb->next)
3291       {
3292         int count = sizeof (scb->string_chars) - scb->pos;
3293
3294         assert (count >= 0 && count < STRING_CHARS_BLOCK_SIZE);
3295         if (count != 0)
3296           {
3297             /* from the block's fill ptr to the end */
3298             memset ((scb->string_chars + scb->pos), 0, count);
3299           }
3300       }
3301   }
3302
3303   /* There, that ought to be enough... */
3304
3305 }
3306
3307 \f
3308 Lisp_Object
3309 restore_gc_inhibit (Lisp_Object val)
3310 {
3311   gc_currently_forbidden = XINT (val);
3312   return val;
3313 }
3314
3315 /* Maybe we want to use this when doing a "panic" gc after memory_full()? */
3316 static int gc_hooks_inhibited;
3317
3318 \f
3319 void
3320 garbage_collect_1 (void)
3321 {
3322 #if MAX_SAVE_STACK > 0
3323   char stack_top_variable;
3324   extern char *stack_bottom;
3325 #endif
3326   struct frame *f;
3327   int speccount;
3328   int cursor_changed;
3329   Lisp_Object pre_gc_cursor;
3330   struct gcpro gcpro1;
3331
3332   if (gc_in_progress
3333       || gc_currently_forbidden
3334       || in_display
3335       || preparing_for_armageddon)
3336     return;
3337
3338   /* We used to call selected_frame() here.
3339
3340      The following functions cannot be called inside GC
3341      so we move to after the above tests. */
3342   {
3343     Lisp_Object frame;
3344     Lisp_Object device = Fselected_device (Qnil);
3345     if (NILP (device)) /* Could happen during startup, eg. if always_gc */
3346       return;
3347     frame = DEVICE_SELECTED_FRAME (XDEVICE (device));
3348     if (NILP (frame))
3349       signal_simple_error ("No frames exist on device", device);
3350     f = XFRAME (frame);
3351   }
3352
3353   pre_gc_cursor = Qnil;
3354   cursor_changed = 0;
3355
3356   GCPRO1 (pre_gc_cursor);
3357
3358   /* Very important to prevent GC during any of the following
3359      stuff that might run Lisp code; otherwise, we'll likely
3360      have infinite GC recursion. */
3361   speccount = specpdl_depth ();
3362   record_unwind_protect (restore_gc_inhibit,
3363                          make_int (gc_currently_forbidden));
3364   gc_currently_forbidden = 1;
3365
3366   if (!gc_hooks_inhibited)
3367     run_hook_trapping_errors ("Error in pre-gc-hook", Qpre_gc_hook);
3368
3369   /* Now show the GC cursor/message. */
3370   if (!noninteractive)
3371     {
3372       if (FRAME_WIN_P (f))
3373         {
3374           Lisp_Object frame = make_frame (f);
3375           Lisp_Object cursor = glyph_image_instance (Vgc_pointer_glyph,
3376                                                      FRAME_SELECTED_WINDOW (f),
3377                                                      ERROR_ME_NOT, 1);
3378           pre_gc_cursor = f->pointer;
3379           if (POINTER_IMAGE_INSTANCEP (cursor)
3380               /* don't change if we don't know how to change back. */
3381               && POINTER_IMAGE_INSTANCEP (pre_gc_cursor))
3382             {
3383               cursor_changed = 1;
3384               Fset_frame_pointer (frame, cursor);
3385             }
3386         }
3387
3388       /* Don't print messages to the stream device. */
3389       if (!cursor_changed && !FRAME_STREAM_P (f))
3390         {
3391           char *msg = (STRINGP (Vgc_message)
3392                        ? GETTEXT ((char *) XSTRING_DATA (Vgc_message))
3393                        : 0);
3394           Lisp_Object args[2], whole_msg;
3395           args[0] = build_string (msg ? msg :
3396                                   GETTEXT ((const char *) gc_default_message));
3397           args[1] = build_string ("...");
3398           whole_msg = Fconcat (2, args);
3399           echo_area_message (f, (Bufbyte *) 0, whole_msg, 0, -1,
3400                              Qgarbage_collecting);
3401         }
3402     }
3403
3404   /***** Now we actually start the garbage collection. */
3405
3406   gc_in_progress = 1;
3407
3408   gc_generation_number[0]++;
3409
3410 #if MAX_SAVE_STACK > 0
3411
3412   /* Save a copy of the contents of the stack, for debugging.  */
3413   if (!purify_flag)
3414     {
3415       /* Static buffer in which we save a copy of the C stack at each GC.  */
3416       static char *stack_copy;
3417       static size_t stack_copy_size;
3418
3419       ptrdiff_t stack_diff = &stack_top_variable - stack_bottom;
3420       size_t stack_size = (stack_diff > 0 ? stack_diff : -stack_diff);
3421       if (stack_size < MAX_SAVE_STACK)
3422         {
3423           if (stack_copy_size < stack_size)
3424             {
3425               stack_copy = (char *) xrealloc (stack_copy, stack_size);
3426               stack_copy_size = stack_size;
3427             }
3428
3429           memcpy (stack_copy,
3430                   stack_diff > 0 ? stack_bottom : &stack_top_variable,
3431                   stack_size);
3432         }
3433     }
3434 #endif /* MAX_SAVE_STACK > 0 */
3435
3436   /* Do some totally ad-hoc resource clearing. */
3437   /* #### generalize this? */
3438   clear_event_resource ();
3439   cleanup_specifiers ();
3440
3441   /* Mark all the special slots that serve as the roots of accessibility. */
3442
3443   { /* staticpro() */
3444     int i;
3445     for (i = 0; i < staticidx; i++)
3446       mark_object (*(staticvec[i]));
3447     for (i = 0; i < staticidx_nodump; i++)
3448       mark_object (*(staticvec_nodump[i]));
3449   }
3450
3451   { /* GCPRO() */
3452     struct gcpro *tail;
3453     int i;
3454     for (tail = gcprolist; tail; tail = tail->next)
3455       for (i = 0; i < tail->nvars; i++)
3456         mark_object (tail->var[i]);
3457   }
3458
3459   { /* specbind() */
3460     struct specbinding *bind;
3461     for (bind = specpdl; bind != specpdl_ptr; bind++)
3462       {
3463         mark_object (bind->symbol);
3464         mark_object (bind->old_value);
3465       }
3466   }
3467
3468   {
3469     struct catchtag *catch;
3470     for (catch = catchlist; catch; catch = catch->next)
3471       {
3472         mark_object (catch->tag);
3473         mark_object (catch->val);
3474       }
3475   }
3476
3477   {
3478     struct backtrace *backlist;
3479     for (backlist = backtrace_list; backlist; backlist = backlist->next)
3480       {
3481         int nargs = backlist->nargs;
3482         int i;
3483
3484         mark_object (*backlist->function);
3485         if (nargs == UNEVALLED || nargs == MANY)
3486           mark_object (backlist->args[0]);
3487         else
3488           for (i = 0; i < nargs; i++)
3489             mark_object (backlist->args[i]);
3490       }
3491   }
3492
3493   mark_redisplay ();
3494   mark_profiling_info ();
3495
3496   /* OK, now do the after-mark stuff.  This is for things that
3497      are only marked when something else is marked (e.g. weak hash tables).
3498      There may be complex dependencies between such objects -- e.g.
3499      a weak hash table might be unmarked, but after processing a later
3500      weak hash table, the former one might get marked.  So we have to
3501      iterate until nothing more gets marked. */
3502
3503   while (finish_marking_weak_hash_tables () > 0 ||
3504          finish_marking_weak_lists       () > 0)
3505     ;
3506
3507   /* And prune (this needs to be called after everything else has been
3508      marked and before we do any sweeping). */
3509   /* #### this is somewhat ad-hoc and should probably be an object
3510      method */
3511   prune_weak_hash_tables ();
3512   prune_weak_lists ();
3513   prune_specifiers ();
3514   prune_syntax_tables ();
3515
3516   gc_sweep ();
3517
3518   consing_since_gc = 0;
3519 #ifndef DEBUG_XEMACS
3520   /* Allow you to set it really fucking low if you really want ... */
3521   if (gc_cons_threshold < 10000)
3522     gc_cons_threshold = 10000;
3523 #endif
3524
3525   gc_in_progress = 0;
3526
3527   /******* End of garbage collection ********/
3528
3529   run_hook_trapping_errors ("Error in post-gc-hook", Qpost_gc_hook);
3530
3531   /* Now remove the GC cursor/message */
3532   if (!noninteractive)
3533     {
3534       if (cursor_changed)
3535         Fset_frame_pointer (make_frame (f), pre_gc_cursor);
3536       else if (!FRAME_STREAM_P (f))
3537         {
3538           char *msg = (STRINGP (Vgc_message)
3539                        ? GETTEXT ((char *) XSTRING_DATA (Vgc_message))
3540                        : 0);
3541
3542           /* Show "...done" only if the echo area would otherwise be empty. */
3543           if (NILP (clear_echo_area (selected_frame (),
3544                                      Qgarbage_collecting, 0)))
3545             {
3546               Lisp_Object args[2], whole_msg;
3547               args[0] = build_string (msg ? msg :
3548                                       GETTEXT ((const char *)
3549                                                gc_default_message));
3550               args[1] = build_string ("... done");
3551               whole_msg = Fconcat (2, args);
3552               echo_area_message (selected_frame (), (Bufbyte *) 0,
3553                                  whole_msg, 0, -1,
3554                                  Qgarbage_collecting);
3555             }
3556         }
3557     }
3558
3559   /* now stop inhibiting GC */
3560   unbind_to (speccount, Qnil);
3561
3562   if (!breathing_space)
3563     {
3564       breathing_space = malloc (4096 - MALLOC_OVERHEAD);
3565     }
3566
3567   UNGCPRO;
3568   return;
3569 }
3570
3571 /* Debugging aids.  */
3572
3573 static Lisp_Object
3574 gc_plist_hack (const char *name, int value, Lisp_Object tail)
3575 {
3576   /* C doesn't have local functions (or closures, or GC, or readable syntax,
3577      or portable numeric datatypes, or bit-vectors, or characters, or
3578      arrays, or exceptions, or ...) */
3579   return cons3 (intern (name), make_int (value), tail);
3580 }
3581
3582 #define HACK_O_MATIC(type, name, pl) do {                               \
3583   int s = 0;                                                            \
3584   struct type##_block *x = current_##type##_block;                      \
3585   while (x) { s += sizeof (*x) + MALLOC_OVERHEAD; x = x->prev; }        \
3586   (pl) = gc_plist_hack ((name), s, (pl));                               \
3587 } while (0)
3588
3589 DEFUN ("garbage-collect", Fgarbage_collect, 0, 0, "", /*
3590 Reclaim storage for Lisp objects no longer needed.
3591 Return info on amount of space in use:
3592  ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
3593   (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
3594   PLIST)
3595   where `PLIST' is a list of alternating keyword/value pairs providing
3596   more detailed information.
3597 Garbage collection happens automatically if you cons more than
3598 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
3599 */
3600        ())
3601 {
3602   Lisp_Object pl = Qnil;
3603   int i;
3604   int gc_count_vector_total_size = 0;
3605
3606   garbage_collect_1 ();
3607
3608   for (i = 0; i < lrecord_type_count; i++)
3609     {
3610       if (lcrecord_stats[i].bytes_in_use != 0
3611           || lcrecord_stats[i].bytes_freed != 0
3612           || lcrecord_stats[i].instances_on_free_list != 0)
3613         {
3614           char buf [255];
3615           const char *name = lrecord_implementations_table[i]->name;
3616           int len = strlen (name);
3617           /* save this for the FSFmacs-compatible part of the summary */
3618           if (i == lrecord_vector.lrecord_type_index)
3619             gc_count_vector_total_size =
3620               lcrecord_stats[i].bytes_in_use + lcrecord_stats[i].bytes_freed;
3621
3622           sprintf (buf, "%s-storage", name);
3623           pl = gc_plist_hack (buf, lcrecord_stats[i].bytes_in_use, pl);
3624           /* Okay, simple pluralization check for `symbol-value-varalias' */
3625           if (name[len-1] == 's')
3626             sprintf (buf, "%ses-freed", name);
3627           else
3628             sprintf (buf, "%ss-freed", name);
3629           if (lcrecord_stats[i].instances_freed != 0)
3630             pl = gc_plist_hack (buf, lcrecord_stats[i].instances_freed, pl);
3631           if (name[len-1] == 's')
3632             sprintf (buf, "%ses-on-free-list", name);
3633           else
3634             sprintf (buf, "%ss-on-free-list", name);
3635           if (lcrecord_stats[i].instances_on_free_list != 0)
3636             pl = gc_plist_hack (buf, lcrecord_stats[i].instances_on_free_list,
3637                                 pl);
3638           if (name[len-1] == 's')
3639             sprintf (buf, "%ses-used", name);
3640           else
3641             sprintf (buf, "%ss-used", name);
3642           pl = gc_plist_hack (buf, lcrecord_stats[i].instances_in_use, pl);
3643         }
3644     }
3645
3646   HACK_O_MATIC (extent, "extent-storage", pl);
3647   pl = gc_plist_hack ("extents-free", gc_count_num_extent_freelist, pl);
3648   pl = gc_plist_hack ("extents-used", gc_count_num_extent_in_use, pl);
3649   HACK_O_MATIC (event, "event-storage", pl);
3650   pl = gc_plist_hack ("events-free", gc_count_num_event_freelist, pl);
3651   pl = gc_plist_hack ("events-used", gc_count_num_event_in_use, pl);
3652   HACK_O_MATIC (marker, "marker-storage", pl);
3653   pl = gc_plist_hack ("markers-free", gc_count_num_marker_freelist, pl);
3654   pl = gc_plist_hack ("markers-used", gc_count_num_marker_in_use, pl);
3655 #ifdef LISP_FLOAT_TYPE
3656   HACK_O_MATIC (float, "float-storage", pl);
3657   pl = gc_plist_hack ("floats-free", gc_count_num_float_freelist, pl);
3658   pl = gc_plist_hack ("floats-used", gc_count_num_float_in_use, pl);
3659 #endif /* LISP_FLOAT_TYPE */
3660   HACK_O_MATIC (string, "string-header-storage", pl);
3661   pl = gc_plist_hack ("long-strings-total-length",
3662                       gc_count_string_total_size
3663                       - gc_count_short_string_total_size, pl);
3664   HACK_O_MATIC (string_chars, "short-string-storage", pl);
3665   pl = gc_plist_hack ("short-strings-total-length",
3666                       gc_count_short_string_total_size, pl);
3667   pl = gc_plist_hack ("strings-free", gc_count_num_string_freelist, pl);
3668   pl = gc_plist_hack ("long-strings-used",
3669                       gc_count_num_string_in_use
3670                       - gc_count_num_short_string_in_use, pl);
3671   pl = gc_plist_hack ("short-strings-used",
3672                       gc_count_num_short_string_in_use, pl);
3673
3674   HACK_O_MATIC (compiled_function, "compiled-function-storage", pl);
3675   pl = gc_plist_hack ("compiled-functions-free",
3676                       gc_count_num_compiled_function_freelist, pl);
3677   pl = gc_plist_hack ("compiled-functions-used",
3678                       gc_count_num_compiled_function_in_use, pl);
3679
3680   pl = gc_plist_hack ("bit-vector-storage", gc_count_bit_vector_storage, pl);
3681   pl = gc_plist_hack ("bit-vectors-total-length",
3682                       gc_count_bit_vector_total_size, pl);
3683   pl = gc_plist_hack ("bit-vectors-used", gc_count_num_bit_vector_used, pl);
3684
3685   HACK_O_MATIC (symbol, "symbol-storage", pl);
3686   pl = gc_plist_hack ("symbols-free", gc_count_num_symbol_freelist, pl);
3687   pl = gc_plist_hack ("symbols-used", gc_count_num_symbol_in_use, pl);
3688
3689   HACK_O_MATIC (cons, "cons-storage", pl);
3690   pl = gc_plist_hack ("conses-free", gc_count_num_cons_freelist, pl);
3691   pl = gc_plist_hack ("conses-used", gc_count_num_cons_in_use, pl);
3692
3693   /* The things we do for backwards-compatibility */
3694   return
3695     list6 (Fcons (make_int (gc_count_num_cons_in_use),
3696                   make_int (gc_count_num_cons_freelist)),
3697            Fcons (make_int (gc_count_num_symbol_in_use),
3698                   make_int (gc_count_num_symbol_freelist)),
3699            Fcons (make_int (gc_count_num_marker_in_use),
3700                   make_int (gc_count_num_marker_freelist)),
3701            make_int (gc_count_string_total_size),
3702            make_int (gc_count_vector_total_size),
3703            pl);
3704 }
3705 #undef HACK_O_MATIC
3706
3707 DEFUN ("consing-since-gc", Fconsing_since_gc, 0, 0, "", /*
3708 Return the number of bytes consed since the last garbage collection.
3709 \"Consed\" is a misnomer in that this actually counts allocation
3710 of all different kinds of objects, not just conses.
3711
3712 If this value exceeds `gc-cons-threshold', a garbage collection happens.
3713 */
3714        ())
3715 {
3716   return make_int (consing_since_gc);
3717 }
3718
3719 #if 0
3720 DEFUN ("memory-limit", Fmemory_limit, 0, 0, "", /*
3721 Return the address of the last byte Emacs has allocated, divided by 1024.
3722 This may be helpful in debugging Emacs's memory usage.
3723 The value is divided by 1024 to make sure it will fit in a lisp integer.
3724 */
3725        ())
3726 {
3727   return make_int ((EMACS_INT) sbrk (0) / 1024);
3728 }
3729 #endif
3730
3731 \f
3732 int
3733 object_dead_p (Lisp_Object obj)
3734 {
3735   return ((BUFFERP  (obj) && !BUFFER_LIVE_P  (XBUFFER  (obj))) ||
3736           (FRAMEP   (obj) && !FRAME_LIVE_P   (XFRAME   (obj))) ||
3737           (WINDOWP  (obj) && !WINDOW_LIVE_P  (XWINDOW  (obj))) ||
3738           (DEVICEP  (obj) && !DEVICE_LIVE_P  (XDEVICE  (obj))) ||
3739           (CONSOLEP (obj) && !CONSOLE_LIVE_P (XCONSOLE (obj))) ||
3740           (EVENTP   (obj) && !EVENT_LIVE_P   (XEVENT   (obj))) ||
3741           (EXTENTP  (obj) && !EXTENT_LIVE_P  (XEXTENT  (obj))));
3742 }
3743
3744 #ifdef MEMORY_USAGE_STATS
3745
3746 /* Attempt to determine the actual amount of space that is used for
3747    the block allocated starting at PTR, supposedly of size "CLAIMED_SIZE".
3748
3749    It seems that the following holds:
3750
3751    1. When using the old allocator (malloc.c):
3752
3753       -- blocks are always allocated in chunks of powers of two.  For
3754          each block, there is an overhead of 8 bytes if rcheck is not
3755          defined, 20 bytes if it is defined.  In other words, a
3756          one-byte allocation needs 8 bytes of overhead for a total of
3757          9 bytes, and needs to have 16 bytes of memory chunked out for
3758          it.
3759
3760    2. When using the new allocator (gmalloc.c):
3761
3762       -- blocks are always allocated in chunks of powers of two up
3763          to 4096 bytes.  Larger blocks are allocated in chunks of
3764          an integral multiple of 4096 bytes.  The minimum block
3765          size is 2*sizeof (void *), or 16 bytes if SUNOS_LOCALTIME_BUG
3766          is defined.  There is no per-block overhead, but there
3767          is an overhead of 3*sizeof (size_t) for each 4096 bytes
3768          allocated.
3769
3770     3. When using the system malloc, anything goes, but they are
3771        generally slower and more space-efficient than the GNU
3772        allocators.  One possibly reasonable assumption to make
3773        for want of better data is that sizeof (void *), or maybe
3774        2 * sizeof (void *), is required as overhead and that
3775        blocks are allocated in the minimum required size except
3776        that some minimum block size is imposed (e.g. 16 bytes). */
3777
3778 size_t
3779 malloced_storage_size (void *ptr, size_t claimed_size,
3780                        struct overhead_stats *stats)
3781 {
3782   size_t orig_claimed_size = claimed_size;
3783
3784 #ifdef GNU_MALLOC
3785
3786   if (claimed_size < 2 * sizeof (void *))
3787     claimed_size = 2 * sizeof (void *);
3788 # ifdef SUNOS_LOCALTIME_BUG
3789   if (claimed_size < 16)
3790     claimed_size = 16;
3791 # endif
3792   if (claimed_size < 4096)
3793     {
3794       int log = 1;
3795
3796       /* compute the log base two, more or less, then use it to compute
3797          the block size needed. */
3798       claimed_size--;
3799       /* It's big, it's heavy, it's wood! */
3800       while ((claimed_size /= 2) != 0)
3801         ++log;
3802       claimed_size = 1;
3803       /* It's better than bad, it's good! */
3804       while (log > 0)
3805         {
3806           claimed_size *= 2;
3807           log--;
3808         }
3809       /* We have to come up with some average about the amount of
3810          blocks used. */
3811       if ((size_t) (rand () & 4095) < claimed_size)
3812         claimed_size += 3 * sizeof (void *);
3813     }
3814   else
3815     {
3816       claimed_size += 4095;
3817       claimed_size &= ~4095;
3818       claimed_size += (claimed_size / 4096) * 3 * sizeof (size_t);
3819     }
3820
3821 #elif defined (SYSTEM_MALLOC)
3822
3823   if (claimed_size < 16)
3824     claimed_size = 16;
3825   claimed_size += 2 * sizeof (void *);
3826
3827 #else /* old GNU allocator */
3828
3829 # ifdef rcheck /* #### may not be defined here */
3830   claimed_size += 20;
3831 # else
3832   claimed_size += 8;
3833 # endif
3834   {
3835     int log = 1;
3836
3837     /* compute the log base two, more or less, then use it to compute
3838        the block size needed. */
3839     claimed_size--;
3840     /* It's big, it's heavy, it's wood! */
3841     while ((claimed_size /= 2) != 0)
3842       ++log;
3843     claimed_size = 1;
3844     /* It's better than bad, it's good! */
3845     while (log > 0)
3846       {
3847         claimed_size *= 2;
3848         log--;
3849       }
3850   }
3851
3852 #endif /* old GNU allocator */
3853
3854   if (stats)
3855     {
3856       stats->was_requested += orig_claimed_size;
3857       stats->malloc_overhead += claimed_size - orig_claimed_size;
3858     }
3859   return claimed_size;
3860 }
3861
3862 size_t
3863 fixed_type_block_overhead (size_t size)
3864 {
3865   size_t per_block = TYPE_ALLOC_SIZE (cons, unsigned char);
3866   size_t overhead = 0;
3867   size_t storage_size = malloced_storage_size (0, per_block, 0);
3868   while (size >= per_block)
3869     {
3870       size -= per_block;
3871       overhead += sizeof (void *) + per_block - storage_size;
3872     }
3873   if (rand () % per_block < size)
3874     overhead += sizeof (void *) + per_block - storage_size;
3875   return overhead;
3876 }
3877
3878 #endif /* MEMORY_USAGE_STATS */
3879
3880 \f
3881 /* Initialization */
3882 void
3883 reinit_alloc_once_early (void)
3884 {
3885   gc_generation_number[0] = 0;
3886   breathing_space = 0;
3887   XSETINT (all_bit_vectors, 0); /* Qzero may not be set yet. */
3888   XSETINT (Vgc_message, 0);
3889   all_lcrecords = 0;
3890   ignore_malloc_warnings = 1;
3891 #ifdef DOUG_LEA_MALLOC
3892   mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
3893   mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
3894 #if 0 /* Moved to emacs.c */
3895   mallopt (M_MMAP_MAX, 64); /* max. number of mmap'ed areas */
3896 #endif
3897 #endif
3898   init_string_alloc ();
3899   init_string_chars_alloc ();
3900   init_cons_alloc ();
3901   init_symbol_alloc ();
3902   init_compiled_function_alloc ();
3903 #ifdef LISP_FLOAT_TYPE
3904   init_float_alloc ();
3905 #endif /* LISP_FLOAT_TYPE */
3906   init_marker_alloc ();
3907   init_extent_alloc ();
3908   init_event_alloc ();
3909
3910   ignore_malloc_warnings = 0;
3911
3912   staticidx_nodump = 0;
3913   dumpstructidx = 0;
3914   pdump_wireidx = 0;
3915
3916   consing_since_gc = 0;
3917 #if 1
3918   gc_cons_threshold = 500000; /* XEmacs change */
3919 #else
3920   gc_cons_threshold = 15000; /* debugging */
3921 #endif
3922 #ifdef VIRT_ADDR_VARIES
3923   malloc_sbrk_unused = 1<<22;   /* A large number */
3924   malloc_sbrk_used = 100000;    /* as reasonable as any number */
3925 #endif /* VIRT_ADDR_VARIES */
3926   lrecord_uid_counter = 259;
3927   debug_string_purity = 0;
3928   gcprolist = 0;
3929
3930   gc_currently_forbidden = 0;
3931   gc_hooks_inhibited = 0;
3932
3933 #ifdef ERROR_CHECK_TYPECHECK
3934   ERROR_ME.really_unlikely_name_to_have_accidentally_in_a_non_errb_structure =
3935     666;
3936   ERROR_ME_NOT.
3937     really_unlikely_name_to_have_accidentally_in_a_non_errb_structure = 42;
3938   ERROR_ME_WARN.
3939     really_unlikely_name_to_have_accidentally_in_a_non_errb_structure =
3940       3333632;
3941 #endif /* ERROR_CHECK_TYPECHECK */
3942 }
3943
3944 void
3945 init_alloc_once_early (void)
3946 {
3947   reinit_alloc_once_early ();
3948
3949   {
3950     int i;
3951     for (i = 0; i < countof (lrecord_implementations_table); i++)
3952       lrecord_implementations_table[i] = 0;
3953   }
3954
3955   INIT_LRECORD_IMPLEMENTATION (cons);
3956   INIT_LRECORD_IMPLEMENTATION (vector);
3957   INIT_LRECORD_IMPLEMENTATION (string);
3958   INIT_LRECORD_IMPLEMENTATION (lcrecord_list);
3959
3960   staticidx = 0;
3961 }
3962
3963 int pure_bytes_used = 0;
3964
3965 void
3966 reinit_alloc (void)
3967 {
3968   gcprolist = 0;
3969 }
3970
3971 void
3972 syms_of_alloc (void)
3973 {
3974   defsymbol (&Qpre_gc_hook, "pre-gc-hook");
3975   defsymbol (&Qpost_gc_hook, "post-gc-hook");
3976   defsymbol (&Qgarbage_collecting, "garbage-collecting");
3977
3978   DEFSUBR (Fcons);
3979   DEFSUBR (Flist);
3980   DEFSUBR (Fvector);
3981   DEFSUBR (Fbit_vector);
3982   DEFSUBR (Fmake_byte_code);
3983   DEFSUBR (Fmake_list);
3984   DEFSUBR (Fmake_vector);
3985   DEFSUBR (Fmake_bit_vector);
3986   DEFSUBR (Fmake_string);
3987   DEFSUBR (Fstring);
3988   DEFSUBR (Fmake_symbol);
3989   DEFSUBR (Fmake_marker);
3990   DEFSUBR (Fpurecopy);
3991   DEFSUBR (Fgarbage_collect);
3992 #if 0
3993   DEFSUBR (Fmemory_limit);
3994 #endif
3995   DEFSUBR (Fconsing_since_gc);
3996 }
3997
3998 void
3999 vars_of_alloc (void)
4000 {
4001   DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold /*
4002 *Number of bytes of consing between garbage collections.
4003 \"Consing\" is a misnomer in that this actually counts allocation
4004 of all different kinds of objects, not just conses.
4005 Garbage collection can happen automatically once this many bytes have been
4006 allocated since the last garbage collection.  All data types count.
4007
4008 Garbage collection happens automatically when `eval' or `funcall' are
4009 called.  (Note that `funcall' is called implicitly as part of evaluation.)
4010 By binding this temporarily to a large number, you can effectively
4011 prevent garbage collection during a part of the program.
4012
4013 See also `consing-since-gc'.
4014 */ );
4015
4016   DEFVAR_INT ("pure-bytes-used", &pure_bytes_used /*
4017 Number of bytes of sharable Lisp data allocated so far.
4018 */ );
4019
4020 #if 0
4021   DEFVAR_INT ("data-bytes-used", &malloc_sbrk_used /*
4022 Number of bytes of unshared memory allocated in this session.
4023 */ );
4024
4025   DEFVAR_INT ("data-bytes-free", &malloc_sbrk_unused /*
4026 Number of bytes of unshared memory remaining available in this session.
4027 */ );
4028 #endif
4029
4030 #ifdef DEBUG_XEMACS
4031   DEFVAR_INT ("debug-allocation", &debug_allocation /*
4032 If non-zero, print out information to stderr about all objects allocated.
4033 See also `debug-allocation-backtrace-length'.
4034 */ );
4035   debug_allocation = 0;
4036
4037   DEFVAR_INT ("debug-allocation-backtrace-length",
4038               &debug_allocation_backtrace_length /*
4039 Length (in stack frames) of short backtrace printed out by `debug-allocation'.
4040 */ );
4041   debug_allocation_backtrace_length = 2;
4042 #endif
4043
4044   DEFVAR_BOOL ("purify-flag", &purify_flag /*
4045 Non-nil means loading Lisp code in order to dump an executable.
4046 This means that certain objects should be allocated in readonly space.
4047 */ );
4048
4049   DEFVAR_LISP ("pre-gc-hook", &Vpre_gc_hook /*
4050 Function or functions to be run just before each garbage collection.
4051 Interrupts, garbage collection, and errors are inhibited while this hook
4052 runs, so be extremely careful in what you add here.  In particular, avoid
4053 consing, and do not interact with the user.
4054 */ );
4055   Vpre_gc_hook = Qnil;
4056
4057   DEFVAR_LISP ("post-gc-hook", &Vpost_gc_hook /*
4058 Function or functions to be run just after each garbage collection.
4059 Interrupts, garbage collection, and errors are inhibited while this hook
4060 runs, so be extremely careful in what you add here.  In particular, avoid
4061 consing, and do not interact with the user.
4062 */ );
4063   Vpost_gc_hook = Qnil;
4064
4065   DEFVAR_LISP ("gc-message", &Vgc_message /*
4066 String to print to indicate that a garbage collection is in progress.
4067 This is printed in the echo area.  If the selected frame is on a
4068 window system and `gc-pointer-glyph' specifies a value (i.e. a pointer
4069 image instance) in the domain of the selected frame, the mouse pointer
4070 will change instead of this message being printed.
4071 */ );
4072   Vgc_message = build_string (gc_default_message);
4073
4074   DEFVAR_LISP ("gc-pointer-glyph", &Vgc_pointer_glyph /*
4075 Pointer glyph used to indicate that a garbage collection is in progress.
4076 If the selected window is on a window system and this glyph specifies a
4077 value (i.e. a pointer image instance) in the domain of the selected
4078 window, the pointer will be changed as specified during garbage collection.
4079 Otherwise, a message will be printed in the echo area, as controlled
4080 by `gc-message'.
4081 */ );
4082 }
4083
4084 void
4085 complex_vars_of_alloc (void)
4086 {
4087   Vgc_pointer_glyph = Fmake_glyph_internal (Qpointer);
4088 }