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