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