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