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