1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
2 
3 Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2021 Free Software
4 Foundation, Inc.
5 
6 This file is part of GNU Emacs.
7 
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
12 
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17 
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
20 
21 #include <config.h>
22 
23 #include <errno.h>
24 #include <stdint.h>
25 #include <stdlib.h>
26 #include <limits.h>		/* For CHAR_BIT.  */
27 #include <signal.h>		/* For SIGABRT, SIGDANGER.  */
28 
29 #ifdef HAVE_PTHREAD
30 #include <pthread.h>
31 #endif
32 
33 #include "lisp.h"
34 #include "bignum.h"
35 #include "dispextern.h"
36 #include "intervals.h"
37 #include "ptr-bounds.h"
38 #include "puresize.h"
39 #include "sheap.h"
40 #include "sysstdio.h"
41 #include "systime.h"
42 #include "character.h"
43 #include "buffer.h"
44 #include "window.h"
45 #include "keyboard.h"
46 #include "frame.h"
47 #include "blockinput.h"
48 #include "pdumper.h"
49 #include "termhooks.h"		/* For struct terminal.  */
50 #ifdef HAVE_WINDOW_SYSTEM
51 #include TERM_HEADER
52 #endif /* HAVE_WINDOW_SYSTEM */
53 
54 #include <flexmember.h>
55 #include <verify.h>
56 #include <execinfo.h>           /* For backtrace.  */
57 
58 #ifdef HAVE_LINUX_SYSINFO
59 #include <sys/sysinfo.h>
60 #endif
61 
62 #ifdef MSDOS
63 #include "dosfns.h"		/* For dos_memory_info.  */
64 #endif
65 
66 #ifdef HAVE_MALLOC_H
67 # include <malloc.h>
68 #endif
69 
70 #if defined HAVE_VALGRIND_VALGRIND_H && !defined USE_VALGRIND
71 # define USE_VALGRIND 1
72 #endif
73 
74 #if USE_VALGRIND
75 #include <valgrind/valgrind.h>
76 #include <valgrind/memcheck.h>
77 #endif
78 
79 /* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects.
80    We turn that on by default when ENABLE_CHECKING is defined;
81    define GC_CHECK_MARKED_OBJECTS to zero to disable.  */
82 
83 #if defined ENABLE_CHECKING && !defined GC_CHECK_MARKED_OBJECTS
84 # define GC_CHECK_MARKED_OBJECTS 1
85 #endif
86 
87 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
88    memory.  Can do this only if using gmalloc.c and if not checking
89    marked objects.  */
90 
91 #if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
92      || defined HYBRID_MALLOC || GC_CHECK_MARKED_OBJECTS)
93 #undef GC_MALLOC_CHECK
94 #endif
95 
96 #include <unistd.h>
97 #include <fcntl.h>
98 
99 #ifdef USE_GTK
100 # include "gtkutil.h"
101 #endif
102 #ifdef WINDOWSNT
103 #include "w32.h"
104 #include "w32heap.h"	/* for sbrk */
105 #endif
106 
107 #ifdef DOUG_LEA_MALLOC
108 
109 /* Specify maximum number of areas to mmap.  It would be nice to use a
110    value that explicitly means "no limit".  */
111 
112 # define MMAP_MAX_AREAS 100000000
113 
114 /* A pointer to the memory allocated that copies that static data
115    inside glibc's malloc.  */
116 static void *malloc_state_ptr;
117 
118 /* Restore the dumped malloc state.  Because malloc can be invoked
119    even before main (e.g. by the dynamic linker), the dumped malloc
120    state must be restored as early as possible using this special hook.  */
121 static void
malloc_initialize_hook(void)122 malloc_initialize_hook (void)
123 {
124   static bool malloc_using_checking;
125 
126   if (! initialized)
127     {
128 # ifdef GNU_LINUX
129       my_heap_start ();
130 # endif
131       malloc_using_checking = getenv ("MALLOC_CHECK_") != NULL;
132     }
133   else
134     {
135       if (!malloc_using_checking)
136 	{
137 	  /* Work around a bug in glibc's malloc.  MALLOC_CHECK_ must be
138 	     ignored if the heap to be restored was constructed without
139 	     malloc checking.  Can't use unsetenv, since that calls malloc.  */
140 	  char **p = environ;
141 	  if (p)
142 	    for (; *p; p++)
143 	      if (strncmp (*p, "MALLOC_CHECK_=", 14) == 0)
144 		{
145 		  do
146 		    *p = p[1];
147 		  while (*++p);
148 
149 		  break;
150 		}
151 	}
152 
153       if (malloc_set_state (malloc_state_ptr) != 0)
154 	emacs_abort ();
155       alloc_unexec_post ();
156     }
157 }
158 
159 /* Declare the malloc initialization hook, which runs before 'main' starts.
160    EXTERNALLY_VISIBLE works around Bug#22522.  */
161 typedef void (*voidfuncptr) (void);
162 # ifndef __MALLOC_HOOK_VOLATILE
163 #  define __MALLOC_HOOK_VOLATILE
164 # endif
165 voidfuncptr __MALLOC_HOOK_VOLATILE __malloc_initialize_hook EXTERNALLY_VISIBLE
166   = malloc_initialize_hook;
167 
168 #endif
169 
170 #if defined DOUG_LEA_MALLOC || defined HAVE_UNEXEC
171 
172 /* Allocator-related actions to do just before and after unexec.  */
173 
174 void
alloc_unexec_pre(void)175 alloc_unexec_pre (void)
176 {
177 # ifdef DOUG_LEA_MALLOC
178   malloc_state_ptr = malloc_get_state ();
179   if (!malloc_state_ptr)
180     fatal ("malloc_get_state: %s", strerror (errno));
181 # endif
182 }
183 
184 void
alloc_unexec_post(void)185 alloc_unexec_post (void)
186 {
187 # ifdef DOUG_LEA_MALLOC
188   free (malloc_state_ptr);
189 # endif
190 }
191 
192 # ifdef GNU_LINUX
193 
194 /* The address where the heap starts.  */
195 void *
my_heap_start(void)196 my_heap_start (void)
197 {
198   static void *start;
199   if (! start)
200     start = sbrk (0);
201   return start;
202 }
203 # endif
204 
205 #endif
206 
207 /* Mark, unmark, query mark bit of a Lisp string.  S must be a pointer
208    to a struct Lisp_String.  */
209 
210 #define XMARK_STRING(S)		((S)->u.s.size |= ARRAY_MARK_FLAG)
211 #define XUNMARK_STRING(S)	((S)->u.s.size &= ~ARRAY_MARK_FLAG)
212 #define XSTRING_MARKED_P(S)	(((S)->u.s.size & ARRAY_MARK_FLAG) != 0)
213 
214 #define XMARK_VECTOR(V)		((V)->header.size |= ARRAY_MARK_FLAG)
215 #define XUNMARK_VECTOR(V)	((V)->header.size &= ~ARRAY_MARK_FLAG)
216 #define XVECTOR_MARKED_P(V)	(((V)->header.size & ARRAY_MARK_FLAG) != 0)
217 
218 /* Default value of gc_cons_threshold (see below).  */
219 
220 #define GC_DEFAULT_THRESHOLD (100000 * word_size)
221 
222 /* Global variables.  */
223 struct emacs_globals globals;
224 
225 /* maybe_gc collects garbage if this goes negative.  */
226 
227 EMACS_INT consing_until_gc;
228 
229 #ifdef HAVE_PDUMPER
230 /* Number of finalizers run: used to loop over GC until we stop
231    generating garbage.  */
232 int number_finalizers_run;
233 #endif
234 
235 /* True during GC.  */
236 
237 bool gc_in_progress;
238 
239 /* System byte and object counts reported by GC.  */
240 
241 /* Assume byte counts fit in uintptr_t and object counts fit into
242    intptr_t.  */
243 typedef uintptr_t byte_ct;
244 typedef intptr_t object_ct;
245 
246 /* Large-magnitude value for a threshold count, which fits in EMACS_INT.
247    Using only half the EMACS_INT range avoids overflow hassles.
248    There is no need to fit these counts into fixnums.  */
249 #define HI_THRESHOLD (EMACS_INT_MAX / 2)
250 
251 /* Number of live and free conses etc. counted by the most-recent GC.  */
252 
253 static struct gcstat
254 {
255   object_ct total_conses, total_free_conses;
256   object_ct total_symbols, total_free_symbols;
257   object_ct total_strings, total_free_strings;
258   byte_ct total_string_bytes;
259   object_ct total_vectors, total_vector_slots, total_free_vector_slots;
260   object_ct total_floats, total_free_floats;
261   object_ct total_intervals, total_free_intervals;
262   object_ct total_buffers;
263 } gcstat;
264 
265 /* Points to memory space allocated as "spare", to be freed if we run
266    out of memory.  We keep one large block, four cons-blocks, and
267    two string blocks.  */
268 
269 static char *spare_memory[7];
270 
271 /* Amount of spare memory to keep in large reserve block, or to see
272    whether this much is available when malloc fails on a larger request.  */
273 
274 #define SPARE_MEMORY (1 << 14)
275 
276 /* Initialize it to a nonzero value to force it into data space
277    (rather than bss space).  That way unexec will remap it into text
278    space (pure), on some systems.  We have not implemented the
279    remapping on more recent systems because this is less important
280    nowadays than in the days of small memories and timesharing.  */
281 
282 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
283 #define PUREBEG (char *) pure
284 
285 /* Pointer to the pure area, and its size.  */
286 
287 static char *purebeg;
288 static ptrdiff_t pure_size;
289 
290 /* Number of bytes of pure storage used before pure storage overflowed.
291    If this is non-zero, this implies that an overflow occurred.  */
292 
293 static ptrdiff_t pure_bytes_used_before_overflow;
294 
295 /* Index in pure at which next pure Lisp object will be allocated..  */
296 
297 static ptrdiff_t pure_bytes_used_lisp;
298 
299 /* Number of bytes allocated for non-Lisp objects in pure storage.  */
300 
301 static ptrdiff_t pure_bytes_used_non_lisp;
302 
303 /* If positive, garbage collection is inhibited.  Otherwise, zero.  */
304 
305 static intptr_t garbage_collection_inhibited;
306 
307 /* The GC threshold in bytes, the last time it was calculated
308    from gc-cons-threshold and gc-cons-percentage.  */
309 static EMACS_INT gc_threshold;
310 
311 /* If nonzero, this is a warning delivered by malloc and not yet
312    displayed.  */
313 
314 const char *pending_malloc_warning;
315 
316 /* Pointer sanity only on request.  FIXME: Code depending on
317    SUSPICIOUS_OBJECT_CHECKING is obsolete; remove it entirely.  */
318 #ifdef ENABLE_CHECKING
319 #define SUSPICIOUS_OBJECT_CHECKING 1
320 #endif
321 
322 #ifdef SUSPICIOUS_OBJECT_CHECKING
323 struct suspicious_free_record
324 {
325   void *suspicious_object;
326   void *backtrace[128];
327 };
328 static void *suspicious_objects[32];
329 static int suspicious_object_index;
330 struct suspicious_free_record suspicious_free_history[64] EXTERNALLY_VISIBLE;
331 static int suspicious_free_history_index;
332 /* Find the first currently-monitored suspicious pointer in range
333    [begin,end) or NULL if no such pointer exists.  */
334 static void *find_suspicious_object_in_range (void *begin, void *end);
335 static void detect_suspicious_free (void *ptr);
336 #else
337 # define find_suspicious_object_in_range(begin, end) ((void *) NULL)
338 # define detect_suspicious_free(ptr) ((void) 0)
339 #endif
340 
341 /* Maximum amount of C stack to save when a GC happens.  */
342 
343 #ifndef MAX_SAVE_STACK
344 #define MAX_SAVE_STACK 16000
345 #endif
346 
347 /* Buffer in which we save a copy of the C stack at each GC.  */
348 
349 #if MAX_SAVE_STACK > 0
350 static char *stack_copy;
351 static ptrdiff_t stack_copy_size;
352 
353 /* Copy to DEST a block of memory from SRC of size SIZE bytes,
354    avoiding any address sanitization.  */
355 
356 static void * ATTRIBUTE_NO_SANITIZE_ADDRESS
no_sanitize_memcpy(void * dest,void const * src,size_t size)357 no_sanitize_memcpy (void *dest, void const *src, size_t size)
358 {
359   if (! ADDRESS_SANITIZER)
360     return memcpy (dest, src, size);
361   else
362     {
363       size_t i;
364       char *d = dest;
365       char const *s = src;
366       for (i = 0; i < size; i++)
367 	d[i] = s[i];
368       return dest;
369     }
370 }
371 
372 #endif /* MAX_SAVE_STACK > 0 */
373 
374 static void unchain_finalizer (struct Lisp_Finalizer *);
375 static void mark_terminals (void);
376 static void gc_sweep (void);
377 static Lisp_Object make_pure_vector (ptrdiff_t);
378 static void mark_buffer (struct buffer *);
379 
380 #if !defined REL_ALLOC || defined SYSTEM_MALLOC || defined HYBRID_MALLOC
381 static void refill_memory_reserve (void);
382 #endif
383 static void compact_small_strings (void);
384 static void free_large_strings (void);
385 extern Lisp_Object which_symbols (Lisp_Object, EMACS_INT) EXTERNALLY_VISIBLE;
386 
387 /* Forward declare mark accessor functions: they're used all over the
388    place.  */
389 
390 inline static bool vector_marked_p (const struct Lisp_Vector *v);
391 inline static void set_vector_marked (struct Lisp_Vector *v);
392 
393 inline static bool vectorlike_marked_p (const union vectorlike_header *v);
394 inline static void set_vectorlike_marked (union vectorlike_header *v);
395 
396 inline static bool cons_marked_p (const struct Lisp_Cons *c);
397 inline static void set_cons_marked (struct Lisp_Cons *c);
398 
399 inline static bool string_marked_p (const struct Lisp_String *s);
400 inline static void set_string_marked (struct Lisp_String *s);
401 
402 inline static bool symbol_marked_p (const struct Lisp_Symbol *s);
403 inline static void set_symbol_marked (struct Lisp_Symbol *s);
404 
405 inline static bool interval_marked_p (INTERVAL i);
406 inline static void set_interval_marked (INTERVAL i);
407 
408 /* When scanning the C stack for live Lisp objects, Emacs keeps track of
409    what memory allocated via lisp_malloc and lisp_align_malloc is intended
410    for what purpose.  This enumeration specifies the type of memory.  */
411 
412 enum mem_type
413 {
414   MEM_TYPE_NON_LISP,
415   MEM_TYPE_BUFFER,
416   MEM_TYPE_CONS,
417   MEM_TYPE_STRING,
418   MEM_TYPE_SYMBOL,
419   MEM_TYPE_FLOAT,
420   /* Since all non-bool pseudovectors are small enough to be
421      allocated from vector blocks, this memory type denotes
422      large regular vectors and large bool pseudovectors.  */
423   MEM_TYPE_VECTORLIKE,
424   /* Special type to denote vector blocks.  */
425   MEM_TYPE_VECTOR_BLOCK,
426   /* Special type to denote reserved memory.  */
427   MEM_TYPE_SPARE
428 };
429 
430 static bool
deadp(Lisp_Object x)431 deadp (Lisp_Object x)
432 {
433   return EQ (x, dead_object ());
434 }
435 
436 #ifdef GC_MALLOC_CHECK
437 
438 enum mem_type allocated_mem_type;
439 
440 #endif /* GC_MALLOC_CHECK */
441 
442 /* A node in the red-black tree describing allocated memory containing
443    Lisp data.  Each such block is recorded with its start and end
444    address when it is allocated, and removed from the tree when it
445    is freed.
446 
447    A red-black tree is a balanced binary tree with the following
448    properties:
449 
450    1. Every node is either red or black.
451    2. Every leaf is black.
452    3. If a node is red, then both of its children are black.
453    4. Every simple path from a node to a descendant leaf contains
454    the same number of black nodes.
455    5. The root is always black.
456 
457    When nodes are inserted into the tree, or deleted from the tree,
458    the tree is "fixed" so that these properties are always true.
459 
460    A red-black tree with N internal nodes has height at most 2
461    log(N+1).  Searches, insertions and deletions are done in O(log N).
462    Please see a text book about data structures for a detailed
463    description of red-black trees.  Any book worth its salt should
464    describe them.  */
465 
466 struct mem_node
467 {
468   /* Children of this node.  These pointers are never NULL.  When there
469      is no child, the value is MEM_NIL, which points to a dummy node.  */
470   struct mem_node *left, *right;
471 
472   /* The parent of this node.  In the root node, this is NULL.  */
473   struct mem_node *parent;
474 
475   /* Start and end of allocated region.  */
476   void *start, *end;
477 
478   /* Node color.  */
479   enum {MEM_BLACK, MEM_RED} color;
480 
481   /* Memory type.  */
482   enum mem_type type;
483 };
484 
485 /* Root of the tree describing allocated Lisp memory.  */
486 
487 static struct mem_node *mem_root;
488 
489 /* Lowest and highest known address in the heap.  */
490 
491 static void *min_heap_address, *max_heap_address;
492 
493 /* Sentinel node of the tree.  */
494 
495 static struct mem_node mem_z;
496 #define MEM_NIL &mem_z
497 
498 static struct mem_node *mem_insert (void *, void *, enum mem_type);
499 static void mem_insert_fixup (struct mem_node *);
500 static void mem_rotate_left (struct mem_node *);
501 static void mem_rotate_right (struct mem_node *);
502 static void mem_delete (struct mem_node *);
503 static void mem_delete_fixup (struct mem_node *);
504 static struct mem_node *mem_find (void *);
505 
506 /* Addresses of staticpro'd variables.  Initialize it to a nonzero
507    value if we might unexec; otherwise some compilers put it into
508    BSS.  */
509 
510 Lisp_Object const *staticvec[NSTATICS]
511 #ifdef HAVE_UNEXEC
512 = {&Vpurify_flag}
513 #endif
514   ;
515 
516 /* Index of next unused slot in staticvec.  */
517 
518 int staticidx;
519 
520 static void *pure_alloc (size_t, int);
521 
522 /* Return PTR rounded up to the next multiple of ALIGNMENT.  */
523 
524 static void *
pointer_align(void * ptr,int alignment)525 pointer_align (void *ptr, int alignment)
526 {
527   return (void *) ROUNDUP ((uintptr_t) ptr, alignment);
528 }
529 
530 /* Extract the pointer hidden within O.  */
531 
532 static ATTRIBUTE_NO_SANITIZE_UNDEFINED void *
XPNTR(Lisp_Object a)533 XPNTR (Lisp_Object a)
534 {
535   return (SYMBOLP (a)
536 	  ? (char *) lispsym + (XLI (a) - LISP_WORD_TAG (Lisp_Symbol))
537 	  : (char *) XLP (a) - (XLI (a) & ~VALMASK));
538 }
539 
540 static void
XFLOAT_INIT(Lisp_Object f,double n)541 XFLOAT_INIT (Lisp_Object f, double n)
542 {
543   XFLOAT (f)->u.data = n;
544 }
545 
546 /* Account for allocation of NBYTES in the heap.  This is a separate
547    function to avoid hassles with implementation-defined conversion
548    from unsigned to signed types.  */
549 static void
tally_consing(ptrdiff_t nbytes)550 tally_consing (ptrdiff_t nbytes)
551 {
552   consing_until_gc -= nbytes;
553 }
554 
555 #ifdef DOUG_LEA_MALLOC
556 static bool
pointers_fit_in_lispobj_p(void)557 pointers_fit_in_lispobj_p (void)
558 {
559   return (UINTPTR_MAX <= VAL_MAX) || USE_LSB_TAG;
560 }
561 
562 static bool
mmap_lisp_allowed_p(void)563 mmap_lisp_allowed_p (void)
564 {
565   /* If we can't store all memory addresses in our lisp objects, it's
566      risky to let the heap use mmap and give us addresses from all
567      over our address space.  We also can't use mmap for lisp objects
568      if we might dump: unexec doesn't preserve the contents of mmapped
569      regions.  */
570   return pointers_fit_in_lispobj_p () && !will_dump_with_unexec_p ();
571 }
572 #endif
573 
574 /* Head of a circularly-linked list of extant finalizers. */
575 struct Lisp_Finalizer finalizers;
576 
577 /* Head of a circularly-linked list of finalizers that must be invoked
578    because we deemed them unreachable.  This list must be global, and
579    not a local inside garbage_collect, in case we GC again while
580    running finalizers.  */
581 struct Lisp_Finalizer doomed_finalizers;
582 
583 
584 /************************************************************************
585 				Malloc
586  ************************************************************************/
587 
588 #if defined SIGDANGER || (!defined SYSTEM_MALLOC && !defined HYBRID_MALLOC)
589 
590 /* Function malloc calls this if it finds we are near exhausting storage.  */
591 
592 void
malloc_warning(const char * str)593 malloc_warning (const char *str)
594 {
595   pending_malloc_warning = str;
596 }
597 
598 #endif
599 
600 /* Display an already-pending malloc warning.  */
601 
602 void
display_malloc_warning(void)603 display_malloc_warning (void)
604 {
605   call3 (intern ("display-warning"),
606 	 intern ("alloc"),
607 	 build_string (pending_malloc_warning),
608 	 intern ("emergency"));
609   pending_malloc_warning = 0;
610 }
611 
612 /* Called if we can't allocate relocatable space for a buffer.  */
613 
614 void
buffer_memory_full(ptrdiff_t nbytes)615 buffer_memory_full (ptrdiff_t nbytes)
616 {
617   /* If buffers use the relocating allocator, no need to free
618      spare_memory, because we may have plenty of malloc space left
619      that we could get, and if we don't, the malloc that fails will
620      itself cause spare_memory to be freed.  If buffers don't use the
621      relocating allocator, treat this like any other failing
622      malloc.  */
623 
624 #ifndef REL_ALLOC
625   memory_full (nbytes);
626 #else
627   /* This used to call error, but if we've run out of memory, we could
628      get infinite recursion trying to build the string.  */
629   xsignal (Qnil, Vmemory_signal_data);
630 #endif
631 }
632 
633 /* A common multiple of the positive integers A and B.  Ideally this
634    would be the least common multiple, but there's no way to do that
635    as a constant expression in C, so do the best that we can easily do.  */
636 #define COMMON_MULTIPLE(a, b) \
637   ((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
638 
639 /* LISP_ALIGNMENT is the alignment of Lisp objects.  It must be at
640    least GCALIGNMENT so that pointers can be tagged.  It also must be
641    at least as strict as the alignment of all the C types used to
642    implement Lisp objects; since pseudovectors can contain any C type,
643    this is max_align_t.  On recent GNU/Linux x86 and x86-64 this can
644    often waste up to 8 bytes, since alignof (max_align_t) is 16 but
645    typical vectors need only an alignment of 8.  Although shrinking
646    the alignment to 8 would save memory, it cost a 20% hit to Emacs
647    CPU performance on Fedora 28 x86-64 when compiled with gcc -m32.  */
648 enum { LISP_ALIGNMENT = alignof (union { max_align_t x;
649 					 GCALIGNED_UNION_MEMBER }) };
650 verify (LISP_ALIGNMENT % GCALIGNMENT == 0);
651 
652 /* True if malloc (N) is known to return storage suitably aligned for
653    Lisp objects whenever N is a multiple of LISP_ALIGNMENT.  In
654    practice this is true whenever alignof (max_align_t) is also a
655    multiple of LISP_ALIGNMENT.  This works even for x86, where some
656    platform combinations (e.g., GCC 7 and later, glibc 2.25 and
657    earlier) have bugs where alignof (max_align_t) is 16 even though
658    the malloc alignment is only 8, and where Emacs still works because
659    it never does anything that requires an alignment of 16.  */
660 enum { MALLOC_IS_LISP_ALIGNED = alignof (max_align_t) % LISP_ALIGNMENT == 0 };
661 
662 /* If compiled with XMALLOC_BLOCK_INPUT_CHECK, define a symbol
663    BLOCK_INPUT_IN_MEMORY_ALLOCATORS that is visible to the debugger.
664    If that variable is set, block input while in one of Emacs's memory
665    allocation functions.  There should be no need for this debugging
666    option, since signal handlers do not allocate memory, but Emacs
667    formerly allocated memory in signal handlers and this compile-time
668    option remains as a way to help debug the issue should it rear its
669    ugly head again.  */
670 #ifdef XMALLOC_BLOCK_INPUT_CHECK
671 bool block_input_in_memory_allocators EXTERNALLY_VISIBLE;
672 static void
malloc_block_input(void)673 malloc_block_input (void)
674 {
675   if (block_input_in_memory_allocators)
676     block_input ();
677 }
678 static void
malloc_unblock_input(void)679 malloc_unblock_input (void)
680 {
681   if (block_input_in_memory_allocators)
682     unblock_input ();
683 }
684 # define MALLOC_BLOCK_INPUT malloc_block_input ()
685 # define MALLOC_UNBLOCK_INPUT malloc_unblock_input ()
686 #else
687 # define MALLOC_BLOCK_INPUT ((void) 0)
688 # define MALLOC_UNBLOCK_INPUT ((void) 0)
689 #endif
690 
691 #define MALLOC_PROBE(size)			\
692   do {						\
693     if (profiler_memory_running)		\
694       malloc_probe (size);			\
695   } while (0)
696 
697 static void *lmalloc (size_t) ATTRIBUTE_MALLOC_SIZE ((1));
698 static void *lrealloc (void *, size_t);
699 
700 /* Like malloc but check for no memory and block interrupt input.  */
701 
702 void *
xmalloc(size_t size)703 xmalloc (size_t size)
704 {
705   void *val;
706 
707   MALLOC_BLOCK_INPUT;
708   val = lmalloc (size);
709   MALLOC_UNBLOCK_INPUT;
710 
711   if (!val && size)
712     memory_full (size);
713   MALLOC_PROBE (size);
714   return val;
715 }
716 
717 /* Like the above, but zeroes out the memory just allocated.  */
718 
719 void *
xzalloc(size_t size)720 xzalloc (size_t size)
721 {
722   void *val;
723 
724   MALLOC_BLOCK_INPUT;
725   val = lmalloc (size);
726   MALLOC_UNBLOCK_INPUT;
727 
728   if (!val && size)
729     memory_full (size);
730   memset (val, 0, size);
731   MALLOC_PROBE (size);
732   return val;
733 }
734 
735 /* Like realloc but check for no memory and block interrupt input.  */
736 
737 void *
xrealloc(void * block,size_t size)738 xrealloc (void *block, size_t size)
739 {
740   void *val;
741 
742   MALLOC_BLOCK_INPUT;
743   /* We must call malloc explicitly when BLOCK is 0, since some
744      reallocs don't do this.  */
745   if (! block)
746     val = lmalloc (size);
747   else
748     val = lrealloc (block, size);
749   MALLOC_UNBLOCK_INPUT;
750 
751   if (!val && size)
752     memory_full (size);
753   MALLOC_PROBE (size);
754   return val;
755 }
756 
757 
758 /* Like free but block interrupt input.  */
759 
760 void
xfree(void * block)761 xfree (void *block)
762 {
763   if (!block)
764     return;
765   if (pdumper_object_p (block))
766     return;
767   MALLOC_BLOCK_INPUT;
768   free (block);
769   MALLOC_UNBLOCK_INPUT;
770   /* We don't call refill_memory_reserve here
771      because in practice the call in r_alloc_free seems to suffice.  */
772 }
773 
774 
775 /* Other parts of Emacs pass large int values to allocator functions
776    expecting ptrdiff_t.  This is portable in practice, but check it to
777    be safe.  */
778 verify (INT_MAX <= PTRDIFF_MAX);
779 
780 
781 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
782    Signal an error on memory exhaustion, and block interrupt input.  */
783 
784 void *
xnmalloc(ptrdiff_t nitems,ptrdiff_t item_size)785 xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
786 {
787   eassert (0 <= nitems && 0 < item_size);
788   ptrdiff_t nbytes;
789   if (INT_MULTIPLY_WRAPV (nitems, item_size, &nbytes) || SIZE_MAX < nbytes)
790     memory_full (SIZE_MAX);
791   return xmalloc (nbytes);
792 }
793 
794 
795 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
796    Signal an error on memory exhaustion, and block interrupt input.  */
797 
798 void *
xnrealloc(void * pa,ptrdiff_t nitems,ptrdiff_t item_size)799 xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
800 {
801   eassert (0 <= nitems && 0 < item_size);
802   ptrdiff_t nbytes;
803   if (INT_MULTIPLY_WRAPV (nitems, item_size, &nbytes) || SIZE_MAX < nbytes)
804     memory_full (SIZE_MAX);
805   return xrealloc (pa, nbytes);
806 }
807 
808 
809 /* Grow PA, which points to an array of *NITEMS items, and return the
810    location of the reallocated array, updating *NITEMS to reflect its
811    new size.  The new array will contain at least NITEMS_INCR_MIN more
812    items, but will not contain more than NITEMS_MAX items total.
813    ITEM_SIZE is the size of each item, in bytes.
814 
815    ITEM_SIZE and NITEMS_INCR_MIN must be positive.  *NITEMS must be
816    nonnegative.  If NITEMS_MAX is -1, it is treated as if it were
817    infinity.
818 
819    If PA is null, then allocate a new array instead of reallocating
820    the old one.
821 
822    Block interrupt input as needed.  If memory exhaustion occurs, set
823    *NITEMS to zero if PA is null, and signal an error (i.e., do not
824    return).
825 
826    Thus, to grow an array A without saving its old contents, do
827    { xfree (A); A = NULL; A = xpalloc (NULL, &AITEMS, ...); }.
828    The A = NULL avoids a dangling pointer if xpalloc exhausts memory
829    and signals an error, and later this code is reexecuted and
830    attempts to free A.  */
831 
832 void *
xpalloc(void * pa,ptrdiff_t * nitems,ptrdiff_t nitems_incr_min,ptrdiff_t nitems_max,ptrdiff_t item_size)833 xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
834 	 ptrdiff_t nitems_max, ptrdiff_t item_size)
835 {
836   ptrdiff_t n0 = *nitems;
837   eassume (0 < item_size && 0 < nitems_incr_min && 0 <= n0 && -1 <= nitems_max);
838 
839   /* The approximate size to use for initial small allocation
840      requests.  This is the largest "small" request for the GNU C
841      library malloc.  */
842   enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
843 
844   /* If the array is tiny, grow it to about (but no greater than)
845      DEFAULT_MXFAST bytes.  Otherwise, grow it by about 50%.
846      Adjust the growth according to three constraints: NITEMS_INCR_MIN,
847      NITEMS_MAX, and what the C language can represent safely.  */
848 
849   ptrdiff_t n, nbytes;
850   if (INT_ADD_WRAPV (n0, n0 >> 1, &n))
851     n = PTRDIFF_MAX;
852   if (0 <= nitems_max && nitems_max < n)
853     n = nitems_max;
854 
855   ptrdiff_t adjusted_nbytes
856     = ((INT_MULTIPLY_WRAPV (n, item_size, &nbytes) || SIZE_MAX < nbytes)
857        ? min (PTRDIFF_MAX, SIZE_MAX)
858        : nbytes < DEFAULT_MXFAST ? DEFAULT_MXFAST : 0);
859   if (adjusted_nbytes)
860     {
861       n = adjusted_nbytes / item_size;
862       nbytes = adjusted_nbytes - adjusted_nbytes % item_size;
863     }
864 
865   if (! pa)
866     *nitems = 0;
867   if (n - n0 < nitems_incr_min
868       && (INT_ADD_WRAPV (n0, nitems_incr_min, &n)
869 	  || (0 <= nitems_max && nitems_max < n)
870 	  || INT_MULTIPLY_WRAPV (n, item_size, &nbytes)))
871     memory_full (SIZE_MAX);
872   pa = xrealloc (pa, nbytes);
873   *nitems = n;
874   return pa;
875 }
876 
877 
878 /* Like strdup, but uses xmalloc.  */
879 
880 char *
xstrdup(const char * s)881 xstrdup (const char *s)
882 {
883   ptrdiff_t size;
884   eassert (s);
885   size = strlen (s) + 1;
886   return memcpy (xmalloc (size), s, size);
887 }
888 
889 /* Like above, but duplicates Lisp string to C string.  */
890 
891 char *
xlispstrdup(Lisp_Object string)892 xlispstrdup (Lisp_Object string)
893 {
894   ptrdiff_t size = SBYTES (string) + 1;
895   return memcpy (xmalloc (size), SSDATA (string), size);
896 }
897 
898 /* Assign to *PTR a copy of STRING, freeing any storage *PTR formerly
899    pointed to.  If STRING is null, assign it without copying anything.
900    Allocate before freeing, to avoid a dangling pointer if allocation
901    fails.  */
902 
903 void
dupstring(char ** ptr,char const * string)904 dupstring (char **ptr, char const *string)
905 {
906   char *old = *ptr;
907   *ptr = string ? xstrdup (string) : 0;
908   xfree (old);
909 }
910 
911 
912 /* Like putenv, but (1) use the equivalent of xmalloc and (2) the
913    argument is a const pointer.  */
914 
915 void
xputenv(char const * string)916 xputenv (char const *string)
917 {
918   if (putenv ((char *) string) != 0)
919     memory_full (0);
920 }
921 
922 /* Return a newly allocated memory block of SIZE bytes, remembering
923    to free it when unwinding.  */
924 void *
record_xmalloc(size_t size)925 record_xmalloc (size_t size)
926 {
927   void *p = xmalloc (size);
928   record_unwind_protect_ptr (xfree, p);
929   return p;
930 }
931 
932 
933 /* Like malloc but used for allocating Lisp data.  NBYTES is the
934    number of bytes to allocate, TYPE describes the intended use of the
935    allocated memory block (for strings, for conses, ...).  */
936 
937 #if ! USE_LSB_TAG
938 void *lisp_malloc_loser EXTERNALLY_VISIBLE;
939 #endif
940 
941 static void *
lisp_malloc(size_t nbytes,enum mem_type type)942 lisp_malloc (size_t nbytes, enum mem_type type)
943 {
944   register void *val;
945 
946   MALLOC_BLOCK_INPUT;
947 
948 #ifdef GC_MALLOC_CHECK
949   allocated_mem_type = type;
950 #endif
951 
952   val = lmalloc (nbytes);
953 
954 #if ! USE_LSB_TAG
955   /* If the memory just allocated cannot be addressed thru a Lisp
956      object's pointer, and it needs to be,
957      that's equivalent to running out of memory.  */
958   if (val && type != MEM_TYPE_NON_LISP)
959     {
960       Lisp_Object tem;
961       XSETCONS (tem, (char *) val + nbytes - 1);
962       if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
963 	{
964 	  lisp_malloc_loser = val;
965 	  free (val);
966 	  val = 0;
967 	}
968     }
969 #endif
970 
971 #ifndef GC_MALLOC_CHECK
972   if (val && type != MEM_TYPE_NON_LISP)
973     mem_insert (val, (char *) val + nbytes, type);
974 #endif
975 
976   MALLOC_UNBLOCK_INPUT;
977   if (!val && nbytes)
978     memory_full (nbytes);
979   MALLOC_PROBE (nbytes);
980   return val;
981 }
982 
983 /* Free BLOCK.  This must be called to free memory allocated with a
984    call to lisp_malloc.  */
985 
986 static void
lisp_free(void * block)987 lisp_free (void *block)
988 {
989   if (pdumper_object_p (block))
990     return;
991 
992   MALLOC_BLOCK_INPUT;
993   free (block);
994 #ifndef GC_MALLOC_CHECK
995   mem_delete (mem_find (block));
996 #endif
997   MALLOC_UNBLOCK_INPUT;
998 }
999 
1000 /*****  Allocation of aligned blocks of memory to store Lisp data.  *****/
1001 
1002 /* The entry point is lisp_align_malloc which returns blocks of at most
1003    BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary.  */
1004 
1005 /* Byte alignment of storage blocks.  */
1006 #define BLOCK_ALIGN (1 << 10)
1007 verify (POWER_OF_2 (BLOCK_ALIGN));
1008 
1009 /* Use aligned_alloc if it or a simple substitute is available.
1010    Aligned allocation is incompatible with unexmacosx.c, so don't use
1011    it on Darwin if HAVE_UNEXEC.  */
1012 
1013 #if ! (defined DARWIN_OS && defined HAVE_UNEXEC)
1014 # if (defined HAVE_ALIGNED_ALLOC					\
1015       || (defined HYBRID_MALLOC						\
1016 	  ? defined HAVE_POSIX_MEMALIGN					\
1017 	  : !defined SYSTEM_MALLOC && !defined DOUG_LEA_MALLOC))
1018 #  define USE_ALIGNED_ALLOC 1
1019 # elif !defined HYBRID_MALLOC && defined HAVE_POSIX_MEMALIGN
1020 #  define USE_ALIGNED_ALLOC 1
1021 #  define aligned_alloc my_aligned_alloc /* Avoid collision with lisp.h.  */
1022 static void *
aligned_alloc(size_t alignment,size_t size)1023 aligned_alloc (size_t alignment, size_t size)
1024 {
1025   /* POSIX says the alignment must be a power-of-2 multiple of sizeof (void *).
1026      Verify this for all arguments this function is given.  */
1027   verify (BLOCK_ALIGN % sizeof (void *) == 0
1028 	  && POWER_OF_2 (BLOCK_ALIGN / sizeof (void *)));
1029   verify (MALLOC_IS_LISP_ALIGNED
1030 	  || (LISP_ALIGNMENT % sizeof (void *) == 0
1031 	      && POWER_OF_2 (LISP_ALIGNMENT / sizeof (void *))));
1032   eassert (alignment == BLOCK_ALIGN
1033 	   || (!MALLOC_IS_LISP_ALIGNED && alignment == LISP_ALIGNMENT));
1034 
1035   void *p;
1036   return posix_memalign (&p, alignment, size) == 0 ? p : 0;
1037 }
1038 # endif
1039 #endif
1040 
1041 /* Padding to leave at the end of a malloc'd block.  This is to give
1042    malloc a chance to minimize the amount of memory wasted to alignment.
1043    It should be tuned to the particular malloc library used.
1044    On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
1045    aligned_alloc on the other hand would ideally prefer a value of 4
1046    because otherwise, there's 1020 bytes wasted between each ablocks.
1047    In Emacs, testing shows that those 1020 can most of the time be
1048    efficiently used by malloc to place other objects, so a value of 0 can
1049    still preferable unless you have a lot of aligned blocks and virtually
1050    nothing else.  */
1051 #define BLOCK_PADDING 0
1052 #define BLOCK_BYTES \
1053   (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
1054 
1055 /* Internal data structures and constants.  */
1056 
1057 #define ABLOCKS_SIZE 16
1058 
1059 /* An aligned block of memory.  */
1060 struct ablock
1061 {
1062   union
1063   {
1064     char payload[BLOCK_BYTES];
1065     struct ablock *next_free;
1066   } x;
1067 
1068   /* ABASE is the aligned base of the ablocks.  It is overloaded to
1069      hold a virtual "busy" field that counts twice the number of used
1070      ablock values in the parent ablocks, plus one if the real base of
1071      the parent ablocks is ABASE (if the "busy" field is even, the
1072      word before the first ablock holds a pointer to the real base).
1073      The first ablock has a "busy" ABASE, and the others have an
1074      ordinary pointer ABASE.  To tell the difference, the code assumes
1075      that pointers, when cast to uintptr_t, are at least 2 *
1076      ABLOCKS_SIZE + 1.  */
1077   struct ablocks *abase;
1078 
1079   /* The padding of all but the last ablock is unused.  The padding of
1080      the last ablock in an ablocks is not allocated.  */
1081 #if BLOCK_PADDING
1082   char padding[BLOCK_PADDING];
1083 #endif
1084 };
1085 
1086 /* A bunch of consecutive aligned blocks.  */
1087 struct ablocks
1088 {
1089   struct ablock blocks[ABLOCKS_SIZE];
1090 };
1091 
1092 /* Size of the block requested from malloc or aligned_alloc.  */
1093 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
1094 
1095 #define ABLOCK_ABASE(block) \
1096   (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE)	\
1097    ? (struct ablocks *) (block)					\
1098    : (block)->abase)
1099 
1100 /* Virtual `busy' field.  */
1101 #define ABLOCKS_BUSY(a_base) ((a_base)->blocks[0].abase)
1102 
1103 /* Pointer to the (not necessarily aligned) malloc block.  */
1104 #ifdef USE_ALIGNED_ALLOC
1105 #define ABLOCKS_BASE(abase) (abase)
1106 #else
1107 #define ABLOCKS_BASE(abase) \
1108   (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void **) (abase))[-1])
1109 #endif
1110 
1111 /* The list of free ablock.   */
1112 static struct ablock *free_ablock;
1113 
1114 /* Allocate an aligned block of nbytes.
1115    Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
1116    smaller or equal to BLOCK_BYTES.  */
1117 static void *
lisp_align_malloc(size_t nbytes,enum mem_type type)1118 lisp_align_malloc (size_t nbytes, enum mem_type type)
1119 {
1120   void *base, *val;
1121   struct ablocks *abase;
1122 
1123   eassert (nbytes <= BLOCK_BYTES);
1124 
1125   MALLOC_BLOCK_INPUT;
1126 
1127 #ifdef GC_MALLOC_CHECK
1128   allocated_mem_type = type;
1129 #endif
1130 
1131   if (!free_ablock)
1132     {
1133       int i;
1134       bool aligned;
1135 
1136 #ifdef DOUG_LEA_MALLOC
1137       if (!mmap_lisp_allowed_p ())
1138         mallopt (M_MMAP_MAX, 0);
1139 #endif
1140 
1141 #ifdef USE_ALIGNED_ALLOC
1142       verify (ABLOCKS_BYTES % BLOCK_ALIGN == 0);
1143       abase = base = aligned_alloc (BLOCK_ALIGN, ABLOCKS_BYTES);
1144 #else
1145       base = malloc (ABLOCKS_BYTES);
1146       abase = pointer_align (base, BLOCK_ALIGN);
1147 #endif
1148 
1149       if (base == 0)
1150 	{
1151 	  MALLOC_UNBLOCK_INPUT;
1152 	  memory_full (ABLOCKS_BYTES);
1153 	}
1154 
1155       aligned = (base == abase);
1156       if (!aligned)
1157 	((void **) abase)[-1] = base;
1158 
1159 #ifdef DOUG_LEA_MALLOC
1160       if (!mmap_lisp_allowed_p ())
1161           mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1162 #endif
1163 
1164 #if ! USE_LSB_TAG
1165       /* If the memory just allocated cannot be addressed thru a Lisp
1166 	 object's pointer, and it needs to be, that's equivalent to
1167 	 running out of memory.  */
1168       if (type != MEM_TYPE_NON_LISP)
1169 	{
1170 	  Lisp_Object tem;
1171 	  char *end = (char *) base + ABLOCKS_BYTES - 1;
1172 	  XSETCONS (tem, end);
1173 	  if ((char *) XCONS (tem) != end)
1174 	    {
1175 	      lisp_malloc_loser = base;
1176 	      free (base);
1177 	      MALLOC_UNBLOCK_INPUT;
1178 	      memory_full (SIZE_MAX);
1179 	    }
1180 	}
1181 #endif
1182 
1183       /* Initialize the blocks and put them on the free list.
1184 	 If `base' was not properly aligned, we can't use the last block.  */
1185       for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1186 	{
1187 	  abase->blocks[i].abase = abase;
1188 	  abase->blocks[i].x.next_free = free_ablock;
1189 	  free_ablock = &abase->blocks[i];
1190 	}
1191       intptr_t ialigned = aligned;
1192       ABLOCKS_BUSY (abase) = (struct ablocks *) ialigned;
1193 
1194       eassert ((uintptr_t) abase % BLOCK_ALIGN == 0);
1195       eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1196       eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1197       eassert (ABLOCKS_BASE (abase) == base);
1198       eassert ((intptr_t) ABLOCKS_BUSY (abase) == aligned);
1199     }
1200 
1201   abase = ABLOCK_ABASE (free_ablock);
1202   ABLOCKS_BUSY (abase)
1203     = (struct ablocks *) (2 + (intptr_t) ABLOCKS_BUSY (abase));
1204   val = free_ablock;
1205   free_ablock = free_ablock->x.next_free;
1206 
1207 #ifndef GC_MALLOC_CHECK
1208   if (type != MEM_TYPE_NON_LISP)
1209     mem_insert (val, (char *) val + nbytes, type);
1210 #endif
1211 
1212   MALLOC_UNBLOCK_INPUT;
1213 
1214   MALLOC_PROBE (nbytes);
1215 
1216   eassert (0 == ((uintptr_t) val) % BLOCK_ALIGN);
1217   return val;
1218 }
1219 
1220 static void
lisp_align_free(void * block)1221 lisp_align_free (void *block)
1222 {
1223   struct ablock *ablock = block;
1224   struct ablocks *abase = ABLOCK_ABASE (ablock);
1225 
1226   MALLOC_BLOCK_INPUT;
1227 #ifndef GC_MALLOC_CHECK
1228   mem_delete (mem_find (block));
1229 #endif
1230   /* Put on free list.  */
1231   ablock->x.next_free = free_ablock;
1232   free_ablock = ablock;
1233   /* Update busy count.  */
1234   intptr_t busy = (intptr_t) ABLOCKS_BUSY (abase) - 2;
1235   eassume (0 <= busy && busy <= 2 * ABLOCKS_SIZE - 1);
1236   ABLOCKS_BUSY (abase) = (struct ablocks *) busy;
1237 
1238   if (busy < 2)
1239     { /* All the blocks are free.  */
1240       int i = 0;
1241       bool aligned = busy;
1242       struct ablock **tem = &free_ablock;
1243       struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1244 
1245       while (*tem)
1246 	{
1247 	  if (*tem >= (struct ablock *) abase && *tem < atop)
1248 	    {
1249 	      i++;
1250 	      *tem = (*tem)->x.next_free;
1251 	    }
1252 	  else
1253 	    tem = &(*tem)->x.next_free;
1254 	}
1255       eassert ((aligned & 1) == aligned);
1256       eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1257 #ifdef USE_POSIX_MEMALIGN
1258       eassert ((uintptr_t) ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1259 #endif
1260       free (ABLOCKS_BASE (abase));
1261     }
1262   MALLOC_UNBLOCK_INPUT;
1263 }
1264 
1265 /* True if a malloc-returned pointer P is suitably aligned for SIZE,
1266    where Lisp object alignment may be needed if SIZE is a multiple of
1267    LISP_ALIGNMENT.  */
1268 
1269 static bool
laligned(void * p,size_t size)1270 laligned (void *p, size_t size)
1271 {
1272   return (MALLOC_IS_LISP_ALIGNED || (intptr_t) p % LISP_ALIGNMENT == 0
1273 	  || size % LISP_ALIGNMENT != 0);
1274 }
1275 
1276 /* Like malloc and realloc except that if SIZE is Lisp-aligned, make
1277    sure the result is too, if necessary by reallocating (typically
1278    with larger and larger sizes) until the allocator returns a
1279    Lisp-aligned pointer.  Code that needs to allocate C heap memory
1280    for a Lisp object should use one of these functions to obtain a
1281    pointer P; that way, if T is an enum Lisp_Type value and L ==
1282    make_lisp_ptr (P, T), then XPNTR (L) == P and XTYPE (L) == T.
1283 
1284    On typical modern platforms these functions' loops do not iterate.
1285    On now-rare (and perhaps nonexistent) platforms, the loops in
1286    theory could repeat forever.  If an infinite loop is possible on a
1287    platform, a build would surely loop and the builder can then send
1288    us a bug report.  Adding a counter to try to detect any such loop
1289    would complicate the code (and possibly introduce bugs, in code
1290    that's never really exercised) for little benefit.  */
1291 
1292 static void *
lmalloc(size_t size)1293 lmalloc (size_t size)
1294 {
1295 #ifdef USE_ALIGNED_ALLOC
1296   if (! MALLOC_IS_LISP_ALIGNED && size % LISP_ALIGNMENT == 0)
1297     return aligned_alloc (LISP_ALIGNMENT, size);
1298 #endif
1299 
1300   while (true)
1301     {
1302       void *p = malloc (size);
1303       if (laligned (p, size))
1304 	return p;
1305       free (p);
1306       size_t bigger = size + LISP_ALIGNMENT;
1307       if (size < bigger)
1308 	size = bigger;
1309     }
1310 }
1311 
1312 static void *
lrealloc(void * p,size_t size)1313 lrealloc (void *p, size_t size)
1314 {
1315   while (true)
1316     {
1317       p = realloc (p, size);
1318       if (laligned (p, size))
1319 	return p;
1320       size_t bigger = size + LISP_ALIGNMENT;
1321       if (size < bigger)
1322 	size = bigger;
1323     }
1324 }
1325 
1326 
1327 /***********************************************************************
1328 			 Interval Allocation
1329  ***********************************************************************/
1330 
1331 /* Number of intervals allocated in an interval_block structure.
1332    The 1020 is 1024 minus malloc overhead.  */
1333 
1334 #define INTERVAL_BLOCK_SIZE \
1335   ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1336 
1337 /* Intervals are allocated in chunks in the form of an interval_block
1338    structure.  */
1339 
1340 struct interval_block
1341 {
1342   /* Place `intervals' first, to preserve alignment.  */
1343   struct interval intervals[INTERVAL_BLOCK_SIZE];
1344   struct interval_block *next;
1345 };
1346 
1347 /* Current interval block.  Its `next' pointer points to older
1348    blocks.  */
1349 
1350 static struct interval_block *interval_block;
1351 
1352 /* Index in interval_block above of the next unused interval
1353    structure.  */
1354 
1355 static int interval_block_index = INTERVAL_BLOCK_SIZE;
1356 
1357 /* List of free intervals.  */
1358 
1359 static INTERVAL interval_free_list;
1360 
1361 /* Return a new interval.  */
1362 
1363 INTERVAL
make_interval(void)1364 make_interval (void)
1365 {
1366   INTERVAL val;
1367 
1368   MALLOC_BLOCK_INPUT;
1369 
1370   if (interval_free_list)
1371     {
1372       val = interval_free_list;
1373       interval_free_list = INTERVAL_PARENT (interval_free_list);
1374     }
1375   else
1376     {
1377       if (interval_block_index == INTERVAL_BLOCK_SIZE)
1378 	{
1379 	  struct interval_block *newi
1380 	    = lisp_malloc (sizeof *newi, MEM_TYPE_NON_LISP);
1381 
1382 	  newi->next = interval_block;
1383 	  interval_block = newi;
1384 	  interval_block_index = 0;
1385 	}
1386       val = &interval_block->intervals[interval_block_index++];
1387     }
1388 
1389   MALLOC_UNBLOCK_INPUT;
1390 
1391   tally_consing (sizeof (struct interval));
1392   intervals_consed++;
1393   RESET_INTERVAL (val);
1394   val->gcmarkbit = 0;
1395   return val;
1396 }
1397 
1398 
1399 /* Mark Lisp objects in interval I.  */
1400 
1401 static void
mark_interval_tree_1(INTERVAL i,void * dummy)1402 mark_interval_tree_1 (INTERVAL i, void *dummy)
1403 {
1404   /* Intervals should never be shared.  So, if extra internal checking is
1405      enabled, GC aborts if it seems to have visited an interval twice.  */
1406   eassert (!interval_marked_p (i));
1407   set_interval_marked (i);
1408   mark_object (i->plist);
1409 }
1410 
1411 /* Mark the interval tree rooted in I.  */
1412 
1413 static void
mark_interval_tree(INTERVAL i)1414 mark_interval_tree (INTERVAL i)
1415 {
1416   if (i && !interval_marked_p (i))
1417     traverse_intervals_noorder (i, mark_interval_tree_1, NULL);
1418 }
1419 
1420 /***********************************************************************
1421 			  String Allocation
1422  ***********************************************************************/
1423 
1424 /* Lisp_Strings are allocated in string_block structures.  When a new
1425    string_block is allocated, all the Lisp_Strings it contains are
1426    added to a free-list string_free_list.  When a new Lisp_String is
1427    needed, it is taken from that list.  During the sweep phase of GC,
1428    string_blocks that are entirely free are freed, except two which
1429    we keep.
1430 
1431    String data is allocated from sblock structures.  Strings larger
1432    than LARGE_STRING_BYTES, get their own sblock, data for smaller
1433    strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1434 
1435    Sblocks consist internally of sdata structures, one for each
1436    Lisp_String.  The sdata structure points to the Lisp_String it
1437    belongs to.  The Lisp_String points back to the `u.data' member of
1438    its sdata structure.
1439 
1440    When a Lisp_String is freed during GC, it is put back on
1441    string_free_list, and its `data' member and its sdata's `string'
1442    pointer is set to null.  The size of the string is recorded in the
1443    `n.nbytes' member of the sdata.  So, sdata structures that are no
1444    longer used, can be easily recognized, and it's easy to compact the
1445    sblocks of small strings which we do in compact_small_strings.  */
1446 
1447 /* Size in bytes of an sblock structure used for small strings.  This
1448    is 8192 minus malloc overhead.  */
1449 
1450 #define SBLOCK_SIZE 8188
1451 
1452 /* Strings larger than this are considered large strings.  String data
1453    for large strings is allocated from individual sblocks.  */
1454 
1455 #define LARGE_STRING_BYTES 1024
1456 
1457 /* The layout of a nonnull string.  */
1458 
1459 struct sdata
1460 {
1461   /* Back-pointer to the string this sdata belongs to.  If null, this
1462      structure is free, and NBYTES (in this structure or in the union below)
1463      contains the string's byte size (the same value that STRING_BYTES
1464      would return if STRING were non-null).  If non-null, STRING_BYTES
1465      (STRING) is the size of the data, and DATA contains the string's
1466      contents.  */
1467   struct Lisp_String *string;
1468 
1469 #ifdef GC_CHECK_STRING_BYTES
1470   ptrdiff_t nbytes;
1471 #endif
1472 
1473   unsigned char data[FLEXIBLE_ARRAY_MEMBER];
1474 };
1475 
1476 /* A union describing string memory sub-allocated from an sblock.
1477    This is where the contents of Lisp strings are stored.  */
1478 
1479 typedef union
1480 {
1481   struct Lisp_String *string;
1482 
1483   /* When STRING is nonnull, this union is actually of type 'struct sdata',
1484      which has a flexible array member.  However, if implemented by
1485      giving this union a member of type 'struct sdata', the union
1486      could not be the last (flexible) member of 'struct sblock',
1487      because C99 prohibits a flexible array member from having a type
1488      that is itself a flexible array.  So, comment this member out here,
1489      but remember that the option's there when using this union.  */
1490 #if 0
1491   struct sdata u;
1492 #endif
1493 
1494   /* When STRING is null.  */
1495   struct
1496   {
1497     struct Lisp_String *string;
1498     ptrdiff_t nbytes;
1499   } n;
1500 } sdata;
1501 
1502 #define SDATA_NBYTES(S)	(S)->n.nbytes
1503 #define SDATA_DATA(S)	((struct sdata *) (S))->data
1504 
1505 enum { SDATA_DATA_OFFSET = offsetof (struct sdata, data) };
1506 
1507 /* Structure describing a block of memory which is sub-allocated to
1508    obtain string data memory for strings.  Blocks for small strings
1509    are of fixed size SBLOCK_SIZE.  Blocks for large strings are made
1510    as large as needed.  */
1511 
1512 struct sblock
1513 {
1514   /* Next in list.  */
1515   struct sblock *next;
1516 
1517   /* Pointer to the next free sdata block.  This points past the end
1518      of the sblock if there isn't any space left in this block.  */
1519   sdata *next_free;
1520 
1521   /* String data.  */
1522   sdata data[FLEXIBLE_ARRAY_MEMBER];
1523 };
1524 
1525 /* Number of Lisp strings in a string_block structure.  The 1020 is
1526    1024 minus malloc overhead.  */
1527 
1528 #define STRING_BLOCK_SIZE \
1529   ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1530 
1531 /* Structure describing a block from which Lisp_String structures
1532    are allocated.  */
1533 
1534 struct string_block
1535 {
1536   /* Place `strings' first, to preserve alignment.  */
1537   struct Lisp_String strings[STRING_BLOCK_SIZE];
1538   struct string_block *next;
1539 };
1540 
1541 /* Head and tail of the list of sblock structures holding Lisp string
1542    data.  We always allocate from current_sblock.  The NEXT pointers
1543    in the sblock structures go from oldest_sblock to current_sblock.  */
1544 
1545 static struct sblock *oldest_sblock, *current_sblock;
1546 
1547 /* List of sblocks for large strings.  */
1548 
1549 static struct sblock *large_sblocks;
1550 
1551 /* List of string_block structures.  */
1552 
1553 static struct string_block *string_blocks;
1554 
1555 /* Free-list of Lisp_Strings.  */
1556 
1557 static struct Lisp_String *string_free_list;
1558 
1559 /* Given a pointer to a Lisp_String S which is on the free-list
1560    string_free_list, return a pointer to its successor in the
1561    free-list.  */
1562 
1563 #define NEXT_FREE_LISP_STRING(S) ((S)->u.next)
1564 
1565 /* Return a pointer to the sdata structure belonging to Lisp string S.
1566    S must be live, i.e. S->data must not be null.  S->data is actually
1567    a pointer to the `u.data' member of its sdata structure; the
1568    structure starts at a constant offset in front of that.  */
1569 
1570 #define SDATA_OF_STRING(S) ((sdata *) ptr_bounds_init ((S)->u.s.data \
1571 						       - SDATA_DATA_OFFSET))
1572 
1573 
1574 #ifdef GC_CHECK_STRING_OVERRUN
1575 
1576 /* Check for overrun in string data blocks by appending a small
1577    "cookie" after each allocated string data block, and check for the
1578    presence of this cookie during GC.  */
1579 # define GC_STRING_OVERRUN_COOKIE_SIZE ROUNDUP (4, alignof (sdata))
1580 static char const string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1581   { '\xde', '\xad', '\xbe', '\xef', /* Perhaps some zeros here.  */ };
1582 
1583 #else
1584 # define GC_STRING_OVERRUN_COOKIE_SIZE 0
1585 #endif
1586 
1587 /* Return the size of an sdata structure large enough to hold N bytes
1588    of string data.  This counts the sdata structure, the N bytes, a
1589    terminating NUL byte, and alignment padding.  */
1590 
1591 static ptrdiff_t
sdata_size(ptrdiff_t n)1592 sdata_size (ptrdiff_t n)
1593 {
1594   /* Reserve space for the nbytes union member even when N + 1 is less
1595      than the size of that member.  */
1596   ptrdiff_t unaligned_size = max (SDATA_DATA_OFFSET + n + 1,
1597 				  sizeof (sdata));
1598   int sdata_align = max (FLEXALIGNOF (struct sdata), alignof (sdata));
1599   return (unaligned_size + sdata_align - 1) & ~(sdata_align - 1);
1600 }
1601 
1602 /* Extra bytes to allocate for each string.  */
1603 #define GC_STRING_EXTRA GC_STRING_OVERRUN_COOKIE_SIZE
1604 
1605 /* Exact bound on the number of bytes in a string, not counting the
1606    terminating NUL.  A string cannot contain more bytes than
1607    STRING_BYTES_BOUND, nor can it be so long that the size_t
1608    arithmetic in allocate_string_data would overflow while it is
1609    calculating a value to be passed to malloc.  */
1610 static ptrdiff_t const STRING_BYTES_MAX =
1611   min (STRING_BYTES_BOUND,
1612        ((SIZE_MAX
1613 	 - GC_STRING_EXTRA
1614 	 - offsetof (struct sblock, data)
1615 	 - SDATA_DATA_OFFSET)
1616 	& ~(sizeof (EMACS_INT) - 1)));
1617 
1618 /* Initialize string allocation.  Called from init_alloc_once.  */
1619 
1620 static void
init_strings(void)1621 init_strings (void)
1622 {
1623   empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1624   staticpro (&empty_unibyte_string);
1625   empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1626   staticpro (&empty_multibyte_string);
1627 }
1628 
1629 
1630 #ifdef GC_CHECK_STRING_BYTES
1631 
1632 static int check_string_bytes_count;
1633 
1634 /* Like STRING_BYTES, but with debugging check.  Can be
1635    called during GC, so pay attention to the mark bit.  */
1636 
1637 ptrdiff_t
string_bytes(struct Lisp_String * s)1638 string_bytes (struct Lisp_String *s)
1639 {
1640   ptrdiff_t nbytes =
1641     (s->u.s.size_byte < 0 ? s->u.s.size & ~ARRAY_MARK_FLAG : s->u.s.size_byte);
1642 
1643   if (!PURE_P (s) && !pdumper_object_p (s) && s->u.s.data
1644       && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1645     emacs_abort ();
1646   return nbytes;
1647 }
1648 
1649 /* Check validity of Lisp strings' string_bytes member in B.  */
1650 
1651 static void
check_sblock(struct sblock * b)1652 check_sblock (struct sblock *b)
1653 {
1654   sdata *end = b->next_free;
1655 
1656   for (sdata *from = b->data; from < end; )
1657     {
1658       ptrdiff_t nbytes = sdata_size (from->string
1659 				     ? string_bytes (from->string)
1660 				     : SDATA_NBYTES (from));
1661       from = (sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1662     }
1663 }
1664 
1665 
1666 /* Check validity of Lisp strings' string_bytes member.  ALL_P
1667    means check all strings, otherwise check only most
1668    recently allocated strings.  Used for hunting a bug.  */
1669 
1670 static void
check_string_bytes(bool all_p)1671 check_string_bytes (bool all_p)
1672 {
1673   if (all_p)
1674     {
1675       struct sblock *b;
1676 
1677       for (b = large_sblocks; b; b = b->next)
1678 	{
1679 	  struct Lisp_String *s = b->data[0].string;
1680 	  if (s)
1681 	    string_bytes (s);
1682 	}
1683 
1684       for (b = oldest_sblock; b; b = b->next)
1685 	check_sblock (b);
1686     }
1687   else if (current_sblock)
1688     check_sblock (current_sblock);
1689 }
1690 
1691 #else /* not GC_CHECK_STRING_BYTES */
1692 
1693 #define check_string_bytes(all) ((void) 0)
1694 
1695 #endif /* GC_CHECK_STRING_BYTES */
1696 
1697 #ifdef GC_CHECK_STRING_FREE_LIST
1698 
1699 /* Walk through the string free list looking for bogus next pointers.
1700    This may catch buffer overrun from a previous string.  */
1701 
1702 static void
check_string_free_list(void)1703 check_string_free_list (void)
1704 {
1705   struct Lisp_String *s;
1706 
1707   /* Pop a Lisp_String off the free-list.  */
1708   s = string_free_list;
1709   while (s != NULL)
1710     {
1711       if ((uintptr_t) s < 1024)
1712 	emacs_abort ();
1713       s = NEXT_FREE_LISP_STRING (s);
1714     }
1715 }
1716 #else
1717 #define check_string_free_list()
1718 #endif
1719 
1720 /* Return a new Lisp_String.  */
1721 
1722 static struct Lisp_String *
allocate_string(void)1723 allocate_string (void)
1724 {
1725   struct Lisp_String *s;
1726 
1727   MALLOC_BLOCK_INPUT;
1728 
1729   /* If the free-list is empty, allocate a new string_block, and
1730      add all the Lisp_Strings in it to the free-list.  */
1731   if (string_free_list == NULL)
1732     {
1733       struct string_block *b = lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1734       int i;
1735 
1736       b->next = string_blocks;
1737       string_blocks = b;
1738 
1739       for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1740 	{
1741 	  s = b->strings + i;
1742 	  /* Every string on a free list should have NULL data pointer.  */
1743 	  s->u.s.data = NULL;
1744 	  NEXT_FREE_LISP_STRING (s) = string_free_list;
1745 	  string_free_list = ptr_bounds_clip (s, sizeof *s);
1746 	}
1747     }
1748 
1749   check_string_free_list ();
1750 
1751   /* Pop a Lisp_String off the free-list.  */
1752   s = string_free_list;
1753   string_free_list = NEXT_FREE_LISP_STRING (s);
1754 
1755   MALLOC_UNBLOCK_INPUT;
1756 
1757   ++strings_consed;
1758   tally_consing (sizeof *s);
1759 
1760 #ifdef GC_CHECK_STRING_BYTES
1761   if (!noninteractive)
1762     {
1763       if (++check_string_bytes_count == 200)
1764 	{
1765 	  check_string_bytes_count = 0;
1766 	  check_string_bytes (1);
1767 	}
1768       else
1769 	check_string_bytes (0);
1770     }
1771 #endif /* GC_CHECK_STRING_BYTES */
1772 
1773   return s;
1774 }
1775 
1776 
1777 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1778    plus a NUL byte at the end.  Allocate an sdata structure DATA for
1779    S, and set S->u.s.data to SDATA->u.data.  Store a NUL byte at the
1780    end of S->u.s.data.  Set S->u.s.size to NCHARS and S->u.s.size_byte
1781    to NBYTES.  Free S->u.s.data if it was initially non-null.  */
1782 
1783 void
allocate_string_data(struct Lisp_String * s,EMACS_INT nchars,EMACS_INT nbytes)1784 allocate_string_data (struct Lisp_String *s,
1785 		      EMACS_INT nchars, EMACS_INT nbytes)
1786 {
1787   sdata *data, *old_data;
1788   struct sblock *b;
1789   ptrdiff_t old_nbytes;
1790 
1791   if (STRING_BYTES_MAX < nbytes)
1792     string_overflow ();
1793 
1794   /* Determine the number of bytes needed to store NBYTES bytes
1795      of string data.  */
1796   ptrdiff_t needed = sdata_size (nbytes);
1797   if (s->u.s.data)
1798     {
1799       old_data = SDATA_OF_STRING (s);
1800       old_nbytes = STRING_BYTES (s);
1801     }
1802   else
1803     old_data = NULL;
1804 
1805   MALLOC_BLOCK_INPUT;
1806 
1807   if (nbytes > LARGE_STRING_BYTES)
1808     {
1809       size_t size = FLEXSIZEOF (struct sblock, data, needed);
1810 
1811 #ifdef DOUG_LEA_MALLOC
1812       if (!mmap_lisp_allowed_p ())
1813         mallopt (M_MMAP_MAX, 0);
1814 #endif
1815 
1816       b = lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
1817 
1818 #ifdef DOUG_LEA_MALLOC
1819       if (!mmap_lisp_allowed_p ())
1820         mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1821 #endif
1822 
1823       data = b->data;
1824       b->next = large_sblocks;
1825       b->next_free = data;
1826       large_sblocks = b;
1827     }
1828   else if (current_sblock == NULL
1829 	   || (((char *) current_sblock + SBLOCK_SIZE
1830 		- (char *) current_sblock->next_free)
1831 	       < (needed + GC_STRING_EXTRA)))
1832     {
1833       /* Not enough room in the current sblock.  */
1834       b = lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1835       data = b->data;
1836       b->next = NULL;
1837       b->next_free = data;
1838 
1839       if (current_sblock)
1840 	current_sblock->next = b;
1841       else
1842 	oldest_sblock = b;
1843       current_sblock = b;
1844     }
1845   else
1846     {
1847       b = current_sblock;
1848       data = b->next_free;
1849     }
1850 
1851   data->string = s;
1852   b->next_free = (sdata *) ((char *) data + needed + GC_STRING_EXTRA);
1853   eassert ((uintptr_t) b->next_free % alignof (sdata) == 0);
1854 
1855   MALLOC_UNBLOCK_INPUT;
1856 
1857   s->u.s.data = ptr_bounds_clip (SDATA_DATA (data), nbytes + 1);
1858 #ifdef GC_CHECK_STRING_BYTES
1859   SDATA_NBYTES (data) = nbytes;
1860 #endif
1861   s->u.s.size = nchars;
1862   s->u.s.size_byte = nbytes;
1863   s->u.s.data[nbytes] = '\0';
1864 #ifdef GC_CHECK_STRING_OVERRUN
1865   memcpy ((char *) data + needed, string_overrun_cookie,
1866 	  GC_STRING_OVERRUN_COOKIE_SIZE);
1867 #endif
1868 
1869   /* Note that Faset may call to this function when S has already data
1870      assigned.  In this case, mark data as free by setting it's string
1871      back-pointer to null, and record the size of the data in it.  */
1872   if (old_data)
1873     {
1874       SDATA_NBYTES (old_data) = old_nbytes;
1875       old_data->string = NULL;
1876     }
1877 
1878   tally_consing (needed);
1879 }
1880 
1881 
1882 /* Sweep and compact strings.  */
1883 
1884 NO_INLINE /* For better stack traces */
1885 static void
sweep_strings(void)1886 sweep_strings (void)
1887 {
1888   struct string_block *b, *next;
1889   struct string_block *live_blocks = NULL;
1890 
1891   string_free_list = NULL;
1892   gcstat.total_strings = gcstat.total_free_strings = 0;
1893   gcstat.total_string_bytes = 0;
1894 
1895   /* Scan strings_blocks, free Lisp_Strings that aren't marked.  */
1896   for (b = string_blocks; b; b = next)
1897     {
1898       int i, nfree = 0;
1899       struct Lisp_String *free_list_before = string_free_list;
1900 
1901       next = b->next;
1902 
1903       for (i = 0; i < STRING_BLOCK_SIZE; ++i)
1904 	{
1905 	  struct Lisp_String *s = b->strings + i;
1906 
1907 	  if (s->u.s.data)
1908 	    {
1909 	      /* String was not on free-list before.  */
1910 	      if (XSTRING_MARKED_P (s))
1911 		{
1912 		  /* String is live; unmark it and its intervals.  */
1913 		  XUNMARK_STRING (s);
1914 
1915 		  /* Do not use string_(set|get)_intervals here.  */
1916 		  s->u.s.intervals = balance_intervals (s->u.s.intervals);
1917 
1918 		  gcstat.total_strings++;
1919 		  gcstat.total_string_bytes += STRING_BYTES (s);
1920 		}
1921 	      else
1922 		{
1923 		  /* String is dead.  Put it on the free-list.  */
1924 		  sdata *data = SDATA_OF_STRING (s);
1925 
1926 		  /* Save the size of S in its sdata so that we know
1927 		     how large that is.  Reset the sdata's string
1928 		     back-pointer so that we know it's free.  */
1929 #ifdef GC_CHECK_STRING_BYTES
1930 		  if (string_bytes (s) != SDATA_NBYTES (data))
1931 		    emacs_abort ();
1932 #else
1933 		  data->n.nbytes = STRING_BYTES (s);
1934 #endif
1935 		  data->string = NULL;
1936 
1937 		  /* Reset the strings's `data' member so that we
1938 		     know it's free.  */
1939 		  s->u.s.data = NULL;
1940 
1941 		  /* Put the string on the free-list.  */
1942 		  NEXT_FREE_LISP_STRING (s) = string_free_list;
1943 		  string_free_list = ptr_bounds_clip (s, sizeof *s);
1944 		  ++nfree;
1945 		}
1946 	    }
1947 	  else
1948 	    {
1949 	      /* S was on the free-list before.  Put it there again.  */
1950 	      NEXT_FREE_LISP_STRING (s) = string_free_list;
1951 	      string_free_list = ptr_bounds_clip (s, sizeof *s);
1952 	      ++nfree;
1953 	    }
1954 	}
1955 
1956       /* Free blocks that contain free Lisp_Strings only, except
1957 	 the first two of them.  */
1958       if (nfree == STRING_BLOCK_SIZE
1959 	  && gcstat.total_free_strings > STRING_BLOCK_SIZE)
1960 	{
1961 	  lisp_free (b);
1962 	  string_free_list = free_list_before;
1963 	}
1964       else
1965 	{
1966 	  gcstat.total_free_strings += nfree;
1967 	  b->next = live_blocks;
1968 	  live_blocks = b;
1969 	}
1970     }
1971 
1972   check_string_free_list ();
1973 
1974   string_blocks = live_blocks;
1975   free_large_strings ();
1976   compact_small_strings ();
1977 
1978   check_string_free_list ();
1979 }
1980 
1981 
1982 /* Free dead large strings.  */
1983 
1984 static void
free_large_strings(void)1985 free_large_strings (void)
1986 {
1987   struct sblock *b, *next;
1988   struct sblock *live_blocks = NULL;
1989 
1990   for (b = large_sblocks; b; b = next)
1991     {
1992       next = b->next;
1993 
1994       if (b->data[0].string == NULL)
1995 	lisp_free (b);
1996       else
1997 	{
1998 	  b->next = live_blocks;
1999 	  live_blocks = b;
2000 	}
2001     }
2002 
2003   large_sblocks = live_blocks;
2004 }
2005 
2006 
2007 /* Compact data of small strings.  Free sblocks that don't contain
2008    data of live strings after compaction.  */
2009 
2010 static void
compact_small_strings(void)2011 compact_small_strings (void)
2012 {
2013   /* TB is the sblock we copy to, TO is the sdata within TB we copy
2014      to, and TB_END is the end of TB.  */
2015   struct sblock *tb = oldest_sblock;
2016   if (tb)
2017     {
2018       sdata *tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
2019       sdata *to = tb->data;
2020 
2021       /* Step through the blocks from the oldest to the youngest.  We
2022 	 expect that old blocks will stabilize over time, so that less
2023 	 copying will happen this way.  */
2024       struct sblock *b = tb;
2025       do
2026 	{
2027 	  sdata *end = b->next_free;
2028 	  eassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2029 
2030 	  for (sdata *from = b->data; from < end; )
2031 	    {
2032 	      /* Compute the next FROM here because copying below may
2033 		 overwrite data we need to compute it.  */
2034 	      ptrdiff_t nbytes;
2035 	      struct Lisp_String *s = from->string;
2036 
2037 #ifdef GC_CHECK_STRING_BYTES
2038 	      /* Check that the string size recorded in the string is the
2039 		 same as the one recorded in the sdata structure.  */
2040 	      if (s && string_bytes (s) != SDATA_NBYTES (from))
2041 		emacs_abort ();
2042 #endif /* GC_CHECK_STRING_BYTES */
2043 
2044 	      nbytes = s ? STRING_BYTES (s) : SDATA_NBYTES (from);
2045 	      eassert (nbytes <= LARGE_STRING_BYTES);
2046 
2047 	      ptrdiff_t size = sdata_size (nbytes);
2048 	      sdata *from_end = (sdata *) ((char *) from
2049 					   + size + GC_STRING_EXTRA);
2050 
2051 #ifdef GC_CHECK_STRING_OVERRUN
2052 	      if (memcmp (string_overrun_cookie,
2053 			  (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
2054 			  GC_STRING_OVERRUN_COOKIE_SIZE))
2055 		emacs_abort ();
2056 #endif
2057 
2058 	      /* Non-NULL S means it's alive.  Copy its data.  */
2059 	      if (s)
2060 		{
2061 		  /* If TB is full, proceed with the next sblock.  */
2062 		  sdata *to_end = (sdata *) ((char *) to
2063 					     + size + GC_STRING_EXTRA);
2064 		  if (to_end > tb_end)
2065 		    {
2066 		      tb->next_free = to;
2067 		      tb = tb->next;
2068 		      tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
2069 		      to = tb->data;
2070 		      to_end = (sdata *) ((char *) to + size + GC_STRING_EXTRA);
2071 		    }
2072 
2073 		  /* Copy, and update the string's `data' pointer.  */
2074 		  if (from != to)
2075 		    {
2076 		      eassert (tb != b || to < from);
2077 		      memmove (to, from, size + GC_STRING_EXTRA);
2078 		      to->string->u.s.data
2079 			= ptr_bounds_clip (SDATA_DATA (to), nbytes + 1);
2080 		    }
2081 
2082 		  /* Advance past the sdata we copied to.  */
2083 		  to = to_end;
2084 		}
2085 	      from = from_end;
2086 	    }
2087 	  b = b->next;
2088 	}
2089       while (b);
2090 
2091       /* The rest of the sblocks following TB don't contain live data, so
2092 	 we can free them.  */
2093       for (b = tb->next; b; )
2094 	{
2095 	  struct sblock *next = b->next;
2096 	  lisp_free (b);
2097 	  b = next;
2098 	}
2099 
2100       tb->next_free = to;
2101       tb->next = NULL;
2102     }
2103 
2104   current_sblock = tb;
2105 }
2106 
2107 void
string_overflow(void)2108 string_overflow (void)
2109 {
2110   error ("Maximum string size exceeded");
2111 }
2112 
2113 DEFUN ("make-string", Fmake_string, Smake_string, 2, 3, 0,
2114        doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2115 LENGTH must be an integer.
2116 INIT must be an integer that represents a character.
2117 If optional argument MULTIBYTE is non-nil, the result will be
2118 a multibyte string even if INIT is an ASCII character.  */)
2119   (Lisp_Object length, Lisp_Object init, Lisp_Object multibyte)
2120 {
2121   register Lisp_Object val;
2122   int c;
2123   EMACS_INT nbytes;
2124 
2125   CHECK_FIXNAT (length);
2126   CHECK_CHARACTER (init);
2127 
2128   c = XFIXNAT (init);
2129   if (ASCII_CHAR_P (c) && NILP (multibyte))
2130     {
2131       nbytes = XFIXNUM (length);
2132       val = make_uninit_string (nbytes);
2133       if (nbytes)
2134 	{
2135 	  memset (SDATA (val), c, nbytes);
2136 	  SDATA (val)[nbytes] = 0;
2137 	}
2138     }
2139   else
2140     {
2141       unsigned char str[MAX_MULTIBYTE_LENGTH];
2142       ptrdiff_t len = CHAR_STRING (c, str);
2143       EMACS_INT string_len = XFIXNUM (length);
2144       unsigned char *p, *beg, *end;
2145 
2146       if (INT_MULTIPLY_WRAPV (len, string_len, &nbytes))
2147 	string_overflow ();
2148       val = make_uninit_multibyte_string (string_len, nbytes);
2149       for (beg = SDATA (val), p = beg, end = beg + nbytes; p < end; p += len)
2150 	{
2151 	  /* First time we just copy `str' to the data of `val'.  */
2152 	  if (p == beg)
2153 	    memcpy (p, str, len);
2154 	  else
2155 	    {
2156 	      /* Next time we copy largest possible chunk from
2157 		 initialized to uninitialized part of `val'.  */
2158 	      len = min (p - beg, end - p);
2159 	      memcpy (p, beg, len);
2160 	    }
2161 	}
2162       if (nbytes)
2163 	*p = 0;
2164     }
2165 
2166   return val;
2167 }
2168 
2169 /* Fill A with 1 bits if INIT is non-nil, and with 0 bits otherwise.
2170    Return A.  */
2171 
2172 Lisp_Object
bool_vector_fill(Lisp_Object a,Lisp_Object init)2173 bool_vector_fill (Lisp_Object a, Lisp_Object init)
2174 {
2175   EMACS_INT nbits = bool_vector_size (a);
2176   if (0 < nbits)
2177     {
2178       unsigned char *data = bool_vector_uchar_data (a);
2179       int pattern = NILP (init) ? 0 : (1 << BOOL_VECTOR_BITS_PER_CHAR) - 1;
2180       ptrdiff_t nbytes = bool_vector_bytes (nbits);
2181       int last_mask = ~ (~0u << ((nbits - 1) % BOOL_VECTOR_BITS_PER_CHAR + 1));
2182       memset (data, pattern, nbytes - 1);
2183       data[nbytes - 1] = pattern & last_mask;
2184     }
2185   return a;
2186 }
2187 
2188 /* Return a newly allocated, uninitialized bool vector of size NBITS.  */
2189 
2190 Lisp_Object
make_uninit_bool_vector(EMACS_INT nbits)2191 make_uninit_bool_vector (EMACS_INT nbits)
2192 {
2193   Lisp_Object val;
2194   EMACS_INT words = bool_vector_words (nbits);
2195   EMACS_INT word_bytes = words * sizeof (bits_word);
2196   EMACS_INT needed_elements = ((bool_header_size - header_size + word_bytes
2197 				+ word_size - 1)
2198 			       / word_size);
2199   if (PTRDIFF_MAX < needed_elements)
2200     memory_full (SIZE_MAX);
2201   struct Lisp_Bool_Vector *p
2202     = (struct Lisp_Bool_Vector *) allocate_vector (needed_elements);
2203   XSETVECTOR (val, p);
2204   XSETPVECTYPESIZE (XVECTOR (val), PVEC_BOOL_VECTOR, 0, 0);
2205   p->size = nbits;
2206 
2207   /* Clear padding at the end.  */
2208   if (words)
2209     p->data[words - 1] = 0;
2210 
2211   return val;
2212 }
2213 
2214 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2215        doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2216 LENGTH must be a number.  INIT matters only in whether it is t or nil.  */)
2217   (Lisp_Object length, Lisp_Object init)
2218 {
2219   Lisp_Object val;
2220 
2221   CHECK_FIXNAT (length);
2222   val = make_uninit_bool_vector (XFIXNAT (length));
2223   return bool_vector_fill (val, init);
2224 }
2225 
2226 DEFUN ("bool-vector", Fbool_vector, Sbool_vector, 0, MANY, 0,
2227        doc: /* Return a new bool-vector with specified arguments as elements.
2228 Allows any number of arguments, including zero.
2229 usage: (bool-vector &rest OBJECTS)  */)
2230   (ptrdiff_t nargs, Lisp_Object *args)
2231 {
2232   ptrdiff_t i;
2233   Lisp_Object vector;
2234 
2235   vector = make_uninit_bool_vector (nargs);
2236   for (i = 0; i < nargs; i++)
2237     bool_vector_set (vector, i, !NILP (args[i]));
2238 
2239   return vector;
2240 }
2241 
2242 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2243    of characters from the contents.  This string may be unibyte or
2244    multibyte, depending on the contents.  */
2245 
2246 Lisp_Object
make_string(const char * contents,ptrdiff_t nbytes)2247 make_string (const char *contents, ptrdiff_t nbytes)
2248 {
2249   register Lisp_Object val;
2250   ptrdiff_t nchars, multibyte_nbytes;
2251 
2252   parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
2253 			  &nchars, &multibyte_nbytes);
2254   if (nbytes == nchars || nbytes != multibyte_nbytes)
2255     /* CONTENTS contains no multibyte sequences or contains an invalid
2256        multibyte sequence.  We must make unibyte string.  */
2257     val = make_unibyte_string (contents, nbytes);
2258   else
2259     val = make_multibyte_string (contents, nchars, nbytes);
2260   return val;
2261 }
2262 
2263 /* Make a unibyte string from LENGTH bytes at CONTENTS.  */
2264 
2265 Lisp_Object
make_unibyte_string(const char * contents,ptrdiff_t length)2266 make_unibyte_string (const char *contents, ptrdiff_t length)
2267 {
2268   register Lisp_Object val;
2269   val = make_uninit_string (length);
2270   memcpy (SDATA (val), contents, length);
2271   return val;
2272 }
2273 
2274 
2275 /* Make a multibyte string from NCHARS characters occupying NBYTES
2276    bytes at CONTENTS.  */
2277 
2278 Lisp_Object
make_multibyte_string(const char * contents,ptrdiff_t nchars,ptrdiff_t nbytes)2279 make_multibyte_string (const char *contents,
2280 		       ptrdiff_t nchars, ptrdiff_t nbytes)
2281 {
2282   register Lisp_Object val;
2283   val = make_uninit_multibyte_string (nchars, nbytes);
2284   memcpy (SDATA (val), contents, nbytes);
2285   return val;
2286 }
2287 
2288 
2289 /* Make a string from NCHARS characters occupying NBYTES bytes at
2290    CONTENTS.  It is a multibyte string if NBYTES != NCHARS.  */
2291 
2292 Lisp_Object
make_string_from_bytes(const char * contents,ptrdiff_t nchars,ptrdiff_t nbytes)2293 make_string_from_bytes (const char *contents,
2294 			ptrdiff_t nchars, ptrdiff_t nbytes)
2295 {
2296   register Lisp_Object val;
2297   val = make_uninit_multibyte_string (nchars, nbytes);
2298   memcpy (SDATA (val), contents, nbytes);
2299   if (SBYTES (val) == SCHARS (val))
2300     STRING_SET_UNIBYTE (val);
2301   return val;
2302 }
2303 
2304 
2305 /* Make a string from NCHARS characters occupying NBYTES bytes at
2306    CONTENTS.  The argument MULTIBYTE controls whether to label the
2307    string as multibyte.  If NCHARS is negative, it counts the number of
2308    characters by itself.  */
2309 
2310 Lisp_Object
make_specified_string(const char * contents,ptrdiff_t nchars,ptrdiff_t nbytes,bool multibyte)2311 make_specified_string (const char *contents,
2312 		       ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
2313 {
2314   Lisp_Object val;
2315 
2316   if (nchars < 0)
2317     {
2318       if (multibyte)
2319 	nchars = multibyte_chars_in_text ((const unsigned char *) contents,
2320 					  nbytes);
2321       else
2322 	nchars = nbytes;
2323     }
2324   val = make_uninit_multibyte_string (nchars, nbytes);
2325   memcpy (SDATA (val), contents, nbytes);
2326   if (!multibyte)
2327     STRING_SET_UNIBYTE (val);
2328   return val;
2329 }
2330 
2331 
2332 /* Return a unibyte Lisp_String set up to hold LENGTH characters
2333    occupying LENGTH bytes.  */
2334 
2335 Lisp_Object
make_uninit_string(EMACS_INT length)2336 make_uninit_string (EMACS_INT length)
2337 {
2338   Lisp_Object val;
2339 
2340   if (!length)
2341     return empty_unibyte_string;
2342   val = make_uninit_multibyte_string (length, length);
2343   STRING_SET_UNIBYTE (val);
2344   return val;
2345 }
2346 
2347 
2348 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2349    which occupy NBYTES bytes.  */
2350 
2351 Lisp_Object
make_uninit_multibyte_string(EMACS_INT nchars,EMACS_INT nbytes)2352 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2353 {
2354   Lisp_Object string;
2355   struct Lisp_String *s;
2356 
2357   if (nchars < 0)
2358     emacs_abort ();
2359   if (!nbytes)
2360     return empty_multibyte_string;
2361 
2362   s = allocate_string ();
2363   s->u.s.intervals = NULL;
2364   allocate_string_data (s, nchars, nbytes);
2365   XSETSTRING (string, s);
2366   string_chars_consed += nbytes;
2367   return string;
2368 }
2369 
2370 /* Print arguments to BUF according to a FORMAT, then return
2371    a Lisp_String initialized with the data from BUF.  */
2372 
2373 Lisp_Object
make_formatted_string(char * buf,const char * format,...)2374 make_formatted_string (char *buf, const char *format, ...)
2375 {
2376   va_list ap;
2377   int length;
2378 
2379   va_start (ap, format);
2380   length = vsprintf (buf, format, ap);
2381   va_end (ap);
2382   return make_string (buf, length);
2383 }
2384 
2385 
2386 /***********************************************************************
2387 			   Float Allocation
2388  ***********************************************************************/
2389 
2390 /* We store float cells inside of float_blocks, allocating a new
2391    float_block with malloc whenever necessary.  Float cells reclaimed
2392    by GC are put on a free list to be reallocated before allocating
2393    any new float cells from the latest float_block.  */
2394 
2395 #define FLOAT_BLOCK_SIZE					\
2396   (((BLOCK_BYTES - sizeof (struct float_block *)		\
2397      /* The compiler might add padding at the end.  */		\
2398      - (sizeof (struct Lisp_Float) - sizeof (bits_word))) * CHAR_BIT) \
2399    / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2400 
2401 #define GETMARKBIT(block,n)				\
2402   (((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD]	\
2403     >> ((n) % BITS_PER_BITS_WORD))			\
2404    & 1)
2405 
2406 #define SETMARKBIT(block,n)				\
2407   ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD]	\
2408    |= (bits_word) 1 << ((n) % BITS_PER_BITS_WORD))
2409 
2410 #define UNSETMARKBIT(block,n)				\
2411   ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD]	\
2412    &= ~((bits_word) 1 << ((n) % BITS_PER_BITS_WORD)))
2413 
2414 #define FLOAT_BLOCK(fptr) \
2415   (eassert (!pdumper_object_p (fptr)),                                  \
2416    ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1))))
2417 
2418 #define FLOAT_INDEX(fptr) \
2419   ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2420 
2421 struct float_block
2422 {
2423   /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job.  */
2424   struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2425   bits_word gcmarkbits[1 + FLOAT_BLOCK_SIZE / BITS_PER_BITS_WORD];
2426   struct float_block *next;
2427 };
2428 
2429 #define XFLOAT_MARKED_P(fptr) \
2430   GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2431 
2432 #define XFLOAT_MARK(fptr) \
2433   SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2434 
2435 #define XFLOAT_UNMARK(fptr) \
2436   UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2437 
2438 /* Current float_block.  */
2439 
2440 static struct float_block *float_block;
2441 
2442 /* Index of first unused Lisp_Float in the current float_block.  */
2443 
2444 static int float_block_index = FLOAT_BLOCK_SIZE;
2445 
2446 /* Free-list of Lisp_Floats.  */
2447 
2448 static struct Lisp_Float *float_free_list;
2449 
2450 /* Return a new float object with value FLOAT_VALUE.  */
2451 
2452 Lisp_Object
make_float(double float_value)2453 make_float (double float_value)
2454 {
2455   register Lisp_Object val;
2456 
2457   MALLOC_BLOCK_INPUT;
2458 
2459   if (float_free_list)
2460     {
2461       XSETFLOAT (val, float_free_list);
2462       float_free_list = float_free_list->u.chain;
2463     }
2464   else
2465     {
2466       if (float_block_index == FLOAT_BLOCK_SIZE)
2467 	{
2468 	  struct float_block *new
2469 	    = lisp_align_malloc (sizeof *new, MEM_TYPE_FLOAT);
2470 	  new->next = float_block;
2471 	  memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2472 	  float_block = new;
2473 	  float_block_index = 0;
2474 	}
2475       XSETFLOAT (val, &float_block->floats[float_block_index]);
2476       float_block_index++;
2477     }
2478 
2479   MALLOC_UNBLOCK_INPUT;
2480 
2481   XFLOAT_INIT (val, float_value);
2482   eassert (!XFLOAT_MARKED_P (XFLOAT (val)));
2483   tally_consing (sizeof (struct Lisp_Float));
2484   floats_consed++;
2485   return val;
2486 }
2487 
2488 
2489 
2490 /***********************************************************************
2491 			   Cons Allocation
2492  ***********************************************************************/
2493 
2494 /* We store cons cells inside of cons_blocks, allocating a new
2495    cons_block with malloc whenever necessary.  Cons cells reclaimed by
2496    GC are put on a free list to be reallocated before allocating
2497    any new cons cells from the latest cons_block.  */
2498 
2499 #define CONS_BLOCK_SIZE						\
2500   (((BLOCK_BYTES - sizeof (struct cons_block *)			\
2501      /* The compiler might add padding at the end.  */		\
2502      - (sizeof (struct Lisp_Cons) - sizeof (bits_word))) * CHAR_BIT)	\
2503    / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2504 
2505 #define CONS_BLOCK(fptr) \
2506   (eassert (!pdumper_object_p (fptr)),                                  \
2507    ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1))))
2508 
2509 #define CONS_INDEX(fptr) \
2510   (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2511 
2512 struct cons_block
2513 {
2514   /* Place `conses' at the beginning, to ease up CONS_INDEX's job.  */
2515   struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2516   bits_word gcmarkbits[1 + CONS_BLOCK_SIZE / BITS_PER_BITS_WORD];
2517   struct cons_block *next;
2518 };
2519 
2520 #define XCONS_MARKED_P(fptr) \
2521   GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2522 
2523 #define XMARK_CONS(fptr) \
2524   SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2525 
2526 #define XUNMARK_CONS(fptr) \
2527   UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2528 
2529 /* Minimum number of bytes of consing since GC before next GC,
2530    when memory is full.  */
2531 
2532 enum { memory_full_cons_threshold = sizeof (struct cons_block) };
2533 
2534 /* Current cons_block.  */
2535 
2536 static struct cons_block *cons_block;
2537 
2538 /* Index of first unused Lisp_Cons in the current block.  */
2539 
2540 static int cons_block_index = CONS_BLOCK_SIZE;
2541 
2542 /* Free-list of Lisp_Cons structures.  */
2543 
2544 static struct Lisp_Cons *cons_free_list;
2545 
2546 /* Explicitly free a cons cell by putting it on the free-list.  */
2547 
2548 void
free_cons(struct Lisp_Cons * ptr)2549 free_cons (struct Lisp_Cons *ptr)
2550 {
2551   ptr->u.s.u.chain = cons_free_list;
2552   ptr->u.s.car = dead_object ();
2553   cons_free_list = ptr;
2554   ptrdiff_t nbytes = sizeof *ptr;
2555   tally_consing (-nbytes);
2556 }
2557 
2558 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2559        doc: /* Create a new cons, give it CAR and CDR as components, and return it.  */)
2560   (Lisp_Object car, Lisp_Object cdr)
2561 {
2562   register Lisp_Object val;
2563 
2564   MALLOC_BLOCK_INPUT;
2565 
2566   if (cons_free_list)
2567     {
2568       XSETCONS (val, cons_free_list);
2569       cons_free_list = cons_free_list->u.s.u.chain;
2570     }
2571   else
2572     {
2573       if (cons_block_index == CONS_BLOCK_SIZE)
2574 	{
2575 	  struct cons_block *new
2576 	    = lisp_align_malloc (sizeof *new, MEM_TYPE_CONS);
2577 	  memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2578 	  new->next = cons_block;
2579 	  cons_block = new;
2580 	  cons_block_index = 0;
2581 	}
2582       XSETCONS (val, &cons_block->conses[cons_block_index]);
2583       cons_block_index++;
2584     }
2585 
2586   MALLOC_UNBLOCK_INPUT;
2587 
2588   XSETCAR (val, car);
2589   XSETCDR (val, cdr);
2590   eassert (!XCONS_MARKED_P (XCONS (val)));
2591   consing_until_gc -= sizeof (struct Lisp_Cons);
2592   cons_cells_consed++;
2593   return val;
2594 }
2595 
2596 /* Make a list of 1, 2, 3, 4 or 5 specified objects.  */
2597 
2598 Lisp_Object
list1(Lisp_Object arg1)2599 list1 (Lisp_Object arg1)
2600 {
2601   return Fcons (arg1, Qnil);
2602 }
2603 
2604 Lisp_Object
list2(Lisp_Object arg1,Lisp_Object arg2)2605 list2 (Lisp_Object arg1, Lisp_Object arg2)
2606 {
2607   return Fcons (arg1, Fcons (arg2, Qnil));
2608 }
2609 
2610 
2611 Lisp_Object
list3(Lisp_Object arg1,Lisp_Object arg2,Lisp_Object arg3)2612 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2613 {
2614   return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2615 }
2616 
2617 Lisp_Object
list4(Lisp_Object arg1,Lisp_Object arg2,Lisp_Object arg3,Lisp_Object arg4)2618 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2619 {
2620   return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2621 }
2622 
2623 Lisp_Object
list5(Lisp_Object arg1,Lisp_Object arg2,Lisp_Object arg3,Lisp_Object arg4,Lisp_Object arg5)2624 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4,
2625        Lisp_Object arg5)
2626 {
2627   return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2628 						       Fcons (arg5, Qnil)))));
2629 }
2630 
2631 /* Make a list of COUNT Lisp_Objects, where ARG is the first one.
2632    Use CONS to construct the pairs.  AP has any remaining args.  */
2633 static Lisp_Object
cons_listn(ptrdiff_t count,Lisp_Object arg,Lisp_Object (* cons)(Lisp_Object,Lisp_Object),va_list ap)2634 cons_listn (ptrdiff_t count, Lisp_Object arg,
2635 	    Lisp_Object (*cons) (Lisp_Object, Lisp_Object), va_list ap)
2636 {
2637   eassume (0 < count);
2638   Lisp_Object val = cons (arg, Qnil);
2639   Lisp_Object tail = val;
2640   for (ptrdiff_t i = 1; i < count; i++)
2641     {
2642       Lisp_Object elem = cons (va_arg (ap, Lisp_Object), Qnil);
2643       XSETCDR (tail, elem);
2644       tail = elem;
2645     }
2646   return val;
2647 }
2648 
2649 /* Make a list of COUNT Lisp_Objects, where ARG1 is the first one.  */
2650 Lisp_Object
listn(ptrdiff_t count,Lisp_Object arg1,...)2651 listn (ptrdiff_t count, Lisp_Object arg1, ...)
2652 {
2653   va_list ap;
2654   va_start (ap, arg1);
2655   Lisp_Object val = cons_listn (count, arg1, Fcons, ap);
2656   va_end (ap);
2657   return val;
2658 }
2659 
2660 /* Make a pure list of COUNT Lisp_Objects, where ARG1 is the first one.  */
2661 Lisp_Object
pure_listn(ptrdiff_t count,Lisp_Object arg1,...)2662 pure_listn (ptrdiff_t count, Lisp_Object arg1, ...)
2663 {
2664   va_list ap;
2665   va_start (ap, arg1);
2666   Lisp_Object val = cons_listn (count, arg1, pure_cons, ap);
2667   va_end (ap);
2668   return val;
2669 }
2670 
2671 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2672        doc: /* Return a newly created list with specified arguments as elements.
2673 Allows any number of arguments, including zero.
2674 usage: (list &rest OBJECTS)  */)
2675   (ptrdiff_t nargs, Lisp_Object *args)
2676 {
2677   register Lisp_Object val;
2678   val = Qnil;
2679 
2680   while (nargs > 0)
2681     {
2682       nargs--;
2683       val = Fcons (args[nargs], val);
2684     }
2685   return val;
2686 }
2687 
2688 
2689 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2690        doc: /* Return a newly created list of length LENGTH, with each element being INIT.  */)
2691   (Lisp_Object length, Lisp_Object init)
2692 {
2693   Lisp_Object val = Qnil;
2694   CHECK_FIXNAT (length);
2695 
2696   for (EMACS_INT size = XFIXNAT (length); 0 < size; size--)
2697     {
2698       val = Fcons (init, val);
2699       rarely_quit (size);
2700     }
2701 
2702   return val;
2703 }
2704 
2705 
2706 
2707 /***********************************************************************
2708 			   Vector Allocation
2709  ***********************************************************************/
2710 
2711 /* Sometimes a vector's contents are merely a pointer internally used
2712    in vector allocation code.  On the rare platforms where a null
2713    pointer cannot be tagged, represent it with a Lisp 0.
2714    Usually you don't want to touch this.  */
2715 
2716 static struct Lisp_Vector *
next_vector(struct Lisp_Vector * v)2717 next_vector (struct Lisp_Vector *v)
2718 {
2719   return XUNTAG (v->contents[0], Lisp_Int0, struct Lisp_Vector);
2720 }
2721 
2722 static void
set_next_vector(struct Lisp_Vector * v,struct Lisp_Vector * p)2723 set_next_vector (struct Lisp_Vector *v, struct Lisp_Vector *p)
2724 {
2725   v->contents[0] = make_lisp_ptr (p, Lisp_Int0);
2726 }
2727 
2728 /* This value is balanced well enough to avoid too much internal overhead
2729    for the most common cases; it's not required to be a power of two, but
2730    it's expected to be a mult-of-ROUNDUP_SIZE (see below).  */
2731 
2732 enum { VECTOR_BLOCK_SIZE = 4096 };
2733 
2734 /* Vector size requests are a multiple of this.  */
2735 enum { roundup_size = COMMON_MULTIPLE (LISP_ALIGNMENT, word_size) };
2736 
2737 /* Verify assumptions described above.  */
2738 verify (VECTOR_BLOCK_SIZE % roundup_size == 0);
2739 verify (VECTOR_BLOCK_SIZE <= (1 << PSEUDOVECTOR_SIZE_BITS));
2740 
2741 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at compile time.  */
2742 #define vroundup_ct(x) ROUNDUP (x, roundup_size)
2743 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at runtime.  */
2744 #define vroundup(x) (eassume ((x) >= 0), vroundup_ct (x))
2745 
2746 /* Rounding helps to maintain alignment constraints if USE_LSB_TAG.  */
2747 
2748 enum {VECTOR_BLOCK_BYTES = VECTOR_BLOCK_SIZE - vroundup_ct (sizeof (void *))};
2749 
2750 /* Size of the minimal vector allocated from block.  */
2751 
2752 enum { VBLOCK_BYTES_MIN = vroundup_ct (header_size + sizeof (Lisp_Object)) };
2753 
2754 /* Size of the largest vector allocated from block.  */
2755 
2756 enum { VBLOCK_BYTES_MAX = vroundup_ct ((VECTOR_BLOCK_BYTES / 2) - word_size) };
2757 
2758 /* We maintain one free list for each possible block-allocated
2759    vector size, and this is the number of free lists we have.  */
2760 
2761 enum { VECTOR_MAX_FREE_LIST_INDEX =
2762        (VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN) / roundup_size + 1 };
2763 
2764 /* Common shortcut to advance vector pointer over a block data.  */
2765 
2766 static struct Lisp_Vector *
ADVANCE(struct Lisp_Vector * v,ptrdiff_t nbytes)2767 ADVANCE (struct Lisp_Vector *v, ptrdiff_t nbytes)
2768 {
2769   void *vv = v;
2770   char *cv = vv;
2771   void *p = cv + nbytes;
2772   return p;
2773 }
2774 
2775 /* Common shortcut to calculate NBYTES-vector index in VECTOR_FREE_LISTS.  */
2776 
2777 static ptrdiff_t
VINDEX(ptrdiff_t nbytes)2778 VINDEX (ptrdiff_t nbytes)
2779 {
2780   eassume (VBLOCK_BYTES_MIN <= nbytes);
2781   return (nbytes - VBLOCK_BYTES_MIN) / roundup_size;
2782 }
2783 
2784 /* This internal type is used to maintain the list of large vectors
2785    which are allocated at their own, e.g. outside of vector blocks.
2786 
2787    struct large_vector itself cannot contain a struct Lisp_Vector, as
2788    the latter contains a flexible array member and C99 does not allow
2789    such structs to be nested.  Instead, each struct large_vector
2790    object LV is followed by a struct Lisp_Vector, which is at offset
2791    large_vector_offset from LV, and whose address is therefore
2792    large_vector_vec (&LV).  */
2793 
2794 struct large_vector
2795 {
2796   struct large_vector *next;
2797 };
2798 
2799 enum
2800 {
2801   large_vector_offset = ROUNDUP (sizeof (struct large_vector), LISP_ALIGNMENT)
2802 };
2803 
2804 static struct Lisp_Vector *
large_vector_vec(struct large_vector * p)2805 large_vector_vec (struct large_vector *p)
2806 {
2807   return (struct Lisp_Vector *) ((char *) p + large_vector_offset);
2808 }
2809 
2810 /* This internal type is used to maintain an underlying storage
2811    for small vectors.  */
2812 
2813 struct vector_block
2814 {
2815   char data[VECTOR_BLOCK_BYTES];
2816   struct vector_block *next;
2817 };
2818 
2819 /* Chain of vector blocks.  */
2820 
2821 static struct vector_block *vector_blocks;
2822 
2823 /* Vector free lists, where NTH item points to a chain of free
2824    vectors of the same NBYTES size, so NTH == VINDEX (NBYTES).  */
2825 
2826 static struct Lisp_Vector *vector_free_lists[VECTOR_MAX_FREE_LIST_INDEX];
2827 
2828 /* Singly-linked list of large vectors.  */
2829 
2830 static struct large_vector *large_vectors;
2831 
2832 /* The only vector with 0 slots, allocated from pure space.  */
2833 
2834 Lisp_Object zero_vector;
2835 
2836 /* Common shortcut to setup vector on a free list.  */
2837 
2838 static void
setup_on_free_list(struct Lisp_Vector * v,ptrdiff_t nbytes)2839 setup_on_free_list (struct Lisp_Vector *v, ptrdiff_t nbytes)
2840 {
2841   v = ptr_bounds_clip (v, nbytes);
2842   eassume (header_size <= nbytes);
2843   ptrdiff_t nwords = (nbytes - header_size) / word_size;
2844   XSETPVECTYPESIZE (v, PVEC_FREE, 0, nwords);
2845   eassert (nbytes % roundup_size == 0);
2846   ptrdiff_t vindex = VINDEX (nbytes);
2847   eassert (vindex < VECTOR_MAX_FREE_LIST_INDEX);
2848   set_next_vector (v, vector_free_lists[vindex]);
2849   vector_free_lists[vindex] = v;
2850 }
2851 
2852 /* Get a new vector block.  */
2853 
2854 static struct vector_block *
allocate_vector_block(void)2855 allocate_vector_block (void)
2856 {
2857   struct vector_block *block = xmalloc (sizeof *block);
2858 
2859 #ifndef GC_MALLOC_CHECK
2860   mem_insert (block->data, block->data + VECTOR_BLOCK_BYTES,
2861 	      MEM_TYPE_VECTOR_BLOCK);
2862 #endif
2863 
2864   block->next = vector_blocks;
2865   vector_blocks = block;
2866   return block;
2867 }
2868 
2869 /* Called once to initialize vector allocation.  */
2870 
2871 static void
init_vectors(void)2872 init_vectors (void)
2873 {
2874   zero_vector = make_pure_vector (0);
2875   staticpro (&zero_vector);
2876 }
2877 
2878 /* Allocate vector from a vector block.  */
2879 
2880 static struct Lisp_Vector *
allocate_vector_from_block(ptrdiff_t nbytes)2881 allocate_vector_from_block (ptrdiff_t nbytes)
2882 {
2883   struct Lisp_Vector *vector;
2884   struct vector_block *block;
2885   size_t index, restbytes;
2886 
2887   eassume (VBLOCK_BYTES_MIN <= nbytes && nbytes <= VBLOCK_BYTES_MAX);
2888   eassume (nbytes % roundup_size == 0);
2889 
2890   /* First, try to allocate from a free list
2891      containing vectors of the requested size.  */
2892   index = VINDEX (nbytes);
2893   if (vector_free_lists[index])
2894     {
2895       vector = vector_free_lists[index];
2896       vector_free_lists[index] = next_vector (vector);
2897       return vector;
2898     }
2899 
2900   /* Next, check free lists containing larger vectors.  Since
2901      we will split the result, we should have remaining space
2902      large enough to use for one-slot vector at least.  */
2903   for (index = VINDEX (nbytes + VBLOCK_BYTES_MIN);
2904        index < VECTOR_MAX_FREE_LIST_INDEX; index++)
2905     if (vector_free_lists[index])
2906       {
2907 	/* This vector is larger than requested.  */
2908 	vector = vector_free_lists[index];
2909 	vector_free_lists[index] = next_vector (vector);
2910 
2911 	/* Excess bytes are used for the smaller vector,
2912 	   which should be set on an appropriate free list.  */
2913 	restbytes = index * roundup_size + VBLOCK_BYTES_MIN - nbytes;
2914 	eassert (restbytes % roundup_size == 0);
2915 	setup_on_free_list (ADVANCE (vector, nbytes), restbytes);
2916 	return vector;
2917       }
2918 
2919   /* Finally, need a new vector block.  */
2920   block = allocate_vector_block ();
2921 
2922   /* New vector will be at the beginning of this block.  */
2923   vector = (struct Lisp_Vector *) block->data;
2924 
2925   /* If the rest of space from this block is large enough
2926      for one-slot vector at least, set up it on a free list.  */
2927   restbytes = VECTOR_BLOCK_BYTES - nbytes;
2928   if (restbytes >= VBLOCK_BYTES_MIN)
2929     {
2930       eassert (restbytes % roundup_size == 0);
2931       setup_on_free_list (ADVANCE (vector, nbytes), restbytes);
2932     }
2933   return vector;
2934 }
2935 
2936 /* Nonzero if VECTOR pointer is valid pointer inside BLOCK.  */
2937 
2938 #define VECTOR_IN_BLOCK(vector, block)		\
2939   ((char *) (vector) <= (block)->data		\
2940    + VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN)
2941 
2942 /* Return the memory footprint of V in bytes.  */
2943 
2944 ptrdiff_t
vectorlike_nbytes(const union vectorlike_header * hdr)2945 vectorlike_nbytes (const union vectorlike_header *hdr)
2946 {
2947   ptrdiff_t size = hdr->size & ~ARRAY_MARK_FLAG;
2948   ptrdiff_t nwords;
2949 
2950   if (size & PSEUDOVECTOR_FLAG)
2951     {
2952       if (PSEUDOVECTOR_TYPEP (hdr, PVEC_BOOL_VECTOR))
2953         {
2954           struct Lisp_Bool_Vector *bv = (struct Lisp_Bool_Vector *) hdr;
2955 	  ptrdiff_t word_bytes = (bool_vector_words (bv->size)
2956 				  * sizeof (bits_word));
2957 	  ptrdiff_t boolvec_bytes = bool_header_size + word_bytes;
2958 	  verify (header_size <= bool_header_size);
2959 	  nwords = (boolvec_bytes - header_size + word_size - 1) / word_size;
2960         }
2961       else
2962 	nwords = ((size & PSEUDOVECTOR_SIZE_MASK)
2963 		  + ((size & PSEUDOVECTOR_REST_MASK)
2964 		     >> PSEUDOVECTOR_SIZE_BITS));
2965     }
2966   else
2967     nwords = size;
2968   return vroundup (header_size + word_size * nwords);
2969 }
2970 
2971 /* Convert a pseudovector pointer P to its underlying struct T pointer.
2972    Verify that the struct is small, since cleanup_vector is called
2973    only on small vector-like objects.  */
2974 
2975 #define PSEUDOVEC_STRUCT(p, t) \
2976   verify_expr ((header_size + VECSIZE (struct t) * word_size \
2977 		<= VBLOCK_BYTES_MAX), \
2978 	       (struct t *) (p))
2979 
2980 /* Release extra resources still in use by VECTOR, which may be any
2981    small vector-like object.  */
2982 
2983 static void
cleanup_vector(struct Lisp_Vector * vector)2984 cleanup_vector (struct Lisp_Vector *vector)
2985 {
2986   detect_suspicious_free (vector);
2987 
2988   if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_BIGNUM))
2989     mpz_clear (PSEUDOVEC_STRUCT (vector, Lisp_Bignum)->value);
2990   else if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FINALIZER))
2991     unchain_finalizer (PSEUDOVEC_STRUCT (vector, Lisp_Finalizer));
2992   else if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FONT))
2993     {
2994       if ((vector->header.size & PSEUDOVECTOR_SIZE_MASK) == FONT_OBJECT_MAX)
2995 	{
2996 	  struct font *font = PSEUDOVEC_STRUCT (vector, font);
2997 	  struct font_driver const *drv = font->driver;
2998 
2999 	  /* The font driver might sometimes be NULL, e.g. if Emacs was
3000 	     interrupted before it had time to set it up.  */
3001 	  if (drv)
3002 	    {
3003 	      /* Attempt to catch subtle bugs like Bug#16140.  */
3004 	      eassert (valid_font_driver (drv));
3005 	      drv->close_font (font);
3006 	    }
3007 	}
3008     }
3009   else if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_THREAD))
3010     finalize_one_thread (PSEUDOVEC_STRUCT (vector, thread_state));
3011   else if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_MUTEX))
3012     finalize_one_mutex (PSEUDOVEC_STRUCT (vector, Lisp_Mutex));
3013   else if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_CONDVAR))
3014     finalize_one_condvar (PSEUDOVEC_STRUCT (vector, Lisp_CondVar));
3015   else if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_MARKER))
3016     {
3017       /* sweep_buffer should already have unchained this from its buffer.  */
3018       eassert (! PSEUDOVEC_STRUCT (vector, Lisp_Marker)->buffer);
3019     }
3020   else if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_USER_PTR))
3021     {
3022       struct Lisp_User_Ptr *uptr = PSEUDOVEC_STRUCT (vector, Lisp_User_Ptr);
3023       if (uptr->finalizer)
3024 	uptr->finalizer (uptr->p);
3025     }
3026 }
3027 
3028 /* Reclaim space used by unmarked vectors.  */
3029 
3030 NO_INLINE /* For better stack traces */
3031 static void
sweep_vectors(void)3032 sweep_vectors (void)
3033 {
3034   struct vector_block *block, **bprev = &vector_blocks;
3035   struct large_vector *lv, **lvprev = &large_vectors;
3036   struct Lisp_Vector *vector, *next;
3037 
3038   gcstat.total_vectors = 0;
3039   gcstat.total_vector_slots = gcstat.total_free_vector_slots = 0;
3040   memset (vector_free_lists, 0, sizeof (vector_free_lists));
3041 
3042   /* Looking through vector blocks.  */
3043 
3044   for (block = vector_blocks; block; block = *bprev)
3045     {
3046       bool free_this_block = false;
3047 
3048       for (vector = (struct Lisp_Vector *) block->data;
3049 	   VECTOR_IN_BLOCK (vector, block); vector = next)
3050 	{
3051 	  if (XVECTOR_MARKED_P (vector))
3052 	    {
3053 	      XUNMARK_VECTOR (vector);
3054 	      gcstat.total_vectors++;
3055 	      ptrdiff_t nbytes = vector_nbytes (vector);
3056 	      gcstat.total_vector_slots += nbytes / word_size;
3057 	      next = ADVANCE (vector, nbytes);
3058 	    }
3059 	  else
3060 	    {
3061 	      ptrdiff_t total_bytes = 0;
3062 
3063 	      /* While NEXT is not marked, try to coalesce with VECTOR,
3064 		 thus making VECTOR of the largest possible size.  */
3065 
3066 	      next = vector;
3067 	      do
3068 		{
3069 		  cleanup_vector (next);
3070 		  ptrdiff_t nbytes = vector_nbytes (next);
3071 		  total_bytes += nbytes;
3072 		  next = ADVANCE (next, nbytes);
3073 		}
3074 	      while (VECTOR_IN_BLOCK (next, block) && !vector_marked_p (next));
3075 
3076 	      eassert (total_bytes % roundup_size == 0);
3077 
3078 	      if (vector == (struct Lisp_Vector *) block->data
3079 		  && !VECTOR_IN_BLOCK (next, block))
3080 		/* This block should be freed because all of its
3081 		   space was coalesced into the only free vector.  */
3082 		free_this_block = true;
3083 	      else
3084 		{
3085 		  setup_on_free_list (vector, total_bytes);
3086 		  gcstat.total_free_vector_slots += total_bytes / word_size;
3087 		}
3088 	    }
3089 	}
3090 
3091       if (free_this_block)
3092 	{
3093 	  *bprev = block->next;
3094 #ifndef GC_MALLOC_CHECK
3095 	  mem_delete (mem_find (block->data));
3096 #endif
3097 	  xfree (block);
3098 	}
3099       else
3100 	bprev = &block->next;
3101     }
3102 
3103   /* Sweep large vectors.  */
3104 
3105   for (lv = large_vectors; lv; lv = *lvprev)
3106     {
3107       vector = large_vector_vec (lv);
3108       if (XVECTOR_MARKED_P (vector))
3109 	{
3110 	  XUNMARK_VECTOR (vector);
3111 	  gcstat.total_vectors++;
3112 	  gcstat.total_vector_slots
3113 	    += (vector->header.size & PSEUDOVECTOR_FLAG
3114 		? vector_nbytes (vector) / word_size
3115 		: header_size / word_size + vector->header.size);
3116 	  lvprev = &lv->next;
3117 	}
3118       else
3119 	{
3120 	  *lvprev = lv->next;
3121 	  lisp_free (lv);
3122 	}
3123     }
3124 }
3125 
3126 /* Maximum number of elements in a vector.  This is a macro so that it
3127    can be used in an integer constant expression.  */
3128 
3129 #define VECTOR_ELTS_MAX \
3130   ((ptrdiff_t) \
3131    min (((min (PTRDIFF_MAX, SIZE_MAX) - header_size - large_vector_offset) \
3132 	 / word_size), \
3133 	MOST_POSITIVE_FIXNUM))
3134 
3135 /* Value is a pointer to a newly allocated Lisp_Vector structure
3136    with room for LEN Lisp_Objects.  LEN must be positive and
3137    at most VECTOR_ELTS_MAX.  */
3138 
3139 static struct Lisp_Vector *
allocate_vectorlike(ptrdiff_t len)3140 allocate_vectorlike (ptrdiff_t len)
3141 {
3142   eassert (0 < len && len <= VECTOR_ELTS_MAX);
3143   ptrdiff_t nbytes = header_size + len * word_size;
3144   struct Lisp_Vector *p;
3145 
3146   MALLOC_BLOCK_INPUT;
3147 
3148 #ifdef DOUG_LEA_MALLOC
3149   if (!mmap_lisp_allowed_p ())
3150     mallopt (M_MMAP_MAX, 0);
3151 #endif
3152 
3153   if (nbytes <= VBLOCK_BYTES_MAX)
3154     p = allocate_vector_from_block (vroundup (nbytes));
3155   else
3156     {
3157       struct large_vector *lv = lisp_malloc (large_vector_offset + nbytes,
3158 					     MEM_TYPE_VECTORLIKE);
3159       lv->next = large_vectors;
3160       large_vectors = lv;
3161       p = large_vector_vec (lv);
3162     }
3163 
3164 #ifdef DOUG_LEA_MALLOC
3165   if (!mmap_lisp_allowed_p ())
3166     mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
3167 #endif
3168 
3169   if (find_suspicious_object_in_range (p, (char *) p + nbytes))
3170     emacs_abort ();
3171 
3172   tally_consing (nbytes);
3173   vector_cells_consed += len;
3174 
3175   MALLOC_UNBLOCK_INPUT;
3176 
3177   return ptr_bounds_clip (p, nbytes);
3178 }
3179 
3180 
3181 /* Allocate a vector with LEN slots.  */
3182 
3183 struct Lisp_Vector *
allocate_vector(ptrdiff_t len)3184 allocate_vector (ptrdiff_t len)
3185 {
3186   if (len == 0)
3187     return XVECTOR (zero_vector);
3188   if (VECTOR_ELTS_MAX < len)
3189     memory_full (SIZE_MAX);
3190   struct Lisp_Vector *v = allocate_vectorlike (len);
3191   v->header.size = len;
3192   return v;
3193 }
3194 
3195 
3196 /* Allocate other vector-like structures.  */
3197 
3198 struct Lisp_Vector *
allocate_pseudovector(int memlen,int lisplen,int zerolen,enum pvec_type tag)3199 allocate_pseudovector (int memlen, int lisplen,
3200 		       int zerolen, enum pvec_type tag)
3201 {
3202   /* Catch bogus values.  */
3203   enum { size_max = (1 << PSEUDOVECTOR_SIZE_BITS) - 1 };
3204   enum { rest_max = (1 << PSEUDOVECTOR_REST_BITS) - 1 };
3205   verify (size_max + rest_max <= VECTOR_ELTS_MAX);
3206   eassert (0 <= tag && tag <= PVEC_FONT);
3207   eassert (0 <= lisplen && lisplen <= zerolen && zerolen <= memlen);
3208   eassert (lisplen <= size_max);
3209   eassert (memlen <= size_max + rest_max);
3210 
3211   struct Lisp_Vector *v = allocate_vectorlike (memlen);
3212   /* Only the first LISPLEN slots will be traced normally by the GC.  */
3213   memclear (v->contents, zerolen * word_size);
3214   XSETPVECTYPESIZE (v, tag, lisplen, memlen - lisplen);
3215   return v;
3216 }
3217 
3218 struct buffer *
allocate_buffer(void)3219 allocate_buffer (void)
3220 {
3221   struct buffer *b = lisp_malloc (sizeof *b, MEM_TYPE_BUFFER);
3222 
3223   BUFFER_PVEC_INIT (b);
3224   /* Put B on the chain of all buffers including killed ones.  */
3225   b->next = all_buffers;
3226   all_buffers = b;
3227   /* Note that the rest fields of B are not initialized.  */
3228   return b;
3229 }
3230 
3231 
3232 /* Allocate a record with COUNT slots.  COUNT must be positive, and
3233    includes the type slot.  */
3234 
3235 static struct Lisp_Vector *
allocate_record(EMACS_INT count)3236 allocate_record (EMACS_INT count)
3237 {
3238   if (count > PSEUDOVECTOR_SIZE_MASK)
3239     error ("Attempt to allocate a record of %"pI"d slots; max is %d",
3240 	   count, PSEUDOVECTOR_SIZE_MASK);
3241   struct Lisp_Vector *p = allocate_vectorlike (count);
3242   p->header.size = count;
3243   XSETPVECTYPE (p, PVEC_RECORD);
3244   return p;
3245 }
3246 
3247 
3248 DEFUN ("make-record", Fmake_record, Smake_record, 3, 3, 0,
3249        doc: /* Create a new record.
3250 TYPE is its type as returned by `type-of'; it should be either a
3251 symbol or a type descriptor.  SLOTS is the number of non-type slots,
3252 each initialized to INIT.  */)
3253   (Lisp_Object type, Lisp_Object slots, Lisp_Object init)
3254 {
3255   CHECK_FIXNAT (slots);
3256   EMACS_INT size = XFIXNAT (slots) + 1;
3257   struct Lisp_Vector *p = allocate_record (size);
3258   p->contents[0] = type;
3259   for (ptrdiff_t i = 1; i < size; i++)
3260     p->contents[i] = init;
3261   return make_lisp_ptr (p, Lisp_Vectorlike);
3262 }
3263 
3264 
3265 DEFUN ("record", Frecord, Srecord, 1, MANY, 0,
3266        doc: /* Create a new record.
3267 TYPE is its type as returned by `type-of'; it should be either a
3268 symbol or a type descriptor.  SLOTS is used to initialize the record
3269 slots with shallow copies of the arguments.
3270 usage: (record TYPE &rest SLOTS) */)
3271   (ptrdiff_t nargs, Lisp_Object *args)
3272 {
3273   struct Lisp_Vector *p = allocate_record (nargs);
3274   memcpy (p->contents, args, nargs * sizeof *args);
3275   return make_lisp_ptr (p, Lisp_Vectorlike);
3276 }
3277 
3278 
3279 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
3280        doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
3281 See also the function `vector'.  */)
3282   (Lisp_Object length, Lisp_Object init)
3283 {
3284   CHECK_TYPE (FIXNATP (length) && XFIXNAT (length) <= PTRDIFF_MAX,
3285 	      Qwholenump, length);
3286   return make_vector (XFIXNAT (length), init);
3287 }
3288 
3289 /* Return a new vector of length LENGTH with each element being INIT.  */
3290 
3291 Lisp_Object
make_vector(ptrdiff_t length,Lisp_Object init)3292 make_vector (ptrdiff_t length, Lisp_Object init)
3293 {
3294   struct Lisp_Vector *p = allocate_vector (length);
3295   for (ptrdiff_t i = 0; i < length; i++)
3296     p->contents[i] = init;
3297   return make_lisp_ptr (p, Lisp_Vectorlike);
3298 }
3299 
3300 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3301        doc: /* Return a newly created vector with specified arguments as elements.
3302 Allows any number of arguments, including zero.
3303 usage: (vector &rest OBJECTS)  */)
3304   (ptrdiff_t nargs, Lisp_Object *args)
3305 {
3306   Lisp_Object val = make_uninit_vector (nargs);
3307   struct Lisp_Vector *p = XVECTOR (val);
3308   memcpy (p->contents, args, nargs * sizeof *args);
3309   return val;
3310 }
3311 
3312 void
make_byte_code(struct Lisp_Vector * v)3313 make_byte_code (struct Lisp_Vector *v)
3314 {
3315   /* Don't allow the global zero_vector to become a byte code object.  */
3316   eassert (0 < v->header.size);
3317 
3318   if (v->header.size > 1 && STRINGP (v->contents[1])
3319       && STRING_MULTIBYTE (v->contents[1]))
3320     /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3321        earlier because they produced a raw 8-bit string for byte-code
3322        and now such a byte-code string is loaded as multibyte while
3323        raw 8-bit characters converted to multibyte form.  Thus, now we
3324        must convert them back to the original unibyte form.  */
3325     v->contents[1] = Fstring_as_unibyte (v->contents[1]);
3326   XSETPVECTYPE (v, PVEC_COMPILED);
3327 }
3328 
3329 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3330        doc: /* Create a byte-code object with specified arguments as elements.
3331 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3332 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3333 and (optional) INTERACTIVE-SPEC.
3334 The first four arguments are required; at most six have any
3335 significance.
3336 The ARGLIST can be either like the one of `lambda', in which case the arguments
3337 will be dynamically bound before executing the byte code, or it can be an
3338 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3339 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3340 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3341 argument to catch the left-over arguments.  If such an integer is used, the
3342 arguments will not be dynamically bound but will be instead pushed on the
3343 stack before executing the byte-code.
3344 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS)  */)
3345   (ptrdiff_t nargs, Lisp_Object *args)
3346 {
3347   Lisp_Object val = make_uninit_vector (nargs);
3348   struct Lisp_Vector *p = XVECTOR (val);
3349 
3350   /* We used to purecopy everything here, if purify-flag was set.  This worked
3351      OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
3352      dangerous, since make-byte-code is used during execution to build
3353      closures, so any closure built during the preload phase would end up
3354      copied into pure space, including its free variables, which is sometimes
3355      just wasteful and other times plainly wrong (e.g. those free vars may want
3356      to be setcar'd).  */
3357 
3358   memcpy (p->contents, args, nargs * sizeof *args);
3359   make_byte_code (p);
3360   XSETCOMPILED (val, p);
3361   return val;
3362 }
3363 
3364 
3365 
3366 /***********************************************************************
3367 			   Symbol Allocation
3368  ***********************************************************************/
3369 
3370 /* Each symbol_block is just under 1020 bytes long, since malloc
3371    really allocates in units of powers of two and uses 4 bytes for its
3372    own overhead.  */
3373 
3374 #define SYMBOL_BLOCK_SIZE \
3375   ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
3376 
3377 struct symbol_block
3378 {
3379   /* Place `symbols' first, to preserve alignment.  */
3380   struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3381   struct symbol_block *next;
3382 };
3383 
3384 /* Current symbol block and index of first unused Lisp_Symbol
3385    structure in it.  */
3386 
3387 static struct symbol_block *symbol_block;
3388 static int symbol_block_index = SYMBOL_BLOCK_SIZE;
3389 /* Pointer to the first symbol_block that contains pinned symbols.
3390    Tests for 24.4 showed that at dump-time, Emacs contains about 15K symbols,
3391    10K of which are pinned (and all but 250 of them are interned in obarray),
3392    whereas a "typical session" has in the order of 30K symbols.
3393    `symbol_block_pinned' lets mark_pinned_symbols scan only 15K symbols rather
3394    than 30K to find the 10K symbols we need to mark.  */
3395 static struct symbol_block *symbol_block_pinned;
3396 
3397 /* List of free symbols.  */
3398 
3399 static struct Lisp_Symbol *symbol_free_list;
3400 
3401 static void
set_symbol_name(Lisp_Object sym,Lisp_Object name)3402 set_symbol_name (Lisp_Object sym, Lisp_Object name)
3403 {
3404   XSYMBOL (sym)->u.s.name = name;
3405 }
3406 
3407 void
init_symbol(Lisp_Object val,Lisp_Object name)3408 init_symbol (Lisp_Object val, Lisp_Object name)
3409 {
3410   struct Lisp_Symbol *p = XSYMBOL (val);
3411   set_symbol_name (val, name);
3412   set_symbol_plist (val, Qnil);
3413   p->u.s.redirect = SYMBOL_PLAINVAL;
3414   SET_SYMBOL_VAL (p, Qunbound);
3415   set_symbol_function (val, Qnil);
3416   set_symbol_next (val, NULL);
3417   p->u.s.gcmarkbit = false;
3418   p->u.s.interned = SYMBOL_UNINTERNED;
3419   p->u.s.trapped_write = SYMBOL_UNTRAPPED_WRITE;
3420   p->u.s.declared_special = false;
3421   p->u.s.pinned = false;
3422 }
3423 
3424 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3425        doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3426 Its value is void, and its function definition and property list are nil.  */)
3427   (Lisp_Object name)
3428 {
3429   Lisp_Object val;
3430 
3431   CHECK_STRING (name);
3432 
3433   MALLOC_BLOCK_INPUT;
3434 
3435   if (symbol_free_list)
3436     {
3437       XSETSYMBOL (val, symbol_free_list);
3438       symbol_free_list = symbol_free_list->u.s.next;
3439     }
3440   else
3441     {
3442       if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3443 	{
3444 	  struct symbol_block *new
3445 	    = lisp_malloc (sizeof *new, MEM_TYPE_SYMBOL);
3446 	  new->next = symbol_block;
3447 	  symbol_block = new;
3448 	  symbol_block_index = 0;
3449 	}
3450       XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index]);
3451       symbol_block_index++;
3452     }
3453 
3454   MALLOC_UNBLOCK_INPUT;
3455 
3456   init_symbol (val, name);
3457   tally_consing (sizeof (struct Lisp_Symbol));
3458   symbols_consed++;
3459   return val;
3460 }
3461 
3462 
3463 
3464 Lisp_Object
make_misc_ptr(void * a)3465 make_misc_ptr (void *a)
3466 {
3467   struct Lisp_Misc_Ptr *p = ALLOCATE_PLAIN_PSEUDOVECTOR (struct Lisp_Misc_Ptr,
3468 							 PVEC_MISC_PTR);
3469   p->pointer = a;
3470   return make_lisp_ptr (p, Lisp_Vectorlike);
3471 }
3472 
3473 /* Return a new overlay with specified START, END and PLIST.  */
3474 
3475 Lisp_Object
build_overlay(Lisp_Object start,Lisp_Object end,Lisp_Object plist)3476 build_overlay (Lisp_Object start, Lisp_Object end, Lisp_Object plist)
3477 {
3478   struct Lisp_Overlay *p = ALLOCATE_PSEUDOVECTOR (struct Lisp_Overlay, plist,
3479 						  PVEC_OVERLAY);
3480   Lisp_Object overlay = make_lisp_ptr (p, Lisp_Vectorlike);
3481   OVERLAY_START (overlay) = start;
3482   OVERLAY_END (overlay) = end;
3483   set_overlay_plist (overlay, plist);
3484   p->next = NULL;
3485   return overlay;
3486 }
3487 
3488 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3489        doc: /* Return a newly allocated marker which does not point at any place.  */)
3490   (void)
3491 {
3492   struct Lisp_Marker *p = ALLOCATE_PLAIN_PSEUDOVECTOR (struct Lisp_Marker,
3493 						       PVEC_MARKER);
3494   p->buffer = 0;
3495   p->bytepos = 0;
3496   p->charpos = 0;
3497   p->next = NULL;
3498   p->insertion_type = 0;
3499   p->need_adjustment = 0;
3500   return make_lisp_ptr (p, Lisp_Vectorlike);
3501 }
3502 
3503 /* Return a newly allocated marker which points into BUF
3504    at character position CHARPOS and byte position BYTEPOS.  */
3505 
3506 Lisp_Object
build_marker(struct buffer * buf,ptrdiff_t charpos,ptrdiff_t bytepos)3507 build_marker (struct buffer *buf, ptrdiff_t charpos, ptrdiff_t bytepos)
3508 {
3509   /* No dead buffers here.  */
3510   eassert (BUFFER_LIVE_P (buf));
3511 
3512   /* Every character is at least one byte.  */
3513   eassert (charpos <= bytepos);
3514 
3515   struct Lisp_Marker *m = ALLOCATE_PLAIN_PSEUDOVECTOR (struct Lisp_Marker,
3516 						       PVEC_MARKER);
3517   m->buffer = buf;
3518   m->charpos = charpos;
3519   m->bytepos = bytepos;
3520   m->insertion_type = 0;
3521   m->need_adjustment = 0;
3522   m->next = BUF_MARKERS (buf);
3523   BUF_MARKERS (buf) = m;
3524   return make_lisp_ptr (m, Lisp_Vectorlike);
3525 }
3526 
3527 
3528 /* Return a newly created vector or string with specified arguments as
3529    elements.  If all the arguments are characters that can fit
3530    in a string of events, make a string; otherwise, make a vector.
3531 
3532    Allows any number of arguments, including zero.  */
3533 
3534 Lisp_Object
make_event_array(ptrdiff_t nargs,Lisp_Object * args)3535 make_event_array (ptrdiff_t nargs, Lisp_Object *args)
3536 {
3537   ptrdiff_t i;
3538 
3539   for (i = 0; i < nargs; i++)
3540     /* The things that fit in a string
3541        are characters that are in 0...127,
3542        after discarding the meta bit and all the bits above it.  */
3543     if (!FIXNUMP (args[i])
3544 	|| (XFIXNUM (args[i]) & ~(-CHAR_META)) >= 0200)
3545       return Fvector (nargs, args);
3546 
3547   /* Since the loop exited, we know that all the things in it are
3548      characters, so we can make a string.  */
3549   {
3550     Lisp_Object result;
3551 
3552     result = Fmake_string (make_fixnum (nargs), make_fixnum (0), Qnil);
3553     for (i = 0; i < nargs; i++)
3554       {
3555 	SSET (result, i, XFIXNUM (args[i]));
3556 	/* Move the meta bit to the right place for a string char.  */
3557 	if (XFIXNUM (args[i]) & CHAR_META)
3558 	  SSET (result, i, SREF (result, i) | 0x80);
3559       }
3560 
3561     return result;
3562   }
3563 }
3564 
3565 #ifdef HAVE_MODULES
3566 /* Create a new module user ptr object.  */
3567 Lisp_Object
make_user_ptr(void (* finalizer)(void *),void * p)3568 make_user_ptr (void (*finalizer) (void *), void *p)
3569 {
3570   struct Lisp_User_Ptr *uptr
3571     = ALLOCATE_PLAIN_PSEUDOVECTOR (struct Lisp_User_Ptr, PVEC_USER_PTR);
3572   uptr->finalizer = finalizer;
3573   uptr->p = p;
3574   return make_lisp_ptr (uptr, Lisp_Vectorlike);
3575 }
3576 #endif
3577 
3578 static void
init_finalizer_list(struct Lisp_Finalizer * head)3579 init_finalizer_list (struct Lisp_Finalizer *head)
3580 {
3581   head->prev = head->next = head;
3582 }
3583 
3584 /* Insert FINALIZER before ELEMENT.  */
3585 
3586 static void
finalizer_insert(struct Lisp_Finalizer * element,struct Lisp_Finalizer * finalizer)3587 finalizer_insert (struct Lisp_Finalizer *element,
3588                   struct Lisp_Finalizer *finalizer)
3589 {
3590   eassert (finalizer->prev == NULL);
3591   eassert (finalizer->next == NULL);
3592   finalizer->next = element;
3593   finalizer->prev = element->prev;
3594   finalizer->prev->next = finalizer;
3595   element->prev = finalizer;
3596 }
3597 
3598 static void
unchain_finalizer(struct Lisp_Finalizer * finalizer)3599 unchain_finalizer (struct Lisp_Finalizer *finalizer)
3600 {
3601   if (finalizer->prev != NULL)
3602     {
3603       eassert (finalizer->next != NULL);
3604       finalizer->prev->next = finalizer->next;
3605       finalizer->next->prev = finalizer->prev;
3606       finalizer->prev = finalizer->next = NULL;
3607     }
3608 }
3609 
3610 static void
mark_finalizer_list(struct Lisp_Finalizer * head)3611 mark_finalizer_list (struct Lisp_Finalizer *head)
3612 {
3613   for (struct Lisp_Finalizer *finalizer = head->next;
3614        finalizer != head;
3615        finalizer = finalizer->next)
3616     {
3617       set_vectorlike_marked (&finalizer->header);
3618       mark_object (finalizer->function);
3619     }
3620 }
3621 
3622 /* Move doomed finalizers to list DEST from list SRC.  A doomed
3623    finalizer is one that is not GC-reachable and whose
3624    finalizer->function is non-nil.  */
3625 
3626 static void
queue_doomed_finalizers(struct Lisp_Finalizer * dest,struct Lisp_Finalizer * src)3627 queue_doomed_finalizers (struct Lisp_Finalizer *dest,
3628                          struct Lisp_Finalizer *src)
3629 {
3630   struct Lisp_Finalizer *finalizer = src->next;
3631   while (finalizer != src)
3632     {
3633       struct Lisp_Finalizer *next = finalizer->next;
3634       if (!vectorlike_marked_p (&finalizer->header)
3635           && !NILP (finalizer->function))
3636         {
3637           unchain_finalizer (finalizer);
3638           finalizer_insert (dest, finalizer);
3639         }
3640 
3641       finalizer = next;
3642     }
3643 }
3644 
3645 static Lisp_Object
run_finalizer_handler(Lisp_Object args)3646 run_finalizer_handler (Lisp_Object args)
3647 {
3648   add_to_log ("finalizer failed: %S", args);
3649   return Qnil;
3650 }
3651 
3652 static void
run_finalizer_function(Lisp_Object function)3653 run_finalizer_function (Lisp_Object function)
3654 {
3655   ptrdiff_t count = SPECPDL_INDEX ();
3656 #ifdef HAVE_PDUMPER
3657   ++number_finalizers_run;
3658 #endif
3659 
3660   specbind (Qinhibit_quit, Qt);
3661   internal_condition_case_1 (call0, function, Qt, run_finalizer_handler);
3662   unbind_to (count, Qnil);
3663 }
3664 
3665 static void
run_finalizers(struct Lisp_Finalizer * finalizers)3666 run_finalizers (struct Lisp_Finalizer *finalizers)
3667 {
3668   struct Lisp_Finalizer *finalizer;
3669   Lisp_Object function;
3670 
3671   while (finalizers->next != finalizers)
3672     {
3673       finalizer = finalizers->next;
3674       unchain_finalizer (finalizer);
3675       function = finalizer->function;
3676       if (!NILP (function))
3677 	{
3678 	  finalizer->function = Qnil;
3679 	  run_finalizer_function (function);
3680 	}
3681     }
3682 }
3683 
3684 DEFUN ("make-finalizer", Fmake_finalizer, Smake_finalizer, 1, 1, 0,
3685        doc: /* Make a finalizer that will run FUNCTION.
3686 FUNCTION will be called after garbage collection when the returned
3687 finalizer object becomes unreachable.  If the finalizer object is
3688 reachable only through references from finalizer objects, it does not
3689 count as reachable for the purpose of deciding whether to run
3690 FUNCTION.  FUNCTION will be run once per finalizer object.  */)
3691   (Lisp_Object function)
3692 {
3693   struct Lisp_Finalizer *finalizer
3694     = ALLOCATE_PSEUDOVECTOR (struct Lisp_Finalizer, function, PVEC_FINALIZER);
3695   finalizer->function = function;
3696   finalizer->prev = finalizer->next = NULL;
3697   finalizer_insert (&finalizers, finalizer);
3698   return make_lisp_ptr (finalizer, Lisp_Vectorlike);
3699 }
3700 
3701 
3702 /************************************************************************
3703                          Mark bit access functions
3704  ************************************************************************/
3705 
3706 /* With the rare exception of functions implementing block-based
3707    allocation of various types, you should not directly test or set GC
3708    mark bits on objects.  Some objects might live in special memory
3709    regions (e.g., a dump image) and might store their mark bits
3710    elsewhere.  */
3711 
3712 static bool
vector_marked_p(const struct Lisp_Vector * v)3713 vector_marked_p (const struct Lisp_Vector *v)
3714 {
3715   if (pdumper_object_p (v))
3716     {
3717       /* Look at cold_start first so that we don't have to fault in
3718          the vector header just to tell that it's a bool vector.  */
3719       if (pdumper_cold_object_p (v))
3720         {
3721           eassert (PSEUDOVECTOR_TYPE (v) == PVEC_BOOL_VECTOR);
3722           return true;
3723         }
3724       return pdumper_marked_p (v);
3725     }
3726   return XVECTOR_MARKED_P (v);
3727 }
3728 
3729 static void
set_vector_marked(struct Lisp_Vector * v)3730 set_vector_marked (struct Lisp_Vector *v)
3731 {
3732   if (pdumper_object_p (v))
3733     {
3734       eassert (PSEUDOVECTOR_TYPE (v) != PVEC_BOOL_VECTOR);
3735       pdumper_set_marked (v);
3736     }
3737   else
3738     XMARK_VECTOR (v);
3739 }
3740 
3741 static bool
vectorlike_marked_p(const union vectorlike_header * header)3742 vectorlike_marked_p (const union vectorlike_header *header)
3743 {
3744   return vector_marked_p ((const struct Lisp_Vector *) header);
3745 }
3746 
3747 static void
set_vectorlike_marked(union vectorlike_header * header)3748 set_vectorlike_marked (union vectorlike_header *header)
3749 {
3750   set_vector_marked ((struct Lisp_Vector *) header);
3751 }
3752 
3753 static bool
cons_marked_p(const struct Lisp_Cons * c)3754 cons_marked_p (const struct Lisp_Cons *c)
3755 {
3756   return pdumper_object_p (c)
3757     ? pdumper_marked_p (c)
3758     : XCONS_MARKED_P (c);
3759 }
3760 
3761 static void
set_cons_marked(struct Lisp_Cons * c)3762 set_cons_marked (struct Lisp_Cons *c)
3763 {
3764   if (pdumper_object_p (c))
3765     pdumper_set_marked (c);
3766   else
3767     XMARK_CONS (c);
3768 }
3769 
3770 static bool
string_marked_p(const struct Lisp_String * s)3771 string_marked_p (const struct Lisp_String *s)
3772 {
3773   return pdumper_object_p (s)
3774     ? pdumper_marked_p (s)
3775     : XSTRING_MARKED_P (s);
3776 }
3777 
3778 static void
set_string_marked(struct Lisp_String * s)3779 set_string_marked (struct Lisp_String *s)
3780 {
3781   if (pdumper_object_p (s))
3782     pdumper_set_marked (s);
3783   else
3784     XMARK_STRING (s);
3785 }
3786 
3787 static bool
symbol_marked_p(const struct Lisp_Symbol * s)3788 symbol_marked_p (const struct Lisp_Symbol *s)
3789 {
3790   return pdumper_object_p (s)
3791     ? pdumper_marked_p (s)
3792     : s->u.s.gcmarkbit;
3793 }
3794 
3795 static void
set_symbol_marked(struct Lisp_Symbol * s)3796 set_symbol_marked (struct Lisp_Symbol *s)
3797 {
3798   if (pdumper_object_p (s))
3799     pdumper_set_marked (s);
3800   else
3801     s->u.s.gcmarkbit = true;
3802 }
3803 
3804 static bool
interval_marked_p(INTERVAL i)3805 interval_marked_p (INTERVAL i)
3806 {
3807   return pdumper_object_p (i)
3808     ? pdumper_marked_p (i)
3809     : i->gcmarkbit;
3810 }
3811 
3812 static void
set_interval_marked(INTERVAL i)3813 set_interval_marked (INTERVAL i)
3814 {
3815   if (pdumper_object_p (i))
3816     pdumper_set_marked (i);
3817   else
3818     i->gcmarkbit = true;
3819 }
3820 
3821 
3822 /************************************************************************
3823 			   Memory Full Handling
3824  ************************************************************************/
3825 
3826 
3827 /* Called if malloc (NBYTES) returns zero.  If NBYTES == SIZE_MAX,
3828    there may have been size_t overflow so that malloc was never
3829    called, or perhaps malloc was invoked successfully but the
3830    resulting pointer had problems fitting into a tagged EMACS_INT.  In
3831    either case this counts as memory being full even though malloc did
3832    not fail.  */
3833 
3834 void
memory_full(size_t nbytes)3835 memory_full (size_t nbytes)
3836 {
3837   if (!initialized)
3838     fatal ("memory exhausted");
3839 
3840   /* Do not go into hysterics merely because a large request failed.  */
3841   bool enough_free_memory = false;
3842   if (SPARE_MEMORY < nbytes)
3843     {
3844       void *p;
3845 
3846       MALLOC_BLOCK_INPUT;
3847       p = malloc (SPARE_MEMORY);
3848       if (p)
3849 	{
3850 	  free (p);
3851 	  enough_free_memory = true;
3852 	}
3853       MALLOC_UNBLOCK_INPUT;
3854     }
3855 
3856   if (! enough_free_memory)
3857     {
3858       Vmemory_full = Qt;
3859       consing_until_gc = min (consing_until_gc, memory_full_cons_threshold);
3860 
3861       /* The first time we get here, free the spare memory.  */
3862       for (int i = 0; i < ARRAYELTS (spare_memory); i++)
3863 	if (spare_memory[i])
3864 	  {
3865 	    if (i == 0)
3866 	      free (spare_memory[i]);
3867 	    else if (i >= 1 && i <= 4)
3868 	      lisp_align_free (spare_memory[i]);
3869 	    else
3870 	      lisp_free (spare_memory[i]);
3871 	    spare_memory[i] = 0;
3872 	  }
3873     }
3874 
3875   /* This used to call error, but if we've run out of memory, we could
3876      get infinite recursion trying to build the string.  */
3877   xsignal (Qnil, Vmemory_signal_data);
3878 }
3879 
3880 /* If we released our reserve (due to running out of memory),
3881    and we have a fair amount free once again,
3882    try to set aside another reserve in case we run out once more.
3883 
3884    This is called when a relocatable block is freed in ralloc.c,
3885    and also directly from this file, in case we're not using ralloc.c.  */
3886 
3887 void
refill_memory_reserve(void)3888 refill_memory_reserve (void)
3889 {
3890 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
3891   if (spare_memory[0] == 0)
3892     spare_memory[0] = malloc (SPARE_MEMORY);
3893   if (spare_memory[1] == 0)
3894     spare_memory[1] = lisp_align_malloc (sizeof (struct cons_block),
3895 						  MEM_TYPE_SPARE);
3896   if (spare_memory[2] == 0)
3897     spare_memory[2] = lisp_align_malloc (sizeof (struct cons_block),
3898 					 MEM_TYPE_SPARE);
3899   if (spare_memory[3] == 0)
3900     spare_memory[3] = lisp_align_malloc (sizeof (struct cons_block),
3901 					 MEM_TYPE_SPARE);
3902   if (spare_memory[4] == 0)
3903     spare_memory[4] = lisp_align_malloc (sizeof (struct cons_block),
3904 					 MEM_TYPE_SPARE);
3905   if (spare_memory[5] == 0)
3906     spare_memory[5] = lisp_malloc (sizeof (struct string_block),
3907 				   MEM_TYPE_SPARE);
3908   if (spare_memory[6] == 0)
3909     spare_memory[6] = lisp_malloc (sizeof (struct string_block),
3910 				   MEM_TYPE_SPARE);
3911   if (spare_memory[0] && spare_memory[1] && spare_memory[5])
3912     Vmemory_full = Qnil;
3913 #endif
3914 }
3915 
3916 /************************************************************************
3917 			   C Stack Marking
3918  ************************************************************************/
3919 
3920 /* Conservative C stack marking requires a method to identify possibly
3921    live Lisp objects given a pointer value.  We do this by keeping
3922    track of blocks of Lisp data that are allocated in a red-black tree
3923    (see also the comment of mem_node which is the type of nodes in
3924    that tree).  Function lisp_malloc adds information for an allocated
3925    block to the red-black tree with calls to mem_insert, and function
3926    lisp_free removes it with mem_delete.  Functions live_string_p etc
3927    call mem_find to lookup information about a given pointer in the
3928    tree, and use that to determine if the pointer points into a Lisp
3929    object or not.  */
3930 
3931 /* Initialize this part of alloc.c.  */
3932 
3933 static void
mem_init(void)3934 mem_init (void)
3935 {
3936   mem_z.left = mem_z.right = MEM_NIL;
3937   mem_z.parent = NULL;
3938   mem_z.color = MEM_BLACK;
3939   mem_z.start = mem_z.end = NULL;
3940   mem_root = MEM_NIL;
3941 }
3942 
3943 
3944 /* Value is a pointer to the mem_node containing START.  Value is
3945    MEM_NIL if there is no node in the tree containing START.  */
3946 
3947 static struct mem_node *
mem_find(void * start)3948 mem_find (void *start)
3949 {
3950   struct mem_node *p;
3951 
3952   if (start < min_heap_address || start > max_heap_address)
3953     return MEM_NIL;
3954 
3955   /* Make the search always successful to speed up the loop below.  */
3956   mem_z.start = start;
3957   mem_z.end = (char *) start + 1;
3958 
3959   p = mem_root;
3960   while (start < p->start || start >= p->end)
3961     p = start < p->start ? p->left : p->right;
3962   return p;
3963 }
3964 
3965 
3966 /* Insert a new node into the tree for a block of memory with start
3967    address START, end address END, and type TYPE.  Value is a
3968    pointer to the node that was inserted.  */
3969 
3970 static struct mem_node *
mem_insert(void * start,void * end,enum mem_type type)3971 mem_insert (void *start, void *end, enum mem_type type)
3972 {
3973   struct mem_node *c, *parent, *x;
3974 
3975   if (min_heap_address == NULL || start < min_heap_address)
3976     min_heap_address = start;
3977   if (max_heap_address == NULL || end > max_heap_address)
3978     max_heap_address = end;
3979 
3980   /* See where in the tree a node for START belongs.  In this
3981      particular application, it shouldn't happen that a node is already
3982      present.  For debugging purposes, let's check that.  */
3983   c = mem_root;
3984   parent = NULL;
3985 
3986   while (c != MEM_NIL)
3987     {
3988       parent = c;
3989       c = start < c->start ? c->left : c->right;
3990     }
3991 
3992   /* Create a new node.  */
3993 #ifdef GC_MALLOC_CHECK
3994   x = malloc (sizeof *x);
3995   if (x == NULL)
3996     emacs_abort ();
3997 #else
3998   x = xmalloc (sizeof *x);
3999 #endif
4000   x->start = start;
4001   x->end = end;
4002   x->type = type;
4003   x->parent = parent;
4004   x->left = x->right = MEM_NIL;
4005   x->color = MEM_RED;
4006 
4007   /* Insert it as child of PARENT or install it as root.  */
4008   if (parent)
4009     {
4010       if (start < parent->start)
4011 	parent->left = x;
4012       else
4013 	parent->right = x;
4014     }
4015   else
4016     mem_root = x;
4017 
4018   /* Re-establish red-black tree properties.  */
4019   mem_insert_fixup (x);
4020 
4021   return x;
4022 }
4023 
4024 
4025 /* Re-establish the red-black properties of the tree, and thereby
4026    balance the tree, after node X has been inserted; X is always red.  */
4027 
4028 static void
mem_insert_fixup(struct mem_node * x)4029 mem_insert_fixup (struct mem_node *x)
4030 {
4031   while (x != mem_root && x->parent->color == MEM_RED)
4032     {
4033       /* X is red and its parent is red.  This is a violation of
4034 	 red-black tree property #3.  */
4035 
4036       if (x->parent == x->parent->parent->left)
4037 	{
4038 	  /* We're on the left side of our grandparent, and Y is our
4039 	     "uncle".  */
4040 	  struct mem_node *y = x->parent->parent->right;
4041 
4042 	  if (y->color == MEM_RED)
4043 	    {
4044 	      /* Uncle and parent are red but should be black because
4045 		 X is red.  Change the colors accordingly and proceed
4046 		 with the grandparent.  */
4047 	      x->parent->color = MEM_BLACK;
4048 	      y->color = MEM_BLACK;
4049 	      x->parent->parent->color = MEM_RED;
4050 	      x = x->parent->parent;
4051             }
4052 	  else
4053 	    {
4054 	      /* Parent and uncle have different colors; parent is
4055 		 red, uncle is black.  */
4056 	      if (x == x->parent->right)
4057 		{
4058 		  x = x->parent;
4059 		  mem_rotate_left (x);
4060                 }
4061 
4062 	      x->parent->color = MEM_BLACK;
4063 	      x->parent->parent->color = MEM_RED;
4064 	      mem_rotate_right (x->parent->parent);
4065             }
4066         }
4067       else
4068 	{
4069 	  /* This is the symmetrical case of above.  */
4070 	  struct mem_node *y = x->parent->parent->left;
4071 
4072 	  if (y->color == MEM_RED)
4073 	    {
4074 	      x->parent->color = MEM_BLACK;
4075 	      y->color = MEM_BLACK;
4076 	      x->parent->parent->color = MEM_RED;
4077 	      x = x->parent->parent;
4078             }
4079 	  else
4080 	    {
4081 	      if (x == x->parent->left)
4082 		{
4083 		  x = x->parent;
4084 		  mem_rotate_right (x);
4085 		}
4086 
4087 	      x->parent->color = MEM_BLACK;
4088 	      x->parent->parent->color = MEM_RED;
4089 	      mem_rotate_left (x->parent->parent);
4090             }
4091         }
4092     }
4093 
4094   /* The root may have been changed to red due to the algorithm.  Set
4095      it to black so that property #5 is satisfied.  */
4096   mem_root->color = MEM_BLACK;
4097 }
4098 
4099 
4100 /*   (x)                   (y)
4101      / \                   / \
4102     a   (y)      ===>    (x)  c
4103         / \              / \
4104        b   c            a   b  */
4105 
4106 static void
mem_rotate_left(struct mem_node * x)4107 mem_rotate_left (struct mem_node *x)
4108 {
4109   struct mem_node *y;
4110 
4111   /* Turn y's left sub-tree into x's right sub-tree.  */
4112   y = x->right;
4113   x->right = y->left;
4114   if (y->left != MEM_NIL)
4115     y->left->parent = x;
4116 
4117   /* Y's parent was x's parent.  */
4118   if (y != MEM_NIL)
4119     y->parent = x->parent;
4120 
4121   /* Get the parent to point to y instead of x.  */
4122   if (x->parent)
4123     {
4124       if (x == x->parent->left)
4125 	x->parent->left = y;
4126       else
4127 	x->parent->right = y;
4128     }
4129   else
4130     mem_root = y;
4131 
4132   /* Put x on y's left.  */
4133   y->left = x;
4134   if (x != MEM_NIL)
4135     x->parent = y;
4136 }
4137 
4138 
4139 /*     (x)                (Y)
4140        / \                / \
4141      (y)  c      ===>    a  (x)
4142      / \                    / \
4143     a   b                  b   c  */
4144 
4145 static void
mem_rotate_right(struct mem_node * x)4146 mem_rotate_right (struct mem_node *x)
4147 {
4148   struct mem_node *y = x->left;
4149 
4150   x->left = y->right;
4151   if (y->right != MEM_NIL)
4152     y->right->parent = x;
4153 
4154   if (y != MEM_NIL)
4155     y->parent = x->parent;
4156   if (x->parent)
4157     {
4158       if (x == x->parent->right)
4159 	x->parent->right = y;
4160       else
4161 	x->parent->left = y;
4162     }
4163   else
4164     mem_root = y;
4165 
4166   y->right = x;
4167   if (x != MEM_NIL)
4168     x->parent = y;
4169 }
4170 
4171 
4172 /* Delete node Z from the tree.  If Z is null or MEM_NIL, do nothing.  */
4173 
4174 static void
mem_delete(struct mem_node * z)4175 mem_delete (struct mem_node *z)
4176 {
4177   struct mem_node *x, *y;
4178 
4179   if (!z || z == MEM_NIL)
4180     return;
4181 
4182   if (z->left == MEM_NIL || z->right == MEM_NIL)
4183     y = z;
4184   else
4185     {
4186       y = z->right;
4187       while (y->left != MEM_NIL)
4188 	y = y->left;
4189     }
4190 
4191   if (y->left != MEM_NIL)
4192     x = y->left;
4193   else
4194     x = y->right;
4195 
4196   x->parent = y->parent;
4197   if (y->parent)
4198     {
4199       if (y == y->parent->left)
4200 	y->parent->left = x;
4201       else
4202 	y->parent->right = x;
4203     }
4204   else
4205     mem_root = x;
4206 
4207   if (y != z)
4208     {
4209       z->start = y->start;
4210       z->end = y->end;
4211       z->type = y->type;
4212     }
4213 
4214   if (y->color == MEM_BLACK)
4215     mem_delete_fixup (x);
4216 
4217 #ifdef GC_MALLOC_CHECK
4218   free (y);
4219 #else
4220   xfree (y);
4221 #endif
4222 }
4223 
4224 
4225 /* Re-establish the red-black properties of the tree, after a
4226    deletion.  */
4227 
4228 static void
mem_delete_fixup(struct mem_node * x)4229 mem_delete_fixup (struct mem_node *x)
4230 {
4231   while (x != mem_root && x->color == MEM_BLACK)
4232     {
4233       if (x == x->parent->left)
4234 	{
4235 	  struct mem_node *w = x->parent->right;
4236 
4237 	  if (w->color == MEM_RED)
4238 	    {
4239 	      w->color = MEM_BLACK;
4240 	      x->parent->color = MEM_RED;
4241 	      mem_rotate_left (x->parent);
4242 	      w = x->parent->right;
4243             }
4244 
4245 	  if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
4246 	    {
4247 	      w->color = MEM_RED;
4248 	      x = x->parent;
4249             }
4250 	  else
4251 	    {
4252 	      if (w->right->color == MEM_BLACK)
4253 		{
4254 		  w->left->color = MEM_BLACK;
4255 		  w->color = MEM_RED;
4256 		  mem_rotate_right (w);
4257 		  w = x->parent->right;
4258                 }
4259 	      w->color = x->parent->color;
4260 	      x->parent->color = MEM_BLACK;
4261 	      w->right->color = MEM_BLACK;
4262 	      mem_rotate_left (x->parent);
4263 	      x = mem_root;
4264             }
4265         }
4266       else
4267 	{
4268 	  struct mem_node *w = x->parent->left;
4269 
4270 	  if (w->color == MEM_RED)
4271 	    {
4272 	      w->color = MEM_BLACK;
4273 	      x->parent->color = MEM_RED;
4274 	      mem_rotate_right (x->parent);
4275 	      w = x->parent->left;
4276             }
4277 
4278 	  if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
4279 	    {
4280 	      w->color = MEM_RED;
4281 	      x = x->parent;
4282             }
4283 	  else
4284 	    {
4285 	      if (w->left->color == MEM_BLACK)
4286 		{
4287 		  w->right->color = MEM_BLACK;
4288 		  w->color = MEM_RED;
4289 		  mem_rotate_left (w);
4290 		  w = x->parent->left;
4291                 }
4292 
4293 	      w->color = x->parent->color;
4294 	      x->parent->color = MEM_BLACK;
4295 	      w->left->color = MEM_BLACK;
4296 	      mem_rotate_right (x->parent);
4297 	      x = mem_root;
4298             }
4299         }
4300     }
4301 
4302   x->color = MEM_BLACK;
4303 }
4304 
4305 
4306 /* If P is a pointer into a live Lisp string object on the heap,
4307    return the object.  Otherwise, return nil.  M is a pointer to the
4308    mem_block for P.
4309 
4310    This and other *_holding functions look for a pointer anywhere into
4311    the object, not merely for a pointer to the start of the object,
4312    because some compilers sometimes optimize away the latter.  See
4313    Bug#28213.  */
4314 
4315 static Lisp_Object
live_string_holding(struct mem_node * m,void * p)4316 live_string_holding (struct mem_node *m, void *p)
4317 {
4318   if (m->type == MEM_TYPE_STRING)
4319     {
4320       struct string_block *b = m->start;
4321       char *cp = p;
4322       ptrdiff_t offset = cp - (char *) &b->strings[0];
4323 
4324       /* P must point into a Lisp_String structure, and it
4325 	 must not be on the free-list.  */
4326       if (0 <= offset && offset < STRING_BLOCK_SIZE * sizeof b->strings[0])
4327 	{
4328 	  cp = ptr_bounds_copy (cp, b);
4329 	  struct Lisp_String *s = p = cp -= offset % sizeof b->strings[0];
4330 	  if (s->u.s.data)
4331 	    return make_lisp_ptr (s, Lisp_String);
4332 	}
4333     }
4334   return Qnil;
4335 }
4336 
4337 static bool
live_string_p(struct mem_node * m,void * p)4338 live_string_p (struct mem_node *m, void *p)
4339 {
4340   return !NILP (live_string_holding (m, p));
4341 }
4342 
4343 /* If P is a pointer into a live Lisp cons object on the heap, return
4344    the object.  Otherwise, return nil.  M is a pointer to the
4345    mem_block for P.  */
4346 
4347 static Lisp_Object
live_cons_holding(struct mem_node * m,void * p)4348 live_cons_holding (struct mem_node *m, void *p)
4349 {
4350   if (m->type == MEM_TYPE_CONS)
4351     {
4352       struct cons_block *b = m->start;
4353       char *cp = p;
4354       ptrdiff_t offset = cp - (char *) &b->conses[0];
4355 
4356       /* P must point into a Lisp_Cons, not be
4357 	 one of the unused cells in the current cons block,
4358 	 and not be on the free-list.  */
4359       if (0 <= offset && offset < CONS_BLOCK_SIZE * sizeof b->conses[0]
4360 	  && (b != cons_block
4361 	      || offset / sizeof b->conses[0] < cons_block_index))
4362 	{
4363 	  cp = ptr_bounds_copy (cp, b);
4364 	  struct Lisp_Cons *s = p = cp -= offset % sizeof b->conses[0];
4365 	  if (!deadp (s->u.s.car))
4366 	    return make_lisp_ptr (s, Lisp_Cons);
4367 	}
4368     }
4369   return Qnil;
4370 }
4371 
4372 static bool
live_cons_p(struct mem_node * m,void * p)4373 live_cons_p (struct mem_node *m, void *p)
4374 {
4375   return !NILP (live_cons_holding (m, p));
4376 }
4377 
4378 
4379 /* If P is a pointer into a live Lisp symbol object on the heap,
4380    return the object.  Otherwise, return nil.  M is a pointer to the
4381    mem_block for P.  */
4382 
4383 static Lisp_Object
live_symbol_holding(struct mem_node * m,void * p)4384 live_symbol_holding (struct mem_node *m, void *p)
4385 {
4386   if (m->type == MEM_TYPE_SYMBOL)
4387     {
4388       struct symbol_block *b = m->start;
4389       char *cp = p;
4390       ptrdiff_t offset = cp - (char *) &b->symbols[0];
4391 
4392       /* P must point into the Lisp_Symbol, not be
4393 	 one of the unused cells in the current symbol block,
4394 	 and not be on the free-list.  */
4395       if (0 <= offset && offset < SYMBOL_BLOCK_SIZE * sizeof b->symbols[0]
4396 	  && (b != symbol_block
4397 	      || offset / sizeof b->symbols[0] < symbol_block_index))
4398 	{
4399 	  cp = ptr_bounds_copy (cp, b);
4400 	  struct Lisp_Symbol *s = p = cp -= offset % sizeof b->symbols[0];
4401 	  if (!deadp (s->u.s.function))
4402 	    return make_lisp_symbol (s);
4403 	}
4404     }
4405   return Qnil;
4406 }
4407 
4408 static bool
live_symbol_p(struct mem_node * m,void * p)4409 live_symbol_p (struct mem_node *m, void *p)
4410 {
4411   return !NILP (live_symbol_holding (m, p));
4412 }
4413 
4414 
4415 /* Return true if P is a pointer to a live Lisp float on
4416    the heap.  M is a pointer to the mem_block for P.  */
4417 
4418 static bool
live_float_p(struct mem_node * m,void * p)4419 live_float_p (struct mem_node *m, void *p)
4420 {
4421   if (m->type == MEM_TYPE_FLOAT)
4422     {
4423       struct float_block *b = m->start;
4424       char *cp = p;
4425       ptrdiff_t offset = cp - (char *) &b->floats[0];
4426 
4427       /* P must point to the start of a Lisp_Float and not be
4428 	 one of the unused cells in the current float block.  */
4429       return (offset >= 0
4430 	      && offset % sizeof b->floats[0] == 0
4431 	      && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
4432 	      && (b != float_block
4433 		  || offset / sizeof b->floats[0] < float_block_index));
4434     }
4435   else
4436     return 0;
4437 }
4438 
4439 /* If P is a pointer to a live vector-like object, return the object.
4440    Otherwise, return nil.
4441    M is a pointer to the mem_block for P.  */
4442 
4443 static Lisp_Object
live_vector_holding(struct mem_node * m,void * p)4444 live_vector_holding (struct mem_node *m, void *p)
4445 {
4446   struct Lisp_Vector *vp = p;
4447 
4448   if (m->type == MEM_TYPE_VECTOR_BLOCK)
4449     {
4450       /* This memory node corresponds to a vector block.  */
4451       struct vector_block *block = m->start;
4452       struct Lisp_Vector *vector = (struct Lisp_Vector *) block->data;
4453 
4454       /* P is in the block's allocation range.  Scan the block
4455 	 up to P and see whether P points to the start of some
4456 	 vector which is not on a free list.  FIXME: check whether
4457 	 some allocation patterns (probably a lot of short vectors)
4458 	 may cause a substantial overhead of this loop.  */
4459       while (VECTOR_IN_BLOCK (vector, block) && vector <= vp)
4460 	{
4461 	  struct Lisp_Vector *next = ADVANCE (vector, vector_nbytes (vector));
4462 	  if (vp < next && !PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FREE))
4463 	    return make_lisp_ptr (vector, Lisp_Vectorlike);
4464 	  vector = next;
4465 	}
4466     }
4467   else if (m->type == MEM_TYPE_VECTORLIKE)
4468     {
4469       /* This memory node corresponds to a large vector.  */
4470       struct Lisp_Vector *vector = large_vector_vec (m->start);
4471       struct Lisp_Vector *next = ADVANCE (vector, vector_nbytes (vector));
4472       if (vector <= vp && vp < next)
4473 	return make_lisp_ptr (vector, Lisp_Vectorlike);
4474     }
4475   return Qnil;
4476 }
4477 
4478 static bool
live_vector_p(struct mem_node * m,void * p)4479 live_vector_p (struct mem_node *m, void *p)
4480 {
4481   return !NILP (live_vector_holding (m, p));
4482 }
4483 
4484 /* If P is a pointer into a live buffer, return the buffer.
4485    Otherwise, return nil.  M is a pointer to the mem_block for P.  */
4486 
4487 static Lisp_Object
live_buffer_holding(struct mem_node * m,void * p)4488 live_buffer_holding (struct mem_node *m, void *p)
4489 {
4490   /* P must point into the block, and the buffer
4491      must not have been killed.  */
4492   if (m->type == MEM_TYPE_BUFFER)
4493     {
4494       struct buffer *b = m->start;
4495       char *cb = m->start;
4496       char *cp = p;
4497       ptrdiff_t offset = cp - cb;
4498       if (0 <= offset && offset < sizeof *b && !NILP (b->name_))
4499 	{
4500 	  Lisp_Object obj;
4501 	  XSETBUFFER (obj, b);
4502 	  return obj;
4503 	}
4504     }
4505   return Qnil;
4506 }
4507 
4508 static bool
live_buffer_p(struct mem_node * m,void * p)4509 live_buffer_p (struct mem_node *m, void *p)
4510 {
4511   return !NILP (live_buffer_holding (m, p));
4512 }
4513 
4514 /* Mark OBJ if we can prove it's a Lisp_Object.  */
4515 
4516 static void
mark_maybe_object(Lisp_Object obj)4517 mark_maybe_object (Lisp_Object obj)
4518 {
4519 #if USE_VALGRIND
4520   VALGRIND_MAKE_MEM_DEFINED (&obj, sizeof (obj));
4521 #endif
4522 
4523   if (FIXNUMP (obj))
4524     return;
4525 
4526   void *po = XPNTR (obj);
4527 
4528   /* If the pointer is in the dump image and the dump has a record
4529      of the object starting at the place where the pointer points, we
4530      definitely have an object.  If the pointer is in the dump image
4531      and the dump has no idea what the pointer is pointing at, we
4532      definitely _don't_ have an object.  */
4533   if (pdumper_object_p (po))
4534     {
4535       /* Don't use pdumper_object_p_precise here! It doesn't check the
4536          tag bits. OBJ here might be complete garbage, so we need to
4537          verify both the pointer and the tag.  */
4538       if (XTYPE (obj) == pdumper_find_object_type (po))
4539         mark_object (obj);
4540       return;
4541     }
4542 
4543   struct mem_node *m = mem_find (po);
4544 
4545   if (m != MEM_NIL)
4546     {
4547       bool mark_p = false;
4548 
4549       switch (XTYPE (obj))
4550 	{
4551 	case Lisp_String:
4552 	  mark_p = EQ (obj, live_string_holding (m, po));
4553 	  break;
4554 
4555 	case Lisp_Cons:
4556 	  mark_p = EQ (obj, live_cons_holding (m, po));
4557 	  break;
4558 
4559 	case Lisp_Symbol:
4560 	  mark_p = EQ (obj, live_symbol_holding (m, po));
4561 	  break;
4562 
4563 	case Lisp_Float:
4564 	  mark_p = live_float_p (m, po);
4565 	  break;
4566 
4567 	case Lisp_Vectorlike:
4568 	  mark_p = (EQ (obj, live_vector_holding (m, po))
4569 		    || EQ (obj, live_buffer_holding (m, po)));
4570 	  break;
4571 
4572 	default:
4573 	  break;
4574 	}
4575 
4576       if (mark_p)
4577 	mark_object (obj);
4578     }
4579 }
4580 
4581 void
mark_maybe_objects(Lisp_Object const * array,ptrdiff_t nelts)4582 mark_maybe_objects (Lisp_Object const *array, ptrdiff_t nelts)
4583 {
4584   for (Lisp_Object const *lim = array + nelts; array < lim; array++)
4585     mark_maybe_object (*array);
4586 }
4587 
4588 /* If P points to Lisp data, mark that as live if it isn't already
4589    marked.  */
4590 
4591 static void
mark_maybe_pointer(void * p)4592 mark_maybe_pointer (void *p)
4593 {
4594   struct mem_node *m;
4595 
4596 #ifdef USE_VALGRIND
4597   VALGRIND_MAKE_MEM_DEFINED (&p, sizeof (p));
4598 #endif
4599 
4600   if (pdumper_object_p (p))
4601     {
4602       int type = pdumper_find_object_type (p);
4603       if (pdumper_valid_object_type_p (type))
4604         mark_object (type == Lisp_Symbol
4605                      ? make_lisp_symbol (p)
4606                      : make_lisp_ptr (p, type));
4607       /* See mark_maybe_object for why we can confidently return.  */
4608       return;
4609     }
4610 
4611   m = mem_find (p);
4612   if (m != MEM_NIL)
4613     {
4614       Lisp_Object obj = Qnil;
4615 
4616       switch (m->type)
4617 	{
4618 	case MEM_TYPE_NON_LISP:
4619 	case MEM_TYPE_SPARE:
4620 	  /* Nothing to do; not a pointer to Lisp memory.  */
4621 	  break;
4622 
4623 	case MEM_TYPE_BUFFER:
4624 	  obj = live_buffer_holding (m, p);
4625 	  break;
4626 
4627 	case MEM_TYPE_CONS:
4628 	  obj = live_cons_holding (m, p);
4629 	  break;
4630 
4631 	case MEM_TYPE_STRING:
4632 	  obj = live_string_holding (m, p);
4633 	  break;
4634 
4635 	case MEM_TYPE_SYMBOL:
4636 	  obj = live_symbol_holding (m, p);
4637 	  break;
4638 
4639 	case MEM_TYPE_FLOAT:
4640 	  if (live_float_p (m, p))
4641 	    obj = make_lisp_ptr (p, Lisp_Float);
4642 	  break;
4643 
4644 	case MEM_TYPE_VECTORLIKE:
4645 	case MEM_TYPE_VECTOR_BLOCK:
4646 	  obj = live_vector_holding (m, p);
4647 	  break;
4648 
4649 	default:
4650 	  emacs_abort ();
4651 	}
4652 
4653       if (!NILP (obj))
4654 	mark_object (obj);
4655     }
4656 }
4657 
4658 
4659 /* Alignment of pointer values.  Use alignof, as it sometimes returns
4660    a smaller alignment than GCC's __alignof__ and mark_memory might
4661    miss objects if __alignof__ were used.  */
4662 #define GC_POINTER_ALIGNMENT alignof (void *)
4663 
4664 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4665    or END+OFFSET..START.  */
4666 
4667 static void ATTRIBUTE_NO_SANITIZE_ADDRESS
mark_memory(void const * start,void const * end)4668 mark_memory (void const *start, void const *end)
4669 {
4670   char const *pp;
4671 
4672   /* Make START the pointer to the start of the memory region,
4673      if it isn't already.  */
4674   if (end < start)
4675     {
4676       void const *tem = start;
4677       start = end;
4678       end = tem;
4679     }
4680 
4681   eassert (((uintptr_t) start) % GC_POINTER_ALIGNMENT == 0);
4682 
4683   /* Mark Lisp data pointed to.  This is necessary because, in some
4684      situations, the C compiler optimizes Lisp objects away, so that
4685      only a pointer to them remains.  Example:
4686 
4687      DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4688      ()
4689      {
4690        Lisp_Object obj = build_string ("test");
4691        struct Lisp_String *s = XSTRING (obj);
4692        garbage_collect ();
4693        fprintf (stderr, "test '%s'\n", s->u.s.data);
4694        return Qnil;
4695      }
4696 
4697      Here, `obj' isn't really used, and the compiler optimizes it
4698      away.  The only reference to the life string is through the
4699      pointer `s'.  */
4700 
4701   for (pp = start; (void const *) pp < end; pp += GC_POINTER_ALIGNMENT)
4702     {
4703       char *p = *(char *const *) pp;
4704       mark_maybe_pointer (p);
4705 
4706       /* Unmask any struct Lisp_Symbol pointer that make_lisp_symbol
4707 	 previously disguised by adding the address of 'lispsym'.
4708 	 On a host with 32-bit pointers and 64-bit Lisp_Objects,
4709 	 a Lisp_Object might be split into registers saved into
4710 	 non-adjacent words and P might be the low-order word's value.  */
4711       p += (intptr_t) lispsym;
4712       mark_maybe_pointer (p);
4713 
4714       verify (alignof (Lisp_Object) % GC_POINTER_ALIGNMENT == 0);
4715       if (alignof (Lisp_Object) == GC_POINTER_ALIGNMENT
4716 	  || (uintptr_t) pp % alignof (Lisp_Object) == 0)
4717 	mark_maybe_object (*(Lisp_Object const *) pp);
4718     }
4719 }
4720 
4721 #ifndef HAVE___BUILTIN_UNWIND_INIT
4722 
4723 # ifdef GC_SETJMP_WORKS
4724 static void
test_setjmp(void)4725 test_setjmp (void)
4726 {
4727 }
4728 # else
4729 
4730 static bool setjmp_tested_p;
4731 static int longjmps_done;
4732 
4733 #  define SETJMP_WILL_LIKELY_WORK "\
4734 \n\
4735 Emacs garbage collector has been changed to use conservative stack\n\
4736 marking.  Emacs has determined that the method it uses to do the\n\
4737 marking will likely work on your system, but this isn't sure.\n\
4738 \n\
4739 If you are a system-programmer, or can get the help of a local wizard\n\
4740 who is, please take a look at the function mark_stack in alloc.c, and\n\
4741 verify that the methods used are appropriate for your system.\n\
4742 \n\
4743 Please mail the result to <emacs-devel@gnu.org>.\n\
4744 "
4745 
4746 #  define SETJMP_WILL_NOT_WORK "\
4747 \n\
4748 Emacs garbage collector has been changed to use conservative stack\n\
4749 marking.  Emacs has determined that the default method it uses to do the\n\
4750 marking will not work on your system.  We will need a system-dependent\n\
4751 solution for your system.\n\
4752 \n\
4753 Please take a look at the function mark_stack in alloc.c, and\n\
4754 try to find a way to make it work on your system.\n\
4755 \n\
4756 Note that you may get false negatives, depending on the compiler.\n\
4757 In particular, you need to use -O with GCC for this test.\n\
4758 \n\
4759 Please mail the result to <emacs-devel@gnu.org>.\n\
4760 "
4761 
4762 
4763 /* Perform a quick check if it looks like setjmp saves registers in a
4764    jmp_buf.  Print a message to stderr saying so.  When this test
4765    succeeds, this is _not_ a proof that setjmp is sufficient for
4766    conservative stack marking.  Only the sources or a disassembly
4767    can prove that.  */
4768 
4769 static void
test_setjmp(void)4770 test_setjmp (void)
4771 {
4772   if (setjmp_tested_p)
4773     return;
4774   setjmp_tested_p = true;
4775   char buf[10];
4776   register int x;
4777   sys_jmp_buf jbuf;
4778 
4779   /* Arrange for X to be put in a register.  */
4780   sprintf (buf, "1");
4781   x = strlen (buf);
4782   x = 2 * x - 1;
4783 
4784   sys_setjmp (jbuf);
4785   if (longjmps_done == 1)
4786     {
4787       /* Came here after the longjmp at the end of the function.
4788 
4789          If x == 1, the longjmp has restored the register to its
4790          value before the setjmp, and we can hope that setjmp
4791          saves all such registers in the jmp_buf, although that
4792 	 isn't sure.
4793 
4794          For other values of X, either something really strange is
4795          taking place, or the setjmp just didn't save the register.  */
4796 
4797       if (x == 1)
4798 	fputs (SETJMP_WILL_LIKELY_WORK, stderr);
4799       else
4800 	{
4801 	  fputs (SETJMP_WILL_NOT_WORK, stderr);
4802 	  exit (1);
4803 	}
4804     }
4805 
4806   ++longjmps_done;
4807   x = 2;
4808   if (longjmps_done == 1)
4809     sys_longjmp (jbuf, 1);
4810 }
4811 # endif /* ! GC_SETJMP_WORKS */
4812 #endif /* ! HAVE___BUILTIN_UNWIND_INIT */
4813 
4814 /* The type of an object near the stack top, whose address can be used
4815    as a stack scan limit.  */
4816 typedef union
4817 {
4818   /* Align the stack top properly.  Even if !HAVE___BUILTIN_UNWIND_INIT,
4819      jmp_buf may not be aligned enough on darwin-ppc64.  */
4820   max_align_t o;
4821 #ifndef HAVE___BUILTIN_UNWIND_INIT
4822   sys_jmp_buf j;
4823   char c;
4824 #endif
4825 } stacktop_sentry;
4826 
4827 /* Force callee-saved registers and register windows onto the stack.
4828    Use the platform-defined __builtin_unwind_init if available,
4829    obviating the need for machine dependent methods.  */
4830 #ifndef HAVE___BUILTIN_UNWIND_INIT
4831 # ifdef __sparc__
4832    /* This trick flushes the register windows so that all the state of
4833       the process is contained in the stack.
4834       FreeBSD does not have a ta 3 handler, so handle it specially.
4835       FIXME: Code in the Boehm GC suggests flushing (with 'flushrs') is
4836       needed on ia64 too.  See mach_dep.c, where it also says inline
4837       assembler doesn't work with relevant proprietary compilers.  */
4838 #  if defined __sparc64__ && defined __FreeBSD__
4839 #   define __builtin_unwind_init() asm ("flushw")
4840 #  else
4841 #   define __builtin_unwind_init() asm ("ta 3")
4842 #  endif
4843 # else
4844 #  define __builtin_unwind_init() ((void) 0)
4845 # endif
4846 #endif
4847 
4848 /* Yield an address close enough to the top of the stack that the
4849    garbage collector need not scan above it.  Callers should be
4850    declared NO_INLINE.  */
4851 #ifdef HAVE___BUILTIN_FRAME_ADDRESS
4852 # define NEAR_STACK_TOP(addr) ((void) (addr), __builtin_frame_address (0))
4853 #else
4854 # define NEAR_STACK_TOP(addr) (addr)
4855 #endif
4856 
4857 /* Set *P to the address of the top of the stack.  This must be a
4858    macro, not a function, so that it is executed in the caller's
4859    environment.  It is not inside a do-while so that its storage
4860    survives the macro.  Callers should be declared NO_INLINE.  */
4861 #ifdef HAVE___BUILTIN_UNWIND_INIT
4862 # define SET_STACK_TOP_ADDRESS(p)	\
4863    stacktop_sentry sentry;		\
4864    __builtin_unwind_init ();		\
4865    *(p) = NEAR_STACK_TOP (&sentry)
4866 #else
4867 # define SET_STACK_TOP_ADDRESS(p)		\
4868    stacktop_sentry sentry;			\
4869    __builtin_unwind_init ();			\
4870    test_setjmp ();				\
4871    sys_setjmp (sentry.j);			\
4872    *(p) = NEAR_STACK_TOP (&sentry + (stack_bottom < &sentry.c))
4873 #endif
4874 
4875 /* Mark live Lisp objects on the C stack.
4876 
4877    There are several system-dependent problems to consider when
4878    porting this to new architectures:
4879 
4880    Processor Registers
4881 
4882    We have to mark Lisp objects in CPU registers that can hold local
4883    variables or are used to pass parameters.
4884 
4885    This code assumes that calling setjmp saves registers we need
4886    to see in a jmp_buf which itself lies on the stack.  This doesn't
4887    have to be true!  It must be verified for each system, possibly
4888    by taking a look at the source code of setjmp.
4889 
4890    If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4891    can use it as a machine independent method to store all registers
4892    to the stack.  In this case the macros described in the previous
4893    two paragraphs are not used.
4894 
4895    Stack Layout
4896 
4897    Architectures differ in the way their processor stack is organized.
4898    For example, the stack might look like this
4899 
4900      +----------------+
4901      |  Lisp_Object   |  size = 4
4902      +----------------+
4903      | something else |  size = 2
4904      +----------------+
4905      |  Lisp_Object   |  size = 4
4906      +----------------+
4907      |	...	      |
4908 
4909    In such a case, not every Lisp_Object will be aligned equally.  To
4910    find all Lisp_Object on the stack it won't be sufficient to walk
4911    the stack in steps of 4 bytes.  Instead, two passes will be
4912    necessary, one starting at the start of the stack, and a second
4913    pass starting at the start of the stack + 2.  Likewise, if the
4914    minimal alignment of Lisp_Objects on the stack is 1, four passes
4915    would be necessary, each one starting with one byte more offset
4916    from the stack start.  */
4917 
4918 void
mark_stack(char const * bottom,char const * end)4919 mark_stack (char const *bottom, char const *end)
4920 {
4921   /* This assumes that the stack is a contiguous region in memory.  If
4922      that's not the case, something has to be done here to iterate
4923      over the stack segments.  */
4924   mark_memory (bottom, end);
4925 
4926   /* Allow for marking a secondary stack, like the register stack on the
4927      ia64.  */
4928 #ifdef GC_MARK_SECONDARY_STACK
4929   GC_MARK_SECONDARY_STACK ();
4930 #endif
4931 }
4932 
4933 /* This is a trampoline function that flushes registers to the stack,
4934    and then calls FUNC.  ARG is passed through to FUNC verbatim.
4935 
4936    This function must be called whenever Emacs is about to release the
4937    global interpreter lock.  This lets the garbage collector easily
4938    find roots in registers on threads that are not actively running
4939    Lisp.
4940 
4941    It is invalid to run any Lisp code or to allocate any GC memory
4942    from FUNC.  */
4943 
4944 NO_INLINE void
flush_stack_call_func(void (* func)(void * arg),void * arg)4945 flush_stack_call_func (void (*func) (void *arg), void *arg)
4946 {
4947   void *end;
4948   struct thread_state *self = current_thread;
4949   SET_STACK_TOP_ADDRESS (&end);
4950   self->stack_top = end;
4951   func (arg);
4952   eassert (current_thread == self);
4953 }
4954 
4955 /* Determine whether it is safe to access memory at address P.  */
4956 static int
valid_pointer_p(void * p)4957 valid_pointer_p (void *p)
4958 {
4959 #ifdef WINDOWSNT
4960   return w32_valid_pointer_p (p, 16);
4961 #else
4962 
4963   if (ADDRESS_SANITIZER)
4964     return p ? -1 : 0;
4965 
4966   int fd[2];
4967   static int under_rr_state;
4968 
4969   if (!under_rr_state)
4970     under_rr_state = getenv ("RUNNING_UNDER_RR") ? -1 : 1;
4971   if (under_rr_state < 0)
4972     return under_rr_state;
4973 
4974   /* Obviously, we cannot just access it (we would SEGV trying), so we
4975      trick the o/s to tell us whether p is a valid pointer.
4976      Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4977      not validate p in that case.  */
4978 
4979   if (emacs_pipe (fd) == 0)
4980     {
4981       bool valid = emacs_write (fd[1], p, 16) == 16;
4982       emacs_close (fd[1]);
4983       emacs_close (fd[0]);
4984       return valid;
4985     }
4986 
4987   return -1;
4988 #endif
4989 }
4990 
4991 /* Return 2 if OBJ is a killed or special buffer object, 1 if OBJ is a
4992    valid lisp object, 0 if OBJ is NOT a valid lisp object, or -1 if we
4993    cannot validate OBJ.  This function can be quite slow, and is used
4994    only in debugging.  */
4995 
4996 int
valid_lisp_object_p(Lisp_Object obj)4997 valid_lisp_object_p (Lisp_Object obj)
4998 {
4999   if (FIXNUMP (obj))
5000     return 1;
5001 
5002   void *p = XPNTR (obj);
5003   if (PURE_P (p))
5004     return 1;
5005 
5006   if (SYMBOLP (obj) && c_symbol_p (p))
5007     return ((char *) p - (char *) lispsym) % sizeof lispsym[0] == 0;
5008 
5009   if (p == &buffer_defaults || p == &buffer_local_symbols)
5010     return 2;
5011 
5012   if (pdumper_object_p (p))
5013     return pdumper_object_p_precise (p) ? 1 : 0;
5014 
5015   struct mem_node *m = mem_find (p);
5016 
5017   if (m == MEM_NIL)
5018     {
5019       int valid = valid_pointer_p (p);
5020       if (valid <= 0)
5021 	return valid;
5022 
5023       if (SUBRP (obj))
5024 	return 1;
5025 
5026       return 0;
5027     }
5028 
5029   switch (m->type)
5030     {
5031     case MEM_TYPE_NON_LISP:
5032     case MEM_TYPE_SPARE:
5033       return 0;
5034 
5035     case MEM_TYPE_BUFFER:
5036       return live_buffer_p (m, p) ? 1 : 2;
5037 
5038     case MEM_TYPE_CONS:
5039       return live_cons_p (m, p);
5040 
5041     case MEM_TYPE_STRING:
5042       return live_string_p (m, p);
5043 
5044     case MEM_TYPE_SYMBOL:
5045       return live_symbol_p (m, p);
5046 
5047     case MEM_TYPE_FLOAT:
5048       return live_float_p (m, p);
5049 
5050     case MEM_TYPE_VECTORLIKE:
5051     case MEM_TYPE_VECTOR_BLOCK:
5052       return live_vector_p (m, p);
5053 
5054     default:
5055       break;
5056     }
5057 
5058   return 0;
5059 }
5060 
5061 /***********************************************************************
5062 		       Pure Storage Management
5063  ***********************************************************************/
5064 
5065 /* Allocate room for SIZE bytes from pure Lisp storage and return a
5066    pointer to it.  TYPE is the Lisp type for which the memory is
5067    allocated.  TYPE < 0 means it's not used for a Lisp object,
5068    and that the result should have an alignment of -TYPE.
5069 
5070    The bytes are initially zero.
5071 
5072    If pure space is exhausted, allocate space from the heap.  This is
5073    merely an expedient to let Emacs warn that pure space was exhausted
5074    and that Emacs should be rebuilt with a larger pure space.  */
5075 
5076 static void *
pure_alloc(size_t size,int type)5077 pure_alloc (size_t size, int type)
5078 {
5079   void *result;
5080 
5081  again:
5082   if (type >= 0)
5083     {
5084       /* Allocate space for a Lisp object from the beginning of the free
5085 	 space with taking account of alignment.  */
5086       result = pointer_align (purebeg + pure_bytes_used_lisp, LISP_ALIGNMENT);
5087       pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
5088     }
5089   else
5090     {
5091       /* Allocate space for a non-Lisp object from the end of the free
5092 	 space.  */
5093       ptrdiff_t unaligned_non_lisp = pure_bytes_used_non_lisp + size;
5094       char *unaligned = purebeg + pure_size - unaligned_non_lisp;
5095       int decr = (intptr_t) unaligned & (-1 - type);
5096       pure_bytes_used_non_lisp = unaligned_non_lisp + decr;
5097       result = unaligned - decr;
5098     }
5099   pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
5100 
5101   if (pure_bytes_used <= pure_size)
5102     return ptr_bounds_clip (result, size);
5103 
5104   /* Don't allocate a large amount here,
5105      because it might get mmap'd and then its address
5106      might not be usable.  */
5107   int small_amount = 10000;
5108   eassert (size <= small_amount - LISP_ALIGNMENT);
5109   purebeg = xzalloc (small_amount);
5110   pure_size = small_amount;
5111   pure_bytes_used_before_overflow += pure_bytes_used - size;
5112   pure_bytes_used = 0;
5113   pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
5114 
5115   /* Can't GC if pure storage overflowed because we can't determine
5116      if something is a pure object or not.  */
5117   garbage_collection_inhibited++;
5118   goto again;
5119 }
5120 
5121 
5122 #ifdef HAVE_UNEXEC
5123 
5124 /* Print a warning if PURESIZE is too small.  */
5125 
5126 void
check_pure_size(void)5127 check_pure_size (void)
5128 {
5129   if (pure_bytes_used_before_overflow)
5130     message (("emacs:0:Pure Lisp storage overflow (approx. %"pI"d"
5131 	      " bytes needed)"),
5132 	     pure_bytes_used + pure_bytes_used_before_overflow);
5133 }
5134 #endif
5135 
5136 
5137 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
5138    the non-Lisp data pool of the pure storage, and return its start
5139    address.  Return NULL if not found.  */
5140 
5141 static char *
find_string_data_in_pure(const char * data,ptrdiff_t nbytes)5142 find_string_data_in_pure (const char *data, ptrdiff_t nbytes)
5143 {
5144   int i;
5145   ptrdiff_t skip, bm_skip[256], last_char_skip, infinity, start, start_max;
5146   const unsigned char *p;
5147   char *non_lisp_beg;
5148 
5149   if (pure_bytes_used_non_lisp <= nbytes)
5150     return NULL;
5151 
5152   /* Set up the Boyer-Moore table.  */
5153   skip = nbytes + 1;
5154   for (i = 0; i < 256; i++)
5155     bm_skip[i] = skip;
5156 
5157   p = (const unsigned char *) data;
5158   while (--skip > 0)
5159     bm_skip[*p++] = skip;
5160 
5161   last_char_skip = bm_skip['\0'];
5162 
5163   non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
5164   start_max = pure_bytes_used_non_lisp - (nbytes + 1);
5165 
5166   /* See the comments in the function `boyer_moore' (search.c) for the
5167      use of `infinity'.  */
5168   infinity = pure_bytes_used_non_lisp + 1;
5169   bm_skip['\0'] = infinity;
5170 
5171   p = (const unsigned char *) non_lisp_beg + nbytes;
5172   start = 0;
5173   do
5174     {
5175       /* Check the last character (== '\0').  */
5176       do
5177 	{
5178 	  start += bm_skip[*(p + start)];
5179 	}
5180       while (start <= start_max);
5181 
5182       if (start < infinity)
5183 	/* Couldn't find the last character.  */
5184 	return NULL;
5185 
5186       /* No less than `infinity' means we could find the last
5187 	 character at `p[start - infinity]'.  */
5188       start -= infinity;
5189 
5190       /* Check the remaining characters.  */
5191       if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
5192 	/* Found.  */
5193 	return ptr_bounds_clip (non_lisp_beg + start, nbytes + 1);
5194 
5195       start += last_char_skip;
5196     }
5197   while (start <= start_max);
5198 
5199   return NULL;
5200 }
5201 
5202 
5203 /* Return a string allocated in pure space.  DATA is a buffer holding
5204    NCHARS characters, and NBYTES bytes of string data.  MULTIBYTE
5205    means make the result string multibyte.
5206 
5207    Must get an error if pure storage is full, since if it cannot hold
5208    a large string it may be able to hold conses that point to that
5209    string; then the string is not protected from gc.  */
5210 
5211 Lisp_Object
make_pure_string(const char * data,ptrdiff_t nchars,ptrdiff_t nbytes,bool multibyte)5212 make_pure_string (const char *data,
5213 		  ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
5214 {
5215   Lisp_Object string;
5216   struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5217   s->u.s.data = (unsigned char *) find_string_data_in_pure (data, nbytes);
5218   if (s->u.s.data == NULL)
5219     {
5220       s->u.s.data = pure_alloc (nbytes + 1, -1);
5221       memcpy (s->u.s.data, data, nbytes);
5222       s->u.s.data[nbytes] = '\0';
5223     }
5224   s->u.s.size = nchars;
5225   s->u.s.size_byte = multibyte ? nbytes : -1;
5226   s->u.s.intervals = NULL;
5227   XSETSTRING (string, s);
5228   return string;
5229 }
5230 
5231 /* Return a string allocated in pure space.  Do not
5232    allocate the string data, just point to DATA.  */
5233 
5234 Lisp_Object
make_pure_c_string(const char * data,ptrdiff_t nchars)5235 make_pure_c_string (const char *data, ptrdiff_t nchars)
5236 {
5237   Lisp_Object string;
5238   struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5239   s->u.s.size = nchars;
5240   s->u.s.size_byte = -2;
5241   s->u.s.data = (unsigned char *) data;
5242   s->u.s.intervals = NULL;
5243   XSETSTRING (string, s);
5244   return string;
5245 }
5246 
5247 static Lisp_Object purecopy (Lisp_Object obj);
5248 
5249 /* Return a cons allocated from pure space.  Give it pure copies
5250    of CAR as car and CDR as cdr.  */
5251 
5252 Lisp_Object
pure_cons(Lisp_Object car,Lisp_Object cdr)5253 pure_cons (Lisp_Object car, Lisp_Object cdr)
5254 {
5255   Lisp_Object new;
5256   struct Lisp_Cons *p = pure_alloc (sizeof *p, Lisp_Cons);
5257   XSETCONS (new, p);
5258   XSETCAR (new, purecopy (car));
5259   XSETCDR (new, purecopy (cdr));
5260   return new;
5261 }
5262 
5263 
5264 /* Value is a float object with value NUM allocated from pure space.  */
5265 
5266 static Lisp_Object
make_pure_float(double num)5267 make_pure_float (double num)
5268 {
5269   Lisp_Object new;
5270   struct Lisp_Float *p = pure_alloc (sizeof *p, Lisp_Float);
5271   XSETFLOAT (new, p);
5272   XFLOAT_INIT (new, num);
5273   return new;
5274 }
5275 
5276 /* Value is a bignum object with value VALUE allocated from pure
5277    space.  */
5278 
5279 static Lisp_Object
make_pure_bignum(Lisp_Object value)5280 make_pure_bignum (Lisp_Object value)
5281 {
5282   mpz_t const *n = xbignum_val (value);
5283   size_t i, nlimbs = mpz_size (*n);
5284   size_t nbytes = nlimbs * sizeof (mp_limb_t);
5285   mp_limb_t *pure_limbs;
5286   mp_size_t new_size;
5287 
5288   struct Lisp_Bignum *b = pure_alloc (sizeof *b, Lisp_Vectorlike);
5289   XSETPVECTYPESIZE (b, PVEC_BIGNUM, 0, VECSIZE (struct Lisp_Bignum));
5290 
5291   int limb_alignment = alignof (mp_limb_t);
5292   pure_limbs = pure_alloc (nbytes, - limb_alignment);
5293   for (i = 0; i < nlimbs; ++i)
5294     pure_limbs[i] = mpz_getlimbn (*n, i);
5295 
5296   new_size = nlimbs;
5297   if (mpz_sgn (*n) < 0)
5298     new_size = -new_size;
5299 
5300   mpz_roinit_n (b->value, pure_limbs, new_size);
5301 
5302   return make_lisp_ptr (b, Lisp_Vectorlike);
5303 }
5304 
5305 /* Return a vector with room for LEN Lisp_Objects allocated from
5306    pure space.  */
5307 
5308 static Lisp_Object
make_pure_vector(ptrdiff_t len)5309 make_pure_vector (ptrdiff_t len)
5310 {
5311   Lisp_Object new;
5312   size_t size = header_size + len * word_size;
5313   struct Lisp_Vector *p = pure_alloc (size, Lisp_Vectorlike);
5314   XSETVECTOR (new, p);
5315   XVECTOR (new)->header.size = len;
5316   return new;
5317 }
5318 
5319 /* Copy all contents and parameters of TABLE to a new table allocated
5320    from pure space, return the purified table.  */
5321 static struct Lisp_Hash_Table *
purecopy_hash_table(struct Lisp_Hash_Table * table)5322 purecopy_hash_table (struct Lisp_Hash_Table *table)
5323 {
5324   eassert (NILP (table->weak));
5325   eassert (table->purecopy);
5326 
5327   struct Lisp_Hash_Table *pure = pure_alloc (sizeof *pure, Lisp_Vectorlike);
5328   struct hash_table_test pure_test = table->test;
5329 
5330   /* Purecopy the hash table test.  */
5331   pure_test.name = purecopy (table->test.name);
5332   pure_test.user_hash_function = purecopy (table->test.user_hash_function);
5333   pure_test.user_cmp_function = purecopy (table->test.user_cmp_function);
5334 
5335   pure->header = table->header;
5336   pure->weak = purecopy (Qnil);
5337   pure->hash = purecopy (table->hash);
5338   pure->next = purecopy (table->next);
5339   pure->index = purecopy (table->index);
5340   pure->count = table->count;
5341   pure->next_free = table->next_free;
5342   pure->purecopy = table->purecopy;
5343   eassert (!pure->mutable);
5344   pure->rehash_threshold = table->rehash_threshold;
5345   pure->rehash_size = table->rehash_size;
5346   pure->key_and_value = purecopy (table->key_and_value);
5347   pure->test = pure_test;
5348 
5349   return pure;
5350 }
5351 
5352 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
5353        doc: /* Make a copy of object OBJ in pure storage.
5354 Recursively copies contents of vectors and cons cells.
5355 Does not copy symbols.  Copies strings without text properties.  */)
5356   (register Lisp_Object obj)
5357 {
5358   if (NILP (Vpurify_flag))
5359     return obj;
5360   else if (MARKERP (obj) || OVERLAYP (obj) || SYMBOLP (obj))
5361     /* Can't purify those.  */
5362     return obj;
5363   else
5364     return purecopy (obj);
5365 }
5366 
5367 /* Pinned objects are marked before every GC cycle.  */
5368 static struct pinned_object
5369 {
5370   Lisp_Object object;
5371   struct pinned_object *next;
5372 } *pinned_objects;
5373 
5374 static Lisp_Object
purecopy(Lisp_Object obj)5375 purecopy (Lisp_Object obj)
5376 {
5377   if (FIXNUMP (obj)
5378       || (! SYMBOLP (obj) && PURE_P (XPNTR (obj)))
5379       || SUBRP (obj))
5380     return obj;    /* Already pure.  */
5381 
5382   if (STRINGP (obj) && XSTRING (obj)->u.s.intervals)
5383     message_with_string ("Dropping text-properties while making string `%s' pure",
5384 			 obj, true);
5385 
5386   if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing.  */
5387     {
5388       Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
5389       if (!NILP (tmp))
5390 	return tmp;
5391     }
5392 
5393   if (CONSP (obj))
5394     obj = pure_cons (XCAR (obj), XCDR (obj));
5395   else if (FLOATP (obj))
5396     obj = make_pure_float (XFLOAT_DATA (obj));
5397   else if (STRINGP (obj))
5398     obj = make_pure_string (SSDATA (obj), SCHARS (obj),
5399 			    SBYTES (obj),
5400 			    STRING_MULTIBYTE (obj));
5401   else if (HASH_TABLE_P (obj))
5402     {
5403       struct Lisp_Hash_Table *table = XHASH_TABLE (obj);
5404       /* Do not purify hash tables which haven't been defined with
5405          :purecopy as non-nil or are weak - they aren't guaranteed to
5406          not change.  */
5407       if (!NILP (table->weak) || !table->purecopy)
5408         {
5409           /* Instead, add the hash table to the list of pinned objects,
5410              so that it will be marked during GC.  */
5411           struct pinned_object *o = xmalloc (sizeof *o);
5412           o->object = obj;
5413           o->next = pinned_objects;
5414           pinned_objects = o;
5415           return obj; /* Don't hash cons it.  */
5416         }
5417 
5418       struct Lisp_Hash_Table *h = purecopy_hash_table (table);
5419       XSET_HASH_TABLE (obj, h);
5420     }
5421   else if (COMPILEDP (obj) || VECTORP (obj) || RECORDP (obj))
5422     {
5423       struct Lisp_Vector *objp = XVECTOR (obj);
5424       ptrdiff_t nbytes = vector_nbytes (objp);
5425       struct Lisp_Vector *vec = pure_alloc (nbytes, Lisp_Vectorlike);
5426       register ptrdiff_t i;
5427       ptrdiff_t size = ASIZE (obj);
5428       if (size & PSEUDOVECTOR_FLAG)
5429 	size &= PSEUDOVECTOR_SIZE_MASK;
5430       memcpy (vec, objp, nbytes);
5431       for (i = 0; i < size; i++)
5432 	vec->contents[i] = purecopy (vec->contents[i]);
5433       XSETVECTOR (obj, vec);
5434     }
5435   else if (SYMBOLP (obj))
5436     {
5437       if (!XSYMBOL (obj)->u.s.pinned && !c_symbol_p (XSYMBOL (obj)))
5438 	{ /* We can't purify them, but they appear in many pure objects.
5439 	     Mark them as `pinned' so we know to mark them at every GC cycle.  */
5440 	  XSYMBOL (obj)->u.s.pinned = true;
5441 	  symbol_block_pinned = symbol_block;
5442 	}
5443       /* Don't hash-cons it.  */
5444       return obj;
5445     }
5446   else if (BIGNUMP (obj))
5447     obj = make_pure_bignum (obj);
5448   else
5449     {
5450       AUTO_STRING (fmt, "Don't know how to purify: %S");
5451       Fsignal (Qerror, list1 (CALLN (Fformat, fmt, obj)));
5452     }
5453 
5454   if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing.  */
5455     Fputhash (obj, obj, Vpurify_flag);
5456 
5457   return obj;
5458 }
5459 
5460 
5461 
5462 /***********************************************************************
5463 			  Protection from GC
5464  ***********************************************************************/
5465 
5466 /* Put an entry in staticvec, pointing at the variable with address
5467    VARADDRESS.  */
5468 
5469 void
staticpro(Lisp_Object const * varaddress)5470 staticpro (Lisp_Object const *varaddress)
5471 {
5472   for (int i = 0; i < staticidx; i++)
5473     eassert (staticvec[i] != varaddress);
5474   if (staticidx >= NSTATICS)
5475     fatal ("NSTATICS too small; try increasing and recompiling Emacs.");
5476   staticvec[staticidx++] = varaddress;
5477 }
5478 
5479 
5480 /***********************************************************************
5481 			  Protection from GC
5482  ***********************************************************************/
5483 
5484 /* Temporarily prevent garbage collection.  Temporarily bump
5485    consing_until_gc to speed up maybe_gc when GC is inhibited.  */
5486 
5487 static void
allow_garbage_collection(intmax_t consing)5488 allow_garbage_collection (intmax_t consing)
5489 {
5490   consing_until_gc = consing - (HI_THRESHOLD - consing_until_gc);
5491   garbage_collection_inhibited--;
5492 }
5493 
5494 ptrdiff_t
inhibit_garbage_collection(void)5495 inhibit_garbage_collection (void)
5496 {
5497   ptrdiff_t count = SPECPDL_INDEX ();
5498   record_unwind_protect_intmax (allow_garbage_collection, consing_until_gc);
5499   garbage_collection_inhibited++;
5500   consing_until_gc = HI_THRESHOLD;
5501   return count;
5502 }
5503 
5504 /* Return the number of bytes in N objects each of size S, guarding
5505    against overflow if size_t is narrower than byte_ct.  */
5506 
5507 static byte_ct
object_bytes(object_ct n,size_t s)5508 object_bytes (object_ct n, size_t s)
5509 {
5510   byte_ct b = s;
5511   return n * b;
5512 }
5513 
5514 /* Calculate total bytes of live objects.  */
5515 
5516 static byte_ct
total_bytes_of_live_objects(void)5517 total_bytes_of_live_objects (void)
5518 {
5519   byte_ct tot = 0;
5520   tot += object_bytes (gcstat.total_conses, sizeof (struct Lisp_Cons));
5521   tot += object_bytes (gcstat.total_symbols, sizeof (struct Lisp_Symbol));
5522   tot += gcstat.total_string_bytes;
5523   tot += object_bytes (gcstat.total_vector_slots, word_size);
5524   tot += object_bytes (gcstat.total_floats, sizeof (struct Lisp_Float));
5525   tot += object_bytes (gcstat.total_intervals, sizeof (struct interval));
5526   tot += object_bytes (gcstat.total_strings, sizeof (struct Lisp_String));
5527   return tot;
5528 }
5529 
5530 #ifdef HAVE_WINDOW_SYSTEM
5531 
5532 /* Remove unmarked font-spec and font-entity objects from ENTRY, which is
5533    (DRIVER-TYPE NUM-FRAMES FONT-CACHE-DATA ...), and return changed entry.  */
5534 
5535 static Lisp_Object
compact_font_cache_entry(Lisp_Object entry)5536 compact_font_cache_entry (Lisp_Object entry)
5537 {
5538   Lisp_Object tail, *prev = &entry;
5539 
5540   for (tail = entry; CONSP (tail); tail = XCDR (tail))
5541     {
5542       bool drop = 0;
5543       Lisp_Object obj = XCAR (tail);
5544 
5545       /* Consider OBJ if it is (font-spec . [font-entity font-entity ...]).  */
5546       if (CONSP (obj) && GC_FONT_SPEC_P (XCAR (obj))
5547 	  && !vectorlike_marked_p (&GC_XFONT_SPEC (XCAR (obj))->header)
5548 	  /* Don't use VECTORP here, as that calls ASIZE, which could
5549 	     hit assertion violation during GC.  */
5550 	  && (VECTORLIKEP (XCDR (obj))
5551 	      && ! (gc_asize (XCDR (obj)) & PSEUDOVECTOR_FLAG)))
5552 	{
5553 	  ptrdiff_t i, size = gc_asize (XCDR (obj));
5554 	  Lisp_Object obj_cdr = XCDR (obj);
5555 
5556 	  /* If font-spec is not marked, most likely all font-entities
5557 	     are not marked too.  But we must be sure that nothing is
5558 	     marked within OBJ before we really drop it.  */
5559 	  for (i = 0; i < size; i++)
5560             {
5561               Lisp_Object objlist;
5562 
5563               if (vectorlike_marked_p (
5564                     &GC_XFONT_ENTITY (AREF (obj_cdr, i))->header))
5565                 break;
5566 
5567               objlist = AREF (AREF (obj_cdr, i), FONT_OBJLIST_INDEX);
5568               for (; CONSP (objlist); objlist = XCDR (objlist))
5569                 {
5570                   Lisp_Object val = XCAR (objlist);
5571                   struct font *font = GC_XFONT_OBJECT (val);
5572 
5573                   if (!NILP (AREF (val, FONT_TYPE_INDEX))
5574                       && vectorlike_marked_p(&font->header))
5575                     break;
5576                 }
5577               if (CONSP (objlist))
5578 		{
5579 		  /* Found a marked font, bail out.  */
5580 		  break;
5581 		}
5582             }
5583 
5584 	  if (i == size)
5585 	    {
5586 	      /* No marked fonts were found, so this entire font
5587 		 entity can be dropped.  */
5588 	      drop = 1;
5589 	    }
5590 	}
5591       if (drop)
5592 	*prev = XCDR (tail);
5593       else
5594 	prev = xcdr_addr (tail);
5595     }
5596   return entry;
5597 }
5598 
5599 /* Compact font caches on all terminals and mark
5600    everything which is still here after compaction.  */
5601 
5602 static void
compact_font_caches(void)5603 compact_font_caches (void)
5604 {
5605   struct terminal *t;
5606 
5607   for (t = terminal_list; t; t = t->next_terminal)
5608     {
5609       Lisp_Object cache = TERMINAL_FONT_CACHE (t);
5610       /* Inhibit compacting the caches if the user so wishes.  Some of
5611 	 the users don't mind a larger memory footprint, but do mind
5612 	 slower redisplay.  */
5613       if (!inhibit_compacting_font_caches
5614 	  && CONSP (cache))
5615 	{
5616 	  Lisp_Object entry;
5617 
5618 	  for (entry = XCDR (cache); CONSP (entry); entry = XCDR (entry))
5619 	    XSETCAR (entry, compact_font_cache_entry (XCAR (entry)));
5620 	}
5621       mark_object (cache);
5622     }
5623 }
5624 
5625 #else /* not HAVE_WINDOW_SYSTEM */
5626 
5627 #define compact_font_caches() (void)(0)
5628 
5629 #endif /* HAVE_WINDOW_SYSTEM */
5630 
5631 /* Remove (MARKER . DATA) entries with unmarked MARKER
5632    from buffer undo LIST and return changed list.  */
5633 
5634 static Lisp_Object
compact_undo_list(Lisp_Object list)5635 compact_undo_list (Lisp_Object list)
5636 {
5637   Lisp_Object tail, *prev = &list;
5638 
5639   for (tail = list; CONSP (tail); tail = XCDR (tail))
5640     {
5641       if (CONSP (XCAR (tail))
5642 	  && MARKERP (XCAR (XCAR (tail)))
5643 	  && !vectorlike_marked_p (&XMARKER (XCAR (XCAR (tail)))->header))
5644 	*prev = XCDR (tail);
5645       else
5646 	prev = xcdr_addr (tail);
5647     }
5648   return list;
5649 }
5650 
5651 static void
mark_pinned_objects(void)5652 mark_pinned_objects (void)
5653 {
5654   for (struct pinned_object *pobj = pinned_objects; pobj; pobj = pobj->next)
5655     mark_object (pobj->object);
5656 }
5657 
5658 static void
mark_pinned_symbols(void)5659 mark_pinned_symbols (void)
5660 {
5661   struct symbol_block *sblk;
5662   int lim = (symbol_block_pinned == symbol_block
5663 	     ? symbol_block_index : SYMBOL_BLOCK_SIZE);
5664 
5665   for (sblk = symbol_block_pinned; sblk; sblk = sblk->next)
5666     {
5667       struct Lisp_Symbol *sym = sblk->symbols, *end = sym + lim;
5668       for (; sym < end; ++sym)
5669 	if (sym->u.s.pinned)
5670 	  mark_object (make_lisp_symbol (sym));
5671 
5672       lim = SYMBOL_BLOCK_SIZE;
5673     }
5674 }
5675 
5676 static void
visit_vectorlike_root(struct gc_root_visitor visitor,struct Lisp_Vector * ptr,enum gc_root_type type)5677 visit_vectorlike_root (struct gc_root_visitor visitor,
5678                        struct Lisp_Vector *ptr,
5679                        enum gc_root_type type)
5680 {
5681   ptrdiff_t size = ptr->header.size;
5682   ptrdiff_t i;
5683 
5684   if (size & PSEUDOVECTOR_FLAG)
5685     size &= PSEUDOVECTOR_SIZE_MASK;
5686   for (i = 0; i < size; i++)
5687     visitor.visit (&ptr->contents[i], type, visitor.data);
5688 }
5689 
5690 static void
visit_buffer_root(struct gc_root_visitor visitor,struct buffer * buffer,enum gc_root_type type)5691 visit_buffer_root (struct gc_root_visitor visitor,
5692                    struct buffer *buffer,
5693                    enum gc_root_type type)
5694 {
5695   /* Buffers that are roots don't have intervals, an undo list, or
5696      other constructs that real buffers have.  */
5697   eassert (buffer->base_buffer == NULL);
5698   eassert (buffer->overlays_before == NULL);
5699   eassert (buffer->overlays_after == NULL);
5700 
5701   /* Visit the buffer-locals.  */
5702   visit_vectorlike_root (visitor, (struct Lisp_Vector *) buffer, type);
5703 }
5704 
5705 /* Visit GC roots stored in the Emacs data section.  Used by both core
5706    GC and by the portable dumping code.
5707 
5708    There are other GC roots of course, but these roots are dynamic
5709    runtime data structures that pdump doesn't care about and so we can
5710    continue to mark those directly in garbage_collect.  */
5711 void
visit_static_gc_roots(struct gc_root_visitor visitor)5712 visit_static_gc_roots (struct gc_root_visitor visitor)
5713 {
5714   visit_buffer_root (visitor,
5715                      &buffer_defaults,
5716                      GC_ROOT_BUFFER_LOCAL_DEFAULT);
5717   visit_buffer_root (visitor,
5718                      &buffer_local_symbols,
5719                      GC_ROOT_BUFFER_LOCAL_NAME);
5720 
5721   for (int i = 0; i < ARRAYELTS (lispsym); i++)
5722     {
5723       Lisp_Object sptr = builtin_lisp_symbol (i);
5724       visitor.visit (&sptr, GC_ROOT_C_SYMBOL, visitor.data);
5725     }
5726 
5727   for (int i = 0; i < staticidx; i++)
5728     visitor.visit (staticvec[i], GC_ROOT_STATICPRO, visitor.data);
5729 }
5730 
5731 static void
mark_object_root_visitor(Lisp_Object const * root_ptr,enum gc_root_type type,void * data)5732 mark_object_root_visitor (Lisp_Object const *root_ptr,
5733                           enum gc_root_type type,
5734                           void *data)
5735 {
5736   mark_object (*root_ptr);
5737 }
5738 
5739 /* List of weak hash tables we found during marking the Lisp heap.
5740    NULL on entry to garbage_collect and after it returns.  */
5741 static struct Lisp_Hash_Table *weak_hash_tables;
5742 
5743 NO_INLINE /* For better stack traces */
5744 static void
mark_and_sweep_weak_table_contents(void)5745 mark_and_sweep_weak_table_contents (void)
5746 {
5747   struct Lisp_Hash_Table *h;
5748   bool marked;
5749 
5750   /* Mark all keys and values that are in use.  Keep on marking until
5751      there is no more change.  This is necessary for cases like
5752      value-weak table A containing an entry X -> Y, where Y is used in a
5753      key-weak table B, Z -> Y.  If B comes after A in the list of weak
5754      tables, X -> Y might be removed from A, although when looking at B
5755      one finds that it shouldn't.  */
5756   do
5757     {
5758       marked = false;
5759       for (h = weak_hash_tables; h; h = h->next_weak)
5760         marked |= sweep_weak_table (h, false);
5761     }
5762   while (marked);
5763 
5764   /* Remove hash table entries that aren't used.  */
5765   while (weak_hash_tables)
5766     {
5767       h = weak_hash_tables;
5768       weak_hash_tables = h->next_weak;
5769       h->next_weak = NULL;
5770       sweep_weak_table (h, true);
5771     }
5772 }
5773 
5774 /* Return the number of bytes to cons between GCs, given THRESHOLD and
5775    PERCENTAGE.  When calculating a threshold based on PERCENTAGE,
5776    assume SINCE_GC bytes have been allocated since the most recent GC.
5777    The returned value is positive and no greater than HI_THRESHOLD.  */
5778 static EMACS_INT
consing_threshold(intmax_t threshold,Lisp_Object percentage,intmax_t since_gc)5779 consing_threshold (intmax_t threshold, Lisp_Object percentage,
5780 		   intmax_t since_gc)
5781 {
5782   if (!NILP (Vmemory_full))
5783     return memory_full_cons_threshold;
5784   else
5785     {
5786       threshold = max (threshold, GC_DEFAULT_THRESHOLD / 10);
5787       if (FLOATP (percentage))
5788 	{
5789 	  double tot = (XFLOAT_DATA (percentage)
5790 			* (total_bytes_of_live_objects () + since_gc));
5791 	  if (threshold < tot)
5792 	    {
5793 	      if (tot < HI_THRESHOLD)
5794 		return tot;
5795 	      else
5796 		return HI_THRESHOLD;
5797 	    }
5798 	}
5799       return min (threshold, HI_THRESHOLD);
5800     }
5801 }
5802 
5803 /* Adjust consing_until_gc and gc_threshold, given THRESHOLD and PERCENTAGE.
5804    Return the updated consing_until_gc.  */
5805 
5806 static EMACS_INT
bump_consing_until_gc(intmax_t threshold,Lisp_Object percentage)5807 bump_consing_until_gc (intmax_t threshold, Lisp_Object percentage)
5808 {
5809   /* Guesstimate that half the bytes allocated since the most
5810      recent GC are still in use.  */
5811   EMACS_INT since_gc = (gc_threshold - consing_until_gc) >> 1;
5812   EMACS_INT new_gc_threshold = consing_threshold (threshold, percentage,
5813 						  since_gc);
5814   consing_until_gc += new_gc_threshold - gc_threshold;
5815   gc_threshold = new_gc_threshold;
5816   return consing_until_gc;
5817 }
5818 
5819 /* Watch changes to gc-cons-threshold.  */
5820 static Lisp_Object
watch_gc_cons_threshold(Lisp_Object symbol,Lisp_Object newval,Lisp_Object operation,Lisp_Object where)5821 watch_gc_cons_threshold (Lisp_Object symbol, Lisp_Object newval,
5822 			 Lisp_Object operation, Lisp_Object where)
5823 {
5824   intmax_t threshold;
5825   if (! (INTEGERP (newval) && integer_to_intmax (newval, &threshold)))
5826     return Qnil;
5827   bump_consing_until_gc (threshold, Vgc_cons_percentage);
5828   return Qnil;
5829 }
5830 
5831 /* Watch changes to gc-cons-percentage.  */
5832 static Lisp_Object
watch_gc_cons_percentage(Lisp_Object symbol,Lisp_Object newval,Lisp_Object operation,Lisp_Object where)5833 watch_gc_cons_percentage (Lisp_Object symbol, Lisp_Object newval,
5834 			  Lisp_Object operation, Lisp_Object where)
5835 {
5836   bump_consing_until_gc (gc_cons_threshold, newval);
5837   return Qnil;
5838 }
5839 
5840 /* It may be time to collect garbage.  Recalculate consing_until_gc,
5841    since it might depend on current usage, and do the garbage
5842    collection if the recalculation says so.  */
5843 void
maybe_garbage_collect(void)5844 maybe_garbage_collect (void)
5845 {
5846   if (bump_consing_until_gc (gc_cons_threshold, Vgc_cons_percentage) < 0)
5847     garbage_collect ();
5848 }
5849 
5850 /* Subroutine of Fgarbage_collect that does most of the work.  */
5851 void
garbage_collect(void)5852 garbage_collect (void)
5853 {
5854   struct buffer *nextb;
5855   char stack_top_variable;
5856   bool message_p;
5857   ptrdiff_t count = SPECPDL_INDEX ();
5858   struct timespec start;
5859 
5860   eassert (weak_hash_tables == NULL);
5861 
5862   if (garbage_collection_inhibited)
5863     return;
5864 
5865   /* Record this function, so it appears on the profiler's backtraces.  */
5866   record_in_backtrace (QAutomatic_GC, 0, 0);
5867 
5868   /* Don't keep undo information around forever.
5869      Do this early on, so it is no problem if the user quits.  */
5870   FOR_EACH_BUFFER (nextb)
5871     compact_buffer (nextb);
5872 
5873   byte_ct tot_before = (profiler_memory_running
5874 			? total_bytes_of_live_objects ()
5875 			: (byte_ct) -1);
5876 
5877   start = current_timespec ();
5878 
5879   /* In case user calls debug_print during GC,
5880      don't let that cause a recursive GC.  */
5881   consing_until_gc = HI_THRESHOLD;
5882 
5883   /* Save what's currently displayed in the echo area.  Don't do that
5884      if we are GC'ing because we've run out of memory, since
5885      push_message will cons, and we might have no memory for that.  */
5886   if (NILP (Vmemory_full))
5887     {
5888       message_p = push_message ();
5889       record_unwind_protect_void (pop_message_unwind);
5890     }
5891   else
5892     message_p = false;
5893 
5894   /* Save a copy of the contents of the stack, for debugging.  */
5895 #if MAX_SAVE_STACK > 0
5896   if (NILP (Vpurify_flag))
5897     {
5898       char const *stack;
5899       ptrdiff_t stack_size;
5900       if (&stack_top_variable < stack_bottom)
5901 	{
5902 	  stack = &stack_top_variable;
5903 	  stack_size = stack_bottom - &stack_top_variable;
5904 	}
5905       else
5906 	{
5907 	  stack = stack_bottom;
5908 	  stack_size = &stack_top_variable - stack_bottom;
5909 	}
5910       if (stack_size <= MAX_SAVE_STACK)
5911 	{
5912 	  if (stack_copy_size < stack_size)
5913 	    {
5914 	      stack_copy = xrealloc (stack_copy, stack_size);
5915 	      stack_copy_size = stack_size;
5916 	    }
5917 	  stack = ptr_bounds_set (stack, stack_size);
5918 	  no_sanitize_memcpy (stack_copy, stack, stack_size);
5919 	}
5920     }
5921 #endif /* MAX_SAVE_STACK > 0 */
5922 
5923   if (garbage_collection_messages)
5924     message1_nolog ("Garbage collecting...");
5925 
5926   block_input ();
5927 
5928   shrink_regexp_cache ();
5929 
5930   gc_in_progress = 1;
5931 
5932   /* Mark all the special slots that serve as the roots of accessibility.  */
5933 
5934   struct gc_root_visitor visitor = { .visit = mark_object_root_visitor };
5935   visit_static_gc_roots (visitor);
5936 
5937   mark_pinned_objects ();
5938   mark_pinned_symbols ();
5939   mark_terminals ();
5940   mark_kboards ();
5941   mark_threads ();
5942 
5943 #ifdef USE_GTK
5944   xg_mark_data ();
5945 #endif
5946 
5947 #ifdef HAVE_WINDOW_SYSTEM
5948   mark_fringe_data ();
5949 #endif
5950 
5951 #ifdef HAVE_MODULES
5952   mark_modules ();
5953 #endif
5954 
5955   /* Everything is now marked, except for the data in font caches,
5956      undo lists, and finalizers.  The first two are compacted by
5957      removing an items which aren't reachable otherwise.  */
5958 
5959   compact_font_caches ();
5960 
5961   FOR_EACH_BUFFER (nextb)
5962     {
5963       if (!EQ (BVAR (nextb, undo_list), Qt))
5964 	bset_undo_list (nextb, compact_undo_list (BVAR (nextb, undo_list)));
5965       /* Now that we have stripped the elements that need not be
5966 	 in the undo_list any more, we can finally mark the list.  */
5967       mark_object (BVAR (nextb, undo_list));
5968     }
5969 
5970   /* Now pre-sweep finalizers.  Here, we add any unmarked finalizers
5971      to doomed_finalizers so we can run their associated functions
5972      after GC.  It's important to scan finalizers at this stage so
5973      that we can be sure that unmarked finalizers are really
5974      unreachable except for references from their associated functions
5975      and from other finalizers.  */
5976 
5977   queue_doomed_finalizers (&doomed_finalizers, &finalizers);
5978   mark_finalizer_list (&doomed_finalizers);
5979 
5980   /* Must happen after all other marking and before gc_sweep.  */
5981   mark_and_sweep_weak_table_contents ();
5982   eassert (weak_hash_tables == NULL);
5983 
5984   gc_sweep ();
5985 
5986   unmark_main_thread ();
5987 
5988   gc_in_progress = 0;
5989 
5990   consing_until_gc = gc_threshold
5991     = consing_threshold (gc_cons_threshold, Vgc_cons_percentage, 0);
5992 
5993   /* Unblock *after* re-setting `consing_until_gc` in case `unblock_input`
5994      signals an error (see bug#43389).  */
5995   unblock_input ();
5996 
5997   if (garbage_collection_messages && NILP (Vmemory_full))
5998     {
5999       if (message_p || minibuf_level > 0)
6000 	restore_message ();
6001       else
6002 	message1_nolog ("Garbage collecting...done");
6003     }
6004 
6005   unbind_to (count, Qnil);
6006 
6007   /* GC is complete: now we can run our finalizer callbacks.  */
6008   run_finalizers (&doomed_finalizers);
6009 
6010   if (!NILP (Vpost_gc_hook))
6011     {
6012       ptrdiff_t gc_count = inhibit_garbage_collection ();
6013       safe_run_hooks (Qpost_gc_hook);
6014       unbind_to (gc_count, Qnil);
6015     }
6016 
6017   /* Accumulate statistics.  */
6018   if (FLOATP (Vgc_elapsed))
6019     {
6020       static struct timespec gc_elapsed;
6021       gc_elapsed = timespec_add (gc_elapsed,
6022 				 timespec_sub (current_timespec (), start));
6023       Vgc_elapsed = make_float (timespectod (gc_elapsed));
6024     }
6025 
6026   gcs_done++;
6027 
6028   /* Collect profiling data.  */
6029   if (tot_before != (byte_ct) -1)
6030     {
6031       byte_ct tot_after = total_bytes_of_live_objects ();
6032       if (tot_after < tot_before)
6033 	malloc_probe (min (tot_before - tot_after, SIZE_MAX));
6034     }
6035 }
6036 
6037 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
6038        doc: /* Reclaim storage for Lisp objects no longer needed.
6039 Garbage collection happens automatically if you cons more than
6040 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
6041 `garbage-collect' normally returns a list with info on amount of space in use,
6042 where each entry has the form (NAME SIZE USED FREE), where:
6043 - NAME is a symbol describing the kind of objects this entry represents,
6044 - SIZE is the number of bytes used by each one,
6045 - USED is the number of those objects that were found live in the heap,
6046 - FREE is the number of those objects that are not live but that Emacs
6047   keeps around for future allocations (maybe because it does not know how
6048   to return them to the OS).
6049 However, if there was overflow in pure space, and Emacs was dumped
6050 using the 'unexec' method, `garbage-collect' returns nil, because
6051 real GC can't be done.
6052 See Info node `(elisp)Garbage Collection'.  */)
6053   (void)
6054 {
6055   if (garbage_collection_inhibited)
6056     return Qnil;
6057 
6058   garbage_collect ();
6059   struct gcstat gcst = gcstat;
6060 
6061   Lisp_Object total[] = {
6062     list4 (Qconses, make_fixnum (sizeof (struct Lisp_Cons)),
6063 	   make_int (gcst.total_conses),
6064 	   make_int (gcst.total_free_conses)),
6065     list4 (Qsymbols, make_fixnum (sizeof (struct Lisp_Symbol)),
6066 	   make_int (gcst.total_symbols),
6067 	   make_int (gcst.total_free_symbols)),
6068     list4 (Qstrings, make_fixnum (sizeof (struct Lisp_String)),
6069 	   make_int (gcst.total_strings),
6070 	   make_int (gcst.total_free_strings)),
6071     list3 (Qstring_bytes, make_fixnum (1),
6072 	   make_int (gcst.total_string_bytes)),
6073     list3 (Qvectors,
6074 	   make_fixnum (header_size + sizeof (Lisp_Object)),
6075 	   make_int (gcst.total_vectors)),
6076     list4 (Qvector_slots, make_fixnum (word_size),
6077 	   make_int (gcst.total_vector_slots),
6078 	   make_int (gcst.total_free_vector_slots)),
6079     list4 (Qfloats, make_fixnum (sizeof (struct Lisp_Float)),
6080 	   make_int (gcst.total_floats),
6081 	   make_int (gcst.total_free_floats)),
6082     list4 (Qintervals, make_fixnum (sizeof (struct interval)),
6083 	   make_int (gcst.total_intervals),
6084 	   make_int (gcst.total_free_intervals)),
6085     list3 (Qbuffers, make_fixnum (sizeof (struct buffer)),
6086 	   make_int (gcst.total_buffers)),
6087 
6088 #ifdef DOUG_LEA_MALLOC
6089     list4 (Qheap, make_fixnum (1024),
6090 	   make_int ((mallinfo ().uordblks + 1023) >> 10),
6091 	   make_int ((mallinfo ().fordblks + 1023) >> 10)),
6092 #endif
6093   };
6094   return CALLMANY (Flist, total);
6095 }
6096 
6097 /* Mark Lisp objects in glyph matrix MATRIX.  Currently the
6098    only interesting objects referenced from glyphs are strings.  */
6099 
6100 static void
mark_glyph_matrix(struct glyph_matrix * matrix)6101 mark_glyph_matrix (struct glyph_matrix *matrix)
6102 {
6103   struct glyph_row *row = matrix->rows;
6104   struct glyph_row *end = row + matrix->nrows;
6105 
6106   for (; row < end; ++row)
6107     if (row->enabled_p)
6108       {
6109 	int area;
6110 	for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
6111 	  {
6112 	    struct glyph *glyph = row->glyphs[area];
6113 	    struct glyph *end_glyph = glyph + row->used[area];
6114 
6115 	    for (; glyph < end_glyph; ++glyph)
6116 	      if (STRINGP (glyph->object)
6117 		  && !string_marked_p (XSTRING (glyph->object)))
6118 		mark_object (glyph->object);
6119 	  }
6120       }
6121 }
6122 
6123 enum { LAST_MARKED_SIZE = 1 << 9 }; /* Must be a power of 2.  */
6124 Lisp_Object last_marked[LAST_MARKED_SIZE] EXTERNALLY_VISIBLE;
6125 static int last_marked_index;
6126 
6127 /* For debugging--call abort when we cdr down this many
6128    links of a list, in mark_object.  In debugging,
6129    the call to abort will hit a breakpoint.
6130    Normally this is zero and the check never goes off.  */
6131 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE;
6132 
6133 static void
mark_vectorlike(union vectorlike_header * header)6134 mark_vectorlike (union vectorlike_header *header)
6135 {
6136   struct Lisp_Vector *ptr = (struct Lisp_Vector *) header;
6137   ptrdiff_t size = ptr->header.size;
6138   ptrdiff_t i;
6139 
6140   eassert (!vector_marked_p (ptr));
6141 
6142   /* Bool vectors have a different case in mark_object.  */
6143   eassert (PSEUDOVECTOR_TYPE (ptr) != PVEC_BOOL_VECTOR);
6144 
6145   set_vector_marked (ptr); /* Else mark it.  */
6146   if (size & PSEUDOVECTOR_FLAG)
6147     size &= PSEUDOVECTOR_SIZE_MASK;
6148 
6149   /* Note that this size is not the memory-footprint size, but only
6150      the number of Lisp_Object fields that we should trace.
6151      The distinction is used e.g. by Lisp_Process which places extra
6152      non-Lisp_Object fields at the end of the structure...  */
6153   for (i = 0; i < size; i++) /* ...and then mark its elements.  */
6154     mark_object (ptr->contents[i]);
6155 }
6156 
6157 /* Like mark_vectorlike but optimized for char-tables (and
6158    sub-char-tables) assuming that the contents are mostly integers or
6159    symbols.  */
6160 
6161 static void
mark_char_table(struct Lisp_Vector * ptr,enum pvec_type pvectype)6162 mark_char_table (struct Lisp_Vector *ptr, enum pvec_type pvectype)
6163 {
6164   int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
6165   /* Consult the Lisp_Sub_Char_Table layout before changing this.  */
6166   int i, idx = (pvectype == PVEC_SUB_CHAR_TABLE ? SUB_CHAR_TABLE_OFFSET : 0);
6167 
6168   eassert (!vector_marked_p (ptr));
6169   set_vector_marked (ptr);
6170   for (i = idx; i < size; i++)
6171     {
6172       Lisp_Object val = ptr->contents[i];
6173 
6174       if (FIXNUMP (val) ||
6175           (SYMBOLP (val) && symbol_marked_p (XSYMBOL (val))))
6176 	continue;
6177       if (SUB_CHAR_TABLE_P (val))
6178 	{
6179 	  if (! vector_marked_p (XVECTOR (val)))
6180 	    mark_char_table (XVECTOR (val), PVEC_SUB_CHAR_TABLE);
6181 	}
6182       else
6183 	mark_object (val);
6184     }
6185 }
6186 
6187 NO_INLINE /* To reduce stack depth in mark_object.  */
6188 static Lisp_Object
mark_compiled(struct Lisp_Vector * ptr)6189 mark_compiled (struct Lisp_Vector *ptr)
6190 {
6191   int i, size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
6192 
6193   set_vector_marked (ptr);
6194   for (i = 0; i < size; i++)
6195     if (i != COMPILED_CONSTANTS)
6196       mark_object (ptr->contents[i]);
6197   return size > COMPILED_CONSTANTS ? ptr->contents[COMPILED_CONSTANTS] : Qnil;
6198 }
6199 
6200 /* Mark the chain of overlays starting at PTR.  */
6201 
6202 static void
mark_overlay(struct Lisp_Overlay * ptr)6203 mark_overlay (struct Lisp_Overlay *ptr)
6204 {
6205   for (; ptr && !vectorlike_marked_p (&ptr->header); ptr = ptr->next)
6206     {
6207       set_vectorlike_marked (&ptr->header);
6208       /* These two are always markers and can be marked fast.  */
6209       set_vectorlike_marked (&XMARKER (ptr->start)->header);
6210       set_vectorlike_marked (&XMARKER (ptr->end)->header);
6211       mark_object (ptr->plist);
6212     }
6213 }
6214 
6215 /* Mark Lisp_Objects and special pointers in BUFFER.  */
6216 
6217 static void
mark_buffer(struct buffer * buffer)6218 mark_buffer (struct buffer *buffer)
6219 {
6220   /* This is handled much like other pseudovectors...  */
6221   mark_vectorlike (&buffer->header);
6222 
6223   /* ...but there are some buffer-specific things.  */
6224 
6225   mark_interval_tree (buffer_intervals (buffer));
6226 
6227   /* For now, we just don't mark the undo_list.  It's done later in
6228      a special way just before the sweep phase, and after stripping
6229      some of its elements that are not needed any more.  */
6230 
6231   mark_overlay (buffer->overlays_before);
6232   mark_overlay (buffer->overlays_after);
6233 
6234   /* If this is an indirect buffer, mark its base buffer.  */
6235   if (buffer->base_buffer &&
6236       !vectorlike_marked_p (&buffer->base_buffer->header))
6237     mark_buffer (buffer->base_buffer);
6238 }
6239 
6240 /* Mark Lisp faces in the face cache C.  */
6241 
6242 NO_INLINE /* To reduce stack depth in mark_object.  */
6243 static void
mark_face_cache(struct face_cache * c)6244 mark_face_cache (struct face_cache *c)
6245 {
6246   if (c)
6247     {
6248       int i, j;
6249       for (i = 0; i < c->used; ++i)
6250 	{
6251 	  struct face *face = FACE_FROM_ID_OR_NULL (c->f, i);
6252 
6253 	  if (face)
6254 	    {
6255 	      if (face->font && !vectorlike_marked_p (&face->font->header))
6256 		mark_vectorlike (&face->font->header);
6257 
6258 	      for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
6259 		mark_object (face->lface[j]);
6260 	    }
6261 	}
6262     }
6263 }
6264 
6265 NO_INLINE /* To reduce stack depth in mark_object.  */
6266 static void
mark_localized_symbol(struct Lisp_Symbol * ptr)6267 mark_localized_symbol (struct Lisp_Symbol *ptr)
6268 {
6269   struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
6270   Lisp_Object where = blv->where;
6271   /* If the value is set up for a killed buffer restore its global binding.  */
6272   if ((BUFFERP (where) && !BUFFER_LIVE_P (XBUFFER (where))))
6273     swap_in_global_binding (ptr);
6274   mark_object (blv->where);
6275   mark_object (blv->valcell);
6276   mark_object (blv->defcell);
6277 }
6278 
6279 /* Remove killed buffers or items whose car is a killed buffer from
6280    LIST, and mark other items.  Return changed LIST, which is marked.  */
6281 
6282 static Lisp_Object
mark_discard_killed_buffers(Lisp_Object list)6283 mark_discard_killed_buffers (Lisp_Object list)
6284 {
6285   Lisp_Object tail, *prev = &list;
6286 
6287   for (tail = list; CONSP (tail) && !cons_marked_p (XCONS (tail));
6288        tail = XCDR (tail))
6289     {
6290       Lisp_Object tem = XCAR (tail);
6291       if (CONSP (tem))
6292 	tem = XCAR (tem);
6293       if (BUFFERP (tem) && !BUFFER_LIVE_P (XBUFFER (tem)))
6294 	*prev = XCDR (tail);
6295       else
6296 	{
6297 	  set_cons_marked (XCONS (tail));
6298 	  mark_object (XCAR (tail));
6299 	  prev = xcdr_addr (tail);
6300 	}
6301     }
6302   mark_object (tail);
6303   return list;
6304 }
6305 
6306 static void
mark_frame(struct Lisp_Vector * ptr)6307 mark_frame (struct Lisp_Vector *ptr)
6308 {
6309   struct frame *f = (struct frame *) ptr;
6310   mark_vectorlike (&ptr->header);
6311   mark_face_cache (f->face_cache);
6312 #ifdef HAVE_WINDOW_SYSTEM
6313   if (FRAME_WINDOW_P (f) && FRAME_OUTPUT_DATA (f))
6314     {
6315       struct font *font = FRAME_FONT (f);
6316 
6317       if (font && !vectorlike_marked_p (&font->header))
6318         mark_vectorlike (&font->header);
6319     }
6320 #endif
6321 }
6322 
6323 static void
mark_window(struct Lisp_Vector * ptr)6324 mark_window (struct Lisp_Vector *ptr)
6325 {
6326   struct window *w = (struct window *) ptr;
6327 
6328   mark_vectorlike (&ptr->header);
6329 
6330   /* Mark glyph matrices, if any.  Marking window
6331      matrices is sufficient because frame matrices
6332      use the same glyph memory.  */
6333   if (w->current_matrix)
6334     {
6335       mark_glyph_matrix (w->current_matrix);
6336       mark_glyph_matrix (w->desired_matrix);
6337     }
6338 
6339   /* Filter out killed buffers from both buffer lists
6340      in attempt to help GC to reclaim killed buffers faster.
6341      We can do it elsewhere for live windows, but this is the
6342      best place to do it for dead windows.  */
6343   wset_prev_buffers
6344     (w, mark_discard_killed_buffers (w->prev_buffers));
6345   wset_next_buffers
6346     (w, mark_discard_killed_buffers (w->next_buffers));
6347 }
6348 
6349 static void
mark_hash_table(struct Lisp_Vector * ptr)6350 mark_hash_table (struct Lisp_Vector *ptr)
6351 {
6352   struct Lisp_Hash_Table *h = (struct Lisp_Hash_Table *) ptr;
6353 
6354   mark_vectorlike (&h->header);
6355   mark_object (h->test.name);
6356   mark_object (h->test.user_hash_function);
6357   mark_object (h->test.user_cmp_function);
6358   /* If hash table is not weak, mark all keys and values.  For weak
6359      tables, mark only the vector and not its contents --- that's what
6360      makes it weak.  */
6361   if (NILP (h->weak))
6362     mark_object (h->key_and_value);
6363   else
6364     {
6365       eassert (h->next_weak == NULL);
6366       h->next_weak = weak_hash_tables;
6367       weak_hash_tables = h;
6368       set_vector_marked (XVECTOR (h->key_and_value));
6369     }
6370 }
6371 
6372 /* Determine type of generic Lisp_Object and mark it accordingly.
6373 
6374    This function implements a straightforward depth-first marking
6375    algorithm and so the recursion depth may be very high (a few
6376    tens of thousands is not uncommon).  To minimize stack usage,
6377    a few cold paths are moved out to NO_INLINE functions above.
6378    In general, inlining them doesn't help you to gain more speed.  */
6379 
6380 void
mark_object(Lisp_Object arg)6381 mark_object (Lisp_Object arg)
6382 {
6383   register Lisp_Object obj;
6384   void *po;
6385 #if GC_CHECK_MARKED_OBJECTS
6386   struct mem_node *m = NULL;
6387 #endif
6388   ptrdiff_t cdr_count = 0;
6389 
6390   obj = arg;
6391  loop:
6392 
6393   po = XPNTR (obj);
6394   if (PURE_P (po))
6395     return;
6396 
6397   last_marked[last_marked_index++] = obj;
6398   last_marked_index &= LAST_MARKED_SIZE - 1;
6399 
6400   /* Perform some sanity checks on the objects marked here.  Abort if
6401      we encounter an object we know is bogus.  This increases GC time
6402      by ~80%.  */
6403 #if GC_CHECK_MARKED_OBJECTS
6404 
6405   /* Check that the object pointed to by PO is known to be a Lisp
6406      structure allocated from the heap.  */
6407 #define CHECK_ALLOCATED()			\
6408   do {						\
6409     if (pdumper_object_p(po))                   \
6410       {                                         \
6411         if (!pdumper_object_p_precise (po))     \
6412           emacs_abort ();                       \
6413         break;                                  \
6414       }                                         \
6415     m = mem_find (po);				\
6416     if (m == MEM_NIL)				\
6417       emacs_abort ();				\
6418   } while (0)
6419 
6420   /* Check that the object pointed to by PO is live, using predicate
6421      function LIVEP.  */
6422 #define CHECK_LIVE(LIVEP)			\
6423   do {						\
6424     if (pdumper_object_p(po))                   \
6425       break;                                    \
6426     if (!LIVEP (m, po))				\
6427       emacs_abort ();				\
6428   } while (0)
6429 
6430   /* Check both of the above conditions, for non-symbols.  */
6431 #define CHECK_ALLOCATED_AND_LIVE(LIVEP)		\
6432   do {						\
6433     CHECK_ALLOCATED ();				\
6434     CHECK_LIVE (LIVEP);				\
6435   } while (false)
6436 
6437   /* Check both of the above conditions, for symbols.  */
6438 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL()	\
6439   do {						\
6440     if (!c_symbol_p (ptr))			\
6441       {						\
6442 	CHECK_ALLOCATED ();			\
6443 	CHECK_LIVE (live_symbol_p);		\
6444       }						\
6445   } while (false)
6446 
6447 #else /* not GC_CHECK_MARKED_OBJECTS */
6448 
6449 #define CHECK_LIVE(LIVEP)			((void) 0)
6450 #define CHECK_ALLOCATED_AND_LIVE(LIVEP)		((void) 0)
6451 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL()	((void) 0)
6452 
6453 #endif /* not GC_CHECK_MARKED_OBJECTS */
6454 
6455   switch (XTYPE (obj))
6456     {
6457     case Lisp_String:
6458       {
6459 	register struct Lisp_String *ptr = XSTRING (obj);
6460         if (string_marked_p (ptr))
6461           break;
6462 	CHECK_ALLOCATED_AND_LIVE (live_string_p);
6463         set_string_marked (ptr);
6464         mark_interval_tree (ptr->u.s.intervals);
6465 #ifdef GC_CHECK_STRING_BYTES
6466 	/* Check that the string size recorded in the string is the
6467 	   same as the one recorded in the sdata structure.  */
6468 	string_bytes (ptr);
6469 #endif /* GC_CHECK_STRING_BYTES */
6470       }
6471       break;
6472 
6473     case Lisp_Vectorlike:
6474       {
6475 	register struct Lisp_Vector *ptr = XVECTOR (obj);
6476 
6477 	if (vector_marked_p (ptr))
6478 	  break;
6479 
6480 #ifdef GC_CHECK_MARKED_OBJECTS
6481         if (!pdumper_object_p(po))
6482           {
6483 	    m = mem_find (po);
6484             if (m == MEM_NIL && !SUBRP (obj) && !main_thread_p (po))
6485 	      emacs_abort ();
6486           }
6487 #endif /* GC_CHECK_MARKED_OBJECTS */
6488 
6489         enum pvec_type pvectype
6490           = PSEUDOVECTOR_TYPE (ptr);
6491 
6492         if (pvectype != PVEC_SUBR &&
6493             pvectype != PVEC_BUFFER &&
6494             !main_thread_p (po))
6495           CHECK_LIVE (live_vector_p);
6496 
6497 	switch (pvectype)
6498 	  {
6499 	  case PVEC_BUFFER:
6500 #if GC_CHECK_MARKED_OBJECTS
6501 	    {
6502 	      struct buffer *b;
6503 	      FOR_EACH_BUFFER (b)
6504 		if (b == po)
6505 		  break;
6506 	      if (b == NULL)
6507 		emacs_abort ();
6508 	    }
6509 #endif /* GC_CHECK_MARKED_OBJECTS */
6510 	    mark_buffer ((struct buffer *) ptr);
6511             break;
6512 
6513           case PVEC_COMPILED:
6514             /* Although we could treat this just like a vector, mark_compiled
6515                returns the COMPILED_CONSTANTS element, which is marked at the
6516                next iteration of goto-loop here.  This is done to avoid a few
6517                recursive calls to mark_object.  */
6518             obj = mark_compiled (ptr);
6519             if (!NILP (obj))
6520               goto loop;
6521             break;
6522 
6523           case PVEC_FRAME:
6524             mark_frame (ptr);
6525             break;
6526 
6527           case PVEC_WINDOW:
6528             mark_window (ptr);
6529             break;
6530 
6531 	  case PVEC_HASH_TABLE:
6532             mark_hash_table (ptr);
6533 	    break;
6534 
6535 	  case PVEC_CHAR_TABLE:
6536 	  case PVEC_SUB_CHAR_TABLE:
6537 	    mark_char_table (ptr, (enum pvec_type) pvectype);
6538 	    break;
6539 
6540           case PVEC_BOOL_VECTOR:
6541             /* bool vectors in a dump are permanently "marked", since
6542                they're in the old section and don't have mark bits.
6543                If we're looking at a dumped bool vector, we should
6544                have aborted above when we called vector_marked_p(), so
6545                we should never get here.  */
6546             eassert (!pdumper_object_p (ptr));
6547             set_vector_marked (ptr);
6548             break;
6549 
6550           case PVEC_OVERLAY:
6551 	    mark_overlay (XOVERLAY (obj));
6552 	    break;
6553 
6554 	  case PVEC_SUBR:
6555 	    break;
6556 
6557 	  case PVEC_FREE:
6558 	    emacs_abort ();
6559 
6560 	  default:
6561 	    /* A regular vector, or a pseudovector needing no special
6562 	       treatment.  */
6563 	    mark_vectorlike (&ptr->header);
6564 	  }
6565       }
6566       break;
6567 
6568     case Lisp_Symbol:
6569       {
6570 	struct Lisp_Symbol *ptr = XSYMBOL (obj);
6571       nextsym:
6572         if (symbol_marked_p (ptr))
6573           break;
6574         CHECK_ALLOCATED_AND_LIVE_SYMBOL ();
6575         set_symbol_marked(ptr);
6576 	/* Attempt to catch bogus objects.  */
6577 	eassert (valid_lisp_object_p (ptr->u.s.function));
6578 	mark_object (ptr->u.s.function);
6579 	mark_object (ptr->u.s.plist);
6580 	switch (ptr->u.s.redirect)
6581 	  {
6582 	  case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
6583 	  case SYMBOL_VARALIAS:
6584 	    {
6585 	      Lisp_Object tem;
6586 	      XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
6587 	      mark_object (tem);
6588 	      break;
6589 	    }
6590 	  case SYMBOL_LOCALIZED:
6591 	    mark_localized_symbol (ptr);
6592 	    break;
6593 	  case SYMBOL_FORWARDED:
6594 	    /* If the value is forwarded to a buffer or keyboard field,
6595 	       these are marked when we see the corresponding object.
6596 	       And if it's forwarded to a C variable, either it's not
6597 	       a Lisp_Object var, or it's staticpro'd already.  */
6598 	    break;
6599 	  default: emacs_abort ();
6600 	  }
6601 	if (!PURE_P (XSTRING (ptr->u.s.name)))
6602           set_string_marked (XSTRING (ptr->u.s.name));
6603         mark_interval_tree (string_intervals (ptr->u.s.name));
6604 	/* Inner loop to mark next symbol in this bucket, if any.  */
6605 	po = ptr = ptr->u.s.next;
6606 	if (ptr)
6607 	  goto nextsym;
6608       }
6609       break;
6610 
6611     case Lisp_Cons:
6612       {
6613 	struct Lisp_Cons *ptr = XCONS (obj);
6614 	if (cons_marked_p (ptr))
6615 	  break;
6616 	CHECK_ALLOCATED_AND_LIVE (live_cons_p);
6617         set_cons_marked (ptr);
6618 	/* If the cdr is nil, avoid recursion for the car.  */
6619 	if (NILP (ptr->u.s.u.cdr))
6620 	  {
6621 	    obj = ptr->u.s.car;
6622 	    cdr_count = 0;
6623 	    goto loop;
6624 	  }
6625 	mark_object (ptr->u.s.car);
6626 	obj = ptr->u.s.u.cdr;
6627 	cdr_count++;
6628 	if (cdr_count == mark_object_loop_halt)
6629 	  emacs_abort ();
6630 	goto loop;
6631       }
6632 
6633     case Lisp_Float:
6634       CHECK_ALLOCATED_AND_LIVE (live_float_p);
6635       /* Do not mark floats stored in a dump image: these floats are
6636          "cold" and do not have mark bits.  */
6637       if (pdumper_object_p (XFLOAT (obj)))
6638         eassert (pdumper_cold_object_p (XFLOAT (obj)));
6639       else if (!XFLOAT_MARKED_P (XFLOAT (obj)))
6640         XFLOAT_MARK (XFLOAT (obj));
6641       break;
6642 
6643     case_Lisp_Int:
6644       break;
6645 
6646     default:
6647       emacs_abort ();
6648     }
6649 
6650 #undef CHECK_LIVE
6651 #undef CHECK_ALLOCATED
6652 #undef CHECK_ALLOCATED_AND_LIVE
6653 }
6654 
6655 /* Mark the Lisp pointers in the terminal objects.
6656    Called by Fgarbage_collect.  */
6657 
6658 static void
mark_terminals(void)6659 mark_terminals (void)
6660 {
6661   struct terminal *t;
6662   for (t = terminal_list; t; t = t->next_terminal)
6663     {
6664       eassert (t->name != NULL);
6665 #ifdef HAVE_WINDOW_SYSTEM
6666       /* If a terminal object is reachable from a stacpro'ed object,
6667 	 it might have been marked already.  Make sure the image cache
6668 	 gets marked.  */
6669       mark_image_cache (t->image_cache);
6670 #endif /* HAVE_WINDOW_SYSTEM */
6671       if (!vectorlike_marked_p (&t->header))
6672 	mark_vectorlike (&t->header);
6673     }
6674 }
6675 
6676 /* Value is non-zero if OBJ will survive the current GC because it's
6677    either marked or does not need to be marked to survive.  */
6678 
6679 bool
survives_gc_p(Lisp_Object obj)6680 survives_gc_p (Lisp_Object obj)
6681 {
6682   bool survives_p;
6683 
6684   switch (XTYPE (obj))
6685     {
6686     case_Lisp_Int:
6687       survives_p = true;
6688       break;
6689 
6690     case Lisp_Symbol:
6691       survives_p = symbol_marked_p (XSYMBOL (obj));
6692       break;
6693 
6694     case Lisp_String:
6695       survives_p = string_marked_p (XSTRING (obj));
6696       break;
6697 
6698     case Lisp_Vectorlike:
6699       survives_p = SUBRP (obj) || vector_marked_p (XVECTOR (obj));
6700       break;
6701 
6702     case Lisp_Cons:
6703       survives_p = cons_marked_p (XCONS (obj));
6704       break;
6705 
6706     case Lisp_Float:
6707       survives_p =
6708         XFLOAT_MARKED_P (XFLOAT (obj)) ||
6709         pdumper_object_p (XFLOAT (obj));
6710       break;
6711 
6712     default:
6713       emacs_abort ();
6714     }
6715 
6716   return survives_p || PURE_P (XPNTR (obj));
6717 }
6718 
6719 
6720 
6721 
6722 NO_INLINE /* For better stack traces */
6723 static void
sweep_conses(void)6724 sweep_conses (void)
6725 {
6726   struct cons_block **cprev = &cons_block;
6727   int lim = cons_block_index;
6728   object_ct num_free = 0, num_used = 0;
6729 
6730   cons_free_list = 0;
6731 
6732   for (struct cons_block *cblk; (cblk = *cprev); )
6733     {
6734       int i = 0;
6735       int this_free = 0;
6736       int ilim = (lim + BITS_PER_BITS_WORD - 1) / BITS_PER_BITS_WORD;
6737 
6738       /* Scan the mark bits an int at a time.  */
6739       for (i = 0; i < ilim; i++)
6740         {
6741           if (cblk->gcmarkbits[i] == BITS_WORD_MAX)
6742             {
6743               /* Fast path - all cons cells for this int are marked.  */
6744               cblk->gcmarkbits[i] = 0;
6745               num_used += BITS_PER_BITS_WORD;
6746             }
6747           else
6748             {
6749               /* Some cons cells for this int are not marked.
6750                  Find which ones, and free them.  */
6751               int start, pos, stop;
6752 
6753               start = i * BITS_PER_BITS_WORD;
6754               stop = lim - start;
6755               if (stop > BITS_PER_BITS_WORD)
6756                 stop = BITS_PER_BITS_WORD;
6757               stop += start;
6758 
6759               for (pos = start; pos < stop; pos++)
6760                 {
6761 		  struct Lisp_Cons *acons
6762 		    = ptr_bounds_copy (&cblk->conses[pos], cblk);
6763 		  if (!XCONS_MARKED_P (acons))
6764                     {
6765                       this_free++;
6766                       cblk->conses[pos].u.s.u.chain = cons_free_list;
6767                       cons_free_list = &cblk->conses[pos];
6768                       cons_free_list->u.s.car = dead_object ();
6769                     }
6770                   else
6771                     {
6772                       num_used++;
6773 		      XUNMARK_CONS (acons);
6774                     }
6775                 }
6776             }
6777         }
6778 
6779       lim = CONS_BLOCK_SIZE;
6780       /* If this block contains only free conses and we have already
6781          seen more than two blocks worth of free conses then deallocate
6782          this block.  */
6783       if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
6784         {
6785           *cprev = cblk->next;
6786           /* Unhook from the free list.  */
6787           cons_free_list = cblk->conses[0].u.s.u.chain;
6788           lisp_align_free (cblk);
6789         }
6790       else
6791         {
6792           num_free += this_free;
6793           cprev = &cblk->next;
6794         }
6795     }
6796   gcstat.total_conses = num_used;
6797   gcstat.total_free_conses = num_free;
6798 }
6799 
6800 NO_INLINE /* For better stack traces */
6801 static void
sweep_floats(void)6802 sweep_floats (void)
6803 {
6804   struct float_block **fprev = &float_block;
6805   int lim = float_block_index;
6806   object_ct num_free = 0, num_used = 0;
6807 
6808   float_free_list = 0;
6809 
6810   for (struct float_block *fblk; (fblk = *fprev); )
6811     {
6812       int this_free = 0;
6813       for (int i = 0; i < lim; i++)
6814 	{
6815 	  struct Lisp_Float *afloat = ptr_bounds_copy (&fblk->floats[i], fblk);
6816 	  if (!XFLOAT_MARKED_P (afloat))
6817 	    {
6818 	      this_free++;
6819 	      fblk->floats[i].u.chain = float_free_list;
6820 	      float_free_list = &fblk->floats[i];
6821 	    }
6822 	  else
6823 	    {
6824 	      num_used++;
6825 	      XFLOAT_UNMARK (afloat);
6826 	    }
6827 	}
6828       lim = FLOAT_BLOCK_SIZE;
6829       /* If this block contains only free floats and we have already
6830          seen more than two blocks worth of free floats then deallocate
6831          this block.  */
6832       if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6833         {
6834           *fprev = fblk->next;
6835           /* Unhook from the free list.  */
6836           float_free_list = fblk->floats[0].u.chain;
6837           lisp_align_free (fblk);
6838         }
6839       else
6840         {
6841           num_free += this_free;
6842           fprev = &fblk->next;
6843         }
6844     }
6845   gcstat.total_floats = num_used;
6846   gcstat.total_free_floats = num_free;
6847 }
6848 
6849 NO_INLINE /* For better stack traces */
6850 static void
sweep_intervals(void)6851 sweep_intervals (void)
6852 {
6853   struct interval_block **iprev = &interval_block;
6854   int lim = interval_block_index;
6855   object_ct num_free = 0, num_used = 0;
6856 
6857   interval_free_list = 0;
6858 
6859   for (struct interval_block *iblk; (iblk = *iprev); )
6860     {
6861       int this_free = 0;
6862 
6863       for (int i = 0; i < lim; i++)
6864         {
6865           if (!iblk->intervals[i].gcmarkbit)
6866             {
6867               set_interval_parent (&iblk->intervals[i], interval_free_list);
6868               interval_free_list = &iblk->intervals[i];
6869               this_free++;
6870             }
6871           else
6872             {
6873               num_used++;
6874               iblk->intervals[i].gcmarkbit = 0;
6875             }
6876         }
6877       lim = INTERVAL_BLOCK_SIZE;
6878       /* If this block contains only free intervals and we have already
6879          seen more than two blocks worth of free intervals then
6880          deallocate this block.  */
6881       if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6882         {
6883           *iprev = iblk->next;
6884           /* Unhook from the free list.  */
6885           interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
6886           lisp_free (iblk);
6887         }
6888       else
6889         {
6890           num_free += this_free;
6891           iprev = &iblk->next;
6892         }
6893     }
6894   gcstat.total_intervals = num_used;
6895   gcstat.total_free_intervals = num_free;
6896 }
6897 
6898 NO_INLINE /* For better stack traces */
6899 static void
sweep_symbols(void)6900 sweep_symbols (void)
6901 {
6902   struct symbol_block *sblk;
6903   struct symbol_block **sprev = &symbol_block;
6904   int lim = symbol_block_index;
6905   object_ct num_free = 0, num_used = ARRAYELTS (lispsym);
6906 
6907   symbol_free_list = NULL;
6908 
6909   for (int i = 0; i < ARRAYELTS (lispsym); i++)
6910     lispsym[i].u.s.gcmarkbit = 0;
6911 
6912   for (sblk = symbol_block; sblk; sblk = *sprev)
6913     {
6914       int this_free = 0;
6915       struct Lisp_Symbol *sym = sblk->symbols;
6916       struct Lisp_Symbol *end = sym + lim;
6917 
6918       for (; sym < end; ++sym)
6919         {
6920           if (!sym->u.s.gcmarkbit)
6921             {
6922               if (sym->u.s.redirect == SYMBOL_LOCALIZED)
6923 		{
6924                   xfree (SYMBOL_BLV (sym));
6925                   /* At every GC we sweep all symbol_blocks and rebuild the
6926                      symbol_free_list, so those symbols which stayed unused
6927                      between the two will be re-swept.
6928                      So we have to make sure we don't re-free this blv next
6929                      time we sweep this symbol_block (bug#29066).  */
6930                   sym->u.s.redirect = SYMBOL_PLAINVAL;
6931                 }
6932               sym->u.s.next = symbol_free_list;
6933               symbol_free_list = sym;
6934               symbol_free_list->u.s.function = dead_object ();
6935               ++this_free;
6936             }
6937           else
6938             {
6939               ++num_used;
6940               sym->u.s.gcmarkbit = 0;
6941               /* Attempt to catch bogus objects.  */
6942               eassert (valid_lisp_object_p (sym->u.s.function));
6943             }
6944         }
6945 
6946       lim = SYMBOL_BLOCK_SIZE;
6947       /* If this block contains only free symbols and we have already
6948          seen more than two blocks worth of free symbols then deallocate
6949          this block.  */
6950       if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6951         {
6952           *sprev = sblk->next;
6953           /* Unhook from the free list.  */
6954           symbol_free_list = sblk->symbols[0].u.s.next;
6955           lisp_free (sblk);
6956         }
6957       else
6958         {
6959           num_free += this_free;
6960           sprev = &sblk->next;
6961         }
6962     }
6963   gcstat.total_symbols = num_used;
6964   gcstat.total_free_symbols = num_free;
6965 }
6966 
6967 /* Remove BUFFER's markers that are due to be swept.  This is needed since
6968    we treat BUF_MARKERS and markers's `next' field as weak pointers.  */
6969 static void
unchain_dead_markers(struct buffer * buffer)6970 unchain_dead_markers (struct buffer *buffer)
6971 {
6972   struct Lisp_Marker *this, **prev = &BUF_MARKERS (buffer);
6973 
6974   while ((this = *prev))
6975     if (vectorlike_marked_p (&this->header))
6976       prev = &this->next;
6977     else
6978       {
6979         this->buffer = NULL;
6980         *prev = this->next;
6981       }
6982 }
6983 
6984 NO_INLINE /* For better stack traces */
6985 static void
sweep_buffers(void)6986 sweep_buffers (void)
6987 {
6988   struct buffer *buffer, **bprev = &all_buffers;
6989 
6990   gcstat.total_buffers = 0;
6991   for (buffer = all_buffers; buffer; buffer = *bprev)
6992     if (!vectorlike_marked_p (&buffer->header))
6993       {
6994         *bprev = buffer->next;
6995         lisp_free (buffer);
6996       }
6997     else
6998       {
6999         if (!pdumper_object_p (buffer))
7000           XUNMARK_VECTOR (buffer);
7001         /* Do not use buffer_(set|get)_intervals here.  */
7002         buffer->text->intervals = balance_intervals (buffer->text->intervals);
7003         unchain_dead_markers (buffer);
7004 	gcstat.total_buffers++;
7005         bprev = &buffer->next;
7006       }
7007 }
7008 
7009 /* Sweep: find all structures not marked, and free them.  */
7010 static void
gc_sweep(void)7011 gc_sweep (void)
7012 {
7013   sweep_strings ();
7014   check_string_bytes (!noninteractive);
7015   sweep_conses ();
7016   sweep_floats ();
7017   sweep_intervals ();
7018   sweep_symbols ();
7019   sweep_buffers ();
7020   sweep_vectors ();
7021   pdumper_clear_marks ();
7022   check_string_bytes (!noninteractive);
7023 }
7024 
7025 DEFUN ("memory-info", Fmemory_info, Smemory_info, 0, 0, 0,
7026        doc: /* Return a list of (TOTAL-RAM FREE-RAM TOTAL-SWAP FREE-SWAP).
7027 All values are in Kbytes.  If there is no swap space,
7028 last two values are zero.  If the system is not supported
7029 or memory information can't be obtained, return nil.  */)
7030   (void)
7031 {
7032 #if defined HAVE_LINUX_SYSINFO
7033   struct sysinfo si;
7034   uintmax_t units;
7035 
7036   if (sysinfo (&si))
7037     return Qnil;
7038 #ifdef LINUX_SYSINFO_UNIT
7039   units = si.mem_unit;
7040 #else
7041   units = 1;
7042 #endif
7043   return list4i ((uintmax_t) si.totalram * units / 1024,
7044 		 (uintmax_t) si.freeram * units / 1024,
7045 		 (uintmax_t) si.totalswap * units / 1024,
7046 		 (uintmax_t) si.freeswap * units / 1024);
7047 #elif defined WINDOWSNT
7048   unsigned long long totalram, freeram, totalswap, freeswap;
7049 
7050   if (w32_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
7051     return list4i ((uintmax_t) totalram / 1024,
7052 		   (uintmax_t) freeram / 1024,
7053 		   (uintmax_t) totalswap / 1024,
7054 		   (uintmax_t) freeswap / 1024);
7055   else
7056     return Qnil;
7057 #elif defined MSDOS
7058   unsigned long totalram, freeram, totalswap, freeswap;
7059 
7060   if (dos_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
7061     return list4i ((uintmax_t) totalram / 1024,
7062 		   (uintmax_t) freeram / 1024,
7063 		   (uintmax_t) totalswap / 1024,
7064 		   (uintmax_t) freeswap / 1024);
7065   else
7066     return Qnil;
7067 #else /* not HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
7068   /* FIXME: add more systems.  */
7069   return Qnil;
7070 #endif /* HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
7071 }
7072 
7073 /* Debugging aids.  */
7074 
7075 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
7076        doc: /* Return a list of counters that measure how much consing there has been.
7077 Each of these counters increments for a certain kind of object.
7078 The counters wrap around from the largest positive integer to zero.
7079 Garbage collection does not decrease them.
7080 The elements of the value are as follows:
7081   (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS INTERVALS STRINGS)
7082 All are in units of 1 = one object consed
7083 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
7084 objects consed.
7085 Frames, windows, buffers, and subprocesses count as vectors
7086   (but the contents of a buffer's text do not count here).  */)
7087   (void)
7088 {
7089   return  list (make_int (cons_cells_consed),
7090 		make_int (floats_consed),
7091 		make_int (vector_cells_consed),
7092 		make_int (symbols_consed),
7093 		make_int (string_chars_consed),
7094 		make_int (intervals_consed),
7095 		make_int (strings_consed));
7096 }
7097 
7098 static bool
symbol_uses_obj(Lisp_Object symbol,Lisp_Object obj)7099 symbol_uses_obj (Lisp_Object symbol, Lisp_Object obj)
7100 {
7101   struct Lisp_Symbol *sym = XSYMBOL (symbol);
7102   Lisp_Object val = find_symbol_value (symbol);
7103   return (EQ (val, obj)
7104 	  || EQ (sym->u.s.function, obj)
7105 	  || (!NILP (sym->u.s.function)
7106 	      && COMPILEDP (sym->u.s.function)
7107 	      && EQ (AREF (sym->u.s.function, COMPILED_BYTECODE), obj))
7108 	  || (!NILP (val)
7109 	      && COMPILEDP (val)
7110 	      && EQ (AREF (val, COMPILED_BYTECODE), obj)));
7111 }
7112 
7113 /* Find at most FIND_MAX symbols which have OBJ as their value or
7114    function.  This is used in gdbinit's `xwhichsymbols' command.  */
7115 
7116 Lisp_Object
which_symbols(Lisp_Object obj,EMACS_INT find_max)7117 which_symbols (Lisp_Object obj, EMACS_INT find_max)
7118 {
7119    struct symbol_block *sblk;
7120    ptrdiff_t gc_count = inhibit_garbage_collection ();
7121    Lisp_Object found = Qnil;
7122 
7123    if (! deadp (obj))
7124      {
7125        for (int i = 0; i < ARRAYELTS (lispsym); i++)
7126 	 {
7127 	   Lisp_Object sym = builtin_lisp_symbol (i);
7128 	   if (symbol_uses_obj (sym, obj))
7129 	     {
7130 	       found = Fcons (sym, found);
7131 	       if (--find_max == 0)
7132 		 goto out;
7133 	     }
7134 	 }
7135 
7136        for (sblk = symbol_block; sblk; sblk = sblk->next)
7137 	 {
7138 	   struct Lisp_Symbol *asym = sblk->symbols;
7139 	   int bn;
7140 
7141 	   for (bn = 0; bn < SYMBOL_BLOCK_SIZE; bn++, asym++)
7142 	     {
7143 	       if (sblk == symbol_block && bn >= symbol_block_index)
7144 		 break;
7145 
7146 	       Lisp_Object sym = make_lisp_symbol (asym);
7147 	       if (symbol_uses_obj (sym, obj))
7148 		 {
7149 		   found = Fcons (sym, found);
7150 		   if (--find_max == 0)
7151 		     goto out;
7152 		 }
7153 	     }
7154 	 }
7155      }
7156 
7157   out:
7158    return unbind_to (gc_count, found);
7159 }
7160 
7161 #ifdef SUSPICIOUS_OBJECT_CHECKING
7162 
7163 static void *
find_suspicious_object_in_range(void * begin,void * end)7164 find_suspicious_object_in_range (void *begin, void *end)
7165 {
7166   char *begin_a = begin;
7167   char *end_a = end;
7168   int i;
7169 
7170   for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
7171     {
7172       char *suspicious_object = suspicious_objects[i];
7173       if (begin_a <= suspicious_object && suspicious_object < end_a)
7174 	return suspicious_object;
7175     }
7176 
7177   return NULL;
7178 }
7179 
7180 static void
note_suspicious_free(void * ptr)7181 note_suspicious_free (void *ptr)
7182 {
7183   struct suspicious_free_record *rec;
7184 
7185   rec = &suspicious_free_history[suspicious_free_history_index++];
7186   if (suspicious_free_history_index ==
7187       ARRAYELTS (suspicious_free_history))
7188     {
7189       suspicious_free_history_index = 0;
7190     }
7191 
7192   memset (rec, 0, sizeof (*rec));
7193   rec->suspicious_object = ptr;
7194   backtrace (&rec->backtrace[0], ARRAYELTS (rec->backtrace));
7195 }
7196 
7197 static void
detect_suspicious_free(void * ptr)7198 detect_suspicious_free (void *ptr)
7199 {
7200   int i;
7201 
7202   eassert (ptr != NULL);
7203 
7204   for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
7205     if (suspicious_objects[i] == ptr)
7206       {
7207         note_suspicious_free (ptr);
7208         suspicious_objects[i] = NULL;
7209       }
7210 }
7211 
7212 #endif /* SUSPICIOUS_OBJECT_CHECKING */
7213 
7214 DEFUN ("suspicious-object", Fsuspicious_object, Ssuspicious_object, 1, 1, 0,
7215        doc: /* Return OBJ, maybe marking it for extra scrutiny.
7216 If Emacs is compiled with suspicious object checking, capture
7217 a stack trace when OBJ is freed in order to help track down
7218 garbage collection bugs.  Otherwise, do nothing and return OBJ.   */)
7219    (Lisp_Object obj)
7220 {
7221 #ifdef SUSPICIOUS_OBJECT_CHECKING
7222   /* Right now, we care only about vectors.  */
7223   if (VECTORLIKEP (obj))
7224     {
7225       suspicious_objects[suspicious_object_index++] = XVECTOR (obj);
7226       if (suspicious_object_index == ARRAYELTS (suspicious_objects))
7227 	suspicious_object_index = 0;
7228     }
7229 #endif
7230   return obj;
7231 }
7232 
7233 #ifdef ENABLE_CHECKING
7234 
7235 bool suppress_checking;
7236 
7237 void
die(const char * msg,const char * file,int line)7238 die (const char *msg, const char *file, int line)
7239 {
7240   fprintf (stderr, "\r\n%s:%d: Emacs fatal error: assertion failed: %s\r\n",
7241 	   file, line, msg);
7242   terminate_due_to_signal (SIGABRT, INT_MAX);
7243 }
7244 
7245 #endif /* ENABLE_CHECKING */
7246 
7247 #if defined (ENABLE_CHECKING) && USE_STACK_LISP_OBJECTS
7248 
7249 /* Stress alloca with inconveniently sized requests and check
7250    whether all allocated areas may be used for Lisp_Object.  */
7251 
7252 NO_INLINE static void
verify_alloca(void)7253 verify_alloca (void)
7254 {
7255   int i;
7256   enum { ALLOCA_CHECK_MAX = 256 };
7257   /* Start from size of the smallest Lisp object.  */
7258   for (i = sizeof (struct Lisp_Cons); i <= ALLOCA_CHECK_MAX; i++)
7259     {
7260       void *ptr = alloca (i);
7261       make_lisp_ptr (ptr, Lisp_Cons);
7262     }
7263 }
7264 
7265 #else /* not ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7266 
7267 #define verify_alloca() ((void) 0)
7268 
7269 #endif /* ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7270 
7271 /* Initialization.  */
7272 
7273 static void init_alloc_once_for_pdumper (void);
7274 
7275 void
init_alloc_once(void)7276 init_alloc_once (void)
7277 {
7278   gc_cons_threshold = GC_DEFAULT_THRESHOLD;
7279   /* Even though Qt's contents are not set up, its address is known.  */
7280   Vpurify_flag = Qt;
7281 
7282   PDUMPER_REMEMBER_SCALAR (buffer_defaults.header);
7283   PDUMPER_REMEMBER_SCALAR (buffer_local_symbols.header);
7284 
7285   /* Call init_alloc_once_for_pdumper now so we run mem_init early.
7286      Keep in mind that when we reload from a dump, we'll run _only_
7287      init_alloc_once_for_pdumper and not init_alloc_once at all.  */
7288   pdumper_do_now_and_after_load (init_alloc_once_for_pdumper);
7289 
7290   verify_alloca ();
7291 
7292   init_strings ();
7293   init_vectors ();
7294 }
7295 
7296 static void
init_alloc_once_for_pdumper(void)7297 init_alloc_once_for_pdumper (void)
7298 {
7299   purebeg = PUREBEG;
7300   pure_size = PURESIZE;
7301   mem_init ();
7302 
7303 #ifdef DOUG_LEA_MALLOC
7304   mallopt (M_TRIM_THRESHOLD, 128 * 1024); /* Trim threshold.  */
7305   mallopt (M_MMAP_THRESHOLD, 64 * 1024);  /* Mmap threshold.  */
7306   mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);   /* Max. number of mmap'ed areas.  */
7307 #endif
7308 
7309 
7310   init_finalizer_list (&finalizers);
7311   init_finalizer_list (&doomed_finalizers);
7312   refill_memory_reserve ();
7313 }
7314 
7315 void
init_alloc(void)7316 init_alloc (void)
7317 {
7318   Vgc_elapsed = make_float (0.0);
7319   gcs_done = 0;
7320 }
7321 
7322 void
syms_of_alloc(void)7323 syms_of_alloc (void)
7324 {
7325   DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
7326 	      doc: /* Number of bytes of consing between garbage collections.
7327 Garbage collection can happen automatically once this many bytes have been
7328 allocated since the last garbage collection.  All data types count.
7329 
7330 Garbage collection happens automatically only when `eval' is called.
7331 
7332 By binding this temporarily to a large number, you can effectively
7333 prevent garbage collection during a part of the program.
7334 See also `gc-cons-percentage'.  */);
7335 
7336   DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
7337 	       doc: /* Portion of the heap used for allocation.
7338 Garbage collection can happen automatically once this portion of the heap
7339 has been allocated since the last garbage collection.
7340 If this portion is smaller than `gc-cons-threshold', this is ignored.  */);
7341   Vgc_cons_percentage = make_float (0.1);
7342 
7343   DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
7344 	      doc: /* Number of bytes of shareable Lisp data allocated so far.  */);
7345 
7346   DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
7347 	      doc: /* Number of cons cells that have been consed so far.  */);
7348 
7349   DEFVAR_INT ("floats-consed", floats_consed,
7350 	      doc: /* Number of floats that have been consed so far.  */);
7351 
7352   DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
7353 	      doc: /* Number of vector cells that have been consed so far.  */);
7354 
7355   DEFVAR_INT ("symbols-consed", symbols_consed,
7356 	      doc: /* Number of symbols that have been consed so far.  */);
7357   symbols_consed += ARRAYELTS (lispsym);
7358 
7359   DEFVAR_INT ("string-chars-consed", string_chars_consed,
7360 	      doc: /* Number of string characters that have been consed so far.  */);
7361 
7362   DEFVAR_INT ("intervals-consed", intervals_consed,
7363 	      doc: /* Number of intervals that have been consed so far.  */);
7364 
7365   DEFVAR_INT ("strings-consed", strings_consed,
7366 	      doc: /* Number of strings that have been consed so far.  */);
7367 
7368   DEFVAR_LISP ("purify-flag", Vpurify_flag,
7369 	       doc: /* Non-nil means loading Lisp code in order to dump an executable.
7370 This means that certain objects should be allocated in shared (pure) space.
7371 It can also be set to a hash-table, in which case this table is used to
7372 do hash-consing of the objects allocated to pure space.  */);
7373 
7374   DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
7375 	       doc: /* Non-nil means display messages at start and end of garbage collection.  */);
7376   garbage_collection_messages = 0;
7377 
7378   DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
7379 	       doc: /* Hook run after garbage collection has finished.  */);
7380   Vpost_gc_hook = Qnil;
7381   DEFSYM (Qpost_gc_hook, "post-gc-hook");
7382 
7383   DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
7384 	       doc: /* Precomputed `signal' argument for memory-full error.  */);
7385   /* We build this in advance because if we wait until we need it, we might
7386      not be able to allocate the memory to hold it.  */
7387   Vmemory_signal_data
7388     = pure_list (Qerror,
7389 		 build_pure_c_string ("Memory exhausted--use"
7390 				      " M-x save-some-buffers then"
7391 				      " exit and restart Emacs"));
7392 
7393   DEFVAR_LISP ("memory-full", Vmemory_full,
7394 	       doc: /* Non-nil means Emacs cannot get much more Lisp memory.  */);
7395   Vmemory_full = Qnil;
7396 
7397   DEFSYM (Qconses, "conses");
7398   DEFSYM (Qsymbols, "symbols");
7399   DEFSYM (Qstrings, "strings");
7400   DEFSYM (Qvectors, "vectors");
7401   DEFSYM (Qfloats, "floats");
7402   DEFSYM (Qintervals, "intervals");
7403   DEFSYM (Qbuffers, "buffers");
7404   DEFSYM (Qstring_bytes, "string-bytes");
7405   DEFSYM (Qvector_slots, "vector-slots");
7406   DEFSYM (Qheap, "heap");
7407   DEFSYM (QAutomatic_GC, "Automatic GC");
7408 
7409   DEFSYM (Qgc_cons_percentage, "gc-cons-percentage");
7410   DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
7411   DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
7412 
7413   DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
7414 	       doc: /* Accumulated time elapsed in garbage collections.
7415 The time is in seconds as a floating point value.  */);
7416   DEFVAR_INT ("gcs-done", gcs_done,
7417               doc: /* Accumulated number of garbage collections done.  */);
7418 
7419   DEFVAR_INT ("integer-width", integer_width,
7420 	      doc: /* Maximum number N of bits in safely-calculated integers.
7421 Integers with absolute values less than 2**N do not signal a range error.
7422 N should be nonnegative.  */);
7423 
7424   defsubr (&Scons);
7425   defsubr (&Slist);
7426   defsubr (&Svector);
7427   defsubr (&Srecord);
7428   defsubr (&Sbool_vector);
7429   defsubr (&Smake_byte_code);
7430   defsubr (&Smake_list);
7431   defsubr (&Smake_vector);
7432   defsubr (&Smake_record);
7433   defsubr (&Smake_string);
7434   defsubr (&Smake_bool_vector);
7435   defsubr (&Smake_symbol);
7436   defsubr (&Smake_marker);
7437   defsubr (&Smake_finalizer);
7438   defsubr (&Spurecopy);
7439   defsubr (&Sgarbage_collect);
7440   defsubr (&Smemory_info);
7441   defsubr (&Smemory_use_counts);
7442   defsubr (&Ssuspicious_object);
7443 
7444   Lisp_Object watcher;
7445 
7446   static union Aligned_Lisp_Subr Swatch_gc_cons_threshold =
7447      {{{ PSEUDOVECTOR_FLAG | (PVEC_SUBR << PSEUDOVECTOR_AREA_BITS) },
7448        { .a4 = watch_gc_cons_threshold },
7449        4, 4, "watch_gc_cons_threshold", 0, 0}};
7450   XSETSUBR (watcher, &Swatch_gc_cons_threshold.s);
7451   Fadd_variable_watcher (Qgc_cons_threshold, watcher);
7452 
7453   static union Aligned_Lisp_Subr Swatch_gc_cons_percentage =
7454      {{{ PSEUDOVECTOR_FLAG | (PVEC_SUBR << PSEUDOVECTOR_AREA_BITS) },
7455        { .a4 = watch_gc_cons_percentage },
7456        4, 4, "watch_gc_cons_percentage", 0, 0}};
7457   XSETSUBR (watcher, &Swatch_gc_cons_percentage.s);
7458   Fadd_variable_watcher (Qgc_cons_percentage, watcher);
7459 }
7460 
7461 #ifdef HAVE_X_WINDOWS
7462 enum defined_HAVE_X_WINDOWS { defined_HAVE_X_WINDOWS = true };
7463 #else
7464 enum defined_HAVE_X_WINDOWS { defined_HAVE_X_WINDOWS = false };
7465 #endif
7466 
7467 /* When compiled with GCC, GDB might say "No enum type named
7468    pvec_type" if we don't have at least one symbol with that type, and
7469    then xbacktrace could fail.  Similarly for the other enums and
7470    their values.  Some non-GCC compilers don't like these constructs.  */
7471 #ifdef __GNUC__
7472 union
7473 {
7474   enum CHARTAB_SIZE_BITS CHARTAB_SIZE_BITS;
7475   enum char_table_specials char_table_specials;
7476   enum char_bits char_bits;
7477   enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE;
7478   enum DEFAULT_HASH_SIZE DEFAULT_HASH_SIZE;
7479   enum Lisp_Bits Lisp_Bits;
7480   enum Lisp_Compiled Lisp_Compiled;
7481   enum maxargs maxargs;
7482   enum MAX_ALLOCA MAX_ALLOCA;
7483   enum More_Lisp_Bits More_Lisp_Bits;
7484   enum pvec_type pvec_type;
7485   enum defined_HAVE_X_WINDOWS defined_HAVE_X_WINDOWS;
7486 } const EXTERNALLY_VISIBLE gdb_make_enums_visible = {0};
7487 #endif	/* __GNUC__ */
7488