* lisp/emacs-lisp/cl-macs.el (cl-defstruct): Fix debug spec (Bug#24430).
[emacs.git] / src / alloc.c
blob1092a34801ae527bf68e1d85b52dd4a09ab53b0b
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2016 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 <http://www.gnu.org/licenses/>. */
21 #include <config.h>
23 #include <errno.h>
24 #include <stdio.h>
25 #include <limits.h> /* For CHAR_BIT. */
26 #include <signal.h> /* For SIGABRT, SIGDANGER. */
28 #ifdef HAVE_PTHREAD
29 #include <pthread.h>
30 #endif
32 #include "lisp.h"
33 #include "dispextern.h"
34 #include "intervals.h"
35 #include "puresize.h"
36 #include "sheap.h"
37 #include "systime.h"
38 #include "character.h"
39 #include "buffer.h"
40 #include "window.h"
41 #include "keyboard.h"
42 #include "frame.h"
43 #include "blockinput.h"
44 #include "termhooks.h" /* For struct terminal. */
45 #ifdef HAVE_WINDOW_SYSTEM
46 #include TERM_HEADER
47 #endif /* HAVE_WINDOW_SYSTEM */
49 #include <flexmember.h>
50 #include <verify.h>
51 #include <execinfo.h> /* For backtrace. */
53 #ifdef HAVE_LINUX_SYSINFO
54 #include <sys/sysinfo.h>
55 #endif
57 #ifdef MSDOS
58 #include "dosfns.h" /* For dos_memory_info. */
59 #endif
61 #ifdef HAVE_MALLOC_H
62 # include <malloc.h>
63 #endif
65 #if (defined ENABLE_CHECKING \
66 && defined HAVE_VALGRIND_VALGRIND_H \
67 && !defined USE_VALGRIND)
68 # define USE_VALGRIND 1
69 #endif
71 #if USE_VALGRIND
72 #include <valgrind/valgrind.h>
73 #include <valgrind/memcheck.h>
74 static bool valgrind_p;
75 #endif
77 /* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects. */
79 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
80 memory. Can do this only if using gmalloc.c and if not checking
81 marked objects. */
83 #if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
84 || defined HYBRID_MALLOC || defined GC_CHECK_MARKED_OBJECTS)
85 #undef GC_MALLOC_CHECK
86 #endif
88 #include <unistd.h>
89 #include <fcntl.h>
91 #ifdef USE_GTK
92 # include "gtkutil.h"
93 #endif
94 #ifdef WINDOWSNT
95 #include "w32.h"
96 #include "w32heap.h" /* for sbrk */
97 #endif
99 #if defined DOUG_LEA_MALLOC || defined GNU_LINUX
100 /* The address where the heap starts. */
101 void *
102 my_heap_start (void)
104 static void *start;
105 if (! start)
106 start = sbrk (0);
107 return start;
109 #endif
111 #ifdef DOUG_LEA_MALLOC
113 /* Specify maximum number of areas to mmap. It would be nice to use a
114 value that explicitly means "no limit". */
116 #define MMAP_MAX_AREAS 100000000
118 /* A pointer to the memory allocated that copies that static data
119 inside glibc's malloc. */
120 static void *malloc_state_ptr;
122 /* Restore the dumped malloc state. Because malloc can be invoked
123 even before main (e.g. by the dynamic linker), the dumped malloc
124 state must be restored as early as possible using this special hook. */
125 static void
126 malloc_initialize_hook (void)
128 static bool malloc_using_checking;
130 if (! initialized)
132 my_heap_start ();
133 malloc_using_checking = getenv ("MALLOC_CHECK_") != NULL;
135 else
137 if (!malloc_using_checking)
139 /* Work around a bug in glibc's malloc. MALLOC_CHECK_ must be
140 ignored if the heap to be restored was constructed without
141 malloc checking. Can't use unsetenv, since that calls malloc. */
142 char **p = environ;
143 if (p)
144 for (; *p; p++)
145 if (strncmp (*p, "MALLOC_CHECK_=", 14) == 0)
148 *p = p[1];
149 while (*++p);
151 break;
155 if (malloc_set_state (malloc_state_ptr) != 0)
156 emacs_abort ();
157 # ifndef XMALLOC_OVERRUN_CHECK
158 alloc_unexec_post ();
159 # endif
163 /* Declare the malloc initialization hook, which runs before 'main' starts.
164 EXTERNALLY_VISIBLE works around Bug#22522. */
165 # ifndef __MALLOC_HOOK_VOLATILE
166 # define __MALLOC_HOOK_VOLATILE
167 # endif
168 voidfuncptr __MALLOC_HOOK_VOLATILE __malloc_initialize_hook EXTERNALLY_VISIBLE
169 = malloc_initialize_hook;
171 #endif
173 /* Allocator-related actions to do just before and after unexec. */
175 void
176 alloc_unexec_pre (void)
178 #ifdef DOUG_LEA_MALLOC
179 malloc_state_ptr = malloc_get_state ();
180 if (!malloc_state_ptr)
181 fatal ("malloc_get_state: %s", strerror (errno));
182 #endif
183 #ifdef HYBRID_MALLOC
184 bss_sbrk_did_unexec = true;
185 #endif
188 void
189 alloc_unexec_post (void)
191 #ifdef DOUG_LEA_MALLOC
192 free (malloc_state_ptr);
193 #endif
194 #ifdef HYBRID_MALLOC
195 bss_sbrk_did_unexec = false;
196 #endif
199 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
200 to a struct Lisp_String. */
202 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
203 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
204 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
206 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
207 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
208 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
210 /* Default value of gc_cons_threshold (see below). */
212 #define GC_DEFAULT_THRESHOLD (100000 * word_size)
214 /* Global variables. */
215 struct emacs_globals globals;
217 /* Number of bytes of consing done since the last gc. */
219 EMACS_INT consing_since_gc;
221 /* Similar minimum, computed from Vgc_cons_percentage. */
223 EMACS_INT gc_relative_threshold;
225 /* Minimum number of bytes of consing since GC before next GC,
226 when memory is full. */
228 EMACS_INT memory_full_cons_threshold;
230 /* True during GC. */
232 bool gc_in_progress;
234 /* Number of live and free conses etc. */
236 static EMACS_INT total_conses, total_markers, total_symbols, total_buffers;
237 static EMACS_INT total_free_conses, total_free_markers, total_free_symbols;
238 static EMACS_INT total_free_floats, total_floats;
240 /* Points to memory space allocated as "spare", to be freed if we run
241 out of memory. We keep one large block, four cons-blocks, and
242 two string blocks. */
244 static char *spare_memory[7];
246 /* Amount of spare memory to keep in large reserve block, or to see
247 whether this much is available when malloc fails on a larger request. */
249 #define SPARE_MEMORY (1 << 14)
251 /* Initialize it to a nonzero value to force it into data space
252 (rather than bss space). That way unexec will remap it into text
253 space (pure), on some systems. We have not implemented the
254 remapping on more recent systems because this is less important
255 nowadays than in the days of small memories and timesharing. */
257 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
258 #define PUREBEG (char *) pure
260 /* Pointer to the pure area, and its size. */
262 static char *purebeg;
263 static ptrdiff_t pure_size;
265 /* Number of bytes of pure storage used before pure storage overflowed.
266 If this is non-zero, this implies that an overflow occurred. */
268 static ptrdiff_t pure_bytes_used_before_overflow;
270 /* Index in pure at which next pure Lisp object will be allocated.. */
272 static ptrdiff_t pure_bytes_used_lisp;
274 /* Number of bytes allocated for non-Lisp objects in pure storage. */
276 static ptrdiff_t pure_bytes_used_non_lisp;
278 /* If nonzero, this is a warning delivered by malloc and not yet
279 displayed. */
281 const char *pending_malloc_warning;
283 #if 0 /* Normally, pointer sanity only on request... */
284 #ifdef ENABLE_CHECKING
285 #define SUSPICIOUS_OBJECT_CHECKING 1
286 #endif
287 #endif
289 /* ... but unconditionally use SUSPICIOUS_OBJECT_CHECKING while the GC
290 bug is unresolved. */
291 #define SUSPICIOUS_OBJECT_CHECKING 1
293 #ifdef SUSPICIOUS_OBJECT_CHECKING
294 struct suspicious_free_record
296 void *suspicious_object;
297 void *backtrace[128];
299 static void *suspicious_objects[32];
300 static int suspicious_object_index;
301 struct suspicious_free_record suspicious_free_history[64] EXTERNALLY_VISIBLE;
302 static int suspicious_free_history_index;
303 /* Find the first currently-monitored suspicious pointer in range
304 [begin,end) or NULL if no such pointer exists. */
305 static void *find_suspicious_object_in_range (void *begin, void *end);
306 static void detect_suspicious_free (void *ptr);
307 #else
308 # define find_suspicious_object_in_range(begin, end) NULL
309 # define detect_suspicious_free(ptr) (void)
310 #endif
312 /* Maximum amount of C stack to save when a GC happens. */
314 #ifndef MAX_SAVE_STACK
315 #define MAX_SAVE_STACK 16000
316 #endif
318 /* Buffer in which we save a copy of the C stack at each GC. */
320 #if MAX_SAVE_STACK > 0
321 static char *stack_copy;
322 static ptrdiff_t stack_copy_size;
324 /* Copy to DEST a block of memory from SRC of size SIZE bytes,
325 avoiding any address sanitization. */
327 static void * ATTRIBUTE_NO_SANITIZE_ADDRESS
328 no_sanitize_memcpy (void *dest, void const *src, size_t size)
330 if (! ADDRESS_SANITIZER)
331 return memcpy (dest, src, size);
332 else
334 size_t i;
335 char *d = dest;
336 char const *s = src;
337 for (i = 0; i < size; i++)
338 d[i] = s[i];
339 return dest;
343 #endif /* MAX_SAVE_STACK > 0 */
345 static void mark_terminals (void);
346 static void gc_sweep (void);
347 static Lisp_Object make_pure_vector (ptrdiff_t);
348 static void mark_buffer (struct buffer *);
350 #if !defined REL_ALLOC || defined SYSTEM_MALLOC || defined HYBRID_MALLOC
351 static void refill_memory_reserve (void);
352 #endif
353 static void compact_small_strings (void);
354 static void free_large_strings (void);
355 extern Lisp_Object which_symbols (Lisp_Object, EMACS_INT) EXTERNALLY_VISIBLE;
357 /* When scanning the C stack for live Lisp objects, Emacs keeps track of
358 what memory allocated via lisp_malloc and lisp_align_malloc is intended
359 for what purpose. This enumeration specifies the type of memory. */
361 enum mem_type
363 MEM_TYPE_NON_LISP,
364 MEM_TYPE_BUFFER,
365 MEM_TYPE_CONS,
366 MEM_TYPE_STRING,
367 MEM_TYPE_MISC,
368 MEM_TYPE_SYMBOL,
369 MEM_TYPE_FLOAT,
370 /* Since all non-bool pseudovectors are small enough to be
371 allocated from vector blocks, this memory type denotes
372 large regular vectors and large bool pseudovectors. */
373 MEM_TYPE_VECTORLIKE,
374 /* Special type to denote vector blocks. */
375 MEM_TYPE_VECTOR_BLOCK,
376 /* Special type to denote reserved memory. */
377 MEM_TYPE_SPARE
380 /* A unique object in pure space used to make some Lisp objects
381 on free lists recognizable in O(1). */
383 static Lisp_Object Vdead;
384 #define DEADP(x) EQ (x, Vdead)
386 #ifdef GC_MALLOC_CHECK
388 enum mem_type allocated_mem_type;
390 #endif /* GC_MALLOC_CHECK */
392 /* A node in the red-black tree describing allocated memory containing
393 Lisp data. Each such block is recorded with its start and end
394 address when it is allocated, and removed from the tree when it
395 is freed.
397 A red-black tree is a balanced binary tree with the following
398 properties:
400 1. Every node is either red or black.
401 2. Every leaf is black.
402 3. If a node is red, then both of its children are black.
403 4. Every simple path from a node to a descendant leaf contains
404 the same number of black nodes.
405 5. The root is always black.
407 When nodes are inserted into the tree, or deleted from the tree,
408 the tree is "fixed" so that these properties are always true.
410 A red-black tree with N internal nodes has height at most 2
411 log(N+1). Searches, insertions and deletions are done in O(log N).
412 Please see a text book about data structures for a detailed
413 description of red-black trees. Any book worth its salt should
414 describe them. */
416 struct mem_node
418 /* Children of this node. These pointers are never NULL. When there
419 is no child, the value is MEM_NIL, which points to a dummy node. */
420 struct mem_node *left, *right;
422 /* The parent of this node. In the root node, this is NULL. */
423 struct mem_node *parent;
425 /* Start and end of allocated region. */
426 void *start, *end;
428 /* Node color. */
429 enum {MEM_BLACK, MEM_RED} color;
431 /* Memory type. */
432 enum mem_type type;
435 /* Base address of stack. Set in main. */
437 Lisp_Object *stack_base;
439 /* Root of the tree describing allocated Lisp memory. */
441 static struct mem_node *mem_root;
443 /* Lowest and highest known address in the heap. */
445 static void *min_heap_address, *max_heap_address;
447 /* Sentinel node of the tree. */
449 static struct mem_node mem_z;
450 #define MEM_NIL &mem_z
452 static struct mem_node *mem_insert (void *, void *, enum mem_type);
453 static void mem_insert_fixup (struct mem_node *);
454 static void mem_rotate_left (struct mem_node *);
455 static void mem_rotate_right (struct mem_node *);
456 static void mem_delete (struct mem_node *);
457 static void mem_delete_fixup (struct mem_node *);
458 static struct mem_node *mem_find (void *);
460 #ifndef DEADP
461 # define DEADP(x) 0
462 #endif
464 /* Addresses of staticpro'd variables. Initialize it to a nonzero
465 value; otherwise some compilers put it into BSS. */
467 enum { NSTATICS = 2048 };
468 static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
470 /* Index of next unused slot in staticvec. */
472 static int staticidx;
474 static void *pure_alloc (size_t, int);
476 /* True if N is a power of 2. N should be positive. */
478 #define POWER_OF_2(n) (((n) & ((n) - 1)) == 0)
480 /* Return X rounded to the next multiple of Y. Y should be positive,
481 and Y - 1 + X should not overflow. Arguments should not have side
482 effects, as they are evaluated more than once. Tune for Y being a
483 power of 2. */
485 #define ROUNDUP(x, y) (POWER_OF_2 (y) \
486 ? ((y) - 1 + (x)) & ~ ((y) - 1) \
487 : ((y) - 1 + (x)) - ((y) - 1 + (x)) % (y))
489 /* Return PTR rounded up to the next multiple of ALIGNMENT. */
491 static void *
492 pointer_align (void *ptr, int alignment)
494 return (void *) ROUNDUP ((uintptr_t) ptr, alignment);
497 /* Extract the pointer hidden within A, if A is not a symbol.
498 If A is a symbol, extract the hidden pointer's offset from lispsym,
499 converted to void *. */
501 #define macro_XPNTR_OR_SYMBOL_OFFSET(a) \
502 ((void *) (intptr_t) (USE_LSB_TAG ? XLI (a) - XTYPE (a) : XLI (a) & VALMASK))
504 /* Extract the pointer hidden within A. */
506 #define macro_XPNTR(a) \
507 ((void *) ((intptr_t) XPNTR_OR_SYMBOL_OFFSET (a) \
508 + (SYMBOLP (a) ? (char *) lispsym : NULL)))
510 /* For pointer access, define XPNTR and XPNTR_OR_SYMBOL_OFFSET as
511 functions, as functions are cleaner and can be used in debuggers.
512 Also, define them as macros if being compiled with GCC without
513 optimization, for performance in that case. The macro_* names are
514 private to this section of code. */
516 static ATTRIBUTE_UNUSED void *
517 XPNTR_OR_SYMBOL_OFFSET (Lisp_Object a)
519 return macro_XPNTR_OR_SYMBOL_OFFSET (a);
521 static ATTRIBUTE_UNUSED void *
522 XPNTR (Lisp_Object a)
524 return macro_XPNTR (a);
527 #if DEFINE_KEY_OPS_AS_MACROS
528 # define XPNTR_OR_SYMBOL_OFFSET(a) macro_XPNTR_OR_SYMBOL_OFFSET (a)
529 # define XPNTR(a) macro_XPNTR (a)
530 #endif
532 static void
533 XFLOAT_INIT (Lisp_Object f, double n)
535 XFLOAT (f)->u.data = n;
538 #ifdef DOUG_LEA_MALLOC
539 static bool
540 pointers_fit_in_lispobj_p (void)
542 return (UINTPTR_MAX <= VAL_MAX) || USE_LSB_TAG;
545 static bool
546 mmap_lisp_allowed_p (void)
548 /* If we can't store all memory addresses in our lisp objects, it's
549 risky to let the heap use mmap and give us addresses from all
550 over our address space. We also can't use mmap for lisp objects
551 if we might dump: unexec doesn't preserve the contents of mmapped
552 regions. */
553 return pointers_fit_in_lispobj_p () && !might_dump;
555 #endif
557 /* Head of a circularly-linked list of extant finalizers. */
558 static struct Lisp_Finalizer finalizers;
560 /* Head of a circularly-linked list of finalizers that must be invoked
561 because we deemed them unreachable. This list must be global, and
562 not a local inside garbage_collect_1, in case we GC again while
563 running finalizers. */
564 static struct Lisp_Finalizer doomed_finalizers;
567 /************************************************************************
568 Malloc
569 ************************************************************************/
571 #if defined SIGDANGER || (!defined SYSTEM_MALLOC && !defined HYBRID_MALLOC)
573 /* Function malloc calls this if it finds we are near exhausting storage. */
575 void
576 malloc_warning (const char *str)
578 pending_malloc_warning = str;
581 #endif
583 /* Display an already-pending malloc warning. */
585 void
586 display_malloc_warning (void)
588 call3 (intern ("display-warning"),
589 intern ("alloc"),
590 build_string (pending_malloc_warning),
591 intern ("emergency"));
592 pending_malloc_warning = 0;
595 /* Called if we can't allocate relocatable space for a buffer. */
597 void
598 buffer_memory_full (ptrdiff_t nbytes)
600 /* If buffers use the relocating allocator, no need to free
601 spare_memory, because we may have plenty of malloc space left
602 that we could get, and if we don't, the malloc that fails will
603 itself cause spare_memory to be freed. If buffers don't use the
604 relocating allocator, treat this like any other failing
605 malloc. */
607 #ifndef REL_ALLOC
608 memory_full (nbytes);
609 #else
610 /* This used to call error, but if we've run out of memory, we could
611 get infinite recursion trying to build the string. */
612 xsignal (Qnil, Vmemory_signal_data);
613 #endif
616 /* A common multiple of the positive integers A and B. Ideally this
617 would be the least common multiple, but there's no way to do that
618 as a constant expression in C, so do the best that we can easily do. */
619 #define COMMON_MULTIPLE(a, b) \
620 ((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
622 #ifndef XMALLOC_OVERRUN_CHECK
623 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
624 #else
626 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
627 around each block.
629 The header consists of XMALLOC_OVERRUN_CHECK_SIZE fixed bytes
630 followed by XMALLOC_OVERRUN_SIZE_SIZE bytes containing the original
631 block size in little-endian order. The trailer consists of
632 XMALLOC_OVERRUN_CHECK_SIZE fixed bytes.
634 The header is used to detect whether this block has been allocated
635 through these functions, as some low-level libc functions may
636 bypass the malloc hooks. */
638 #define XMALLOC_OVERRUN_CHECK_SIZE 16
639 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
640 (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)
642 #define XMALLOC_BASE_ALIGNMENT alignof (max_align_t)
644 #define XMALLOC_HEADER_ALIGNMENT \
645 COMMON_MULTIPLE (GCALIGNMENT, XMALLOC_BASE_ALIGNMENT)
647 /* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
648 hold a size_t value and (2) the header size is a multiple of the
649 alignment that Emacs needs for C types and for USE_LSB_TAG. */
650 #define XMALLOC_OVERRUN_SIZE_SIZE \
651 (((XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t) \
652 + XMALLOC_HEADER_ALIGNMENT - 1) \
653 / XMALLOC_HEADER_ALIGNMENT * XMALLOC_HEADER_ALIGNMENT) \
654 - XMALLOC_OVERRUN_CHECK_SIZE)
656 static char const xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE] =
657 { '\x9a', '\x9b', '\xae', '\xaf',
658 '\xbf', '\xbe', '\xce', '\xcf',
659 '\xea', '\xeb', '\xec', '\xed',
660 '\xdf', '\xde', '\x9c', '\x9d' };
662 static char const xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
663 { '\xaa', '\xab', '\xac', '\xad',
664 '\xba', '\xbb', '\xbc', '\xbd',
665 '\xca', '\xcb', '\xcc', '\xcd',
666 '\xda', '\xdb', '\xdc', '\xdd' };
668 /* Insert and extract the block size in the header. */
670 static void
671 xmalloc_put_size (unsigned char *ptr, size_t size)
673 int i;
674 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
676 *--ptr = size & ((1 << CHAR_BIT) - 1);
677 size >>= CHAR_BIT;
681 static size_t
682 xmalloc_get_size (unsigned char *ptr)
684 size_t size = 0;
685 int i;
686 ptr -= XMALLOC_OVERRUN_SIZE_SIZE;
687 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
689 size <<= CHAR_BIT;
690 size += *ptr++;
692 return size;
696 /* Like malloc, but wraps allocated block with header and trailer. */
698 static void *
699 overrun_check_malloc (size_t size)
701 register unsigned char *val;
702 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
703 emacs_abort ();
705 val = malloc (size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
706 if (val)
708 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
709 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
710 xmalloc_put_size (val, size);
711 memcpy (val + size, xmalloc_overrun_check_trailer,
712 XMALLOC_OVERRUN_CHECK_SIZE);
714 return val;
718 /* Like realloc, but checks old block for overrun, and wraps new block
719 with header and trailer. */
721 static void *
722 overrun_check_realloc (void *block, size_t size)
724 register unsigned char *val = (unsigned char *) block;
725 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
726 emacs_abort ();
728 if (val
729 && memcmp (xmalloc_overrun_check_header,
730 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
731 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
733 size_t osize = xmalloc_get_size (val);
734 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
735 XMALLOC_OVERRUN_CHECK_SIZE))
736 emacs_abort ();
737 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
738 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
739 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
742 val = realloc (val, size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
744 if (val)
746 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
747 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
748 xmalloc_put_size (val, size);
749 memcpy (val + size, xmalloc_overrun_check_trailer,
750 XMALLOC_OVERRUN_CHECK_SIZE);
752 return val;
755 /* Like free, but checks block for overrun. */
757 static void
758 overrun_check_free (void *block)
760 unsigned char *val = (unsigned char *) block;
762 if (val
763 && memcmp (xmalloc_overrun_check_header,
764 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
765 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
767 size_t osize = xmalloc_get_size (val);
768 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
769 XMALLOC_OVERRUN_CHECK_SIZE))
770 emacs_abort ();
771 #ifdef XMALLOC_CLEAR_FREE_MEMORY
772 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
773 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_OVERHEAD);
774 #else
775 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
776 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
777 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
778 #endif
781 free (val);
784 #undef malloc
785 #undef realloc
786 #undef free
787 #define malloc overrun_check_malloc
788 #define realloc overrun_check_realloc
789 #define free overrun_check_free
790 #endif
792 /* If compiled with XMALLOC_BLOCK_INPUT_CHECK, define a symbol
793 BLOCK_INPUT_IN_MEMORY_ALLOCATORS that is visible to the debugger.
794 If that variable is set, block input while in one of Emacs's memory
795 allocation functions. There should be no need for this debugging
796 option, since signal handlers do not allocate memory, but Emacs
797 formerly allocated memory in signal handlers and this compile-time
798 option remains as a way to help debug the issue should it rear its
799 ugly head again. */
800 #ifdef XMALLOC_BLOCK_INPUT_CHECK
801 bool block_input_in_memory_allocators EXTERNALLY_VISIBLE;
802 static void
803 malloc_block_input (void)
805 if (block_input_in_memory_allocators)
806 block_input ();
808 static void
809 malloc_unblock_input (void)
811 if (block_input_in_memory_allocators)
812 unblock_input ();
814 # define MALLOC_BLOCK_INPUT malloc_block_input ()
815 # define MALLOC_UNBLOCK_INPUT malloc_unblock_input ()
816 #else
817 # define MALLOC_BLOCK_INPUT ((void) 0)
818 # define MALLOC_UNBLOCK_INPUT ((void) 0)
819 #endif
821 #define MALLOC_PROBE(size) \
822 do { \
823 if (profiler_memory_running) \
824 malloc_probe (size); \
825 } while (0)
827 static void *lmalloc (size_t) ATTRIBUTE_MALLOC_SIZE ((1));
828 static void *lrealloc (void *, size_t);
830 /* Like malloc but check for no memory and block interrupt input. */
832 void *
833 xmalloc (size_t size)
835 void *val;
837 MALLOC_BLOCK_INPUT;
838 val = lmalloc (size);
839 MALLOC_UNBLOCK_INPUT;
841 if (!val && size)
842 memory_full (size);
843 MALLOC_PROBE (size);
844 return val;
847 /* Like the above, but zeroes out the memory just allocated. */
849 void *
850 xzalloc (size_t size)
852 void *val;
854 MALLOC_BLOCK_INPUT;
855 val = lmalloc (size);
856 MALLOC_UNBLOCK_INPUT;
858 if (!val && size)
859 memory_full (size);
860 memset (val, 0, size);
861 MALLOC_PROBE (size);
862 return val;
865 /* Like realloc but check for no memory and block interrupt input.. */
867 void *
868 xrealloc (void *block, size_t size)
870 void *val;
872 MALLOC_BLOCK_INPUT;
873 /* We must call malloc explicitly when BLOCK is 0, since some
874 reallocs don't do this. */
875 if (! block)
876 val = lmalloc (size);
877 else
878 val = lrealloc (block, size);
879 MALLOC_UNBLOCK_INPUT;
881 if (!val && size)
882 memory_full (size);
883 MALLOC_PROBE (size);
884 return val;
888 /* Like free but block interrupt input. */
890 void
891 xfree (void *block)
893 if (!block)
894 return;
895 MALLOC_BLOCK_INPUT;
896 free (block);
897 MALLOC_UNBLOCK_INPUT;
898 /* We don't call refill_memory_reserve here
899 because in practice the call in r_alloc_free seems to suffice. */
903 /* Other parts of Emacs pass large int values to allocator functions
904 expecting ptrdiff_t. This is portable in practice, but check it to
905 be safe. */
906 verify (INT_MAX <= PTRDIFF_MAX);
909 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
910 Signal an error on memory exhaustion, and block interrupt input. */
912 void *
913 xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
915 eassert (0 <= nitems && 0 < item_size);
916 ptrdiff_t nbytes;
917 if (INT_MULTIPLY_WRAPV (nitems, item_size, &nbytes) || SIZE_MAX < nbytes)
918 memory_full (SIZE_MAX);
919 return xmalloc (nbytes);
923 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
924 Signal an error on memory exhaustion, and block interrupt input. */
926 void *
927 xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
929 eassert (0 <= nitems && 0 < item_size);
930 ptrdiff_t nbytes;
931 if (INT_MULTIPLY_WRAPV (nitems, item_size, &nbytes) || SIZE_MAX < nbytes)
932 memory_full (SIZE_MAX);
933 return xrealloc (pa, nbytes);
937 /* Grow PA, which points to an array of *NITEMS items, and return the
938 location of the reallocated array, updating *NITEMS to reflect its
939 new size. The new array will contain at least NITEMS_INCR_MIN more
940 items, but will not contain more than NITEMS_MAX items total.
941 ITEM_SIZE is the size of each item, in bytes.
943 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
944 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
945 infinity.
947 If PA is null, then allocate a new array instead of reallocating
948 the old one.
950 Block interrupt input as needed. If memory exhaustion occurs, set
951 *NITEMS to zero if PA is null, and signal an error (i.e., do not
952 return).
954 Thus, to grow an array A without saving its old contents, do
955 { xfree (A); A = NULL; A = xpalloc (NULL, &AITEMS, ...); }.
956 The A = NULL avoids a dangling pointer if xpalloc exhausts memory
957 and signals an error, and later this code is reexecuted and
958 attempts to free A. */
960 void *
961 xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
962 ptrdiff_t nitems_max, ptrdiff_t item_size)
964 ptrdiff_t n0 = *nitems;
965 eassume (0 < item_size && 0 < nitems_incr_min && 0 <= n0 && -1 <= nitems_max);
967 /* The approximate size to use for initial small allocation
968 requests. This is the largest "small" request for the GNU C
969 library malloc. */
970 enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
972 /* If the array is tiny, grow it to about (but no greater than)
973 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%.
974 Adjust the growth according to three constraints: NITEMS_INCR_MIN,
975 NITEMS_MAX, and what the C language can represent safely. */
977 ptrdiff_t n, nbytes;
978 if (INT_ADD_WRAPV (n0, n0 >> 1, &n))
979 n = PTRDIFF_MAX;
980 if (0 <= nitems_max && nitems_max < n)
981 n = nitems_max;
983 ptrdiff_t adjusted_nbytes
984 = ((INT_MULTIPLY_WRAPV (n, item_size, &nbytes) || SIZE_MAX < nbytes)
985 ? min (PTRDIFF_MAX, SIZE_MAX)
986 : nbytes < DEFAULT_MXFAST ? DEFAULT_MXFAST : 0);
987 if (adjusted_nbytes)
989 n = adjusted_nbytes / item_size;
990 nbytes = adjusted_nbytes - adjusted_nbytes % item_size;
993 if (! pa)
994 *nitems = 0;
995 if (n - n0 < nitems_incr_min
996 && (INT_ADD_WRAPV (n0, nitems_incr_min, &n)
997 || (0 <= nitems_max && nitems_max < n)
998 || INT_MULTIPLY_WRAPV (n, item_size, &nbytes)))
999 memory_full (SIZE_MAX);
1000 pa = xrealloc (pa, nbytes);
1001 *nitems = n;
1002 return pa;
1006 /* Like strdup, but uses xmalloc. */
1008 char *
1009 xstrdup (const char *s)
1011 ptrdiff_t size;
1012 eassert (s);
1013 size = strlen (s) + 1;
1014 return memcpy (xmalloc (size), s, size);
1017 /* Like above, but duplicates Lisp string to C string. */
1019 char *
1020 xlispstrdup (Lisp_Object string)
1022 ptrdiff_t size = SBYTES (string) + 1;
1023 return memcpy (xmalloc (size), SSDATA (string), size);
1026 /* Assign to *PTR a copy of STRING, freeing any storage *PTR formerly
1027 pointed to. If STRING is null, assign it without copying anything.
1028 Allocate before freeing, to avoid a dangling pointer if allocation
1029 fails. */
1031 void
1032 dupstring (char **ptr, char const *string)
1034 char *old = *ptr;
1035 *ptr = string ? xstrdup (string) : 0;
1036 xfree (old);
1040 /* Like putenv, but (1) use the equivalent of xmalloc and (2) the
1041 argument is a const pointer. */
1043 void
1044 xputenv (char const *string)
1046 if (putenv ((char *) string) != 0)
1047 memory_full (0);
1050 /* Return a newly allocated memory block of SIZE bytes, remembering
1051 to free it when unwinding. */
1052 void *
1053 record_xmalloc (size_t size)
1055 void *p = xmalloc (size);
1056 record_unwind_protect_ptr (xfree, p);
1057 return p;
1061 /* Like malloc but used for allocating Lisp data. NBYTES is the
1062 number of bytes to allocate, TYPE describes the intended use of the
1063 allocated memory block (for strings, for conses, ...). */
1065 #if ! USE_LSB_TAG
1066 void *lisp_malloc_loser EXTERNALLY_VISIBLE;
1067 #endif
1069 static void *
1070 lisp_malloc (size_t nbytes, enum mem_type type)
1072 register void *val;
1074 MALLOC_BLOCK_INPUT;
1076 #ifdef GC_MALLOC_CHECK
1077 allocated_mem_type = type;
1078 #endif
1080 val = lmalloc (nbytes);
1082 #if ! USE_LSB_TAG
1083 /* If the memory just allocated cannot be addressed thru a Lisp
1084 object's pointer, and it needs to be,
1085 that's equivalent to running out of memory. */
1086 if (val && type != MEM_TYPE_NON_LISP)
1088 Lisp_Object tem;
1089 XSETCONS (tem, (char *) val + nbytes - 1);
1090 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
1092 lisp_malloc_loser = val;
1093 free (val);
1094 val = 0;
1097 #endif
1099 #ifndef GC_MALLOC_CHECK
1100 if (val && type != MEM_TYPE_NON_LISP)
1101 mem_insert (val, (char *) val + nbytes, type);
1102 #endif
1104 MALLOC_UNBLOCK_INPUT;
1105 if (!val && nbytes)
1106 memory_full (nbytes);
1107 MALLOC_PROBE (nbytes);
1108 return val;
1111 /* Free BLOCK. This must be called to free memory allocated with a
1112 call to lisp_malloc. */
1114 static void
1115 lisp_free (void *block)
1117 MALLOC_BLOCK_INPUT;
1118 free (block);
1119 #ifndef GC_MALLOC_CHECK
1120 mem_delete (mem_find (block));
1121 #endif
1122 MALLOC_UNBLOCK_INPUT;
1125 /***** Allocation of aligned blocks of memory to store Lisp data. *****/
1127 /* The entry point is lisp_align_malloc which returns blocks of at most
1128 BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
1130 /* Byte alignment of storage blocks. */
1131 #define BLOCK_ALIGN (1 << 10)
1132 verify (POWER_OF_2 (BLOCK_ALIGN));
1134 /* Use aligned_alloc if it or a simple substitute is available.
1135 Address sanitization breaks aligned allocation, as of gcc 4.8.2 and
1136 clang 3.3 anyway. Aligned allocation is incompatible with
1137 unexmacosx.c, so don't use it on Darwin. */
1139 #if ! ADDRESS_SANITIZER && !defined DARWIN_OS
1140 # if (defined HAVE_ALIGNED_ALLOC \
1141 || (defined HYBRID_MALLOC \
1142 ? defined HAVE_POSIX_MEMALIGN \
1143 : !defined SYSTEM_MALLOC && !defined DOUG_LEA_MALLOC))
1144 # define USE_ALIGNED_ALLOC 1
1145 # elif !defined HYBRID_MALLOC && defined HAVE_POSIX_MEMALIGN
1146 # define USE_ALIGNED_ALLOC 1
1147 # define aligned_alloc my_aligned_alloc /* Avoid collision with lisp.h. */
1148 static void *
1149 aligned_alloc (size_t alignment, size_t size)
1151 /* POSIX says the alignment must be a power-of-2 multiple of sizeof (void *).
1152 Verify this for all arguments this function is given. */
1153 verify (BLOCK_ALIGN % sizeof (void *) == 0
1154 && POWER_OF_2 (BLOCK_ALIGN / sizeof (void *)));
1155 verify (GCALIGNMENT % sizeof (void *) == 0
1156 && POWER_OF_2 (GCALIGNMENT / sizeof (void *)));
1157 eassert (alignment == BLOCK_ALIGN || alignment == GCALIGNMENT);
1159 void *p;
1160 return posix_memalign (&p, alignment, size) == 0 ? p : 0;
1162 # endif
1163 #endif
1165 /* Padding to leave at the end of a malloc'd block. This is to give
1166 malloc a chance to minimize the amount of memory wasted to alignment.
1167 It should be tuned to the particular malloc library used.
1168 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
1169 aligned_alloc on the other hand would ideally prefer a value of 4
1170 because otherwise, there's 1020 bytes wasted between each ablocks.
1171 In Emacs, testing shows that those 1020 can most of the time be
1172 efficiently used by malloc to place other objects, so a value of 0 can
1173 still preferable unless you have a lot of aligned blocks and virtually
1174 nothing else. */
1175 #define BLOCK_PADDING 0
1176 #define BLOCK_BYTES \
1177 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
1179 /* Internal data structures and constants. */
1181 #define ABLOCKS_SIZE 16
1183 /* An aligned block of memory. */
1184 struct ablock
1186 union
1188 char payload[BLOCK_BYTES];
1189 struct ablock *next_free;
1190 } x;
1192 /* ABASE is the aligned base of the ablocks. It is overloaded to
1193 hold a virtual "busy" field that counts twice the number of used
1194 ablock values in the parent ablocks, plus one if the real base of
1195 the parent ablocks is ABASE (if the "busy" field is even, the
1196 word before the first ablock holds a pointer to the real base).
1197 The first ablock has a "busy" ABASE, and the others have an
1198 ordinary pointer ABASE. To tell the difference, the code assumes
1199 that pointers, when cast to uintptr_t, are at least 2 *
1200 ABLOCKS_SIZE + 1. */
1201 struct ablocks *abase;
1203 /* The padding of all but the last ablock is unused. The padding of
1204 the last ablock in an ablocks is not allocated. */
1205 #if BLOCK_PADDING
1206 char padding[BLOCK_PADDING];
1207 #endif
1210 /* A bunch of consecutive aligned blocks. */
1211 struct ablocks
1213 struct ablock blocks[ABLOCKS_SIZE];
1216 /* Size of the block requested from malloc or aligned_alloc. */
1217 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
1219 #define ABLOCK_ABASE(block) \
1220 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
1221 ? (struct ablocks *) (block) \
1222 : (block)->abase)
1224 /* Virtual `busy' field. */
1225 #define ABLOCKS_BUSY(a_base) ((a_base)->blocks[0].abase)
1227 /* Pointer to the (not necessarily aligned) malloc block. */
1228 #ifdef USE_ALIGNED_ALLOC
1229 #define ABLOCKS_BASE(abase) (abase)
1230 #else
1231 #define ABLOCKS_BASE(abase) \
1232 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void **) (abase))[-1])
1233 #endif
1235 /* The list of free ablock. */
1236 static struct ablock *free_ablock;
1238 /* Allocate an aligned block of nbytes.
1239 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
1240 smaller or equal to BLOCK_BYTES. */
1241 static void *
1242 lisp_align_malloc (size_t nbytes, enum mem_type type)
1244 void *base, *val;
1245 struct ablocks *abase;
1247 eassert (nbytes <= BLOCK_BYTES);
1249 MALLOC_BLOCK_INPUT;
1251 #ifdef GC_MALLOC_CHECK
1252 allocated_mem_type = type;
1253 #endif
1255 if (!free_ablock)
1257 int i;
1258 bool aligned;
1260 #ifdef DOUG_LEA_MALLOC
1261 if (!mmap_lisp_allowed_p ())
1262 mallopt (M_MMAP_MAX, 0);
1263 #endif
1265 #ifdef USE_ALIGNED_ALLOC
1266 verify (ABLOCKS_BYTES % BLOCK_ALIGN == 0);
1267 abase = base = aligned_alloc (BLOCK_ALIGN, ABLOCKS_BYTES);
1268 #else
1269 base = malloc (ABLOCKS_BYTES);
1270 abase = pointer_align (base, BLOCK_ALIGN);
1271 #endif
1273 if (base == 0)
1275 MALLOC_UNBLOCK_INPUT;
1276 memory_full (ABLOCKS_BYTES);
1279 aligned = (base == abase);
1280 if (!aligned)
1281 ((void **) abase)[-1] = base;
1283 #ifdef DOUG_LEA_MALLOC
1284 if (!mmap_lisp_allowed_p ())
1285 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1286 #endif
1288 #if ! USE_LSB_TAG
1289 /* If the memory just allocated cannot be addressed thru a Lisp
1290 object's pointer, and it needs to be, that's equivalent to
1291 running out of memory. */
1292 if (type != MEM_TYPE_NON_LISP)
1294 Lisp_Object tem;
1295 char *end = (char *) base + ABLOCKS_BYTES - 1;
1296 XSETCONS (tem, end);
1297 if ((char *) XCONS (tem) != end)
1299 lisp_malloc_loser = base;
1300 free (base);
1301 MALLOC_UNBLOCK_INPUT;
1302 memory_full (SIZE_MAX);
1305 #endif
1307 /* Initialize the blocks and put them on the free list.
1308 If `base' was not properly aligned, we can't use the last block. */
1309 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1311 abase->blocks[i].abase = abase;
1312 abase->blocks[i].x.next_free = free_ablock;
1313 free_ablock = &abase->blocks[i];
1315 intptr_t ialigned = aligned;
1316 ABLOCKS_BUSY (abase) = (struct ablocks *) ialigned;
1318 eassert ((uintptr_t) abase % BLOCK_ALIGN == 0);
1319 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1320 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1321 eassert (ABLOCKS_BASE (abase) == base);
1322 eassert ((intptr_t) ABLOCKS_BUSY (abase) == aligned);
1325 abase = ABLOCK_ABASE (free_ablock);
1326 ABLOCKS_BUSY (abase)
1327 = (struct ablocks *) (2 + (intptr_t) ABLOCKS_BUSY (abase));
1328 val = free_ablock;
1329 free_ablock = free_ablock->x.next_free;
1331 #ifndef GC_MALLOC_CHECK
1332 if (type != MEM_TYPE_NON_LISP)
1333 mem_insert (val, (char *) val + nbytes, type);
1334 #endif
1336 MALLOC_UNBLOCK_INPUT;
1338 MALLOC_PROBE (nbytes);
1340 eassert (0 == ((uintptr_t) val) % BLOCK_ALIGN);
1341 return val;
1344 static void
1345 lisp_align_free (void *block)
1347 struct ablock *ablock = block;
1348 struct ablocks *abase = ABLOCK_ABASE (ablock);
1350 MALLOC_BLOCK_INPUT;
1351 #ifndef GC_MALLOC_CHECK
1352 mem_delete (mem_find (block));
1353 #endif
1354 /* Put on free list. */
1355 ablock->x.next_free = free_ablock;
1356 free_ablock = ablock;
1357 /* Update busy count. */
1358 intptr_t busy = (intptr_t) ABLOCKS_BUSY (abase) - 2;
1359 eassume (0 <= busy && busy <= 2 * ABLOCKS_SIZE - 1);
1360 ABLOCKS_BUSY (abase) = (struct ablocks *) busy;
1362 if (busy < 2)
1363 { /* All the blocks are free. */
1364 int i = 0;
1365 bool aligned = busy;
1366 struct ablock **tem = &free_ablock;
1367 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1369 while (*tem)
1371 if (*tem >= (struct ablock *) abase && *tem < atop)
1373 i++;
1374 *tem = (*tem)->x.next_free;
1376 else
1377 tem = &(*tem)->x.next_free;
1379 eassert ((aligned & 1) == aligned);
1380 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1381 #ifdef USE_POSIX_MEMALIGN
1382 eassert ((uintptr_t) ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1383 #endif
1384 free (ABLOCKS_BASE (abase));
1386 MALLOC_UNBLOCK_INPUT;
1389 #if !defined __GNUC__ && !defined __alignof__
1390 # define __alignof__(type) alignof (type)
1391 #endif
1393 /* True if malloc (N) is known to return a multiple of GCALIGNMENT
1394 whenever N is also a multiple. In practice this is true if
1395 __alignof__ (max_align_t) is a multiple as well, assuming
1396 GCALIGNMENT is 8; other values of GCALIGNMENT have not been looked
1397 into. Use __alignof__ if available, as otherwise
1398 MALLOC_IS_GC_ALIGNED would be false on GCC x86 even though the
1399 alignment is OK there.
1401 This is a macro, not an enum constant, for portability to HP-UX
1402 10.20 cc and AIX 3.2.5 xlc. */
1403 #define MALLOC_IS_GC_ALIGNED \
1404 (GCALIGNMENT == 8 && __alignof__ (max_align_t) % GCALIGNMENT == 0)
1406 /* True if a malloc-returned pointer P is suitably aligned for SIZE,
1407 where Lisp alignment may be needed if SIZE is Lisp-aligned. */
1409 static bool
1410 laligned (void *p, size_t size)
1412 return (MALLOC_IS_GC_ALIGNED || (intptr_t) p % GCALIGNMENT == 0
1413 || size % GCALIGNMENT != 0);
1416 /* Like malloc and realloc except that if SIZE is Lisp-aligned, make
1417 sure the result is too, if necessary by reallocating (typically
1418 with larger and larger sizes) until the allocator returns a
1419 Lisp-aligned pointer. Code that needs to allocate C heap memory
1420 for a Lisp object should use one of these functions to obtain a
1421 pointer P; that way, if T is an enum Lisp_Type value and L ==
1422 make_lisp_ptr (P, T), then XPNTR (L) == P and XTYPE (L) == T.
1424 On typical modern platforms these functions' loops do not iterate.
1425 On now-rare (and perhaps nonexistent) platforms, the loops in
1426 theory could repeat forever. If an infinite loop is possible on a
1427 platform, a build would surely loop and the builder can then send
1428 us a bug report. Adding a counter to try to detect any such loop
1429 would complicate the code (and possibly introduce bugs, in code
1430 that's never really exercised) for little benefit. */
1432 static void *
1433 lmalloc (size_t size)
1435 #if USE_ALIGNED_ALLOC
1436 if (! MALLOC_IS_GC_ALIGNED && size % GCALIGNMENT == 0)
1437 return aligned_alloc (GCALIGNMENT, size);
1438 #endif
1440 while (true)
1442 void *p = malloc (size);
1443 if (laligned (p, size))
1444 return p;
1445 free (p);
1446 size_t bigger = size + GCALIGNMENT;
1447 if (size < bigger)
1448 size = bigger;
1452 static void *
1453 lrealloc (void *p, size_t size)
1455 while (true)
1457 p = realloc (p, size);
1458 if (laligned (p, size))
1459 return p;
1460 size_t bigger = size + GCALIGNMENT;
1461 if (size < bigger)
1462 size = bigger;
1467 /***********************************************************************
1468 Interval Allocation
1469 ***********************************************************************/
1471 /* Number of intervals allocated in an interval_block structure.
1472 The 1020 is 1024 minus malloc overhead. */
1474 #define INTERVAL_BLOCK_SIZE \
1475 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1477 /* Intervals are allocated in chunks in the form of an interval_block
1478 structure. */
1480 struct interval_block
1482 /* Place `intervals' first, to preserve alignment. */
1483 struct interval intervals[INTERVAL_BLOCK_SIZE];
1484 struct interval_block *next;
1487 /* Current interval block. Its `next' pointer points to older
1488 blocks. */
1490 static struct interval_block *interval_block;
1492 /* Index in interval_block above of the next unused interval
1493 structure. */
1495 static int interval_block_index = INTERVAL_BLOCK_SIZE;
1497 /* Number of free and live intervals. */
1499 static EMACS_INT total_free_intervals, total_intervals;
1501 /* List of free intervals. */
1503 static INTERVAL interval_free_list;
1505 /* Return a new interval. */
1507 INTERVAL
1508 make_interval (void)
1510 INTERVAL val;
1512 MALLOC_BLOCK_INPUT;
1514 if (interval_free_list)
1516 val = interval_free_list;
1517 interval_free_list = INTERVAL_PARENT (interval_free_list);
1519 else
1521 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1523 struct interval_block *newi
1524 = lisp_malloc (sizeof *newi, MEM_TYPE_NON_LISP);
1526 newi->next = interval_block;
1527 interval_block = newi;
1528 interval_block_index = 0;
1529 total_free_intervals += INTERVAL_BLOCK_SIZE;
1531 val = &interval_block->intervals[interval_block_index++];
1534 MALLOC_UNBLOCK_INPUT;
1536 consing_since_gc += sizeof (struct interval);
1537 intervals_consed++;
1538 total_free_intervals--;
1539 RESET_INTERVAL (val);
1540 val->gcmarkbit = 0;
1541 return val;
1545 /* Mark Lisp objects in interval I. */
1547 static void
1548 mark_interval (register INTERVAL i, Lisp_Object dummy)
1550 /* Intervals should never be shared. So, if extra internal checking is
1551 enabled, GC aborts if it seems to have visited an interval twice. */
1552 eassert (!i->gcmarkbit);
1553 i->gcmarkbit = 1;
1554 mark_object (i->plist);
1557 /* Mark the interval tree rooted in I. */
1559 #define MARK_INTERVAL_TREE(i) \
1560 do { \
1561 if (i && !i->gcmarkbit) \
1562 traverse_intervals_noorder (i, mark_interval, Qnil); \
1563 } while (0)
1565 /***********************************************************************
1566 String Allocation
1567 ***********************************************************************/
1569 /* Lisp_Strings are allocated in string_block structures. When a new
1570 string_block is allocated, all the Lisp_Strings it contains are
1571 added to a free-list string_free_list. When a new Lisp_String is
1572 needed, it is taken from that list. During the sweep phase of GC,
1573 string_blocks that are entirely free are freed, except two which
1574 we keep.
1576 String data is allocated from sblock structures. Strings larger
1577 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1578 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1580 Sblocks consist internally of sdata structures, one for each
1581 Lisp_String. The sdata structure points to the Lisp_String it
1582 belongs to. The Lisp_String points back to the `u.data' member of
1583 its sdata structure.
1585 When a Lisp_String is freed during GC, it is put back on
1586 string_free_list, and its `data' member and its sdata's `string'
1587 pointer is set to null. The size of the string is recorded in the
1588 `n.nbytes' member of the sdata. So, sdata structures that are no
1589 longer used, can be easily recognized, and it's easy to compact the
1590 sblocks of small strings which we do in compact_small_strings. */
1592 /* Size in bytes of an sblock structure used for small strings. This
1593 is 8192 minus malloc overhead. */
1595 #define SBLOCK_SIZE 8188
1597 /* Strings larger than this are considered large strings. String data
1598 for large strings is allocated from individual sblocks. */
1600 #define LARGE_STRING_BYTES 1024
1602 /* The SDATA typedef is a struct or union describing string memory
1603 sub-allocated from an sblock. This is where the contents of Lisp
1604 strings are stored. */
1606 struct sdata
1608 /* Back-pointer to the string this sdata belongs to. If null, this
1609 structure is free, and NBYTES (in this structure or in the union below)
1610 contains the string's byte size (the same value that STRING_BYTES
1611 would return if STRING were non-null). If non-null, STRING_BYTES
1612 (STRING) is the size of the data, and DATA contains the string's
1613 contents. */
1614 struct Lisp_String *string;
1616 #ifdef GC_CHECK_STRING_BYTES
1617 ptrdiff_t nbytes;
1618 #endif
1620 unsigned char data[FLEXIBLE_ARRAY_MEMBER];
1623 #ifdef GC_CHECK_STRING_BYTES
1625 typedef struct sdata sdata;
1626 #define SDATA_NBYTES(S) (S)->nbytes
1627 #define SDATA_DATA(S) (S)->data
1629 #else
1631 typedef union
1633 struct Lisp_String *string;
1635 /* When STRING is nonnull, this union is actually of type 'struct sdata',
1636 which has a flexible array member. However, if implemented by
1637 giving this union a member of type 'struct sdata', the union
1638 could not be the last (flexible) member of 'struct sblock',
1639 because C99 prohibits a flexible array member from having a type
1640 that is itself a flexible array. So, comment this member out here,
1641 but remember that the option's there when using this union. */
1642 #if 0
1643 struct sdata u;
1644 #endif
1646 /* When STRING is null. */
1647 struct
1649 struct Lisp_String *string;
1650 ptrdiff_t nbytes;
1651 } n;
1652 } sdata;
1654 #define SDATA_NBYTES(S) (S)->n.nbytes
1655 #define SDATA_DATA(S) ((struct sdata *) (S))->data
1657 #endif /* not GC_CHECK_STRING_BYTES */
1659 enum { SDATA_DATA_OFFSET = offsetof (struct sdata, data) };
1661 /* Structure describing a block of memory which is sub-allocated to
1662 obtain string data memory for strings. Blocks for small strings
1663 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1664 as large as needed. */
1666 struct sblock
1668 /* Next in list. */
1669 struct sblock *next;
1671 /* Pointer to the next free sdata block. This points past the end
1672 of the sblock if there isn't any space left in this block. */
1673 sdata *next_free;
1675 /* String data. */
1676 sdata data[FLEXIBLE_ARRAY_MEMBER];
1679 /* Number of Lisp strings in a string_block structure. The 1020 is
1680 1024 minus malloc overhead. */
1682 #define STRING_BLOCK_SIZE \
1683 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1685 /* Structure describing a block from which Lisp_String structures
1686 are allocated. */
1688 struct string_block
1690 /* Place `strings' first, to preserve alignment. */
1691 struct Lisp_String strings[STRING_BLOCK_SIZE];
1692 struct string_block *next;
1695 /* Head and tail of the list of sblock structures holding Lisp string
1696 data. We always allocate from current_sblock. The NEXT pointers
1697 in the sblock structures go from oldest_sblock to current_sblock. */
1699 static struct sblock *oldest_sblock, *current_sblock;
1701 /* List of sblocks for large strings. */
1703 static struct sblock *large_sblocks;
1705 /* List of string_block structures. */
1707 static struct string_block *string_blocks;
1709 /* Free-list of Lisp_Strings. */
1711 static struct Lisp_String *string_free_list;
1713 /* Number of live and free Lisp_Strings. */
1715 static EMACS_INT total_strings, total_free_strings;
1717 /* Number of bytes used by live strings. */
1719 static EMACS_INT total_string_bytes;
1721 /* Given a pointer to a Lisp_String S which is on the free-list
1722 string_free_list, return a pointer to its successor in the
1723 free-list. */
1725 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1727 /* Return a pointer to the sdata structure belonging to Lisp string S.
1728 S must be live, i.e. S->data must not be null. S->data is actually
1729 a pointer to the `u.data' member of its sdata structure; the
1730 structure starts at a constant offset in front of that. */
1732 #define SDATA_OF_STRING(S) ((sdata *) ((S)->data - SDATA_DATA_OFFSET))
1735 #ifdef GC_CHECK_STRING_OVERRUN
1737 /* We check for overrun in string data blocks by appending a small
1738 "cookie" after each allocated string data block, and check for the
1739 presence of this cookie during GC. */
1741 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1742 static char const string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1743 { '\xde', '\xad', '\xbe', '\xef' };
1745 #else
1746 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1747 #endif
1749 /* Value is the size of an sdata structure large enough to hold NBYTES
1750 bytes of string data. The value returned includes a terminating
1751 NUL byte, the size of the sdata structure, and padding. */
1753 #ifdef GC_CHECK_STRING_BYTES
1755 #define SDATA_SIZE(NBYTES) FLEXSIZEOF (struct sdata, data, NBYTES)
1757 #else /* not GC_CHECK_STRING_BYTES */
1759 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1760 less than the size of that member. The 'max' is not needed when
1761 SDATA_DATA_OFFSET is a multiple of FLEXALIGNOF (struct sdata),
1762 because then the alignment code reserves enough space. */
1764 #define SDATA_SIZE(NBYTES) \
1765 ((SDATA_DATA_OFFSET \
1766 + (SDATA_DATA_OFFSET % FLEXALIGNOF (struct sdata) == 0 \
1767 ? NBYTES \
1768 : max (NBYTES, FLEXALIGNOF (struct sdata) - 1)) \
1769 + 1 \
1770 + FLEXALIGNOF (struct sdata) - 1) \
1771 & ~(FLEXALIGNOF (struct sdata) - 1))
1773 #endif /* not GC_CHECK_STRING_BYTES */
1775 /* Extra bytes to allocate for each string. */
1777 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1779 /* Exact bound on the number of bytes in a string, not counting the
1780 terminating null. A string cannot contain more bytes than
1781 STRING_BYTES_BOUND, nor can it be so long that the size_t
1782 arithmetic in allocate_string_data would overflow while it is
1783 calculating a value to be passed to malloc. */
1784 static ptrdiff_t const STRING_BYTES_MAX =
1785 min (STRING_BYTES_BOUND,
1786 ((SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD
1787 - GC_STRING_EXTRA
1788 - offsetof (struct sblock, data)
1789 - SDATA_DATA_OFFSET)
1790 & ~(sizeof (EMACS_INT) - 1)));
1792 /* Initialize string allocation. Called from init_alloc_once. */
1794 static void
1795 init_strings (void)
1797 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1798 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1802 #ifdef GC_CHECK_STRING_BYTES
1804 static int check_string_bytes_count;
1806 /* Like STRING_BYTES, but with debugging check. Can be
1807 called during GC, so pay attention to the mark bit. */
1809 ptrdiff_t
1810 string_bytes (struct Lisp_String *s)
1812 ptrdiff_t nbytes =
1813 (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1815 if (!PURE_P (s) && s->data && 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->data = NULL;
1922 NEXT_FREE_LISP_STRING (s) = string_free_list;
1923 string_free_list = 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 for S, and
1961 set S->data to its `u.data' member. Store a NUL byte at the end of
1962 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1963 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->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 b->next_free = b->data;
2006 b->data[0].string = NULL;
2007 b->next = large_sblocks;
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 b->next_free = b->data;
2018 b->data[0].string = NULL;
2019 b->next = NULL;
2021 if (current_sblock)
2022 current_sblock->next = b;
2023 else
2024 oldest_sblock = b;
2025 current_sblock = b;
2027 else
2028 b = current_sblock;
2030 data = b->next_free;
2031 b->next_free = (sdata *) ((char *) data + needed + GC_STRING_EXTRA);
2033 MALLOC_UNBLOCK_INPUT;
2035 data->string = s;
2036 s->data = SDATA_DATA (data);
2037 #ifdef GC_CHECK_STRING_BYTES
2038 SDATA_NBYTES (data) = nbytes;
2039 #endif
2040 s->size = nchars;
2041 s->size_byte = nbytes;
2042 s->data[nbytes] = '\0';
2043 #ifdef GC_CHECK_STRING_OVERRUN
2044 memcpy ((char *) data + needed, string_overrun_cookie,
2045 GC_STRING_OVERRUN_COOKIE_SIZE);
2046 #endif
2048 /* Note that Faset may call to this function when S has already data
2049 assigned. In this case, mark data as free by setting it's string
2050 back-pointer to null, and record the size of the data in it. */
2051 if (old_data)
2053 SDATA_NBYTES (old_data) = old_nbytes;
2054 old_data->string = NULL;
2057 consing_since_gc += needed;
2061 /* Sweep and compact strings. */
2063 NO_INLINE /* For better stack traces */
2064 static void
2065 sweep_strings (void)
2067 struct string_block *b, *next;
2068 struct string_block *live_blocks = NULL;
2070 string_free_list = NULL;
2071 total_strings = total_free_strings = 0;
2072 total_string_bytes = 0;
2074 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
2075 for (b = string_blocks; b; b = next)
2077 int i, nfree = 0;
2078 struct Lisp_String *free_list_before = string_free_list;
2080 next = b->next;
2082 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
2084 struct Lisp_String *s = b->strings + i;
2086 if (s->data)
2088 /* String was not on free-list before. */
2089 if (STRING_MARKED_P (s))
2091 /* String is live; unmark it and its intervals. */
2092 UNMARK_STRING (s);
2094 /* Do not use string_(set|get)_intervals here. */
2095 s->intervals = balance_intervals (s->intervals);
2097 ++total_strings;
2098 total_string_bytes += STRING_BYTES (s);
2100 else
2102 /* String is dead. Put it on the free-list. */
2103 sdata *data = SDATA_OF_STRING (s);
2105 /* Save the size of S in its sdata so that we know
2106 how large that is. Reset the sdata's string
2107 back-pointer so that we know it's free. */
2108 #ifdef GC_CHECK_STRING_BYTES
2109 if (string_bytes (s) != SDATA_NBYTES (data))
2110 emacs_abort ();
2111 #else
2112 data->n.nbytes = STRING_BYTES (s);
2113 #endif
2114 data->string = NULL;
2116 /* Reset the strings's `data' member so that we
2117 know it's free. */
2118 s->data = NULL;
2120 /* Put the string on the free-list. */
2121 NEXT_FREE_LISP_STRING (s) = string_free_list;
2122 string_free_list = s;
2123 ++nfree;
2126 else
2128 /* S was on the free-list before. Put it there again. */
2129 NEXT_FREE_LISP_STRING (s) = string_free_list;
2130 string_free_list = s;
2131 ++nfree;
2135 /* Free blocks that contain free Lisp_Strings only, except
2136 the first two of them. */
2137 if (nfree == STRING_BLOCK_SIZE
2138 && total_free_strings > STRING_BLOCK_SIZE)
2140 lisp_free (b);
2141 string_free_list = free_list_before;
2143 else
2145 total_free_strings += nfree;
2146 b->next = live_blocks;
2147 live_blocks = b;
2151 check_string_free_list ();
2153 string_blocks = live_blocks;
2154 free_large_strings ();
2155 compact_small_strings ();
2157 check_string_free_list ();
2161 /* Free dead large strings. */
2163 static void
2164 free_large_strings (void)
2166 struct sblock *b, *next;
2167 struct sblock *live_blocks = NULL;
2169 for (b = large_sblocks; b; b = next)
2171 next = b->next;
2173 if (b->data[0].string == NULL)
2174 lisp_free (b);
2175 else
2177 b->next = live_blocks;
2178 live_blocks = b;
2182 large_sblocks = live_blocks;
2186 /* Compact data of small strings. Free sblocks that don't contain
2187 data of live strings after compaction. */
2189 static void
2190 compact_small_strings (void)
2192 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2193 to, and TB_END is the end of TB. */
2194 struct sblock *tb = oldest_sblock;
2195 if (tb)
2197 sdata *tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
2198 sdata *to = tb->data;
2200 /* Step through the blocks from the oldest to the youngest. We
2201 expect that old blocks will stabilize over time, so that less
2202 copying will happen this way. */
2203 struct sblock *b = tb;
2206 sdata *end = b->next_free;
2207 eassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2209 for (sdata *from = b->data; from < end; )
2211 /* Compute the next FROM here because copying below may
2212 overwrite data we need to compute it. */
2213 ptrdiff_t nbytes;
2214 struct Lisp_String *s = from->string;
2216 #ifdef GC_CHECK_STRING_BYTES
2217 /* Check that the string size recorded in the string is the
2218 same as the one recorded in the sdata structure. */
2219 if (s && string_bytes (s) != SDATA_NBYTES (from))
2220 emacs_abort ();
2221 #endif /* GC_CHECK_STRING_BYTES */
2223 nbytes = s ? STRING_BYTES (s) : SDATA_NBYTES (from);
2224 eassert (nbytes <= LARGE_STRING_BYTES);
2226 nbytes = SDATA_SIZE (nbytes);
2227 sdata *from_end = (sdata *) ((char *) from
2228 + nbytes + GC_STRING_EXTRA);
2230 #ifdef GC_CHECK_STRING_OVERRUN
2231 if (memcmp (string_overrun_cookie,
2232 (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
2233 GC_STRING_OVERRUN_COOKIE_SIZE))
2234 emacs_abort ();
2235 #endif
2237 /* Non-NULL S means it's alive. Copy its data. */
2238 if (s)
2240 /* If TB is full, proceed with the next sblock. */
2241 sdata *to_end = (sdata *) ((char *) to
2242 + nbytes + GC_STRING_EXTRA);
2243 if (to_end > tb_end)
2245 tb->next_free = to;
2246 tb = tb->next;
2247 tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
2248 to = tb->data;
2249 to_end = (sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2252 /* Copy, and update the string's `data' pointer. */
2253 if (from != to)
2255 eassert (tb != b || to < from);
2256 memmove (to, from, nbytes + GC_STRING_EXTRA);
2257 to->string->data = SDATA_DATA (to);
2260 /* Advance past the sdata we copied to. */
2261 to = to_end;
2263 from = from_end;
2265 b = b->next;
2267 while (b);
2269 /* The rest of the sblocks following TB don't contain live data, so
2270 we can free them. */
2271 for (b = tb->next; b; )
2273 struct sblock *next = b->next;
2274 lisp_free (b);
2275 b = next;
2278 tb->next_free = to;
2279 tb->next = NULL;
2282 current_sblock = tb;
2285 void
2286 string_overflow (void)
2288 error ("Maximum string size exceeded");
2291 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2292 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2293 LENGTH must be an integer.
2294 INIT must be an integer that represents a character. */)
2295 (Lisp_Object length, Lisp_Object init)
2297 register Lisp_Object val;
2298 int c;
2299 EMACS_INT nbytes;
2301 CHECK_NATNUM (length);
2302 CHECK_CHARACTER (init);
2304 c = XFASTINT (init);
2305 if (ASCII_CHAR_P (c))
2307 nbytes = XINT (length);
2308 val = make_uninit_string (nbytes);
2309 if (nbytes)
2311 memset (SDATA (val), c, nbytes);
2312 SDATA (val)[nbytes] = 0;
2315 else
2317 unsigned char str[MAX_MULTIBYTE_LENGTH];
2318 ptrdiff_t len = CHAR_STRING (c, str);
2319 EMACS_INT string_len = XINT (length);
2320 unsigned char *p, *beg, *end;
2322 if (INT_MULTIPLY_WRAPV (len, string_len, &nbytes))
2323 string_overflow ();
2324 val = make_uninit_multibyte_string (string_len, nbytes);
2325 for (beg = SDATA (val), p = beg, end = beg + nbytes; p < end; p += len)
2327 /* First time we just copy `str' to the data of `val'. */
2328 if (p == beg)
2329 memcpy (p, str, len);
2330 else
2332 /* Next time we copy largest possible chunk from
2333 initialized to uninitialized part of `val'. */
2334 len = min (p - beg, end - p);
2335 memcpy (p, beg, len);
2338 if (nbytes)
2339 *p = 0;
2342 return val;
2345 /* Fill A with 1 bits if INIT is non-nil, and with 0 bits otherwise.
2346 Return A. */
2348 Lisp_Object
2349 bool_vector_fill (Lisp_Object a, Lisp_Object init)
2351 EMACS_INT nbits = bool_vector_size (a);
2352 if (0 < nbits)
2354 unsigned char *data = bool_vector_uchar_data (a);
2355 int pattern = NILP (init) ? 0 : (1 << BOOL_VECTOR_BITS_PER_CHAR) - 1;
2356 ptrdiff_t nbytes = bool_vector_bytes (nbits);
2357 int last_mask = ~ (~0u << ((nbits - 1) % BOOL_VECTOR_BITS_PER_CHAR + 1));
2358 memset (data, pattern, nbytes - 1);
2359 data[nbytes - 1] = pattern & last_mask;
2361 return a;
2364 /* Return a newly allocated, uninitialized bool vector of size NBITS. */
2366 Lisp_Object
2367 make_uninit_bool_vector (EMACS_INT nbits)
2369 Lisp_Object val;
2370 EMACS_INT words = bool_vector_words (nbits);
2371 EMACS_INT word_bytes = words * sizeof (bits_word);
2372 EMACS_INT needed_elements = ((bool_header_size - header_size + word_bytes
2373 + word_size - 1)
2374 / word_size);
2375 struct Lisp_Bool_Vector *p
2376 = (struct Lisp_Bool_Vector *) allocate_vector (needed_elements);
2377 XSETVECTOR (val, p);
2378 XSETPVECTYPESIZE (XVECTOR (val), PVEC_BOOL_VECTOR, 0, 0);
2379 p->size = nbits;
2381 /* Clear padding at the end. */
2382 if (words)
2383 p->data[words - 1] = 0;
2385 return val;
2388 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2389 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2390 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2391 (Lisp_Object length, Lisp_Object init)
2393 Lisp_Object val;
2395 CHECK_NATNUM (length);
2396 val = make_uninit_bool_vector (XFASTINT (length));
2397 return bool_vector_fill (val, init);
2400 DEFUN ("bool-vector", Fbool_vector, Sbool_vector, 0, MANY, 0,
2401 doc: /* Return a new bool-vector with specified arguments as elements.
2402 Any number of arguments, even zero arguments, are allowed.
2403 usage: (bool-vector &rest OBJECTS) */)
2404 (ptrdiff_t nargs, Lisp_Object *args)
2406 ptrdiff_t i;
2407 Lisp_Object vector;
2409 vector = make_uninit_bool_vector (nargs);
2410 for (i = 0; i < nargs; i++)
2411 bool_vector_set (vector, i, !NILP (args[i]));
2413 return vector;
2416 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2417 of characters from the contents. This string may be unibyte or
2418 multibyte, depending on the contents. */
2420 Lisp_Object
2421 make_string (const char *contents, ptrdiff_t nbytes)
2423 register Lisp_Object val;
2424 ptrdiff_t nchars, multibyte_nbytes;
2426 parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
2427 &nchars, &multibyte_nbytes);
2428 if (nbytes == nchars || nbytes != multibyte_nbytes)
2429 /* CONTENTS contains no multibyte sequences or contains an invalid
2430 multibyte sequence. We must make unibyte string. */
2431 val = make_unibyte_string (contents, nbytes);
2432 else
2433 val = make_multibyte_string (contents, nchars, nbytes);
2434 return val;
2437 /* Make a unibyte string from LENGTH bytes at CONTENTS. */
2439 Lisp_Object
2440 make_unibyte_string (const char *contents, ptrdiff_t length)
2442 register Lisp_Object val;
2443 val = make_uninit_string (length);
2444 memcpy (SDATA (val), contents, length);
2445 return val;
2449 /* Make a multibyte string from NCHARS characters occupying NBYTES
2450 bytes at CONTENTS. */
2452 Lisp_Object
2453 make_multibyte_string (const char *contents,
2454 ptrdiff_t nchars, ptrdiff_t nbytes)
2456 register Lisp_Object val;
2457 val = make_uninit_multibyte_string (nchars, nbytes);
2458 memcpy (SDATA (val), contents, nbytes);
2459 return val;
2463 /* Make a string from NCHARS characters occupying NBYTES bytes at
2464 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2466 Lisp_Object
2467 make_string_from_bytes (const char *contents,
2468 ptrdiff_t nchars, ptrdiff_t nbytes)
2470 register Lisp_Object val;
2471 val = make_uninit_multibyte_string (nchars, nbytes);
2472 memcpy (SDATA (val), contents, nbytes);
2473 if (SBYTES (val) == SCHARS (val))
2474 STRING_SET_UNIBYTE (val);
2475 return val;
2479 /* Make a string from NCHARS characters occupying NBYTES bytes at
2480 CONTENTS. The argument MULTIBYTE controls whether to label the
2481 string as multibyte. If NCHARS is negative, it counts the number of
2482 characters by itself. */
2484 Lisp_Object
2485 make_specified_string (const char *contents,
2486 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
2488 Lisp_Object val;
2490 if (nchars < 0)
2492 if (multibyte)
2493 nchars = multibyte_chars_in_text ((const unsigned char *) contents,
2494 nbytes);
2495 else
2496 nchars = nbytes;
2498 val = make_uninit_multibyte_string (nchars, nbytes);
2499 memcpy (SDATA (val), contents, nbytes);
2500 if (!multibyte)
2501 STRING_SET_UNIBYTE (val);
2502 return val;
2506 /* Return a unibyte Lisp_String set up to hold LENGTH characters
2507 occupying LENGTH bytes. */
2509 Lisp_Object
2510 make_uninit_string (EMACS_INT length)
2512 Lisp_Object val;
2514 if (!length)
2515 return empty_unibyte_string;
2516 val = make_uninit_multibyte_string (length, length);
2517 STRING_SET_UNIBYTE (val);
2518 return val;
2522 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2523 which occupy NBYTES bytes. */
2525 Lisp_Object
2526 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2528 Lisp_Object string;
2529 struct Lisp_String *s;
2531 if (nchars < 0)
2532 emacs_abort ();
2533 if (!nbytes)
2534 return empty_multibyte_string;
2536 s = allocate_string ();
2537 s->intervals = NULL;
2538 allocate_string_data (s, nchars, nbytes);
2539 XSETSTRING (string, s);
2540 string_chars_consed += nbytes;
2541 return string;
2544 /* Print arguments to BUF according to a FORMAT, then return
2545 a Lisp_String initialized with the data from BUF. */
2547 Lisp_Object
2548 make_formatted_string (char *buf, const char *format, ...)
2550 va_list ap;
2551 int length;
2553 va_start (ap, format);
2554 length = vsprintf (buf, format, ap);
2555 va_end (ap);
2556 return make_string (buf, length);
2560 /***********************************************************************
2561 Float Allocation
2562 ***********************************************************************/
2564 /* We store float cells inside of float_blocks, allocating a new
2565 float_block with malloc whenever necessary. Float cells reclaimed
2566 by GC are put on a free list to be reallocated before allocating
2567 any new float cells from the latest float_block. */
2569 #define FLOAT_BLOCK_SIZE \
2570 (((BLOCK_BYTES - sizeof (struct float_block *) \
2571 /* The compiler might add padding at the end. */ \
2572 - (sizeof (struct Lisp_Float) - sizeof (bits_word))) * CHAR_BIT) \
2573 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2575 #define GETMARKBIT(block,n) \
2576 (((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2577 >> ((n) % BITS_PER_BITS_WORD)) \
2578 & 1)
2580 #define SETMARKBIT(block,n) \
2581 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2582 |= (bits_word) 1 << ((n) % BITS_PER_BITS_WORD))
2584 #define UNSETMARKBIT(block,n) \
2585 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2586 &= ~((bits_word) 1 << ((n) % BITS_PER_BITS_WORD)))
2588 #define FLOAT_BLOCK(fptr) \
2589 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2591 #define FLOAT_INDEX(fptr) \
2592 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2594 struct float_block
2596 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2597 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2598 bits_word gcmarkbits[1 + FLOAT_BLOCK_SIZE / BITS_PER_BITS_WORD];
2599 struct float_block *next;
2602 #define FLOAT_MARKED_P(fptr) \
2603 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2605 #define FLOAT_MARK(fptr) \
2606 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2608 #define FLOAT_UNMARK(fptr) \
2609 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2611 /* Current float_block. */
2613 static struct float_block *float_block;
2615 /* Index of first unused Lisp_Float in the current float_block. */
2617 static int float_block_index = FLOAT_BLOCK_SIZE;
2619 /* Free-list of Lisp_Floats. */
2621 static struct Lisp_Float *float_free_list;
2623 /* Return a new float object with value FLOAT_VALUE. */
2625 Lisp_Object
2626 make_float (double float_value)
2628 register Lisp_Object val;
2630 MALLOC_BLOCK_INPUT;
2632 if (float_free_list)
2634 /* We use the data field for chaining the free list
2635 so that we won't use the same field that has the mark bit. */
2636 XSETFLOAT (val, float_free_list);
2637 float_free_list = float_free_list->u.chain;
2639 else
2641 if (float_block_index == FLOAT_BLOCK_SIZE)
2643 struct float_block *new
2644 = lisp_align_malloc (sizeof *new, MEM_TYPE_FLOAT);
2645 new->next = float_block;
2646 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2647 float_block = new;
2648 float_block_index = 0;
2649 total_free_floats += FLOAT_BLOCK_SIZE;
2651 XSETFLOAT (val, &float_block->floats[float_block_index]);
2652 float_block_index++;
2655 MALLOC_UNBLOCK_INPUT;
2657 XFLOAT_INIT (val, float_value);
2658 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2659 consing_since_gc += sizeof (struct Lisp_Float);
2660 floats_consed++;
2661 total_free_floats--;
2662 return val;
2667 /***********************************************************************
2668 Cons Allocation
2669 ***********************************************************************/
2671 /* We store cons cells inside of cons_blocks, allocating a new
2672 cons_block with malloc whenever necessary. Cons cells reclaimed by
2673 GC are put on a free list to be reallocated before allocating
2674 any new cons cells from the latest cons_block. */
2676 #define CONS_BLOCK_SIZE \
2677 (((BLOCK_BYTES - sizeof (struct cons_block *) \
2678 /* The compiler might add padding at the end. */ \
2679 - (sizeof (struct Lisp_Cons) - sizeof (bits_word))) * CHAR_BIT) \
2680 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2682 #define CONS_BLOCK(fptr) \
2683 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2685 #define CONS_INDEX(fptr) \
2686 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2688 struct cons_block
2690 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2691 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2692 bits_word gcmarkbits[1 + CONS_BLOCK_SIZE / BITS_PER_BITS_WORD];
2693 struct cons_block *next;
2696 #define CONS_MARKED_P(fptr) \
2697 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2699 #define CONS_MARK(fptr) \
2700 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2702 #define CONS_UNMARK(fptr) \
2703 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2705 /* Current cons_block. */
2707 static struct cons_block *cons_block;
2709 /* Index of first unused Lisp_Cons in the current block. */
2711 static int cons_block_index = CONS_BLOCK_SIZE;
2713 /* Free-list of Lisp_Cons structures. */
2715 static struct Lisp_Cons *cons_free_list;
2717 /* Explicitly free a cons cell by putting it on the free-list. */
2719 void
2720 free_cons (struct Lisp_Cons *ptr)
2722 ptr->u.chain = cons_free_list;
2723 ptr->car = Vdead;
2724 cons_free_list = ptr;
2725 consing_since_gc -= sizeof *ptr;
2726 total_free_conses++;
2729 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2730 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2731 (Lisp_Object car, Lisp_Object cdr)
2733 register Lisp_Object val;
2735 MALLOC_BLOCK_INPUT;
2737 if (cons_free_list)
2739 /* We use the cdr for chaining the free list
2740 so that we won't use the same field that has the mark bit. */
2741 XSETCONS (val, cons_free_list);
2742 cons_free_list = cons_free_list->u.chain;
2744 else
2746 if (cons_block_index == CONS_BLOCK_SIZE)
2748 struct cons_block *new
2749 = lisp_align_malloc (sizeof *new, MEM_TYPE_CONS);
2750 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2751 new->next = cons_block;
2752 cons_block = new;
2753 cons_block_index = 0;
2754 total_free_conses += CONS_BLOCK_SIZE;
2756 XSETCONS (val, &cons_block->conses[cons_block_index]);
2757 cons_block_index++;
2760 MALLOC_UNBLOCK_INPUT;
2762 XSETCAR (val, car);
2763 XSETCDR (val, cdr);
2764 eassert (!CONS_MARKED_P (XCONS (val)));
2765 consing_since_gc += sizeof (struct Lisp_Cons);
2766 total_free_conses--;
2767 cons_cells_consed++;
2768 return val;
2771 #ifdef GC_CHECK_CONS_LIST
2772 /* Get an error now if there's any junk in the cons free list. */
2773 void
2774 check_cons_list (void)
2776 struct Lisp_Cons *tail = cons_free_list;
2778 while (tail)
2779 tail = tail->u.chain;
2781 #endif
2783 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2785 Lisp_Object
2786 list1 (Lisp_Object arg1)
2788 return Fcons (arg1, Qnil);
2791 Lisp_Object
2792 list2 (Lisp_Object arg1, Lisp_Object arg2)
2794 return Fcons (arg1, Fcons (arg2, Qnil));
2798 Lisp_Object
2799 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2801 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2805 Lisp_Object
2806 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2808 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2812 Lisp_Object
2813 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2815 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2816 Fcons (arg5, Qnil)))));
2819 /* Make a list of COUNT Lisp_Objects, where ARG is the
2820 first one. Allocate conses from pure space if TYPE
2821 is CONSTYPE_PURE, or allocate as usual if type is CONSTYPE_HEAP. */
2823 Lisp_Object
2824 listn (enum constype type, ptrdiff_t count, Lisp_Object arg, ...)
2826 Lisp_Object (*cons) (Lisp_Object, Lisp_Object);
2827 switch (type)
2829 case CONSTYPE_PURE: cons = pure_cons; break;
2830 case CONSTYPE_HEAP: cons = Fcons; break;
2831 default: emacs_abort ();
2834 eassume (0 < count);
2835 Lisp_Object val = cons (arg, Qnil);
2836 Lisp_Object tail = val;
2838 va_list ap;
2839 va_start (ap, arg);
2840 for (ptrdiff_t i = 1; i < count; i++)
2842 Lisp_Object elem = cons (va_arg (ap, Lisp_Object), Qnil);
2843 XSETCDR (tail, elem);
2844 tail = elem;
2846 va_end (ap);
2848 return val;
2851 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2852 doc: /* Return a newly created list with specified arguments as elements.
2853 Any number of arguments, even zero arguments, are allowed.
2854 usage: (list &rest OBJECTS) */)
2855 (ptrdiff_t nargs, Lisp_Object *args)
2857 register Lisp_Object val;
2858 val = Qnil;
2860 while (nargs > 0)
2862 nargs--;
2863 val = Fcons (args[nargs], val);
2865 return val;
2869 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2870 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2871 (register Lisp_Object length, Lisp_Object init)
2873 register Lisp_Object val;
2874 register EMACS_INT size;
2876 CHECK_NATNUM (length);
2877 size = XFASTINT (length);
2879 val = Qnil;
2880 while (size > 0)
2882 val = Fcons (init, val);
2883 --size;
2885 if (size > 0)
2887 val = Fcons (init, val);
2888 --size;
2890 if (size > 0)
2892 val = Fcons (init, val);
2893 --size;
2895 if (size > 0)
2897 val = Fcons (init, val);
2898 --size;
2900 if (size > 0)
2902 val = Fcons (init, val);
2903 --size;
2909 QUIT;
2912 return val;
2917 /***********************************************************************
2918 Vector Allocation
2919 ***********************************************************************/
2921 /* Sometimes a vector's contents are merely a pointer internally used
2922 in vector allocation code. On the rare platforms where a null
2923 pointer cannot be tagged, represent it with a Lisp 0.
2924 Usually you don't want to touch this. */
2926 static struct Lisp_Vector *
2927 next_vector (struct Lisp_Vector *v)
2929 return XUNTAG (v->contents[0], Lisp_Int0);
2932 static void
2933 set_next_vector (struct Lisp_Vector *v, struct Lisp_Vector *p)
2935 v->contents[0] = make_lisp_ptr (p, Lisp_Int0);
2938 /* This value is balanced well enough to avoid too much internal overhead
2939 for the most common cases; it's not required to be a power of two, but
2940 it's expected to be a mult-of-ROUNDUP_SIZE (see below). */
2942 #define VECTOR_BLOCK_SIZE 4096
2944 enum
2946 /* Alignment of struct Lisp_Vector objects. */
2947 vector_alignment = COMMON_MULTIPLE (FLEXALIGNOF (struct Lisp_Vector),
2948 GCALIGNMENT),
2950 /* Vector size requests are a multiple of this. */
2951 roundup_size = COMMON_MULTIPLE (vector_alignment, word_size)
2954 /* Verify assumptions described above. */
2955 verify (VECTOR_BLOCK_SIZE % roundup_size == 0);
2956 verify (VECTOR_BLOCK_SIZE <= (1 << PSEUDOVECTOR_SIZE_BITS));
2958 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at compile time. */
2959 #define vroundup_ct(x) ROUNDUP (x, roundup_size)
2960 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at runtime. */
2961 #define vroundup(x) (eassume ((x) >= 0), vroundup_ct (x))
2963 /* Rounding helps to maintain alignment constraints if USE_LSB_TAG. */
2965 #define VECTOR_BLOCK_BYTES (VECTOR_BLOCK_SIZE - vroundup_ct (sizeof (void *)))
2967 /* Size of the minimal vector allocated from block. */
2969 #define VBLOCK_BYTES_MIN vroundup_ct (header_size + sizeof (Lisp_Object))
2971 /* Size of the largest vector allocated from block. */
2973 #define VBLOCK_BYTES_MAX \
2974 vroundup ((VECTOR_BLOCK_BYTES / 2) - word_size)
2976 /* We maintain one free list for each possible block-allocated
2977 vector size, and this is the number of free lists we have. */
2979 #define VECTOR_MAX_FREE_LIST_INDEX \
2980 ((VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN) / roundup_size + 1)
2982 /* Common shortcut to advance vector pointer over a block data. */
2984 #define ADVANCE(v, nbytes) ((struct Lisp_Vector *) ((char *) (v) + (nbytes)))
2986 /* Common shortcut to calculate NBYTES-vector index in VECTOR_FREE_LISTS. */
2988 #define VINDEX(nbytes) (((nbytes) - VBLOCK_BYTES_MIN) / roundup_size)
2990 /* Common shortcut to setup vector on a free list. */
2992 #define SETUP_ON_FREE_LIST(v, nbytes, tmp) \
2993 do { \
2994 (tmp) = ((nbytes - header_size) / word_size); \
2995 XSETPVECTYPESIZE (v, PVEC_FREE, 0, (tmp)); \
2996 eassert ((nbytes) % roundup_size == 0); \
2997 (tmp) = VINDEX (nbytes); \
2998 eassert ((tmp) < VECTOR_MAX_FREE_LIST_INDEX); \
2999 set_next_vector (v, vector_free_lists[tmp]); \
3000 vector_free_lists[tmp] = (v); \
3001 total_free_vector_slots += (nbytes) / word_size; \
3002 } while (0)
3004 /* This internal type is used to maintain the list of large vectors
3005 which are allocated at their own, e.g. outside of vector blocks.
3007 struct large_vector itself cannot contain a struct Lisp_Vector, as
3008 the latter contains a flexible array member and C99 does not allow
3009 such structs to be nested. Instead, each struct large_vector
3010 object LV is followed by a struct Lisp_Vector, which is at offset
3011 large_vector_offset from LV, and whose address is therefore
3012 large_vector_vec (&LV). */
3014 struct large_vector
3016 struct large_vector *next;
3019 enum
3021 large_vector_offset = ROUNDUP (sizeof (struct large_vector), vector_alignment)
3024 static struct Lisp_Vector *
3025 large_vector_vec (struct large_vector *p)
3027 return (struct Lisp_Vector *) ((char *) p + large_vector_offset);
3030 /* This internal type is used to maintain an underlying storage
3031 for small vectors. */
3033 struct vector_block
3035 char data[VECTOR_BLOCK_BYTES];
3036 struct vector_block *next;
3039 /* Chain of vector blocks. */
3041 static struct vector_block *vector_blocks;
3043 /* Vector free lists, where NTH item points to a chain of free
3044 vectors of the same NBYTES size, so NTH == VINDEX (NBYTES). */
3046 static struct Lisp_Vector *vector_free_lists[VECTOR_MAX_FREE_LIST_INDEX];
3048 /* Singly-linked list of large vectors. */
3050 static struct large_vector *large_vectors;
3052 /* The only vector with 0 slots, allocated from pure space. */
3054 Lisp_Object zero_vector;
3056 /* Number of live vectors. */
3058 static EMACS_INT total_vectors;
3060 /* Total size of live and free vectors, in Lisp_Object units. */
3062 static EMACS_INT total_vector_slots, total_free_vector_slots;
3064 /* Get a new vector block. */
3066 static struct vector_block *
3067 allocate_vector_block (void)
3069 struct vector_block *block = xmalloc (sizeof *block);
3071 #ifndef GC_MALLOC_CHECK
3072 mem_insert (block->data, block->data + VECTOR_BLOCK_BYTES,
3073 MEM_TYPE_VECTOR_BLOCK);
3074 #endif
3076 block->next = vector_blocks;
3077 vector_blocks = block;
3078 return block;
3081 /* Called once to initialize vector allocation. */
3083 static void
3084 init_vectors (void)
3086 zero_vector = make_pure_vector (0);
3089 /* Allocate vector from a vector block. */
3091 static struct Lisp_Vector *
3092 allocate_vector_from_block (size_t nbytes)
3094 struct Lisp_Vector *vector;
3095 struct vector_block *block;
3096 size_t index, restbytes;
3098 eassert (VBLOCK_BYTES_MIN <= nbytes && nbytes <= VBLOCK_BYTES_MAX);
3099 eassert (nbytes % roundup_size == 0);
3101 /* First, try to allocate from a free list
3102 containing vectors of the requested size. */
3103 index = VINDEX (nbytes);
3104 if (vector_free_lists[index])
3106 vector = vector_free_lists[index];
3107 vector_free_lists[index] = next_vector (vector);
3108 total_free_vector_slots -= nbytes / word_size;
3109 return vector;
3112 /* Next, check free lists containing larger vectors. Since
3113 we will split the result, we should have remaining space
3114 large enough to use for one-slot vector at least. */
3115 for (index = VINDEX (nbytes + VBLOCK_BYTES_MIN);
3116 index < VECTOR_MAX_FREE_LIST_INDEX; index++)
3117 if (vector_free_lists[index])
3119 /* This vector is larger than requested. */
3120 vector = vector_free_lists[index];
3121 vector_free_lists[index] = next_vector (vector);
3122 total_free_vector_slots -= nbytes / word_size;
3124 /* Excess bytes are used for the smaller vector,
3125 which should be set on an appropriate free list. */
3126 restbytes = index * roundup_size + VBLOCK_BYTES_MIN - nbytes;
3127 eassert (restbytes % roundup_size == 0);
3128 SETUP_ON_FREE_LIST (ADVANCE (vector, nbytes), restbytes, index);
3129 return vector;
3132 /* Finally, need a new vector block. */
3133 block = allocate_vector_block ();
3135 /* New vector will be at the beginning of this block. */
3136 vector = (struct Lisp_Vector *) block->data;
3138 /* If the rest of space from this block is large enough
3139 for one-slot vector at least, set up it on a free list. */
3140 restbytes = VECTOR_BLOCK_BYTES - nbytes;
3141 if (restbytes >= VBLOCK_BYTES_MIN)
3143 eassert (restbytes % roundup_size == 0);
3144 SETUP_ON_FREE_LIST (ADVANCE (vector, nbytes), restbytes, index);
3146 return vector;
3149 /* Nonzero if VECTOR pointer is valid pointer inside BLOCK. */
3151 #define VECTOR_IN_BLOCK(vector, block) \
3152 ((char *) (vector) <= (block)->data \
3153 + VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN)
3155 /* Return the memory footprint of V in bytes. */
3157 static ptrdiff_t
3158 vector_nbytes (struct Lisp_Vector *v)
3160 ptrdiff_t size = v->header.size & ~ARRAY_MARK_FLAG;
3161 ptrdiff_t nwords;
3163 if (size & PSEUDOVECTOR_FLAG)
3165 if (PSEUDOVECTOR_TYPEP (&v->header, PVEC_BOOL_VECTOR))
3167 struct Lisp_Bool_Vector *bv = (struct Lisp_Bool_Vector *) v;
3168 ptrdiff_t word_bytes = (bool_vector_words (bv->size)
3169 * sizeof (bits_word));
3170 ptrdiff_t boolvec_bytes = bool_header_size + word_bytes;
3171 verify (header_size <= bool_header_size);
3172 nwords = (boolvec_bytes - header_size + word_size - 1) / word_size;
3174 else
3175 nwords = ((size & PSEUDOVECTOR_SIZE_MASK)
3176 + ((size & PSEUDOVECTOR_REST_MASK)
3177 >> PSEUDOVECTOR_SIZE_BITS));
3179 else
3180 nwords = size;
3181 return vroundup (header_size + word_size * nwords);
3184 /* Release extra resources still in use by VECTOR, which may be any
3185 vector-like object. For now, this is used just to free data in
3186 font objects. */
3188 static void
3189 cleanup_vector (struct Lisp_Vector *vector)
3191 detect_suspicious_free (vector);
3192 if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FONT)
3193 && ((vector->header.size & PSEUDOVECTOR_SIZE_MASK)
3194 == FONT_OBJECT_MAX))
3196 struct font_driver *drv = ((struct font *) vector)->driver;
3198 /* The font driver might sometimes be NULL, e.g. if Emacs was
3199 interrupted before it had time to set it up. */
3200 if (drv)
3202 /* Attempt to catch subtle bugs like Bug#16140. */
3203 eassert (valid_font_driver (drv));
3204 drv->close ((struct font *) vector);
3209 /* Reclaim space used by unmarked vectors. */
3211 NO_INLINE /* For better stack traces */
3212 static void
3213 sweep_vectors (void)
3215 struct vector_block *block, **bprev = &vector_blocks;
3216 struct large_vector *lv, **lvprev = &large_vectors;
3217 struct Lisp_Vector *vector, *next;
3219 total_vectors = total_vector_slots = total_free_vector_slots = 0;
3220 memset (vector_free_lists, 0, sizeof (vector_free_lists));
3222 /* Looking through vector blocks. */
3224 for (block = vector_blocks; block; block = *bprev)
3226 bool free_this_block = 0;
3227 ptrdiff_t nbytes;
3229 for (vector = (struct Lisp_Vector *) block->data;
3230 VECTOR_IN_BLOCK (vector, block); vector = next)
3232 if (VECTOR_MARKED_P (vector))
3234 VECTOR_UNMARK (vector);
3235 total_vectors++;
3236 nbytes = vector_nbytes (vector);
3237 total_vector_slots += nbytes / word_size;
3238 next = ADVANCE (vector, nbytes);
3240 else
3242 ptrdiff_t total_bytes;
3244 cleanup_vector (vector);
3245 nbytes = vector_nbytes (vector);
3246 total_bytes = nbytes;
3247 next = ADVANCE (vector, nbytes);
3249 /* While NEXT is not marked, try to coalesce with VECTOR,
3250 thus making VECTOR of the largest possible size. */
3252 while (VECTOR_IN_BLOCK (next, block))
3254 if (VECTOR_MARKED_P (next))
3255 break;
3256 cleanup_vector (next);
3257 nbytes = vector_nbytes (next);
3258 total_bytes += nbytes;
3259 next = ADVANCE (next, nbytes);
3262 eassert (total_bytes % roundup_size == 0);
3264 if (vector == (struct Lisp_Vector *) block->data
3265 && !VECTOR_IN_BLOCK (next, block))
3266 /* This block should be freed because all of its
3267 space was coalesced into the only free vector. */
3268 free_this_block = 1;
3269 else
3271 size_t tmp;
3272 SETUP_ON_FREE_LIST (vector, total_bytes, tmp);
3277 if (free_this_block)
3279 *bprev = block->next;
3280 #ifndef GC_MALLOC_CHECK
3281 mem_delete (mem_find (block->data));
3282 #endif
3283 xfree (block);
3285 else
3286 bprev = &block->next;
3289 /* Sweep large vectors. */
3291 for (lv = large_vectors; lv; lv = *lvprev)
3293 vector = large_vector_vec (lv);
3294 if (VECTOR_MARKED_P (vector))
3296 VECTOR_UNMARK (vector);
3297 total_vectors++;
3298 if (vector->header.size & PSEUDOVECTOR_FLAG)
3300 /* All non-bool pseudovectors are small enough to be allocated
3301 from vector blocks. This code should be redesigned if some
3302 pseudovector type grows beyond VBLOCK_BYTES_MAX. */
3303 eassert (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_BOOL_VECTOR));
3304 total_vector_slots += vector_nbytes (vector) / word_size;
3306 else
3307 total_vector_slots
3308 += header_size / word_size + vector->header.size;
3309 lvprev = &lv->next;
3311 else
3313 *lvprev = lv->next;
3314 lisp_free (lv);
3319 /* Value is a pointer to a newly allocated Lisp_Vector structure
3320 with room for LEN Lisp_Objects. */
3322 static struct Lisp_Vector *
3323 allocate_vectorlike (ptrdiff_t len)
3325 struct Lisp_Vector *p;
3327 MALLOC_BLOCK_INPUT;
3329 if (len == 0)
3330 p = XVECTOR (zero_vector);
3331 else
3333 size_t nbytes = header_size + len * word_size;
3335 #ifdef DOUG_LEA_MALLOC
3336 if (!mmap_lisp_allowed_p ())
3337 mallopt (M_MMAP_MAX, 0);
3338 #endif
3340 if (nbytes <= VBLOCK_BYTES_MAX)
3341 p = allocate_vector_from_block (vroundup (nbytes));
3342 else
3344 struct large_vector *lv
3345 = lisp_malloc ((large_vector_offset + header_size
3346 + len * word_size),
3347 MEM_TYPE_VECTORLIKE);
3348 lv->next = large_vectors;
3349 large_vectors = lv;
3350 p = large_vector_vec (lv);
3353 #ifdef DOUG_LEA_MALLOC
3354 if (!mmap_lisp_allowed_p ())
3355 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
3356 #endif
3358 if (find_suspicious_object_in_range (p, (char *) p + nbytes))
3359 emacs_abort ();
3361 consing_since_gc += nbytes;
3362 vector_cells_consed += len;
3365 MALLOC_UNBLOCK_INPUT;
3367 return p;
3371 /* Allocate a vector with LEN slots. */
3373 struct Lisp_Vector *
3374 allocate_vector (EMACS_INT len)
3376 struct Lisp_Vector *v;
3377 ptrdiff_t nbytes_max = min (PTRDIFF_MAX, SIZE_MAX);
3379 if (min ((nbytes_max - header_size) / word_size, MOST_POSITIVE_FIXNUM) < len)
3380 memory_full (SIZE_MAX);
3381 v = allocate_vectorlike (len);
3382 if (len)
3383 v->header.size = len;
3384 return v;
3388 /* Allocate other vector-like structures. */
3390 struct Lisp_Vector *
3391 allocate_pseudovector (int memlen, int lisplen,
3392 int zerolen, enum pvec_type tag)
3394 struct Lisp_Vector *v = allocate_vectorlike (memlen);
3396 /* Catch bogus values. */
3397 eassert (0 <= tag && tag <= PVEC_FONT);
3398 eassert (0 <= lisplen && lisplen <= zerolen && zerolen <= memlen);
3399 eassert (memlen - lisplen <= (1 << PSEUDOVECTOR_REST_BITS) - 1);
3400 eassert (lisplen <= (1 << PSEUDOVECTOR_SIZE_BITS) - 1);
3402 /* Only the first LISPLEN slots will be traced normally by the GC. */
3403 memclear (v->contents, zerolen * word_size);
3404 XSETPVECTYPESIZE (v, tag, lisplen, memlen - lisplen);
3405 return v;
3408 struct buffer *
3409 allocate_buffer (void)
3411 struct buffer *b = lisp_malloc (sizeof *b, MEM_TYPE_BUFFER);
3413 BUFFER_PVEC_INIT (b);
3414 /* Put B on the chain of all buffers including killed ones. */
3415 b->next = all_buffers;
3416 all_buffers = b;
3417 /* Note that the rest fields of B are not initialized. */
3418 return b;
3421 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
3422 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
3423 See also the function `vector'. */)
3424 (Lisp_Object length, Lisp_Object init)
3426 CHECK_NATNUM (length);
3427 struct Lisp_Vector *p = allocate_vector (XFASTINT (length));
3428 for (ptrdiff_t i = 0; i < XFASTINT (length); i++)
3429 p->contents[i] = init;
3430 return make_lisp_ptr (p, Lisp_Vectorlike);
3433 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3434 doc: /* Return a newly created vector with specified arguments as elements.
3435 Any number of arguments, even zero arguments, are allowed.
3436 usage: (vector &rest OBJECTS) */)
3437 (ptrdiff_t nargs, Lisp_Object *args)
3439 Lisp_Object val = make_uninit_vector (nargs);
3440 struct Lisp_Vector *p = XVECTOR (val);
3441 memcpy (p->contents, args, nargs * sizeof *args);
3442 return val;
3445 void
3446 make_byte_code (struct Lisp_Vector *v)
3448 /* Don't allow the global zero_vector to become a byte code object. */
3449 eassert (0 < v->header.size);
3451 if (v->header.size > 1 && STRINGP (v->contents[1])
3452 && STRING_MULTIBYTE (v->contents[1]))
3453 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3454 earlier because they produced a raw 8-bit string for byte-code
3455 and now such a byte-code string is loaded as multibyte while
3456 raw 8-bit characters converted to multibyte form. Thus, now we
3457 must convert them back to the original unibyte form. */
3458 v->contents[1] = Fstring_as_unibyte (v->contents[1]);
3459 XSETPVECTYPE (v, PVEC_COMPILED);
3462 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3463 doc: /* Create a byte-code object with specified arguments as elements.
3464 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3465 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3466 and (optional) INTERACTIVE-SPEC.
3467 The first four arguments are required; at most six have any
3468 significance.
3469 The ARGLIST can be either like the one of `lambda', in which case the arguments
3470 will be dynamically bound before executing the byte code, or it can be an
3471 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3472 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3473 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3474 argument to catch the left-over arguments. If such an integer is used, the
3475 arguments will not be dynamically bound but will be instead pushed on the
3476 stack before executing the byte-code.
3477 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3478 (ptrdiff_t nargs, Lisp_Object *args)
3480 Lisp_Object val = make_uninit_vector (nargs);
3481 struct Lisp_Vector *p = XVECTOR (val);
3483 /* We used to purecopy everything here, if purify-flag was set. This worked
3484 OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
3485 dangerous, since make-byte-code is used during execution to build
3486 closures, so any closure built during the preload phase would end up
3487 copied into pure space, including its free variables, which is sometimes
3488 just wasteful and other times plainly wrong (e.g. those free vars may want
3489 to be setcar'd). */
3491 memcpy (p->contents, args, nargs * sizeof *args);
3492 make_byte_code (p);
3493 XSETCOMPILED (val, p);
3494 return val;
3499 /***********************************************************************
3500 Symbol Allocation
3501 ***********************************************************************/
3503 /* Like struct Lisp_Symbol, but padded so that the size is a multiple
3504 of the required alignment. */
3506 union aligned_Lisp_Symbol
3508 struct Lisp_Symbol s;
3509 unsigned char c[(sizeof (struct Lisp_Symbol) + GCALIGNMENT - 1)
3510 & -GCALIGNMENT];
3513 /* Each symbol_block is just under 1020 bytes long, since malloc
3514 really allocates in units of powers of two and uses 4 bytes for its
3515 own overhead. */
3517 #define SYMBOL_BLOCK_SIZE \
3518 ((1020 - sizeof (struct symbol_block *)) / sizeof (union aligned_Lisp_Symbol))
3520 struct symbol_block
3522 /* Place `symbols' first, to preserve alignment. */
3523 union aligned_Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3524 struct symbol_block *next;
3527 /* Current symbol block and index of first unused Lisp_Symbol
3528 structure in it. */
3530 static struct symbol_block *symbol_block;
3531 static int symbol_block_index = SYMBOL_BLOCK_SIZE;
3532 /* Pointer to the first symbol_block that contains pinned symbols.
3533 Tests for 24.4 showed that at dump-time, Emacs contains about 15K symbols,
3534 10K of which are pinned (and all but 250 of them are interned in obarray),
3535 whereas a "typical session" has in the order of 30K symbols.
3536 `symbol_block_pinned' lets mark_pinned_symbols scan only 15K symbols rather
3537 than 30K to find the 10K symbols we need to mark. */
3538 static struct symbol_block *symbol_block_pinned;
3540 /* List of free symbols. */
3542 static struct Lisp_Symbol *symbol_free_list;
3544 static void
3545 set_symbol_name (Lisp_Object sym, Lisp_Object name)
3547 XSYMBOL (sym)->name = name;
3550 void
3551 init_symbol (Lisp_Object val, Lisp_Object name)
3553 struct Lisp_Symbol *p = XSYMBOL (val);
3554 set_symbol_name (val, name);
3555 set_symbol_plist (val, Qnil);
3556 p->redirect = SYMBOL_PLAINVAL;
3557 SET_SYMBOL_VAL (p, Qunbound);
3558 set_symbol_function (val, Qnil);
3559 set_symbol_next (val, NULL);
3560 p->gcmarkbit = false;
3561 p->interned = SYMBOL_UNINTERNED;
3562 p->constant = 0;
3563 p->declared_special = false;
3564 p->pinned = false;
3567 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3568 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3569 Its value is void, and its function definition and property list are nil. */)
3570 (Lisp_Object name)
3572 Lisp_Object val;
3574 CHECK_STRING (name);
3576 MALLOC_BLOCK_INPUT;
3578 if (symbol_free_list)
3580 XSETSYMBOL (val, symbol_free_list);
3581 symbol_free_list = symbol_free_list->next;
3583 else
3585 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3587 struct symbol_block *new
3588 = lisp_malloc (sizeof *new, MEM_TYPE_SYMBOL);
3589 new->next = symbol_block;
3590 symbol_block = new;
3591 symbol_block_index = 0;
3592 total_free_symbols += SYMBOL_BLOCK_SIZE;
3594 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index].s);
3595 symbol_block_index++;
3598 MALLOC_UNBLOCK_INPUT;
3600 init_symbol (val, name);
3601 consing_since_gc += sizeof (struct Lisp_Symbol);
3602 symbols_consed++;
3603 total_free_symbols--;
3604 return val;
3609 /***********************************************************************
3610 Marker (Misc) Allocation
3611 ***********************************************************************/
3613 /* Like union Lisp_Misc, but padded so that its size is a multiple of
3614 the required alignment. */
3616 union aligned_Lisp_Misc
3618 union Lisp_Misc m;
3619 unsigned char c[(sizeof (union Lisp_Misc) + GCALIGNMENT - 1)
3620 & -GCALIGNMENT];
3623 /* Allocation of markers and other objects that share that structure.
3624 Works like allocation of conses. */
3626 #define MARKER_BLOCK_SIZE \
3627 ((1020 - sizeof (struct marker_block *)) / sizeof (union aligned_Lisp_Misc))
3629 struct marker_block
3631 /* Place `markers' first, to preserve alignment. */
3632 union aligned_Lisp_Misc markers[MARKER_BLOCK_SIZE];
3633 struct marker_block *next;
3636 static struct marker_block *marker_block;
3637 static int marker_block_index = MARKER_BLOCK_SIZE;
3639 static union Lisp_Misc *marker_free_list;
3641 /* Return a newly allocated Lisp_Misc object of specified TYPE. */
3643 static Lisp_Object
3644 allocate_misc (enum Lisp_Misc_Type type)
3646 Lisp_Object val;
3648 MALLOC_BLOCK_INPUT;
3650 if (marker_free_list)
3652 XSETMISC (val, marker_free_list);
3653 marker_free_list = marker_free_list->u_free.chain;
3655 else
3657 if (marker_block_index == MARKER_BLOCK_SIZE)
3659 struct marker_block *new = lisp_malloc (sizeof *new, MEM_TYPE_MISC);
3660 new->next = marker_block;
3661 marker_block = new;
3662 marker_block_index = 0;
3663 total_free_markers += MARKER_BLOCK_SIZE;
3665 XSETMISC (val, &marker_block->markers[marker_block_index].m);
3666 marker_block_index++;
3669 MALLOC_UNBLOCK_INPUT;
3671 --total_free_markers;
3672 consing_since_gc += sizeof (union Lisp_Misc);
3673 misc_objects_consed++;
3674 XMISCANY (val)->type = type;
3675 XMISCANY (val)->gcmarkbit = 0;
3676 return val;
3679 /* Free a Lisp_Misc object. */
3681 void
3682 free_misc (Lisp_Object misc)
3684 XMISCANY (misc)->type = Lisp_Misc_Free;
3685 XMISC (misc)->u_free.chain = marker_free_list;
3686 marker_free_list = XMISC (misc);
3687 consing_since_gc -= sizeof (union Lisp_Misc);
3688 total_free_markers++;
3691 /* Verify properties of Lisp_Save_Value's representation
3692 that are assumed here and elsewhere. */
3694 verify (SAVE_UNUSED == 0);
3695 verify (((SAVE_INTEGER | SAVE_POINTER | SAVE_FUNCPOINTER | SAVE_OBJECT)
3696 >> SAVE_SLOT_BITS)
3697 == 0);
3699 /* Return Lisp_Save_Value objects for the various combinations
3700 that callers need. */
3702 Lisp_Object
3703 make_save_int_int_int (ptrdiff_t a, ptrdiff_t b, ptrdiff_t c)
3705 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3706 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3707 p->save_type = SAVE_TYPE_INT_INT_INT;
3708 p->data[0].integer = a;
3709 p->data[1].integer = b;
3710 p->data[2].integer = c;
3711 return val;
3714 Lisp_Object
3715 make_save_obj_obj_obj_obj (Lisp_Object a, Lisp_Object b, Lisp_Object c,
3716 Lisp_Object d)
3718 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3719 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3720 p->save_type = SAVE_TYPE_OBJ_OBJ_OBJ_OBJ;
3721 p->data[0].object = a;
3722 p->data[1].object = b;
3723 p->data[2].object = c;
3724 p->data[3].object = d;
3725 return val;
3728 Lisp_Object
3729 make_save_ptr (void *a)
3731 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3732 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3733 p->save_type = SAVE_POINTER;
3734 p->data[0].pointer = a;
3735 return val;
3738 Lisp_Object
3739 make_save_ptr_int (void *a, ptrdiff_t b)
3741 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3742 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3743 p->save_type = SAVE_TYPE_PTR_INT;
3744 p->data[0].pointer = a;
3745 p->data[1].integer = b;
3746 return val;
3749 Lisp_Object
3750 make_save_ptr_ptr (void *a, void *b)
3752 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3753 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3754 p->save_type = SAVE_TYPE_PTR_PTR;
3755 p->data[0].pointer = a;
3756 p->data[1].pointer = b;
3757 return val;
3760 Lisp_Object
3761 make_save_funcptr_ptr_obj (void (*a) (void), void *b, Lisp_Object c)
3763 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3764 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3765 p->save_type = SAVE_TYPE_FUNCPTR_PTR_OBJ;
3766 p->data[0].funcpointer = a;
3767 p->data[1].pointer = b;
3768 p->data[2].object = c;
3769 return val;
3772 /* Return a Lisp_Save_Value object that represents an array A
3773 of N Lisp objects. */
3775 Lisp_Object
3776 make_save_memory (Lisp_Object *a, ptrdiff_t n)
3778 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3779 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3780 p->save_type = SAVE_TYPE_MEMORY;
3781 p->data[0].pointer = a;
3782 p->data[1].integer = n;
3783 return val;
3786 /* Free a Lisp_Save_Value object. Do not use this function
3787 if SAVE contains pointer other than returned by xmalloc. */
3789 void
3790 free_save_value (Lisp_Object save)
3792 xfree (XSAVE_POINTER (save, 0));
3793 free_misc (save);
3796 /* Return a Lisp_Misc_Overlay object with specified START, END and PLIST. */
3798 Lisp_Object
3799 build_overlay (Lisp_Object start, Lisp_Object end, Lisp_Object plist)
3801 register Lisp_Object overlay;
3803 overlay = allocate_misc (Lisp_Misc_Overlay);
3804 OVERLAY_START (overlay) = start;
3805 OVERLAY_END (overlay) = end;
3806 set_overlay_plist (overlay, plist);
3807 XOVERLAY (overlay)->next = NULL;
3808 return overlay;
3811 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3812 doc: /* Return a newly allocated marker which does not point at any place. */)
3813 (void)
3815 register Lisp_Object val;
3816 register struct Lisp_Marker *p;
3818 val = allocate_misc (Lisp_Misc_Marker);
3819 p = XMARKER (val);
3820 p->buffer = 0;
3821 p->bytepos = 0;
3822 p->charpos = 0;
3823 p->next = NULL;
3824 p->insertion_type = 0;
3825 p->need_adjustment = 0;
3826 return val;
3829 /* Return a newly allocated marker which points into BUF
3830 at character position CHARPOS and byte position BYTEPOS. */
3832 Lisp_Object
3833 build_marker (struct buffer *buf, ptrdiff_t charpos, ptrdiff_t bytepos)
3835 Lisp_Object obj;
3836 struct Lisp_Marker *m;
3838 /* No dead buffers here. */
3839 eassert (BUFFER_LIVE_P (buf));
3841 /* Every character is at least one byte. */
3842 eassert (charpos <= bytepos);
3844 obj = allocate_misc (Lisp_Misc_Marker);
3845 m = XMARKER (obj);
3846 m->buffer = buf;
3847 m->charpos = charpos;
3848 m->bytepos = bytepos;
3849 m->insertion_type = 0;
3850 m->need_adjustment = 0;
3851 m->next = BUF_MARKERS (buf);
3852 BUF_MARKERS (buf) = m;
3853 return obj;
3856 /* Put MARKER back on the free list after using it temporarily. */
3858 void
3859 free_marker (Lisp_Object marker)
3861 unchain_marker (XMARKER (marker));
3862 free_misc (marker);
3866 /* Return a newly created vector or string with specified arguments as
3867 elements. If all the arguments are characters that can fit
3868 in a string of events, make a string; otherwise, make a vector.
3870 Any number of arguments, even zero arguments, are allowed. */
3872 Lisp_Object
3873 make_event_array (ptrdiff_t nargs, Lisp_Object *args)
3875 ptrdiff_t i;
3877 for (i = 0; i < nargs; i++)
3878 /* The things that fit in a string
3879 are characters that are in 0...127,
3880 after discarding the meta bit and all the bits above it. */
3881 if (!INTEGERP (args[i])
3882 || (XINT (args[i]) & ~(-CHAR_META)) >= 0200)
3883 return Fvector (nargs, args);
3885 /* Since the loop exited, we know that all the things in it are
3886 characters, so we can make a string. */
3888 Lisp_Object result;
3890 result = Fmake_string (make_number (nargs), make_number (0));
3891 for (i = 0; i < nargs; i++)
3893 SSET (result, i, XINT (args[i]));
3894 /* Move the meta bit to the right place for a string char. */
3895 if (XINT (args[i]) & CHAR_META)
3896 SSET (result, i, SREF (result, i) | 0x80);
3899 return result;
3903 #ifdef HAVE_MODULES
3904 /* Create a new module user ptr object. */
3905 Lisp_Object
3906 make_user_ptr (void (*finalizer) (void *), void *p)
3908 Lisp_Object obj;
3909 struct Lisp_User_Ptr *uptr;
3911 obj = allocate_misc (Lisp_Misc_User_Ptr);
3912 uptr = XUSER_PTR (obj);
3913 uptr->finalizer = finalizer;
3914 uptr->p = p;
3915 return obj;
3918 #endif
3920 static void
3921 init_finalizer_list (struct Lisp_Finalizer *head)
3923 head->prev = head->next = head;
3926 /* Insert FINALIZER before ELEMENT. */
3928 static void
3929 finalizer_insert (struct Lisp_Finalizer *element,
3930 struct Lisp_Finalizer *finalizer)
3932 eassert (finalizer->prev == NULL);
3933 eassert (finalizer->next == NULL);
3934 finalizer->next = element;
3935 finalizer->prev = element->prev;
3936 finalizer->prev->next = finalizer;
3937 element->prev = finalizer;
3940 static void
3941 unchain_finalizer (struct Lisp_Finalizer *finalizer)
3943 if (finalizer->prev != NULL)
3945 eassert (finalizer->next != NULL);
3946 finalizer->prev->next = finalizer->next;
3947 finalizer->next->prev = finalizer->prev;
3948 finalizer->prev = finalizer->next = NULL;
3952 static void
3953 mark_finalizer_list (struct Lisp_Finalizer *head)
3955 for (struct Lisp_Finalizer *finalizer = head->next;
3956 finalizer != head;
3957 finalizer = finalizer->next)
3959 finalizer->base.gcmarkbit = true;
3960 mark_object (finalizer->function);
3964 /* Move doomed finalizers to list DEST from list SRC. A doomed
3965 finalizer is one that is not GC-reachable and whose
3966 finalizer->function is non-nil. */
3968 static void
3969 queue_doomed_finalizers (struct Lisp_Finalizer *dest,
3970 struct Lisp_Finalizer *src)
3972 struct Lisp_Finalizer *finalizer = src->next;
3973 while (finalizer != src)
3975 struct Lisp_Finalizer *next = finalizer->next;
3976 if (!finalizer->base.gcmarkbit && !NILP (finalizer->function))
3978 unchain_finalizer (finalizer);
3979 finalizer_insert (dest, finalizer);
3982 finalizer = next;
3986 static Lisp_Object
3987 run_finalizer_handler (Lisp_Object args)
3989 add_to_log ("finalizer failed: %S", args);
3990 return Qnil;
3993 static void
3994 run_finalizer_function (Lisp_Object function)
3996 ptrdiff_t count = SPECPDL_INDEX ();
3998 specbind (Qinhibit_quit, Qt);
3999 internal_condition_case_1 (call0, function, Qt, run_finalizer_handler);
4000 unbind_to (count, Qnil);
4003 static void
4004 run_finalizers (struct Lisp_Finalizer *finalizers)
4006 struct Lisp_Finalizer *finalizer;
4007 Lisp_Object function;
4009 while (finalizers->next != finalizers)
4011 finalizer = finalizers->next;
4012 eassert (finalizer->base.type == Lisp_Misc_Finalizer);
4013 unchain_finalizer (finalizer);
4014 function = finalizer->function;
4015 if (!NILP (function))
4017 finalizer->function = Qnil;
4018 run_finalizer_function (function);
4023 DEFUN ("make-finalizer", Fmake_finalizer, Smake_finalizer, 1, 1, 0,
4024 doc: /* Make a finalizer that will run FUNCTION.
4025 FUNCTION will be called after garbage collection when the returned
4026 finalizer object becomes unreachable. If the finalizer object is
4027 reachable only through references from finalizer objects, it does not
4028 count as reachable for the purpose of deciding whether to run
4029 FUNCTION. FUNCTION will be run once per finalizer object. */)
4030 (Lisp_Object function)
4032 Lisp_Object val = allocate_misc (Lisp_Misc_Finalizer);
4033 struct Lisp_Finalizer *finalizer = XFINALIZER (val);
4034 finalizer->function = function;
4035 finalizer->prev = finalizer->next = NULL;
4036 finalizer_insert (&finalizers, finalizer);
4037 return val;
4041 /************************************************************************
4042 Memory Full Handling
4043 ************************************************************************/
4046 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
4047 there may have been size_t overflow so that malloc was never
4048 called, or perhaps malloc was invoked successfully but the
4049 resulting pointer had problems fitting into a tagged EMACS_INT. In
4050 either case this counts as memory being full even though malloc did
4051 not fail. */
4053 void
4054 memory_full (size_t nbytes)
4056 /* Do not go into hysterics merely because a large request failed. */
4057 bool enough_free_memory = 0;
4058 if (SPARE_MEMORY < nbytes)
4060 void *p;
4062 MALLOC_BLOCK_INPUT;
4063 p = malloc (SPARE_MEMORY);
4064 if (p)
4066 free (p);
4067 enough_free_memory = 1;
4069 MALLOC_UNBLOCK_INPUT;
4072 if (! enough_free_memory)
4074 int i;
4076 Vmemory_full = Qt;
4078 memory_full_cons_threshold = sizeof (struct cons_block);
4080 /* The first time we get here, free the spare memory. */
4081 for (i = 0; i < ARRAYELTS (spare_memory); i++)
4082 if (spare_memory[i])
4084 if (i == 0)
4085 free (spare_memory[i]);
4086 else if (i >= 1 && i <= 4)
4087 lisp_align_free (spare_memory[i]);
4088 else
4089 lisp_free (spare_memory[i]);
4090 spare_memory[i] = 0;
4094 /* This used to call error, but if we've run out of memory, we could
4095 get infinite recursion trying to build the string. */
4096 xsignal (Qnil, Vmemory_signal_data);
4099 /* If we released our reserve (due to running out of memory),
4100 and we have a fair amount free once again,
4101 try to set aside another reserve in case we run out once more.
4103 This is called when a relocatable block is freed in ralloc.c,
4104 and also directly from this file, in case we're not using ralloc.c. */
4106 void
4107 refill_memory_reserve (void)
4109 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
4110 if (spare_memory[0] == 0)
4111 spare_memory[0] = malloc (SPARE_MEMORY);
4112 if (spare_memory[1] == 0)
4113 spare_memory[1] = lisp_align_malloc (sizeof (struct cons_block),
4114 MEM_TYPE_SPARE);
4115 if (spare_memory[2] == 0)
4116 spare_memory[2] = lisp_align_malloc (sizeof (struct cons_block),
4117 MEM_TYPE_SPARE);
4118 if (spare_memory[3] == 0)
4119 spare_memory[3] = lisp_align_malloc (sizeof (struct cons_block),
4120 MEM_TYPE_SPARE);
4121 if (spare_memory[4] == 0)
4122 spare_memory[4] = lisp_align_malloc (sizeof (struct cons_block),
4123 MEM_TYPE_SPARE);
4124 if (spare_memory[5] == 0)
4125 spare_memory[5] = lisp_malloc (sizeof (struct string_block),
4126 MEM_TYPE_SPARE);
4127 if (spare_memory[6] == 0)
4128 spare_memory[6] = lisp_malloc (sizeof (struct string_block),
4129 MEM_TYPE_SPARE);
4130 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
4131 Vmemory_full = Qnil;
4132 #endif
4135 /************************************************************************
4136 C Stack Marking
4137 ************************************************************************/
4139 /* Conservative C stack marking requires a method to identify possibly
4140 live Lisp objects given a pointer value. We do this by keeping
4141 track of blocks of Lisp data that are allocated in a red-black tree
4142 (see also the comment of mem_node which is the type of nodes in
4143 that tree). Function lisp_malloc adds information for an allocated
4144 block to the red-black tree with calls to mem_insert, and function
4145 lisp_free removes it with mem_delete. Functions live_string_p etc
4146 call mem_find to lookup information about a given pointer in the
4147 tree, and use that to determine if the pointer points to a Lisp
4148 object or not. */
4150 /* Initialize this part of alloc.c. */
4152 static void
4153 mem_init (void)
4155 mem_z.left = mem_z.right = MEM_NIL;
4156 mem_z.parent = NULL;
4157 mem_z.color = MEM_BLACK;
4158 mem_z.start = mem_z.end = NULL;
4159 mem_root = MEM_NIL;
4163 /* Value is a pointer to the mem_node containing START. Value is
4164 MEM_NIL if there is no node in the tree containing START. */
4166 static struct mem_node *
4167 mem_find (void *start)
4169 struct mem_node *p;
4171 if (start < min_heap_address || start > max_heap_address)
4172 return MEM_NIL;
4174 /* Make the search always successful to speed up the loop below. */
4175 mem_z.start = start;
4176 mem_z.end = (char *) start + 1;
4178 p = mem_root;
4179 while (start < p->start || start >= p->end)
4180 p = start < p->start ? p->left : p->right;
4181 return p;
4185 /* Insert a new node into the tree for a block of memory with start
4186 address START, end address END, and type TYPE. Value is a
4187 pointer to the node that was inserted. */
4189 static struct mem_node *
4190 mem_insert (void *start, void *end, enum mem_type type)
4192 struct mem_node *c, *parent, *x;
4194 if (min_heap_address == NULL || start < min_heap_address)
4195 min_heap_address = start;
4196 if (max_heap_address == NULL || end > max_heap_address)
4197 max_heap_address = end;
4199 /* See where in the tree a node for START belongs. In this
4200 particular application, it shouldn't happen that a node is already
4201 present. For debugging purposes, let's check that. */
4202 c = mem_root;
4203 parent = NULL;
4205 while (c != MEM_NIL)
4207 parent = c;
4208 c = start < c->start ? c->left : c->right;
4211 /* Create a new node. */
4212 #ifdef GC_MALLOC_CHECK
4213 x = malloc (sizeof *x);
4214 if (x == NULL)
4215 emacs_abort ();
4216 #else
4217 x = xmalloc (sizeof *x);
4218 #endif
4219 x->start = start;
4220 x->end = end;
4221 x->type = type;
4222 x->parent = parent;
4223 x->left = x->right = MEM_NIL;
4224 x->color = MEM_RED;
4226 /* Insert it as child of PARENT or install it as root. */
4227 if (parent)
4229 if (start < parent->start)
4230 parent->left = x;
4231 else
4232 parent->right = x;
4234 else
4235 mem_root = x;
4237 /* Re-establish red-black tree properties. */
4238 mem_insert_fixup (x);
4240 return x;
4244 /* Re-establish the red-black properties of the tree, and thereby
4245 balance the tree, after node X has been inserted; X is always red. */
4247 static void
4248 mem_insert_fixup (struct mem_node *x)
4250 while (x != mem_root && x->parent->color == MEM_RED)
4252 /* X is red and its parent is red. This is a violation of
4253 red-black tree property #3. */
4255 if (x->parent == x->parent->parent->left)
4257 /* We're on the left side of our grandparent, and Y is our
4258 "uncle". */
4259 struct mem_node *y = x->parent->parent->right;
4261 if (y->color == MEM_RED)
4263 /* Uncle and parent are red but should be black because
4264 X is red. Change the colors accordingly and proceed
4265 with the grandparent. */
4266 x->parent->color = MEM_BLACK;
4267 y->color = MEM_BLACK;
4268 x->parent->parent->color = MEM_RED;
4269 x = x->parent->parent;
4271 else
4273 /* Parent and uncle have different colors; parent is
4274 red, uncle is black. */
4275 if (x == x->parent->right)
4277 x = x->parent;
4278 mem_rotate_left (x);
4281 x->parent->color = MEM_BLACK;
4282 x->parent->parent->color = MEM_RED;
4283 mem_rotate_right (x->parent->parent);
4286 else
4288 /* This is the symmetrical case of above. */
4289 struct mem_node *y = x->parent->parent->left;
4291 if (y->color == MEM_RED)
4293 x->parent->color = MEM_BLACK;
4294 y->color = MEM_BLACK;
4295 x->parent->parent->color = MEM_RED;
4296 x = x->parent->parent;
4298 else
4300 if (x == x->parent->left)
4302 x = x->parent;
4303 mem_rotate_right (x);
4306 x->parent->color = MEM_BLACK;
4307 x->parent->parent->color = MEM_RED;
4308 mem_rotate_left (x->parent->parent);
4313 /* The root may have been changed to red due to the algorithm. Set
4314 it to black so that property #5 is satisfied. */
4315 mem_root->color = MEM_BLACK;
4319 /* (x) (y)
4320 / \ / \
4321 a (y) ===> (x) c
4322 / \ / \
4323 b c a b */
4325 static void
4326 mem_rotate_left (struct mem_node *x)
4328 struct mem_node *y;
4330 /* Turn y's left sub-tree into x's right sub-tree. */
4331 y = x->right;
4332 x->right = y->left;
4333 if (y->left != MEM_NIL)
4334 y->left->parent = x;
4336 /* Y's parent was x's parent. */
4337 if (y != MEM_NIL)
4338 y->parent = x->parent;
4340 /* Get the parent to point to y instead of x. */
4341 if (x->parent)
4343 if (x == x->parent->left)
4344 x->parent->left = y;
4345 else
4346 x->parent->right = y;
4348 else
4349 mem_root = y;
4351 /* Put x on y's left. */
4352 y->left = x;
4353 if (x != MEM_NIL)
4354 x->parent = y;
4358 /* (x) (Y)
4359 / \ / \
4360 (y) c ===> a (x)
4361 / \ / \
4362 a b b c */
4364 static void
4365 mem_rotate_right (struct mem_node *x)
4367 struct mem_node *y = x->left;
4369 x->left = y->right;
4370 if (y->right != MEM_NIL)
4371 y->right->parent = x;
4373 if (y != MEM_NIL)
4374 y->parent = x->parent;
4375 if (x->parent)
4377 if (x == x->parent->right)
4378 x->parent->right = y;
4379 else
4380 x->parent->left = y;
4382 else
4383 mem_root = y;
4385 y->right = x;
4386 if (x != MEM_NIL)
4387 x->parent = y;
4391 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
4393 static void
4394 mem_delete (struct mem_node *z)
4396 struct mem_node *x, *y;
4398 if (!z || z == MEM_NIL)
4399 return;
4401 if (z->left == MEM_NIL || z->right == MEM_NIL)
4402 y = z;
4403 else
4405 y = z->right;
4406 while (y->left != MEM_NIL)
4407 y = y->left;
4410 if (y->left != MEM_NIL)
4411 x = y->left;
4412 else
4413 x = y->right;
4415 x->parent = y->parent;
4416 if (y->parent)
4418 if (y == y->parent->left)
4419 y->parent->left = x;
4420 else
4421 y->parent->right = x;
4423 else
4424 mem_root = x;
4426 if (y != z)
4428 z->start = y->start;
4429 z->end = y->end;
4430 z->type = y->type;
4433 if (y->color == MEM_BLACK)
4434 mem_delete_fixup (x);
4436 #ifdef GC_MALLOC_CHECK
4437 free (y);
4438 #else
4439 xfree (y);
4440 #endif
4444 /* Re-establish the red-black properties of the tree, after a
4445 deletion. */
4447 static void
4448 mem_delete_fixup (struct mem_node *x)
4450 while (x != mem_root && x->color == MEM_BLACK)
4452 if (x == x->parent->left)
4454 struct mem_node *w = x->parent->right;
4456 if (w->color == MEM_RED)
4458 w->color = MEM_BLACK;
4459 x->parent->color = MEM_RED;
4460 mem_rotate_left (x->parent);
4461 w = x->parent->right;
4464 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
4466 w->color = MEM_RED;
4467 x = x->parent;
4469 else
4471 if (w->right->color == MEM_BLACK)
4473 w->left->color = MEM_BLACK;
4474 w->color = MEM_RED;
4475 mem_rotate_right (w);
4476 w = x->parent->right;
4478 w->color = x->parent->color;
4479 x->parent->color = MEM_BLACK;
4480 w->right->color = MEM_BLACK;
4481 mem_rotate_left (x->parent);
4482 x = mem_root;
4485 else
4487 struct mem_node *w = x->parent->left;
4489 if (w->color == MEM_RED)
4491 w->color = MEM_BLACK;
4492 x->parent->color = MEM_RED;
4493 mem_rotate_right (x->parent);
4494 w = x->parent->left;
4497 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
4499 w->color = MEM_RED;
4500 x = x->parent;
4502 else
4504 if (w->left->color == MEM_BLACK)
4506 w->right->color = MEM_BLACK;
4507 w->color = MEM_RED;
4508 mem_rotate_left (w);
4509 w = x->parent->left;
4512 w->color = x->parent->color;
4513 x->parent->color = MEM_BLACK;
4514 w->left->color = MEM_BLACK;
4515 mem_rotate_right (x->parent);
4516 x = mem_root;
4521 x->color = MEM_BLACK;
4525 /* Value is non-zero if P is a pointer to a live Lisp string on
4526 the heap. M is a pointer to the mem_block for P. */
4528 static bool
4529 live_string_p (struct mem_node *m, void *p)
4531 if (m->type == MEM_TYPE_STRING)
4533 struct string_block *b = m->start;
4534 ptrdiff_t offset = (char *) p - (char *) &b->strings[0];
4536 /* P must point to the start of a Lisp_String structure, and it
4537 must not be on the free-list. */
4538 return (offset >= 0
4539 && offset % sizeof b->strings[0] == 0
4540 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
4541 && ((struct Lisp_String *) p)->data != NULL);
4543 else
4544 return 0;
4548 /* Value is non-zero if P is a pointer to a live Lisp cons on
4549 the heap. M is a pointer to the mem_block for P. */
4551 static bool
4552 live_cons_p (struct mem_node *m, void *p)
4554 if (m->type == MEM_TYPE_CONS)
4556 struct cons_block *b = m->start;
4557 ptrdiff_t offset = (char *) p - (char *) &b->conses[0];
4559 /* P must point to the start of a Lisp_Cons, not be
4560 one of the unused cells in the current cons block,
4561 and not be on the free-list. */
4562 return (offset >= 0
4563 && offset % sizeof b->conses[0] == 0
4564 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
4565 && (b != cons_block
4566 || offset / sizeof b->conses[0] < cons_block_index)
4567 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
4569 else
4570 return 0;
4574 /* Value is non-zero if P is a pointer to a live Lisp symbol on
4575 the heap. M is a pointer to the mem_block for P. */
4577 static bool
4578 live_symbol_p (struct mem_node *m, void *p)
4580 if (m->type == MEM_TYPE_SYMBOL)
4582 struct symbol_block *b = m->start;
4583 ptrdiff_t offset = (char *) p - (char *) &b->symbols[0];
4585 /* P must point to the start of a Lisp_Symbol, not be
4586 one of the unused cells in the current symbol block,
4587 and not be on the free-list. */
4588 return (offset >= 0
4589 && offset % sizeof b->symbols[0] == 0
4590 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
4591 && (b != symbol_block
4592 || offset / sizeof b->symbols[0] < symbol_block_index)
4593 && !EQ (((struct Lisp_Symbol *)p)->function, Vdead));
4595 else
4596 return 0;
4600 /* Value is non-zero if P is a pointer to a live Lisp float on
4601 the heap. M is a pointer to the mem_block for P. */
4603 static bool
4604 live_float_p (struct mem_node *m, void *p)
4606 if (m->type == MEM_TYPE_FLOAT)
4608 struct float_block *b = m->start;
4609 ptrdiff_t offset = (char *) p - (char *) &b->floats[0];
4611 /* P must point to the start of a Lisp_Float and not be
4612 one of the unused cells in the current float block. */
4613 return (offset >= 0
4614 && offset % sizeof b->floats[0] == 0
4615 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
4616 && (b != float_block
4617 || offset / sizeof b->floats[0] < float_block_index));
4619 else
4620 return 0;
4624 /* Value is non-zero if P is a pointer to a live Lisp Misc on
4625 the heap. M is a pointer to the mem_block for P. */
4627 static bool
4628 live_misc_p (struct mem_node *m, void *p)
4630 if (m->type == MEM_TYPE_MISC)
4632 struct marker_block *b = m->start;
4633 ptrdiff_t offset = (char *) p - (char *) &b->markers[0];
4635 /* P must point to the start of a Lisp_Misc, not be
4636 one of the unused cells in the current misc block,
4637 and not be on the free-list. */
4638 return (offset >= 0
4639 && offset % sizeof b->markers[0] == 0
4640 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
4641 && (b != marker_block
4642 || offset / sizeof b->markers[0] < marker_block_index)
4643 && ((union Lisp_Misc *) p)->u_any.type != Lisp_Misc_Free);
4645 else
4646 return 0;
4650 /* Value is non-zero if P is a pointer to a live vector-like object.
4651 M is a pointer to the mem_block for P. */
4653 static bool
4654 live_vector_p (struct mem_node *m, void *p)
4656 if (m->type == MEM_TYPE_VECTOR_BLOCK)
4658 /* This memory node corresponds to a vector block. */
4659 struct vector_block *block = m->start;
4660 struct Lisp_Vector *vector = (struct Lisp_Vector *) block->data;
4662 /* P is in the block's allocation range. Scan the block
4663 up to P and see whether P points to the start of some
4664 vector which is not on a free list. FIXME: check whether
4665 some allocation patterns (probably a lot of short vectors)
4666 may cause a substantial overhead of this loop. */
4667 while (VECTOR_IN_BLOCK (vector, block)
4668 && vector <= (struct Lisp_Vector *) p)
4670 if (!PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FREE) && vector == p)
4671 return 1;
4672 else
4673 vector = ADVANCE (vector, vector_nbytes (vector));
4676 else if (m->type == MEM_TYPE_VECTORLIKE && p == large_vector_vec (m->start))
4677 /* This memory node corresponds to a large vector. */
4678 return 1;
4679 return 0;
4683 /* Value is non-zero if P is a pointer to a live buffer. M is a
4684 pointer to the mem_block for P. */
4686 static bool
4687 live_buffer_p (struct mem_node *m, void *p)
4689 /* P must point to the start of the block, and the buffer
4690 must not have been killed. */
4691 return (m->type == MEM_TYPE_BUFFER
4692 && p == m->start
4693 && !NILP (((struct buffer *) p)->name_));
4696 /* Mark OBJ if we can prove it's a Lisp_Object. */
4698 static void
4699 mark_maybe_object (Lisp_Object obj)
4701 #if USE_VALGRIND
4702 if (valgrind_p)
4703 VALGRIND_MAKE_MEM_DEFINED (&obj, sizeof (obj));
4704 #endif
4706 if (INTEGERP (obj))
4707 return;
4709 void *po = XPNTR (obj);
4710 struct mem_node *m = mem_find (po);
4712 if (m != MEM_NIL)
4714 bool mark_p = false;
4716 switch (XTYPE (obj))
4718 case Lisp_String:
4719 mark_p = (live_string_p (m, po)
4720 && !STRING_MARKED_P ((struct Lisp_String *) po));
4721 break;
4723 case Lisp_Cons:
4724 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4725 break;
4727 case Lisp_Symbol:
4728 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4729 break;
4731 case Lisp_Float:
4732 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4733 break;
4735 case Lisp_Vectorlike:
4736 /* Note: can't check BUFFERP before we know it's a
4737 buffer because checking that dereferences the pointer
4738 PO which might point anywhere. */
4739 if (live_vector_p (m, po))
4740 mark_p = !SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4741 else if (live_buffer_p (m, po))
4742 mark_p = BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4743 break;
4745 case Lisp_Misc:
4746 mark_p = (live_misc_p (m, po) && !XMISCANY (obj)->gcmarkbit);
4747 break;
4749 default:
4750 break;
4753 if (mark_p)
4754 mark_object (obj);
4758 /* Return true if P can point to Lisp data, and false otherwise.
4759 Symbols are implemented via offsets not pointers, but the offsets
4760 are also multiples of GCALIGNMENT. */
4762 static bool
4763 maybe_lisp_pointer (void *p)
4765 return (uintptr_t) p % GCALIGNMENT == 0;
4768 #ifndef HAVE_MODULES
4769 enum { HAVE_MODULES = false };
4770 #endif
4772 /* If P points to Lisp data, mark that as live if it isn't already
4773 marked. */
4775 static void
4776 mark_maybe_pointer (void *p)
4778 struct mem_node *m;
4780 #if USE_VALGRIND
4781 if (valgrind_p)
4782 VALGRIND_MAKE_MEM_DEFINED (&p, sizeof (p));
4783 #endif
4785 if (sizeof (Lisp_Object) == sizeof (void *) || !HAVE_MODULES)
4787 if (!maybe_lisp_pointer (p))
4788 return;
4790 else
4792 /* For the wide-int case, also mark emacs_value tagged pointers,
4793 which can be generated by emacs-module.c's value_to_lisp. */
4794 p = (void *) ((uintptr_t) p & ~(GCALIGNMENT - 1));
4797 m = mem_find (p);
4798 if (m != MEM_NIL)
4800 Lisp_Object obj = Qnil;
4802 switch (m->type)
4804 case MEM_TYPE_NON_LISP:
4805 case MEM_TYPE_SPARE:
4806 /* Nothing to do; not a pointer to Lisp memory. */
4807 break;
4809 case MEM_TYPE_BUFFER:
4810 if (live_buffer_p (m, p) && !VECTOR_MARKED_P ((struct buffer *)p))
4811 XSETVECTOR (obj, p);
4812 break;
4814 case MEM_TYPE_CONS:
4815 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4816 XSETCONS (obj, p);
4817 break;
4819 case MEM_TYPE_STRING:
4820 if (live_string_p (m, p)
4821 && !STRING_MARKED_P ((struct Lisp_String *) p))
4822 XSETSTRING (obj, p);
4823 break;
4825 case MEM_TYPE_MISC:
4826 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4827 XSETMISC (obj, p);
4828 break;
4830 case MEM_TYPE_SYMBOL:
4831 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4832 XSETSYMBOL (obj, p);
4833 break;
4835 case MEM_TYPE_FLOAT:
4836 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4837 XSETFLOAT (obj, p);
4838 break;
4840 case MEM_TYPE_VECTORLIKE:
4841 case MEM_TYPE_VECTOR_BLOCK:
4842 if (live_vector_p (m, p))
4844 Lisp_Object tem;
4845 XSETVECTOR (tem, p);
4846 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4847 obj = tem;
4849 break;
4851 default:
4852 emacs_abort ();
4855 if (!NILP (obj))
4856 mark_object (obj);
4861 /* Alignment of pointer values. Use alignof, as it sometimes returns
4862 a smaller alignment than GCC's __alignof__ and mark_memory might
4863 miss objects if __alignof__ were used. */
4864 #define GC_POINTER_ALIGNMENT alignof (void *)
4866 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4867 or END+OFFSET..START. */
4869 static void ATTRIBUTE_NO_SANITIZE_ADDRESS
4870 mark_memory (void *start, void *end)
4872 char *pp;
4874 /* Make START the pointer to the start of the memory region,
4875 if it isn't already. */
4876 if (end < start)
4878 void *tem = start;
4879 start = end;
4880 end = tem;
4883 eassert (((uintptr_t) start) % GC_POINTER_ALIGNMENT == 0);
4885 /* Mark Lisp data pointed to. This is necessary because, in some
4886 situations, the C compiler optimizes Lisp objects away, so that
4887 only a pointer to them remains. Example:
4889 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4892 Lisp_Object obj = build_string ("test");
4893 struct Lisp_String *s = XSTRING (obj);
4894 Fgarbage_collect ();
4895 fprintf (stderr, "test '%s'\n", s->data);
4896 return Qnil;
4899 Here, `obj' isn't really used, and the compiler optimizes it
4900 away. The only reference to the life string is through the
4901 pointer `s'. */
4903 for (pp = start; (void *) pp < end; pp += GC_POINTER_ALIGNMENT)
4905 mark_maybe_pointer (*(void **) pp);
4906 mark_maybe_object (*(Lisp_Object *) pp);
4910 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4912 static bool setjmp_tested_p;
4913 static int longjmps_done;
4915 #define SETJMP_WILL_LIKELY_WORK "\
4917 Emacs garbage collector has been changed to use conservative stack\n\
4918 marking. Emacs has determined that the method it uses to do the\n\
4919 marking will likely work on your system, but this isn't sure.\n\
4921 If you are a system-programmer, or can get the help of a local wizard\n\
4922 who is, please take a look at the function mark_stack in alloc.c, and\n\
4923 verify that the methods used are appropriate for your system.\n\
4925 Please mail the result to <emacs-devel@gnu.org>.\n\
4928 #define SETJMP_WILL_NOT_WORK "\
4930 Emacs garbage collector has been changed to use conservative stack\n\
4931 marking. Emacs has determined that the default method it uses to do the\n\
4932 marking will not work on your system. We will need a system-dependent\n\
4933 solution for your system.\n\
4935 Please take a look at the function mark_stack in alloc.c, and\n\
4936 try to find a way to make it work on your system.\n\
4938 Note that you may get false negatives, depending on the compiler.\n\
4939 In particular, you need to use -O with GCC for this test.\n\
4941 Please mail the result to <emacs-devel@gnu.org>.\n\
4945 /* Perform a quick check if it looks like setjmp saves registers in a
4946 jmp_buf. Print a message to stderr saying so. When this test
4947 succeeds, this is _not_ a proof that setjmp is sufficient for
4948 conservative stack marking. Only the sources or a disassembly
4949 can prove that. */
4951 static void
4952 test_setjmp (void)
4954 char buf[10];
4955 register int x;
4956 sys_jmp_buf jbuf;
4958 /* Arrange for X to be put in a register. */
4959 sprintf (buf, "1");
4960 x = strlen (buf);
4961 x = 2 * x - 1;
4963 sys_setjmp (jbuf);
4964 if (longjmps_done == 1)
4966 /* Came here after the longjmp at the end of the function.
4968 If x == 1, the longjmp has restored the register to its
4969 value before the setjmp, and we can hope that setjmp
4970 saves all such registers in the jmp_buf, although that
4971 isn't sure.
4973 For other values of X, either something really strange is
4974 taking place, or the setjmp just didn't save the register. */
4976 if (x == 1)
4977 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4978 else
4980 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4981 exit (1);
4985 ++longjmps_done;
4986 x = 2;
4987 if (longjmps_done == 1)
4988 sys_longjmp (jbuf, 1);
4991 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4994 /* Mark live Lisp objects on the C stack.
4996 There are several system-dependent problems to consider when
4997 porting this to new architectures:
4999 Processor Registers
5001 We have to mark Lisp objects in CPU registers that can hold local
5002 variables or are used to pass parameters.
5004 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
5005 something that either saves relevant registers on the stack, or
5006 calls mark_maybe_object passing it each register's contents.
5008 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
5009 implementation assumes that calling setjmp saves registers we need
5010 to see in a jmp_buf which itself lies on the stack. This doesn't
5011 have to be true! It must be verified for each system, possibly
5012 by taking a look at the source code of setjmp.
5014 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
5015 can use it as a machine independent method to store all registers
5016 to the stack. In this case the macros described in the previous
5017 two paragraphs are not used.
5019 Stack Layout
5021 Architectures differ in the way their processor stack is organized.
5022 For example, the stack might look like this
5024 +----------------+
5025 | Lisp_Object | size = 4
5026 +----------------+
5027 | something else | size = 2
5028 +----------------+
5029 | Lisp_Object | size = 4
5030 +----------------+
5031 | ... |
5033 In such a case, not every Lisp_Object will be aligned equally. To
5034 find all Lisp_Object on the stack it won't be sufficient to walk
5035 the stack in steps of 4 bytes. Instead, two passes will be
5036 necessary, one starting at the start of the stack, and a second
5037 pass starting at the start of the stack + 2. Likewise, if the
5038 minimal alignment of Lisp_Objects on the stack is 1, four passes
5039 would be necessary, each one starting with one byte more offset
5040 from the stack start. */
5042 static void
5043 mark_stack (void *end)
5046 /* This assumes that the stack is a contiguous region in memory. If
5047 that's not the case, something has to be done here to iterate
5048 over the stack segments. */
5049 mark_memory (stack_base, end);
5051 /* Allow for marking a secondary stack, like the register stack on the
5052 ia64. */
5053 #ifdef GC_MARK_SECONDARY_STACK
5054 GC_MARK_SECONDARY_STACK ();
5055 #endif
5058 static bool
5059 c_symbol_p (struct Lisp_Symbol *sym)
5061 char *lispsym_ptr = (char *) lispsym;
5062 char *sym_ptr = (char *) sym;
5063 ptrdiff_t lispsym_offset = sym_ptr - lispsym_ptr;
5064 return 0 <= lispsym_offset && lispsym_offset < sizeof lispsym;
5067 /* Determine whether it is safe to access memory at address P. */
5068 static int
5069 valid_pointer_p (void *p)
5071 #ifdef WINDOWSNT
5072 return w32_valid_pointer_p (p, 16);
5073 #else
5075 if (ADDRESS_SANITIZER)
5076 return p ? -1 : 0;
5078 int fd[2];
5080 /* Obviously, we cannot just access it (we would SEGV trying), so we
5081 trick the o/s to tell us whether p is a valid pointer.
5082 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
5083 not validate p in that case. */
5085 if (emacs_pipe (fd) == 0)
5087 bool valid = emacs_write (fd[1], p, 16) == 16;
5088 emacs_close (fd[1]);
5089 emacs_close (fd[0]);
5090 return valid;
5093 return -1;
5094 #endif
5097 /* Return 2 if OBJ is a killed or special buffer object, 1 if OBJ is a
5098 valid lisp object, 0 if OBJ is NOT a valid lisp object, or -1 if we
5099 cannot validate OBJ. This function can be quite slow, so its primary
5100 use is the manual debugging. The only exception is print_object, where
5101 we use it to check whether the memory referenced by the pointer of
5102 Lisp_Save_Value object contains valid objects. */
5105 valid_lisp_object_p (Lisp_Object obj)
5107 if (INTEGERP (obj))
5108 return 1;
5110 void *p = XPNTR (obj);
5111 if (PURE_P (p))
5112 return 1;
5114 if (SYMBOLP (obj) && c_symbol_p (p))
5115 return ((char *) p - (char *) lispsym) % sizeof lispsym[0] == 0;
5117 if (p == &buffer_defaults || p == &buffer_local_symbols)
5118 return 2;
5120 struct mem_node *m = mem_find (p);
5122 if (m == MEM_NIL)
5124 int valid = valid_pointer_p (p);
5125 if (valid <= 0)
5126 return valid;
5128 if (SUBRP (obj))
5129 return 1;
5131 return 0;
5134 switch (m->type)
5136 case MEM_TYPE_NON_LISP:
5137 case MEM_TYPE_SPARE:
5138 return 0;
5140 case MEM_TYPE_BUFFER:
5141 return live_buffer_p (m, p) ? 1 : 2;
5143 case MEM_TYPE_CONS:
5144 return live_cons_p (m, p);
5146 case MEM_TYPE_STRING:
5147 return live_string_p (m, p);
5149 case MEM_TYPE_MISC:
5150 return live_misc_p (m, p);
5152 case MEM_TYPE_SYMBOL:
5153 return live_symbol_p (m, p);
5155 case MEM_TYPE_FLOAT:
5156 return live_float_p (m, p);
5158 case MEM_TYPE_VECTORLIKE:
5159 case MEM_TYPE_VECTOR_BLOCK:
5160 return live_vector_p (m, p);
5162 default:
5163 break;
5166 return 0;
5169 /***********************************************************************
5170 Pure Storage Management
5171 ***********************************************************************/
5173 /* Allocate room for SIZE bytes from pure Lisp storage and return a
5174 pointer to it. TYPE is the Lisp type for which the memory is
5175 allocated. TYPE < 0 means it's not used for a Lisp object. */
5177 static void *
5178 pure_alloc (size_t size, int type)
5180 void *result;
5182 again:
5183 if (type >= 0)
5185 /* Allocate space for a Lisp object from the beginning of the free
5186 space with taking account of alignment. */
5187 result = pointer_align (purebeg + pure_bytes_used_lisp, GCALIGNMENT);
5188 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
5190 else
5192 /* Allocate space for a non-Lisp object from the end of the free
5193 space. */
5194 pure_bytes_used_non_lisp += size;
5195 result = purebeg + pure_size - pure_bytes_used_non_lisp;
5197 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
5199 if (pure_bytes_used <= pure_size)
5200 return result;
5202 /* Don't allocate a large amount here,
5203 because it might get mmap'd and then its address
5204 might not be usable. */
5205 purebeg = xmalloc (10000);
5206 pure_size = 10000;
5207 pure_bytes_used_before_overflow += pure_bytes_used - size;
5208 pure_bytes_used = 0;
5209 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
5210 goto again;
5214 /* Print a warning if PURESIZE is too small. */
5216 void
5217 check_pure_size (void)
5219 if (pure_bytes_used_before_overflow)
5220 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI"d"
5221 " bytes needed)"),
5222 pure_bytes_used + pure_bytes_used_before_overflow);
5226 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
5227 the non-Lisp data pool of the pure storage, and return its start
5228 address. Return NULL if not found. */
5230 static char *
5231 find_string_data_in_pure (const char *data, ptrdiff_t nbytes)
5233 int i;
5234 ptrdiff_t skip, bm_skip[256], last_char_skip, infinity, start, start_max;
5235 const unsigned char *p;
5236 char *non_lisp_beg;
5238 if (pure_bytes_used_non_lisp <= nbytes)
5239 return NULL;
5241 /* Set up the Boyer-Moore table. */
5242 skip = nbytes + 1;
5243 for (i = 0; i < 256; i++)
5244 bm_skip[i] = skip;
5246 p = (const unsigned char *) data;
5247 while (--skip > 0)
5248 bm_skip[*p++] = skip;
5250 last_char_skip = bm_skip['\0'];
5252 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
5253 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
5255 /* See the comments in the function `boyer_moore' (search.c) for the
5256 use of `infinity'. */
5257 infinity = pure_bytes_used_non_lisp + 1;
5258 bm_skip['\0'] = infinity;
5260 p = (const unsigned char *) non_lisp_beg + nbytes;
5261 start = 0;
5264 /* Check the last character (== '\0'). */
5267 start += bm_skip[*(p + start)];
5269 while (start <= start_max);
5271 if (start < infinity)
5272 /* Couldn't find the last character. */
5273 return NULL;
5275 /* No less than `infinity' means we could find the last
5276 character at `p[start - infinity]'. */
5277 start -= infinity;
5279 /* Check the remaining characters. */
5280 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
5281 /* Found. */
5282 return non_lisp_beg + start;
5284 start += last_char_skip;
5286 while (start <= start_max);
5288 return NULL;
5292 /* Return a string allocated in pure space. DATA is a buffer holding
5293 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
5294 means make the result string multibyte.
5296 Must get an error if pure storage is full, since if it cannot hold
5297 a large string it may be able to hold conses that point to that
5298 string; then the string is not protected from gc. */
5300 Lisp_Object
5301 make_pure_string (const char *data,
5302 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
5304 Lisp_Object string;
5305 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5306 s->data = (unsigned char *) find_string_data_in_pure (data, nbytes);
5307 if (s->data == NULL)
5309 s->data = pure_alloc (nbytes + 1, -1);
5310 memcpy (s->data, data, nbytes);
5311 s->data[nbytes] = '\0';
5313 s->size = nchars;
5314 s->size_byte = multibyte ? nbytes : -1;
5315 s->intervals = NULL;
5316 XSETSTRING (string, s);
5317 return string;
5320 /* Return a string allocated in pure space. Do not
5321 allocate the string data, just point to DATA. */
5323 Lisp_Object
5324 make_pure_c_string (const char *data, ptrdiff_t nchars)
5326 Lisp_Object string;
5327 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5328 s->size = nchars;
5329 s->size_byte = -1;
5330 s->data = (unsigned char *) data;
5331 s->intervals = NULL;
5332 XSETSTRING (string, s);
5333 return string;
5336 static Lisp_Object purecopy (Lisp_Object obj);
5338 /* Return a cons allocated from pure space. Give it pure copies
5339 of CAR as car and CDR as cdr. */
5341 Lisp_Object
5342 pure_cons (Lisp_Object car, Lisp_Object cdr)
5344 Lisp_Object new;
5345 struct Lisp_Cons *p = pure_alloc (sizeof *p, Lisp_Cons);
5346 XSETCONS (new, p);
5347 XSETCAR (new, purecopy (car));
5348 XSETCDR (new, purecopy (cdr));
5349 return new;
5353 /* Value is a float object with value NUM allocated from pure space. */
5355 static Lisp_Object
5356 make_pure_float (double num)
5358 Lisp_Object new;
5359 struct Lisp_Float *p = pure_alloc (sizeof *p, Lisp_Float);
5360 XSETFLOAT (new, p);
5361 XFLOAT_INIT (new, num);
5362 return new;
5366 /* Return a vector with room for LEN Lisp_Objects allocated from
5367 pure space. */
5369 static Lisp_Object
5370 make_pure_vector (ptrdiff_t len)
5372 Lisp_Object new;
5373 size_t size = header_size + len * word_size;
5374 struct Lisp_Vector *p = pure_alloc (size, Lisp_Vectorlike);
5375 XSETVECTOR (new, p);
5376 XVECTOR (new)->header.size = len;
5377 return new;
5380 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
5381 doc: /* Make a copy of object OBJ in pure storage.
5382 Recursively copies contents of vectors and cons cells.
5383 Does not copy symbols. Copies strings without text properties. */)
5384 (register Lisp_Object obj)
5386 if (NILP (Vpurify_flag))
5387 return obj;
5388 else if (MARKERP (obj) || OVERLAYP (obj)
5389 || HASH_TABLE_P (obj) || SYMBOLP (obj))
5390 /* Can't purify those. */
5391 return obj;
5392 else
5393 return purecopy (obj);
5396 static Lisp_Object
5397 purecopy (Lisp_Object obj)
5399 if (INTEGERP (obj)
5400 || (! SYMBOLP (obj) && PURE_P (XPNTR_OR_SYMBOL_OFFSET (obj)))
5401 || SUBRP (obj))
5402 return obj; /* Already pure. */
5404 if (STRINGP (obj) && XSTRING (obj)->intervals)
5405 message_with_string ("Dropping text-properties while making string `%s' pure",
5406 obj, true);
5408 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5410 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
5411 if (!NILP (tmp))
5412 return tmp;
5415 if (CONSP (obj))
5416 obj = pure_cons (XCAR (obj), XCDR (obj));
5417 else if (FLOATP (obj))
5418 obj = make_pure_float (XFLOAT_DATA (obj));
5419 else if (STRINGP (obj))
5420 obj = make_pure_string (SSDATA (obj), SCHARS (obj),
5421 SBYTES (obj),
5422 STRING_MULTIBYTE (obj));
5423 else if (COMPILEDP (obj) || VECTORP (obj) || HASH_TABLE_P (obj))
5425 struct Lisp_Vector *objp = XVECTOR (obj);
5426 ptrdiff_t nbytes = vector_nbytes (objp);
5427 struct Lisp_Vector *vec = pure_alloc (nbytes, Lisp_Vectorlike);
5428 register ptrdiff_t i;
5429 ptrdiff_t size = ASIZE (obj);
5430 if (size & PSEUDOVECTOR_FLAG)
5431 size &= PSEUDOVECTOR_SIZE_MASK;
5432 memcpy (vec, objp, nbytes);
5433 for (i = 0; i < size; i++)
5434 vec->contents[i] = purecopy (vec->contents[i]);
5435 XSETVECTOR (obj, vec);
5437 else if (SYMBOLP (obj))
5439 if (!XSYMBOL (obj)->pinned && !c_symbol_p (XSYMBOL (obj)))
5440 { /* We can't purify them, but they appear in many pure objects.
5441 Mark them as `pinned' so we know to mark them at every GC cycle. */
5442 XSYMBOL (obj)->pinned = true;
5443 symbol_block_pinned = symbol_block;
5445 /* Don't hash-cons it. */
5446 return obj;
5448 else
5450 AUTO_STRING (fmt, "Don't know how to purify: %S");
5451 Fsignal (Qerror, list1 (CALLN (Fformat, fmt, obj)));
5454 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5455 Fputhash (obj, obj, Vpurify_flag);
5457 return obj;
5462 /***********************************************************************
5463 Protection from GC
5464 ***********************************************************************/
5466 /* Put an entry in staticvec, pointing at the variable with address
5467 VARADDRESS. */
5469 void
5470 staticpro (Lisp_Object *varaddress)
5472 if (staticidx >= NSTATICS)
5473 fatal ("NSTATICS too small; try increasing and recompiling Emacs.");
5474 staticvec[staticidx++] = varaddress;
5478 /***********************************************************************
5479 Protection from GC
5480 ***********************************************************************/
5482 /* Temporarily prevent garbage collection. */
5484 ptrdiff_t
5485 inhibit_garbage_collection (void)
5487 ptrdiff_t count = SPECPDL_INDEX ();
5489 specbind (Qgc_cons_threshold, make_number (MOST_POSITIVE_FIXNUM));
5490 return count;
5493 /* Used to avoid possible overflows when
5494 converting from C to Lisp integers. */
5496 static Lisp_Object
5497 bounded_number (EMACS_INT number)
5499 return make_number (min (MOST_POSITIVE_FIXNUM, number));
5502 /* Calculate total bytes of live objects. */
5504 static size_t
5505 total_bytes_of_live_objects (void)
5507 size_t tot = 0;
5508 tot += total_conses * sizeof (struct Lisp_Cons);
5509 tot += total_symbols * sizeof (struct Lisp_Symbol);
5510 tot += total_markers * sizeof (union Lisp_Misc);
5511 tot += total_string_bytes;
5512 tot += total_vector_slots * word_size;
5513 tot += total_floats * sizeof (struct Lisp_Float);
5514 tot += total_intervals * sizeof (struct interval);
5515 tot += total_strings * sizeof (struct Lisp_String);
5516 return tot;
5519 #ifdef HAVE_WINDOW_SYSTEM
5521 /* Remove unmarked font-spec and font-entity objects from ENTRY, which is
5522 (DRIVER-TYPE NUM-FRAMES FONT-CACHE-DATA ...), and return changed entry. */
5524 static Lisp_Object
5525 compact_font_cache_entry (Lisp_Object entry)
5527 Lisp_Object tail, *prev = &entry;
5529 for (tail = entry; CONSP (tail); tail = XCDR (tail))
5531 bool drop = 0;
5532 Lisp_Object obj = XCAR (tail);
5534 /* Consider OBJ if it is (font-spec . [font-entity font-entity ...]). */
5535 if (CONSP (obj) && GC_FONT_SPEC_P (XCAR (obj))
5536 && !VECTOR_MARKED_P (GC_XFONT_SPEC (XCAR (obj)))
5537 /* Don't use VECTORP here, as that calls ASIZE, which could
5538 hit assertion violation during GC. */
5539 && (VECTORLIKEP (XCDR (obj))
5540 && ! (gc_asize (XCDR (obj)) & PSEUDOVECTOR_FLAG)))
5542 ptrdiff_t i, size = gc_asize (XCDR (obj));
5543 Lisp_Object obj_cdr = XCDR (obj);
5545 /* If font-spec is not marked, most likely all font-entities
5546 are not marked too. But we must be sure that nothing is
5547 marked within OBJ before we really drop it. */
5548 for (i = 0; i < size; i++)
5550 Lisp_Object objlist;
5552 if (VECTOR_MARKED_P (GC_XFONT_ENTITY (AREF (obj_cdr, i))))
5553 break;
5555 objlist = AREF (AREF (obj_cdr, i), FONT_OBJLIST_INDEX);
5556 for (; CONSP (objlist); objlist = XCDR (objlist))
5558 Lisp_Object val = XCAR (objlist);
5559 struct font *font = GC_XFONT_OBJECT (val);
5561 if (!NILP (AREF (val, FONT_TYPE_INDEX))
5562 && VECTOR_MARKED_P(font))
5563 break;
5565 if (CONSP (objlist))
5567 /* Found a marked font, bail out. */
5568 break;
5572 if (i == size)
5574 /* No marked fonts were found, so this entire font
5575 entity can be dropped. */
5576 drop = 1;
5579 if (drop)
5580 *prev = XCDR (tail);
5581 else
5582 prev = xcdr_addr (tail);
5584 return entry;
5587 /* Compact font caches on all terminals and mark
5588 everything which is still here after compaction. */
5590 static void
5591 compact_font_caches (void)
5593 struct terminal *t;
5595 for (t = terminal_list; t; t = t->next_terminal)
5597 Lisp_Object cache = TERMINAL_FONT_CACHE (t);
5598 if (CONSP (cache))
5600 Lisp_Object entry;
5602 for (entry = XCDR (cache); CONSP (entry); entry = XCDR (entry))
5603 XSETCAR (entry, compact_font_cache_entry (XCAR (entry)));
5605 mark_object (cache);
5609 #else /* not HAVE_WINDOW_SYSTEM */
5611 #define compact_font_caches() (void)(0)
5613 #endif /* HAVE_WINDOW_SYSTEM */
5615 /* Remove (MARKER . DATA) entries with unmarked MARKER
5616 from buffer undo LIST and return changed list. */
5618 static Lisp_Object
5619 compact_undo_list (Lisp_Object list)
5621 Lisp_Object tail, *prev = &list;
5623 for (tail = list; CONSP (tail); tail = XCDR (tail))
5625 if (CONSP (XCAR (tail))
5626 && MARKERP (XCAR (XCAR (tail)))
5627 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5628 *prev = XCDR (tail);
5629 else
5630 prev = xcdr_addr (tail);
5632 return list;
5635 static void
5636 mark_pinned_symbols (void)
5638 struct symbol_block *sblk;
5639 int lim = (symbol_block_pinned == symbol_block
5640 ? symbol_block_index : SYMBOL_BLOCK_SIZE);
5642 for (sblk = symbol_block_pinned; sblk; sblk = sblk->next)
5644 union aligned_Lisp_Symbol *sym = sblk->symbols, *end = sym + lim;
5645 for (; sym < end; ++sym)
5646 if (sym->s.pinned)
5647 mark_object (make_lisp_symbol (&sym->s));
5649 lim = SYMBOL_BLOCK_SIZE;
5653 /* Subroutine of Fgarbage_collect that does most of the work. It is a
5654 separate function so that we could limit mark_stack in searching
5655 the stack frames below this function, thus avoiding the rare cases
5656 where mark_stack finds values that look like live Lisp objects on
5657 portions of stack that couldn't possibly contain such live objects.
5658 For more details of this, see the discussion at
5659 http://lists.gnu.org/archive/html/emacs-devel/2014-05/msg00270.html. */
5660 static Lisp_Object
5661 garbage_collect_1 (void *end)
5663 struct buffer *nextb;
5664 char stack_top_variable;
5665 ptrdiff_t i;
5666 bool message_p;
5667 ptrdiff_t count = SPECPDL_INDEX ();
5668 struct timespec start;
5669 Lisp_Object retval = Qnil;
5670 size_t tot_before = 0;
5672 /* Can't GC if pure storage overflowed because we can't determine
5673 if something is a pure object or not. */
5674 if (pure_bytes_used_before_overflow)
5675 return Qnil;
5677 /* Record this function, so it appears on the profiler's backtraces. */
5678 record_in_backtrace (QAutomatic_GC, 0, 0);
5680 check_cons_list ();
5682 /* Don't keep undo information around forever.
5683 Do this early on, so it is no problem if the user quits. */
5684 FOR_EACH_BUFFER (nextb)
5685 compact_buffer (nextb);
5687 if (profiler_memory_running)
5688 tot_before = total_bytes_of_live_objects ();
5690 start = current_timespec ();
5692 /* In case user calls debug_print during GC,
5693 don't let that cause a recursive GC. */
5694 consing_since_gc = 0;
5696 /* Save what's currently displayed in the echo area. Don't do that
5697 if we are GC'ing because we've run out of memory, since
5698 push_message will cons, and we might have no memory for that. */
5699 if (NILP (Vmemory_full))
5701 message_p = push_message ();
5702 record_unwind_protect_void (pop_message_unwind);
5704 else
5705 message_p = false;
5707 /* Save a copy of the contents of the stack, for debugging. */
5708 #if MAX_SAVE_STACK > 0
5709 if (NILP (Vpurify_flag))
5711 char *stack;
5712 ptrdiff_t stack_size;
5713 if (&stack_top_variable < stack_bottom)
5715 stack = &stack_top_variable;
5716 stack_size = stack_bottom - &stack_top_variable;
5718 else
5720 stack = stack_bottom;
5721 stack_size = &stack_top_variable - stack_bottom;
5723 if (stack_size <= MAX_SAVE_STACK)
5725 if (stack_copy_size < stack_size)
5727 stack_copy = xrealloc (stack_copy, stack_size);
5728 stack_copy_size = stack_size;
5730 no_sanitize_memcpy (stack_copy, stack, stack_size);
5733 #endif /* MAX_SAVE_STACK > 0 */
5735 if (garbage_collection_messages)
5736 message1_nolog ("Garbage collecting...");
5738 block_input ();
5740 shrink_regexp_cache ();
5742 gc_in_progress = 1;
5744 /* Mark all the special slots that serve as the roots of accessibility. */
5746 mark_buffer (&buffer_defaults);
5747 mark_buffer (&buffer_local_symbols);
5749 for (i = 0; i < ARRAYELTS (lispsym); i++)
5750 mark_object (builtin_lisp_symbol (i));
5752 for (i = 0; i < staticidx; i++)
5753 mark_object (*staticvec[i]);
5755 mark_pinned_symbols ();
5756 mark_specpdl ();
5757 mark_terminals ();
5758 mark_kboards ();
5760 #ifdef USE_GTK
5761 xg_mark_data ();
5762 #endif
5764 mark_stack (end);
5767 struct handler *handler;
5768 for (handler = handlerlist; handler; handler = handler->next)
5770 mark_object (handler->tag_or_ch);
5771 mark_object (handler->val);
5774 #ifdef HAVE_WINDOW_SYSTEM
5775 mark_fringe_data ();
5776 #endif
5778 /* Everything is now marked, except for the data in font caches,
5779 undo lists, and finalizers. The first two are compacted by
5780 removing an items which aren't reachable otherwise. */
5782 compact_font_caches ();
5784 FOR_EACH_BUFFER (nextb)
5786 if (!EQ (BVAR (nextb, undo_list), Qt))
5787 bset_undo_list (nextb, compact_undo_list (BVAR (nextb, undo_list)));
5788 /* Now that we have stripped the elements that need not be
5789 in the undo_list any more, we can finally mark the list. */
5790 mark_object (BVAR (nextb, undo_list));
5793 /* Now pre-sweep finalizers. Here, we add any unmarked finalizers
5794 to doomed_finalizers so we can run their associated functions
5795 after GC. It's important to scan finalizers at this stage so
5796 that we can be sure that unmarked finalizers are really
5797 unreachable except for references from their associated functions
5798 and from other finalizers. */
5800 queue_doomed_finalizers (&doomed_finalizers, &finalizers);
5801 mark_finalizer_list (&doomed_finalizers);
5803 gc_sweep ();
5805 /* Clear the mark bits that we set in certain root slots. */
5806 VECTOR_UNMARK (&buffer_defaults);
5807 VECTOR_UNMARK (&buffer_local_symbols);
5809 check_cons_list ();
5811 gc_in_progress = 0;
5813 unblock_input ();
5815 consing_since_gc = 0;
5816 if (gc_cons_threshold < GC_DEFAULT_THRESHOLD / 10)
5817 gc_cons_threshold = GC_DEFAULT_THRESHOLD / 10;
5819 gc_relative_threshold = 0;
5820 if (FLOATP (Vgc_cons_percentage))
5821 { /* Set gc_cons_combined_threshold. */
5822 double tot = total_bytes_of_live_objects ();
5824 tot *= XFLOAT_DATA (Vgc_cons_percentage);
5825 if (0 < tot)
5827 if (tot < TYPE_MAXIMUM (EMACS_INT))
5828 gc_relative_threshold = tot;
5829 else
5830 gc_relative_threshold = TYPE_MAXIMUM (EMACS_INT);
5834 if (garbage_collection_messages && NILP (Vmemory_full))
5836 if (message_p || minibuf_level > 0)
5837 restore_message ();
5838 else
5839 message1_nolog ("Garbage collecting...done");
5842 unbind_to (count, Qnil);
5844 Lisp_Object total[] = {
5845 list4 (Qconses, make_number (sizeof (struct Lisp_Cons)),
5846 bounded_number (total_conses),
5847 bounded_number (total_free_conses)),
5848 list4 (Qsymbols, make_number (sizeof (struct Lisp_Symbol)),
5849 bounded_number (total_symbols),
5850 bounded_number (total_free_symbols)),
5851 list4 (Qmiscs, make_number (sizeof (union Lisp_Misc)),
5852 bounded_number (total_markers),
5853 bounded_number (total_free_markers)),
5854 list4 (Qstrings, make_number (sizeof (struct Lisp_String)),
5855 bounded_number (total_strings),
5856 bounded_number (total_free_strings)),
5857 list3 (Qstring_bytes, make_number (1),
5858 bounded_number (total_string_bytes)),
5859 list3 (Qvectors,
5860 make_number (header_size + sizeof (Lisp_Object)),
5861 bounded_number (total_vectors)),
5862 list4 (Qvector_slots, make_number (word_size),
5863 bounded_number (total_vector_slots),
5864 bounded_number (total_free_vector_slots)),
5865 list4 (Qfloats, make_number (sizeof (struct Lisp_Float)),
5866 bounded_number (total_floats),
5867 bounded_number (total_free_floats)),
5868 list4 (Qintervals, make_number (sizeof (struct interval)),
5869 bounded_number (total_intervals),
5870 bounded_number (total_free_intervals)),
5871 list3 (Qbuffers, make_number (sizeof (struct buffer)),
5872 bounded_number (total_buffers)),
5874 #ifdef DOUG_LEA_MALLOC
5875 list4 (Qheap, make_number (1024),
5876 bounded_number ((mallinfo ().uordblks + 1023) >> 10),
5877 bounded_number ((mallinfo ().fordblks + 1023) >> 10)),
5878 #endif
5880 retval = CALLMANY (Flist, total);
5882 /* GC is complete: now we can run our finalizer callbacks. */
5883 run_finalizers (&doomed_finalizers);
5885 if (!NILP (Vpost_gc_hook))
5887 ptrdiff_t gc_count = inhibit_garbage_collection ();
5888 safe_run_hooks (Qpost_gc_hook);
5889 unbind_to (gc_count, Qnil);
5892 /* Accumulate statistics. */
5893 if (FLOATP (Vgc_elapsed))
5895 struct timespec since_start = timespec_sub (current_timespec (), start);
5896 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed)
5897 + timespectod (since_start));
5900 gcs_done++;
5902 /* Collect profiling data. */
5903 if (profiler_memory_running)
5905 size_t swept = 0;
5906 size_t tot_after = total_bytes_of_live_objects ();
5907 if (tot_before > tot_after)
5908 swept = tot_before - tot_after;
5909 malloc_probe (swept);
5912 return retval;
5915 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
5916 doc: /* Reclaim storage for Lisp objects no longer needed.
5917 Garbage collection happens automatically if you cons more than
5918 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5919 `garbage-collect' normally returns a list with info on amount of space in use,
5920 where each entry has the form (NAME SIZE USED FREE), where:
5921 - NAME is a symbol describing the kind of objects this entry represents,
5922 - SIZE is the number of bytes used by each one,
5923 - USED is the number of those objects that were found live in the heap,
5924 - FREE is the number of those objects that are not live but that Emacs
5925 keeps around for future allocations (maybe because it does not know how
5926 to return them to the OS).
5927 However, if there was overflow in pure space, `garbage-collect'
5928 returns nil, because real GC can't be done.
5929 See Info node `(elisp)Garbage Collection'. */)
5930 (void)
5932 void *end;
5934 #ifdef HAVE___BUILTIN_UNWIND_INIT
5935 /* Force callee-saved registers and register windows onto the stack.
5936 This is the preferred method if available, obviating the need for
5937 machine dependent methods. */
5938 __builtin_unwind_init ();
5939 end = &end;
5940 #else /* not HAVE___BUILTIN_UNWIND_INIT */
5941 #ifndef GC_SAVE_REGISTERS_ON_STACK
5942 /* jmp_buf may not be aligned enough on darwin-ppc64 */
5943 union aligned_jmpbuf {
5944 Lisp_Object o;
5945 sys_jmp_buf j;
5946 } j;
5947 volatile bool stack_grows_down_p = (char *) &j > (char *) stack_base;
5948 #endif
5949 /* This trick flushes the register windows so that all the state of
5950 the process is contained in the stack. */
5951 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
5952 needed on ia64 too. See mach_dep.c, where it also says inline
5953 assembler doesn't work with relevant proprietary compilers. */
5954 #ifdef __sparc__
5955 #if defined (__sparc64__) && defined (__FreeBSD__)
5956 /* FreeBSD does not have a ta 3 handler. */
5957 asm ("flushw");
5958 #else
5959 asm ("ta 3");
5960 #endif
5961 #endif
5963 /* Save registers that we need to see on the stack. We need to see
5964 registers used to hold register variables and registers used to
5965 pass parameters. */
5966 #ifdef GC_SAVE_REGISTERS_ON_STACK
5967 GC_SAVE_REGISTERS_ON_STACK (end);
5968 #else /* not GC_SAVE_REGISTERS_ON_STACK */
5970 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
5971 setjmp will definitely work, test it
5972 and print a message with the result
5973 of the test. */
5974 if (!setjmp_tested_p)
5976 setjmp_tested_p = 1;
5977 test_setjmp ();
5979 #endif /* GC_SETJMP_WORKS */
5981 sys_setjmp (j.j);
5982 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
5983 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
5984 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
5985 return garbage_collect_1 (end);
5988 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5989 only interesting objects referenced from glyphs are strings. */
5991 static void
5992 mark_glyph_matrix (struct glyph_matrix *matrix)
5994 struct glyph_row *row = matrix->rows;
5995 struct glyph_row *end = row + matrix->nrows;
5997 for (; row < end; ++row)
5998 if (row->enabled_p)
6000 int area;
6001 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
6003 struct glyph *glyph = row->glyphs[area];
6004 struct glyph *end_glyph = glyph + row->used[area];
6006 for (; glyph < end_glyph; ++glyph)
6007 if (STRINGP (glyph->object)
6008 && !STRING_MARKED_P (XSTRING (glyph->object)))
6009 mark_object (glyph->object);
6014 /* Mark reference to a Lisp_Object.
6015 If the object referred to has not been seen yet, recursively mark
6016 all the references contained in it. */
6018 #define LAST_MARKED_SIZE 500
6019 static Lisp_Object last_marked[LAST_MARKED_SIZE];
6020 static int last_marked_index;
6022 /* For debugging--call abort when we cdr down this many
6023 links of a list, in mark_object. In debugging,
6024 the call to abort will hit a breakpoint.
6025 Normally this is zero and the check never goes off. */
6026 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE;
6028 static void
6029 mark_vectorlike (struct Lisp_Vector *ptr)
6031 ptrdiff_t size = ptr->header.size;
6032 ptrdiff_t i;
6034 eassert (!VECTOR_MARKED_P (ptr));
6035 VECTOR_MARK (ptr); /* Else mark it. */
6036 if (size & PSEUDOVECTOR_FLAG)
6037 size &= PSEUDOVECTOR_SIZE_MASK;
6039 /* Note that this size is not the memory-footprint size, but only
6040 the number of Lisp_Object fields that we should trace.
6041 The distinction is used e.g. by Lisp_Process which places extra
6042 non-Lisp_Object fields at the end of the structure... */
6043 for (i = 0; i < size; i++) /* ...and then mark its elements. */
6044 mark_object (ptr->contents[i]);
6047 /* Like mark_vectorlike but optimized for char-tables (and
6048 sub-char-tables) assuming that the contents are mostly integers or
6049 symbols. */
6051 static void
6052 mark_char_table (struct Lisp_Vector *ptr, enum pvec_type pvectype)
6054 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
6055 /* Consult the Lisp_Sub_Char_Table layout before changing this. */
6056 int i, idx = (pvectype == PVEC_SUB_CHAR_TABLE ? SUB_CHAR_TABLE_OFFSET : 0);
6058 eassert (!VECTOR_MARKED_P (ptr));
6059 VECTOR_MARK (ptr);
6060 for (i = idx; i < size; i++)
6062 Lisp_Object val = ptr->contents[i];
6064 if (INTEGERP (val) || (SYMBOLP (val) && XSYMBOL (val)->gcmarkbit))
6065 continue;
6066 if (SUB_CHAR_TABLE_P (val))
6068 if (! VECTOR_MARKED_P (XVECTOR (val)))
6069 mark_char_table (XVECTOR (val), PVEC_SUB_CHAR_TABLE);
6071 else
6072 mark_object (val);
6076 NO_INLINE /* To reduce stack depth in mark_object. */
6077 static Lisp_Object
6078 mark_compiled (struct Lisp_Vector *ptr)
6080 int i, size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
6082 VECTOR_MARK (ptr);
6083 for (i = 0; i < size; i++)
6084 if (i != COMPILED_CONSTANTS)
6085 mark_object (ptr->contents[i]);
6086 return size > COMPILED_CONSTANTS ? ptr->contents[COMPILED_CONSTANTS] : Qnil;
6089 /* Mark the chain of overlays starting at PTR. */
6091 static void
6092 mark_overlay (struct Lisp_Overlay *ptr)
6094 for (; ptr && !ptr->gcmarkbit; ptr = ptr->next)
6096 ptr->gcmarkbit = 1;
6097 /* These two are always markers and can be marked fast. */
6098 XMARKER (ptr->start)->gcmarkbit = 1;
6099 XMARKER (ptr->end)->gcmarkbit = 1;
6100 mark_object (ptr->plist);
6104 /* Mark Lisp_Objects and special pointers in BUFFER. */
6106 static void
6107 mark_buffer (struct buffer *buffer)
6109 /* This is handled much like other pseudovectors... */
6110 mark_vectorlike ((struct Lisp_Vector *) buffer);
6112 /* ...but there are some buffer-specific things. */
6114 MARK_INTERVAL_TREE (buffer_intervals (buffer));
6116 /* For now, we just don't mark the undo_list. It's done later in
6117 a special way just before the sweep phase, and after stripping
6118 some of its elements that are not needed any more. */
6120 mark_overlay (buffer->overlays_before);
6121 mark_overlay (buffer->overlays_after);
6123 /* If this is an indirect buffer, mark its base buffer. */
6124 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
6125 mark_buffer (buffer->base_buffer);
6128 /* Mark Lisp faces in the face cache C. */
6130 NO_INLINE /* To reduce stack depth in mark_object. */
6131 static void
6132 mark_face_cache (struct face_cache *c)
6134 if (c)
6136 int i, j;
6137 for (i = 0; i < c->used; ++i)
6139 struct face *face = FACE_FROM_ID_OR_NULL (c->f, i);
6141 if (face)
6143 if (face->font && !VECTOR_MARKED_P (face->font))
6144 mark_vectorlike ((struct Lisp_Vector *) face->font);
6146 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
6147 mark_object (face->lface[j]);
6153 NO_INLINE /* To reduce stack depth in mark_object. */
6154 static void
6155 mark_localized_symbol (struct Lisp_Symbol *ptr)
6157 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
6158 Lisp_Object where = blv->where;
6159 /* If the value is set up for a killed buffer or deleted
6160 frame, restore its global binding. If the value is
6161 forwarded to a C variable, either it's not a Lisp_Object
6162 var, or it's staticpro'd already. */
6163 if ((BUFFERP (where) && !BUFFER_LIVE_P (XBUFFER (where)))
6164 || (FRAMEP (where) && !FRAME_LIVE_P (XFRAME (where))))
6165 swap_in_global_binding (ptr);
6166 mark_object (blv->where);
6167 mark_object (blv->valcell);
6168 mark_object (blv->defcell);
6171 NO_INLINE /* To reduce stack depth in mark_object. */
6172 static void
6173 mark_save_value (struct Lisp_Save_Value *ptr)
6175 /* If `save_type' is zero, `data[0].pointer' is the address
6176 of a memory area containing `data[1].integer' potential
6177 Lisp_Objects. */
6178 if (ptr->save_type == SAVE_TYPE_MEMORY)
6180 Lisp_Object *p = ptr->data[0].pointer;
6181 ptrdiff_t nelt;
6182 for (nelt = ptr->data[1].integer; nelt > 0; nelt--, p++)
6183 mark_maybe_object (*p);
6185 else
6187 /* Find Lisp_Objects in `data[N]' slots and mark them. */
6188 int i;
6189 for (i = 0; i < SAVE_VALUE_SLOTS; i++)
6190 if (save_type (ptr, i) == SAVE_OBJECT)
6191 mark_object (ptr->data[i].object);
6195 /* Remove killed buffers or items whose car is a killed buffer from
6196 LIST, and mark other items. Return changed LIST, which is marked. */
6198 static Lisp_Object
6199 mark_discard_killed_buffers (Lisp_Object list)
6201 Lisp_Object tail, *prev = &list;
6203 for (tail = list; CONSP (tail) && !CONS_MARKED_P (XCONS (tail));
6204 tail = XCDR (tail))
6206 Lisp_Object tem = XCAR (tail);
6207 if (CONSP (tem))
6208 tem = XCAR (tem);
6209 if (BUFFERP (tem) && !BUFFER_LIVE_P (XBUFFER (tem)))
6210 *prev = XCDR (tail);
6211 else
6213 CONS_MARK (XCONS (tail));
6214 mark_object (XCAR (tail));
6215 prev = xcdr_addr (tail);
6218 mark_object (tail);
6219 return list;
6222 /* Determine type of generic Lisp_Object and mark it accordingly.
6224 This function implements a straightforward depth-first marking
6225 algorithm and so the recursion depth may be very high (a few
6226 tens of thousands is not uncommon). To minimize stack usage,
6227 a few cold paths are moved out to NO_INLINE functions above.
6228 In general, inlining them doesn't help you to gain more speed. */
6230 void
6231 mark_object (Lisp_Object arg)
6233 register Lisp_Object obj;
6234 void *po;
6235 #ifdef GC_CHECK_MARKED_OBJECTS
6236 struct mem_node *m;
6237 #endif
6238 ptrdiff_t cdr_count = 0;
6240 obj = arg;
6241 loop:
6243 po = XPNTR (obj);
6244 if (PURE_P (po))
6245 return;
6247 last_marked[last_marked_index++] = obj;
6248 if (last_marked_index == LAST_MARKED_SIZE)
6249 last_marked_index = 0;
6251 /* Perform some sanity checks on the objects marked here. Abort if
6252 we encounter an object we know is bogus. This increases GC time
6253 by ~80%. */
6254 #ifdef GC_CHECK_MARKED_OBJECTS
6256 /* Check that the object pointed to by PO is known to be a Lisp
6257 structure allocated from the heap. */
6258 #define CHECK_ALLOCATED() \
6259 do { \
6260 m = mem_find (po); \
6261 if (m == MEM_NIL) \
6262 emacs_abort (); \
6263 } while (0)
6265 /* Check that the object pointed to by PO is live, using predicate
6266 function LIVEP. */
6267 #define CHECK_LIVE(LIVEP) \
6268 do { \
6269 if (!LIVEP (m, po)) \
6270 emacs_abort (); \
6271 } while (0)
6273 /* Check both of the above conditions, for non-symbols. */
6274 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
6275 do { \
6276 CHECK_ALLOCATED (); \
6277 CHECK_LIVE (LIVEP); \
6278 } while (0) \
6280 /* Check both of the above conditions, for symbols. */
6281 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() \
6282 do { \
6283 if (!c_symbol_p (ptr)) \
6285 CHECK_ALLOCATED (); \
6286 CHECK_LIVE (live_symbol_p); \
6288 } while (0) \
6290 #else /* not GC_CHECK_MARKED_OBJECTS */
6292 #define CHECK_LIVE(LIVEP) ((void) 0)
6293 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) ((void) 0)
6294 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() ((void) 0)
6296 #endif /* not GC_CHECK_MARKED_OBJECTS */
6298 switch (XTYPE (obj))
6300 case Lisp_String:
6302 register struct Lisp_String *ptr = XSTRING (obj);
6303 if (STRING_MARKED_P (ptr))
6304 break;
6305 CHECK_ALLOCATED_AND_LIVE (live_string_p);
6306 MARK_STRING (ptr);
6307 MARK_INTERVAL_TREE (ptr->intervals);
6308 #ifdef GC_CHECK_STRING_BYTES
6309 /* Check that the string size recorded in the string is the
6310 same as the one recorded in the sdata structure. */
6311 string_bytes (ptr);
6312 #endif /* GC_CHECK_STRING_BYTES */
6314 break;
6316 case Lisp_Vectorlike:
6318 register struct Lisp_Vector *ptr = XVECTOR (obj);
6319 register ptrdiff_t pvectype;
6321 if (VECTOR_MARKED_P (ptr))
6322 break;
6324 #ifdef GC_CHECK_MARKED_OBJECTS
6325 m = mem_find (po);
6326 if (m == MEM_NIL && !SUBRP (obj))
6327 emacs_abort ();
6328 #endif /* GC_CHECK_MARKED_OBJECTS */
6330 if (ptr->header.size & PSEUDOVECTOR_FLAG)
6331 pvectype = ((ptr->header.size & PVEC_TYPE_MASK)
6332 >> PSEUDOVECTOR_AREA_BITS);
6333 else
6334 pvectype = PVEC_NORMAL_VECTOR;
6336 if (pvectype != PVEC_SUBR && pvectype != PVEC_BUFFER)
6337 CHECK_LIVE (live_vector_p);
6339 switch (pvectype)
6341 case PVEC_BUFFER:
6342 #ifdef GC_CHECK_MARKED_OBJECTS
6344 struct buffer *b;
6345 FOR_EACH_BUFFER (b)
6346 if (b == po)
6347 break;
6348 if (b == NULL)
6349 emacs_abort ();
6351 #endif /* GC_CHECK_MARKED_OBJECTS */
6352 mark_buffer ((struct buffer *) ptr);
6353 break;
6355 case PVEC_COMPILED:
6356 /* Although we could treat this just like a vector, mark_compiled
6357 returns the COMPILED_CONSTANTS element, which is marked at the
6358 next iteration of goto-loop here. This is done to avoid a few
6359 recursive calls to mark_object. */
6360 obj = mark_compiled (ptr);
6361 if (!NILP (obj))
6362 goto loop;
6363 break;
6365 case PVEC_FRAME:
6367 struct frame *f = (struct frame *) ptr;
6369 mark_vectorlike (ptr);
6370 mark_face_cache (f->face_cache);
6371 #ifdef HAVE_WINDOW_SYSTEM
6372 if (FRAME_WINDOW_P (f) && FRAME_X_OUTPUT (f))
6374 struct font *font = FRAME_FONT (f);
6376 if (font && !VECTOR_MARKED_P (font))
6377 mark_vectorlike ((struct Lisp_Vector *) font);
6379 #endif
6381 break;
6383 case PVEC_WINDOW:
6385 struct window *w = (struct window *) ptr;
6387 mark_vectorlike (ptr);
6389 /* Mark glyph matrices, if any. Marking window
6390 matrices is sufficient because frame matrices
6391 use the same glyph memory. */
6392 if (w->current_matrix)
6394 mark_glyph_matrix (w->current_matrix);
6395 mark_glyph_matrix (w->desired_matrix);
6398 /* Filter out killed buffers from both buffer lists
6399 in attempt to help GC to reclaim killed buffers faster.
6400 We can do it elsewhere for live windows, but this is the
6401 best place to do it for dead windows. */
6402 wset_prev_buffers
6403 (w, mark_discard_killed_buffers (w->prev_buffers));
6404 wset_next_buffers
6405 (w, mark_discard_killed_buffers (w->next_buffers));
6407 break;
6409 case PVEC_HASH_TABLE:
6411 struct Lisp_Hash_Table *h = (struct Lisp_Hash_Table *) ptr;
6413 mark_vectorlike (ptr);
6414 mark_object (h->test.name);
6415 mark_object (h->test.user_hash_function);
6416 mark_object (h->test.user_cmp_function);
6417 /* If hash table is not weak, mark all keys and values.
6418 For weak tables, mark only the vector. */
6419 if (NILP (h->weak))
6420 mark_object (h->key_and_value);
6421 else
6422 VECTOR_MARK (XVECTOR (h->key_and_value));
6424 break;
6426 case PVEC_CHAR_TABLE:
6427 case PVEC_SUB_CHAR_TABLE:
6428 mark_char_table (ptr, (enum pvec_type) pvectype);
6429 break;
6431 case PVEC_BOOL_VECTOR:
6432 /* No Lisp_Objects to mark in a bool vector. */
6433 VECTOR_MARK (ptr);
6434 break;
6436 case PVEC_SUBR:
6437 break;
6439 case PVEC_FREE:
6440 emacs_abort ();
6442 default:
6443 mark_vectorlike (ptr);
6446 break;
6448 case Lisp_Symbol:
6450 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
6451 nextsym:
6452 if (ptr->gcmarkbit)
6453 break;
6454 CHECK_ALLOCATED_AND_LIVE_SYMBOL ();
6455 ptr->gcmarkbit = 1;
6456 /* Attempt to catch bogus objects. */
6457 eassert (valid_lisp_object_p (ptr->function));
6458 mark_object (ptr->function);
6459 mark_object (ptr->plist);
6460 switch (ptr->redirect)
6462 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
6463 case SYMBOL_VARALIAS:
6465 Lisp_Object tem;
6466 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
6467 mark_object (tem);
6468 break;
6470 case SYMBOL_LOCALIZED:
6471 mark_localized_symbol (ptr);
6472 break;
6473 case SYMBOL_FORWARDED:
6474 /* If the value is forwarded to a buffer or keyboard field,
6475 these are marked when we see the corresponding object.
6476 And if it's forwarded to a C variable, either it's not
6477 a Lisp_Object var, or it's staticpro'd already. */
6478 break;
6479 default: emacs_abort ();
6481 if (!PURE_P (XSTRING (ptr->name)))
6482 MARK_STRING (XSTRING (ptr->name));
6483 MARK_INTERVAL_TREE (string_intervals (ptr->name));
6484 /* Inner loop to mark next symbol in this bucket, if any. */
6485 po = ptr = ptr->next;
6486 if (ptr)
6487 goto nextsym;
6489 break;
6491 case Lisp_Misc:
6492 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
6494 if (XMISCANY (obj)->gcmarkbit)
6495 break;
6497 switch (XMISCTYPE (obj))
6499 case Lisp_Misc_Marker:
6500 /* DO NOT mark thru the marker's chain.
6501 The buffer's markers chain does not preserve markers from gc;
6502 instead, markers are removed from the chain when freed by gc. */
6503 XMISCANY (obj)->gcmarkbit = 1;
6504 break;
6506 case Lisp_Misc_Save_Value:
6507 XMISCANY (obj)->gcmarkbit = 1;
6508 mark_save_value (XSAVE_VALUE (obj));
6509 break;
6511 case Lisp_Misc_Overlay:
6512 mark_overlay (XOVERLAY (obj));
6513 break;
6515 case Lisp_Misc_Finalizer:
6516 XMISCANY (obj)->gcmarkbit = true;
6517 mark_object (XFINALIZER (obj)->function);
6518 break;
6520 #ifdef HAVE_MODULES
6521 case Lisp_Misc_User_Ptr:
6522 XMISCANY (obj)->gcmarkbit = true;
6523 break;
6524 #endif
6526 default:
6527 emacs_abort ();
6529 break;
6531 case Lisp_Cons:
6533 register struct Lisp_Cons *ptr = XCONS (obj);
6534 if (CONS_MARKED_P (ptr))
6535 break;
6536 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
6537 CONS_MARK (ptr);
6538 /* If the cdr is nil, avoid recursion for the car. */
6539 if (EQ (ptr->u.cdr, Qnil))
6541 obj = ptr->car;
6542 cdr_count = 0;
6543 goto loop;
6545 mark_object (ptr->car);
6546 obj = ptr->u.cdr;
6547 cdr_count++;
6548 if (cdr_count == mark_object_loop_halt)
6549 emacs_abort ();
6550 goto loop;
6553 case Lisp_Float:
6554 CHECK_ALLOCATED_AND_LIVE (live_float_p);
6555 FLOAT_MARK (XFLOAT (obj));
6556 break;
6558 case_Lisp_Int:
6559 break;
6561 default:
6562 emacs_abort ();
6565 #undef CHECK_LIVE
6566 #undef CHECK_ALLOCATED
6567 #undef CHECK_ALLOCATED_AND_LIVE
6569 /* Mark the Lisp pointers in the terminal objects.
6570 Called by Fgarbage_collect. */
6572 static void
6573 mark_terminals (void)
6575 struct terminal *t;
6576 for (t = terminal_list; t; t = t->next_terminal)
6578 eassert (t->name != NULL);
6579 #ifdef HAVE_WINDOW_SYSTEM
6580 /* If a terminal object is reachable from a stacpro'ed object,
6581 it might have been marked already. Make sure the image cache
6582 gets marked. */
6583 mark_image_cache (t->image_cache);
6584 #endif /* HAVE_WINDOW_SYSTEM */
6585 if (!VECTOR_MARKED_P (t))
6586 mark_vectorlike ((struct Lisp_Vector *)t);
6592 /* Value is non-zero if OBJ will survive the current GC because it's
6593 either marked or does not need to be marked to survive. */
6595 bool
6596 survives_gc_p (Lisp_Object obj)
6598 bool survives_p;
6600 switch (XTYPE (obj))
6602 case_Lisp_Int:
6603 survives_p = 1;
6604 break;
6606 case Lisp_Symbol:
6607 survives_p = XSYMBOL (obj)->gcmarkbit;
6608 break;
6610 case Lisp_Misc:
6611 survives_p = XMISCANY (obj)->gcmarkbit;
6612 break;
6614 case Lisp_String:
6615 survives_p = STRING_MARKED_P (XSTRING (obj));
6616 break;
6618 case Lisp_Vectorlike:
6619 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
6620 break;
6622 case Lisp_Cons:
6623 survives_p = CONS_MARKED_P (XCONS (obj));
6624 break;
6626 case Lisp_Float:
6627 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
6628 break;
6630 default:
6631 emacs_abort ();
6634 return survives_p || PURE_P (XPNTR (obj));
6640 NO_INLINE /* For better stack traces */
6641 static void
6642 sweep_conses (void)
6644 struct cons_block *cblk;
6645 struct cons_block **cprev = &cons_block;
6646 int lim = cons_block_index;
6647 EMACS_INT num_free = 0, num_used = 0;
6649 cons_free_list = 0;
6651 for (cblk = cons_block; cblk; cblk = *cprev)
6653 int i = 0;
6654 int this_free = 0;
6655 int ilim = (lim + BITS_PER_BITS_WORD - 1) / BITS_PER_BITS_WORD;
6657 /* Scan the mark bits an int at a time. */
6658 for (i = 0; i < ilim; i++)
6660 if (cblk->gcmarkbits[i] == BITS_WORD_MAX)
6662 /* Fast path - all cons cells for this int are marked. */
6663 cblk->gcmarkbits[i] = 0;
6664 num_used += BITS_PER_BITS_WORD;
6666 else
6668 /* Some cons cells for this int are not marked.
6669 Find which ones, and free them. */
6670 int start, pos, stop;
6672 start = i * BITS_PER_BITS_WORD;
6673 stop = lim - start;
6674 if (stop > BITS_PER_BITS_WORD)
6675 stop = BITS_PER_BITS_WORD;
6676 stop += start;
6678 for (pos = start; pos < stop; pos++)
6680 if (!CONS_MARKED_P (&cblk->conses[pos]))
6682 this_free++;
6683 cblk->conses[pos].u.chain = cons_free_list;
6684 cons_free_list = &cblk->conses[pos];
6685 cons_free_list->car = Vdead;
6687 else
6689 num_used++;
6690 CONS_UNMARK (&cblk->conses[pos]);
6696 lim = CONS_BLOCK_SIZE;
6697 /* If this block contains only free conses and we have already
6698 seen more than two blocks worth of free conses then deallocate
6699 this block. */
6700 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
6702 *cprev = cblk->next;
6703 /* Unhook from the free list. */
6704 cons_free_list = cblk->conses[0].u.chain;
6705 lisp_align_free (cblk);
6707 else
6709 num_free += this_free;
6710 cprev = &cblk->next;
6713 total_conses = num_used;
6714 total_free_conses = num_free;
6717 NO_INLINE /* For better stack traces */
6718 static void
6719 sweep_floats (void)
6721 register struct float_block *fblk;
6722 struct float_block **fprev = &float_block;
6723 register int lim = float_block_index;
6724 EMACS_INT num_free = 0, num_used = 0;
6726 float_free_list = 0;
6728 for (fblk = float_block; fblk; fblk = *fprev)
6730 register int i;
6731 int this_free = 0;
6732 for (i = 0; i < lim; i++)
6733 if (!FLOAT_MARKED_P (&fblk->floats[i]))
6735 this_free++;
6736 fblk->floats[i].u.chain = float_free_list;
6737 float_free_list = &fblk->floats[i];
6739 else
6741 num_used++;
6742 FLOAT_UNMARK (&fblk->floats[i]);
6744 lim = FLOAT_BLOCK_SIZE;
6745 /* If this block contains only free floats and we have already
6746 seen more than two blocks worth of free floats then deallocate
6747 this block. */
6748 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6750 *fprev = fblk->next;
6751 /* Unhook from the free list. */
6752 float_free_list = fblk->floats[0].u.chain;
6753 lisp_align_free (fblk);
6755 else
6757 num_free += this_free;
6758 fprev = &fblk->next;
6761 total_floats = num_used;
6762 total_free_floats = num_free;
6765 NO_INLINE /* For better stack traces */
6766 static void
6767 sweep_intervals (void)
6769 register struct interval_block *iblk;
6770 struct interval_block **iprev = &interval_block;
6771 register int lim = interval_block_index;
6772 EMACS_INT num_free = 0, num_used = 0;
6774 interval_free_list = 0;
6776 for (iblk = interval_block; iblk; iblk = *iprev)
6778 register int i;
6779 int this_free = 0;
6781 for (i = 0; i < lim; i++)
6783 if (!iblk->intervals[i].gcmarkbit)
6785 set_interval_parent (&iblk->intervals[i], interval_free_list);
6786 interval_free_list = &iblk->intervals[i];
6787 this_free++;
6789 else
6791 num_used++;
6792 iblk->intervals[i].gcmarkbit = 0;
6795 lim = INTERVAL_BLOCK_SIZE;
6796 /* If this block contains only free intervals and we have already
6797 seen more than two blocks worth of free intervals then
6798 deallocate this block. */
6799 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6801 *iprev = iblk->next;
6802 /* Unhook from the free list. */
6803 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
6804 lisp_free (iblk);
6806 else
6808 num_free += this_free;
6809 iprev = &iblk->next;
6812 total_intervals = num_used;
6813 total_free_intervals = num_free;
6816 NO_INLINE /* For better stack traces */
6817 static void
6818 sweep_symbols (void)
6820 struct symbol_block *sblk;
6821 struct symbol_block **sprev = &symbol_block;
6822 int lim = symbol_block_index;
6823 EMACS_INT num_free = 0, num_used = ARRAYELTS (lispsym);
6825 symbol_free_list = NULL;
6827 for (int i = 0; i < ARRAYELTS (lispsym); i++)
6828 lispsym[i].gcmarkbit = 0;
6830 for (sblk = symbol_block; sblk; sblk = *sprev)
6832 int this_free = 0;
6833 union aligned_Lisp_Symbol *sym = sblk->symbols;
6834 union aligned_Lisp_Symbol *end = sym + lim;
6836 for (; sym < end; ++sym)
6838 if (!sym->s.gcmarkbit)
6840 if (sym->s.redirect == SYMBOL_LOCALIZED)
6841 xfree (SYMBOL_BLV (&sym->s));
6842 sym->s.next = symbol_free_list;
6843 symbol_free_list = &sym->s;
6844 symbol_free_list->function = Vdead;
6845 ++this_free;
6847 else
6849 ++num_used;
6850 sym->s.gcmarkbit = 0;
6851 /* Attempt to catch bogus objects. */
6852 eassert (valid_lisp_object_p (sym->s.function));
6856 lim = SYMBOL_BLOCK_SIZE;
6857 /* If this block contains only free symbols and we have already
6858 seen more than two blocks worth of free symbols then deallocate
6859 this block. */
6860 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6862 *sprev = sblk->next;
6863 /* Unhook from the free list. */
6864 symbol_free_list = sblk->symbols[0].s.next;
6865 lisp_free (sblk);
6867 else
6869 num_free += this_free;
6870 sprev = &sblk->next;
6873 total_symbols = num_used;
6874 total_free_symbols = num_free;
6877 NO_INLINE /* For better stack traces. */
6878 static void
6879 sweep_misc (void)
6881 register struct marker_block *mblk;
6882 struct marker_block **mprev = &marker_block;
6883 register int lim = marker_block_index;
6884 EMACS_INT num_free = 0, num_used = 0;
6886 /* Put all unmarked misc's on free list. For a marker, first
6887 unchain it from the buffer it points into. */
6889 marker_free_list = 0;
6891 for (mblk = marker_block; mblk; mblk = *mprev)
6893 register int i;
6894 int this_free = 0;
6896 for (i = 0; i < lim; i++)
6898 if (!mblk->markers[i].m.u_any.gcmarkbit)
6900 if (mblk->markers[i].m.u_any.type == Lisp_Misc_Marker)
6901 unchain_marker (&mblk->markers[i].m.u_marker);
6902 else if (mblk->markers[i].m.u_any.type == Lisp_Misc_Finalizer)
6903 unchain_finalizer (&mblk->markers[i].m.u_finalizer);
6904 #ifdef HAVE_MODULES
6905 else if (mblk->markers[i].m.u_any.type == Lisp_Misc_User_Ptr)
6907 struct Lisp_User_Ptr *uptr = &mblk->markers[i].m.u_user_ptr;
6908 uptr->finalizer (uptr->p);
6910 #endif
6911 /* Set the type of the freed object to Lisp_Misc_Free.
6912 We could leave the type alone, since nobody checks it,
6913 but this might catch bugs faster. */
6914 mblk->markers[i].m.u_marker.type = Lisp_Misc_Free;
6915 mblk->markers[i].m.u_free.chain = marker_free_list;
6916 marker_free_list = &mblk->markers[i].m;
6917 this_free++;
6919 else
6921 num_used++;
6922 mblk->markers[i].m.u_any.gcmarkbit = 0;
6925 lim = MARKER_BLOCK_SIZE;
6926 /* If this block contains only free markers and we have already
6927 seen more than two blocks worth of free markers then deallocate
6928 this block. */
6929 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6931 *mprev = mblk->next;
6932 /* Unhook from the free list. */
6933 marker_free_list = mblk->markers[0].m.u_free.chain;
6934 lisp_free (mblk);
6936 else
6938 num_free += this_free;
6939 mprev = &mblk->next;
6943 total_markers = num_used;
6944 total_free_markers = num_free;
6947 NO_INLINE /* For better stack traces */
6948 static void
6949 sweep_buffers (void)
6951 register struct buffer *buffer, **bprev = &all_buffers;
6953 total_buffers = 0;
6954 for (buffer = all_buffers; buffer; buffer = *bprev)
6955 if (!VECTOR_MARKED_P (buffer))
6957 *bprev = buffer->next;
6958 lisp_free (buffer);
6960 else
6962 VECTOR_UNMARK (buffer);
6963 /* Do not use buffer_(set|get)_intervals here. */
6964 buffer->text->intervals = balance_intervals (buffer->text->intervals);
6965 total_buffers++;
6966 bprev = &buffer->next;
6970 /* Sweep: find all structures not marked, and free them. */
6971 static void
6972 gc_sweep (void)
6974 /* Remove or mark entries in weak hash tables.
6975 This must be done before any object is unmarked. */
6976 sweep_weak_hash_tables ();
6978 sweep_strings ();
6979 check_string_bytes (!noninteractive);
6980 sweep_conses ();
6981 sweep_floats ();
6982 sweep_intervals ();
6983 sweep_symbols ();
6984 sweep_misc ();
6985 sweep_buffers ();
6986 sweep_vectors ();
6987 check_string_bytes (!noninteractive);
6990 DEFUN ("memory-info", Fmemory_info, Smemory_info, 0, 0, 0,
6991 doc: /* Return a list of (TOTAL-RAM FREE-RAM TOTAL-SWAP FREE-SWAP).
6992 All values are in Kbytes. If there is no swap space,
6993 last two values are zero. If the system is not supported
6994 or memory information can't be obtained, return nil. */)
6995 (void)
6997 #if defined HAVE_LINUX_SYSINFO
6998 struct sysinfo si;
6999 uintmax_t units;
7001 if (sysinfo (&si))
7002 return Qnil;
7003 #ifdef LINUX_SYSINFO_UNIT
7004 units = si.mem_unit;
7005 #else
7006 units = 1;
7007 #endif
7008 return list4i ((uintmax_t) si.totalram * units / 1024,
7009 (uintmax_t) si.freeram * units / 1024,
7010 (uintmax_t) si.totalswap * units / 1024,
7011 (uintmax_t) si.freeswap * units / 1024);
7012 #elif defined WINDOWSNT
7013 unsigned long long totalram, freeram, totalswap, freeswap;
7015 if (w32_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
7016 return list4i ((uintmax_t) totalram / 1024,
7017 (uintmax_t) freeram / 1024,
7018 (uintmax_t) totalswap / 1024,
7019 (uintmax_t) freeswap / 1024);
7020 else
7021 return Qnil;
7022 #elif defined MSDOS
7023 unsigned long totalram, freeram, totalswap, freeswap;
7025 if (dos_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
7026 return list4i ((uintmax_t) totalram / 1024,
7027 (uintmax_t) freeram / 1024,
7028 (uintmax_t) totalswap / 1024,
7029 (uintmax_t) freeswap / 1024);
7030 else
7031 return Qnil;
7032 #else /* not HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
7033 /* FIXME: add more systems. */
7034 return Qnil;
7035 #endif /* HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
7038 /* Debugging aids. */
7040 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
7041 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
7042 This may be helpful in debugging Emacs's memory usage.
7043 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
7044 (void)
7046 Lisp_Object end;
7048 #ifdef HAVE_NS
7049 /* Avoid warning. sbrk has no relation to memory allocated anyway. */
7050 XSETINT (end, 0);
7051 #else
7052 XSETINT (end, (intptr_t) (char *) sbrk (0) / 1024);
7053 #endif
7055 return end;
7058 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
7059 doc: /* Return a list of counters that measure how much consing there has been.
7060 Each of these counters increments for a certain kind of object.
7061 The counters wrap around from the largest positive integer to zero.
7062 Garbage collection does not decrease them.
7063 The elements of the value are as follows:
7064 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
7065 All are in units of 1 = one object consed
7066 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
7067 objects consed.
7068 MISCS include overlays, markers, and some internal types.
7069 Frames, windows, buffers, and subprocesses count as vectors
7070 (but the contents of a buffer's text do not count here). */)
7071 (void)
7073 return listn (CONSTYPE_HEAP, 8,
7074 bounded_number (cons_cells_consed),
7075 bounded_number (floats_consed),
7076 bounded_number (vector_cells_consed),
7077 bounded_number (symbols_consed),
7078 bounded_number (string_chars_consed),
7079 bounded_number (misc_objects_consed),
7080 bounded_number (intervals_consed),
7081 bounded_number (strings_consed));
7084 static bool
7085 symbol_uses_obj (Lisp_Object symbol, Lisp_Object obj)
7087 struct Lisp_Symbol *sym = XSYMBOL (symbol);
7088 Lisp_Object val = find_symbol_value (symbol);
7089 return (EQ (val, obj)
7090 || EQ (sym->function, obj)
7091 || (!NILP (sym->function)
7092 && COMPILEDP (sym->function)
7093 && EQ (AREF (sym->function, COMPILED_BYTECODE), obj))
7094 || (!NILP (val)
7095 && COMPILEDP (val)
7096 && EQ (AREF (val, COMPILED_BYTECODE), obj)));
7099 /* Find at most FIND_MAX symbols which have OBJ as their value or
7100 function. This is used in gdbinit's `xwhichsymbols' command. */
7102 Lisp_Object
7103 which_symbols (Lisp_Object obj, EMACS_INT find_max)
7105 struct symbol_block *sblk;
7106 ptrdiff_t gc_count = inhibit_garbage_collection ();
7107 Lisp_Object found = Qnil;
7109 if (! DEADP (obj))
7111 for (int i = 0; i < ARRAYELTS (lispsym); i++)
7113 Lisp_Object sym = builtin_lisp_symbol (i);
7114 if (symbol_uses_obj (sym, obj))
7116 found = Fcons (sym, found);
7117 if (--find_max == 0)
7118 goto out;
7122 for (sblk = symbol_block; sblk; sblk = sblk->next)
7124 union aligned_Lisp_Symbol *aligned_sym = sblk->symbols;
7125 int bn;
7127 for (bn = 0; bn < SYMBOL_BLOCK_SIZE; bn++, aligned_sym++)
7129 if (sblk == symbol_block && bn >= symbol_block_index)
7130 break;
7132 Lisp_Object sym = make_lisp_symbol (&aligned_sym->s);
7133 if (symbol_uses_obj (sym, obj))
7135 found = Fcons (sym, found);
7136 if (--find_max == 0)
7137 goto out;
7143 out:
7144 unbind_to (gc_count, Qnil);
7145 return found;
7148 #ifdef SUSPICIOUS_OBJECT_CHECKING
7150 static void *
7151 find_suspicious_object_in_range (void *begin, void *end)
7153 char *begin_a = begin;
7154 char *end_a = end;
7155 int i;
7157 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
7159 char *suspicious_object = suspicious_objects[i];
7160 if (begin_a <= suspicious_object && suspicious_object < end_a)
7161 return suspicious_object;
7164 return NULL;
7167 static void
7168 note_suspicious_free (void* ptr)
7170 struct suspicious_free_record* rec;
7172 rec = &suspicious_free_history[suspicious_free_history_index++];
7173 if (suspicious_free_history_index ==
7174 ARRAYELTS (suspicious_free_history))
7176 suspicious_free_history_index = 0;
7179 memset (rec, 0, sizeof (*rec));
7180 rec->suspicious_object = ptr;
7181 backtrace (&rec->backtrace[0], ARRAYELTS (rec->backtrace));
7184 static void
7185 detect_suspicious_free (void* ptr)
7187 int i;
7189 eassert (ptr != NULL);
7191 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
7192 if (suspicious_objects[i] == ptr)
7194 note_suspicious_free (ptr);
7195 suspicious_objects[i] = NULL;
7199 #endif /* SUSPICIOUS_OBJECT_CHECKING */
7201 DEFUN ("suspicious-object", Fsuspicious_object, Ssuspicious_object, 1, 1, 0,
7202 doc: /* Return OBJ, maybe marking it for extra scrutiny.
7203 If Emacs is compiled with suspicious object checking, capture
7204 a stack trace when OBJ is freed in order to help track down
7205 garbage collection bugs. Otherwise, do nothing and return OBJ. */)
7206 (Lisp_Object obj)
7208 #ifdef SUSPICIOUS_OBJECT_CHECKING
7209 /* Right now, we care only about vectors. */
7210 if (VECTORLIKEP (obj))
7212 suspicious_objects[suspicious_object_index++] = XVECTOR (obj);
7213 if (suspicious_object_index == ARRAYELTS (suspicious_objects))
7214 suspicious_object_index = 0;
7216 #endif
7217 return obj;
7220 #ifdef ENABLE_CHECKING
7222 bool suppress_checking;
7224 void
7225 die (const char *msg, const char *file, int line)
7227 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: assertion failed: %s\r\n",
7228 file, line, msg);
7229 terminate_due_to_signal (SIGABRT, INT_MAX);
7232 #endif /* ENABLE_CHECKING */
7234 #if defined (ENABLE_CHECKING) && USE_STACK_LISP_OBJECTS
7236 /* Stress alloca with inconveniently sized requests and check
7237 whether all allocated areas may be used for Lisp_Object. */
7239 NO_INLINE static void
7240 verify_alloca (void)
7242 int i;
7243 enum { ALLOCA_CHECK_MAX = 256 };
7244 /* Start from size of the smallest Lisp object. */
7245 for (i = sizeof (struct Lisp_Cons); i <= ALLOCA_CHECK_MAX; i++)
7247 void *ptr = alloca (i);
7248 make_lisp_ptr (ptr, Lisp_Cons);
7252 #else /* not ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7254 #define verify_alloca() ((void) 0)
7256 #endif /* ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7258 /* Initialization. */
7260 void
7261 init_alloc_once (void)
7263 /* Even though Qt's contents are not set up, its address is known. */
7264 Vpurify_flag = Qt;
7266 purebeg = PUREBEG;
7267 pure_size = PURESIZE;
7269 verify_alloca ();
7270 init_finalizer_list (&finalizers);
7271 init_finalizer_list (&doomed_finalizers);
7273 mem_init ();
7274 Vdead = make_pure_string ("DEAD", 4, 4, 0);
7276 #ifdef DOUG_LEA_MALLOC
7277 mallopt (M_TRIM_THRESHOLD, 128 * 1024); /* Trim threshold. */
7278 mallopt (M_MMAP_THRESHOLD, 64 * 1024); /* Mmap threshold. */
7279 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* Max. number of mmap'ed areas. */
7280 #endif
7281 init_strings ();
7282 init_vectors ();
7284 refill_memory_reserve ();
7285 gc_cons_threshold = GC_DEFAULT_THRESHOLD;
7288 void
7289 init_alloc (void)
7291 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
7292 setjmp_tested_p = longjmps_done = 0;
7293 #endif
7294 Vgc_elapsed = make_float (0.0);
7295 gcs_done = 0;
7297 #if USE_VALGRIND
7298 valgrind_p = RUNNING_ON_VALGRIND != 0;
7299 #endif
7302 void
7303 syms_of_alloc (void)
7305 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
7306 doc: /* Number of bytes of consing between garbage collections.
7307 Garbage collection can happen automatically once this many bytes have been
7308 allocated since the last garbage collection. All data types count.
7310 Garbage collection happens automatically only when `eval' is called.
7312 By binding this temporarily to a large number, you can effectively
7313 prevent garbage collection during a part of the program.
7314 See also `gc-cons-percentage'. */);
7316 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
7317 doc: /* Portion of the heap used for allocation.
7318 Garbage collection can happen automatically once this portion of the heap
7319 has been allocated since the last garbage collection.
7320 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
7321 Vgc_cons_percentage = make_float (0.1);
7323 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
7324 doc: /* Number of bytes of shareable Lisp data allocated so far. */);
7326 DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
7327 doc: /* Number of cons cells that have been consed so far. */);
7329 DEFVAR_INT ("floats-consed", floats_consed,
7330 doc: /* Number of floats that have been consed so far. */);
7332 DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
7333 doc: /* Number of vector cells that have been consed so far. */);
7335 DEFVAR_INT ("symbols-consed", symbols_consed,
7336 doc: /* Number of symbols that have been consed so far. */);
7337 symbols_consed += ARRAYELTS (lispsym);
7339 DEFVAR_INT ("string-chars-consed", string_chars_consed,
7340 doc: /* Number of string characters that have been consed so far. */);
7342 DEFVAR_INT ("misc-objects-consed", misc_objects_consed,
7343 doc: /* Number of miscellaneous objects that have been consed so far.
7344 These include markers and overlays, plus certain objects not visible
7345 to users. */);
7347 DEFVAR_INT ("intervals-consed", intervals_consed,
7348 doc: /* Number of intervals that have been consed so far. */);
7350 DEFVAR_INT ("strings-consed", strings_consed,
7351 doc: /* Number of strings that have been consed so far. */);
7353 DEFVAR_LISP ("purify-flag", Vpurify_flag,
7354 doc: /* Non-nil means loading Lisp code in order to dump an executable.
7355 This means that certain objects should be allocated in shared (pure) space.
7356 It can also be set to a hash-table, in which case this table is used to
7357 do hash-consing of the objects allocated to pure space. */);
7359 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
7360 doc: /* Non-nil means display messages at start and end of garbage collection. */);
7361 garbage_collection_messages = 0;
7363 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
7364 doc: /* Hook run after garbage collection has finished. */);
7365 Vpost_gc_hook = Qnil;
7366 DEFSYM (Qpost_gc_hook, "post-gc-hook");
7368 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
7369 doc: /* Precomputed `signal' argument for memory-full error. */);
7370 /* We build this in advance because if we wait until we need it, we might
7371 not be able to allocate the memory to hold it. */
7372 Vmemory_signal_data
7373 = listn (CONSTYPE_PURE, 2, Qerror,
7374 build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
7376 DEFVAR_LISP ("memory-full", Vmemory_full,
7377 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
7378 Vmemory_full = Qnil;
7380 DEFSYM (Qconses, "conses");
7381 DEFSYM (Qsymbols, "symbols");
7382 DEFSYM (Qmiscs, "miscs");
7383 DEFSYM (Qstrings, "strings");
7384 DEFSYM (Qvectors, "vectors");
7385 DEFSYM (Qfloats, "floats");
7386 DEFSYM (Qintervals, "intervals");
7387 DEFSYM (Qbuffers, "buffers");
7388 DEFSYM (Qstring_bytes, "string-bytes");
7389 DEFSYM (Qvector_slots, "vector-slots");
7390 DEFSYM (Qheap, "heap");
7391 DEFSYM (QAutomatic_GC, "Automatic GC");
7393 DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
7394 DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
7396 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
7397 doc: /* Accumulated time elapsed in garbage collections.
7398 The time is in seconds as a floating point value. */);
7399 DEFVAR_INT ("gcs-done", gcs_done,
7400 doc: /* Accumulated number of garbage collections done. */);
7402 defsubr (&Scons);
7403 defsubr (&Slist);
7404 defsubr (&Svector);
7405 defsubr (&Sbool_vector);
7406 defsubr (&Smake_byte_code);
7407 defsubr (&Smake_list);
7408 defsubr (&Smake_vector);
7409 defsubr (&Smake_string);
7410 defsubr (&Smake_bool_vector);
7411 defsubr (&Smake_symbol);
7412 defsubr (&Smake_marker);
7413 defsubr (&Smake_finalizer);
7414 defsubr (&Spurecopy);
7415 defsubr (&Sgarbage_collect);
7416 defsubr (&Smemory_limit);
7417 defsubr (&Smemory_info);
7418 defsubr (&Smemory_use_counts);
7419 defsubr (&Ssuspicious_object);
7422 /* When compiled with GCC, GDB might say "No enum type named
7423 pvec_type" if we don't have at least one symbol with that type, and
7424 then xbacktrace could fail. Similarly for the other enums and
7425 their values. Some non-GCC compilers don't like these constructs. */
7426 #ifdef __GNUC__
7427 union
7429 enum CHARTAB_SIZE_BITS CHARTAB_SIZE_BITS;
7430 enum char_table_specials char_table_specials;
7431 enum char_bits char_bits;
7432 enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE;
7433 enum DEFAULT_HASH_SIZE DEFAULT_HASH_SIZE;
7434 enum Lisp_Bits Lisp_Bits;
7435 enum Lisp_Compiled Lisp_Compiled;
7436 enum maxargs maxargs;
7437 enum MAX_ALLOCA MAX_ALLOCA;
7438 enum More_Lisp_Bits More_Lisp_Bits;
7439 enum pvec_type pvec_type;
7440 } const EXTERNALLY_VISIBLE gdb_make_enums_visible = {0};
7441 #endif /* __GNUC__ */