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