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