Tweak mark_object to avoid a conditional branch
[emacs.git] / src / alloc.c
blob8264e0623cf442ddafcad31a51df97bf0780a69c
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2018 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
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.
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.
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/>. */
21 #include <config.h>
23 #include <errno.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <limits.h> /* For CHAR_BIT. */
27 #include <signal.h> /* For SIGABRT, SIGDANGER. */
29 #ifdef HAVE_PTHREAD
30 #include <pthread.h>
31 #endif
33 #include "lisp.h"
34 #include "dispextern.h"
35 #include "intervals.h"
36 #include "ptr-bounds.h"
37 #include "puresize.h"
38 #include "sheap.h"
39 #include "systime.h"
40 #include "character.h"
41 #include "buffer.h"
42 #include "window.h"
43 #include "keyboard.h"
44 #include "frame.h"
45 #include "blockinput.h"
46 #include "termhooks.h" /* For struct terminal. */
47 #ifdef HAVE_WINDOW_SYSTEM
48 #include TERM_HEADER
49 #endif /* HAVE_WINDOW_SYSTEM */
51 #include <flexmember.h>
52 #include <verify.h>
53 #include <execinfo.h> /* For backtrace. */
55 #ifdef HAVE_LINUX_SYSINFO
56 #include <sys/sysinfo.h>
57 #endif
59 #ifdef MSDOS
60 #include "dosfns.h" /* For dos_memory_info. */
61 #endif
63 #ifdef HAVE_MALLOC_H
64 # include <malloc.h>
65 #endif
67 #if (defined ENABLE_CHECKING \
68 && defined HAVE_VALGRIND_VALGRIND_H \
69 && !defined USE_VALGRIND)
70 # define USE_VALGRIND 1
71 #endif
73 #if USE_VALGRIND
74 #include <valgrind/valgrind.h>
75 #include <valgrind/memcheck.h>
76 static bool valgrind_p;
77 #endif
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. */
83 #if defined ENABLE_CHECKING && !defined GC_CHECK_MARKED_OBJECTS
84 # define GC_CHECK_MARKED_OBJECTS 1
85 #endif
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. */
91 #if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
92 || defined HYBRID_MALLOC || GC_CHECK_MARKED_OBJECTS)
93 #undef GC_MALLOC_CHECK
94 #endif
96 #include <unistd.h>
97 #include <fcntl.h>
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
107 #ifdef GNU_LINUX
108 /* The address where the heap starts. */
109 void *
110 my_heap_start (void)
112 static void *start;
113 if (! start)
114 start = sbrk (0);
115 return start;
117 #endif
119 #ifdef DOUG_LEA_MALLOC
121 /* Specify maximum number of areas to mmap. It would be nice to use a
122 value that explicitly means "no limit". */
124 #define MMAP_MAX_AREAS 100000000
126 /* A pointer to the memory allocated that copies that static data
127 inside glibc's malloc. */
128 static void *malloc_state_ptr;
130 /* Restore the dumped malloc state. Because malloc can be invoked
131 even before main (e.g. by the dynamic linker), the dumped malloc
132 state must be restored as early as possible using this special hook. */
133 static void
134 malloc_initialize_hook (void)
136 static bool malloc_using_checking;
138 if (! initialized)
140 #ifdef GNU_LINUX
141 my_heap_start ();
142 #endif
143 malloc_using_checking = getenv ("MALLOC_CHECK_") != NULL;
145 else
147 if (!malloc_using_checking)
149 /* Work around a bug in glibc's malloc. MALLOC_CHECK_ must be
150 ignored if the heap to be restored was constructed without
151 malloc checking. Can't use unsetenv, since that calls malloc. */
152 char **p = environ;
153 if (p)
154 for (; *p; p++)
155 if (strncmp (*p, "MALLOC_CHECK_=", 14) == 0)
158 *p = p[1];
159 while (*++p);
161 break;
165 if (malloc_set_state (malloc_state_ptr) != 0)
166 emacs_abort ();
167 # ifndef XMALLOC_OVERRUN_CHECK
168 alloc_unexec_post ();
169 # endif
173 /* Declare the malloc initialization hook, which runs before 'main' starts.
174 EXTERNALLY_VISIBLE works around Bug#22522. */
175 # ifndef __MALLOC_HOOK_VOLATILE
176 # define __MALLOC_HOOK_VOLATILE
177 # endif
178 voidfuncptr __MALLOC_HOOK_VOLATILE __malloc_initialize_hook EXTERNALLY_VISIBLE
179 = malloc_initialize_hook;
181 #endif
183 #if defined DOUG_LEA_MALLOC || !defined CANNOT_DUMP
185 /* Allocator-related actions to do just before and after unexec. */
187 void
188 alloc_unexec_pre (void)
190 # ifdef DOUG_LEA_MALLOC
191 malloc_state_ptr = malloc_get_state ();
192 if (!malloc_state_ptr)
193 fatal ("malloc_get_state: %s", strerror (errno));
194 # endif
195 # ifdef HYBRID_MALLOC
196 bss_sbrk_did_unexec = true;
197 # endif
200 void
201 alloc_unexec_post (void)
203 # ifdef DOUG_LEA_MALLOC
204 free (malloc_state_ptr);
205 # endif
206 # ifdef HYBRID_MALLOC
207 bss_sbrk_did_unexec = false;
208 # endif
210 #endif
212 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
213 to a struct Lisp_String. */
215 #define MARK_STRING(S) ((S)->u.s.size |= ARRAY_MARK_FLAG)
216 #define UNMARK_STRING(S) ((S)->u.s.size &= ~ARRAY_MARK_FLAG)
217 #define STRING_MARKED_P(S) (((S)->u.s.size & ARRAY_MARK_FLAG) != 0)
219 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
220 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
221 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
223 /* Default value of gc_cons_threshold (see below). */
225 #define GC_DEFAULT_THRESHOLD (100000 * word_size)
227 /* Global variables. */
228 struct emacs_globals globals;
230 /* Number of bytes of consing done since the last gc. */
232 EMACS_INT consing_since_gc;
234 /* Similar minimum, computed from Vgc_cons_percentage. */
236 EMACS_INT gc_relative_threshold;
238 /* Minimum number of bytes of consing since GC before next GC,
239 when memory is full. */
241 EMACS_INT memory_full_cons_threshold;
243 /* True during GC. */
245 bool gc_in_progress;
247 /* Number of live and free conses etc. */
249 static EMACS_INT total_conses, total_markers, total_symbols, total_buffers;
250 static EMACS_INT total_free_conses, total_free_markers, total_free_symbols;
251 static EMACS_INT total_free_floats, total_floats;
253 /* Points to memory space allocated as "spare", to be freed if we run
254 out of memory. We keep one large block, four cons-blocks, and
255 two string blocks. */
257 static char *spare_memory[7];
259 /* Amount of spare memory to keep in large reserve block, or to see
260 whether this much is available when malloc fails on a larger request. */
262 #define SPARE_MEMORY (1 << 14)
264 /* Initialize it to a nonzero value to force it into data space
265 (rather than bss space). That way unexec will remap it into text
266 space (pure), on some systems. We have not implemented the
267 remapping on more recent systems because this is less important
268 nowadays than in the days of small memories and timesharing. */
270 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
271 #define PUREBEG (char *) pure
273 /* Pointer to the pure area, and its size. */
275 static char *purebeg;
276 static ptrdiff_t pure_size;
278 /* Number of bytes of pure storage used before pure storage overflowed.
279 If this is non-zero, this implies that an overflow occurred. */
281 static ptrdiff_t pure_bytes_used_before_overflow;
283 /* Index in pure at which next pure Lisp object will be allocated.. */
285 static ptrdiff_t pure_bytes_used_lisp;
287 /* Number of bytes allocated for non-Lisp objects in pure storage. */
289 static ptrdiff_t pure_bytes_used_non_lisp;
291 /* If nonzero, this is a warning delivered by malloc and not yet
292 displayed. */
294 const char *pending_malloc_warning;
296 #if 0 /* Normally, pointer sanity only on request... */
297 #ifdef ENABLE_CHECKING
298 #define SUSPICIOUS_OBJECT_CHECKING 1
299 #endif
300 #endif
302 /* ... but unconditionally use SUSPICIOUS_OBJECT_CHECKING while the GC
303 bug is unresolved. */
304 #define SUSPICIOUS_OBJECT_CHECKING 1
306 #ifdef SUSPICIOUS_OBJECT_CHECKING
307 struct suspicious_free_record
309 void *suspicious_object;
310 void *backtrace[128];
312 static void *suspicious_objects[32];
313 static int suspicious_object_index;
314 struct suspicious_free_record suspicious_free_history[64] EXTERNALLY_VISIBLE;
315 static int suspicious_free_history_index;
316 /* Find the first currently-monitored suspicious pointer in range
317 [begin,end) or NULL if no such pointer exists. */
318 static void *find_suspicious_object_in_range (void *begin, void *end);
319 static void detect_suspicious_free (void *ptr);
320 #else
321 # define find_suspicious_object_in_range(begin, end) NULL
322 # define detect_suspicious_free(ptr) (void)
323 #endif
325 /* Maximum amount of C stack to save when a GC happens. */
327 #ifndef MAX_SAVE_STACK
328 #define MAX_SAVE_STACK 16000
329 #endif
331 /* Buffer in which we save a copy of the C stack at each GC. */
333 #if MAX_SAVE_STACK > 0
334 static char *stack_copy;
335 static ptrdiff_t stack_copy_size;
337 /* Copy to DEST a block of memory from SRC of size SIZE bytes,
338 avoiding any address sanitization. */
340 static void * ATTRIBUTE_NO_SANITIZE_ADDRESS
341 no_sanitize_memcpy (void *dest, void const *src, size_t size)
343 if (! ADDRESS_SANITIZER)
344 return memcpy (dest, src, size);
345 else
347 size_t i;
348 char *d = dest;
349 char const *s = src;
350 for (i = 0; i < size; i++)
351 d[i] = s[i];
352 return dest;
356 #endif /* MAX_SAVE_STACK > 0 */
358 static void mark_terminals (void);
359 static void gc_sweep (void);
360 static Lisp_Object make_pure_vector (ptrdiff_t);
361 static void mark_buffer (struct buffer *);
363 #if !defined REL_ALLOC || defined SYSTEM_MALLOC || defined HYBRID_MALLOC
364 static void refill_memory_reserve (void);
365 #endif
366 static void compact_small_strings (void);
367 static void free_large_strings (void);
368 extern Lisp_Object which_symbols (Lisp_Object, EMACS_INT) EXTERNALLY_VISIBLE;
370 /* When scanning the C stack for live Lisp objects, Emacs keeps track of
371 what memory allocated via lisp_malloc and lisp_align_malloc is intended
372 for what purpose. This enumeration specifies the type of memory. */
374 enum mem_type
376 MEM_TYPE_NON_LISP,
377 MEM_TYPE_BUFFER,
378 MEM_TYPE_CONS,
379 MEM_TYPE_STRING,
380 MEM_TYPE_MISC,
381 MEM_TYPE_SYMBOL,
382 MEM_TYPE_FLOAT,
383 /* Since all non-bool pseudovectors are small enough to be
384 allocated from vector blocks, this memory type denotes
385 large regular vectors and large bool pseudovectors. */
386 MEM_TYPE_VECTORLIKE,
387 /* Special type to denote vector blocks. */
388 MEM_TYPE_VECTOR_BLOCK,
389 /* Special type to denote reserved memory. */
390 MEM_TYPE_SPARE
393 /* A unique object in pure space used to make some Lisp objects
394 on free lists recognizable in O(1). */
396 static Lisp_Object Vdead;
397 #define DEADP(x) EQ (x, Vdead)
399 #ifdef GC_MALLOC_CHECK
401 enum mem_type allocated_mem_type;
403 #endif /* GC_MALLOC_CHECK */
405 /* A node in the red-black tree describing allocated memory containing
406 Lisp data. Each such block is recorded with its start and end
407 address when it is allocated, and removed from the tree when it
408 is freed.
410 A red-black tree is a balanced binary tree with the following
411 properties:
413 1. Every node is either red or black.
414 2. Every leaf is black.
415 3. If a node is red, then both of its children are black.
416 4. Every simple path from a node to a descendant leaf contains
417 the same number of black nodes.
418 5. The root is always black.
420 When nodes are inserted into the tree, or deleted from the tree,
421 the tree is "fixed" so that these properties are always true.
423 A red-black tree with N internal nodes has height at most 2
424 log(N+1). Searches, insertions and deletions are done in O(log N).
425 Please see a text book about data structures for a detailed
426 description of red-black trees. Any book worth its salt should
427 describe them. */
429 struct mem_node
431 /* Children of this node. These pointers are never NULL. When there
432 is no child, the value is MEM_NIL, which points to a dummy node. */
433 struct mem_node *left, *right;
435 /* The parent of this node. In the root node, this is NULL. */
436 struct mem_node *parent;
438 /* Start and end of allocated region. */
439 void *start, *end;
441 /* Node color. */
442 enum {MEM_BLACK, MEM_RED} color;
444 /* Memory type. */
445 enum mem_type type;
448 /* Root of the tree describing allocated Lisp memory. */
450 static struct mem_node *mem_root;
452 /* Lowest and highest known address in the heap. */
454 static void *min_heap_address, *max_heap_address;
456 /* Sentinel node of the tree. */
458 static struct mem_node mem_z;
459 #define MEM_NIL &mem_z
461 static struct mem_node *mem_insert (void *, void *, enum mem_type);
462 static void mem_insert_fixup (struct mem_node *);
463 static void mem_rotate_left (struct mem_node *);
464 static void mem_rotate_right (struct mem_node *);
465 static void mem_delete (struct mem_node *);
466 static void mem_delete_fixup (struct mem_node *);
467 static struct mem_node *mem_find (void *);
469 #ifndef DEADP
470 # define DEADP(x) 0
471 #endif
473 /* Addresses of staticpro'd variables. Initialize it to a nonzero
474 value; otherwise some compilers put it into BSS. */
476 enum { NSTATICS = 2048 };
477 static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
479 /* Index of next unused slot in staticvec. */
481 static int staticidx;
483 static void *pure_alloc (size_t, int);
485 /* True if N is a power of 2. N should be positive. */
487 #define POWER_OF_2(n) (((n) & ((n) - 1)) == 0)
489 /* Return X rounded to the next multiple of Y. Y should be positive,
490 and Y - 1 + X should not overflow. Arguments should not have side
491 effects, as they are evaluated more than once. Tune for Y being a
492 power of 2. */
494 #define ROUNDUP(x, y) (POWER_OF_2 (y) \
495 ? ((y) - 1 + (x)) & ~ ((y) - 1) \
496 : ((y) - 1 + (x)) - ((y) - 1 + (x)) % (y))
498 /* Return PTR rounded up to the next multiple of ALIGNMENT. */
500 static void *
501 pointer_align (void *ptr, int alignment)
503 return (void *) ROUNDUP ((uintptr_t) ptr, alignment);
506 /* Extract the pointer hidden within O. Define this as a function, as
507 functions are cleaner and can be used in debuggers. Also, define
508 it as a macro if being compiled with GCC without optimization, for
509 performance in that case. macro_XPNTR is private to this section
510 of code. */
512 #define macro_XPNTR(o) \
513 ((void *) \
514 (SYMBOLP (o) \
515 ? ((char *) lispsym \
516 - ((EMACS_UINT) Lisp_Symbol << (USE_LSB_TAG ? 0 : VALBITS)) \
517 + XLI (o)) \
518 : (char *) XLP (o) - (XLI (o) & ~VALMASK)))
520 static ATTRIBUTE_UNUSED void *
521 XPNTR (Lisp_Object a)
523 return macro_XPNTR (a);
526 #if DEFINE_KEY_OPS_AS_MACROS
527 # define XPNTR(a) macro_XPNTR (a)
528 #endif
530 static void
531 XFLOAT_INIT (Lisp_Object f, double n)
533 XFLOAT (f)->u.data = n;
536 #ifdef DOUG_LEA_MALLOC
537 static bool
538 pointers_fit_in_lispobj_p (void)
540 return (UINTPTR_MAX <= VAL_MAX) || USE_LSB_TAG;
543 static bool
544 mmap_lisp_allowed_p (void)
546 /* If we can't store all memory addresses in our lisp objects, it's
547 risky to let the heap use mmap and give us addresses from all
548 over our address space. We also can't use mmap for lisp objects
549 if we might dump: unexec doesn't preserve the contents of mmapped
550 regions. */
551 return pointers_fit_in_lispobj_p () && !might_dump;
553 #endif
555 /* Head of a circularly-linked list of extant finalizers. */
556 static struct Lisp_Finalizer finalizers;
558 /* Head of a circularly-linked list of finalizers that must be invoked
559 because we deemed them unreachable. This list must be global, and
560 not a local inside garbage_collect_1, in case we GC again while
561 running finalizers. */
562 static struct Lisp_Finalizer doomed_finalizers;
565 /************************************************************************
566 Malloc
567 ************************************************************************/
569 #if defined SIGDANGER || (!defined SYSTEM_MALLOC && !defined HYBRID_MALLOC)
571 /* Function malloc calls this if it finds we are near exhausting storage. */
573 void
574 malloc_warning (const char *str)
576 pending_malloc_warning = str;
579 #endif
581 /* Display an already-pending malloc warning. */
583 void
584 display_malloc_warning (void)
586 call3 (intern ("display-warning"),
587 intern ("alloc"),
588 build_string (pending_malloc_warning),
589 intern ("emergency"));
590 pending_malloc_warning = 0;
593 /* Called if we can't allocate relocatable space for a buffer. */
595 void
596 buffer_memory_full (ptrdiff_t nbytes)
598 /* If buffers use the relocating allocator, no need to free
599 spare_memory, because we may have plenty of malloc space left
600 that we could get, and if we don't, the malloc that fails will
601 itself cause spare_memory to be freed. If buffers don't use the
602 relocating allocator, treat this like any other failing
603 malloc. */
605 #ifndef REL_ALLOC
606 memory_full (nbytes);
607 #else
608 /* This used to call error, but if we've run out of memory, we could
609 get infinite recursion trying to build the string. */
610 xsignal (Qnil, Vmemory_signal_data);
611 #endif
614 /* A common multiple of the positive integers A and B. Ideally this
615 would be the least common multiple, but there's no way to do that
616 as a constant expression in C, so do the best that we can easily do. */
617 #define COMMON_MULTIPLE(a, b) \
618 ((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
620 #ifndef XMALLOC_OVERRUN_CHECK
621 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
622 #else
624 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
625 around each block.
627 The header consists of XMALLOC_OVERRUN_CHECK_SIZE fixed bytes
628 followed by XMALLOC_OVERRUN_SIZE_SIZE bytes containing the original
629 block size in little-endian order. The trailer consists of
630 XMALLOC_OVERRUN_CHECK_SIZE fixed bytes.
632 The header is used to detect whether this block has been allocated
633 through these functions, as some low-level libc functions may
634 bypass the malloc hooks. */
636 #define XMALLOC_OVERRUN_CHECK_SIZE 16
637 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
638 (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)
640 #define XMALLOC_BASE_ALIGNMENT alignof (max_align_t)
642 #define XMALLOC_HEADER_ALIGNMENT \
643 COMMON_MULTIPLE (GCALIGNMENT, XMALLOC_BASE_ALIGNMENT)
645 /* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
646 hold a size_t value and (2) the header size is a multiple of the
647 alignment that Emacs needs for C types and for USE_LSB_TAG. */
648 #define XMALLOC_OVERRUN_SIZE_SIZE \
649 (((XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t) \
650 + XMALLOC_HEADER_ALIGNMENT - 1) \
651 / XMALLOC_HEADER_ALIGNMENT * XMALLOC_HEADER_ALIGNMENT) \
652 - XMALLOC_OVERRUN_CHECK_SIZE)
654 static char const xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE] =
655 { '\x9a', '\x9b', '\xae', '\xaf',
656 '\xbf', '\xbe', '\xce', '\xcf',
657 '\xea', '\xeb', '\xec', '\xed',
658 '\xdf', '\xde', '\x9c', '\x9d' };
660 static char const xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
661 { '\xaa', '\xab', '\xac', '\xad',
662 '\xba', '\xbb', '\xbc', '\xbd',
663 '\xca', '\xcb', '\xcc', '\xcd',
664 '\xda', '\xdb', '\xdc', '\xdd' };
666 /* Insert and extract the block size in the header. */
668 static void
669 xmalloc_put_size (unsigned char *ptr, size_t size)
671 int i;
672 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
674 *--ptr = size & ((1 << CHAR_BIT) - 1);
675 size >>= CHAR_BIT;
679 static size_t
680 xmalloc_get_size (unsigned char *ptr)
682 size_t size = 0;
683 int i;
684 ptr -= XMALLOC_OVERRUN_SIZE_SIZE;
685 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
687 size <<= CHAR_BIT;
688 size += *ptr++;
690 return size;
694 /* Like malloc, but wraps allocated block with header and trailer. */
696 static void *
697 overrun_check_malloc (size_t size)
699 register unsigned char *val;
700 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
701 emacs_abort ();
703 val = malloc (size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
704 if (val)
706 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
707 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
708 xmalloc_put_size (val, size);
709 memcpy (val + size, xmalloc_overrun_check_trailer,
710 XMALLOC_OVERRUN_CHECK_SIZE);
712 return val;
716 /* Like realloc, but checks old block for overrun, and wraps new block
717 with header and trailer. */
719 static void *
720 overrun_check_realloc (void *block, size_t size)
722 register unsigned char *val = (unsigned char *) block;
723 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
724 emacs_abort ();
726 if (val
727 && memcmp (xmalloc_overrun_check_header,
728 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
729 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
731 size_t osize = xmalloc_get_size (val);
732 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
733 XMALLOC_OVERRUN_CHECK_SIZE))
734 emacs_abort ();
735 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
736 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
737 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
740 val = realloc (val, size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
742 if (val)
744 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
745 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
746 xmalloc_put_size (val, size);
747 memcpy (val + size, xmalloc_overrun_check_trailer,
748 XMALLOC_OVERRUN_CHECK_SIZE);
750 return val;
753 /* Like free, but checks block for overrun. */
755 static void
756 overrun_check_free (void *block)
758 unsigned char *val = (unsigned char *) block;
760 if (val
761 && memcmp (xmalloc_overrun_check_header,
762 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
763 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
765 size_t osize = xmalloc_get_size (val);
766 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
767 XMALLOC_OVERRUN_CHECK_SIZE))
768 emacs_abort ();
769 #ifdef XMALLOC_CLEAR_FREE_MEMORY
770 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
771 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_OVERHEAD);
772 #else
773 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
774 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
775 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
776 #endif
779 free (val);
782 #undef malloc
783 #undef realloc
784 #undef free
785 #define malloc overrun_check_malloc
786 #define realloc overrun_check_realloc
787 #define free overrun_check_free
788 #endif
790 /* If compiled with XMALLOC_BLOCK_INPUT_CHECK, define a symbol
791 BLOCK_INPUT_IN_MEMORY_ALLOCATORS that is visible to the debugger.
792 If that variable is set, block input while in one of Emacs's memory
793 allocation functions. There should be no need for this debugging
794 option, since signal handlers do not allocate memory, but Emacs
795 formerly allocated memory in signal handlers and this compile-time
796 option remains as a way to help debug the issue should it rear its
797 ugly head again. */
798 #ifdef XMALLOC_BLOCK_INPUT_CHECK
799 bool block_input_in_memory_allocators EXTERNALLY_VISIBLE;
800 static void
801 malloc_block_input (void)
803 if (block_input_in_memory_allocators)
804 block_input ();
806 static void
807 malloc_unblock_input (void)
809 if (block_input_in_memory_allocators)
810 unblock_input ();
812 # define MALLOC_BLOCK_INPUT malloc_block_input ()
813 # define MALLOC_UNBLOCK_INPUT malloc_unblock_input ()
814 #else
815 # define MALLOC_BLOCK_INPUT ((void) 0)
816 # define MALLOC_UNBLOCK_INPUT ((void) 0)
817 #endif
819 #define MALLOC_PROBE(size) \
820 do { \
821 if (profiler_memory_running) \
822 malloc_probe (size); \
823 } while (0)
825 static void *lmalloc (size_t) ATTRIBUTE_MALLOC_SIZE ((1));
826 static void *lrealloc (void *, size_t);
828 /* Like malloc but check for no memory and block interrupt input. */
830 void *
831 xmalloc (size_t size)
833 void *val;
835 MALLOC_BLOCK_INPUT;
836 val = lmalloc (size);
837 MALLOC_UNBLOCK_INPUT;
839 if (!val && size)
840 memory_full (size);
841 MALLOC_PROBE (size);
842 return val;
845 /* Like the above, but zeroes out the memory just allocated. */
847 void *
848 xzalloc (size_t size)
850 void *val;
852 MALLOC_BLOCK_INPUT;
853 val = lmalloc (size);
854 MALLOC_UNBLOCK_INPUT;
856 if (!val && size)
857 memory_full (size);
858 memset (val, 0, size);
859 MALLOC_PROBE (size);
860 return val;
863 /* Like realloc but check for no memory and block interrupt input.. */
865 void *
866 xrealloc (void *block, size_t size)
868 void *val;
870 MALLOC_BLOCK_INPUT;
871 /* We must call malloc explicitly when BLOCK is 0, since some
872 reallocs don't do this. */
873 if (! block)
874 val = lmalloc (size);
875 else
876 val = lrealloc (block, size);
877 MALLOC_UNBLOCK_INPUT;
879 if (!val && size)
880 memory_full (size);
881 MALLOC_PROBE (size);
882 return val;
886 /* Like free but block interrupt input. */
888 void
889 xfree (void *block)
891 if (!block)
892 return;
893 MALLOC_BLOCK_INPUT;
894 free (block);
895 MALLOC_UNBLOCK_INPUT;
896 /* We don't call refill_memory_reserve here
897 because in practice the call in r_alloc_free seems to suffice. */
901 /* Other parts of Emacs pass large int values to allocator functions
902 expecting ptrdiff_t. This is portable in practice, but check it to
903 be safe. */
904 verify (INT_MAX <= PTRDIFF_MAX);
907 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
908 Signal an error on memory exhaustion, and block interrupt input. */
910 void *
911 xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
913 eassert (0 <= nitems && 0 < item_size);
914 ptrdiff_t nbytes;
915 if (INT_MULTIPLY_WRAPV (nitems, item_size, &nbytes) || SIZE_MAX < nbytes)
916 memory_full (SIZE_MAX);
917 return xmalloc (nbytes);
921 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
922 Signal an error on memory exhaustion, and block interrupt input. */
924 void *
925 xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
927 eassert (0 <= nitems && 0 < item_size);
928 ptrdiff_t nbytes;
929 if (INT_MULTIPLY_WRAPV (nitems, item_size, &nbytes) || SIZE_MAX < nbytes)
930 memory_full (SIZE_MAX);
931 return xrealloc (pa, nbytes);
935 /* Grow PA, which points to an array of *NITEMS items, and return the
936 location of the reallocated array, updating *NITEMS to reflect its
937 new size. The new array will contain at least NITEMS_INCR_MIN more
938 items, but will not contain more than NITEMS_MAX items total.
939 ITEM_SIZE is the size of each item, in bytes.
941 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
942 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
943 infinity.
945 If PA is null, then allocate a new array instead of reallocating
946 the old one.
948 Block interrupt input as needed. If memory exhaustion occurs, set
949 *NITEMS to zero if PA is null, and signal an error (i.e., do not
950 return).
952 Thus, to grow an array A without saving its old contents, do
953 { xfree (A); A = NULL; A = xpalloc (NULL, &AITEMS, ...); }.
954 The A = NULL avoids a dangling pointer if xpalloc exhausts memory
955 and signals an error, and later this code is reexecuted and
956 attempts to free A. */
958 void *
959 xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
960 ptrdiff_t nitems_max, ptrdiff_t item_size)
962 ptrdiff_t n0 = *nitems;
963 eassume (0 < item_size && 0 < nitems_incr_min && 0 <= n0 && -1 <= nitems_max);
965 /* The approximate size to use for initial small allocation
966 requests. This is the largest "small" request for the GNU C
967 library malloc. */
968 enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
970 /* If the array is tiny, grow it to about (but no greater than)
971 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%.
972 Adjust the growth according to three constraints: NITEMS_INCR_MIN,
973 NITEMS_MAX, and what the C language can represent safely. */
975 ptrdiff_t n, nbytes;
976 if (INT_ADD_WRAPV (n0, n0 >> 1, &n))
977 n = PTRDIFF_MAX;
978 if (0 <= nitems_max && nitems_max < n)
979 n = nitems_max;
981 ptrdiff_t adjusted_nbytes
982 = ((INT_MULTIPLY_WRAPV (n, item_size, &nbytes) || SIZE_MAX < nbytes)
983 ? min (PTRDIFF_MAX, SIZE_MAX)
984 : nbytes < DEFAULT_MXFAST ? DEFAULT_MXFAST : 0);
985 if (adjusted_nbytes)
987 n = adjusted_nbytes / item_size;
988 nbytes = adjusted_nbytes - adjusted_nbytes % item_size;
991 if (! pa)
992 *nitems = 0;
993 if (n - n0 < nitems_incr_min
994 && (INT_ADD_WRAPV (n0, nitems_incr_min, &n)
995 || (0 <= nitems_max && nitems_max < n)
996 || INT_MULTIPLY_WRAPV (n, item_size, &nbytes)))
997 memory_full (SIZE_MAX);
998 pa = xrealloc (pa, nbytes);
999 *nitems = n;
1000 return pa;
1004 /* Like strdup, but uses xmalloc. */
1006 char *
1007 xstrdup (const char *s)
1009 ptrdiff_t size;
1010 eassert (s);
1011 size = strlen (s) + 1;
1012 return memcpy (xmalloc (size), s, size);
1015 /* Like above, but duplicates Lisp string to C string. */
1017 char *
1018 xlispstrdup (Lisp_Object string)
1020 ptrdiff_t size = SBYTES (string) + 1;
1021 return memcpy (xmalloc (size), SSDATA (string), size);
1024 /* Assign to *PTR a copy of STRING, freeing any storage *PTR formerly
1025 pointed to. If STRING is null, assign it without copying anything.
1026 Allocate before freeing, to avoid a dangling pointer if allocation
1027 fails. */
1029 void
1030 dupstring (char **ptr, char const *string)
1032 char *old = *ptr;
1033 *ptr = string ? xstrdup (string) : 0;
1034 xfree (old);
1038 /* Like putenv, but (1) use the equivalent of xmalloc and (2) the
1039 argument is a const pointer. */
1041 void
1042 xputenv (char const *string)
1044 if (putenv ((char *) string) != 0)
1045 memory_full (0);
1048 /* Return a newly allocated memory block of SIZE bytes, remembering
1049 to free it when unwinding. */
1050 void *
1051 record_xmalloc (size_t size)
1053 void *p = xmalloc (size);
1054 record_unwind_protect_ptr (xfree, p);
1055 return p;
1059 /* Like malloc but used for allocating Lisp data. NBYTES is the
1060 number of bytes to allocate, TYPE describes the intended use of the
1061 allocated memory block (for strings, for conses, ...). */
1063 #if ! USE_LSB_TAG
1064 void *lisp_malloc_loser EXTERNALLY_VISIBLE;
1065 #endif
1067 static void *
1068 lisp_malloc (size_t nbytes, enum mem_type type)
1070 register void *val;
1072 MALLOC_BLOCK_INPUT;
1074 #ifdef GC_MALLOC_CHECK
1075 allocated_mem_type = type;
1076 #endif
1078 val = lmalloc (nbytes);
1080 #if ! USE_LSB_TAG
1081 /* If the memory just allocated cannot be addressed thru a Lisp
1082 object's pointer, and it needs to be,
1083 that's equivalent to running out of memory. */
1084 if (val && type != MEM_TYPE_NON_LISP)
1086 Lisp_Object tem;
1087 XSETCONS (tem, (char *) val + nbytes - 1);
1088 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
1090 lisp_malloc_loser = val;
1091 free (val);
1092 val = 0;
1095 #endif
1097 #ifndef GC_MALLOC_CHECK
1098 if (val && type != MEM_TYPE_NON_LISP)
1099 mem_insert (val, (char *) val + nbytes, type);
1100 #endif
1102 MALLOC_UNBLOCK_INPUT;
1103 if (!val && nbytes)
1104 memory_full (nbytes);
1105 MALLOC_PROBE (nbytes);
1106 return val;
1109 /* Free BLOCK. This must be called to free memory allocated with a
1110 call to lisp_malloc. */
1112 static void
1113 lisp_free (void *block)
1115 MALLOC_BLOCK_INPUT;
1116 free (block);
1117 #ifndef GC_MALLOC_CHECK
1118 mem_delete (mem_find (block));
1119 #endif
1120 MALLOC_UNBLOCK_INPUT;
1123 /***** Allocation of aligned blocks of memory to store Lisp data. *****/
1125 /* The entry point is lisp_align_malloc which returns blocks of at most
1126 BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
1128 /* Byte alignment of storage blocks. */
1129 #define BLOCK_ALIGN (1 << 10)
1130 verify (POWER_OF_2 (BLOCK_ALIGN));
1132 /* Use aligned_alloc if it or a simple substitute is available.
1133 Address sanitization breaks aligned allocation, as of gcc 4.8.2 and
1134 clang 3.3 anyway. Aligned allocation is incompatible with
1135 unexmacosx.c, so don't use it on Darwin. */
1137 #if ! ADDRESS_SANITIZER && !defined DARWIN_OS
1138 # if (defined HAVE_ALIGNED_ALLOC \
1139 || (defined HYBRID_MALLOC \
1140 ? defined HAVE_POSIX_MEMALIGN \
1141 : !defined SYSTEM_MALLOC && !defined DOUG_LEA_MALLOC))
1142 # define USE_ALIGNED_ALLOC 1
1143 # elif !defined HYBRID_MALLOC && defined HAVE_POSIX_MEMALIGN
1144 # define USE_ALIGNED_ALLOC 1
1145 # define aligned_alloc my_aligned_alloc /* Avoid collision with lisp.h. */
1146 static void *
1147 aligned_alloc (size_t alignment, size_t size)
1149 /* POSIX says the alignment must be a power-of-2 multiple of sizeof (void *).
1150 Verify this for all arguments this function is given. */
1151 verify (BLOCK_ALIGN % sizeof (void *) == 0
1152 && POWER_OF_2 (BLOCK_ALIGN / sizeof (void *)));
1153 verify (GCALIGNMENT % sizeof (void *) == 0
1154 && POWER_OF_2 (GCALIGNMENT / sizeof (void *)));
1155 eassert (alignment == BLOCK_ALIGN || alignment == GCALIGNMENT);
1157 void *p;
1158 return posix_memalign (&p, alignment, size) == 0 ? p : 0;
1160 # endif
1161 #endif
1163 /* Padding to leave at the end of a malloc'd block. This is to give
1164 malloc a chance to minimize the amount of memory wasted to alignment.
1165 It should be tuned to the particular malloc library used.
1166 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
1167 aligned_alloc on the other hand would ideally prefer a value of 4
1168 because otherwise, there's 1020 bytes wasted between each ablocks.
1169 In Emacs, testing shows that those 1020 can most of the time be
1170 efficiently used by malloc to place other objects, so a value of 0 can
1171 still preferable unless you have a lot of aligned blocks and virtually
1172 nothing else. */
1173 #define BLOCK_PADDING 0
1174 #define BLOCK_BYTES \
1175 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
1177 /* Internal data structures and constants. */
1179 #define ABLOCKS_SIZE 16
1181 /* An aligned block of memory. */
1182 struct ablock
1184 union
1186 char payload[BLOCK_BYTES];
1187 struct ablock *next_free;
1188 } x;
1190 /* ABASE is the aligned base of the ablocks. It is overloaded to
1191 hold a virtual "busy" field that counts twice the number of used
1192 ablock values in the parent ablocks, plus one if the real base of
1193 the parent ablocks is ABASE (if the "busy" field is even, the
1194 word before the first ablock holds a pointer to the real base).
1195 The first ablock has a "busy" ABASE, and the others have an
1196 ordinary pointer ABASE. To tell the difference, the code assumes
1197 that pointers, when cast to uintptr_t, are at least 2 *
1198 ABLOCKS_SIZE + 1. */
1199 struct ablocks *abase;
1201 /* The padding of all but the last ablock is unused. The padding of
1202 the last ablock in an ablocks is not allocated. */
1203 #if BLOCK_PADDING
1204 char padding[BLOCK_PADDING];
1205 #endif
1208 /* A bunch of consecutive aligned blocks. */
1209 struct ablocks
1211 struct ablock blocks[ABLOCKS_SIZE];
1214 /* Size of the block requested from malloc or aligned_alloc. */
1215 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
1217 #define ABLOCK_ABASE(block) \
1218 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
1219 ? (struct ablocks *) (block) \
1220 : (block)->abase)
1222 /* Virtual `busy' field. */
1223 #define ABLOCKS_BUSY(a_base) ((a_base)->blocks[0].abase)
1225 /* Pointer to the (not necessarily aligned) malloc block. */
1226 #ifdef USE_ALIGNED_ALLOC
1227 #define ABLOCKS_BASE(abase) (abase)
1228 #else
1229 #define ABLOCKS_BASE(abase) \
1230 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void **) (abase))[-1])
1231 #endif
1233 /* The list of free ablock. */
1234 static struct ablock *free_ablock;
1236 /* Allocate an aligned block of nbytes.
1237 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
1238 smaller or equal to BLOCK_BYTES. */
1239 static void *
1240 lisp_align_malloc (size_t nbytes, enum mem_type type)
1242 void *base, *val;
1243 struct ablocks *abase;
1245 eassert (nbytes <= BLOCK_BYTES);
1247 MALLOC_BLOCK_INPUT;
1249 #ifdef GC_MALLOC_CHECK
1250 allocated_mem_type = type;
1251 #endif
1253 if (!free_ablock)
1255 int i;
1256 bool aligned;
1258 #ifdef DOUG_LEA_MALLOC
1259 if (!mmap_lisp_allowed_p ())
1260 mallopt (M_MMAP_MAX, 0);
1261 #endif
1263 #ifdef USE_ALIGNED_ALLOC
1264 verify (ABLOCKS_BYTES % BLOCK_ALIGN == 0);
1265 abase = base = aligned_alloc (BLOCK_ALIGN, ABLOCKS_BYTES);
1266 #else
1267 base = malloc (ABLOCKS_BYTES);
1268 abase = pointer_align (base, BLOCK_ALIGN);
1269 #endif
1271 if (base == 0)
1273 MALLOC_UNBLOCK_INPUT;
1274 memory_full (ABLOCKS_BYTES);
1277 aligned = (base == abase);
1278 if (!aligned)
1279 ((void **) abase)[-1] = base;
1281 #ifdef DOUG_LEA_MALLOC
1282 if (!mmap_lisp_allowed_p ())
1283 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1284 #endif
1286 #if ! USE_LSB_TAG
1287 /* If the memory just allocated cannot be addressed thru a Lisp
1288 object's pointer, and it needs to be, that's equivalent to
1289 running out of memory. */
1290 if (type != MEM_TYPE_NON_LISP)
1292 Lisp_Object tem;
1293 char *end = (char *) base + ABLOCKS_BYTES - 1;
1294 XSETCONS (tem, end);
1295 if ((char *) XCONS (tem) != end)
1297 lisp_malloc_loser = base;
1298 free (base);
1299 MALLOC_UNBLOCK_INPUT;
1300 memory_full (SIZE_MAX);
1303 #endif
1305 /* Initialize the blocks and put them on the free list.
1306 If `base' was not properly aligned, we can't use the last block. */
1307 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1309 abase->blocks[i].abase = abase;
1310 abase->blocks[i].x.next_free = free_ablock;
1311 free_ablock = &abase->blocks[i];
1313 intptr_t ialigned = aligned;
1314 ABLOCKS_BUSY (abase) = (struct ablocks *) ialigned;
1316 eassert ((uintptr_t) abase % BLOCK_ALIGN == 0);
1317 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1318 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1319 eassert (ABLOCKS_BASE (abase) == base);
1320 eassert ((intptr_t) ABLOCKS_BUSY (abase) == aligned);
1323 abase = ABLOCK_ABASE (free_ablock);
1324 ABLOCKS_BUSY (abase)
1325 = (struct ablocks *) (2 + (intptr_t) ABLOCKS_BUSY (abase));
1326 val = free_ablock;
1327 free_ablock = free_ablock->x.next_free;
1329 #ifndef GC_MALLOC_CHECK
1330 if (type != MEM_TYPE_NON_LISP)
1331 mem_insert (val, (char *) val + nbytes, type);
1332 #endif
1334 MALLOC_UNBLOCK_INPUT;
1336 MALLOC_PROBE (nbytes);
1338 eassert (0 == ((uintptr_t) val) % BLOCK_ALIGN);
1339 return val;
1342 static void
1343 lisp_align_free (void *block)
1345 struct ablock *ablock = block;
1346 struct ablocks *abase = ABLOCK_ABASE (ablock);
1348 MALLOC_BLOCK_INPUT;
1349 #ifndef GC_MALLOC_CHECK
1350 mem_delete (mem_find (block));
1351 #endif
1352 /* Put on free list. */
1353 ablock->x.next_free = free_ablock;
1354 free_ablock = ablock;
1355 /* Update busy count. */
1356 intptr_t busy = (intptr_t) ABLOCKS_BUSY (abase) - 2;
1357 eassume (0 <= busy && busy <= 2 * ABLOCKS_SIZE - 1);
1358 ABLOCKS_BUSY (abase) = (struct ablocks *) busy;
1360 if (busy < 2)
1361 { /* All the blocks are free. */
1362 int i = 0;
1363 bool aligned = busy;
1364 struct ablock **tem = &free_ablock;
1365 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1367 while (*tem)
1369 if (*tem >= (struct ablock *) abase && *tem < atop)
1371 i++;
1372 *tem = (*tem)->x.next_free;
1374 else
1375 tem = &(*tem)->x.next_free;
1377 eassert ((aligned & 1) == aligned);
1378 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1379 #ifdef USE_POSIX_MEMALIGN
1380 eassert ((uintptr_t) ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1381 #endif
1382 free (ABLOCKS_BASE (abase));
1384 MALLOC_UNBLOCK_INPUT;
1387 #if !defined __GNUC__ && !defined __alignof__
1388 # define __alignof__(type) alignof (type)
1389 #endif
1391 /* True if malloc (N) is known to return a multiple of GCALIGNMENT
1392 whenever N is also a multiple. In practice this is true if
1393 __alignof__ (max_align_t) is a multiple as well, assuming
1394 GCALIGNMENT is 8; other values of GCALIGNMENT have not been looked
1395 into. Use __alignof__ if available, as otherwise
1396 MALLOC_IS_GC_ALIGNED would be false on GCC x86 even though the
1397 alignment is OK there.
1399 This is a macro, not an enum constant, for portability to HP-UX
1400 10.20 cc and AIX 3.2.5 xlc. */
1401 #define MALLOC_IS_GC_ALIGNED \
1402 (GCALIGNMENT == 8 && __alignof__ (max_align_t) % GCALIGNMENT == 0)
1404 /* True if a malloc-returned pointer P is suitably aligned for SIZE,
1405 where Lisp alignment may be needed if SIZE is Lisp-aligned. */
1407 static bool
1408 laligned (void *p, size_t size)
1410 return (MALLOC_IS_GC_ALIGNED || (intptr_t) p % GCALIGNMENT == 0
1411 || size % GCALIGNMENT != 0);
1414 /* Like malloc and realloc except that if SIZE is Lisp-aligned, make
1415 sure the result is too, if necessary by reallocating (typically
1416 with larger and larger sizes) until the allocator returns a
1417 Lisp-aligned pointer. Code that needs to allocate C heap memory
1418 for a Lisp object should use one of these functions to obtain a
1419 pointer P; that way, if T is an enum Lisp_Type value and L ==
1420 make_lisp_ptr (P, T), then XPNTR (L) == P and XTYPE (L) == T.
1422 On typical modern platforms these functions' loops do not iterate.
1423 On now-rare (and perhaps nonexistent) platforms, the loops in
1424 theory could repeat forever. If an infinite loop is possible on a
1425 platform, a build would surely loop and the builder can then send
1426 us a bug report. Adding a counter to try to detect any such loop
1427 would complicate the code (and possibly introduce bugs, in code
1428 that's never really exercised) for little benefit. */
1430 static void *
1431 lmalloc (size_t size)
1433 #if USE_ALIGNED_ALLOC
1434 if (! MALLOC_IS_GC_ALIGNED && size % GCALIGNMENT == 0)
1435 return aligned_alloc (GCALIGNMENT, size);
1436 #endif
1438 while (true)
1440 void *p = malloc (size);
1441 if (laligned (p, size))
1442 return p;
1443 free (p);
1444 size_t bigger = size + GCALIGNMENT;
1445 if (size < bigger)
1446 size = bigger;
1450 static void *
1451 lrealloc (void *p, size_t size)
1453 while (true)
1455 p = realloc (p, size);
1456 if (laligned (p, size))
1457 return p;
1458 size_t bigger = size + GCALIGNMENT;
1459 if (size < bigger)
1460 size = bigger;
1465 /***********************************************************************
1466 Interval Allocation
1467 ***********************************************************************/
1469 /* Number of intervals allocated in an interval_block structure.
1470 The 1020 is 1024 minus malloc overhead. */
1472 #define INTERVAL_BLOCK_SIZE \
1473 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1475 /* Intervals are allocated in chunks in the form of an interval_block
1476 structure. */
1478 struct interval_block
1480 /* Place `intervals' first, to preserve alignment. */
1481 struct interval intervals[INTERVAL_BLOCK_SIZE];
1482 struct interval_block *next;
1485 /* Current interval block. Its `next' pointer points to older
1486 blocks. */
1488 static struct interval_block *interval_block;
1490 /* Index in interval_block above of the next unused interval
1491 structure. */
1493 static int interval_block_index = INTERVAL_BLOCK_SIZE;
1495 /* Number of free and live intervals. */
1497 static EMACS_INT total_free_intervals, total_intervals;
1499 /* List of free intervals. */
1501 static INTERVAL interval_free_list;
1503 /* Return a new interval. */
1505 INTERVAL
1506 make_interval (void)
1508 INTERVAL val;
1510 MALLOC_BLOCK_INPUT;
1512 if (interval_free_list)
1514 val = interval_free_list;
1515 interval_free_list = INTERVAL_PARENT (interval_free_list);
1517 else
1519 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1521 struct interval_block *newi
1522 = lisp_malloc (sizeof *newi, MEM_TYPE_NON_LISP);
1524 newi->next = interval_block;
1525 interval_block = newi;
1526 interval_block_index = 0;
1527 total_free_intervals += INTERVAL_BLOCK_SIZE;
1529 val = &interval_block->intervals[interval_block_index++];
1532 MALLOC_UNBLOCK_INPUT;
1534 consing_since_gc += sizeof (struct interval);
1535 intervals_consed++;
1536 total_free_intervals--;
1537 RESET_INTERVAL (val);
1538 val->gcmarkbit = 0;
1539 return val;
1543 /* Mark Lisp objects in interval I. */
1545 static void
1546 mark_interval (INTERVAL i, void *dummy)
1548 /* Intervals should never be shared. So, if extra internal checking is
1549 enabled, GC aborts if it seems to have visited an interval twice. */
1550 eassert (!i->gcmarkbit);
1551 i->gcmarkbit = 1;
1552 mark_object (i->plist);
1555 /* Mark the interval tree rooted in I. */
1557 #define MARK_INTERVAL_TREE(i) \
1558 do { \
1559 if (i && !i->gcmarkbit) \
1560 traverse_intervals_noorder (i, mark_interval, NULL); \
1561 } while (0)
1563 /***********************************************************************
1564 String Allocation
1565 ***********************************************************************/
1567 /* Lisp_Strings are allocated in string_block structures. When a new
1568 string_block is allocated, all the Lisp_Strings it contains are
1569 added to a free-list string_free_list. When a new Lisp_String is
1570 needed, it is taken from that list. During the sweep phase of GC,
1571 string_blocks that are entirely free are freed, except two which
1572 we keep.
1574 String data is allocated from sblock structures. Strings larger
1575 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1576 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1578 Sblocks consist internally of sdata structures, one for each
1579 Lisp_String. The sdata structure points to the Lisp_String it
1580 belongs to. The Lisp_String points back to the `u.data' member of
1581 its sdata structure.
1583 When a Lisp_String is freed during GC, it is put back on
1584 string_free_list, and its `data' member and its sdata's `string'
1585 pointer is set to null. The size of the string is recorded in the
1586 `n.nbytes' member of the sdata. So, sdata structures that are no
1587 longer used, can be easily recognized, and it's easy to compact the
1588 sblocks of small strings which we do in compact_small_strings. */
1590 /* Size in bytes of an sblock structure used for small strings. This
1591 is 8192 minus malloc overhead. */
1593 #define SBLOCK_SIZE 8188
1595 /* Strings larger than this are considered large strings. String data
1596 for large strings is allocated from individual sblocks. */
1598 #define LARGE_STRING_BYTES 1024
1600 /* The SDATA typedef is a struct or union describing string memory
1601 sub-allocated from an sblock. This is where the contents of Lisp
1602 strings are stored. */
1604 struct sdata
1606 /* Back-pointer to the string this sdata belongs to. If null, this
1607 structure is free, and NBYTES (in this structure or in the union below)
1608 contains the string's byte size (the same value that STRING_BYTES
1609 would return if STRING were non-null). If non-null, STRING_BYTES
1610 (STRING) is the size of the data, and DATA contains the string's
1611 contents. */
1612 struct Lisp_String *string;
1614 #ifdef GC_CHECK_STRING_BYTES
1615 ptrdiff_t nbytes;
1616 #endif
1618 unsigned char data[FLEXIBLE_ARRAY_MEMBER];
1621 #ifdef GC_CHECK_STRING_BYTES
1623 typedef struct sdata sdata;
1624 #define SDATA_NBYTES(S) (S)->nbytes
1625 #define SDATA_DATA(S) (S)->data
1627 #else
1629 typedef union
1631 struct Lisp_String *string;
1633 /* When STRING is nonnull, this union is actually of type 'struct sdata',
1634 which has a flexible array member. However, if implemented by
1635 giving this union a member of type 'struct sdata', the union
1636 could not be the last (flexible) member of 'struct sblock',
1637 because C99 prohibits a flexible array member from having a type
1638 that is itself a flexible array. So, comment this member out here,
1639 but remember that the option's there when using this union. */
1640 #if 0
1641 struct sdata u;
1642 #endif
1644 /* When STRING is null. */
1645 struct
1647 struct Lisp_String *string;
1648 ptrdiff_t nbytes;
1649 } n;
1650 } sdata;
1652 #define SDATA_NBYTES(S) (S)->n.nbytes
1653 #define SDATA_DATA(S) ((struct sdata *) (S))->data
1655 #endif /* not GC_CHECK_STRING_BYTES */
1657 enum { SDATA_DATA_OFFSET = offsetof (struct sdata, data) };
1659 /* Structure describing a block of memory which is sub-allocated to
1660 obtain string data memory for strings. Blocks for small strings
1661 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1662 as large as needed. */
1664 struct sblock
1666 /* Next in list. */
1667 struct sblock *next;
1669 /* Pointer to the next free sdata block. This points past the end
1670 of the sblock if there isn't any space left in this block. */
1671 sdata *next_free;
1673 /* String data. */
1674 sdata data[FLEXIBLE_ARRAY_MEMBER];
1677 /* Number of Lisp strings in a string_block structure. The 1020 is
1678 1024 minus malloc overhead. */
1680 #define STRING_BLOCK_SIZE \
1681 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1683 /* Structure describing a block from which Lisp_String structures
1684 are allocated. */
1686 struct string_block
1688 /* Place `strings' first, to preserve alignment. */
1689 struct Lisp_String strings[STRING_BLOCK_SIZE];
1690 struct string_block *next;
1693 /* Head and tail of the list of sblock structures holding Lisp string
1694 data. We always allocate from current_sblock. The NEXT pointers
1695 in the sblock structures go from oldest_sblock to current_sblock. */
1697 static struct sblock *oldest_sblock, *current_sblock;
1699 /* List of sblocks for large strings. */
1701 static struct sblock *large_sblocks;
1703 /* List of string_block structures. */
1705 static struct string_block *string_blocks;
1707 /* Free-list of Lisp_Strings. */
1709 static struct Lisp_String *string_free_list;
1711 /* Number of live and free Lisp_Strings. */
1713 static EMACS_INT total_strings, total_free_strings;
1715 /* Number of bytes used by live strings. */
1717 static EMACS_INT total_string_bytes;
1719 /* Given a pointer to a Lisp_String S which is on the free-list
1720 string_free_list, return a pointer to its successor in the
1721 free-list. */
1723 #define NEXT_FREE_LISP_STRING(S) ((S)->u.next)
1725 /* Return a pointer to the sdata structure belonging to Lisp string S.
1726 S must be live, i.e. S->data must not be null. S->data is actually
1727 a pointer to the `u.data' member of its sdata structure; the
1728 structure starts at a constant offset in front of that. */
1730 #define SDATA_OF_STRING(S) ((sdata *) ptr_bounds_init ((S)->u.s.data \
1731 - SDATA_DATA_OFFSET))
1734 #ifdef GC_CHECK_STRING_OVERRUN
1736 /* We check for overrun in string data blocks by appending a small
1737 "cookie" after each allocated string data block, and check for the
1738 presence of this cookie during GC. */
1740 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1741 static char const string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1742 { '\xde', '\xad', '\xbe', '\xef' };
1744 #else
1745 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1746 #endif
1748 /* Value is the size of an sdata structure large enough to hold NBYTES
1749 bytes of string data. The value returned includes a terminating
1750 NUL byte, the size of the sdata structure, and padding. */
1752 #ifdef GC_CHECK_STRING_BYTES
1754 #define SDATA_SIZE(NBYTES) FLEXSIZEOF (struct sdata, data, (NBYTES) + 1)
1756 #else /* not GC_CHECK_STRING_BYTES */
1758 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1759 less than the size of that member. The 'max' is not needed when
1760 SDATA_DATA_OFFSET is a multiple of FLEXALIGNOF (struct sdata),
1761 because then the alignment code reserves enough space. */
1763 #define SDATA_SIZE(NBYTES) \
1764 ((SDATA_DATA_OFFSET \
1765 + (SDATA_DATA_OFFSET % FLEXALIGNOF (struct sdata) == 0 \
1766 ? NBYTES \
1767 : max (NBYTES, FLEXALIGNOF (struct sdata) - 1)) \
1768 + 1 \
1769 + FLEXALIGNOF (struct sdata) - 1) \
1770 & ~(FLEXALIGNOF (struct sdata) - 1))
1772 #endif /* not GC_CHECK_STRING_BYTES */
1774 /* Extra bytes to allocate for each string. */
1776 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1778 /* Exact bound on the number of bytes in a string, not counting the
1779 terminating null. A string cannot contain more bytes than
1780 STRING_BYTES_BOUND, nor can it be so long that the size_t
1781 arithmetic in allocate_string_data would overflow while it is
1782 calculating a value to be passed to malloc. */
1783 static ptrdiff_t const STRING_BYTES_MAX =
1784 min (STRING_BYTES_BOUND,
1785 ((SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD
1786 - GC_STRING_EXTRA
1787 - offsetof (struct sblock, data)
1788 - SDATA_DATA_OFFSET)
1789 & ~(sizeof (EMACS_INT) - 1)));
1791 /* Initialize string allocation. Called from init_alloc_once. */
1793 static void
1794 init_strings (void)
1796 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1797 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1801 #ifdef GC_CHECK_STRING_BYTES
1803 static int check_string_bytes_count;
1805 /* Like STRING_BYTES, but with debugging check. Can be
1806 called during GC, so pay attention to the mark bit. */
1808 ptrdiff_t
1809 string_bytes (struct Lisp_String *s)
1811 ptrdiff_t nbytes =
1812 (s->u.s.size_byte < 0 ? s->u.s.size & ~ARRAY_MARK_FLAG : s->u.s.size_byte);
1814 if (!PURE_P (s) && s->u.s.data
1815 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1816 emacs_abort ();
1817 return nbytes;
1820 /* Check validity of Lisp strings' string_bytes member in B. */
1822 static void
1823 check_sblock (struct sblock *b)
1825 sdata *from, *end, *from_end;
1827 end = b->next_free;
1829 for (from = b->data; from < end; from = from_end)
1831 /* Compute the next FROM here because copying below may
1832 overwrite data we need to compute it. */
1833 ptrdiff_t nbytes;
1835 /* Check that the string size recorded in the string is the
1836 same as the one recorded in the sdata structure. */
1837 nbytes = SDATA_SIZE (from->string ? string_bytes (from->string)
1838 : SDATA_NBYTES (from));
1839 from_end = (sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1844 /* Check validity of Lisp strings' string_bytes member. ALL_P
1845 means check all strings, otherwise check only most
1846 recently allocated strings. Used for hunting a bug. */
1848 static void
1849 check_string_bytes (bool all_p)
1851 if (all_p)
1853 struct sblock *b;
1855 for (b = large_sblocks; b; b = b->next)
1857 struct Lisp_String *s = b->data[0].string;
1858 if (s)
1859 string_bytes (s);
1862 for (b = oldest_sblock; b; b = b->next)
1863 check_sblock (b);
1865 else if (current_sblock)
1866 check_sblock (current_sblock);
1869 #else /* not GC_CHECK_STRING_BYTES */
1871 #define check_string_bytes(all) ((void) 0)
1873 #endif /* GC_CHECK_STRING_BYTES */
1875 #ifdef GC_CHECK_STRING_FREE_LIST
1877 /* Walk through the string free list looking for bogus next pointers.
1878 This may catch buffer overrun from a previous string. */
1880 static void
1881 check_string_free_list (void)
1883 struct Lisp_String *s;
1885 /* Pop a Lisp_String off the free-list. */
1886 s = string_free_list;
1887 while (s != NULL)
1889 if ((uintptr_t) s < 1024)
1890 emacs_abort ();
1891 s = NEXT_FREE_LISP_STRING (s);
1894 #else
1895 #define check_string_free_list()
1896 #endif
1898 /* Return a new Lisp_String. */
1900 static struct Lisp_String *
1901 allocate_string (void)
1903 struct Lisp_String *s;
1905 MALLOC_BLOCK_INPUT;
1907 /* If the free-list is empty, allocate a new string_block, and
1908 add all the Lisp_Strings in it to the free-list. */
1909 if (string_free_list == NULL)
1911 struct string_block *b = lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1912 int i;
1914 b->next = string_blocks;
1915 string_blocks = b;
1917 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1919 s = b->strings + i;
1920 /* Every string on a free list should have NULL data pointer. */
1921 s->u.s.data = NULL;
1922 NEXT_FREE_LISP_STRING (s) = string_free_list;
1923 string_free_list = ptr_bounds_clip (s, sizeof *s);
1926 total_free_strings += STRING_BLOCK_SIZE;
1929 check_string_free_list ();
1931 /* Pop a Lisp_String off the free-list. */
1932 s = string_free_list;
1933 string_free_list = NEXT_FREE_LISP_STRING (s);
1935 MALLOC_UNBLOCK_INPUT;
1937 --total_free_strings;
1938 ++total_strings;
1939 ++strings_consed;
1940 consing_since_gc += sizeof *s;
1942 #ifdef GC_CHECK_STRING_BYTES
1943 if (!noninteractive)
1945 if (++check_string_bytes_count == 200)
1947 check_string_bytes_count = 0;
1948 check_string_bytes (1);
1950 else
1951 check_string_bytes (0);
1953 #endif /* GC_CHECK_STRING_BYTES */
1955 return s;
1959 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1960 plus a NUL byte at the end. Allocate an sdata structure DATA for
1961 S, and set S->u.s.data to SDATA->u.data. Store a NUL byte at the
1962 end of S->u.s.data. Set S->u.s.size to NCHARS and S->u.s.size_byte
1963 to NBYTES. Free S->u.s.data if it was initially non-null. */
1965 void
1966 allocate_string_data (struct Lisp_String *s,
1967 EMACS_INT nchars, EMACS_INT nbytes)
1969 sdata *data, *old_data;
1970 struct sblock *b;
1971 ptrdiff_t needed, old_nbytes;
1973 if (STRING_BYTES_MAX < nbytes)
1974 string_overflow ();
1976 /* Determine the number of bytes needed to store NBYTES bytes
1977 of string data. */
1978 needed = SDATA_SIZE (nbytes);
1979 if (s->u.s.data)
1981 old_data = SDATA_OF_STRING (s);
1982 old_nbytes = STRING_BYTES (s);
1984 else
1985 old_data = NULL;
1987 MALLOC_BLOCK_INPUT;
1989 if (nbytes > LARGE_STRING_BYTES)
1991 size_t size = FLEXSIZEOF (struct sblock, data, needed);
1993 #ifdef DOUG_LEA_MALLOC
1994 if (!mmap_lisp_allowed_p ())
1995 mallopt (M_MMAP_MAX, 0);
1996 #endif
1998 b = lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
2000 #ifdef DOUG_LEA_MALLOC
2001 if (!mmap_lisp_allowed_p ())
2002 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2003 #endif
2005 data = b->data;
2006 b->next = large_sblocks;
2007 b->next_free = data;
2008 large_sblocks = b;
2010 else if (current_sblock == NULL
2011 || (((char *) current_sblock + SBLOCK_SIZE
2012 - (char *) current_sblock->next_free)
2013 < (needed + GC_STRING_EXTRA)))
2015 /* Not enough room in the current sblock. */
2016 b = lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
2017 data = b->data;
2018 b->next = NULL;
2019 b->next_free = data;
2021 if (current_sblock)
2022 current_sblock->next = b;
2023 else
2024 oldest_sblock = b;
2025 current_sblock = b;
2027 else
2029 b = current_sblock;
2030 data = b->next_free;
2033 data->string = s;
2034 b->next_free = (sdata *) ((char *) data + needed + GC_STRING_EXTRA);
2036 MALLOC_UNBLOCK_INPUT;
2038 s->u.s.data = ptr_bounds_clip (SDATA_DATA (data), nbytes + 1);
2039 #ifdef GC_CHECK_STRING_BYTES
2040 SDATA_NBYTES (data) = nbytes;
2041 #endif
2042 s->u.s.size = nchars;
2043 s->u.s.size_byte = nbytes;
2044 s->u.s.data[nbytes] = '\0';
2045 #ifdef GC_CHECK_STRING_OVERRUN
2046 memcpy ((char *) data + needed, string_overrun_cookie,
2047 GC_STRING_OVERRUN_COOKIE_SIZE);
2048 #endif
2050 /* Note that Faset may call to this function when S has already data
2051 assigned. In this case, mark data as free by setting it's string
2052 back-pointer to null, and record the size of the data in it. */
2053 if (old_data)
2055 SDATA_NBYTES (old_data) = old_nbytes;
2056 old_data->string = NULL;
2059 consing_since_gc += needed;
2063 /* Sweep and compact strings. */
2065 NO_INLINE /* For better stack traces */
2066 static void
2067 sweep_strings (void)
2069 struct string_block *b, *next;
2070 struct string_block *live_blocks = NULL;
2072 string_free_list = NULL;
2073 total_strings = total_free_strings = 0;
2074 total_string_bytes = 0;
2076 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
2077 for (b = string_blocks; b; b = next)
2079 int i, nfree = 0;
2080 struct Lisp_String *free_list_before = string_free_list;
2082 next = b->next;
2084 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
2086 struct Lisp_String *s = b->strings + i;
2088 if (s->u.s.data)
2090 /* String was not on free-list before. */
2091 if (STRING_MARKED_P (s))
2093 /* String is live; unmark it and its intervals. */
2094 UNMARK_STRING (s);
2096 /* Do not use string_(set|get)_intervals here. */
2097 s->u.s.intervals = balance_intervals (s->u.s.intervals);
2099 ++total_strings;
2100 total_string_bytes += STRING_BYTES (s);
2102 else
2104 /* String is dead. Put it on the free-list. */
2105 sdata *data = SDATA_OF_STRING (s);
2107 /* Save the size of S in its sdata so that we know
2108 how large that is. Reset the sdata's string
2109 back-pointer so that we know it's free. */
2110 #ifdef GC_CHECK_STRING_BYTES
2111 if (string_bytes (s) != SDATA_NBYTES (data))
2112 emacs_abort ();
2113 #else
2114 data->n.nbytes = STRING_BYTES (s);
2115 #endif
2116 data->string = NULL;
2118 /* Reset the strings's `data' member so that we
2119 know it's free. */
2120 s->u.s.data = NULL;
2122 /* Put the string on the free-list. */
2123 NEXT_FREE_LISP_STRING (s) = string_free_list;
2124 string_free_list = ptr_bounds_clip (s, sizeof *s);
2125 ++nfree;
2128 else
2130 /* S was on the free-list before. Put it there again. */
2131 NEXT_FREE_LISP_STRING (s) = string_free_list;
2132 string_free_list = ptr_bounds_clip (s, sizeof *s);
2133 ++nfree;
2137 /* Free blocks that contain free Lisp_Strings only, except
2138 the first two of them. */
2139 if (nfree == STRING_BLOCK_SIZE
2140 && total_free_strings > STRING_BLOCK_SIZE)
2142 lisp_free (b);
2143 string_free_list = free_list_before;
2145 else
2147 total_free_strings += nfree;
2148 b->next = live_blocks;
2149 live_blocks = b;
2153 check_string_free_list ();
2155 string_blocks = live_blocks;
2156 free_large_strings ();
2157 compact_small_strings ();
2159 check_string_free_list ();
2163 /* Free dead large strings. */
2165 static void
2166 free_large_strings (void)
2168 struct sblock *b, *next;
2169 struct sblock *live_blocks = NULL;
2171 for (b = large_sblocks; b; b = next)
2173 next = b->next;
2175 if (b->data[0].string == NULL)
2176 lisp_free (b);
2177 else
2179 b->next = live_blocks;
2180 live_blocks = b;
2184 large_sblocks = live_blocks;
2188 /* Compact data of small strings. Free sblocks that don't contain
2189 data of live strings after compaction. */
2191 static void
2192 compact_small_strings (void)
2194 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2195 to, and TB_END is the end of TB. */
2196 struct sblock *tb = oldest_sblock;
2197 if (tb)
2199 sdata *tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
2200 sdata *to = tb->data;
2202 /* Step through the blocks from the oldest to the youngest. We
2203 expect that old blocks will stabilize over time, so that less
2204 copying will happen this way. */
2205 struct sblock *b = tb;
2208 sdata *end = b->next_free;
2209 eassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2211 for (sdata *from = b->data; from < end; )
2213 /* Compute the next FROM here because copying below may
2214 overwrite data we need to compute it. */
2215 ptrdiff_t nbytes;
2216 struct Lisp_String *s = from->string;
2218 #ifdef GC_CHECK_STRING_BYTES
2219 /* Check that the string size recorded in the string is the
2220 same as the one recorded in the sdata structure. */
2221 if (s && string_bytes (s) != SDATA_NBYTES (from))
2222 emacs_abort ();
2223 #endif /* GC_CHECK_STRING_BYTES */
2225 nbytes = s ? STRING_BYTES (s) : SDATA_NBYTES (from);
2226 eassert (nbytes <= LARGE_STRING_BYTES);
2228 ptrdiff_t size = SDATA_SIZE (nbytes);
2229 sdata *from_end = (sdata *) ((char *) from
2230 + size + GC_STRING_EXTRA);
2232 #ifdef GC_CHECK_STRING_OVERRUN
2233 if (memcmp (string_overrun_cookie,
2234 (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
2235 GC_STRING_OVERRUN_COOKIE_SIZE))
2236 emacs_abort ();
2237 #endif
2239 /* Non-NULL S means it's alive. Copy its data. */
2240 if (s)
2242 /* If TB is full, proceed with the next sblock. */
2243 sdata *to_end = (sdata *) ((char *) to
2244 + size + GC_STRING_EXTRA);
2245 if (to_end > tb_end)
2247 tb->next_free = to;
2248 tb = tb->next;
2249 tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
2250 to = tb->data;
2251 to_end = (sdata *) ((char *) to + size + GC_STRING_EXTRA);
2254 /* Copy, and update the string's `data' pointer. */
2255 if (from != to)
2257 eassert (tb != b || to < from);
2258 memmove (to, from, size + GC_STRING_EXTRA);
2259 to->string->u.s.data
2260 = ptr_bounds_clip (SDATA_DATA (to), nbytes + 1);
2263 /* Advance past the sdata we copied to. */
2264 to = to_end;
2266 from = from_end;
2268 b = b->next;
2270 while (b);
2272 /* The rest of the sblocks following TB don't contain live data, so
2273 we can free them. */
2274 for (b = tb->next; b; )
2276 struct sblock *next = b->next;
2277 lisp_free (b);
2278 b = next;
2281 tb->next_free = to;
2282 tb->next = NULL;
2285 current_sblock = tb;
2288 void
2289 string_overflow (void)
2291 error ("Maximum string size exceeded");
2294 DEFUN ("make-string", Fmake_string, Smake_string, 2, 3, 0,
2295 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2296 LENGTH must be an integer.
2297 INIT must be an integer that represents a character.
2298 If optional argument MULTIBYTE is non-nil, the result will be
2299 a multibyte string even if INIT is an ASCII character. */)
2300 (Lisp_Object length, Lisp_Object init, Lisp_Object multibyte)
2302 register Lisp_Object val;
2303 int c;
2304 EMACS_INT nbytes;
2306 CHECK_NATNUM (length);
2307 CHECK_CHARACTER (init);
2309 c = XFASTINT (init);
2310 if (ASCII_CHAR_P (c) && NILP (multibyte))
2312 nbytes = XINT (length);
2313 val = make_uninit_string (nbytes);
2314 if (nbytes)
2316 memset (SDATA (val), c, nbytes);
2317 SDATA (val)[nbytes] = 0;
2320 else
2322 unsigned char str[MAX_MULTIBYTE_LENGTH];
2323 ptrdiff_t len = CHAR_STRING (c, str);
2324 EMACS_INT string_len = XINT (length);
2325 unsigned char *p, *beg, *end;
2327 if (INT_MULTIPLY_WRAPV (len, string_len, &nbytes))
2328 string_overflow ();
2329 val = make_uninit_multibyte_string (string_len, nbytes);
2330 for (beg = SDATA (val), p = beg, end = beg + nbytes; p < end; p += len)
2332 /* First time we just copy `str' to the data of `val'. */
2333 if (p == beg)
2334 memcpy (p, str, len);
2335 else
2337 /* Next time we copy largest possible chunk from
2338 initialized to uninitialized part of `val'. */
2339 len = min (p - beg, end - p);
2340 memcpy (p, beg, len);
2343 if (nbytes)
2344 *p = 0;
2347 return val;
2350 /* Fill A with 1 bits if INIT is non-nil, and with 0 bits otherwise.
2351 Return A. */
2353 Lisp_Object
2354 bool_vector_fill (Lisp_Object a, Lisp_Object init)
2356 EMACS_INT nbits = bool_vector_size (a);
2357 if (0 < nbits)
2359 unsigned char *data = bool_vector_uchar_data (a);
2360 int pattern = NILP (init) ? 0 : (1 << BOOL_VECTOR_BITS_PER_CHAR) - 1;
2361 ptrdiff_t nbytes = bool_vector_bytes (nbits);
2362 int last_mask = ~ (~0u << ((nbits - 1) % BOOL_VECTOR_BITS_PER_CHAR + 1));
2363 memset (data, pattern, nbytes - 1);
2364 data[nbytes - 1] = pattern & last_mask;
2366 return a;
2369 /* Return a newly allocated, uninitialized bool vector of size NBITS. */
2371 Lisp_Object
2372 make_uninit_bool_vector (EMACS_INT nbits)
2374 Lisp_Object val;
2375 EMACS_INT words = bool_vector_words (nbits);
2376 EMACS_INT word_bytes = words * sizeof (bits_word);
2377 EMACS_INT needed_elements = ((bool_header_size - header_size + word_bytes
2378 + word_size - 1)
2379 / word_size);
2380 struct Lisp_Bool_Vector *p
2381 = (struct Lisp_Bool_Vector *) allocate_vector (needed_elements);
2382 XSETVECTOR (val, p);
2383 XSETPVECTYPESIZE (XVECTOR (val), PVEC_BOOL_VECTOR, 0, 0);
2384 p->size = nbits;
2386 /* Clear padding at the end. */
2387 if (words)
2388 p->data[words - 1] = 0;
2390 return val;
2393 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2394 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2395 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2396 (Lisp_Object length, Lisp_Object init)
2398 Lisp_Object val;
2400 CHECK_NATNUM (length);
2401 val = make_uninit_bool_vector (XFASTINT (length));
2402 return bool_vector_fill (val, init);
2405 DEFUN ("bool-vector", Fbool_vector, Sbool_vector, 0, MANY, 0,
2406 doc: /* Return a new bool-vector with specified arguments as elements.
2407 Any number of arguments, even zero arguments, are allowed.
2408 usage: (bool-vector &rest OBJECTS) */)
2409 (ptrdiff_t nargs, Lisp_Object *args)
2411 ptrdiff_t i;
2412 Lisp_Object vector;
2414 vector = make_uninit_bool_vector (nargs);
2415 for (i = 0; i < nargs; i++)
2416 bool_vector_set (vector, i, !NILP (args[i]));
2418 return vector;
2421 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2422 of characters from the contents. This string may be unibyte or
2423 multibyte, depending on the contents. */
2425 Lisp_Object
2426 make_string (const char *contents, ptrdiff_t nbytes)
2428 register Lisp_Object val;
2429 ptrdiff_t nchars, multibyte_nbytes;
2431 parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
2432 &nchars, &multibyte_nbytes);
2433 if (nbytes == nchars || nbytes != multibyte_nbytes)
2434 /* CONTENTS contains no multibyte sequences or contains an invalid
2435 multibyte sequence. We must make unibyte string. */
2436 val = make_unibyte_string (contents, nbytes);
2437 else
2438 val = make_multibyte_string (contents, nchars, nbytes);
2439 return val;
2442 /* Make a unibyte string from LENGTH bytes at CONTENTS. */
2444 Lisp_Object
2445 make_unibyte_string (const char *contents, ptrdiff_t length)
2447 register Lisp_Object val;
2448 val = make_uninit_string (length);
2449 memcpy (SDATA (val), contents, length);
2450 return val;
2454 /* Make a multibyte string from NCHARS characters occupying NBYTES
2455 bytes at CONTENTS. */
2457 Lisp_Object
2458 make_multibyte_string (const char *contents,
2459 ptrdiff_t nchars, ptrdiff_t nbytes)
2461 register Lisp_Object val;
2462 val = make_uninit_multibyte_string (nchars, nbytes);
2463 memcpy (SDATA (val), contents, nbytes);
2464 return val;
2468 /* Make a string from NCHARS characters occupying NBYTES bytes at
2469 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2471 Lisp_Object
2472 make_string_from_bytes (const char *contents,
2473 ptrdiff_t nchars, ptrdiff_t nbytes)
2475 register Lisp_Object val;
2476 val = make_uninit_multibyte_string (nchars, nbytes);
2477 memcpy (SDATA (val), contents, nbytes);
2478 if (SBYTES (val) == SCHARS (val))
2479 STRING_SET_UNIBYTE (val);
2480 return val;
2484 /* Make a string from NCHARS characters occupying NBYTES bytes at
2485 CONTENTS. The argument MULTIBYTE controls whether to label the
2486 string as multibyte. If NCHARS is negative, it counts the number of
2487 characters by itself. */
2489 Lisp_Object
2490 make_specified_string (const char *contents,
2491 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
2493 Lisp_Object val;
2495 if (nchars < 0)
2497 if (multibyte)
2498 nchars = multibyte_chars_in_text ((const unsigned char *) contents,
2499 nbytes);
2500 else
2501 nchars = nbytes;
2503 val = make_uninit_multibyte_string (nchars, nbytes);
2504 memcpy (SDATA (val), contents, nbytes);
2505 if (!multibyte)
2506 STRING_SET_UNIBYTE (val);
2507 return val;
2511 /* Return a unibyte Lisp_String set up to hold LENGTH characters
2512 occupying LENGTH bytes. */
2514 Lisp_Object
2515 make_uninit_string (EMACS_INT length)
2517 Lisp_Object val;
2519 if (!length)
2520 return empty_unibyte_string;
2521 val = make_uninit_multibyte_string (length, length);
2522 STRING_SET_UNIBYTE (val);
2523 return val;
2527 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2528 which occupy NBYTES bytes. */
2530 Lisp_Object
2531 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2533 Lisp_Object string;
2534 struct Lisp_String *s;
2536 if (nchars < 0)
2537 emacs_abort ();
2538 if (!nbytes)
2539 return empty_multibyte_string;
2541 s = allocate_string ();
2542 s->u.s.intervals = NULL;
2543 allocate_string_data (s, nchars, nbytes);
2544 XSETSTRING (string, s);
2545 string_chars_consed += nbytes;
2546 return string;
2549 /* Print arguments to BUF according to a FORMAT, then return
2550 a Lisp_String initialized with the data from BUF. */
2552 Lisp_Object
2553 make_formatted_string (char *buf, const char *format, ...)
2555 va_list ap;
2556 int length;
2558 va_start (ap, format);
2559 length = vsprintf (buf, format, ap);
2560 va_end (ap);
2561 return make_string (buf, length);
2565 /***********************************************************************
2566 Float Allocation
2567 ***********************************************************************/
2569 /* We store float cells inside of float_blocks, allocating a new
2570 float_block with malloc whenever necessary. Float cells reclaimed
2571 by GC are put on a free list to be reallocated before allocating
2572 any new float cells from the latest float_block. */
2574 #define FLOAT_BLOCK_SIZE \
2575 (((BLOCK_BYTES - sizeof (struct float_block *) \
2576 /* The compiler might add padding at the end. */ \
2577 - (sizeof (struct Lisp_Float) - sizeof (bits_word))) * CHAR_BIT) \
2578 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2580 #define GETMARKBIT(block,n) \
2581 (((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2582 >> ((n) % BITS_PER_BITS_WORD)) \
2583 & 1)
2585 #define SETMARKBIT(block,n) \
2586 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2587 |= (bits_word) 1 << ((n) % BITS_PER_BITS_WORD))
2589 #define UNSETMARKBIT(block,n) \
2590 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2591 &= ~((bits_word) 1 << ((n) % BITS_PER_BITS_WORD)))
2593 #define FLOAT_BLOCK(fptr) \
2594 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2596 #define FLOAT_INDEX(fptr) \
2597 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2599 struct float_block
2601 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2602 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2603 bits_word gcmarkbits[1 + FLOAT_BLOCK_SIZE / BITS_PER_BITS_WORD];
2604 struct float_block *next;
2607 #define FLOAT_MARKED_P(fptr) \
2608 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2610 #define FLOAT_MARK(fptr) \
2611 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2613 #define FLOAT_UNMARK(fptr) \
2614 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2616 /* Current float_block. */
2618 static struct float_block *float_block;
2620 /* Index of first unused Lisp_Float in the current float_block. */
2622 static int float_block_index = FLOAT_BLOCK_SIZE;
2624 /* Free-list of Lisp_Floats. */
2626 static struct Lisp_Float *float_free_list;
2628 /* Return a new float object with value FLOAT_VALUE. */
2630 Lisp_Object
2631 make_float (double float_value)
2633 register Lisp_Object val;
2635 MALLOC_BLOCK_INPUT;
2637 if (float_free_list)
2639 /* We use the data field for chaining the free list
2640 so that we won't use the same field that has the mark bit. */
2641 XSETFLOAT (val, float_free_list);
2642 float_free_list = float_free_list->u.chain;
2644 else
2646 if (float_block_index == FLOAT_BLOCK_SIZE)
2648 struct float_block *new
2649 = lisp_align_malloc (sizeof *new, MEM_TYPE_FLOAT);
2650 new->next = float_block;
2651 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2652 float_block = new;
2653 float_block_index = 0;
2654 total_free_floats += FLOAT_BLOCK_SIZE;
2656 XSETFLOAT (val, &float_block->floats[float_block_index]);
2657 float_block_index++;
2660 MALLOC_UNBLOCK_INPUT;
2662 XFLOAT_INIT (val, float_value);
2663 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2664 consing_since_gc += sizeof (struct Lisp_Float);
2665 floats_consed++;
2666 total_free_floats--;
2667 return val;
2672 /***********************************************************************
2673 Cons Allocation
2674 ***********************************************************************/
2676 /* We store cons cells inside of cons_blocks, allocating a new
2677 cons_block with malloc whenever necessary. Cons cells reclaimed by
2678 GC are put on a free list to be reallocated before allocating
2679 any new cons cells from the latest cons_block. */
2681 #define CONS_BLOCK_SIZE \
2682 (((BLOCK_BYTES - sizeof (struct cons_block *) \
2683 /* The compiler might add padding at the end. */ \
2684 - (sizeof (struct Lisp_Cons) - sizeof (bits_word))) * CHAR_BIT) \
2685 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2687 #define CONS_BLOCK(fptr) \
2688 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2690 #define CONS_INDEX(fptr) \
2691 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2693 struct cons_block
2695 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2696 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2697 bits_word gcmarkbits[1 + CONS_BLOCK_SIZE / BITS_PER_BITS_WORD];
2698 struct cons_block *next;
2701 #define CONS_MARKED_P(fptr) \
2702 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2704 #define CONS_MARK(fptr) \
2705 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2707 #define CONS_UNMARK(fptr) \
2708 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2710 /* Current cons_block. */
2712 static struct cons_block *cons_block;
2714 /* Index of first unused Lisp_Cons in the current block. */
2716 static int cons_block_index = CONS_BLOCK_SIZE;
2718 /* Free-list of Lisp_Cons structures. */
2720 static struct Lisp_Cons *cons_free_list;
2722 /* Explicitly free a cons cell by putting it on the free-list. */
2724 void
2725 free_cons (struct Lisp_Cons *ptr)
2727 ptr->u.s.u.chain = cons_free_list;
2728 ptr->u.s.car = Vdead;
2729 cons_free_list = ptr;
2730 consing_since_gc -= sizeof *ptr;
2731 total_free_conses++;
2734 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2735 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2736 (Lisp_Object car, Lisp_Object cdr)
2738 register Lisp_Object val;
2740 MALLOC_BLOCK_INPUT;
2742 if (cons_free_list)
2744 /* We use the cdr for chaining the free list
2745 so that we won't use the same field that has the mark bit. */
2746 XSETCONS (val, cons_free_list);
2747 cons_free_list = cons_free_list->u.s.u.chain;
2749 else
2751 if (cons_block_index == CONS_BLOCK_SIZE)
2753 struct cons_block *new
2754 = lisp_align_malloc (sizeof *new, MEM_TYPE_CONS);
2755 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2756 new->next = cons_block;
2757 cons_block = new;
2758 cons_block_index = 0;
2759 total_free_conses += CONS_BLOCK_SIZE;
2761 XSETCONS (val, &cons_block->conses[cons_block_index]);
2762 cons_block_index++;
2765 MALLOC_UNBLOCK_INPUT;
2767 XSETCAR (val, car);
2768 XSETCDR (val, cdr);
2769 eassert (!CONS_MARKED_P (XCONS (val)));
2770 consing_since_gc += sizeof (struct Lisp_Cons);
2771 total_free_conses--;
2772 cons_cells_consed++;
2773 return val;
2776 #ifdef GC_CHECK_CONS_LIST
2777 /* Get an error now if there's any junk in the cons free list. */
2778 void
2779 check_cons_list (void)
2781 struct Lisp_Cons *tail = cons_free_list;
2783 while (tail)
2784 tail = tail->u.s.u.chain;
2786 #endif
2788 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2790 Lisp_Object
2791 list1 (Lisp_Object arg1)
2793 return Fcons (arg1, Qnil);
2796 Lisp_Object
2797 list2 (Lisp_Object arg1, Lisp_Object arg2)
2799 return Fcons (arg1, Fcons (arg2, Qnil));
2803 Lisp_Object
2804 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2806 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2810 Lisp_Object
2811 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2813 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2817 Lisp_Object
2818 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2820 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2821 Fcons (arg5, Qnil)))));
2824 /* Make a list of COUNT Lisp_Objects, where ARG is the
2825 first one. Allocate conses from pure space if TYPE
2826 is CONSTYPE_PURE, or allocate as usual if type is CONSTYPE_HEAP. */
2828 Lisp_Object
2829 listn (enum constype type, ptrdiff_t count, Lisp_Object arg, ...)
2831 Lisp_Object (*cons) (Lisp_Object, Lisp_Object);
2832 switch (type)
2834 case CONSTYPE_PURE: cons = pure_cons; break;
2835 case CONSTYPE_HEAP: cons = Fcons; break;
2836 default: emacs_abort ();
2839 eassume (0 < count);
2840 Lisp_Object val = cons (arg, Qnil);
2841 Lisp_Object tail = val;
2843 va_list ap;
2844 va_start (ap, arg);
2845 for (ptrdiff_t i = 1; i < count; i++)
2847 Lisp_Object elem = cons (va_arg (ap, Lisp_Object), Qnil);
2848 XSETCDR (tail, elem);
2849 tail = elem;
2851 va_end (ap);
2853 return val;
2856 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2857 doc: /* Return a newly created list with specified arguments as elements.
2858 Any number of arguments, even zero arguments, are allowed.
2859 usage: (list &rest OBJECTS) */)
2860 (ptrdiff_t nargs, Lisp_Object *args)
2862 register Lisp_Object val;
2863 val = Qnil;
2865 while (nargs > 0)
2867 nargs--;
2868 val = Fcons (args[nargs], val);
2870 return val;
2874 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2875 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2876 (Lisp_Object length, Lisp_Object init)
2878 Lisp_Object val = Qnil;
2879 CHECK_NATNUM (length);
2881 for (EMACS_INT size = XFASTINT (length); 0 < size; size--)
2883 val = Fcons (init, val);
2884 rarely_quit (size);
2887 return val;
2892 /***********************************************************************
2893 Vector Allocation
2894 ***********************************************************************/
2896 /* Sometimes a vector's contents are merely a pointer internally used
2897 in vector allocation code. On the rare platforms where a null
2898 pointer cannot be tagged, represent it with a Lisp 0.
2899 Usually you don't want to touch this. */
2901 static struct Lisp_Vector *
2902 next_vector (struct Lisp_Vector *v)
2904 return XUNTAG (v->contents[0], Lisp_Int0);
2907 static void
2908 set_next_vector (struct Lisp_Vector *v, struct Lisp_Vector *p)
2910 v->contents[0] = make_lisp_ptr (p, Lisp_Int0);
2913 /* This value is balanced well enough to avoid too much internal overhead
2914 for the most common cases; it's not required to be a power of two, but
2915 it's expected to be a mult-of-ROUNDUP_SIZE (see below). */
2917 #define VECTOR_BLOCK_SIZE 4096
2919 /* Alignment of struct Lisp_Vector objects. Because pseudovectors
2920 can contain any C type, align at least as strictly as
2921 max_align_t. On x86 and x86-64 this can waste up to 8 bytes
2922 for typical vectors, since alignof (max_align_t) is 16 but
2923 typical vectors need only an alignment of 8. However, it is
2924 not worth the hassle to avoid wasting those bytes. */
2925 enum {vector_alignment = COMMON_MULTIPLE (alignof (max_align_t), GCALIGNMENT)};
2927 /* Vector size requests are a multiple of this. */
2928 enum { roundup_size = COMMON_MULTIPLE (vector_alignment, word_size) };
2930 /* Verify assumptions described above. */
2931 verify (VECTOR_BLOCK_SIZE % roundup_size == 0);
2932 verify (VECTOR_BLOCK_SIZE <= (1 << PSEUDOVECTOR_SIZE_BITS));
2934 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at compile time. */
2935 #define vroundup_ct(x) ROUNDUP (x, roundup_size)
2936 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at runtime. */
2937 #define vroundup(x) (eassume ((x) >= 0), vroundup_ct (x))
2939 /* Rounding helps to maintain alignment constraints if USE_LSB_TAG. */
2941 #define VECTOR_BLOCK_BYTES (VECTOR_BLOCK_SIZE - vroundup_ct (sizeof (void *)))
2943 /* Size of the minimal vector allocated from block. */
2945 #define VBLOCK_BYTES_MIN vroundup_ct (header_size + sizeof (Lisp_Object))
2947 /* Size of the largest vector allocated from block. */
2949 #define VBLOCK_BYTES_MAX \
2950 vroundup ((VECTOR_BLOCK_BYTES / 2) - word_size)
2952 /* We maintain one free list for each possible block-allocated
2953 vector size, and this is the number of free lists we have. */
2955 #define VECTOR_MAX_FREE_LIST_INDEX \
2956 ((VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN) / roundup_size + 1)
2958 /* Common shortcut to advance vector pointer over a block data. */
2960 static struct Lisp_Vector *
2961 ADVANCE (struct Lisp_Vector *v, ptrdiff_t nbytes)
2963 void *vv = v;
2964 char *cv = vv;
2965 void *p = cv + nbytes;
2966 return p;
2969 /* Common shortcut to calculate NBYTES-vector index in VECTOR_FREE_LISTS. */
2971 static ptrdiff_t
2972 VINDEX (ptrdiff_t nbytes)
2974 eassume (VBLOCK_BYTES_MIN <= nbytes);
2975 return (nbytes - VBLOCK_BYTES_MIN) / roundup_size;
2978 /* This internal type is used to maintain the list of large vectors
2979 which are allocated at their own, e.g. outside of vector blocks.
2981 struct large_vector itself cannot contain a struct Lisp_Vector, as
2982 the latter contains a flexible array member and C99 does not allow
2983 such structs to be nested. Instead, each struct large_vector
2984 object LV is followed by a struct Lisp_Vector, which is at offset
2985 large_vector_offset from LV, and whose address is therefore
2986 large_vector_vec (&LV). */
2988 struct large_vector
2990 struct large_vector *next;
2993 enum
2995 large_vector_offset = ROUNDUP (sizeof (struct large_vector), vector_alignment)
2998 static struct Lisp_Vector *
2999 large_vector_vec (struct large_vector *p)
3001 return (struct Lisp_Vector *) ((char *) p + large_vector_offset);
3004 /* This internal type is used to maintain an underlying storage
3005 for small vectors. */
3007 struct vector_block
3009 char data[VECTOR_BLOCK_BYTES];
3010 struct vector_block *next;
3013 /* Chain of vector blocks. */
3015 static struct vector_block *vector_blocks;
3017 /* Vector free lists, where NTH item points to a chain of free
3018 vectors of the same NBYTES size, so NTH == VINDEX (NBYTES). */
3020 static struct Lisp_Vector *vector_free_lists[VECTOR_MAX_FREE_LIST_INDEX];
3022 /* Singly-linked list of large vectors. */
3024 static struct large_vector *large_vectors;
3026 /* The only vector with 0 slots, allocated from pure space. */
3028 Lisp_Object zero_vector;
3030 /* Number of live vectors. */
3032 static EMACS_INT total_vectors;
3034 /* Total size of live and free vectors, in Lisp_Object units. */
3036 static EMACS_INT total_vector_slots, total_free_vector_slots;
3038 /* Common shortcut to setup vector on a free list. */
3040 static void
3041 setup_on_free_list (struct Lisp_Vector *v, ptrdiff_t nbytes)
3043 v = ptr_bounds_clip (v, nbytes);
3044 eassume (header_size <= nbytes);
3045 ptrdiff_t nwords = (nbytes - header_size) / word_size;
3046 XSETPVECTYPESIZE (v, PVEC_FREE, 0, nwords);
3047 eassert (nbytes % roundup_size == 0);
3048 ptrdiff_t vindex = VINDEX (nbytes);
3049 eassert (vindex < VECTOR_MAX_FREE_LIST_INDEX);
3050 set_next_vector (v, vector_free_lists[vindex]);
3051 vector_free_lists[vindex] = v;
3052 total_free_vector_slots += nbytes / word_size;
3055 /* Get a new vector block. */
3057 static struct vector_block *
3058 allocate_vector_block (void)
3060 struct vector_block *block = xmalloc (sizeof *block);
3062 #ifndef GC_MALLOC_CHECK
3063 mem_insert (block->data, block->data + VECTOR_BLOCK_BYTES,
3064 MEM_TYPE_VECTOR_BLOCK);
3065 #endif
3067 block->next = vector_blocks;
3068 vector_blocks = block;
3069 return block;
3072 /* Called once to initialize vector allocation. */
3074 static void
3075 init_vectors (void)
3077 zero_vector = make_pure_vector (0);
3080 /* Allocate vector from a vector block. */
3082 static struct Lisp_Vector *
3083 allocate_vector_from_block (size_t nbytes)
3085 struct Lisp_Vector *vector;
3086 struct vector_block *block;
3087 size_t index, restbytes;
3089 eassert (VBLOCK_BYTES_MIN <= nbytes && nbytes <= VBLOCK_BYTES_MAX);
3090 eassert (nbytes % roundup_size == 0);
3092 /* First, try to allocate from a free list
3093 containing vectors of the requested size. */
3094 index = VINDEX (nbytes);
3095 if (vector_free_lists[index])
3097 vector = vector_free_lists[index];
3098 vector_free_lists[index] = next_vector (vector);
3099 total_free_vector_slots -= nbytes / word_size;
3100 return vector;
3103 /* Next, check free lists containing larger vectors. Since
3104 we will split the result, we should have remaining space
3105 large enough to use for one-slot vector at least. */
3106 for (index = VINDEX (nbytes + VBLOCK_BYTES_MIN);
3107 index < VECTOR_MAX_FREE_LIST_INDEX; index++)
3108 if (vector_free_lists[index])
3110 /* This vector is larger than requested. */
3111 vector = vector_free_lists[index];
3112 vector_free_lists[index] = next_vector (vector);
3113 total_free_vector_slots -= nbytes / word_size;
3115 /* Excess bytes are used for the smaller vector,
3116 which should be set on an appropriate free list. */
3117 restbytes = index * roundup_size + VBLOCK_BYTES_MIN - nbytes;
3118 eassert (restbytes % roundup_size == 0);
3119 setup_on_free_list (ADVANCE (vector, nbytes), restbytes);
3120 return vector;
3123 /* Finally, need a new vector block. */
3124 block = allocate_vector_block ();
3126 /* New vector will be at the beginning of this block. */
3127 vector = (struct Lisp_Vector *) block->data;
3129 /* If the rest of space from this block is large enough
3130 for one-slot vector at least, set up it on a free list. */
3131 restbytes = VECTOR_BLOCK_BYTES - nbytes;
3132 if (restbytes >= VBLOCK_BYTES_MIN)
3134 eassert (restbytes % roundup_size == 0);
3135 setup_on_free_list (ADVANCE (vector, nbytes), restbytes);
3137 return vector;
3140 /* Nonzero if VECTOR pointer is valid pointer inside BLOCK. */
3142 #define VECTOR_IN_BLOCK(vector, block) \
3143 ((char *) (vector) <= (block)->data \
3144 + VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN)
3146 /* Return the memory footprint of V in bytes. */
3148 static ptrdiff_t
3149 vector_nbytes (struct Lisp_Vector *v)
3151 ptrdiff_t size = v->header.size & ~ARRAY_MARK_FLAG;
3152 ptrdiff_t nwords;
3154 if (size & PSEUDOVECTOR_FLAG)
3156 if (PSEUDOVECTOR_TYPEP (&v->header, PVEC_BOOL_VECTOR))
3158 struct Lisp_Bool_Vector *bv = (struct Lisp_Bool_Vector *) v;
3159 ptrdiff_t word_bytes = (bool_vector_words (bv->size)
3160 * sizeof (bits_word));
3161 ptrdiff_t boolvec_bytes = bool_header_size + word_bytes;
3162 verify (header_size <= bool_header_size);
3163 nwords = (boolvec_bytes - header_size + word_size - 1) / word_size;
3165 else
3166 nwords = ((size & PSEUDOVECTOR_SIZE_MASK)
3167 + ((size & PSEUDOVECTOR_REST_MASK)
3168 >> PSEUDOVECTOR_SIZE_BITS));
3170 else
3171 nwords = size;
3172 return vroundup (header_size + word_size * nwords);
3175 /* Release extra resources still in use by VECTOR, which may be any
3176 vector-like object. */
3178 static void
3179 cleanup_vector (struct Lisp_Vector *vector)
3181 detect_suspicious_free (vector);
3182 if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FONT)
3183 && ((vector->header.size & PSEUDOVECTOR_SIZE_MASK)
3184 == FONT_OBJECT_MAX))
3186 struct font_driver const *drv = ((struct font *) vector)->driver;
3188 /* The font driver might sometimes be NULL, e.g. if Emacs was
3189 interrupted before it had time to set it up. */
3190 if (drv)
3192 /* Attempt to catch subtle bugs like Bug#16140. */
3193 eassert (valid_font_driver (drv));
3194 drv->close ((struct font *) vector);
3198 if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_THREAD))
3199 finalize_one_thread ((struct thread_state *) vector);
3200 else if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_MUTEX))
3201 finalize_one_mutex ((struct Lisp_Mutex *) vector);
3202 else if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_CONDVAR))
3203 finalize_one_condvar ((struct Lisp_CondVar *) vector);
3206 /* Reclaim space used by unmarked vectors. */
3208 NO_INLINE /* For better stack traces */
3209 static void
3210 sweep_vectors (void)
3212 struct vector_block *block, **bprev = &vector_blocks;
3213 struct large_vector *lv, **lvprev = &large_vectors;
3214 struct Lisp_Vector *vector, *next;
3216 total_vectors = total_vector_slots = total_free_vector_slots = 0;
3217 memset (vector_free_lists, 0, sizeof (vector_free_lists));
3219 /* Looking through vector blocks. */
3221 for (block = vector_blocks; block; block = *bprev)
3223 bool free_this_block = 0;
3224 ptrdiff_t nbytes;
3226 for (vector = (struct Lisp_Vector *) block->data;
3227 VECTOR_IN_BLOCK (vector, block); vector = next)
3229 if (VECTOR_MARKED_P (vector))
3231 VECTOR_UNMARK (vector);
3232 total_vectors++;
3233 nbytes = vector_nbytes (vector);
3234 total_vector_slots += nbytes / word_size;
3235 next = ADVANCE (vector, nbytes);
3237 else
3239 ptrdiff_t total_bytes;
3241 cleanup_vector (vector);
3242 nbytes = vector_nbytes (vector);
3243 total_bytes = nbytes;
3244 next = ADVANCE (vector, nbytes);
3246 /* While NEXT is not marked, try to coalesce with VECTOR,
3247 thus making VECTOR of the largest possible size. */
3249 while (VECTOR_IN_BLOCK (next, block))
3251 if (VECTOR_MARKED_P (next))
3252 break;
3253 cleanup_vector (next);
3254 nbytes = vector_nbytes (next);
3255 total_bytes += nbytes;
3256 next = ADVANCE (next, nbytes);
3259 eassert (total_bytes % roundup_size == 0);
3261 if (vector == (struct Lisp_Vector *) block->data
3262 && !VECTOR_IN_BLOCK (next, block))
3263 /* This block should be freed because all of its
3264 space was coalesced into the only free vector. */
3265 free_this_block = 1;
3266 else
3267 setup_on_free_list (vector, total_bytes);
3271 if (free_this_block)
3273 *bprev = block->next;
3274 #ifndef GC_MALLOC_CHECK
3275 mem_delete (mem_find (block->data));
3276 #endif
3277 xfree (block);
3279 else
3280 bprev = &block->next;
3283 /* Sweep large vectors. */
3285 for (lv = large_vectors; lv; lv = *lvprev)
3287 vector = large_vector_vec (lv);
3288 if (VECTOR_MARKED_P (vector))
3290 VECTOR_UNMARK (vector);
3291 total_vectors++;
3292 if (vector->header.size & PSEUDOVECTOR_FLAG)
3293 total_vector_slots += vector_nbytes (vector) / word_size;
3294 else
3295 total_vector_slots
3296 += header_size / word_size + vector->header.size;
3297 lvprev = &lv->next;
3299 else
3301 *lvprev = lv->next;
3302 lisp_free (lv);
3307 /* Value is a pointer to a newly allocated Lisp_Vector structure
3308 with room for LEN Lisp_Objects. */
3310 static struct Lisp_Vector *
3311 allocate_vectorlike (ptrdiff_t len)
3313 if (len == 0)
3314 return XVECTOR (zero_vector);
3315 else
3317 size_t nbytes = header_size + len * word_size;
3318 struct Lisp_Vector *p;
3320 MALLOC_BLOCK_INPUT;
3322 #ifdef DOUG_LEA_MALLOC
3323 if (!mmap_lisp_allowed_p ())
3324 mallopt (M_MMAP_MAX, 0);
3325 #endif
3327 if (nbytes <= VBLOCK_BYTES_MAX)
3328 p = allocate_vector_from_block (vroundup (nbytes));
3329 else
3331 struct large_vector *lv
3332 = lisp_malloc ((large_vector_offset + header_size
3333 + len * word_size),
3334 MEM_TYPE_VECTORLIKE);
3335 lv->next = large_vectors;
3336 large_vectors = lv;
3337 p = large_vector_vec (lv);
3340 #ifdef DOUG_LEA_MALLOC
3341 if (!mmap_lisp_allowed_p ())
3342 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
3343 #endif
3345 if (find_suspicious_object_in_range (p, (char *) p + nbytes))
3346 emacs_abort ();
3348 consing_since_gc += nbytes;
3349 vector_cells_consed += len;
3351 MALLOC_UNBLOCK_INPUT;
3353 return ptr_bounds_clip (p, nbytes);
3358 /* Allocate a vector with LEN slots. */
3360 struct Lisp_Vector *
3361 allocate_vector (EMACS_INT len)
3363 struct Lisp_Vector *v;
3364 ptrdiff_t nbytes_max = min (PTRDIFF_MAX, SIZE_MAX);
3366 if (min ((nbytes_max - header_size) / word_size, MOST_POSITIVE_FIXNUM) < len)
3367 memory_full (SIZE_MAX);
3368 v = allocate_vectorlike (len);
3369 if (len)
3370 v->header.size = len;
3371 return v;
3375 /* Allocate other vector-like structures. */
3377 struct Lisp_Vector *
3378 allocate_pseudovector (int memlen, int lisplen,
3379 int zerolen, enum pvec_type tag)
3381 struct Lisp_Vector *v = allocate_vectorlike (memlen);
3383 /* Catch bogus values. */
3384 eassert (0 <= tag && tag <= PVEC_FONT);
3385 eassert (0 <= lisplen && lisplen <= zerolen && zerolen <= memlen);
3386 eassert (memlen - lisplen <= (1 << PSEUDOVECTOR_REST_BITS) - 1);
3387 eassert (lisplen <= PSEUDOVECTOR_SIZE_MASK);
3389 /* Only the first LISPLEN slots will be traced normally by the GC. */
3390 memclear (v->contents, zerolen * word_size);
3391 XSETPVECTYPESIZE (v, tag, lisplen, memlen - lisplen);
3392 return v;
3395 struct buffer *
3396 allocate_buffer (void)
3398 struct buffer *b = lisp_malloc (sizeof *b, MEM_TYPE_BUFFER);
3400 BUFFER_PVEC_INIT (b);
3401 /* Put B on the chain of all buffers including killed ones. */
3402 b->next = all_buffers;
3403 all_buffers = b;
3404 /* Note that the rest fields of B are not initialized. */
3405 return b;
3409 /* Allocate a record with COUNT slots. COUNT must be positive, and
3410 includes the type slot. */
3412 static struct Lisp_Vector *
3413 allocate_record (EMACS_INT count)
3415 if (count > PSEUDOVECTOR_SIZE_MASK)
3416 error ("Attempt to allocate a record of %"pI"d slots; max is %d",
3417 count, PSEUDOVECTOR_SIZE_MASK);
3418 struct Lisp_Vector *p = allocate_vectorlike (count);
3419 p->header.size = count;
3420 XSETPVECTYPE (p, PVEC_RECORD);
3421 return p;
3425 DEFUN ("make-record", Fmake_record, Smake_record, 3, 3, 0,
3426 doc: /* Create a new record.
3427 TYPE is its type as returned by `type-of'; it should be either a
3428 symbol or a type descriptor. SLOTS is the number of non-type slots,
3429 each initialized to INIT. */)
3430 (Lisp_Object type, Lisp_Object slots, Lisp_Object init)
3432 CHECK_NATNUM (slots);
3433 EMACS_INT size = XFASTINT (slots) + 1;
3434 struct Lisp_Vector *p = allocate_record (size);
3435 p->contents[0] = type;
3436 for (ptrdiff_t i = 1; i < size; i++)
3437 p->contents[i] = init;
3438 return make_lisp_ptr (p, Lisp_Vectorlike);
3442 DEFUN ("record", Frecord, Srecord, 1, MANY, 0,
3443 doc: /* Create a new record.
3444 TYPE is its type as returned by `type-of'; it should be either a
3445 symbol or a type descriptor. SLOTS is used to initialize the record
3446 slots with shallow copies of the arguments.
3447 usage: (record TYPE &rest SLOTS) */)
3448 (ptrdiff_t nargs, Lisp_Object *args)
3450 struct Lisp_Vector *p = allocate_record (nargs);
3451 memcpy (p->contents, args, nargs * sizeof *args);
3452 return make_lisp_ptr (p, Lisp_Vectorlike);
3456 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
3457 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
3458 See also the function `vector'. */)
3459 (Lisp_Object length, Lisp_Object init)
3461 CHECK_NATNUM (length);
3462 struct Lisp_Vector *p = allocate_vector (XFASTINT (length));
3463 for (ptrdiff_t i = 0; i < XFASTINT (length); i++)
3464 p->contents[i] = init;
3465 return make_lisp_ptr (p, Lisp_Vectorlike);
3468 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3469 doc: /* Return a newly created vector with specified arguments as elements.
3470 Any number of arguments, even zero arguments, are allowed.
3471 usage: (vector &rest OBJECTS) */)
3472 (ptrdiff_t nargs, Lisp_Object *args)
3474 Lisp_Object val = make_uninit_vector (nargs);
3475 struct Lisp_Vector *p = XVECTOR (val);
3476 memcpy (p->contents, args, nargs * sizeof *args);
3477 return val;
3480 void
3481 make_byte_code (struct Lisp_Vector *v)
3483 /* Don't allow the global zero_vector to become a byte code object. */
3484 eassert (0 < v->header.size);
3486 if (v->header.size > 1 && STRINGP (v->contents[1])
3487 && STRING_MULTIBYTE (v->contents[1]))
3488 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3489 earlier because they produced a raw 8-bit string for byte-code
3490 and now such a byte-code string is loaded as multibyte while
3491 raw 8-bit characters converted to multibyte form. Thus, now we
3492 must convert them back to the original unibyte form. */
3493 v->contents[1] = Fstring_as_unibyte (v->contents[1]);
3494 XSETPVECTYPE (v, PVEC_COMPILED);
3497 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3498 doc: /* Create a byte-code object with specified arguments as elements.
3499 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3500 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3501 and (optional) INTERACTIVE-SPEC.
3502 The first four arguments are required; at most six have any
3503 significance.
3504 The ARGLIST can be either like the one of `lambda', in which case the arguments
3505 will be dynamically bound before executing the byte code, or it can be an
3506 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3507 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3508 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3509 argument to catch the left-over arguments. If such an integer is used, the
3510 arguments will not be dynamically bound but will be instead pushed on the
3511 stack before executing the byte-code.
3512 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3513 (ptrdiff_t nargs, Lisp_Object *args)
3515 Lisp_Object val = make_uninit_vector (nargs);
3516 struct Lisp_Vector *p = XVECTOR (val);
3518 /* We used to purecopy everything here, if purify-flag was set. This worked
3519 OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
3520 dangerous, since make-byte-code is used during execution to build
3521 closures, so any closure built during the preload phase would end up
3522 copied into pure space, including its free variables, which is sometimes
3523 just wasteful and other times plainly wrong (e.g. those free vars may want
3524 to be setcar'd). */
3526 memcpy (p->contents, args, nargs * sizeof *args);
3527 make_byte_code (p);
3528 XSETCOMPILED (val, p);
3529 return val;
3534 /***********************************************************************
3535 Symbol Allocation
3536 ***********************************************************************/
3538 /* Each symbol_block is just under 1020 bytes long, since malloc
3539 really allocates in units of powers of two and uses 4 bytes for its
3540 own overhead. */
3542 #define SYMBOL_BLOCK_SIZE \
3543 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
3545 struct symbol_block
3547 /* Place `symbols' first, to preserve alignment. */
3548 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3549 struct symbol_block *next;
3552 /* Current symbol block and index of first unused Lisp_Symbol
3553 structure in it. */
3555 static struct symbol_block *symbol_block;
3556 static int symbol_block_index = SYMBOL_BLOCK_SIZE;
3557 /* Pointer to the first symbol_block that contains pinned symbols.
3558 Tests for 24.4 showed that at dump-time, Emacs contains about 15K symbols,
3559 10K of which are pinned (and all but 250 of them are interned in obarray),
3560 whereas a "typical session" has in the order of 30K symbols.
3561 `symbol_block_pinned' lets mark_pinned_symbols scan only 15K symbols rather
3562 than 30K to find the 10K symbols we need to mark. */
3563 static struct symbol_block *symbol_block_pinned;
3565 /* List of free symbols. */
3567 static struct Lisp_Symbol *symbol_free_list;
3569 static void
3570 set_symbol_name (Lisp_Object sym, Lisp_Object name)
3572 XSYMBOL (sym)->u.s.name = name;
3575 void
3576 init_symbol (Lisp_Object val, Lisp_Object name)
3578 struct Lisp_Symbol *p = XSYMBOL (val);
3579 set_symbol_name (val, name);
3580 set_symbol_plist (val, Qnil);
3581 p->u.s.redirect = SYMBOL_PLAINVAL;
3582 SET_SYMBOL_VAL (p, Qunbound);
3583 set_symbol_function (val, Qnil);
3584 set_symbol_next (val, NULL);
3585 p->u.s.gcmarkbit = false;
3586 p->u.s.interned = SYMBOL_UNINTERNED;
3587 p->u.s.trapped_write = SYMBOL_UNTRAPPED_WRITE;
3588 p->u.s.declared_special = false;
3589 p->u.s.pinned = false;
3592 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3593 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3594 Its value is void, and its function definition and property list are nil. */)
3595 (Lisp_Object name)
3597 Lisp_Object val;
3599 CHECK_STRING (name);
3601 MALLOC_BLOCK_INPUT;
3603 if (symbol_free_list)
3605 XSETSYMBOL (val, symbol_free_list);
3606 symbol_free_list = symbol_free_list->u.s.next;
3608 else
3610 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3612 struct symbol_block *new
3613 = lisp_malloc (sizeof *new, MEM_TYPE_SYMBOL);
3614 new->next = symbol_block;
3615 symbol_block = new;
3616 symbol_block_index = 0;
3617 total_free_symbols += SYMBOL_BLOCK_SIZE;
3619 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index]);
3620 symbol_block_index++;
3623 MALLOC_UNBLOCK_INPUT;
3625 init_symbol (val, name);
3626 consing_since_gc += sizeof (struct Lisp_Symbol);
3627 symbols_consed++;
3628 total_free_symbols--;
3629 return val;
3634 /***********************************************************************
3635 Marker (Misc) Allocation
3636 ***********************************************************************/
3638 /* Like union Lisp_Misc, but padded so that its size is a multiple of
3639 the required alignment. */
3641 union aligned_Lisp_Misc
3643 union Lisp_Misc m;
3644 unsigned char c[(sizeof (union Lisp_Misc) + GCALIGNMENT - 1)
3645 & -GCALIGNMENT];
3648 /* Allocation of markers and other objects that share that structure.
3649 Works like allocation of conses. */
3651 #define MARKER_BLOCK_SIZE \
3652 ((1020 - sizeof (struct marker_block *)) / sizeof (union aligned_Lisp_Misc))
3654 struct marker_block
3656 /* Place `markers' first, to preserve alignment. */
3657 union aligned_Lisp_Misc markers[MARKER_BLOCK_SIZE];
3658 struct marker_block *next;
3661 static struct marker_block *marker_block;
3662 static int marker_block_index = MARKER_BLOCK_SIZE;
3664 static union Lisp_Misc *misc_free_list;
3666 /* Return a newly allocated Lisp_Misc object of specified TYPE. */
3668 static Lisp_Object
3669 allocate_misc (enum Lisp_Misc_Type type)
3671 Lisp_Object val;
3673 MALLOC_BLOCK_INPUT;
3675 if (misc_free_list)
3677 XSETMISC (val, misc_free_list);
3678 misc_free_list = misc_free_list->u_free.chain;
3680 else
3682 if (marker_block_index == MARKER_BLOCK_SIZE)
3684 struct marker_block *new = lisp_malloc (sizeof *new, MEM_TYPE_MISC);
3685 new->next = marker_block;
3686 marker_block = new;
3687 marker_block_index = 0;
3688 total_free_markers += MARKER_BLOCK_SIZE;
3690 XSETMISC (val, &marker_block->markers[marker_block_index].m);
3691 marker_block_index++;
3694 MALLOC_UNBLOCK_INPUT;
3696 --total_free_markers;
3697 consing_since_gc += sizeof (union Lisp_Misc);
3698 misc_objects_consed++;
3699 XMISCANY (val)->type = type;
3700 XMISCANY (val)->gcmarkbit = 0;
3701 return val;
3704 /* Free a Lisp_Misc object. */
3706 void
3707 free_misc (Lisp_Object misc)
3709 XMISCANY (misc)->type = Lisp_Misc_Free;
3710 XMISC (misc)->u_free.chain = misc_free_list;
3711 misc_free_list = XMISC (misc);
3712 consing_since_gc -= sizeof (union Lisp_Misc);
3713 total_free_markers++;
3716 /* Verify properties of Lisp_Save_Value's representation
3717 that are assumed here and elsewhere. */
3719 verify (SAVE_UNUSED == 0);
3720 verify (((SAVE_INTEGER | SAVE_POINTER | SAVE_FUNCPOINTER | SAVE_OBJECT)
3721 >> SAVE_SLOT_BITS)
3722 == 0);
3724 /* Return Lisp_Save_Value objects for the various combinations
3725 that callers need. */
3727 Lisp_Object
3728 make_save_int_int_int (ptrdiff_t a, ptrdiff_t b, ptrdiff_t c)
3730 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3731 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3732 p->save_type = SAVE_TYPE_INT_INT_INT;
3733 p->data[0].integer = a;
3734 p->data[1].integer = b;
3735 p->data[2].integer = c;
3736 return val;
3739 Lisp_Object
3740 make_save_obj_obj_obj_obj (Lisp_Object a, Lisp_Object b, Lisp_Object c,
3741 Lisp_Object d)
3743 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3744 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3745 p->save_type = SAVE_TYPE_OBJ_OBJ_OBJ_OBJ;
3746 p->data[0].object = a;
3747 p->data[1].object = b;
3748 p->data[2].object = c;
3749 p->data[3].object = d;
3750 return val;
3753 Lisp_Object
3754 make_save_ptr (void *a)
3756 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3757 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3758 p->save_type = SAVE_POINTER;
3759 p->data[0].pointer = a;
3760 return val;
3763 Lisp_Object
3764 make_save_ptr_int (void *a, ptrdiff_t b)
3766 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3767 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3768 p->save_type = SAVE_TYPE_PTR_INT;
3769 p->data[0].pointer = a;
3770 p->data[1].integer = b;
3771 return val;
3774 Lisp_Object
3775 make_save_ptr_ptr (void *a, void *b)
3777 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3778 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3779 p->save_type = SAVE_TYPE_PTR_PTR;
3780 p->data[0].pointer = a;
3781 p->data[1].pointer = b;
3782 return val;
3785 Lisp_Object
3786 make_save_funcptr_ptr_obj (void (*a) (void), void *b, Lisp_Object c)
3788 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3789 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3790 p->save_type = SAVE_TYPE_FUNCPTR_PTR_OBJ;
3791 p->data[0].funcpointer = a;
3792 p->data[1].pointer = b;
3793 p->data[2].object = c;
3794 return val;
3797 /* Return a Lisp_Save_Value object that represents an array A
3798 of N Lisp objects. */
3800 Lisp_Object
3801 make_save_memory (Lisp_Object *a, ptrdiff_t n)
3803 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3804 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3805 p->save_type = SAVE_TYPE_MEMORY;
3806 p->data[0].pointer = a;
3807 p->data[1].integer = n;
3808 return val;
3811 /* Free a Lisp_Save_Value object. Do not use this function
3812 if SAVE contains pointer other than returned by xmalloc. */
3814 void
3815 free_save_value (Lisp_Object save)
3817 xfree (XSAVE_POINTER (save, 0));
3818 free_misc (save);
3821 /* Return a Lisp_Misc_Overlay object with specified START, END and PLIST. */
3823 Lisp_Object
3824 build_overlay (Lisp_Object start, Lisp_Object end, Lisp_Object plist)
3826 register Lisp_Object overlay;
3828 overlay = allocate_misc (Lisp_Misc_Overlay);
3829 OVERLAY_START (overlay) = start;
3830 OVERLAY_END (overlay) = end;
3831 set_overlay_plist (overlay, plist);
3832 XOVERLAY (overlay)->next = NULL;
3833 return overlay;
3836 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3837 doc: /* Return a newly allocated marker which does not point at any place. */)
3838 (void)
3840 register Lisp_Object val;
3841 register struct Lisp_Marker *p;
3843 val = allocate_misc (Lisp_Misc_Marker);
3844 p = XMARKER (val);
3845 p->buffer = 0;
3846 p->bytepos = 0;
3847 p->charpos = 0;
3848 p->next = NULL;
3849 p->insertion_type = 0;
3850 p->need_adjustment = 0;
3851 return val;
3854 /* Return a newly allocated marker which points into BUF
3855 at character position CHARPOS and byte position BYTEPOS. */
3857 Lisp_Object
3858 build_marker (struct buffer *buf, ptrdiff_t charpos, ptrdiff_t bytepos)
3860 Lisp_Object obj;
3861 struct Lisp_Marker *m;
3863 /* No dead buffers here. */
3864 eassert (BUFFER_LIVE_P (buf));
3866 /* Every character is at least one byte. */
3867 eassert (charpos <= bytepos);
3869 obj = allocate_misc (Lisp_Misc_Marker);
3870 m = XMARKER (obj);
3871 m->buffer = buf;
3872 m->charpos = charpos;
3873 m->bytepos = bytepos;
3874 m->insertion_type = 0;
3875 m->need_adjustment = 0;
3876 m->next = BUF_MARKERS (buf);
3877 BUF_MARKERS (buf) = m;
3878 return obj;
3882 /* Return a newly created vector or string with specified arguments as
3883 elements. If all the arguments are characters that can fit
3884 in a string of events, make a string; otherwise, make a vector.
3886 Any number of arguments, even zero arguments, are allowed. */
3888 Lisp_Object
3889 make_event_array (ptrdiff_t nargs, Lisp_Object *args)
3891 ptrdiff_t i;
3893 for (i = 0; i < nargs; i++)
3894 /* The things that fit in a string
3895 are characters that are in 0...127,
3896 after discarding the meta bit and all the bits above it. */
3897 if (!INTEGERP (args[i])
3898 || (XINT (args[i]) & ~(-CHAR_META)) >= 0200)
3899 return Fvector (nargs, args);
3901 /* Since the loop exited, we know that all the things in it are
3902 characters, so we can make a string. */
3904 Lisp_Object result;
3906 result = Fmake_string (make_number (nargs), make_number (0), Qnil);
3907 for (i = 0; i < nargs; i++)
3909 SSET (result, i, XINT (args[i]));
3910 /* Move the meta bit to the right place for a string char. */
3911 if (XINT (args[i]) & CHAR_META)
3912 SSET (result, i, SREF (result, i) | 0x80);
3915 return result;
3919 #ifdef HAVE_MODULES
3920 /* Create a new module user ptr object. */
3921 Lisp_Object
3922 make_user_ptr (void (*finalizer) (void *), void *p)
3924 Lisp_Object obj;
3925 struct Lisp_User_Ptr *uptr;
3927 obj = allocate_misc (Lisp_Misc_User_Ptr);
3928 uptr = XUSER_PTR (obj);
3929 uptr->finalizer = finalizer;
3930 uptr->p = p;
3931 return obj;
3933 #endif
3935 static void
3936 init_finalizer_list (struct Lisp_Finalizer *head)
3938 head->prev = head->next = head;
3941 /* Insert FINALIZER before ELEMENT. */
3943 static void
3944 finalizer_insert (struct Lisp_Finalizer *element,
3945 struct Lisp_Finalizer *finalizer)
3947 eassert (finalizer->prev == NULL);
3948 eassert (finalizer->next == NULL);
3949 finalizer->next = element;
3950 finalizer->prev = element->prev;
3951 finalizer->prev->next = finalizer;
3952 element->prev = finalizer;
3955 static void
3956 unchain_finalizer (struct Lisp_Finalizer *finalizer)
3958 if (finalizer->prev != NULL)
3960 eassert (finalizer->next != NULL);
3961 finalizer->prev->next = finalizer->next;
3962 finalizer->next->prev = finalizer->prev;
3963 finalizer->prev = finalizer->next = NULL;
3967 static void
3968 mark_finalizer_list (struct Lisp_Finalizer *head)
3970 for (struct Lisp_Finalizer *finalizer = head->next;
3971 finalizer != head;
3972 finalizer = finalizer->next)
3974 finalizer->base.gcmarkbit = true;
3975 mark_object (finalizer->function);
3979 /* Move doomed finalizers to list DEST from list SRC. A doomed
3980 finalizer is one that is not GC-reachable and whose
3981 finalizer->function is non-nil. */
3983 static void
3984 queue_doomed_finalizers (struct Lisp_Finalizer *dest,
3985 struct Lisp_Finalizer *src)
3987 struct Lisp_Finalizer *finalizer = src->next;
3988 while (finalizer != src)
3990 struct Lisp_Finalizer *next = finalizer->next;
3991 if (!finalizer->base.gcmarkbit && !NILP (finalizer->function))
3993 unchain_finalizer (finalizer);
3994 finalizer_insert (dest, finalizer);
3997 finalizer = next;
4001 static Lisp_Object
4002 run_finalizer_handler (Lisp_Object args)
4004 add_to_log ("finalizer failed: %S", args);
4005 return Qnil;
4008 static void
4009 run_finalizer_function (Lisp_Object function)
4011 ptrdiff_t count = SPECPDL_INDEX ();
4013 specbind (Qinhibit_quit, Qt);
4014 internal_condition_case_1 (call0, function, Qt, run_finalizer_handler);
4015 unbind_to (count, Qnil);
4018 static void
4019 run_finalizers (struct Lisp_Finalizer *finalizers)
4021 struct Lisp_Finalizer *finalizer;
4022 Lisp_Object function;
4024 while (finalizers->next != finalizers)
4026 finalizer = finalizers->next;
4027 eassert (finalizer->base.type == Lisp_Misc_Finalizer);
4028 unchain_finalizer (finalizer);
4029 function = finalizer->function;
4030 if (!NILP (function))
4032 finalizer->function = Qnil;
4033 run_finalizer_function (function);
4038 DEFUN ("make-finalizer", Fmake_finalizer, Smake_finalizer, 1, 1, 0,
4039 doc: /* Make a finalizer that will run FUNCTION.
4040 FUNCTION will be called after garbage collection when the returned
4041 finalizer object becomes unreachable. If the finalizer object is
4042 reachable only through references from finalizer objects, it does not
4043 count as reachable for the purpose of deciding whether to run
4044 FUNCTION. FUNCTION will be run once per finalizer object. */)
4045 (Lisp_Object function)
4047 Lisp_Object val = allocate_misc (Lisp_Misc_Finalizer);
4048 struct Lisp_Finalizer *finalizer = XFINALIZER (val);
4049 finalizer->function = function;
4050 finalizer->prev = finalizer->next = NULL;
4051 finalizer_insert (&finalizers, finalizer);
4052 return val;
4056 /************************************************************************
4057 Memory Full Handling
4058 ************************************************************************/
4061 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
4062 there may have been size_t overflow so that malloc was never
4063 called, or perhaps malloc was invoked successfully but the
4064 resulting pointer had problems fitting into a tagged EMACS_INT. In
4065 either case this counts as memory being full even though malloc did
4066 not fail. */
4068 void
4069 memory_full (size_t nbytes)
4071 /* Do not go into hysterics merely because a large request failed. */
4072 bool enough_free_memory = 0;
4073 if (SPARE_MEMORY < nbytes)
4075 void *p;
4077 MALLOC_BLOCK_INPUT;
4078 p = malloc (SPARE_MEMORY);
4079 if (p)
4081 free (p);
4082 enough_free_memory = 1;
4084 MALLOC_UNBLOCK_INPUT;
4087 if (! enough_free_memory)
4089 int i;
4091 Vmemory_full = Qt;
4093 memory_full_cons_threshold = sizeof (struct cons_block);
4095 /* The first time we get here, free the spare memory. */
4096 for (i = 0; i < ARRAYELTS (spare_memory); i++)
4097 if (spare_memory[i])
4099 if (i == 0)
4100 free (spare_memory[i]);
4101 else if (i >= 1 && i <= 4)
4102 lisp_align_free (spare_memory[i]);
4103 else
4104 lisp_free (spare_memory[i]);
4105 spare_memory[i] = 0;
4109 /* This used to call error, but if we've run out of memory, we could
4110 get infinite recursion trying to build the string. */
4111 xsignal (Qnil, Vmemory_signal_data);
4114 /* If we released our reserve (due to running out of memory),
4115 and we have a fair amount free once again,
4116 try to set aside another reserve in case we run out once more.
4118 This is called when a relocatable block is freed in ralloc.c,
4119 and also directly from this file, in case we're not using ralloc.c. */
4121 void
4122 refill_memory_reserve (void)
4124 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
4125 if (spare_memory[0] == 0)
4126 spare_memory[0] = malloc (SPARE_MEMORY);
4127 if (spare_memory[1] == 0)
4128 spare_memory[1] = lisp_align_malloc (sizeof (struct cons_block),
4129 MEM_TYPE_SPARE);
4130 if (spare_memory[2] == 0)
4131 spare_memory[2] = lisp_align_malloc (sizeof (struct cons_block),
4132 MEM_TYPE_SPARE);
4133 if (spare_memory[3] == 0)
4134 spare_memory[3] = lisp_align_malloc (sizeof (struct cons_block),
4135 MEM_TYPE_SPARE);
4136 if (spare_memory[4] == 0)
4137 spare_memory[4] = lisp_align_malloc (sizeof (struct cons_block),
4138 MEM_TYPE_SPARE);
4139 if (spare_memory[5] == 0)
4140 spare_memory[5] = lisp_malloc (sizeof (struct string_block),
4141 MEM_TYPE_SPARE);
4142 if (spare_memory[6] == 0)
4143 spare_memory[6] = lisp_malloc (sizeof (struct string_block),
4144 MEM_TYPE_SPARE);
4145 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
4146 Vmemory_full = Qnil;
4147 #endif
4150 /************************************************************************
4151 C Stack Marking
4152 ************************************************************************/
4154 /* Conservative C stack marking requires a method to identify possibly
4155 live Lisp objects given a pointer value. We do this by keeping
4156 track of blocks of Lisp data that are allocated in a red-black tree
4157 (see also the comment of mem_node which is the type of nodes in
4158 that tree). Function lisp_malloc adds information for an allocated
4159 block to the red-black tree with calls to mem_insert, and function
4160 lisp_free removes it with mem_delete. Functions live_string_p etc
4161 call mem_find to lookup information about a given pointer in the
4162 tree, and use that to determine if the pointer points into a Lisp
4163 object or not. */
4165 /* Initialize this part of alloc.c. */
4167 static void
4168 mem_init (void)
4170 mem_z.left = mem_z.right = MEM_NIL;
4171 mem_z.parent = NULL;
4172 mem_z.color = MEM_BLACK;
4173 mem_z.start = mem_z.end = NULL;
4174 mem_root = MEM_NIL;
4178 /* Value is a pointer to the mem_node containing START. Value is
4179 MEM_NIL if there is no node in the tree containing START. */
4181 static struct mem_node *
4182 mem_find (void *start)
4184 struct mem_node *p;
4186 if (start < min_heap_address || start > max_heap_address)
4187 return MEM_NIL;
4189 /* Make the search always successful to speed up the loop below. */
4190 mem_z.start = start;
4191 mem_z.end = (char *) start + 1;
4193 p = mem_root;
4194 while (start < p->start || start >= p->end)
4195 p = start < p->start ? p->left : p->right;
4196 return p;
4200 /* Insert a new node into the tree for a block of memory with start
4201 address START, end address END, and type TYPE. Value is a
4202 pointer to the node that was inserted. */
4204 static struct mem_node *
4205 mem_insert (void *start, void *end, enum mem_type type)
4207 struct mem_node *c, *parent, *x;
4209 if (min_heap_address == NULL || start < min_heap_address)
4210 min_heap_address = start;
4211 if (max_heap_address == NULL || end > max_heap_address)
4212 max_heap_address = end;
4214 /* See where in the tree a node for START belongs. In this
4215 particular application, it shouldn't happen that a node is already
4216 present. For debugging purposes, let's check that. */
4217 c = mem_root;
4218 parent = NULL;
4220 while (c != MEM_NIL)
4222 parent = c;
4223 c = start < c->start ? c->left : c->right;
4226 /* Create a new node. */
4227 #ifdef GC_MALLOC_CHECK
4228 x = malloc (sizeof *x);
4229 if (x == NULL)
4230 emacs_abort ();
4231 #else
4232 x = xmalloc (sizeof *x);
4233 #endif
4234 x->start = start;
4235 x->end = end;
4236 x->type = type;
4237 x->parent = parent;
4238 x->left = x->right = MEM_NIL;
4239 x->color = MEM_RED;
4241 /* Insert it as child of PARENT or install it as root. */
4242 if (parent)
4244 if (start < parent->start)
4245 parent->left = x;
4246 else
4247 parent->right = x;
4249 else
4250 mem_root = x;
4252 /* Re-establish red-black tree properties. */
4253 mem_insert_fixup (x);
4255 return x;
4259 /* Re-establish the red-black properties of the tree, and thereby
4260 balance the tree, after node X has been inserted; X is always red. */
4262 static void
4263 mem_insert_fixup (struct mem_node *x)
4265 while (x != mem_root && x->parent->color == MEM_RED)
4267 /* X is red and its parent is red. This is a violation of
4268 red-black tree property #3. */
4270 if (x->parent == x->parent->parent->left)
4272 /* We're on the left side of our grandparent, and Y is our
4273 "uncle". */
4274 struct mem_node *y = x->parent->parent->right;
4276 if (y->color == MEM_RED)
4278 /* Uncle and parent are red but should be black because
4279 X is red. Change the colors accordingly and proceed
4280 with the grandparent. */
4281 x->parent->color = MEM_BLACK;
4282 y->color = MEM_BLACK;
4283 x->parent->parent->color = MEM_RED;
4284 x = x->parent->parent;
4286 else
4288 /* Parent and uncle have different colors; parent is
4289 red, uncle is black. */
4290 if (x == x->parent->right)
4292 x = x->parent;
4293 mem_rotate_left (x);
4296 x->parent->color = MEM_BLACK;
4297 x->parent->parent->color = MEM_RED;
4298 mem_rotate_right (x->parent->parent);
4301 else
4303 /* This is the symmetrical case of above. */
4304 struct mem_node *y = x->parent->parent->left;
4306 if (y->color == MEM_RED)
4308 x->parent->color = MEM_BLACK;
4309 y->color = MEM_BLACK;
4310 x->parent->parent->color = MEM_RED;
4311 x = x->parent->parent;
4313 else
4315 if (x == x->parent->left)
4317 x = x->parent;
4318 mem_rotate_right (x);
4321 x->parent->color = MEM_BLACK;
4322 x->parent->parent->color = MEM_RED;
4323 mem_rotate_left (x->parent->parent);
4328 /* The root may have been changed to red due to the algorithm. Set
4329 it to black so that property #5 is satisfied. */
4330 mem_root->color = MEM_BLACK;
4334 /* (x) (y)
4335 / \ / \
4336 a (y) ===> (x) c
4337 / \ / \
4338 b c a b */
4340 static void
4341 mem_rotate_left (struct mem_node *x)
4343 struct mem_node *y;
4345 /* Turn y's left sub-tree into x's right sub-tree. */
4346 y = x->right;
4347 x->right = y->left;
4348 if (y->left != MEM_NIL)
4349 y->left->parent = x;
4351 /* Y's parent was x's parent. */
4352 if (y != MEM_NIL)
4353 y->parent = x->parent;
4355 /* Get the parent to point to y instead of x. */
4356 if (x->parent)
4358 if (x == x->parent->left)
4359 x->parent->left = y;
4360 else
4361 x->parent->right = y;
4363 else
4364 mem_root = y;
4366 /* Put x on y's left. */
4367 y->left = x;
4368 if (x != MEM_NIL)
4369 x->parent = y;
4373 /* (x) (Y)
4374 / \ / \
4375 (y) c ===> a (x)
4376 / \ / \
4377 a b b c */
4379 static void
4380 mem_rotate_right (struct mem_node *x)
4382 struct mem_node *y = x->left;
4384 x->left = y->right;
4385 if (y->right != MEM_NIL)
4386 y->right->parent = x;
4388 if (y != MEM_NIL)
4389 y->parent = x->parent;
4390 if (x->parent)
4392 if (x == x->parent->right)
4393 x->parent->right = y;
4394 else
4395 x->parent->left = y;
4397 else
4398 mem_root = y;
4400 y->right = x;
4401 if (x != MEM_NIL)
4402 x->parent = y;
4406 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
4408 static void
4409 mem_delete (struct mem_node *z)
4411 struct mem_node *x, *y;
4413 if (!z || z == MEM_NIL)
4414 return;
4416 if (z->left == MEM_NIL || z->right == MEM_NIL)
4417 y = z;
4418 else
4420 y = z->right;
4421 while (y->left != MEM_NIL)
4422 y = y->left;
4425 if (y->left != MEM_NIL)
4426 x = y->left;
4427 else
4428 x = y->right;
4430 x->parent = y->parent;
4431 if (y->parent)
4433 if (y == y->parent->left)
4434 y->parent->left = x;
4435 else
4436 y->parent->right = x;
4438 else
4439 mem_root = x;
4441 if (y != z)
4443 z->start = y->start;
4444 z->end = y->end;
4445 z->type = y->type;
4448 if (y->color == MEM_BLACK)
4449 mem_delete_fixup (x);
4451 #ifdef GC_MALLOC_CHECK
4452 free (y);
4453 #else
4454 xfree (y);
4455 #endif
4459 /* Re-establish the red-black properties of the tree, after a
4460 deletion. */
4462 static void
4463 mem_delete_fixup (struct mem_node *x)
4465 while (x != mem_root && x->color == MEM_BLACK)
4467 if (x == x->parent->left)
4469 struct mem_node *w = x->parent->right;
4471 if (w->color == MEM_RED)
4473 w->color = MEM_BLACK;
4474 x->parent->color = MEM_RED;
4475 mem_rotate_left (x->parent);
4476 w = x->parent->right;
4479 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
4481 w->color = MEM_RED;
4482 x = x->parent;
4484 else
4486 if (w->right->color == MEM_BLACK)
4488 w->left->color = MEM_BLACK;
4489 w->color = MEM_RED;
4490 mem_rotate_right (w);
4491 w = x->parent->right;
4493 w->color = x->parent->color;
4494 x->parent->color = MEM_BLACK;
4495 w->right->color = MEM_BLACK;
4496 mem_rotate_left (x->parent);
4497 x = mem_root;
4500 else
4502 struct mem_node *w = x->parent->left;
4504 if (w->color == MEM_RED)
4506 w->color = MEM_BLACK;
4507 x->parent->color = MEM_RED;
4508 mem_rotate_right (x->parent);
4509 w = x->parent->left;
4512 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
4514 w->color = MEM_RED;
4515 x = x->parent;
4517 else
4519 if (w->left->color == MEM_BLACK)
4521 w->right->color = MEM_BLACK;
4522 w->color = MEM_RED;
4523 mem_rotate_left (w);
4524 w = x->parent->left;
4527 w->color = x->parent->color;
4528 x->parent->color = MEM_BLACK;
4529 w->left->color = MEM_BLACK;
4530 mem_rotate_right (x->parent);
4531 x = mem_root;
4536 x->color = MEM_BLACK;
4540 /* If P is a pointer into a live Lisp string object on the heap,
4541 return the object. Otherwise, return nil. M is a pointer to the
4542 mem_block for P.
4544 This and other *_holding functions look for a pointer anywhere into
4545 the object, not merely for a pointer to the start of the object,
4546 because some compilers sometimes optimize away the latter. See
4547 Bug#28213. */
4549 static Lisp_Object
4550 live_string_holding (struct mem_node *m, void *p)
4552 if (m->type == MEM_TYPE_STRING)
4554 struct string_block *b = m->start;
4555 char *cp = p;
4556 ptrdiff_t offset = cp - (char *) &b->strings[0];
4558 /* P must point into a Lisp_String structure, and it
4559 must not be on the free-list. */
4560 if (0 <= offset && offset < STRING_BLOCK_SIZE * sizeof b->strings[0])
4562 cp = ptr_bounds_copy (cp, b);
4563 struct Lisp_String *s = p = cp -= offset % sizeof b->strings[0];
4564 if (s->u.s.data)
4565 return make_lisp_ptr (s, Lisp_String);
4568 return Qnil;
4571 static bool
4572 live_string_p (struct mem_node *m, void *p)
4574 return !NILP (live_string_holding (m, p));
4577 /* If P is a pointer into a live Lisp cons object on the heap, return
4578 the object. Otherwise, return nil. M is a pointer to the
4579 mem_block for P. */
4581 static Lisp_Object
4582 live_cons_holding (struct mem_node *m, void *p)
4584 if (m->type == MEM_TYPE_CONS)
4586 struct cons_block *b = m->start;
4587 char *cp = p;
4588 ptrdiff_t offset = cp - (char *) &b->conses[0];
4590 /* P must point into a Lisp_Cons, not be
4591 one of the unused cells in the current cons block,
4592 and not be on the free-list. */
4593 if (0 <= offset && offset < CONS_BLOCK_SIZE * sizeof b->conses[0]
4594 && (b != cons_block
4595 || offset / sizeof b->conses[0] < cons_block_index))
4597 cp = ptr_bounds_copy (cp, b);
4598 struct Lisp_Cons *s = p = cp -= offset % sizeof b->conses[0];
4599 if (!EQ (s->u.s.car, Vdead))
4600 return make_lisp_ptr (s, Lisp_Cons);
4603 return Qnil;
4606 static bool
4607 live_cons_p (struct mem_node *m, void *p)
4609 return !NILP (live_cons_holding (m, p));
4613 /* If P is a pointer into a live Lisp symbol object on the heap,
4614 return the object. Otherwise, return nil. M is a pointer to the
4615 mem_block for P. */
4617 static Lisp_Object
4618 live_symbol_holding (struct mem_node *m, void *p)
4620 if (m->type == MEM_TYPE_SYMBOL)
4622 struct symbol_block *b = m->start;
4623 char *cp = p;
4624 ptrdiff_t offset = cp - (char *) &b->symbols[0];
4626 /* P must point into the Lisp_Symbol, not be
4627 one of the unused cells in the current symbol block,
4628 and not be on the free-list. */
4629 if (0 <= offset && offset < SYMBOL_BLOCK_SIZE * sizeof b->symbols[0]
4630 && (b != symbol_block
4631 || offset / sizeof b->symbols[0] < symbol_block_index))
4633 cp = ptr_bounds_copy (cp, b);
4634 struct Lisp_Symbol *s = p = cp -= offset % sizeof b->symbols[0];
4635 if (!EQ (s->u.s.function, Vdead))
4636 return make_lisp_symbol (s);
4639 return Qnil;
4642 static bool
4643 live_symbol_p (struct mem_node *m, void *p)
4645 return !NILP (live_symbol_holding (m, p));
4649 /* Return true if P is a pointer to a live Lisp float on
4650 the heap. M is a pointer to the mem_block for P. */
4652 static bool
4653 live_float_p (struct mem_node *m, void *p)
4655 if (m->type == MEM_TYPE_FLOAT)
4657 struct float_block *b = m->start;
4658 char *cp = p;
4659 ptrdiff_t offset = cp - (char *) &b->floats[0];
4661 /* P must point to the start of a Lisp_Float and not be
4662 one of the unused cells in the current float block. */
4663 return (offset >= 0
4664 && offset % sizeof b->floats[0] == 0
4665 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
4666 && (b != float_block
4667 || offset / sizeof b->floats[0] < float_block_index));
4669 else
4670 return 0;
4674 /* If P is a pointer to a live Lisp Misc on the heap, return the object.
4675 Otherwise, return nil. M is a pointer to the mem_block for P. */
4677 static Lisp_Object
4678 live_misc_holding (struct mem_node *m, void *p)
4680 if (m->type == MEM_TYPE_MISC)
4682 struct marker_block *b = m->start;
4683 char *cp = p;
4684 ptrdiff_t offset = cp - (char *) &b->markers[0];
4686 /* P must point into a Lisp_Misc, not be
4687 one of the unused cells in the current misc block,
4688 and not be on the free-list. */
4689 if (0 <= offset && offset < MARKER_BLOCK_SIZE * sizeof b->markers[0]
4690 && (b != marker_block
4691 || offset / sizeof b->markers[0] < marker_block_index))
4693 cp = ptr_bounds_copy (cp, b);
4694 union Lisp_Misc *s = p = cp -= offset % sizeof b->markers[0];
4695 if (s->u_any.type != Lisp_Misc_Free)
4696 return make_lisp_ptr (s, Lisp_Misc);
4699 return Qnil;
4702 static bool
4703 live_misc_p (struct mem_node *m, void *p)
4705 return !NILP (live_misc_holding (m, p));
4708 /* If P is a pointer to a live vector-like object, return the object.
4709 Otherwise, return nil.
4710 M is a pointer to the mem_block for P. */
4712 static Lisp_Object
4713 live_vector_holding (struct mem_node *m, void *p)
4715 struct Lisp_Vector *vp = p;
4717 if (m->type == MEM_TYPE_VECTOR_BLOCK)
4719 /* This memory node corresponds to a vector block. */
4720 struct vector_block *block = m->start;
4721 struct Lisp_Vector *vector = (struct Lisp_Vector *) block->data;
4723 /* P is in the block's allocation range. Scan the block
4724 up to P and see whether P points to the start of some
4725 vector which is not on a free list. FIXME: check whether
4726 some allocation patterns (probably a lot of short vectors)
4727 may cause a substantial overhead of this loop. */
4728 while (VECTOR_IN_BLOCK (vector, block) && vector <= vp)
4730 struct Lisp_Vector *next = ADVANCE (vector, vector_nbytes (vector));
4731 if (vp < next && !PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FREE))
4732 return make_lisp_ptr (vector, Lisp_Vectorlike);
4733 vector = next;
4736 else if (m->type == MEM_TYPE_VECTORLIKE)
4738 /* This memory node corresponds to a large vector. */
4739 struct Lisp_Vector *vector = large_vector_vec (m->start);
4740 struct Lisp_Vector *next = ADVANCE (vector, vector_nbytes (vector));
4741 if (vector <= vp && vp < next)
4742 return make_lisp_ptr (vector, Lisp_Vectorlike);
4744 return Qnil;
4747 static bool
4748 live_vector_p (struct mem_node *m, void *p)
4750 return !NILP (live_vector_holding (m, p));
4753 /* If P is a pointer into a live buffer, return the buffer.
4754 Otherwise, return nil. M is a pointer to the mem_block for P. */
4756 static Lisp_Object
4757 live_buffer_holding (struct mem_node *m, void *p)
4759 /* P must point into the block, and the buffer
4760 must not have been killed. */
4761 if (m->type == MEM_TYPE_BUFFER)
4763 struct buffer *b = m->start;
4764 char *cb = m->start;
4765 char *cp = p;
4766 ptrdiff_t offset = cp - cb;
4767 if (0 <= offset && offset < sizeof *b && !NILP (b->name_))
4769 Lisp_Object obj;
4770 XSETBUFFER (obj, b);
4771 return obj;
4774 return Qnil;
4777 static bool
4778 live_buffer_p (struct mem_node *m, void *p)
4780 return !NILP (live_buffer_holding (m, p));
4783 /* Mark OBJ if we can prove it's a Lisp_Object. */
4785 static void
4786 mark_maybe_object (Lisp_Object obj)
4788 #if USE_VALGRIND
4789 if (valgrind_p)
4790 VALGRIND_MAKE_MEM_DEFINED (&obj, sizeof (obj));
4791 #endif
4793 if (INTEGERP (obj))
4794 return;
4796 void *po = XPNTR (obj);
4797 struct mem_node *m = mem_find (po);
4799 if (m != MEM_NIL)
4801 bool mark_p = false;
4803 switch (XTYPE (obj))
4805 case Lisp_String:
4806 mark_p = EQ (obj, live_string_holding (m, po));
4807 break;
4809 case Lisp_Cons:
4810 mark_p = EQ (obj, live_cons_holding (m, po));
4811 break;
4813 case Lisp_Symbol:
4814 mark_p = EQ (obj, live_symbol_holding (m, po));
4815 break;
4817 case Lisp_Float:
4818 mark_p = live_float_p (m, po);
4819 break;
4821 case Lisp_Vectorlike:
4822 mark_p = (EQ (obj, live_vector_holding (m, po))
4823 || EQ (obj, live_buffer_holding (m, po)));
4824 break;
4826 case Lisp_Misc:
4827 mark_p = EQ (obj, live_misc_holding (m, po));
4828 break;
4830 default:
4831 break;
4834 if (mark_p)
4835 mark_object (obj);
4839 /* Return true if P can point to Lisp data, and false otherwise.
4840 Symbols are implemented via offsets not pointers, but the offsets
4841 are also multiples of GCALIGNMENT. */
4843 static bool
4844 maybe_lisp_pointer (void *p)
4846 return (uintptr_t) p % GCALIGNMENT == 0;
4849 #ifndef HAVE_MODULES
4850 enum { HAVE_MODULES = false };
4851 #endif
4853 /* If P points to Lisp data, mark that as live if it isn't already
4854 marked. */
4856 static void
4857 mark_maybe_pointer (void *p)
4859 struct mem_node *m;
4861 #if USE_VALGRIND
4862 if (valgrind_p)
4863 VALGRIND_MAKE_MEM_DEFINED (&p, sizeof (p));
4864 #endif
4866 if (sizeof (Lisp_Object) == sizeof (void *) || !HAVE_MODULES)
4868 if (!maybe_lisp_pointer (p))
4869 return;
4871 else
4873 /* For the wide-int case, also mark emacs_value tagged pointers,
4874 which can be generated by emacs-module.c's value_to_lisp. */
4875 p = (void *) ((uintptr_t) p & ~(GCALIGNMENT - 1));
4878 m = mem_find (p);
4879 if (m != MEM_NIL)
4881 Lisp_Object obj = Qnil;
4883 switch (m->type)
4885 case MEM_TYPE_NON_LISP:
4886 case MEM_TYPE_SPARE:
4887 /* Nothing to do; not a pointer to Lisp memory. */
4888 break;
4890 case MEM_TYPE_BUFFER:
4891 obj = live_buffer_holding (m, p);
4892 break;
4894 case MEM_TYPE_CONS:
4895 obj = live_cons_holding (m, p);
4896 break;
4898 case MEM_TYPE_STRING:
4899 obj = live_string_holding (m, p);
4900 break;
4902 case MEM_TYPE_MISC:
4903 obj = live_misc_holding (m, p);
4904 break;
4906 case MEM_TYPE_SYMBOL:
4907 obj = live_symbol_holding (m, p);
4908 break;
4910 case MEM_TYPE_FLOAT:
4911 if (live_float_p (m, p))
4912 obj = make_lisp_ptr (p, Lisp_Float);
4913 break;
4915 case MEM_TYPE_VECTORLIKE:
4916 case MEM_TYPE_VECTOR_BLOCK:
4917 obj = live_vector_holding (m, p);
4918 break;
4920 default:
4921 emacs_abort ();
4924 if (!NILP (obj))
4925 mark_object (obj);
4930 /* Alignment of pointer values. Use alignof, as it sometimes returns
4931 a smaller alignment than GCC's __alignof__ and mark_memory might
4932 miss objects if __alignof__ were used. */
4933 #define GC_POINTER_ALIGNMENT alignof (void *)
4935 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4936 or END+OFFSET..START. */
4938 static void ATTRIBUTE_NO_SANITIZE_ADDRESS
4939 mark_memory (void *start, void *end)
4941 char *pp;
4943 /* Make START the pointer to the start of the memory region,
4944 if it isn't already. */
4945 if (end < start)
4947 void *tem = start;
4948 start = end;
4949 end = tem;
4952 eassert (((uintptr_t) start) % GC_POINTER_ALIGNMENT == 0);
4954 /* Mark Lisp data pointed to. This is necessary because, in some
4955 situations, the C compiler optimizes Lisp objects away, so that
4956 only a pointer to them remains. Example:
4958 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4961 Lisp_Object obj = build_string ("test");
4962 struct Lisp_String *s = XSTRING (obj);
4963 Fgarbage_collect ();
4964 fprintf (stderr, "test '%s'\n", s->u.s.data);
4965 return Qnil;
4968 Here, `obj' isn't really used, and the compiler optimizes it
4969 away. The only reference to the life string is through the
4970 pointer `s'. */
4972 for (pp = start; (void *) pp < end; pp += GC_POINTER_ALIGNMENT)
4974 mark_maybe_pointer (*(void **) pp);
4976 verify (alignof (Lisp_Object) % GC_POINTER_ALIGNMENT == 0);
4977 if (alignof (Lisp_Object) == GC_POINTER_ALIGNMENT
4978 || (uintptr_t) pp % alignof (Lisp_Object) == 0)
4979 mark_maybe_object (*(Lisp_Object *) pp);
4983 #ifndef HAVE___BUILTIN_UNWIND_INIT
4985 # ifdef GC_SETJMP_WORKS
4986 static void
4987 test_setjmp (void)
4990 # else
4992 static bool setjmp_tested_p;
4993 static int longjmps_done;
4995 # define SETJMP_WILL_LIKELY_WORK "\
4997 Emacs garbage collector has been changed to use conservative stack\n\
4998 marking. Emacs has determined that the method it uses to do the\n\
4999 marking will likely work on your system, but this isn't sure.\n\
5001 If you are a system-programmer, or can get the help of a local wizard\n\
5002 who is, please take a look at the function mark_stack in alloc.c, and\n\
5003 verify that the methods used are appropriate for your system.\n\
5005 Please mail the result to <emacs-devel@gnu.org>.\n\
5008 # define SETJMP_WILL_NOT_WORK "\
5010 Emacs garbage collector has been changed to use conservative stack\n\
5011 marking. Emacs has determined that the default method it uses to do the\n\
5012 marking will not work on your system. We will need a system-dependent\n\
5013 solution for your system.\n\
5015 Please take a look at the function mark_stack in alloc.c, and\n\
5016 try to find a way to make it work on your system.\n\
5018 Note that you may get false negatives, depending on the compiler.\n\
5019 In particular, you need to use -O with GCC for this test.\n\
5021 Please mail the result to <emacs-devel@gnu.org>.\n\
5025 /* Perform a quick check if it looks like setjmp saves registers in a
5026 jmp_buf. Print a message to stderr saying so. When this test
5027 succeeds, this is _not_ a proof that setjmp is sufficient for
5028 conservative stack marking. Only the sources or a disassembly
5029 can prove that. */
5031 static void
5032 test_setjmp (void)
5034 if (setjmp_tested_p)
5035 return;
5036 setjmp_tested_p = true;
5037 char buf[10];
5038 register int x;
5039 sys_jmp_buf jbuf;
5041 /* Arrange for X to be put in a register. */
5042 sprintf (buf, "1");
5043 x = strlen (buf);
5044 x = 2 * x - 1;
5046 sys_setjmp (jbuf);
5047 if (longjmps_done == 1)
5049 /* Came here after the longjmp at the end of the function.
5051 If x == 1, the longjmp has restored the register to its
5052 value before the setjmp, and we can hope that setjmp
5053 saves all such registers in the jmp_buf, although that
5054 isn't sure.
5056 For other values of X, either something really strange is
5057 taking place, or the setjmp just didn't save the register. */
5059 if (x == 1)
5060 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
5061 else
5063 fprintf (stderr, SETJMP_WILL_NOT_WORK);
5064 exit (1);
5068 ++longjmps_done;
5069 x = 2;
5070 if (longjmps_done == 1)
5071 sys_longjmp (jbuf, 1);
5073 # endif /* ! GC_SETJMP_WORKS */
5074 #endif /* ! HAVE___BUILTIN_UNWIND_INIT */
5076 /* The type of an object near the stack top, whose address can be used
5077 as a stack scan limit. */
5078 typedef union
5080 /* Align the stack top properly. Even if !HAVE___BUILTIN_UNWIND_INIT,
5081 jmp_buf may not be aligned enough on darwin-ppc64. */
5082 max_align_t o;
5083 #ifndef HAVE___BUILTIN_UNWIND_INIT
5084 sys_jmp_buf j;
5085 char c;
5086 #endif
5087 } stacktop_sentry;
5089 /* Force callee-saved registers and register windows onto the stack.
5090 Use the platform-defined __builtin_unwind_init if available,
5091 obviating the need for machine dependent methods. */
5092 #ifndef HAVE___BUILTIN_UNWIND_INIT
5093 # ifdef __sparc__
5094 /* This trick flushes the register windows so that all the state of
5095 the process is contained in the stack.
5096 FreeBSD does not have a ta 3 handler, so handle it specially.
5097 FIXME: Code in the Boehm GC suggests flushing (with 'flushrs') is
5098 needed on ia64 too. See mach_dep.c, where it also says inline
5099 assembler doesn't work with relevant proprietary compilers. */
5100 # if defined __sparc64__ && defined __FreeBSD__
5101 # define __builtin_unwind_init() asm ("flushw")
5102 # else
5103 # define __builtin_unwind_init() asm ("ta 3")
5104 # endif
5105 # else
5106 # define __builtin_unwind_init() ((void) 0)
5107 # endif
5108 #endif
5110 /* Yield an address close enough to the top of the stack that the
5111 garbage collector need not scan above it. Callers should be
5112 declared NO_INLINE. */
5113 #ifdef HAVE___BUILTIN_FRAME_ADDRESS
5114 # define NEAR_STACK_TOP(addr) ((void) (addr), __builtin_frame_address (0))
5115 #else
5116 # define NEAR_STACK_TOP(addr) (addr)
5117 #endif
5119 /* Set *P to the address of the top of the stack. This must be a
5120 macro, not a function, so that it is executed in the caller's
5121 environment. It is not inside a do-while so that its storage
5122 survives the macro. Callers should be declared NO_INLINE. */
5123 #ifdef HAVE___BUILTIN_UNWIND_INIT
5124 # define SET_STACK_TOP_ADDRESS(p) \
5125 stacktop_sentry sentry; \
5126 __builtin_unwind_init (); \
5127 *(p) = NEAR_STACK_TOP (&sentry)
5128 #else
5129 # define SET_STACK_TOP_ADDRESS(p) \
5130 stacktop_sentry sentry; \
5131 __builtin_unwind_init (); \
5132 test_setjmp (); \
5133 sys_setjmp (sentry.j); \
5134 *(p) = NEAR_STACK_TOP (&sentry + (stack_bottom < &sentry.c))
5135 #endif
5137 /* Mark live Lisp objects on the C stack.
5139 There are several system-dependent problems to consider when
5140 porting this to new architectures:
5142 Processor Registers
5144 We have to mark Lisp objects in CPU registers that can hold local
5145 variables or are used to pass parameters.
5147 This code assumes that calling setjmp saves registers we need
5148 to see in a jmp_buf which itself lies on the stack. This doesn't
5149 have to be true! It must be verified for each system, possibly
5150 by taking a look at the source code of setjmp.
5152 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
5153 can use it as a machine independent method to store all registers
5154 to the stack. In this case the macros described in the previous
5155 two paragraphs are not used.
5157 Stack Layout
5159 Architectures differ in the way their processor stack is organized.
5160 For example, the stack might look like this
5162 +----------------+
5163 | Lisp_Object | size = 4
5164 +----------------+
5165 | something else | size = 2
5166 +----------------+
5167 | Lisp_Object | size = 4
5168 +----------------+
5169 | ... |
5171 In such a case, not every Lisp_Object will be aligned equally. To
5172 find all Lisp_Object on the stack it won't be sufficient to walk
5173 the stack in steps of 4 bytes. Instead, two passes will be
5174 necessary, one starting at the start of the stack, and a second
5175 pass starting at the start of the stack + 2. Likewise, if the
5176 minimal alignment of Lisp_Objects on the stack is 1, four passes
5177 would be necessary, each one starting with one byte more offset
5178 from the stack start. */
5180 void
5181 mark_stack (char *bottom, char *end)
5183 /* This assumes that the stack is a contiguous region in memory. If
5184 that's not the case, something has to be done here to iterate
5185 over the stack segments. */
5186 mark_memory (bottom, end);
5188 /* Allow for marking a secondary stack, like the register stack on the
5189 ia64. */
5190 #ifdef GC_MARK_SECONDARY_STACK
5191 GC_MARK_SECONDARY_STACK ();
5192 #endif
5195 /* This is a trampoline function that flushes registers to the stack,
5196 and then calls FUNC. ARG is passed through to FUNC verbatim.
5198 This function must be called whenever Emacs is about to release the
5199 global interpreter lock. This lets the garbage collector easily
5200 find roots in registers on threads that are not actively running
5201 Lisp.
5203 It is invalid to run any Lisp code or to allocate any GC memory
5204 from FUNC. */
5206 NO_INLINE void
5207 flush_stack_call_func (void (*func) (void *arg), void *arg)
5209 void *end;
5210 struct thread_state *self = current_thread;
5211 SET_STACK_TOP_ADDRESS (&end);
5212 self->stack_top = end;
5213 func (arg);
5214 eassert (current_thread == self);
5217 static bool
5218 c_symbol_p (struct Lisp_Symbol *sym)
5220 char *lispsym_ptr = (char *) lispsym;
5221 char *sym_ptr = (char *) sym;
5222 ptrdiff_t lispsym_offset = sym_ptr - lispsym_ptr;
5223 return 0 <= lispsym_offset && lispsym_offset < sizeof lispsym;
5226 /* Determine whether it is safe to access memory at address P. */
5227 static int
5228 valid_pointer_p (void *p)
5230 #ifdef WINDOWSNT
5231 return w32_valid_pointer_p (p, 16);
5232 #else
5234 if (ADDRESS_SANITIZER)
5235 return p ? -1 : 0;
5237 int fd[2];
5239 /* Obviously, we cannot just access it (we would SEGV trying), so we
5240 trick the o/s to tell us whether p is a valid pointer.
5241 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
5242 not validate p in that case. */
5244 if (emacs_pipe (fd) == 0)
5246 bool valid = emacs_write (fd[1], p, 16) == 16;
5247 emacs_close (fd[1]);
5248 emacs_close (fd[0]);
5249 return valid;
5252 return -1;
5253 #endif
5256 /* Return 2 if OBJ is a killed or special buffer object, 1 if OBJ is a
5257 valid lisp object, 0 if OBJ is NOT a valid lisp object, or -1 if we
5258 cannot validate OBJ. This function can be quite slow, so its primary
5259 use is the manual debugging. The only exception is print_object, where
5260 we use it to check whether the memory referenced by the pointer of
5261 Lisp_Save_Value object contains valid objects. */
5264 valid_lisp_object_p (Lisp_Object obj)
5266 if (INTEGERP (obj))
5267 return 1;
5269 void *p = XPNTR (obj);
5270 if (PURE_P (p))
5271 return 1;
5273 if (SYMBOLP (obj) && c_symbol_p (p))
5274 return ((char *) p - (char *) lispsym) % sizeof lispsym[0] == 0;
5276 if (p == &buffer_defaults || p == &buffer_local_symbols)
5277 return 2;
5279 struct mem_node *m = mem_find (p);
5281 if (m == MEM_NIL)
5283 int valid = valid_pointer_p (p);
5284 if (valid <= 0)
5285 return valid;
5287 if (SUBRP (obj))
5288 return 1;
5290 return 0;
5293 switch (m->type)
5295 case MEM_TYPE_NON_LISP:
5296 case MEM_TYPE_SPARE:
5297 return 0;
5299 case MEM_TYPE_BUFFER:
5300 return live_buffer_p (m, p) ? 1 : 2;
5302 case MEM_TYPE_CONS:
5303 return live_cons_p (m, p);
5305 case MEM_TYPE_STRING:
5306 return live_string_p (m, p);
5308 case MEM_TYPE_MISC:
5309 return live_misc_p (m, p);
5311 case MEM_TYPE_SYMBOL:
5312 return live_symbol_p (m, p);
5314 case MEM_TYPE_FLOAT:
5315 return live_float_p (m, p);
5317 case MEM_TYPE_VECTORLIKE:
5318 case MEM_TYPE_VECTOR_BLOCK:
5319 return live_vector_p (m, p);
5321 default:
5322 break;
5325 return 0;
5328 /***********************************************************************
5329 Pure Storage Management
5330 ***********************************************************************/
5332 /* Allocate room for SIZE bytes from pure Lisp storage and return a
5333 pointer to it. TYPE is the Lisp type for which the memory is
5334 allocated. TYPE < 0 means it's not used for a Lisp object. */
5336 static void *
5337 pure_alloc (size_t size, int type)
5339 void *result;
5341 again:
5342 if (type >= 0)
5344 /* Allocate space for a Lisp object from the beginning of the free
5345 space with taking account of alignment. */
5346 result = pointer_align (purebeg + pure_bytes_used_lisp, GCALIGNMENT);
5347 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
5349 else
5351 /* Allocate space for a non-Lisp object from the end of the free
5352 space. */
5353 pure_bytes_used_non_lisp += size;
5354 result = purebeg + pure_size - pure_bytes_used_non_lisp;
5356 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
5358 if (pure_bytes_used <= pure_size)
5359 return ptr_bounds_clip (result, size);
5361 /* Don't allocate a large amount here,
5362 because it might get mmap'd and then its address
5363 might not be usable. */
5364 purebeg = xmalloc (10000);
5365 pure_size = 10000;
5366 pure_bytes_used_before_overflow += pure_bytes_used - size;
5367 pure_bytes_used = 0;
5368 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
5369 goto again;
5373 #ifndef CANNOT_DUMP
5375 /* Print a warning if PURESIZE is too small. */
5377 void
5378 check_pure_size (void)
5380 if (pure_bytes_used_before_overflow)
5381 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI"d"
5382 " bytes needed)"),
5383 pure_bytes_used + pure_bytes_used_before_overflow);
5385 #endif
5388 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
5389 the non-Lisp data pool of the pure storage, and return its start
5390 address. Return NULL if not found. */
5392 static char *
5393 find_string_data_in_pure (const char *data, ptrdiff_t nbytes)
5395 int i;
5396 ptrdiff_t skip, bm_skip[256], last_char_skip, infinity, start, start_max;
5397 const unsigned char *p;
5398 char *non_lisp_beg;
5400 if (pure_bytes_used_non_lisp <= nbytes)
5401 return NULL;
5403 /* Set up the Boyer-Moore table. */
5404 skip = nbytes + 1;
5405 for (i = 0; i < 256; i++)
5406 bm_skip[i] = skip;
5408 p = (const unsigned char *) data;
5409 while (--skip > 0)
5410 bm_skip[*p++] = skip;
5412 last_char_skip = bm_skip['\0'];
5414 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
5415 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
5417 /* See the comments in the function `boyer_moore' (search.c) for the
5418 use of `infinity'. */
5419 infinity = pure_bytes_used_non_lisp + 1;
5420 bm_skip['\0'] = infinity;
5422 p = (const unsigned char *) non_lisp_beg + nbytes;
5423 start = 0;
5426 /* Check the last character (== '\0'). */
5429 start += bm_skip[*(p + start)];
5431 while (start <= start_max);
5433 if (start < infinity)
5434 /* Couldn't find the last character. */
5435 return NULL;
5437 /* No less than `infinity' means we could find the last
5438 character at `p[start - infinity]'. */
5439 start -= infinity;
5441 /* Check the remaining characters. */
5442 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
5443 /* Found. */
5444 return ptr_bounds_clip (non_lisp_beg + start, nbytes + 1);
5446 start += last_char_skip;
5448 while (start <= start_max);
5450 return NULL;
5454 /* Return a string allocated in pure space. DATA is a buffer holding
5455 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
5456 means make the result string multibyte.
5458 Must get an error if pure storage is full, since if it cannot hold
5459 a large string it may be able to hold conses that point to that
5460 string; then the string is not protected from gc. */
5462 Lisp_Object
5463 make_pure_string (const char *data,
5464 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
5466 Lisp_Object string;
5467 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5468 s->u.s.data = (unsigned char *) find_string_data_in_pure (data, nbytes);
5469 if (s->u.s.data == NULL)
5471 s->u.s.data = pure_alloc (nbytes + 1, -1);
5472 memcpy (s->u.s.data, data, nbytes);
5473 s->u.s.data[nbytes] = '\0';
5475 s->u.s.size = nchars;
5476 s->u.s.size_byte = multibyte ? nbytes : -1;
5477 s->u.s.intervals = NULL;
5478 XSETSTRING (string, s);
5479 return string;
5482 /* Return a string allocated in pure space. Do not
5483 allocate the string data, just point to DATA. */
5485 Lisp_Object
5486 make_pure_c_string (const char *data, ptrdiff_t nchars)
5488 Lisp_Object string;
5489 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5490 s->u.s.size = nchars;
5491 s->u.s.size_byte = -1;
5492 s->u.s.data = (unsigned char *) data;
5493 s->u.s.intervals = NULL;
5494 XSETSTRING (string, s);
5495 return string;
5498 static Lisp_Object purecopy (Lisp_Object obj);
5500 /* Return a cons allocated from pure space. Give it pure copies
5501 of CAR as car and CDR as cdr. */
5503 Lisp_Object
5504 pure_cons (Lisp_Object car, Lisp_Object cdr)
5506 Lisp_Object new;
5507 struct Lisp_Cons *p = pure_alloc (sizeof *p, Lisp_Cons);
5508 XSETCONS (new, p);
5509 XSETCAR (new, purecopy (car));
5510 XSETCDR (new, purecopy (cdr));
5511 return new;
5515 /* Value is a float object with value NUM allocated from pure space. */
5517 static Lisp_Object
5518 make_pure_float (double num)
5520 Lisp_Object new;
5521 struct Lisp_Float *p = pure_alloc (sizeof *p, Lisp_Float);
5522 XSETFLOAT (new, p);
5523 XFLOAT_INIT (new, num);
5524 return new;
5528 /* Return a vector with room for LEN Lisp_Objects allocated from
5529 pure space. */
5531 static Lisp_Object
5532 make_pure_vector (ptrdiff_t len)
5534 Lisp_Object new;
5535 size_t size = header_size + len * word_size;
5536 struct Lisp_Vector *p = pure_alloc (size, Lisp_Vectorlike);
5537 XSETVECTOR (new, p);
5538 XVECTOR (new)->header.size = len;
5539 return new;
5542 /* Copy all contents and parameters of TABLE to a new table allocated
5543 from pure space, return the purified table. */
5544 static struct Lisp_Hash_Table *
5545 purecopy_hash_table (struct Lisp_Hash_Table *table)
5547 eassert (NILP (table->weak));
5548 eassert (table->pure);
5550 struct Lisp_Hash_Table *pure = pure_alloc (sizeof *pure, Lisp_Vectorlike);
5551 struct hash_table_test pure_test = table->test;
5553 /* Purecopy the hash table test. */
5554 pure_test.name = purecopy (table->test.name);
5555 pure_test.user_hash_function = purecopy (table->test.user_hash_function);
5556 pure_test.user_cmp_function = purecopy (table->test.user_cmp_function);
5558 pure->header = table->header;
5559 pure->weak = purecopy (Qnil);
5560 pure->hash = purecopy (table->hash);
5561 pure->next = purecopy (table->next);
5562 pure->index = purecopy (table->index);
5563 pure->count = table->count;
5564 pure->next_free = table->next_free;
5565 pure->pure = table->pure;
5566 pure->rehash_threshold = table->rehash_threshold;
5567 pure->rehash_size = table->rehash_size;
5568 pure->key_and_value = purecopy (table->key_and_value);
5569 pure->test = pure_test;
5571 return pure;
5574 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
5575 doc: /* Make a copy of object OBJ in pure storage.
5576 Recursively copies contents of vectors and cons cells.
5577 Does not copy symbols. Copies strings without text properties. */)
5578 (register Lisp_Object obj)
5580 if (NILP (Vpurify_flag))
5581 return obj;
5582 else if (MARKERP (obj) || OVERLAYP (obj) || SYMBOLP (obj))
5583 /* Can't purify those. */
5584 return obj;
5585 else
5586 return purecopy (obj);
5589 /* Pinned objects are marked before every GC cycle. */
5590 static struct pinned_object
5592 Lisp_Object object;
5593 struct pinned_object *next;
5594 } *pinned_objects;
5596 static Lisp_Object
5597 purecopy (Lisp_Object obj)
5599 if (INTEGERP (obj)
5600 || (! SYMBOLP (obj) && PURE_P (XPNTR (obj)))
5601 || SUBRP (obj))
5602 return obj; /* Already pure. */
5604 if (STRINGP (obj) && XSTRING (obj)->u.s.intervals)
5605 message_with_string ("Dropping text-properties while making string `%s' pure",
5606 obj, true);
5608 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5610 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
5611 if (!NILP (tmp))
5612 return tmp;
5615 if (CONSP (obj))
5616 obj = pure_cons (XCAR (obj), XCDR (obj));
5617 else if (FLOATP (obj))
5618 obj = make_pure_float (XFLOAT_DATA (obj));
5619 else if (STRINGP (obj))
5620 obj = make_pure_string (SSDATA (obj), SCHARS (obj),
5621 SBYTES (obj),
5622 STRING_MULTIBYTE (obj));
5623 else if (HASH_TABLE_P (obj))
5625 struct Lisp_Hash_Table *table = XHASH_TABLE (obj);
5626 /* Do not purify hash tables which haven't been defined with
5627 :purecopy as non-nil or are weak - they aren't guaranteed to
5628 not change. */
5629 if (!NILP (table->weak) || !table->pure)
5631 /* Instead, add the hash table to the list of pinned objects,
5632 so that it will be marked during GC. */
5633 struct pinned_object *o = xmalloc (sizeof *o);
5634 o->object = obj;
5635 o->next = pinned_objects;
5636 pinned_objects = o;
5637 return obj; /* Don't hash cons it. */
5640 struct Lisp_Hash_Table *h = purecopy_hash_table (table);
5641 XSET_HASH_TABLE (obj, h);
5643 else if (COMPILEDP (obj) || VECTORP (obj) || RECORDP (obj))
5645 struct Lisp_Vector *objp = XVECTOR (obj);
5646 ptrdiff_t nbytes = vector_nbytes (objp);
5647 struct Lisp_Vector *vec = pure_alloc (nbytes, Lisp_Vectorlike);
5648 register ptrdiff_t i;
5649 ptrdiff_t size = ASIZE (obj);
5650 if (size & PSEUDOVECTOR_FLAG)
5651 size &= PSEUDOVECTOR_SIZE_MASK;
5652 memcpy (vec, objp, nbytes);
5653 for (i = 0; i < size; i++)
5654 vec->contents[i] = purecopy (vec->contents[i]);
5655 XSETVECTOR (obj, vec);
5657 else if (SYMBOLP (obj))
5659 if (!XSYMBOL (obj)->u.s.pinned && !c_symbol_p (XSYMBOL (obj)))
5660 { /* We can't purify them, but they appear in many pure objects.
5661 Mark them as `pinned' so we know to mark them at every GC cycle. */
5662 XSYMBOL (obj)->u.s.pinned = true;
5663 symbol_block_pinned = symbol_block;
5665 /* Don't hash-cons it. */
5666 return obj;
5668 else
5670 AUTO_STRING (fmt, "Don't know how to purify: %S");
5671 Fsignal (Qerror, list1 (CALLN (Fformat, fmt, obj)));
5674 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5675 Fputhash (obj, obj, Vpurify_flag);
5677 return obj;
5682 /***********************************************************************
5683 Protection from GC
5684 ***********************************************************************/
5686 /* Put an entry in staticvec, pointing at the variable with address
5687 VARADDRESS. */
5689 void
5690 staticpro (Lisp_Object *varaddress)
5692 if (staticidx >= NSTATICS)
5693 fatal ("NSTATICS too small; try increasing and recompiling Emacs.");
5694 staticvec[staticidx++] = varaddress;
5698 /***********************************************************************
5699 Protection from GC
5700 ***********************************************************************/
5702 /* Temporarily prevent garbage collection. */
5704 ptrdiff_t
5705 inhibit_garbage_collection (void)
5707 ptrdiff_t count = SPECPDL_INDEX ();
5709 specbind (Qgc_cons_threshold, make_number (MOST_POSITIVE_FIXNUM));
5710 return count;
5713 /* Used to avoid possible overflows when
5714 converting from C to Lisp integers. */
5716 static Lisp_Object
5717 bounded_number (EMACS_INT number)
5719 return make_number (min (MOST_POSITIVE_FIXNUM, number));
5722 /* Calculate total bytes of live objects. */
5724 static size_t
5725 total_bytes_of_live_objects (void)
5727 size_t tot = 0;
5728 tot += total_conses * sizeof (struct Lisp_Cons);
5729 tot += total_symbols * sizeof (struct Lisp_Symbol);
5730 tot += total_markers * sizeof (union Lisp_Misc);
5731 tot += total_string_bytes;
5732 tot += total_vector_slots * word_size;
5733 tot += total_floats * sizeof (struct Lisp_Float);
5734 tot += total_intervals * sizeof (struct interval);
5735 tot += total_strings * sizeof (struct Lisp_String);
5736 return tot;
5739 #ifdef HAVE_WINDOW_SYSTEM
5741 /* Remove unmarked font-spec and font-entity objects from ENTRY, which is
5742 (DRIVER-TYPE NUM-FRAMES FONT-CACHE-DATA ...), and return changed entry. */
5744 static Lisp_Object
5745 compact_font_cache_entry (Lisp_Object entry)
5747 Lisp_Object tail, *prev = &entry;
5749 for (tail = entry; CONSP (tail); tail = XCDR (tail))
5751 bool drop = 0;
5752 Lisp_Object obj = XCAR (tail);
5754 /* Consider OBJ if it is (font-spec . [font-entity font-entity ...]). */
5755 if (CONSP (obj) && GC_FONT_SPEC_P (XCAR (obj))
5756 && !VECTOR_MARKED_P (GC_XFONT_SPEC (XCAR (obj)))
5757 /* Don't use VECTORP here, as that calls ASIZE, which could
5758 hit assertion violation during GC. */
5759 && (VECTORLIKEP (XCDR (obj))
5760 && ! (gc_asize (XCDR (obj)) & PSEUDOVECTOR_FLAG)))
5762 ptrdiff_t i, size = gc_asize (XCDR (obj));
5763 Lisp_Object obj_cdr = XCDR (obj);
5765 /* If font-spec is not marked, most likely all font-entities
5766 are not marked too. But we must be sure that nothing is
5767 marked within OBJ before we really drop it. */
5768 for (i = 0; i < size; i++)
5770 Lisp_Object objlist;
5772 if (VECTOR_MARKED_P (GC_XFONT_ENTITY (AREF (obj_cdr, i))))
5773 break;
5775 objlist = AREF (AREF (obj_cdr, i), FONT_OBJLIST_INDEX);
5776 for (; CONSP (objlist); objlist = XCDR (objlist))
5778 Lisp_Object val = XCAR (objlist);
5779 struct font *font = GC_XFONT_OBJECT (val);
5781 if (!NILP (AREF (val, FONT_TYPE_INDEX))
5782 && VECTOR_MARKED_P(font))
5783 break;
5785 if (CONSP (objlist))
5787 /* Found a marked font, bail out. */
5788 break;
5792 if (i == size)
5794 /* No marked fonts were found, so this entire font
5795 entity can be dropped. */
5796 drop = 1;
5799 if (drop)
5800 *prev = XCDR (tail);
5801 else
5802 prev = xcdr_addr (tail);
5804 return entry;
5807 /* Compact font caches on all terminals and mark
5808 everything which is still here after compaction. */
5810 static void
5811 compact_font_caches (void)
5813 struct terminal *t;
5815 for (t = terminal_list; t; t = t->next_terminal)
5817 Lisp_Object cache = TERMINAL_FONT_CACHE (t);
5818 /* Inhibit compacting the caches if the user so wishes. Some of
5819 the users don't mind a larger memory footprint, but do mind
5820 slower redisplay. */
5821 if (!inhibit_compacting_font_caches
5822 && CONSP (cache))
5824 Lisp_Object entry;
5826 for (entry = XCDR (cache); CONSP (entry); entry = XCDR (entry))
5827 XSETCAR (entry, compact_font_cache_entry (XCAR (entry)));
5829 mark_object (cache);
5833 #else /* not HAVE_WINDOW_SYSTEM */
5835 #define compact_font_caches() (void)(0)
5837 #endif /* HAVE_WINDOW_SYSTEM */
5839 /* Remove (MARKER . DATA) entries with unmarked MARKER
5840 from buffer undo LIST and return changed list. */
5842 static Lisp_Object
5843 compact_undo_list (Lisp_Object list)
5845 Lisp_Object tail, *prev = &list;
5847 for (tail = list; CONSP (tail); tail = XCDR (tail))
5849 if (CONSP (XCAR (tail))
5850 && MARKERP (XCAR (XCAR (tail)))
5851 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5852 *prev = XCDR (tail);
5853 else
5854 prev = xcdr_addr (tail);
5856 return list;
5859 static void
5860 mark_pinned_objects (void)
5862 for (struct pinned_object *pobj = pinned_objects; pobj; pobj = pobj->next)
5863 mark_object (pobj->object);
5866 static void
5867 mark_pinned_symbols (void)
5869 struct symbol_block *sblk;
5870 int lim = (symbol_block_pinned == symbol_block
5871 ? symbol_block_index : SYMBOL_BLOCK_SIZE);
5873 for (sblk = symbol_block_pinned; sblk; sblk = sblk->next)
5875 struct Lisp_Symbol *sym = sblk->symbols, *end = sym + lim;
5876 for (; sym < end; ++sym)
5877 if (sym->u.s.pinned)
5878 mark_object (make_lisp_symbol (sym));
5880 lim = SYMBOL_BLOCK_SIZE;
5884 /* Subroutine of Fgarbage_collect that does most of the work. It is a
5885 separate function so that we could limit mark_stack in searching
5886 the stack frames below this function, thus avoiding the rare cases
5887 where mark_stack finds values that look like live Lisp objects on
5888 portions of stack that couldn't possibly contain such live objects.
5889 For more details of this, see the discussion at
5890 https://lists.gnu.org/r/emacs-devel/2014-05/msg00270.html. */
5891 static Lisp_Object
5892 garbage_collect_1 (void *end)
5894 struct buffer *nextb;
5895 char stack_top_variable;
5896 ptrdiff_t i;
5897 bool message_p;
5898 ptrdiff_t count = SPECPDL_INDEX ();
5899 struct timespec start;
5900 Lisp_Object retval = Qnil;
5901 size_t tot_before = 0;
5903 /* Can't GC if pure storage overflowed because we can't determine
5904 if something is a pure object or not. */
5905 if (pure_bytes_used_before_overflow)
5906 return Qnil;
5908 /* Record this function, so it appears on the profiler's backtraces. */
5909 record_in_backtrace (QAutomatic_GC, 0, 0);
5911 check_cons_list ();
5913 /* Don't keep undo information around forever.
5914 Do this early on, so it is no problem if the user quits. */
5915 FOR_EACH_BUFFER (nextb)
5916 compact_buffer (nextb);
5918 if (profiler_memory_running)
5919 tot_before = total_bytes_of_live_objects ();
5921 start = current_timespec ();
5923 /* In case user calls debug_print during GC,
5924 don't let that cause a recursive GC. */
5925 consing_since_gc = 0;
5927 /* Save what's currently displayed in the echo area. Don't do that
5928 if we are GC'ing because we've run out of memory, since
5929 push_message will cons, and we might have no memory for that. */
5930 if (NILP (Vmemory_full))
5932 message_p = push_message ();
5933 record_unwind_protect_void (pop_message_unwind);
5935 else
5936 message_p = false;
5938 /* Save a copy of the contents of the stack, for debugging. */
5939 #if MAX_SAVE_STACK > 0
5940 if (NILP (Vpurify_flag))
5942 char *stack;
5943 ptrdiff_t stack_size;
5944 if (&stack_top_variable < stack_bottom)
5946 stack = &stack_top_variable;
5947 stack_size = stack_bottom - &stack_top_variable;
5949 else
5951 stack = stack_bottom;
5952 stack_size = &stack_top_variable - stack_bottom;
5954 if (stack_size <= MAX_SAVE_STACK)
5956 if (stack_copy_size < stack_size)
5958 stack_copy = xrealloc (stack_copy, stack_size);
5959 stack_copy_size = stack_size;
5961 stack = ptr_bounds_set (stack, stack_size);
5962 no_sanitize_memcpy (stack_copy, stack, stack_size);
5965 #endif /* MAX_SAVE_STACK > 0 */
5967 if (garbage_collection_messages)
5968 message1_nolog ("Garbage collecting...");
5970 block_input ();
5972 shrink_regexp_cache ();
5974 gc_in_progress = 1;
5976 /* Mark all the special slots that serve as the roots of accessibility. */
5978 mark_buffer (&buffer_defaults);
5979 mark_buffer (&buffer_local_symbols);
5981 for (i = 0; i < ARRAYELTS (lispsym); i++)
5982 mark_object (builtin_lisp_symbol (i));
5984 for (i = 0; i < staticidx; i++)
5985 mark_object (*staticvec[i]);
5987 mark_pinned_objects ();
5988 mark_pinned_symbols ();
5989 mark_terminals ();
5990 mark_kboards ();
5991 mark_threads ();
5993 #ifdef USE_GTK
5994 xg_mark_data ();
5995 #endif
5997 #ifdef HAVE_WINDOW_SYSTEM
5998 mark_fringe_data ();
5999 #endif
6001 #ifdef HAVE_MODULES
6002 mark_modules ();
6003 #endif
6005 /* Everything is now marked, except for the data in font caches,
6006 undo lists, and finalizers. The first two are compacted by
6007 removing an items which aren't reachable otherwise. */
6009 compact_font_caches ();
6011 FOR_EACH_BUFFER (nextb)
6013 if (!EQ (BVAR (nextb, undo_list), Qt))
6014 bset_undo_list (nextb, compact_undo_list (BVAR (nextb, undo_list)));
6015 /* Now that we have stripped the elements that need not be
6016 in the undo_list any more, we can finally mark the list. */
6017 mark_object (BVAR (nextb, undo_list));
6020 /* Now pre-sweep finalizers. Here, we add any unmarked finalizers
6021 to doomed_finalizers so we can run their associated functions
6022 after GC. It's important to scan finalizers at this stage so
6023 that we can be sure that unmarked finalizers are really
6024 unreachable except for references from their associated functions
6025 and from other finalizers. */
6027 queue_doomed_finalizers (&doomed_finalizers, &finalizers);
6028 mark_finalizer_list (&doomed_finalizers);
6030 gc_sweep ();
6032 /* Clear the mark bits that we set in certain root slots. */
6033 VECTOR_UNMARK (&buffer_defaults);
6034 VECTOR_UNMARK (&buffer_local_symbols);
6036 check_cons_list ();
6038 gc_in_progress = 0;
6040 unblock_input ();
6042 consing_since_gc = 0;
6043 if (gc_cons_threshold < GC_DEFAULT_THRESHOLD / 10)
6044 gc_cons_threshold = GC_DEFAULT_THRESHOLD / 10;
6046 gc_relative_threshold = 0;
6047 if (FLOATP (Vgc_cons_percentage))
6048 { /* Set gc_cons_combined_threshold. */
6049 double tot = total_bytes_of_live_objects ();
6051 tot *= XFLOAT_DATA (Vgc_cons_percentage);
6052 if (0 < tot)
6054 if (tot < TYPE_MAXIMUM (EMACS_INT))
6055 gc_relative_threshold = tot;
6056 else
6057 gc_relative_threshold = TYPE_MAXIMUM (EMACS_INT);
6061 if (garbage_collection_messages && NILP (Vmemory_full))
6063 if (message_p || minibuf_level > 0)
6064 restore_message ();
6065 else
6066 message1_nolog ("Garbage collecting...done");
6069 unbind_to (count, Qnil);
6071 Lisp_Object total[] = {
6072 list4 (Qconses, make_number (sizeof (struct Lisp_Cons)),
6073 bounded_number (total_conses),
6074 bounded_number (total_free_conses)),
6075 list4 (Qsymbols, make_number (sizeof (struct Lisp_Symbol)),
6076 bounded_number (total_symbols),
6077 bounded_number (total_free_symbols)),
6078 list4 (Qmiscs, make_number (sizeof (union Lisp_Misc)),
6079 bounded_number (total_markers),
6080 bounded_number (total_free_markers)),
6081 list4 (Qstrings, make_number (sizeof (struct Lisp_String)),
6082 bounded_number (total_strings),
6083 bounded_number (total_free_strings)),
6084 list3 (Qstring_bytes, make_number (1),
6085 bounded_number (total_string_bytes)),
6086 list3 (Qvectors,
6087 make_number (header_size + sizeof (Lisp_Object)),
6088 bounded_number (total_vectors)),
6089 list4 (Qvector_slots, make_number (word_size),
6090 bounded_number (total_vector_slots),
6091 bounded_number (total_free_vector_slots)),
6092 list4 (Qfloats, make_number (sizeof (struct Lisp_Float)),
6093 bounded_number (total_floats),
6094 bounded_number (total_free_floats)),
6095 list4 (Qintervals, make_number (sizeof (struct interval)),
6096 bounded_number (total_intervals),
6097 bounded_number (total_free_intervals)),
6098 list3 (Qbuffers, make_number (sizeof (struct buffer)),
6099 bounded_number (total_buffers)),
6101 #ifdef DOUG_LEA_MALLOC
6102 list4 (Qheap, make_number (1024),
6103 bounded_number ((mallinfo ().uordblks + 1023) >> 10),
6104 bounded_number ((mallinfo ().fordblks + 1023) >> 10)),
6105 #endif
6107 retval = CALLMANY (Flist, total);
6109 /* GC is complete: now we can run our finalizer callbacks. */
6110 run_finalizers (&doomed_finalizers);
6112 if (!NILP (Vpost_gc_hook))
6114 ptrdiff_t gc_count = inhibit_garbage_collection ();
6115 safe_run_hooks (Qpost_gc_hook);
6116 unbind_to (gc_count, Qnil);
6119 /* Accumulate statistics. */
6120 if (FLOATP (Vgc_elapsed))
6122 struct timespec since_start = timespec_sub (current_timespec (), start);
6123 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed)
6124 + timespectod (since_start));
6127 gcs_done++;
6129 /* Collect profiling data. */
6130 if (profiler_memory_running)
6132 size_t swept = 0;
6133 size_t tot_after = total_bytes_of_live_objects ();
6134 if (tot_before > tot_after)
6135 swept = tot_before - tot_after;
6136 malloc_probe (swept);
6139 return retval;
6142 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
6143 doc: /* Reclaim storage for Lisp objects no longer needed.
6144 Garbage collection happens automatically if you cons more than
6145 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
6146 `garbage-collect' normally returns a list with info on amount of space in use,
6147 where each entry has the form (NAME SIZE USED FREE), where:
6148 - NAME is a symbol describing the kind of objects this entry represents,
6149 - SIZE is the number of bytes used by each one,
6150 - USED is the number of those objects that were found live in the heap,
6151 - FREE is the number of those objects that are not live but that Emacs
6152 keeps around for future allocations (maybe because it does not know how
6153 to return them to the OS).
6154 However, if there was overflow in pure space, `garbage-collect'
6155 returns nil, because real GC can't be done.
6156 See Info node `(elisp)Garbage Collection'. */
6157 attributes: noinline)
6158 (void)
6160 void *end;
6161 SET_STACK_TOP_ADDRESS (&end);
6162 return garbage_collect_1 (end);
6165 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
6166 only interesting objects referenced from glyphs are strings. */
6168 static void
6169 mark_glyph_matrix (struct glyph_matrix *matrix)
6171 struct glyph_row *row = matrix->rows;
6172 struct glyph_row *end = row + matrix->nrows;
6174 for (; row < end; ++row)
6175 if (row->enabled_p)
6177 int area;
6178 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
6180 struct glyph *glyph = row->glyphs[area];
6181 struct glyph *end_glyph = glyph + row->used[area];
6183 for (; glyph < end_glyph; ++glyph)
6184 if (STRINGP (glyph->object)
6185 && !STRING_MARKED_P (XSTRING (glyph->object)))
6186 mark_object (glyph->object);
6191 enum { LAST_MARKED_SIZE = 1 << 9 }; /* Must be a power of 2. */
6192 Lisp_Object last_marked[LAST_MARKED_SIZE] EXTERNALLY_VISIBLE;
6193 static int last_marked_index;
6195 /* For debugging--call abort when we cdr down this many
6196 links of a list, in mark_object. In debugging,
6197 the call to abort will hit a breakpoint.
6198 Normally this is zero and the check never goes off. */
6199 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE;
6201 static void
6202 mark_vectorlike (struct Lisp_Vector *ptr)
6204 ptrdiff_t size = ptr->header.size;
6205 ptrdiff_t i;
6207 eassert (!VECTOR_MARKED_P (ptr));
6208 VECTOR_MARK (ptr); /* Else mark it. */
6209 if (size & PSEUDOVECTOR_FLAG)
6210 size &= PSEUDOVECTOR_SIZE_MASK;
6212 /* Note that this size is not the memory-footprint size, but only
6213 the number of Lisp_Object fields that we should trace.
6214 The distinction is used e.g. by Lisp_Process which places extra
6215 non-Lisp_Object fields at the end of the structure... */
6216 for (i = 0; i < size; i++) /* ...and then mark its elements. */
6217 mark_object (ptr->contents[i]);
6220 /* Like mark_vectorlike but optimized for char-tables (and
6221 sub-char-tables) assuming that the contents are mostly integers or
6222 symbols. */
6224 static void
6225 mark_char_table (struct Lisp_Vector *ptr, enum pvec_type pvectype)
6227 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
6228 /* Consult the Lisp_Sub_Char_Table layout before changing this. */
6229 int i, idx = (pvectype == PVEC_SUB_CHAR_TABLE ? SUB_CHAR_TABLE_OFFSET : 0);
6231 eassert (!VECTOR_MARKED_P (ptr));
6232 VECTOR_MARK (ptr);
6233 for (i = idx; i < size; i++)
6235 Lisp_Object val = ptr->contents[i];
6237 if (INTEGERP (val) || (SYMBOLP (val) && XSYMBOL (val)->u.s.gcmarkbit))
6238 continue;
6239 if (SUB_CHAR_TABLE_P (val))
6241 if (! VECTOR_MARKED_P (XVECTOR (val)))
6242 mark_char_table (XVECTOR (val), PVEC_SUB_CHAR_TABLE);
6244 else
6245 mark_object (val);
6249 NO_INLINE /* To reduce stack depth in mark_object. */
6250 static Lisp_Object
6251 mark_compiled (struct Lisp_Vector *ptr)
6253 int i, size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
6255 VECTOR_MARK (ptr);
6256 for (i = 0; i < size; i++)
6257 if (i != COMPILED_CONSTANTS)
6258 mark_object (ptr->contents[i]);
6259 return size > COMPILED_CONSTANTS ? ptr->contents[COMPILED_CONSTANTS] : Qnil;
6262 /* Mark the chain of overlays starting at PTR. */
6264 static void
6265 mark_overlay (struct Lisp_Overlay *ptr)
6267 for (; ptr && !ptr->gcmarkbit; ptr = ptr->next)
6269 ptr->gcmarkbit = 1;
6270 /* These two are always markers and can be marked fast. */
6271 XMARKER (ptr->start)->gcmarkbit = 1;
6272 XMARKER (ptr->end)->gcmarkbit = 1;
6273 mark_object (ptr->plist);
6277 /* Mark Lisp_Objects and special pointers in BUFFER. */
6279 static void
6280 mark_buffer (struct buffer *buffer)
6282 /* This is handled much like other pseudovectors... */
6283 mark_vectorlike ((struct Lisp_Vector *) buffer);
6285 /* ...but there are some buffer-specific things. */
6287 MARK_INTERVAL_TREE (buffer_intervals (buffer));
6289 /* For now, we just don't mark the undo_list. It's done later in
6290 a special way just before the sweep phase, and after stripping
6291 some of its elements that are not needed any more. */
6293 mark_overlay (buffer->overlays_before);
6294 mark_overlay (buffer->overlays_after);
6296 /* If this is an indirect buffer, mark its base buffer. */
6297 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
6298 mark_buffer (buffer->base_buffer);
6301 /* Mark Lisp faces in the face cache C. */
6303 NO_INLINE /* To reduce stack depth in mark_object. */
6304 static void
6305 mark_face_cache (struct face_cache *c)
6307 if (c)
6309 int i, j;
6310 for (i = 0; i < c->used; ++i)
6312 struct face *face = FACE_FROM_ID_OR_NULL (c->f, i);
6314 if (face)
6316 if (face->font && !VECTOR_MARKED_P (face->font))
6317 mark_vectorlike ((struct Lisp_Vector *) face->font);
6319 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
6320 mark_object (face->lface[j]);
6326 NO_INLINE /* To reduce stack depth in mark_object. */
6327 static void
6328 mark_localized_symbol (struct Lisp_Symbol *ptr)
6330 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
6331 Lisp_Object where = blv->where;
6332 /* If the value is set up for a killed buffer restore its global binding. */
6333 if ((BUFFERP (where) && !BUFFER_LIVE_P (XBUFFER (where))))
6334 swap_in_global_binding (ptr);
6335 mark_object (blv->where);
6336 mark_object (blv->valcell);
6337 mark_object (blv->defcell);
6340 NO_INLINE /* To reduce stack depth in mark_object. */
6341 static void
6342 mark_save_value (struct Lisp_Save_Value *ptr)
6344 /* If `save_type' is zero, `data[0].pointer' is the address
6345 of a memory area containing `data[1].integer' potential
6346 Lisp_Objects. */
6347 if (ptr->save_type == SAVE_TYPE_MEMORY)
6349 Lisp_Object *p = ptr->data[0].pointer;
6350 ptrdiff_t nelt;
6351 for (nelt = ptr->data[1].integer; nelt > 0; nelt--, p++)
6352 mark_maybe_object (*p);
6354 else
6356 /* Find Lisp_Objects in `data[N]' slots and mark them. */
6357 int i;
6358 for (i = 0; i < SAVE_VALUE_SLOTS; i++)
6359 if (save_type (ptr, i) == SAVE_OBJECT)
6360 mark_object (ptr->data[i].object);
6364 /* Remove killed buffers or items whose car is a killed buffer from
6365 LIST, and mark other items. Return changed LIST, which is marked. */
6367 static Lisp_Object
6368 mark_discard_killed_buffers (Lisp_Object list)
6370 Lisp_Object tail, *prev = &list;
6372 for (tail = list; CONSP (tail) && !CONS_MARKED_P (XCONS (tail));
6373 tail = XCDR (tail))
6375 Lisp_Object tem = XCAR (tail);
6376 if (CONSP (tem))
6377 tem = XCAR (tem);
6378 if (BUFFERP (tem) && !BUFFER_LIVE_P (XBUFFER (tem)))
6379 *prev = XCDR (tail);
6380 else
6382 CONS_MARK (XCONS (tail));
6383 mark_object (XCAR (tail));
6384 prev = xcdr_addr (tail);
6387 mark_object (tail);
6388 return list;
6391 /* Determine type of generic Lisp_Object and mark it accordingly.
6393 This function implements a straightforward depth-first marking
6394 algorithm and so the recursion depth may be very high (a few
6395 tens of thousands is not uncommon). To minimize stack usage,
6396 a few cold paths are moved out to NO_INLINE functions above.
6397 In general, inlining them doesn't help you to gain more speed. */
6399 void
6400 mark_object (Lisp_Object arg)
6402 register Lisp_Object obj;
6403 void *po;
6404 #if GC_CHECK_MARKED_OBJECTS
6405 struct mem_node *m;
6406 #endif
6407 ptrdiff_t cdr_count = 0;
6409 obj = arg;
6410 loop:
6412 po = XPNTR (obj);
6413 if (PURE_P (po))
6414 return;
6416 last_marked[last_marked_index++] = obj;
6417 last_marked_index &= LAST_MARKED_SIZE - 1;
6419 /* Perform some sanity checks on the objects marked here. Abort if
6420 we encounter an object we know is bogus. This increases GC time
6421 by ~80%. */
6422 #if GC_CHECK_MARKED_OBJECTS
6424 /* Check that the object pointed to by PO is known to be a Lisp
6425 structure allocated from the heap. */
6426 #define CHECK_ALLOCATED() \
6427 do { \
6428 m = mem_find (po); \
6429 if (m == MEM_NIL) \
6430 emacs_abort (); \
6431 } while (0)
6433 /* Check that the object pointed to by PO is live, using predicate
6434 function LIVEP. */
6435 #define CHECK_LIVE(LIVEP) \
6436 do { \
6437 if (!LIVEP (m, po)) \
6438 emacs_abort (); \
6439 } while (0)
6441 /* Check both of the above conditions, for non-symbols. */
6442 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
6443 do { \
6444 CHECK_ALLOCATED (); \
6445 CHECK_LIVE (LIVEP); \
6446 } while (0) \
6448 /* Check both of the above conditions, for symbols. */
6449 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() \
6450 do { \
6451 if (!c_symbol_p (ptr)) \
6453 CHECK_ALLOCATED (); \
6454 CHECK_LIVE (live_symbol_p); \
6456 } while (0) \
6458 #else /* not GC_CHECK_MARKED_OBJECTS */
6460 #define CHECK_LIVE(LIVEP) ((void) 0)
6461 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) ((void) 0)
6462 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() ((void) 0)
6464 #endif /* not GC_CHECK_MARKED_OBJECTS */
6466 switch (XTYPE (obj))
6468 case Lisp_String:
6470 register struct Lisp_String *ptr = XSTRING (obj);
6471 if (STRING_MARKED_P (ptr))
6472 break;
6473 CHECK_ALLOCATED_AND_LIVE (live_string_p);
6474 MARK_STRING (ptr);
6475 MARK_INTERVAL_TREE (ptr->u.s.intervals);
6476 #ifdef GC_CHECK_STRING_BYTES
6477 /* Check that the string size recorded in the string is the
6478 same as the one recorded in the sdata structure. */
6479 string_bytes (ptr);
6480 #endif /* GC_CHECK_STRING_BYTES */
6482 break;
6484 case Lisp_Vectorlike:
6486 register struct Lisp_Vector *ptr = XVECTOR (obj);
6488 if (VECTOR_MARKED_P (ptr))
6489 break;
6491 #if GC_CHECK_MARKED_OBJECTS
6492 m = mem_find (po);
6493 if (m == MEM_NIL && !SUBRP (obj) && !main_thread_p (po))
6494 emacs_abort ();
6495 #endif /* GC_CHECK_MARKED_OBJECTS */
6497 enum pvec_type pvectype
6498 = PSEUDOVECTOR_TYPE (ptr);
6500 if (pvectype != PVEC_SUBR
6501 && pvectype != PVEC_BUFFER
6502 && !main_thread_p (po))
6503 CHECK_LIVE (live_vector_p);
6505 switch (pvectype)
6507 case PVEC_BUFFER:
6508 #if GC_CHECK_MARKED_OBJECTS
6510 struct buffer *b;
6511 FOR_EACH_BUFFER (b)
6512 if (b == po)
6513 break;
6514 if (b == NULL)
6515 emacs_abort ();
6517 #endif /* GC_CHECK_MARKED_OBJECTS */
6518 mark_buffer ((struct buffer *) ptr);
6519 break;
6521 case PVEC_COMPILED:
6522 /* Although we could treat this just like a vector, mark_compiled
6523 returns the COMPILED_CONSTANTS element, which is marked at the
6524 next iteration of goto-loop here. This is done to avoid a few
6525 recursive calls to mark_object. */
6526 obj = mark_compiled (ptr);
6527 if (!NILP (obj))
6528 goto loop;
6529 break;
6531 case PVEC_FRAME:
6533 struct frame *f = (struct frame *) ptr;
6535 mark_vectorlike (ptr);
6536 mark_face_cache (f->face_cache);
6537 #ifdef HAVE_WINDOW_SYSTEM
6538 if (FRAME_WINDOW_P (f) && FRAME_X_OUTPUT (f))
6540 struct font *font = FRAME_FONT (f);
6542 if (font && !VECTOR_MARKED_P (font))
6543 mark_vectorlike ((struct Lisp_Vector *) font);
6545 #endif
6547 break;
6549 case PVEC_WINDOW:
6551 struct window *w = (struct window *) ptr;
6553 mark_vectorlike (ptr);
6555 /* Mark glyph matrices, if any. Marking window
6556 matrices is sufficient because frame matrices
6557 use the same glyph memory. */
6558 if (w->current_matrix)
6560 mark_glyph_matrix (w->current_matrix);
6561 mark_glyph_matrix (w->desired_matrix);
6564 /* Filter out killed buffers from both buffer lists
6565 in attempt to help GC to reclaim killed buffers faster.
6566 We can do it elsewhere for live windows, but this is the
6567 best place to do it for dead windows. */
6568 wset_prev_buffers
6569 (w, mark_discard_killed_buffers (w->prev_buffers));
6570 wset_next_buffers
6571 (w, mark_discard_killed_buffers (w->next_buffers));
6573 break;
6575 case PVEC_HASH_TABLE:
6577 struct Lisp_Hash_Table *h = (struct Lisp_Hash_Table *) ptr;
6579 mark_vectorlike (ptr);
6580 mark_object (h->test.name);
6581 mark_object (h->test.user_hash_function);
6582 mark_object (h->test.user_cmp_function);
6583 /* If hash table is not weak, mark all keys and values.
6584 For weak tables, mark only the vector. */
6585 if (NILP (h->weak))
6586 mark_object (h->key_and_value);
6587 else
6588 VECTOR_MARK (XVECTOR (h->key_and_value));
6590 break;
6592 case PVEC_CHAR_TABLE:
6593 case PVEC_SUB_CHAR_TABLE:
6594 mark_char_table (ptr, (enum pvec_type) pvectype);
6595 break;
6597 case PVEC_BOOL_VECTOR:
6598 /* No Lisp_Objects to mark in a bool vector. */
6599 VECTOR_MARK (ptr);
6600 break;
6602 case PVEC_SUBR:
6603 break;
6605 case PVEC_FREE:
6606 emacs_abort ();
6608 default:
6609 mark_vectorlike (ptr);
6612 break;
6614 case Lisp_Symbol:
6616 struct Lisp_Symbol *ptr = XSYMBOL (obj);
6617 nextsym:
6618 if (ptr->u.s.gcmarkbit)
6619 break;
6620 CHECK_ALLOCATED_AND_LIVE_SYMBOL ();
6621 ptr->u.s.gcmarkbit = 1;
6622 /* Attempt to catch bogus objects. */
6623 eassert (valid_lisp_object_p (ptr->u.s.function));
6624 mark_object (ptr->u.s.function);
6625 mark_object (ptr->u.s.plist);
6626 switch (ptr->u.s.redirect)
6628 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
6629 case SYMBOL_VARALIAS:
6631 Lisp_Object tem;
6632 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
6633 mark_object (tem);
6634 break;
6636 case SYMBOL_LOCALIZED:
6637 mark_localized_symbol (ptr);
6638 break;
6639 case SYMBOL_FORWARDED:
6640 /* If the value is forwarded to a buffer or keyboard field,
6641 these are marked when we see the corresponding object.
6642 And if it's forwarded to a C variable, either it's not
6643 a Lisp_Object var, or it's staticpro'd already. */
6644 break;
6645 default: emacs_abort ();
6647 if (!PURE_P (XSTRING (ptr->u.s.name)))
6648 MARK_STRING (XSTRING (ptr->u.s.name));
6649 MARK_INTERVAL_TREE (string_intervals (ptr->u.s.name));
6650 /* Inner loop to mark next symbol in this bucket, if any. */
6651 po = ptr = ptr->u.s.next;
6652 if (ptr)
6653 goto nextsym;
6655 break;
6657 case Lisp_Misc:
6658 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
6660 if (XMISCANY (obj)->gcmarkbit)
6661 break;
6663 switch (XMISCTYPE (obj))
6665 case Lisp_Misc_Marker:
6666 /* DO NOT mark thru the marker's chain.
6667 The buffer's markers chain does not preserve markers from gc;
6668 instead, markers are removed from the chain when freed by gc. */
6669 XMISCANY (obj)->gcmarkbit = 1;
6670 break;
6672 case Lisp_Misc_Save_Value:
6673 XMISCANY (obj)->gcmarkbit = 1;
6674 mark_save_value (XSAVE_VALUE (obj));
6675 break;
6677 case Lisp_Misc_Overlay:
6678 mark_overlay (XOVERLAY (obj));
6679 break;
6681 case Lisp_Misc_Finalizer:
6682 XMISCANY (obj)->gcmarkbit = true;
6683 mark_object (XFINALIZER (obj)->function);
6684 break;
6686 #ifdef HAVE_MODULES
6687 case Lisp_Misc_User_Ptr:
6688 XMISCANY (obj)->gcmarkbit = true;
6689 break;
6690 #endif
6692 default:
6693 emacs_abort ();
6695 break;
6697 case Lisp_Cons:
6699 register struct Lisp_Cons *ptr = XCONS (obj);
6700 if (CONS_MARKED_P (ptr))
6701 break;
6702 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
6703 CONS_MARK (ptr);
6704 /* If the cdr is nil, avoid recursion for the car. */
6705 if (EQ (ptr->u.s.u.cdr, Qnil))
6707 obj = ptr->u.s.car;
6708 cdr_count = 0;
6709 goto loop;
6711 mark_object (ptr->u.s.car);
6712 obj = ptr->u.s.u.cdr;
6713 cdr_count++;
6714 if (cdr_count == mark_object_loop_halt)
6715 emacs_abort ();
6716 goto loop;
6719 case Lisp_Float:
6720 CHECK_ALLOCATED_AND_LIVE (live_float_p);
6721 FLOAT_MARK (XFLOAT (obj));
6722 break;
6724 case_Lisp_Int:
6725 break;
6727 default:
6728 emacs_abort ();
6731 #undef CHECK_LIVE
6732 #undef CHECK_ALLOCATED
6733 #undef CHECK_ALLOCATED_AND_LIVE
6735 /* Mark the Lisp pointers in the terminal objects.
6736 Called by Fgarbage_collect. */
6738 static void
6739 mark_terminals (void)
6741 struct terminal *t;
6742 for (t = terminal_list; t; t = t->next_terminal)
6744 eassert (t->name != NULL);
6745 #ifdef HAVE_WINDOW_SYSTEM
6746 /* If a terminal object is reachable from a stacpro'ed object,
6747 it might have been marked already. Make sure the image cache
6748 gets marked. */
6749 mark_image_cache (t->image_cache);
6750 #endif /* HAVE_WINDOW_SYSTEM */
6751 if (!VECTOR_MARKED_P (t))
6752 mark_vectorlike ((struct Lisp_Vector *)t);
6758 /* Value is non-zero if OBJ will survive the current GC because it's
6759 either marked or does not need to be marked to survive. */
6761 bool
6762 survives_gc_p (Lisp_Object obj)
6764 bool survives_p;
6766 switch (XTYPE (obj))
6768 case_Lisp_Int:
6769 survives_p = 1;
6770 break;
6772 case Lisp_Symbol:
6773 survives_p = XSYMBOL (obj)->u.s.gcmarkbit;
6774 break;
6776 case Lisp_Misc:
6777 survives_p = XMISCANY (obj)->gcmarkbit;
6778 break;
6780 case Lisp_String:
6781 survives_p = STRING_MARKED_P (XSTRING (obj));
6782 break;
6784 case Lisp_Vectorlike:
6785 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
6786 break;
6788 case Lisp_Cons:
6789 survives_p = CONS_MARKED_P (XCONS (obj));
6790 break;
6792 case Lisp_Float:
6793 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
6794 break;
6796 default:
6797 emacs_abort ();
6800 return survives_p || PURE_P (XPNTR (obj));
6806 NO_INLINE /* For better stack traces */
6807 static void
6808 sweep_conses (void)
6810 struct cons_block *cblk;
6811 struct cons_block **cprev = &cons_block;
6812 int lim = cons_block_index;
6813 EMACS_INT num_free = 0, num_used = 0;
6815 cons_free_list = 0;
6817 for (cblk = cons_block; cblk; cblk = *cprev)
6819 int i = 0;
6820 int this_free = 0;
6821 int ilim = (lim + BITS_PER_BITS_WORD - 1) / BITS_PER_BITS_WORD;
6823 /* Scan the mark bits an int at a time. */
6824 for (i = 0; i < ilim; i++)
6826 if (cblk->gcmarkbits[i] == BITS_WORD_MAX)
6828 /* Fast path - all cons cells for this int are marked. */
6829 cblk->gcmarkbits[i] = 0;
6830 num_used += BITS_PER_BITS_WORD;
6832 else
6834 /* Some cons cells for this int are not marked.
6835 Find which ones, and free them. */
6836 int start, pos, stop;
6838 start = i * BITS_PER_BITS_WORD;
6839 stop = lim - start;
6840 if (stop > BITS_PER_BITS_WORD)
6841 stop = BITS_PER_BITS_WORD;
6842 stop += start;
6844 for (pos = start; pos < stop; pos++)
6846 struct Lisp_Cons *acons
6847 = ptr_bounds_copy (&cblk->conses[pos], cblk);
6848 if (!CONS_MARKED_P (acons))
6850 this_free++;
6851 cblk->conses[pos].u.s.u.chain = cons_free_list;
6852 cons_free_list = &cblk->conses[pos];
6853 cons_free_list->u.s.car = Vdead;
6855 else
6857 num_used++;
6858 CONS_UNMARK (acons);
6864 lim = CONS_BLOCK_SIZE;
6865 /* If this block contains only free conses and we have already
6866 seen more than two blocks worth of free conses then deallocate
6867 this block. */
6868 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
6870 *cprev = cblk->next;
6871 /* Unhook from the free list. */
6872 cons_free_list = cblk->conses[0].u.s.u.chain;
6873 lisp_align_free (cblk);
6875 else
6877 num_free += this_free;
6878 cprev = &cblk->next;
6881 total_conses = num_used;
6882 total_free_conses = num_free;
6885 NO_INLINE /* For better stack traces */
6886 static void
6887 sweep_floats (void)
6889 register struct float_block *fblk;
6890 struct float_block **fprev = &float_block;
6891 register int lim = float_block_index;
6892 EMACS_INT num_free = 0, num_used = 0;
6894 float_free_list = 0;
6896 for (fblk = float_block; fblk; fblk = *fprev)
6898 register int i;
6899 int this_free = 0;
6900 for (i = 0; i < lim; i++)
6902 struct Lisp_Float *afloat = ptr_bounds_copy (&fblk->floats[i], fblk);
6903 if (!FLOAT_MARKED_P (afloat))
6905 this_free++;
6906 fblk->floats[i].u.chain = float_free_list;
6907 float_free_list = &fblk->floats[i];
6909 else
6911 num_used++;
6912 FLOAT_UNMARK (afloat);
6915 lim = FLOAT_BLOCK_SIZE;
6916 /* If this block contains only free floats and we have already
6917 seen more than two blocks worth of free floats then deallocate
6918 this block. */
6919 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6921 *fprev = fblk->next;
6922 /* Unhook from the free list. */
6923 float_free_list = fblk->floats[0].u.chain;
6924 lisp_align_free (fblk);
6926 else
6928 num_free += this_free;
6929 fprev = &fblk->next;
6932 total_floats = num_used;
6933 total_free_floats = num_free;
6936 NO_INLINE /* For better stack traces */
6937 static void
6938 sweep_intervals (void)
6940 register struct interval_block *iblk;
6941 struct interval_block **iprev = &interval_block;
6942 register int lim = interval_block_index;
6943 EMACS_INT num_free = 0, num_used = 0;
6945 interval_free_list = 0;
6947 for (iblk = interval_block; iblk; iblk = *iprev)
6949 register int i;
6950 int this_free = 0;
6952 for (i = 0; i < lim; i++)
6954 if (!iblk->intervals[i].gcmarkbit)
6956 set_interval_parent (&iblk->intervals[i], interval_free_list);
6957 interval_free_list = &iblk->intervals[i];
6958 this_free++;
6960 else
6962 num_used++;
6963 iblk->intervals[i].gcmarkbit = 0;
6966 lim = INTERVAL_BLOCK_SIZE;
6967 /* If this block contains only free intervals and we have already
6968 seen more than two blocks worth of free intervals then
6969 deallocate this block. */
6970 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6972 *iprev = iblk->next;
6973 /* Unhook from the free list. */
6974 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
6975 lisp_free (iblk);
6977 else
6979 num_free += this_free;
6980 iprev = &iblk->next;
6983 total_intervals = num_used;
6984 total_free_intervals = num_free;
6987 NO_INLINE /* For better stack traces */
6988 static void
6989 sweep_symbols (void)
6991 struct symbol_block *sblk;
6992 struct symbol_block **sprev = &symbol_block;
6993 int lim = symbol_block_index;
6994 EMACS_INT num_free = 0, num_used = ARRAYELTS (lispsym);
6996 symbol_free_list = NULL;
6998 for (int i = 0; i < ARRAYELTS (lispsym); i++)
6999 lispsym[i].u.s.gcmarkbit = 0;
7001 for (sblk = symbol_block; sblk; sblk = *sprev)
7003 int this_free = 0;
7004 struct Lisp_Symbol *sym = sblk->symbols;
7005 struct Lisp_Symbol *end = sym + lim;
7007 for (; sym < end; ++sym)
7009 if (!sym->u.s.gcmarkbit)
7011 if (sym->u.s.redirect == SYMBOL_LOCALIZED)
7013 xfree (SYMBOL_BLV (sym));
7014 /* At every GC we sweep all symbol_blocks and rebuild the
7015 symbol_free_list, so those symbols which stayed unused
7016 between the two will be re-swept.
7017 So we have to make sure we don't re-free this blv next
7018 time we sweep this symbol_block (bug#29066). */
7019 sym->u.s.redirect = SYMBOL_PLAINVAL;
7021 sym->u.s.next = symbol_free_list;
7022 symbol_free_list = sym;
7023 symbol_free_list->u.s.function = Vdead;
7024 ++this_free;
7026 else
7028 ++num_used;
7029 sym->u.s.gcmarkbit = 0;
7030 /* Attempt to catch bogus objects. */
7031 eassert (valid_lisp_object_p (sym->u.s.function));
7035 lim = SYMBOL_BLOCK_SIZE;
7036 /* If this block contains only free symbols and we have already
7037 seen more than two blocks worth of free symbols then deallocate
7038 this block. */
7039 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
7041 *sprev = sblk->next;
7042 /* Unhook from the free list. */
7043 symbol_free_list = sblk->symbols[0].u.s.next;
7044 lisp_free (sblk);
7046 else
7048 num_free += this_free;
7049 sprev = &sblk->next;
7052 total_symbols = num_used;
7053 total_free_symbols = num_free;
7056 NO_INLINE /* For better stack traces. */
7057 static void
7058 sweep_misc (void)
7060 register struct marker_block *mblk;
7061 struct marker_block **mprev = &marker_block;
7062 register int lim = marker_block_index;
7063 EMACS_INT num_free = 0, num_used = 0;
7065 /* Put all unmarked misc's on free list. For a marker, first
7066 unchain it from the buffer it points into. */
7068 misc_free_list = 0;
7070 for (mblk = marker_block; mblk; mblk = *mprev)
7072 register int i;
7073 int this_free = 0;
7075 for (i = 0; i < lim; i++)
7077 if (!mblk->markers[i].m.u_any.gcmarkbit)
7079 if (mblk->markers[i].m.u_any.type == Lisp_Misc_Marker)
7080 /* Make sure markers have been unchained from their buffer
7081 in sweep_buffer before we collect them. */
7082 eassert (!mblk->markers[i].m.u_marker.buffer);
7083 else if (mblk->markers[i].m.u_any.type == Lisp_Misc_Finalizer)
7084 unchain_finalizer (&mblk->markers[i].m.u_finalizer);
7085 #ifdef HAVE_MODULES
7086 else if (mblk->markers[i].m.u_any.type == Lisp_Misc_User_Ptr)
7088 struct Lisp_User_Ptr *uptr = &mblk->markers[i].m.u_user_ptr;
7089 if (uptr->finalizer)
7090 uptr->finalizer (uptr->p);
7092 #endif
7093 /* Set the type of the freed object to Lisp_Misc_Free.
7094 We could leave the type alone, since nobody checks it,
7095 but this might catch bugs faster. */
7096 mblk->markers[i].m.u_marker.type = Lisp_Misc_Free;
7097 mblk->markers[i].m.u_free.chain = misc_free_list;
7098 misc_free_list = &mblk->markers[i].m;
7099 this_free++;
7101 else
7103 num_used++;
7104 mblk->markers[i].m.u_any.gcmarkbit = 0;
7107 lim = MARKER_BLOCK_SIZE;
7108 /* If this block contains only free markers and we have already
7109 seen more than two blocks worth of free markers then deallocate
7110 this block. */
7111 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
7113 *mprev = mblk->next;
7114 /* Unhook from the free list. */
7115 misc_free_list = mblk->markers[0].m.u_free.chain;
7116 lisp_free (mblk);
7118 else
7120 num_free += this_free;
7121 mprev = &mblk->next;
7125 total_markers = num_used;
7126 total_free_markers = num_free;
7129 /* Remove BUFFER's markers that are due to be swept. This is needed since
7130 we treat BUF_MARKERS and markers's `next' field as weak pointers. */
7131 static void
7132 unchain_dead_markers (struct buffer *buffer)
7134 struct Lisp_Marker *this, **prev = &BUF_MARKERS (buffer);
7136 while ((this = *prev))
7137 if (this->gcmarkbit)
7138 prev = &this->next;
7139 else
7141 this->buffer = NULL;
7142 *prev = this->next;
7146 NO_INLINE /* For better stack traces */
7147 static void
7148 sweep_buffers (void)
7150 register struct buffer *buffer, **bprev = &all_buffers;
7152 total_buffers = 0;
7153 for (buffer = all_buffers; buffer; buffer = *bprev)
7154 if (!VECTOR_MARKED_P (buffer))
7156 *bprev = buffer->next;
7157 lisp_free (buffer);
7159 else
7161 VECTOR_UNMARK (buffer);
7162 /* Do not use buffer_(set|get)_intervals here. */
7163 buffer->text->intervals = balance_intervals (buffer->text->intervals);
7164 unchain_dead_markers (buffer);
7165 total_buffers++;
7166 bprev = &buffer->next;
7170 /* Sweep: find all structures not marked, and free them. */
7171 static void
7172 gc_sweep (void)
7174 /* Remove or mark entries in weak hash tables.
7175 This must be done before any object is unmarked. */
7176 sweep_weak_hash_tables ();
7178 sweep_strings ();
7179 check_string_bytes (!noninteractive);
7180 sweep_conses ();
7181 sweep_floats ();
7182 sweep_intervals ();
7183 sweep_symbols ();
7184 sweep_buffers ();
7185 sweep_misc ();
7186 sweep_vectors ();
7187 check_string_bytes (!noninteractive);
7190 DEFUN ("memory-info", Fmemory_info, Smemory_info, 0, 0, 0,
7191 doc: /* Return a list of (TOTAL-RAM FREE-RAM TOTAL-SWAP FREE-SWAP).
7192 All values are in Kbytes. If there is no swap space,
7193 last two values are zero. If the system is not supported
7194 or memory information can't be obtained, return nil. */)
7195 (void)
7197 #if defined HAVE_LINUX_SYSINFO
7198 struct sysinfo si;
7199 uintmax_t units;
7201 if (sysinfo (&si))
7202 return Qnil;
7203 #ifdef LINUX_SYSINFO_UNIT
7204 units = si.mem_unit;
7205 #else
7206 units = 1;
7207 #endif
7208 return list4i ((uintmax_t) si.totalram * units / 1024,
7209 (uintmax_t) si.freeram * units / 1024,
7210 (uintmax_t) si.totalswap * units / 1024,
7211 (uintmax_t) si.freeswap * units / 1024);
7212 #elif defined WINDOWSNT
7213 unsigned long long totalram, freeram, totalswap, freeswap;
7215 if (w32_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
7216 return list4i ((uintmax_t) totalram / 1024,
7217 (uintmax_t) freeram / 1024,
7218 (uintmax_t) totalswap / 1024,
7219 (uintmax_t) freeswap / 1024);
7220 else
7221 return Qnil;
7222 #elif defined MSDOS
7223 unsigned long totalram, freeram, totalswap, freeswap;
7225 if (dos_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
7226 return list4i ((uintmax_t) totalram / 1024,
7227 (uintmax_t) freeram / 1024,
7228 (uintmax_t) totalswap / 1024,
7229 (uintmax_t) freeswap / 1024);
7230 else
7231 return Qnil;
7232 #else /* not HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
7233 /* FIXME: add more systems. */
7234 return Qnil;
7235 #endif /* HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
7238 /* Debugging aids. */
7240 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
7241 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
7242 This may be helpful in debugging Emacs's memory usage.
7243 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
7244 (void)
7246 Lisp_Object end;
7248 #if defined HAVE_NS || defined __APPLE__ || !HAVE_SBRK
7249 /* Avoid warning. sbrk has no relation to memory allocated anyway. */
7250 XSETINT (end, 0);
7251 #else
7252 XSETINT (end, (intptr_t) (char *) sbrk (0) / 1024);
7253 #endif
7255 return end;
7258 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
7259 doc: /* Return a list of counters that measure how much consing there has been.
7260 Each of these counters increments for a certain kind of object.
7261 The counters wrap around from the largest positive integer to zero.
7262 Garbage collection does not decrease them.
7263 The elements of the value are as follows:
7264 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
7265 All are in units of 1 = one object consed
7266 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
7267 objects consed.
7268 MISCS include overlays, markers, and some internal types.
7269 Frames, windows, buffers, and subprocesses count as vectors
7270 (but the contents of a buffer's text do not count here). */)
7271 (void)
7273 return listn (CONSTYPE_HEAP, 8,
7274 bounded_number (cons_cells_consed),
7275 bounded_number (floats_consed),
7276 bounded_number (vector_cells_consed),
7277 bounded_number (symbols_consed),
7278 bounded_number (string_chars_consed),
7279 bounded_number (misc_objects_consed),
7280 bounded_number (intervals_consed),
7281 bounded_number (strings_consed));
7284 static bool
7285 symbol_uses_obj (Lisp_Object symbol, Lisp_Object obj)
7287 struct Lisp_Symbol *sym = XSYMBOL (symbol);
7288 Lisp_Object val = find_symbol_value (symbol);
7289 return (EQ (val, obj)
7290 || EQ (sym->u.s.function, obj)
7291 || (!NILP (sym->u.s.function)
7292 && COMPILEDP (sym->u.s.function)
7293 && EQ (AREF (sym->u.s.function, COMPILED_BYTECODE), obj))
7294 || (!NILP (val)
7295 && COMPILEDP (val)
7296 && EQ (AREF (val, COMPILED_BYTECODE), obj)));
7299 /* Find at most FIND_MAX symbols which have OBJ as their value or
7300 function. This is used in gdbinit's `xwhichsymbols' command. */
7302 Lisp_Object
7303 which_symbols (Lisp_Object obj, EMACS_INT find_max)
7305 struct symbol_block *sblk;
7306 ptrdiff_t gc_count = inhibit_garbage_collection ();
7307 Lisp_Object found = Qnil;
7309 if (! DEADP (obj))
7311 for (int i = 0; i < ARRAYELTS (lispsym); i++)
7313 Lisp_Object sym = builtin_lisp_symbol (i);
7314 if (symbol_uses_obj (sym, obj))
7316 found = Fcons (sym, found);
7317 if (--find_max == 0)
7318 goto out;
7322 for (sblk = symbol_block; sblk; sblk = sblk->next)
7324 struct Lisp_Symbol *asym = sblk->symbols;
7325 int bn;
7327 for (bn = 0; bn < SYMBOL_BLOCK_SIZE; bn++, asym++)
7329 if (sblk == symbol_block && bn >= symbol_block_index)
7330 break;
7332 Lisp_Object sym = make_lisp_symbol (asym);
7333 if (symbol_uses_obj (sym, obj))
7335 found = Fcons (sym, found);
7336 if (--find_max == 0)
7337 goto out;
7343 out:
7344 unbind_to (gc_count, Qnil);
7345 return found;
7348 #ifdef SUSPICIOUS_OBJECT_CHECKING
7350 static void *
7351 find_suspicious_object_in_range (void *begin, void *end)
7353 char *begin_a = begin;
7354 char *end_a = end;
7355 int i;
7357 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
7359 char *suspicious_object = suspicious_objects[i];
7360 if (begin_a <= suspicious_object && suspicious_object < end_a)
7361 return suspicious_object;
7364 return NULL;
7367 static void
7368 note_suspicious_free (void *ptr)
7370 struct suspicious_free_record *rec;
7372 rec = &suspicious_free_history[suspicious_free_history_index++];
7373 if (suspicious_free_history_index ==
7374 ARRAYELTS (suspicious_free_history))
7376 suspicious_free_history_index = 0;
7379 memset (rec, 0, sizeof (*rec));
7380 rec->suspicious_object = ptr;
7381 backtrace (&rec->backtrace[0], ARRAYELTS (rec->backtrace));
7384 static void
7385 detect_suspicious_free (void *ptr)
7387 int i;
7389 eassert (ptr != NULL);
7391 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
7392 if (suspicious_objects[i] == ptr)
7394 note_suspicious_free (ptr);
7395 suspicious_objects[i] = NULL;
7399 #endif /* SUSPICIOUS_OBJECT_CHECKING */
7401 DEFUN ("suspicious-object", Fsuspicious_object, Ssuspicious_object, 1, 1, 0,
7402 doc: /* Return OBJ, maybe marking it for extra scrutiny.
7403 If Emacs is compiled with suspicious object checking, capture
7404 a stack trace when OBJ is freed in order to help track down
7405 garbage collection bugs. Otherwise, do nothing and return OBJ. */)
7406 (Lisp_Object obj)
7408 #ifdef SUSPICIOUS_OBJECT_CHECKING
7409 /* Right now, we care only about vectors. */
7410 if (VECTORLIKEP (obj))
7412 suspicious_objects[suspicious_object_index++] = XVECTOR (obj);
7413 if (suspicious_object_index == ARRAYELTS (suspicious_objects))
7414 suspicious_object_index = 0;
7416 #endif
7417 return obj;
7420 #ifdef ENABLE_CHECKING
7422 bool suppress_checking;
7424 void
7425 die (const char *msg, const char *file, int line)
7427 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: assertion failed: %s\r\n",
7428 file, line, msg);
7429 terminate_due_to_signal (SIGABRT, INT_MAX);
7432 #endif /* ENABLE_CHECKING */
7434 #if defined (ENABLE_CHECKING) && USE_STACK_LISP_OBJECTS
7436 /* Stress alloca with inconveniently sized requests and check
7437 whether all allocated areas may be used for Lisp_Object. */
7439 NO_INLINE static void
7440 verify_alloca (void)
7442 int i;
7443 enum { ALLOCA_CHECK_MAX = 256 };
7444 /* Start from size of the smallest Lisp object. */
7445 for (i = sizeof (struct Lisp_Cons); i <= ALLOCA_CHECK_MAX; i++)
7447 void *ptr = alloca (i);
7448 make_lisp_ptr (ptr, Lisp_Cons);
7452 #else /* not ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7454 #define verify_alloca() ((void) 0)
7456 #endif /* ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7458 /* Initialization. */
7460 void
7461 init_alloc_once (void)
7463 /* Even though Qt's contents are not set up, its address is known. */
7464 Vpurify_flag = Qt;
7466 purebeg = PUREBEG;
7467 pure_size = PURESIZE;
7469 verify_alloca ();
7470 init_finalizer_list (&finalizers);
7471 init_finalizer_list (&doomed_finalizers);
7473 mem_init ();
7474 Vdead = make_pure_string ("DEAD", 4, 4, 0);
7476 #ifdef DOUG_LEA_MALLOC
7477 mallopt (M_TRIM_THRESHOLD, 128 * 1024); /* Trim threshold. */
7478 mallopt (M_MMAP_THRESHOLD, 64 * 1024); /* Mmap threshold. */
7479 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* Max. number of mmap'ed areas. */
7480 #endif
7481 init_strings ();
7482 init_vectors ();
7484 refill_memory_reserve ();
7485 gc_cons_threshold = GC_DEFAULT_THRESHOLD;
7488 void
7489 init_alloc (void)
7491 Vgc_elapsed = make_float (0.0);
7492 gcs_done = 0;
7494 #if USE_VALGRIND
7495 valgrind_p = RUNNING_ON_VALGRIND != 0;
7496 #endif
7499 void
7500 syms_of_alloc (void)
7502 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
7503 doc: /* Number of bytes of consing between garbage collections.
7504 Garbage collection can happen automatically once this many bytes have been
7505 allocated since the last garbage collection. All data types count.
7507 Garbage collection happens automatically only when `eval' is called.
7509 By binding this temporarily to a large number, you can effectively
7510 prevent garbage collection during a part of the program.
7511 See also `gc-cons-percentage'. */);
7513 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
7514 doc: /* Portion of the heap used for allocation.
7515 Garbage collection can happen automatically once this portion of the heap
7516 has been allocated since the last garbage collection.
7517 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
7518 Vgc_cons_percentage = make_float (0.1);
7520 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
7521 doc: /* Number of bytes of shareable Lisp data allocated so far. */);
7523 DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
7524 doc: /* Number of cons cells that have been consed so far. */);
7526 DEFVAR_INT ("floats-consed", floats_consed,
7527 doc: /* Number of floats that have been consed so far. */);
7529 DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
7530 doc: /* Number of vector cells that have been consed so far. */);
7532 DEFVAR_INT ("symbols-consed", symbols_consed,
7533 doc: /* Number of symbols that have been consed so far. */);
7534 symbols_consed += ARRAYELTS (lispsym);
7536 DEFVAR_INT ("string-chars-consed", string_chars_consed,
7537 doc: /* Number of string characters that have been consed so far. */);
7539 DEFVAR_INT ("misc-objects-consed", misc_objects_consed,
7540 doc: /* Number of miscellaneous objects that have been consed so far.
7541 These include markers and overlays, plus certain objects not visible
7542 to users. */);
7544 DEFVAR_INT ("intervals-consed", intervals_consed,
7545 doc: /* Number of intervals that have been consed so far. */);
7547 DEFVAR_INT ("strings-consed", strings_consed,
7548 doc: /* Number of strings that have been consed so far. */);
7550 DEFVAR_LISP ("purify-flag", Vpurify_flag,
7551 doc: /* Non-nil means loading Lisp code in order to dump an executable.
7552 This means that certain objects should be allocated in shared (pure) space.
7553 It can also be set to a hash-table, in which case this table is used to
7554 do hash-consing of the objects allocated to pure space. */);
7556 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
7557 doc: /* Non-nil means display messages at start and end of garbage collection. */);
7558 garbage_collection_messages = 0;
7560 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
7561 doc: /* Hook run after garbage collection has finished. */);
7562 Vpost_gc_hook = Qnil;
7563 DEFSYM (Qpost_gc_hook, "post-gc-hook");
7565 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
7566 doc: /* Precomputed `signal' argument for memory-full error. */);
7567 /* We build this in advance because if we wait until we need it, we might
7568 not be able to allocate the memory to hold it. */
7569 Vmemory_signal_data
7570 = listn (CONSTYPE_PURE, 2, Qerror,
7571 build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
7573 DEFVAR_LISP ("memory-full", Vmemory_full,
7574 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
7575 Vmemory_full = Qnil;
7577 DEFSYM (Qconses, "conses");
7578 DEFSYM (Qsymbols, "symbols");
7579 DEFSYM (Qmiscs, "miscs");
7580 DEFSYM (Qstrings, "strings");
7581 DEFSYM (Qvectors, "vectors");
7582 DEFSYM (Qfloats, "floats");
7583 DEFSYM (Qintervals, "intervals");
7584 DEFSYM (Qbuffers, "buffers");
7585 DEFSYM (Qstring_bytes, "string-bytes");
7586 DEFSYM (Qvector_slots, "vector-slots");
7587 DEFSYM (Qheap, "heap");
7588 DEFSYM (QAutomatic_GC, "Automatic GC");
7590 DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
7591 DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
7593 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
7594 doc: /* Accumulated time elapsed in garbage collections.
7595 The time is in seconds as a floating point value. */);
7596 DEFVAR_INT ("gcs-done", gcs_done,
7597 doc: /* Accumulated number of garbage collections done. */);
7599 defsubr (&Scons);
7600 defsubr (&Slist);
7601 defsubr (&Svector);
7602 defsubr (&Srecord);
7603 defsubr (&Sbool_vector);
7604 defsubr (&Smake_byte_code);
7605 defsubr (&Smake_list);
7606 defsubr (&Smake_vector);
7607 defsubr (&Smake_record);
7608 defsubr (&Smake_string);
7609 defsubr (&Smake_bool_vector);
7610 defsubr (&Smake_symbol);
7611 defsubr (&Smake_marker);
7612 defsubr (&Smake_finalizer);
7613 defsubr (&Spurecopy);
7614 defsubr (&Sgarbage_collect);
7615 defsubr (&Smemory_limit);
7616 defsubr (&Smemory_info);
7617 defsubr (&Smemory_use_counts);
7618 defsubr (&Ssuspicious_object);
7621 /* When compiled with GCC, GDB might say "No enum type named
7622 pvec_type" if we don't have at least one symbol with that type, and
7623 then xbacktrace could fail. Similarly for the other enums and
7624 their values. Some non-GCC compilers don't like these constructs. */
7625 #ifdef __GNUC__
7626 union
7628 enum CHARTAB_SIZE_BITS CHARTAB_SIZE_BITS;
7629 enum char_table_specials char_table_specials;
7630 enum char_bits char_bits;
7631 enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE;
7632 enum DEFAULT_HASH_SIZE DEFAULT_HASH_SIZE;
7633 enum Lisp_Bits Lisp_Bits;
7634 enum Lisp_Compiled Lisp_Compiled;
7635 enum maxargs maxargs;
7636 enum MAX_ALLOCA MAX_ALLOCA;
7637 enum More_Lisp_Bits More_Lisp_Bits;
7638 enum pvec_type pvec_type;
7639 } const EXTERNALLY_VISIBLE gdb_make_enums_visible = {0};
7640 #endif /* __GNUC__ */