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