Do not use map.el in seq-tests.el
[emacs.git] / src / alloc.c
blob90c6f9441faf96183744bdf67087c104e13a3fce
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 <stdlib.h>
26 #include <limits.h> /* For CHAR_BIT. */
27 #include <signal.h> /* For SIGABRT, SIGDANGER. */
29 #ifdef HAVE_PTHREAD
30 #include <pthread.h>
31 #endif
33 #include "lisp.h"
34 #include "dispextern.h"
35 #include "intervals.h"
36 #include "puresize.h"
37 #include "sheap.h"
38 #include "systime.h"
39 #include "character.h"
40 #include "buffer.h"
41 #include "window.h"
42 #include "keyboard.h"
43 #include "frame.h"
44 #include "blockinput.h"
45 #include "termhooks.h" /* For struct terminal. */
46 #ifdef HAVE_WINDOW_SYSTEM
47 #include TERM_HEADER
48 #endif /* HAVE_WINDOW_SYSTEM */
50 #include <flexmember.h>
51 #include <verify.h>
52 #include <execinfo.h> /* For backtrace. */
54 #ifdef HAVE_LINUX_SYSINFO
55 #include <sys/sysinfo.h>
56 #endif
58 #ifdef MSDOS
59 #include "dosfns.h" /* For dos_memory_info. */
60 #endif
62 #ifdef HAVE_MALLOC_H
63 # include <malloc.h>
64 #endif
66 #if (defined ENABLE_CHECKING \
67 && defined HAVE_VALGRIND_VALGRIND_H \
68 && !defined USE_VALGRIND)
69 # define USE_VALGRIND 1
70 #endif
72 #if USE_VALGRIND
73 #include <valgrind/valgrind.h>
74 #include <valgrind/memcheck.h>
75 static bool valgrind_p;
76 #endif
78 /* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects. */
80 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
81 memory. Can do this only if using gmalloc.c and if not checking
82 marked objects. */
84 #if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
85 || defined HYBRID_MALLOC || defined GC_CHECK_MARKED_OBJECTS)
86 #undef GC_MALLOC_CHECK
87 #endif
89 #include <unistd.h>
90 #include <fcntl.h>
92 #ifdef USE_GTK
93 # include "gtkutil.h"
94 #endif
95 #ifdef WINDOWSNT
96 #include "w32.h"
97 #include "w32heap.h" /* for sbrk */
98 #endif
100 #ifdef GNU_LINUX
101 /* The address where the heap starts. */
102 void *
103 my_heap_start (void)
105 static void *start;
106 if (! start)
107 start = sbrk (0);
108 return start;
110 #endif
112 #ifdef DOUG_LEA_MALLOC
114 /* Specify maximum number of areas to mmap. It would be nice to use a
115 value that explicitly means "no limit". */
117 #define MMAP_MAX_AREAS 100000000
119 /* A pointer to the memory allocated that copies that static data
120 inside glibc's malloc. */
121 static void *malloc_state_ptr;
123 /* Restore the dumped malloc state. Because malloc can be invoked
124 even before main (e.g. by the dynamic linker), the dumped malloc
125 state must be restored as early as possible using this special hook. */
126 static void
127 malloc_initialize_hook (void)
129 static bool malloc_using_checking;
131 if (! initialized)
133 #ifdef GNU_LINUX
134 my_heap_start ();
135 #endif
136 malloc_using_checking = getenv ("MALLOC_CHECK_") != NULL;
138 else
140 if (!malloc_using_checking)
142 /* Work around a bug in glibc's malloc. MALLOC_CHECK_ must be
143 ignored if the heap to be restored was constructed without
144 malloc checking. Can't use unsetenv, since that calls malloc. */
145 char **p = environ;
146 if (p)
147 for (; *p; p++)
148 if (strncmp (*p, "MALLOC_CHECK_=", 14) == 0)
151 *p = p[1];
152 while (*++p);
154 break;
158 if (malloc_set_state (malloc_state_ptr) != 0)
159 emacs_abort ();
160 # ifndef XMALLOC_OVERRUN_CHECK
161 alloc_unexec_post ();
162 # endif
166 /* Declare the malloc initialization hook, which runs before 'main' starts.
167 EXTERNALLY_VISIBLE works around Bug#22522. */
168 # ifndef __MALLOC_HOOK_VOLATILE
169 # define __MALLOC_HOOK_VOLATILE
170 # endif
171 voidfuncptr __MALLOC_HOOK_VOLATILE __malloc_initialize_hook EXTERNALLY_VISIBLE
172 = malloc_initialize_hook;
174 #endif
176 /* Allocator-related actions to do just before and after unexec. */
178 void
179 alloc_unexec_pre (void)
181 #ifdef DOUG_LEA_MALLOC
182 malloc_state_ptr = malloc_get_state ();
183 if (!malloc_state_ptr)
184 fatal ("malloc_get_state: %s", strerror (errno));
185 #endif
186 #ifdef HYBRID_MALLOC
187 bss_sbrk_did_unexec = true;
188 #endif
191 void
192 alloc_unexec_post (void)
194 #ifdef DOUG_LEA_MALLOC
195 free (malloc_state_ptr);
196 #endif
197 #ifdef HYBRID_MALLOC
198 bss_sbrk_did_unexec = false;
199 #endif
202 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
203 to a struct Lisp_String. */
205 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
206 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
207 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
209 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
210 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
211 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
213 /* Default value of gc_cons_threshold (see below). */
215 #define GC_DEFAULT_THRESHOLD (100000 * word_size)
217 /* Global variables. */
218 struct emacs_globals globals;
220 /* Number of bytes of consing done since the last gc. */
222 EMACS_INT consing_since_gc;
224 /* Similar minimum, computed from Vgc_cons_percentage. */
226 EMACS_INT gc_relative_threshold;
228 /* Minimum number of bytes of consing since GC before next GC,
229 when memory is full. */
231 EMACS_INT memory_full_cons_threshold;
233 /* True during GC. */
235 bool gc_in_progress;
237 /* Number of live and free conses etc. */
239 static EMACS_INT total_conses, total_markers, total_symbols, total_buffers;
240 static EMACS_INT total_free_conses, total_free_markers, total_free_symbols;
241 static EMACS_INT total_free_floats, total_floats;
243 /* Points to memory space allocated as "spare", to be freed if we run
244 out of memory. We keep one large block, four cons-blocks, and
245 two string blocks. */
247 static char *spare_memory[7];
249 /* Amount of spare memory to keep in large reserve block, or to see
250 whether this much is available when malloc fails on a larger request. */
252 #define SPARE_MEMORY (1 << 14)
254 /* Initialize it to a nonzero value to force it into data space
255 (rather than bss space). That way unexec will remap it into text
256 space (pure), on some systems. We have not implemented the
257 remapping on more recent systems because this is less important
258 nowadays than in the days of small memories and timesharing. */
260 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
261 #define PUREBEG (char *) pure
263 /* Pointer to the pure area, and its size. */
265 static char *purebeg;
266 static ptrdiff_t pure_size;
268 /* Number of bytes of pure storage used before pure storage overflowed.
269 If this is non-zero, this implies that an overflow occurred. */
271 static ptrdiff_t pure_bytes_used_before_overflow;
273 /* Index in pure at which next pure Lisp object will be allocated.. */
275 static ptrdiff_t pure_bytes_used_lisp;
277 /* Number of bytes allocated for non-Lisp objects in pure storage. */
279 static ptrdiff_t pure_bytes_used_non_lisp;
281 /* If nonzero, this is a warning delivered by malloc and not yet
282 displayed. */
284 const char *pending_malloc_warning;
286 #if 0 /* Normally, pointer sanity only on request... */
287 #ifdef ENABLE_CHECKING
288 #define SUSPICIOUS_OBJECT_CHECKING 1
289 #endif
290 #endif
292 /* ... but unconditionally use SUSPICIOUS_OBJECT_CHECKING while the GC
293 bug is unresolved. */
294 #define SUSPICIOUS_OBJECT_CHECKING 1
296 #ifdef SUSPICIOUS_OBJECT_CHECKING
297 struct suspicious_free_record
299 void *suspicious_object;
300 void *backtrace[128];
302 static void *suspicious_objects[32];
303 static int suspicious_object_index;
304 struct suspicious_free_record suspicious_free_history[64] EXTERNALLY_VISIBLE;
305 static int suspicious_free_history_index;
306 /* Find the first currently-monitored suspicious pointer in range
307 [begin,end) or NULL if no such pointer exists. */
308 static void *find_suspicious_object_in_range (void *begin, void *end);
309 static void detect_suspicious_free (void *ptr);
310 #else
311 # define find_suspicious_object_in_range(begin, end) NULL
312 # define detect_suspicious_free(ptr) (void)
313 #endif
315 /* Maximum amount of C stack to save when a GC happens. */
317 #ifndef MAX_SAVE_STACK
318 #define MAX_SAVE_STACK 16000
319 #endif
321 /* Buffer in which we save a copy of the C stack at each GC. */
323 #if MAX_SAVE_STACK > 0
324 static char *stack_copy;
325 static ptrdiff_t stack_copy_size;
327 /* Copy to DEST a block of memory from SRC of size SIZE bytes,
328 avoiding any address sanitization. */
330 static void * ATTRIBUTE_NO_SANITIZE_ADDRESS
331 no_sanitize_memcpy (void *dest, void const *src, size_t size)
333 if (! ADDRESS_SANITIZER)
334 return memcpy (dest, src, size);
335 else
337 size_t i;
338 char *d = dest;
339 char const *s = src;
340 for (i = 0; i < size; i++)
341 d[i] = s[i];
342 return dest;
346 #endif /* MAX_SAVE_STACK > 0 */
348 static void mark_terminals (void);
349 static void gc_sweep (void);
350 static Lisp_Object make_pure_vector (ptrdiff_t);
351 static void mark_buffer (struct buffer *);
353 #if !defined REL_ALLOC || defined SYSTEM_MALLOC || defined HYBRID_MALLOC
354 static void refill_memory_reserve (void);
355 #endif
356 static void compact_small_strings (void);
357 static void free_large_strings (void);
358 extern Lisp_Object which_symbols (Lisp_Object, EMACS_INT) EXTERNALLY_VISIBLE;
360 /* When scanning the C stack for live Lisp objects, Emacs keeps track of
361 what memory allocated via lisp_malloc and lisp_align_malloc is intended
362 for what purpose. This enumeration specifies the type of memory. */
364 enum mem_type
366 MEM_TYPE_NON_LISP,
367 MEM_TYPE_BUFFER,
368 MEM_TYPE_CONS,
369 MEM_TYPE_STRING,
370 MEM_TYPE_MISC,
371 MEM_TYPE_SYMBOL,
372 MEM_TYPE_FLOAT,
373 /* Since all non-bool pseudovectors are small enough to be
374 allocated from vector blocks, this memory type denotes
375 large regular vectors and large bool pseudovectors. */
376 MEM_TYPE_VECTORLIKE,
377 /* Special type to denote vector blocks. */
378 MEM_TYPE_VECTOR_BLOCK,
379 /* Special type to denote reserved memory. */
380 MEM_TYPE_SPARE
383 /* A unique object in pure space used to make some Lisp objects
384 on free lists recognizable in O(1). */
386 static Lisp_Object Vdead;
387 #define DEADP(x) EQ (x, Vdead)
389 #ifdef GC_MALLOC_CHECK
391 enum mem_type allocated_mem_type;
393 #endif /* GC_MALLOC_CHECK */
395 /* A node in the red-black tree describing allocated memory containing
396 Lisp data. Each such block is recorded with its start and end
397 address when it is allocated, and removed from the tree when it
398 is freed.
400 A red-black tree is a balanced binary tree with the following
401 properties:
403 1. Every node is either red or black.
404 2. Every leaf is black.
405 3. If a node is red, then both of its children are black.
406 4. Every simple path from a node to a descendant leaf contains
407 the same number of black nodes.
408 5. The root is always black.
410 When nodes are inserted into the tree, or deleted from the tree,
411 the tree is "fixed" so that these properties are always true.
413 A red-black tree with N internal nodes has height at most 2
414 log(N+1). Searches, insertions and deletions are done in O(log N).
415 Please see a text book about data structures for a detailed
416 description of red-black trees. Any book worth its salt should
417 describe them. */
419 struct mem_node
421 /* Children of this node. These pointers are never NULL. When there
422 is no child, the value is MEM_NIL, which points to a dummy node. */
423 struct mem_node *left, *right;
425 /* The parent of this node. In the root node, this is NULL. */
426 struct mem_node *parent;
428 /* Start and end of allocated region. */
429 void *start, *end;
431 /* Node color. */
432 enum {MEM_BLACK, MEM_RED} color;
434 /* Memory type. */
435 enum mem_type type;
438 /* Base address of stack. Set in main. */
440 Lisp_Object *stack_base;
442 /* Root of the tree describing allocated Lisp memory. */
444 static struct mem_node *mem_root;
446 /* Lowest and highest known address in the heap. */
448 static void *min_heap_address, *max_heap_address;
450 /* Sentinel node of the tree. */
452 static struct mem_node mem_z;
453 #define MEM_NIL &mem_z
455 static struct mem_node *mem_insert (void *, void *, enum mem_type);
456 static void mem_insert_fixup (struct mem_node *);
457 static void mem_rotate_left (struct mem_node *);
458 static void mem_rotate_right (struct mem_node *);
459 static void mem_delete (struct mem_node *);
460 static void mem_delete_fixup (struct mem_node *);
461 static struct mem_node *mem_find (void *);
463 #ifndef DEADP
464 # define DEADP(x) 0
465 #endif
467 /* Addresses of staticpro'd variables. Initialize it to a nonzero
468 value; otherwise some compilers put it into BSS. */
470 enum { NSTATICS = 2048 };
471 static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
473 /* Index of next unused slot in staticvec. */
475 static int staticidx;
477 static void *pure_alloc (size_t, int);
479 /* True if N is a power of 2. N should be positive. */
481 #define POWER_OF_2(n) (((n) & ((n) - 1)) == 0)
483 /* Return X rounded to the next multiple of Y. Y should be positive,
484 and Y - 1 + X should not overflow. Arguments should not have side
485 effects, as they are evaluated more than once. Tune for Y being a
486 power of 2. */
488 #define ROUNDUP(x, y) (POWER_OF_2 (y) \
489 ? ((y) - 1 + (x)) & ~ ((y) - 1) \
490 : ((y) - 1 + (x)) - ((y) - 1 + (x)) % (y))
492 /* Return PTR rounded up to the next multiple of ALIGNMENT. */
494 static void *
495 pointer_align (void *ptr, int alignment)
497 return (void *) ROUNDUP ((uintptr_t) ptr, alignment);
500 /* Extract the pointer hidden within A, if A is not a symbol.
501 If A is a symbol, extract the hidden pointer's offset from lispsym,
502 converted to void *. */
504 #define macro_XPNTR_OR_SYMBOL_OFFSET(a) \
505 ((void *) (intptr_t) (USE_LSB_TAG ? XLI (a) - XTYPE (a) : XLI (a) & VALMASK))
507 /* Extract the pointer hidden within A. */
509 #define macro_XPNTR(a) \
510 ((void *) ((intptr_t) XPNTR_OR_SYMBOL_OFFSET (a) \
511 + (SYMBOLP (a) ? (char *) lispsym : NULL)))
513 /* For pointer access, define XPNTR and XPNTR_OR_SYMBOL_OFFSET as
514 functions, as functions are cleaner and can be used in debuggers.
515 Also, define them as macros if being compiled with GCC without
516 optimization, for performance in that case. The macro_* names are
517 private to this section of code. */
519 static ATTRIBUTE_UNUSED void *
520 XPNTR_OR_SYMBOL_OFFSET (Lisp_Object a)
522 return macro_XPNTR_OR_SYMBOL_OFFSET (a);
524 static ATTRIBUTE_UNUSED void *
525 XPNTR (Lisp_Object a)
527 return macro_XPNTR (a);
530 #if DEFINE_KEY_OPS_AS_MACROS
531 # define XPNTR_OR_SYMBOL_OFFSET(a) macro_XPNTR_OR_SYMBOL_OFFSET (a)
532 # define XPNTR(a) macro_XPNTR (a)
533 #endif
535 static void
536 XFLOAT_INIT (Lisp_Object f, double n)
538 XFLOAT (f)->u.data = n;
541 #ifdef DOUG_LEA_MALLOC
542 static bool
543 pointers_fit_in_lispobj_p (void)
545 return (UINTPTR_MAX <= VAL_MAX) || USE_LSB_TAG;
548 static bool
549 mmap_lisp_allowed_p (void)
551 /* If we can't store all memory addresses in our lisp objects, it's
552 risky to let the heap use mmap and give us addresses from all
553 over our address space. We also can't use mmap for lisp objects
554 if we might dump: unexec doesn't preserve the contents of mmapped
555 regions. */
556 return pointers_fit_in_lispobj_p () && !might_dump;
558 #endif
560 /* Head of a circularly-linked list of extant finalizers. */
561 static struct Lisp_Finalizer finalizers;
563 /* Head of a circularly-linked list of finalizers that must be invoked
564 because we deemed them unreachable. This list must be global, and
565 not a local inside garbage_collect_1, in case we GC again while
566 running finalizers. */
567 static struct Lisp_Finalizer doomed_finalizers;
570 /************************************************************************
571 Malloc
572 ************************************************************************/
574 #if defined SIGDANGER || (!defined SYSTEM_MALLOC && !defined HYBRID_MALLOC)
576 /* Function malloc calls this if it finds we are near exhausting storage. */
578 void
579 malloc_warning (const char *str)
581 pending_malloc_warning = str;
584 #endif
586 /* Display an already-pending malloc warning. */
588 void
589 display_malloc_warning (void)
591 call3 (intern ("display-warning"),
592 intern ("alloc"),
593 build_string (pending_malloc_warning),
594 intern ("emergency"));
595 pending_malloc_warning = 0;
598 /* Called if we can't allocate relocatable space for a buffer. */
600 void
601 buffer_memory_full (ptrdiff_t nbytes)
603 /* If buffers use the relocating allocator, no need to free
604 spare_memory, because we may have plenty of malloc space left
605 that we could get, and if we don't, the malloc that fails will
606 itself cause spare_memory to be freed. If buffers don't use the
607 relocating allocator, treat this like any other failing
608 malloc. */
610 #ifndef REL_ALLOC
611 memory_full (nbytes);
612 #else
613 /* This used to call error, but if we've run out of memory, we could
614 get infinite recursion trying to build the string. */
615 xsignal (Qnil, Vmemory_signal_data);
616 #endif
619 /* A common multiple of the positive integers A and B. Ideally this
620 would be the least common multiple, but there's no way to do that
621 as a constant expression in C, so do the best that we can easily do. */
622 #define COMMON_MULTIPLE(a, b) \
623 ((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
625 #ifndef XMALLOC_OVERRUN_CHECK
626 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
627 #else
629 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
630 around each block.
632 The header consists of XMALLOC_OVERRUN_CHECK_SIZE fixed bytes
633 followed by XMALLOC_OVERRUN_SIZE_SIZE bytes containing the original
634 block size in little-endian order. The trailer consists of
635 XMALLOC_OVERRUN_CHECK_SIZE fixed bytes.
637 The header is used to detect whether this block has been allocated
638 through these functions, as some low-level libc functions may
639 bypass the malloc hooks. */
641 #define XMALLOC_OVERRUN_CHECK_SIZE 16
642 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
643 (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)
645 #define XMALLOC_BASE_ALIGNMENT alignof (max_align_t)
647 #define XMALLOC_HEADER_ALIGNMENT \
648 COMMON_MULTIPLE (GCALIGNMENT, XMALLOC_BASE_ALIGNMENT)
650 /* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
651 hold a size_t value and (2) the header size is a multiple of the
652 alignment that Emacs needs for C types and for USE_LSB_TAG. */
653 #define XMALLOC_OVERRUN_SIZE_SIZE \
654 (((XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t) \
655 + XMALLOC_HEADER_ALIGNMENT - 1) \
656 / XMALLOC_HEADER_ALIGNMENT * XMALLOC_HEADER_ALIGNMENT) \
657 - XMALLOC_OVERRUN_CHECK_SIZE)
659 static char const xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE] =
660 { '\x9a', '\x9b', '\xae', '\xaf',
661 '\xbf', '\xbe', '\xce', '\xcf',
662 '\xea', '\xeb', '\xec', '\xed',
663 '\xdf', '\xde', '\x9c', '\x9d' };
665 static char const xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
666 { '\xaa', '\xab', '\xac', '\xad',
667 '\xba', '\xbb', '\xbc', '\xbd',
668 '\xca', '\xcb', '\xcc', '\xcd',
669 '\xda', '\xdb', '\xdc', '\xdd' };
671 /* Insert and extract the block size in the header. */
673 static void
674 xmalloc_put_size (unsigned char *ptr, size_t size)
676 int i;
677 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
679 *--ptr = size & ((1 << CHAR_BIT) - 1);
680 size >>= CHAR_BIT;
684 static size_t
685 xmalloc_get_size (unsigned char *ptr)
687 size_t size = 0;
688 int i;
689 ptr -= XMALLOC_OVERRUN_SIZE_SIZE;
690 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
692 size <<= CHAR_BIT;
693 size += *ptr++;
695 return size;
699 /* Like malloc, but wraps allocated block with header and trailer. */
701 static void *
702 overrun_check_malloc (size_t size)
704 register unsigned char *val;
705 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
706 emacs_abort ();
708 val = malloc (size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
709 if (val)
711 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
712 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
713 xmalloc_put_size (val, size);
714 memcpy (val + size, xmalloc_overrun_check_trailer,
715 XMALLOC_OVERRUN_CHECK_SIZE);
717 return val;
721 /* Like realloc, but checks old block for overrun, and wraps new block
722 with header and trailer. */
724 static void *
725 overrun_check_realloc (void *block, size_t size)
727 register unsigned char *val = (unsigned char *) block;
728 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
729 emacs_abort ();
731 if (val
732 && memcmp (xmalloc_overrun_check_header,
733 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
734 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
736 size_t osize = xmalloc_get_size (val);
737 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
738 XMALLOC_OVERRUN_CHECK_SIZE))
739 emacs_abort ();
740 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
741 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
742 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
745 val = realloc (val, size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
747 if (val)
749 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
750 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
751 xmalloc_put_size (val, size);
752 memcpy (val + size, xmalloc_overrun_check_trailer,
753 XMALLOC_OVERRUN_CHECK_SIZE);
755 return val;
758 /* Like free, but checks block for overrun. */
760 static void
761 overrun_check_free (void *block)
763 unsigned char *val = (unsigned char *) block;
765 if (val
766 && memcmp (xmalloc_overrun_check_header,
767 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
768 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
770 size_t osize = xmalloc_get_size (val);
771 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
772 XMALLOC_OVERRUN_CHECK_SIZE))
773 emacs_abort ();
774 #ifdef XMALLOC_CLEAR_FREE_MEMORY
775 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
776 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_OVERHEAD);
777 #else
778 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
779 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
780 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
781 #endif
784 free (val);
787 #undef malloc
788 #undef realloc
789 #undef free
790 #define malloc overrun_check_malloc
791 #define realloc overrun_check_realloc
792 #define free overrun_check_free
793 #endif
795 /* If compiled with XMALLOC_BLOCK_INPUT_CHECK, define a symbol
796 BLOCK_INPUT_IN_MEMORY_ALLOCATORS that is visible to the debugger.
797 If that variable is set, block input while in one of Emacs's memory
798 allocation functions. There should be no need for this debugging
799 option, since signal handlers do not allocate memory, but Emacs
800 formerly allocated memory in signal handlers and this compile-time
801 option remains as a way to help debug the issue should it rear its
802 ugly head again. */
803 #ifdef XMALLOC_BLOCK_INPUT_CHECK
804 bool block_input_in_memory_allocators EXTERNALLY_VISIBLE;
805 static void
806 malloc_block_input (void)
808 if (block_input_in_memory_allocators)
809 block_input ();
811 static void
812 malloc_unblock_input (void)
814 if (block_input_in_memory_allocators)
815 unblock_input ();
817 # define MALLOC_BLOCK_INPUT malloc_block_input ()
818 # define MALLOC_UNBLOCK_INPUT malloc_unblock_input ()
819 #else
820 # define MALLOC_BLOCK_INPUT ((void) 0)
821 # define MALLOC_UNBLOCK_INPUT ((void) 0)
822 #endif
824 #define MALLOC_PROBE(size) \
825 do { \
826 if (profiler_memory_running) \
827 malloc_probe (size); \
828 } while (0)
830 static void *lmalloc (size_t) ATTRIBUTE_MALLOC_SIZE ((1));
831 static void *lrealloc (void *, size_t);
833 /* Like malloc but check for no memory and block interrupt input. */
835 void *
836 xmalloc (size_t size)
838 void *val;
840 MALLOC_BLOCK_INPUT;
841 val = lmalloc (size);
842 MALLOC_UNBLOCK_INPUT;
844 if (!val && size)
845 memory_full (size);
846 MALLOC_PROBE (size);
847 return val;
850 /* Like the above, but zeroes out the memory just allocated. */
852 void *
853 xzalloc (size_t size)
855 void *val;
857 MALLOC_BLOCK_INPUT;
858 val = lmalloc (size);
859 MALLOC_UNBLOCK_INPUT;
861 if (!val && size)
862 memory_full (size);
863 memset (val, 0, size);
864 MALLOC_PROBE (size);
865 return val;
868 /* Like realloc but check for no memory and block interrupt input.. */
870 void *
871 xrealloc (void *block, size_t size)
873 void *val;
875 MALLOC_BLOCK_INPUT;
876 /* We must call malloc explicitly when BLOCK is 0, since some
877 reallocs don't do this. */
878 if (! block)
879 val = lmalloc (size);
880 else
881 val = lrealloc (block, size);
882 MALLOC_UNBLOCK_INPUT;
884 if (!val && size)
885 memory_full (size);
886 MALLOC_PROBE (size);
887 return val;
891 /* Like free but block interrupt input. */
893 void
894 xfree (void *block)
896 if (!block)
897 return;
898 MALLOC_BLOCK_INPUT;
899 free (block);
900 MALLOC_UNBLOCK_INPUT;
901 /* We don't call refill_memory_reserve here
902 because in practice the call in r_alloc_free seems to suffice. */
906 /* Other parts of Emacs pass large int values to allocator functions
907 expecting ptrdiff_t. This is portable in practice, but check it to
908 be safe. */
909 verify (INT_MAX <= PTRDIFF_MAX);
912 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
913 Signal an error on memory exhaustion, and block interrupt input. */
915 void *
916 xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
918 eassert (0 <= nitems && 0 < item_size);
919 ptrdiff_t nbytes;
920 if (INT_MULTIPLY_WRAPV (nitems, item_size, &nbytes) || SIZE_MAX < nbytes)
921 memory_full (SIZE_MAX);
922 return xmalloc (nbytes);
926 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
927 Signal an error on memory exhaustion, and block interrupt input. */
929 void *
930 xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
932 eassert (0 <= nitems && 0 < item_size);
933 ptrdiff_t nbytes;
934 if (INT_MULTIPLY_WRAPV (nitems, item_size, &nbytes) || SIZE_MAX < nbytes)
935 memory_full (SIZE_MAX);
936 return xrealloc (pa, nbytes);
940 /* Grow PA, which points to an array of *NITEMS items, and return the
941 location of the reallocated array, updating *NITEMS to reflect its
942 new size. The new array will contain at least NITEMS_INCR_MIN more
943 items, but will not contain more than NITEMS_MAX items total.
944 ITEM_SIZE is the size of each item, in bytes.
946 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
947 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
948 infinity.
950 If PA is null, then allocate a new array instead of reallocating
951 the old one.
953 Block interrupt input as needed. If memory exhaustion occurs, set
954 *NITEMS to zero if PA is null, and signal an error (i.e., do not
955 return).
957 Thus, to grow an array A without saving its old contents, do
958 { xfree (A); A = NULL; A = xpalloc (NULL, &AITEMS, ...); }.
959 The A = NULL avoids a dangling pointer if xpalloc exhausts memory
960 and signals an error, and later this code is reexecuted and
961 attempts to free A. */
963 void *
964 xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
965 ptrdiff_t nitems_max, ptrdiff_t item_size)
967 ptrdiff_t n0 = *nitems;
968 eassume (0 < item_size && 0 < nitems_incr_min && 0 <= n0 && -1 <= nitems_max);
970 /* The approximate size to use for initial small allocation
971 requests. This is the largest "small" request for the GNU C
972 library malloc. */
973 enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
975 /* If the array is tiny, grow it to about (but no greater than)
976 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%.
977 Adjust the growth according to three constraints: NITEMS_INCR_MIN,
978 NITEMS_MAX, and what the C language can represent safely. */
980 ptrdiff_t n, nbytes;
981 if (INT_ADD_WRAPV (n0, n0 >> 1, &n))
982 n = PTRDIFF_MAX;
983 if (0 <= nitems_max && nitems_max < n)
984 n = nitems_max;
986 ptrdiff_t adjusted_nbytes
987 = ((INT_MULTIPLY_WRAPV (n, item_size, &nbytes) || SIZE_MAX < nbytes)
988 ? min (PTRDIFF_MAX, SIZE_MAX)
989 : nbytes < DEFAULT_MXFAST ? DEFAULT_MXFAST : 0);
990 if (adjusted_nbytes)
992 n = adjusted_nbytes / item_size;
993 nbytes = adjusted_nbytes - adjusted_nbytes % item_size;
996 if (! pa)
997 *nitems = 0;
998 if (n - n0 < nitems_incr_min
999 && (INT_ADD_WRAPV (n0, nitems_incr_min, &n)
1000 || (0 <= nitems_max && nitems_max < n)
1001 || INT_MULTIPLY_WRAPV (n, item_size, &nbytes)))
1002 memory_full (SIZE_MAX);
1003 pa = xrealloc (pa, nbytes);
1004 *nitems = n;
1005 return pa;
1009 /* Like strdup, but uses xmalloc. */
1011 char *
1012 xstrdup (const char *s)
1014 ptrdiff_t size;
1015 eassert (s);
1016 size = strlen (s) + 1;
1017 return memcpy (xmalloc (size), s, size);
1020 /* Like above, but duplicates Lisp string to C string. */
1022 char *
1023 xlispstrdup (Lisp_Object string)
1025 ptrdiff_t size = SBYTES (string) + 1;
1026 return memcpy (xmalloc (size), SSDATA (string), size);
1029 /* Assign to *PTR a copy of STRING, freeing any storage *PTR formerly
1030 pointed to. If STRING is null, assign it without copying anything.
1031 Allocate before freeing, to avoid a dangling pointer if allocation
1032 fails. */
1034 void
1035 dupstring (char **ptr, char const *string)
1037 char *old = *ptr;
1038 *ptr = string ? xstrdup (string) : 0;
1039 xfree (old);
1043 /* Like putenv, but (1) use the equivalent of xmalloc and (2) the
1044 argument is a const pointer. */
1046 void
1047 xputenv (char const *string)
1049 if (putenv ((char *) string) != 0)
1050 memory_full (0);
1053 /* Return a newly allocated memory block of SIZE bytes, remembering
1054 to free it when unwinding. */
1055 void *
1056 record_xmalloc (size_t size)
1058 void *p = xmalloc (size);
1059 record_unwind_protect_ptr (xfree, p);
1060 return p;
1064 /* Like malloc but used for allocating Lisp data. NBYTES is the
1065 number of bytes to allocate, TYPE describes the intended use of the
1066 allocated memory block (for strings, for conses, ...). */
1068 #if ! USE_LSB_TAG
1069 void *lisp_malloc_loser EXTERNALLY_VISIBLE;
1070 #endif
1072 static void *
1073 lisp_malloc (size_t nbytes, enum mem_type type)
1075 register void *val;
1077 MALLOC_BLOCK_INPUT;
1079 #ifdef GC_MALLOC_CHECK
1080 allocated_mem_type = type;
1081 #endif
1083 val = lmalloc (nbytes);
1085 #if ! USE_LSB_TAG
1086 /* If the memory just allocated cannot be addressed thru a Lisp
1087 object's pointer, and it needs to be,
1088 that's equivalent to running out of memory. */
1089 if (val && type != MEM_TYPE_NON_LISP)
1091 Lisp_Object tem;
1092 XSETCONS (tem, (char *) val + nbytes - 1);
1093 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
1095 lisp_malloc_loser = val;
1096 free (val);
1097 val = 0;
1100 #endif
1102 #ifndef GC_MALLOC_CHECK
1103 if (val && type != MEM_TYPE_NON_LISP)
1104 mem_insert (val, (char *) val + nbytes, type);
1105 #endif
1107 MALLOC_UNBLOCK_INPUT;
1108 if (!val && nbytes)
1109 memory_full (nbytes);
1110 MALLOC_PROBE (nbytes);
1111 return val;
1114 /* Free BLOCK. This must be called to free memory allocated with a
1115 call to lisp_malloc. */
1117 static void
1118 lisp_free (void *block)
1120 MALLOC_BLOCK_INPUT;
1121 free (block);
1122 #ifndef GC_MALLOC_CHECK
1123 mem_delete (mem_find (block));
1124 #endif
1125 MALLOC_UNBLOCK_INPUT;
1128 /***** Allocation of aligned blocks of memory to store Lisp data. *****/
1130 /* The entry point is lisp_align_malloc which returns blocks of at most
1131 BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
1133 /* Byte alignment of storage blocks. */
1134 #define BLOCK_ALIGN (1 << 10)
1135 verify (POWER_OF_2 (BLOCK_ALIGN));
1137 /* Use aligned_alloc if it or a simple substitute is available.
1138 Address sanitization breaks aligned allocation, as of gcc 4.8.2 and
1139 clang 3.3 anyway. Aligned allocation is incompatible with
1140 unexmacosx.c, so don't use it on Darwin. */
1142 #if ! ADDRESS_SANITIZER && !defined DARWIN_OS
1143 # if (defined HAVE_ALIGNED_ALLOC \
1144 || (defined HYBRID_MALLOC \
1145 ? defined HAVE_POSIX_MEMALIGN \
1146 : !defined SYSTEM_MALLOC && !defined DOUG_LEA_MALLOC))
1147 # define USE_ALIGNED_ALLOC 1
1148 # elif !defined HYBRID_MALLOC && defined HAVE_POSIX_MEMALIGN
1149 # define USE_ALIGNED_ALLOC 1
1150 # define aligned_alloc my_aligned_alloc /* Avoid collision with lisp.h. */
1151 static void *
1152 aligned_alloc (size_t alignment, size_t size)
1154 /* POSIX says the alignment must be a power-of-2 multiple of sizeof (void *).
1155 Verify this for all arguments this function is given. */
1156 verify (BLOCK_ALIGN % sizeof (void *) == 0
1157 && POWER_OF_2 (BLOCK_ALIGN / sizeof (void *)));
1158 verify (GCALIGNMENT % sizeof (void *) == 0
1159 && POWER_OF_2 (GCALIGNMENT / sizeof (void *)));
1160 eassert (alignment == BLOCK_ALIGN || alignment == GCALIGNMENT);
1162 void *p;
1163 return posix_memalign (&p, alignment, size) == 0 ? p : 0;
1165 # endif
1166 #endif
1168 /* Padding to leave at the end of a malloc'd block. This is to give
1169 malloc a chance to minimize the amount of memory wasted to alignment.
1170 It should be tuned to the particular malloc library used.
1171 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
1172 aligned_alloc on the other hand would ideally prefer a value of 4
1173 because otherwise, there's 1020 bytes wasted between each ablocks.
1174 In Emacs, testing shows that those 1020 can most of the time be
1175 efficiently used by malloc to place other objects, so a value of 0 can
1176 still preferable unless you have a lot of aligned blocks and virtually
1177 nothing else. */
1178 #define BLOCK_PADDING 0
1179 #define BLOCK_BYTES \
1180 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
1182 /* Internal data structures and constants. */
1184 #define ABLOCKS_SIZE 16
1186 /* An aligned block of memory. */
1187 struct ablock
1189 union
1191 char payload[BLOCK_BYTES];
1192 struct ablock *next_free;
1193 } x;
1195 /* ABASE is the aligned base of the ablocks. It is overloaded to
1196 hold a virtual "busy" field that counts twice the number of used
1197 ablock values in the parent ablocks, plus one if the real base of
1198 the parent ablocks is ABASE (if the "busy" field is even, the
1199 word before the first ablock holds a pointer to the real base).
1200 The first ablock has a "busy" ABASE, and the others have an
1201 ordinary pointer ABASE. To tell the difference, the code assumes
1202 that pointers, when cast to uintptr_t, are at least 2 *
1203 ABLOCKS_SIZE + 1. */
1204 struct ablocks *abase;
1206 /* The padding of all but the last ablock is unused. The padding of
1207 the last ablock in an ablocks is not allocated. */
1208 #if BLOCK_PADDING
1209 char padding[BLOCK_PADDING];
1210 #endif
1213 /* A bunch of consecutive aligned blocks. */
1214 struct ablocks
1216 struct ablock blocks[ABLOCKS_SIZE];
1219 /* Size of the block requested from malloc or aligned_alloc. */
1220 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
1222 #define ABLOCK_ABASE(block) \
1223 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
1224 ? (struct ablocks *) (block) \
1225 : (block)->abase)
1227 /* Virtual `busy' field. */
1228 #define ABLOCKS_BUSY(a_base) ((a_base)->blocks[0].abase)
1230 /* Pointer to the (not necessarily aligned) malloc block. */
1231 #ifdef USE_ALIGNED_ALLOC
1232 #define ABLOCKS_BASE(abase) (abase)
1233 #else
1234 #define ABLOCKS_BASE(abase) \
1235 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void **) (abase))[-1])
1236 #endif
1238 /* The list of free ablock. */
1239 static struct ablock *free_ablock;
1241 /* Allocate an aligned block of nbytes.
1242 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
1243 smaller or equal to BLOCK_BYTES. */
1244 static void *
1245 lisp_align_malloc (size_t nbytes, enum mem_type type)
1247 void *base, *val;
1248 struct ablocks *abase;
1250 eassert (nbytes <= BLOCK_BYTES);
1252 MALLOC_BLOCK_INPUT;
1254 #ifdef GC_MALLOC_CHECK
1255 allocated_mem_type = type;
1256 #endif
1258 if (!free_ablock)
1260 int i;
1261 bool aligned;
1263 #ifdef DOUG_LEA_MALLOC
1264 if (!mmap_lisp_allowed_p ())
1265 mallopt (M_MMAP_MAX, 0);
1266 #endif
1268 #ifdef USE_ALIGNED_ALLOC
1269 verify (ABLOCKS_BYTES % BLOCK_ALIGN == 0);
1270 abase = base = aligned_alloc (BLOCK_ALIGN, ABLOCKS_BYTES);
1271 #else
1272 base = malloc (ABLOCKS_BYTES);
1273 abase = pointer_align (base, BLOCK_ALIGN);
1274 #endif
1276 if (base == 0)
1278 MALLOC_UNBLOCK_INPUT;
1279 memory_full (ABLOCKS_BYTES);
1282 aligned = (base == abase);
1283 if (!aligned)
1284 ((void **) abase)[-1] = base;
1286 #ifdef DOUG_LEA_MALLOC
1287 if (!mmap_lisp_allowed_p ())
1288 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1289 #endif
1291 #if ! USE_LSB_TAG
1292 /* If the memory just allocated cannot be addressed thru a Lisp
1293 object's pointer, and it needs to be, that's equivalent to
1294 running out of memory. */
1295 if (type != MEM_TYPE_NON_LISP)
1297 Lisp_Object tem;
1298 char *end = (char *) base + ABLOCKS_BYTES - 1;
1299 XSETCONS (tem, end);
1300 if ((char *) XCONS (tem) != end)
1302 lisp_malloc_loser = base;
1303 free (base);
1304 MALLOC_UNBLOCK_INPUT;
1305 memory_full (SIZE_MAX);
1308 #endif
1310 /* Initialize the blocks and put them on the free list.
1311 If `base' was not properly aligned, we can't use the last block. */
1312 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1314 abase->blocks[i].abase = abase;
1315 abase->blocks[i].x.next_free = free_ablock;
1316 free_ablock = &abase->blocks[i];
1318 intptr_t ialigned = aligned;
1319 ABLOCKS_BUSY (abase) = (struct ablocks *) ialigned;
1321 eassert ((uintptr_t) abase % BLOCK_ALIGN == 0);
1322 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1323 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1324 eassert (ABLOCKS_BASE (abase) == base);
1325 eassert ((intptr_t) ABLOCKS_BUSY (abase) == aligned);
1328 abase = ABLOCK_ABASE (free_ablock);
1329 ABLOCKS_BUSY (abase)
1330 = (struct ablocks *) (2 + (intptr_t) ABLOCKS_BUSY (abase));
1331 val = free_ablock;
1332 free_ablock = free_ablock->x.next_free;
1334 #ifndef GC_MALLOC_CHECK
1335 if (type != MEM_TYPE_NON_LISP)
1336 mem_insert (val, (char *) val + nbytes, type);
1337 #endif
1339 MALLOC_UNBLOCK_INPUT;
1341 MALLOC_PROBE (nbytes);
1343 eassert (0 == ((uintptr_t) val) % BLOCK_ALIGN);
1344 return val;
1347 static void
1348 lisp_align_free (void *block)
1350 struct ablock *ablock = block;
1351 struct ablocks *abase = ABLOCK_ABASE (ablock);
1353 MALLOC_BLOCK_INPUT;
1354 #ifndef GC_MALLOC_CHECK
1355 mem_delete (mem_find (block));
1356 #endif
1357 /* Put on free list. */
1358 ablock->x.next_free = free_ablock;
1359 free_ablock = ablock;
1360 /* Update busy count. */
1361 intptr_t busy = (intptr_t) ABLOCKS_BUSY (abase) - 2;
1362 eassume (0 <= busy && busy <= 2 * ABLOCKS_SIZE - 1);
1363 ABLOCKS_BUSY (abase) = (struct ablocks *) busy;
1365 if (busy < 2)
1366 { /* All the blocks are free. */
1367 int i = 0;
1368 bool aligned = busy;
1369 struct ablock **tem = &free_ablock;
1370 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1372 while (*tem)
1374 if (*tem >= (struct ablock *) abase && *tem < atop)
1376 i++;
1377 *tem = (*tem)->x.next_free;
1379 else
1380 tem = &(*tem)->x.next_free;
1382 eassert ((aligned & 1) == aligned);
1383 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1384 #ifdef USE_POSIX_MEMALIGN
1385 eassert ((uintptr_t) ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1386 #endif
1387 free (ABLOCKS_BASE (abase));
1389 MALLOC_UNBLOCK_INPUT;
1392 #if !defined __GNUC__ && !defined __alignof__
1393 # define __alignof__(type) alignof (type)
1394 #endif
1396 /* True if malloc (N) is known to return a multiple of GCALIGNMENT
1397 whenever N is also a multiple. In practice this is true if
1398 __alignof__ (max_align_t) is a multiple as well, assuming
1399 GCALIGNMENT is 8; other values of GCALIGNMENT have not been looked
1400 into. Use __alignof__ if available, as otherwise
1401 MALLOC_IS_GC_ALIGNED would be false on GCC x86 even though the
1402 alignment is OK there.
1404 This is a macro, not an enum constant, for portability to HP-UX
1405 10.20 cc and AIX 3.2.5 xlc. */
1406 #define MALLOC_IS_GC_ALIGNED \
1407 (GCALIGNMENT == 8 && __alignof__ (max_align_t) % GCALIGNMENT == 0)
1409 /* True if a malloc-returned pointer P is suitably aligned for SIZE,
1410 where Lisp alignment may be needed if SIZE is Lisp-aligned. */
1412 static bool
1413 laligned (void *p, size_t size)
1415 return (MALLOC_IS_GC_ALIGNED || (intptr_t) p % GCALIGNMENT == 0
1416 || size % GCALIGNMENT != 0);
1419 /* Like malloc and realloc except that if SIZE is Lisp-aligned, make
1420 sure the result is too, if necessary by reallocating (typically
1421 with larger and larger sizes) until the allocator returns a
1422 Lisp-aligned pointer. Code that needs to allocate C heap memory
1423 for a Lisp object should use one of these functions to obtain a
1424 pointer P; that way, if T is an enum Lisp_Type value and L ==
1425 make_lisp_ptr (P, T), then XPNTR (L) == P and XTYPE (L) == T.
1427 On typical modern platforms these functions' loops do not iterate.
1428 On now-rare (and perhaps nonexistent) platforms, the loops in
1429 theory could repeat forever. If an infinite loop is possible on a
1430 platform, a build would surely loop and the builder can then send
1431 us a bug report. Adding a counter to try to detect any such loop
1432 would complicate the code (and possibly introduce bugs, in code
1433 that's never really exercised) for little benefit. */
1435 static void *
1436 lmalloc (size_t size)
1438 #if USE_ALIGNED_ALLOC
1439 if (! MALLOC_IS_GC_ALIGNED && size % GCALIGNMENT == 0)
1440 return aligned_alloc (GCALIGNMENT, size);
1441 #endif
1443 while (true)
1445 void *p = malloc (size);
1446 if (laligned (p, size))
1447 return p;
1448 free (p);
1449 size_t bigger = size + GCALIGNMENT;
1450 if (size < bigger)
1451 size = bigger;
1455 static void *
1456 lrealloc (void *p, size_t size)
1458 while (true)
1460 p = realloc (p, size);
1461 if (laligned (p, size))
1462 return p;
1463 size_t bigger = size + GCALIGNMENT;
1464 if (size < bigger)
1465 size = bigger;
1470 /***********************************************************************
1471 Interval Allocation
1472 ***********************************************************************/
1474 /* Number of intervals allocated in an interval_block structure.
1475 The 1020 is 1024 minus malloc overhead. */
1477 #define INTERVAL_BLOCK_SIZE \
1478 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1480 /* Intervals are allocated in chunks in the form of an interval_block
1481 structure. */
1483 struct interval_block
1485 /* Place `intervals' first, to preserve alignment. */
1486 struct interval intervals[INTERVAL_BLOCK_SIZE];
1487 struct interval_block *next;
1490 /* Current interval block. Its `next' pointer points to older
1491 blocks. */
1493 static struct interval_block *interval_block;
1495 /* Index in interval_block above of the next unused interval
1496 structure. */
1498 static int interval_block_index = INTERVAL_BLOCK_SIZE;
1500 /* Number of free and live intervals. */
1502 static EMACS_INT total_free_intervals, total_intervals;
1504 /* List of free intervals. */
1506 static INTERVAL interval_free_list;
1508 /* Return a new interval. */
1510 INTERVAL
1511 make_interval (void)
1513 INTERVAL val;
1515 MALLOC_BLOCK_INPUT;
1517 if (interval_free_list)
1519 val = interval_free_list;
1520 interval_free_list = INTERVAL_PARENT (interval_free_list);
1522 else
1524 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1526 struct interval_block *newi
1527 = lisp_malloc (sizeof *newi, MEM_TYPE_NON_LISP);
1529 newi->next = interval_block;
1530 interval_block = newi;
1531 interval_block_index = 0;
1532 total_free_intervals += INTERVAL_BLOCK_SIZE;
1534 val = &interval_block->intervals[interval_block_index++];
1537 MALLOC_UNBLOCK_INPUT;
1539 consing_since_gc += sizeof (struct interval);
1540 intervals_consed++;
1541 total_free_intervals--;
1542 RESET_INTERVAL (val);
1543 val->gcmarkbit = 0;
1544 return val;
1548 /* Mark Lisp objects in interval I. */
1550 static void
1551 mark_interval (register INTERVAL i, Lisp_Object dummy)
1553 /* Intervals should never be shared. So, if extra internal checking is
1554 enabled, GC aborts if it seems to have visited an interval twice. */
1555 eassert (!i->gcmarkbit);
1556 i->gcmarkbit = 1;
1557 mark_object (i->plist);
1560 /* Mark the interval tree rooted in I. */
1562 #define MARK_INTERVAL_TREE(i) \
1563 do { \
1564 if (i && !i->gcmarkbit) \
1565 traverse_intervals_noorder (i, mark_interval, Qnil); \
1566 } while (0)
1568 /***********************************************************************
1569 String Allocation
1570 ***********************************************************************/
1572 /* Lisp_Strings are allocated in string_block structures. When a new
1573 string_block is allocated, all the Lisp_Strings it contains are
1574 added to a free-list string_free_list. When a new Lisp_String is
1575 needed, it is taken from that list. During the sweep phase of GC,
1576 string_blocks that are entirely free are freed, except two which
1577 we keep.
1579 String data is allocated from sblock structures. Strings larger
1580 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1581 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1583 Sblocks consist internally of sdata structures, one for each
1584 Lisp_String. The sdata structure points to the Lisp_String it
1585 belongs to. The Lisp_String points back to the `u.data' member of
1586 its sdata structure.
1588 When a Lisp_String is freed during GC, it is put back on
1589 string_free_list, and its `data' member and its sdata's `string'
1590 pointer is set to null. The size of the string is recorded in the
1591 `n.nbytes' member of the sdata. So, sdata structures that are no
1592 longer used, can be easily recognized, and it's easy to compact the
1593 sblocks of small strings which we do in compact_small_strings. */
1595 /* Size in bytes of an sblock structure used for small strings. This
1596 is 8192 minus malloc overhead. */
1598 #define SBLOCK_SIZE 8188
1600 /* Strings larger than this are considered large strings. String data
1601 for large strings is allocated from individual sblocks. */
1603 #define LARGE_STRING_BYTES 1024
1605 /* The SDATA typedef is a struct or union describing string memory
1606 sub-allocated from an sblock. This is where the contents of Lisp
1607 strings are stored. */
1609 struct sdata
1611 /* Back-pointer to the string this sdata belongs to. If null, this
1612 structure is free, and NBYTES (in this structure or in the union below)
1613 contains the string's byte size (the same value that STRING_BYTES
1614 would return if STRING were non-null). If non-null, STRING_BYTES
1615 (STRING) is the size of the data, and DATA contains the string's
1616 contents. */
1617 struct Lisp_String *string;
1619 #ifdef GC_CHECK_STRING_BYTES
1620 ptrdiff_t nbytes;
1621 #endif
1623 unsigned char data[FLEXIBLE_ARRAY_MEMBER];
1626 #ifdef GC_CHECK_STRING_BYTES
1628 typedef struct sdata sdata;
1629 #define SDATA_NBYTES(S) (S)->nbytes
1630 #define SDATA_DATA(S) (S)->data
1632 #else
1634 typedef union
1636 struct Lisp_String *string;
1638 /* When STRING is nonnull, this union is actually of type 'struct sdata',
1639 which has a flexible array member. However, if implemented by
1640 giving this union a member of type 'struct sdata', the union
1641 could not be the last (flexible) member of 'struct sblock',
1642 because C99 prohibits a flexible array member from having a type
1643 that is itself a flexible array. So, comment this member out here,
1644 but remember that the option's there when using this union. */
1645 #if 0
1646 struct sdata u;
1647 #endif
1649 /* When STRING is null. */
1650 struct
1652 struct Lisp_String *string;
1653 ptrdiff_t nbytes;
1654 } n;
1655 } sdata;
1657 #define SDATA_NBYTES(S) (S)->n.nbytes
1658 #define SDATA_DATA(S) ((struct sdata *) (S))->data
1660 #endif /* not GC_CHECK_STRING_BYTES */
1662 enum { SDATA_DATA_OFFSET = offsetof (struct sdata, data) };
1664 /* Structure describing a block of memory which is sub-allocated to
1665 obtain string data memory for strings. Blocks for small strings
1666 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1667 as large as needed. */
1669 struct sblock
1671 /* Next in list. */
1672 struct sblock *next;
1674 /* Pointer to the next free sdata block. This points past the end
1675 of the sblock if there isn't any space left in this block. */
1676 sdata *next_free;
1678 /* String data. */
1679 sdata data[FLEXIBLE_ARRAY_MEMBER];
1682 /* Number of Lisp strings in a string_block structure. The 1020 is
1683 1024 minus malloc overhead. */
1685 #define STRING_BLOCK_SIZE \
1686 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1688 /* Structure describing a block from which Lisp_String structures
1689 are allocated. */
1691 struct string_block
1693 /* Place `strings' first, to preserve alignment. */
1694 struct Lisp_String strings[STRING_BLOCK_SIZE];
1695 struct string_block *next;
1698 /* Head and tail of the list of sblock structures holding Lisp string
1699 data. We always allocate from current_sblock. The NEXT pointers
1700 in the sblock structures go from oldest_sblock to current_sblock. */
1702 static struct sblock *oldest_sblock, *current_sblock;
1704 /* List of sblocks for large strings. */
1706 static struct sblock *large_sblocks;
1708 /* List of string_block structures. */
1710 static struct string_block *string_blocks;
1712 /* Free-list of Lisp_Strings. */
1714 static struct Lisp_String *string_free_list;
1716 /* Number of live and free Lisp_Strings. */
1718 static EMACS_INT total_strings, total_free_strings;
1720 /* Number of bytes used by live strings. */
1722 static EMACS_INT total_string_bytes;
1724 /* Given a pointer to a Lisp_String S which is on the free-list
1725 string_free_list, return a pointer to its successor in the
1726 free-list. */
1728 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1730 /* Return a pointer to the sdata structure belonging to Lisp string S.
1731 S must be live, i.e. S->data must not be null. S->data is actually
1732 a pointer to the `u.data' member of its sdata structure; the
1733 structure starts at a constant offset in front of that. */
1735 #define SDATA_OF_STRING(S) ((sdata *) ((S)->data - SDATA_DATA_OFFSET))
1738 #ifdef GC_CHECK_STRING_OVERRUN
1740 /* We check for overrun in string data blocks by appending a small
1741 "cookie" after each allocated string data block, and check for the
1742 presence of this cookie during GC. */
1744 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1745 static char const string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1746 { '\xde', '\xad', '\xbe', '\xef' };
1748 #else
1749 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1750 #endif
1752 /* Value is the size of an sdata structure large enough to hold NBYTES
1753 bytes of string data. The value returned includes a terminating
1754 NUL byte, the size of the sdata structure, and padding. */
1756 #ifdef GC_CHECK_STRING_BYTES
1758 #define SDATA_SIZE(NBYTES) FLEXSIZEOF (struct sdata, data, NBYTES)
1760 #else /* not GC_CHECK_STRING_BYTES */
1762 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1763 less than the size of that member. The 'max' is not needed when
1764 SDATA_DATA_OFFSET is a multiple of FLEXALIGNOF (struct sdata),
1765 because then the alignment code reserves enough space. */
1767 #define SDATA_SIZE(NBYTES) \
1768 ((SDATA_DATA_OFFSET \
1769 + (SDATA_DATA_OFFSET % FLEXALIGNOF (struct sdata) == 0 \
1770 ? NBYTES \
1771 : max (NBYTES, FLEXALIGNOF (struct sdata) - 1)) \
1772 + 1 \
1773 + FLEXALIGNOF (struct sdata) - 1) \
1774 & ~(FLEXALIGNOF (struct sdata) - 1))
1776 #endif /* not GC_CHECK_STRING_BYTES */
1778 /* Extra bytes to allocate for each string. */
1780 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1782 /* Exact bound on the number of bytes in a string, not counting the
1783 terminating null. A string cannot contain more bytes than
1784 STRING_BYTES_BOUND, nor can it be so long that the size_t
1785 arithmetic in allocate_string_data would overflow while it is
1786 calculating a value to be passed to malloc. */
1787 static ptrdiff_t const STRING_BYTES_MAX =
1788 min (STRING_BYTES_BOUND,
1789 ((SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD
1790 - GC_STRING_EXTRA
1791 - offsetof (struct sblock, data)
1792 - SDATA_DATA_OFFSET)
1793 & ~(sizeof (EMACS_INT) - 1)));
1795 /* Initialize string allocation. Called from init_alloc_once. */
1797 static void
1798 init_strings (void)
1800 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1801 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1805 #ifdef GC_CHECK_STRING_BYTES
1807 static int check_string_bytes_count;
1809 /* Like STRING_BYTES, but with debugging check. Can be
1810 called during GC, so pay attention to the mark bit. */
1812 ptrdiff_t
1813 string_bytes (struct Lisp_String *s)
1815 ptrdiff_t nbytes =
1816 (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1818 if (!PURE_P (s) && s->data && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1819 emacs_abort ();
1820 return nbytes;
1823 /* Check validity of Lisp strings' string_bytes member in B. */
1825 static void
1826 check_sblock (struct sblock *b)
1828 sdata *from, *end, *from_end;
1830 end = b->next_free;
1832 for (from = b->data; from < end; from = from_end)
1834 /* Compute the next FROM here because copying below may
1835 overwrite data we need to compute it. */
1836 ptrdiff_t nbytes;
1838 /* Check that the string size recorded in the string is the
1839 same as the one recorded in the sdata structure. */
1840 nbytes = SDATA_SIZE (from->string ? string_bytes (from->string)
1841 : SDATA_NBYTES (from));
1842 from_end = (sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1847 /* Check validity of Lisp strings' string_bytes member. ALL_P
1848 means check all strings, otherwise check only most
1849 recently allocated strings. Used for hunting a bug. */
1851 static void
1852 check_string_bytes (bool all_p)
1854 if (all_p)
1856 struct sblock *b;
1858 for (b = large_sblocks; b; b = b->next)
1860 struct Lisp_String *s = b->data[0].string;
1861 if (s)
1862 string_bytes (s);
1865 for (b = oldest_sblock; b; b = b->next)
1866 check_sblock (b);
1868 else if (current_sblock)
1869 check_sblock (current_sblock);
1872 #else /* not GC_CHECK_STRING_BYTES */
1874 #define check_string_bytes(all) ((void) 0)
1876 #endif /* GC_CHECK_STRING_BYTES */
1878 #ifdef GC_CHECK_STRING_FREE_LIST
1880 /* Walk through the string free list looking for bogus next pointers.
1881 This may catch buffer overrun from a previous string. */
1883 static void
1884 check_string_free_list (void)
1886 struct Lisp_String *s;
1888 /* Pop a Lisp_String off the free-list. */
1889 s = string_free_list;
1890 while (s != NULL)
1892 if ((uintptr_t) s < 1024)
1893 emacs_abort ();
1894 s = NEXT_FREE_LISP_STRING (s);
1897 #else
1898 #define check_string_free_list()
1899 #endif
1901 /* Return a new Lisp_String. */
1903 static struct Lisp_String *
1904 allocate_string (void)
1906 struct Lisp_String *s;
1908 MALLOC_BLOCK_INPUT;
1910 /* If the free-list is empty, allocate a new string_block, and
1911 add all the Lisp_Strings in it to the free-list. */
1912 if (string_free_list == NULL)
1914 struct string_block *b = lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1915 int i;
1917 b->next = string_blocks;
1918 string_blocks = b;
1920 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1922 s = b->strings + i;
1923 /* Every string on a free list should have NULL data pointer. */
1924 s->data = NULL;
1925 NEXT_FREE_LISP_STRING (s) = string_free_list;
1926 string_free_list = s;
1929 total_free_strings += STRING_BLOCK_SIZE;
1932 check_string_free_list ();
1934 /* Pop a Lisp_String off the free-list. */
1935 s = string_free_list;
1936 string_free_list = NEXT_FREE_LISP_STRING (s);
1938 MALLOC_UNBLOCK_INPUT;
1940 --total_free_strings;
1941 ++total_strings;
1942 ++strings_consed;
1943 consing_since_gc += sizeof *s;
1945 #ifdef GC_CHECK_STRING_BYTES
1946 if (!noninteractive)
1948 if (++check_string_bytes_count == 200)
1950 check_string_bytes_count = 0;
1951 check_string_bytes (1);
1953 else
1954 check_string_bytes (0);
1956 #endif /* GC_CHECK_STRING_BYTES */
1958 return s;
1962 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1963 plus a NUL byte at the end. Allocate an sdata structure for S, and
1964 set S->data to its `u.data' member. Store a NUL byte at the end of
1965 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1966 S->data if it was initially non-null. */
1968 void
1969 allocate_string_data (struct Lisp_String *s,
1970 EMACS_INT nchars, EMACS_INT nbytes)
1972 sdata *data, *old_data;
1973 struct sblock *b;
1974 ptrdiff_t needed, old_nbytes;
1976 if (STRING_BYTES_MAX < nbytes)
1977 string_overflow ();
1979 /* Determine the number of bytes needed to store NBYTES bytes
1980 of string data. */
1981 needed = SDATA_SIZE (nbytes);
1982 if (s->data)
1984 old_data = SDATA_OF_STRING (s);
1985 old_nbytes = STRING_BYTES (s);
1987 else
1988 old_data = NULL;
1990 MALLOC_BLOCK_INPUT;
1992 if (nbytes > LARGE_STRING_BYTES)
1994 size_t size = FLEXSIZEOF (struct sblock, data, needed);
1996 #ifdef DOUG_LEA_MALLOC
1997 if (!mmap_lisp_allowed_p ())
1998 mallopt (M_MMAP_MAX, 0);
1999 #endif
2001 b = lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
2003 #ifdef DOUG_LEA_MALLOC
2004 if (!mmap_lisp_allowed_p ())
2005 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2006 #endif
2008 data = b->data;
2009 b->next = large_sblocks;
2010 b->next_free = data;
2011 large_sblocks = b;
2013 else if (current_sblock == NULL
2014 || (((char *) current_sblock + SBLOCK_SIZE
2015 - (char *) current_sblock->next_free)
2016 < (needed + GC_STRING_EXTRA)))
2018 /* Not enough room in the current sblock. */
2019 b = lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
2020 data = b->data;
2021 b->next = NULL;
2022 b->next_free = data;
2024 if (current_sblock)
2025 current_sblock->next = b;
2026 else
2027 oldest_sblock = b;
2028 current_sblock = b;
2030 else
2032 b = current_sblock;
2033 data = b->next_free;
2036 data->string = s;
2037 b->next_free = (sdata *) ((char *) data + needed + GC_STRING_EXTRA);
2039 MALLOC_UNBLOCK_INPUT;
2041 s->data = SDATA_DATA (data);
2042 #ifdef GC_CHECK_STRING_BYTES
2043 SDATA_NBYTES (data) = nbytes;
2044 #endif
2045 s->size = nchars;
2046 s->size_byte = nbytes;
2047 s->data[nbytes] = '\0';
2048 #ifdef GC_CHECK_STRING_OVERRUN
2049 memcpy ((char *) data + needed, string_overrun_cookie,
2050 GC_STRING_OVERRUN_COOKIE_SIZE);
2051 #endif
2053 /* Note that Faset may call to this function when S has already data
2054 assigned. In this case, mark data as free by setting it's string
2055 back-pointer to null, and record the size of the data in it. */
2056 if (old_data)
2058 SDATA_NBYTES (old_data) = old_nbytes;
2059 old_data->string = NULL;
2062 consing_since_gc += needed;
2066 /* Sweep and compact strings. */
2068 NO_INLINE /* For better stack traces */
2069 static void
2070 sweep_strings (void)
2072 struct string_block *b, *next;
2073 struct string_block *live_blocks = NULL;
2075 string_free_list = NULL;
2076 total_strings = total_free_strings = 0;
2077 total_string_bytes = 0;
2079 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
2080 for (b = string_blocks; b; b = next)
2082 int i, nfree = 0;
2083 struct Lisp_String *free_list_before = string_free_list;
2085 next = b->next;
2087 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
2089 struct Lisp_String *s = b->strings + i;
2091 if (s->data)
2093 /* String was not on free-list before. */
2094 if (STRING_MARKED_P (s))
2096 /* String is live; unmark it and its intervals. */
2097 UNMARK_STRING (s);
2099 /* Do not use string_(set|get)_intervals here. */
2100 s->intervals = balance_intervals (s->intervals);
2102 ++total_strings;
2103 total_string_bytes += STRING_BYTES (s);
2105 else
2107 /* String is dead. Put it on the free-list. */
2108 sdata *data = SDATA_OF_STRING (s);
2110 /* Save the size of S in its sdata so that we know
2111 how large that is. Reset the sdata's string
2112 back-pointer so that we know it's free. */
2113 #ifdef GC_CHECK_STRING_BYTES
2114 if (string_bytes (s) != SDATA_NBYTES (data))
2115 emacs_abort ();
2116 #else
2117 data->n.nbytes = STRING_BYTES (s);
2118 #endif
2119 data->string = NULL;
2121 /* Reset the strings's `data' member so that we
2122 know it's free. */
2123 s->data = NULL;
2125 /* Put the string on the free-list. */
2126 NEXT_FREE_LISP_STRING (s) = string_free_list;
2127 string_free_list = s;
2128 ++nfree;
2131 else
2133 /* S was on the free-list before. Put it there again. */
2134 NEXT_FREE_LISP_STRING (s) = string_free_list;
2135 string_free_list = s;
2136 ++nfree;
2140 /* Free blocks that contain free Lisp_Strings only, except
2141 the first two of them. */
2142 if (nfree == STRING_BLOCK_SIZE
2143 && total_free_strings > STRING_BLOCK_SIZE)
2145 lisp_free (b);
2146 string_free_list = free_list_before;
2148 else
2150 total_free_strings += nfree;
2151 b->next = live_blocks;
2152 live_blocks = b;
2156 check_string_free_list ();
2158 string_blocks = live_blocks;
2159 free_large_strings ();
2160 compact_small_strings ();
2162 check_string_free_list ();
2166 /* Free dead large strings. */
2168 static void
2169 free_large_strings (void)
2171 struct sblock *b, *next;
2172 struct sblock *live_blocks = NULL;
2174 for (b = large_sblocks; b; b = next)
2176 next = b->next;
2178 if (b->data[0].string == NULL)
2179 lisp_free (b);
2180 else
2182 b->next = live_blocks;
2183 live_blocks = b;
2187 large_sblocks = live_blocks;
2191 /* Compact data of small strings. Free sblocks that don't contain
2192 data of live strings after compaction. */
2194 static void
2195 compact_small_strings (void)
2197 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2198 to, and TB_END is the end of TB. */
2199 struct sblock *tb = oldest_sblock;
2200 if (tb)
2202 sdata *tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
2203 sdata *to = tb->data;
2205 /* Step through the blocks from the oldest to the youngest. We
2206 expect that old blocks will stabilize over time, so that less
2207 copying will happen this way. */
2208 struct sblock *b = tb;
2211 sdata *end = b->next_free;
2212 eassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2214 for (sdata *from = b->data; from < end; )
2216 /* Compute the next FROM here because copying below may
2217 overwrite data we need to compute it. */
2218 ptrdiff_t nbytes;
2219 struct Lisp_String *s = from->string;
2221 #ifdef GC_CHECK_STRING_BYTES
2222 /* Check that the string size recorded in the string is the
2223 same as the one recorded in the sdata structure. */
2224 if (s && string_bytes (s) != SDATA_NBYTES (from))
2225 emacs_abort ();
2226 #endif /* GC_CHECK_STRING_BYTES */
2228 nbytes = s ? STRING_BYTES (s) : SDATA_NBYTES (from);
2229 eassert (nbytes <= LARGE_STRING_BYTES);
2231 nbytes = SDATA_SIZE (nbytes);
2232 sdata *from_end = (sdata *) ((char *) from
2233 + nbytes + GC_STRING_EXTRA);
2235 #ifdef GC_CHECK_STRING_OVERRUN
2236 if (memcmp (string_overrun_cookie,
2237 (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
2238 GC_STRING_OVERRUN_COOKIE_SIZE))
2239 emacs_abort ();
2240 #endif
2242 /* Non-NULL S means it's alive. Copy its data. */
2243 if (s)
2245 /* If TB is full, proceed with the next sblock. */
2246 sdata *to_end = (sdata *) ((char *) to
2247 + nbytes + GC_STRING_EXTRA);
2248 if (to_end > tb_end)
2250 tb->next_free = to;
2251 tb = tb->next;
2252 tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
2253 to = tb->data;
2254 to_end = (sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2257 /* Copy, and update the string's `data' pointer. */
2258 if (from != to)
2260 eassert (tb != b || to < from);
2261 memmove (to, from, nbytes + GC_STRING_EXTRA);
2262 to->string->data = SDATA_DATA (to);
2265 /* Advance past the sdata we copied to. */
2266 to = to_end;
2268 from = from_end;
2270 b = b->next;
2272 while (b);
2274 /* The rest of the sblocks following TB don't contain live data, so
2275 we can free them. */
2276 for (b = tb->next; b; )
2278 struct sblock *next = b->next;
2279 lisp_free (b);
2280 b = next;
2283 tb->next_free = to;
2284 tb->next = NULL;
2287 current_sblock = tb;
2290 void
2291 string_overflow (void)
2293 error ("Maximum string size exceeded");
2296 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2297 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2298 LENGTH must be an integer.
2299 INIT must be an integer that represents a character. */)
2300 (Lisp_Object length, Lisp_Object init)
2302 register Lisp_Object val;
2303 int c;
2304 EMACS_INT nbytes;
2306 CHECK_NATNUM (length);
2307 CHECK_CHARACTER (init);
2309 c = XFASTINT (init);
2310 if (ASCII_CHAR_P (c))
2312 nbytes = XINT (length);
2313 val = make_uninit_string (nbytes);
2314 if (nbytes)
2316 memset (SDATA (val), c, nbytes);
2317 SDATA (val)[nbytes] = 0;
2320 else
2322 unsigned char str[MAX_MULTIBYTE_LENGTH];
2323 ptrdiff_t len = CHAR_STRING (c, str);
2324 EMACS_INT string_len = XINT (length);
2325 unsigned char *p, *beg, *end;
2327 if (INT_MULTIPLY_WRAPV (len, string_len, &nbytes))
2328 string_overflow ();
2329 val = make_uninit_multibyte_string (string_len, nbytes);
2330 for (beg = SDATA (val), p = beg, end = beg + nbytes; p < end; p += len)
2332 /* First time we just copy `str' to the data of `val'. */
2333 if (p == beg)
2334 memcpy (p, str, len);
2335 else
2337 /* Next time we copy largest possible chunk from
2338 initialized to uninitialized part of `val'. */
2339 len = min (p - beg, end - p);
2340 memcpy (p, beg, len);
2343 if (nbytes)
2344 *p = 0;
2347 return val;
2350 /* Fill A with 1 bits if INIT is non-nil, and with 0 bits otherwise.
2351 Return A. */
2353 Lisp_Object
2354 bool_vector_fill (Lisp_Object a, Lisp_Object init)
2356 EMACS_INT nbits = bool_vector_size (a);
2357 if (0 < nbits)
2359 unsigned char *data = bool_vector_uchar_data (a);
2360 int pattern = NILP (init) ? 0 : (1 << BOOL_VECTOR_BITS_PER_CHAR) - 1;
2361 ptrdiff_t nbytes = bool_vector_bytes (nbits);
2362 int last_mask = ~ (~0u << ((nbits - 1) % BOOL_VECTOR_BITS_PER_CHAR + 1));
2363 memset (data, pattern, nbytes - 1);
2364 data[nbytes - 1] = pattern & last_mask;
2366 return a;
2369 /* Return a newly allocated, uninitialized bool vector of size NBITS. */
2371 Lisp_Object
2372 make_uninit_bool_vector (EMACS_INT nbits)
2374 Lisp_Object val;
2375 EMACS_INT words = bool_vector_words (nbits);
2376 EMACS_INT word_bytes = words * sizeof (bits_word);
2377 EMACS_INT needed_elements = ((bool_header_size - header_size + word_bytes
2378 + word_size - 1)
2379 / word_size);
2380 struct Lisp_Bool_Vector *p
2381 = (struct Lisp_Bool_Vector *) allocate_vector (needed_elements);
2382 XSETVECTOR (val, p);
2383 XSETPVECTYPESIZE (XVECTOR (val), PVEC_BOOL_VECTOR, 0, 0);
2384 p->size = nbits;
2386 /* Clear padding at the end. */
2387 if (words)
2388 p->data[words - 1] = 0;
2390 return val;
2393 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2394 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2395 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2396 (Lisp_Object length, Lisp_Object init)
2398 Lisp_Object val;
2400 CHECK_NATNUM (length);
2401 val = make_uninit_bool_vector (XFASTINT (length));
2402 return bool_vector_fill (val, init);
2405 DEFUN ("bool-vector", Fbool_vector, Sbool_vector, 0, MANY, 0,
2406 doc: /* Return a new bool-vector with specified arguments as elements.
2407 Any number of arguments, even zero arguments, are allowed.
2408 usage: (bool-vector &rest OBJECTS) */)
2409 (ptrdiff_t nargs, Lisp_Object *args)
2411 ptrdiff_t i;
2412 Lisp_Object vector;
2414 vector = make_uninit_bool_vector (nargs);
2415 for (i = 0; i < nargs; i++)
2416 bool_vector_set (vector, i, !NILP (args[i]));
2418 return vector;
2421 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2422 of characters from the contents. This string may be unibyte or
2423 multibyte, depending on the contents. */
2425 Lisp_Object
2426 make_string (const char *contents, ptrdiff_t nbytes)
2428 register Lisp_Object val;
2429 ptrdiff_t nchars, multibyte_nbytes;
2431 parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
2432 &nchars, &multibyte_nbytes);
2433 if (nbytes == nchars || nbytes != multibyte_nbytes)
2434 /* CONTENTS contains no multibyte sequences or contains an invalid
2435 multibyte sequence. We must make unibyte string. */
2436 val = make_unibyte_string (contents, nbytes);
2437 else
2438 val = make_multibyte_string (contents, nchars, nbytes);
2439 return val;
2442 /* Make a unibyte string from LENGTH bytes at CONTENTS. */
2444 Lisp_Object
2445 make_unibyte_string (const char *contents, ptrdiff_t length)
2447 register Lisp_Object val;
2448 val = make_uninit_string (length);
2449 memcpy (SDATA (val), contents, length);
2450 return val;
2454 /* Make a multibyte string from NCHARS characters occupying NBYTES
2455 bytes at CONTENTS. */
2457 Lisp_Object
2458 make_multibyte_string (const char *contents,
2459 ptrdiff_t nchars, ptrdiff_t nbytes)
2461 register Lisp_Object val;
2462 val = make_uninit_multibyte_string (nchars, nbytes);
2463 memcpy (SDATA (val), contents, nbytes);
2464 return val;
2468 /* Make a string from NCHARS characters occupying NBYTES bytes at
2469 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2471 Lisp_Object
2472 make_string_from_bytes (const char *contents,
2473 ptrdiff_t nchars, ptrdiff_t nbytes)
2475 register Lisp_Object val;
2476 val = make_uninit_multibyte_string (nchars, nbytes);
2477 memcpy (SDATA (val), contents, nbytes);
2478 if (SBYTES (val) == SCHARS (val))
2479 STRING_SET_UNIBYTE (val);
2480 return val;
2484 /* Make a string from NCHARS characters occupying NBYTES bytes at
2485 CONTENTS. The argument MULTIBYTE controls whether to label the
2486 string as multibyte. If NCHARS is negative, it counts the number of
2487 characters by itself. */
2489 Lisp_Object
2490 make_specified_string (const char *contents,
2491 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
2493 Lisp_Object val;
2495 if (nchars < 0)
2497 if (multibyte)
2498 nchars = multibyte_chars_in_text ((const unsigned char *) contents,
2499 nbytes);
2500 else
2501 nchars = nbytes;
2503 val = make_uninit_multibyte_string (nchars, nbytes);
2504 memcpy (SDATA (val), contents, nbytes);
2505 if (!multibyte)
2506 STRING_SET_UNIBYTE (val);
2507 return val;
2511 /* Return a unibyte Lisp_String set up to hold LENGTH characters
2512 occupying LENGTH bytes. */
2514 Lisp_Object
2515 make_uninit_string (EMACS_INT length)
2517 Lisp_Object val;
2519 if (!length)
2520 return empty_unibyte_string;
2521 val = make_uninit_multibyte_string (length, length);
2522 STRING_SET_UNIBYTE (val);
2523 return val;
2527 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2528 which occupy NBYTES bytes. */
2530 Lisp_Object
2531 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2533 Lisp_Object string;
2534 struct Lisp_String *s;
2536 if (nchars < 0)
2537 emacs_abort ();
2538 if (!nbytes)
2539 return empty_multibyte_string;
2541 s = allocate_string ();
2542 s->intervals = NULL;
2543 allocate_string_data (s, nchars, nbytes);
2544 XSETSTRING (string, s);
2545 string_chars_consed += nbytes;
2546 return string;
2549 /* Print arguments to BUF according to a FORMAT, then return
2550 a Lisp_String initialized with the data from BUF. */
2552 Lisp_Object
2553 make_formatted_string (char *buf, const char *format, ...)
2555 va_list ap;
2556 int length;
2558 va_start (ap, format);
2559 length = vsprintf (buf, format, ap);
2560 va_end (ap);
2561 return make_string (buf, length);
2565 /***********************************************************************
2566 Float Allocation
2567 ***********************************************************************/
2569 /* We store float cells inside of float_blocks, allocating a new
2570 float_block with malloc whenever necessary. Float cells reclaimed
2571 by GC are put on a free list to be reallocated before allocating
2572 any new float cells from the latest float_block. */
2574 #define FLOAT_BLOCK_SIZE \
2575 (((BLOCK_BYTES - sizeof (struct float_block *) \
2576 /* The compiler might add padding at the end. */ \
2577 - (sizeof (struct Lisp_Float) - sizeof (bits_word))) * CHAR_BIT) \
2578 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2580 #define GETMARKBIT(block,n) \
2581 (((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2582 >> ((n) % BITS_PER_BITS_WORD)) \
2583 & 1)
2585 #define SETMARKBIT(block,n) \
2586 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2587 |= (bits_word) 1 << ((n) % BITS_PER_BITS_WORD))
2589 #define UNSETMARKBIT(block,n) \
2590 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2591 &= ~((bits_word) 1 << ((n) % BITS_PER_BITS_WORD)))
2593 #define FLOAT_BLOCK(fptr) \
2594 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2596 #define FLOAT_INDEX(fptr) \
2597 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2599 struct float_block
2601 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2602 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2603 bits_word gcmarkbits[1 + FLOAT_BLOCK_SIZE / BITS_PER_BITS_WORD];
2604 struct float_block *next;
2607 #define FLOAT_MARKED_P(fptr) \
2608 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2610 #define FLOAT_MARK(fptr) \
2611 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2613 #define FLOAT_UNMARK(fptr) \
2614 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2616 /* Current float_block. */
2618 static struct float_block *float_block;
2620 /* Index of first unused Lisp_Float in the current float_block. */
2622 static int float_block_index = FLOAT_BLOCK_SIZE;
2624 /* Free-list of Lisp_Floats. */
2626 static struct Lisp_Float *float_free_list;
2628 /* Return a new float object with value FLOAT_VALUE. */
2630 Lisp_Object
2631 make_float (double float_value)
2633 register Lisp_Object val;
2635 MALLOC_BLOCK_INPUT;
2637 if (float_free_list)
2639 /* We use the data field for chaining the free list
2640 so that we won't use the same field that has the mark bit. */
2641 XSETFLOAT (val, float_free_list);
2642 float_free_list = float_free_list->u.chain;
2644 else
2646 if (float_block_index == FLOAT_BLOCK_SIZE)
2648 struct float_block *new
2649 = lisp_align_malloc (sizeof *new, MEM_TYPE_FLOAT);
2650 new->next = float_block;
2651 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2652 float_block = new;
2653 float_block_index = 0;
2654 total_free_floats += FLOAT_BLOCK_SIZE;
2656 XSETFLOAT (val, &float_block->floats[float_block_index]);
2657 float_block_index++;
2660 MALLOC_UNBLOCK_INPUT;
2662 XFLOAT_INIT (val, float_value);
2663 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2664 consing_since_gc += sizeof (struct Lisp_Float);
2665 floats_consed++;
2666 total_free_floats--;
2667 return val;
2672 /***********************************************************************
2673 Cons Allocation
2674 ***********************************************************************/
2676 /* We store cons cells inside of cons_blocks, allocating a new
2677 cons_block with malloc whenever necessary. Cons cells reclaimed by
2678 GC are put on a free list to be reallocated before allocating
2679 any new cons cells from the latest cons_block. */
2681 #define CONS_BLOCK_SIZE \
2682 (((BLOCK_BYTES - sizeof (struct cons_block *) \
2683 /* The compiler might add padding at the end. */ \
2684 - (sizeof (struct Lisp_Cons) - sizeof (bits_word))) * CHAR_BIT) \
2685 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2687 #define CONS_BLOCK(fptr) \
2688 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2690 #define CONS_INDEX(fptr) \
2691 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2693 struct cons_block
2695 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2696 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2697 bits_word gcmarkbits[1 + CONS_BLOCK_SIZE / BITS_PER_BITS_WORD];
2698 struct cons_block *next;
2701 #define CONS_MARKED_P(fptr) \
2702 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2704 #define CONS_MARK(fptr) \
2705 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2707 #define CONS_UNMARK(fptr) \
2708 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2710 /* Current cons_block. */
2712 static struct cons_block *cons_block;
2714 /* Index of first unused Lisp_Cons in the current block. */
2716 static int cons_block_index = CONS_BLOCK_SIZE;
2718 /* Free-list of Lisp_Cons structures. */
2720 static struct Lisp_Cons *cons_free_list;
2722 /* Explicitly free a cons cell by putting it on the free-list. */
2724 void
2725 free_cons (struct Lisp_Cons *ptr)
2727 ptr->u.chain = cons_free_list;
2728 ptr->car = Vdead;
2729 cons_free_list = ptr;
2730 consing_since_gc -= sizeof *ptr;
2731 total_free_conses++;
2734 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2735 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2736 (Lisp_Object car, Lisp_Object cdr)
2738 register Lisp_Object val;
2740 MALLOC_BLOCK_INPUT;
2742 if (cons_free_list)
2744 /* We use the cdr for chaining the free list
2745 so that we won't use the same field that has the mark bit. */
2746 XSETCONS (val, cons_free_list);
2747 cons_free_list = cons_free_list->u.chain;
2749 else
2751 if (cons_block_index == CONS_BLOCK_SIZE)
2753 struct cons_block *new
2754 = lisp_align_malloc (sizeof *new, MEM_TYPE_CONS);
2755 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2756 new->next = cons_block;
2757 cons_block = new;
2758 cons_block_index = 0;
2759 total_free_conses += CONS_BLOCK_SIZE;
2761 XSETCONS (val, &cons_block->conses[cons_block_index]);
2762 cons_block_index++;
2765 MALLOC_UNBLOCK_INPUT;
2767 XSETCAR (val, car);
2768 XSETCDR (val, cdr);
2769 eassert (!CONS_MARKED_P (XCONS (val)));
2770 consing_since_gc += sizeof (struct Lisp_Cons);
2771 total_free_conses--;
2772 cons_cells_consed++;
2773 return val;
2776 #ifdef GC_CHECK_CONS_LIST
2777 /* Get an error now if there's any junk in the cons free list. */
2778 void
2779 check_cons_list (void)
2781 struct Lisp_Cons *tail = cons_free_list;
2783 while (tail)
2784 tail = tail->u.chain;
2786 #endif
2788 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2790 Lisp_Object
2791 list1 (Lisp_Object arg1)
2793 return Fcons (arg1, Qnil);
2796 Lisp_Object
2797 list2 (Lisp_Object arg1, Lisp_Object arg2)
2799 return Fcons (arg1, Fcons (arg2, Qnil));
2803 Lisp_Object
2804 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2806 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2810 Lisp_Object
2811 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2813 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2817 Lisp_Object
2818 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2820 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2821 Fcons (arg5, Qnil)))));
2824 /* Make a list of COUNT Lisp_Objects, where ARG is the
2825 first one. Allocate conses from pure space if TYPE
2826 is CONSTYPE_PURE, or allocate as usual if type is CONSTYPE_HEAP. */
2828 Lisp_Object
2829 listn (enum constype type, ptrdiff_t count, Lisp_Object arg, ...)
2831 Lisp_Object (*cons) (Lisp_Object, Lisp_Object);
2832 switch (type)
2834 case CONSTYPE_PURE: cons = pure_cons; break;
2835 case CONSTYPE_HEAP: cons = Fcons; break;
2836 default: emacs_abort ();
2839 eassume (0 < count);
2840 Lisp_Object val = cons (arg, Qnil);
2841 Lisp_Object tail = val;
2843 va_list ap;
2844 va_start (ap, arg);
2845 for (ptrdiff_t i = 1; i < count; i++)
2847 Lisp_Object elem = cons (va_arg (ap, Lisp_Object), Qnil);
2848 XSETCDR (tail, elem);
2849 tail = elem;
2851 va_end (ap);
2853 return val;
2856 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2857 doc: /* Return a newly created list with specified arguments as elements.
2858 Any number of arguments, even zero arguments, are allowed.
2859 usage: (list &rest OBJECTS) */)
2860 (ptrdiff_t nargs, Lisp_Object *args)
2862 register Lisp_Object val;
2863 val = Qnil;
2865 while (nargs > 0)
2867 nargs--;
2868 val = Fcons (args[nargs], val);
2870 return val;
2874 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2875 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2876 (register Lisp_Object length, Lisp_Object init)
2878 register Lisp_Object val;
2879 register EMACS_INT size;
2881 CHECK_NATNUM (length);
2882 size = XFASTINT (length);
2884 val = Qnil;
2885 while (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;
2905 if (size > 0)
2907 val = Fcons (init, val);
2908 --size;
2914 QUIT;
2917 return val;
2922 /***********************************************************************
2923 Vector Allocation
2924 ***********************************************************************/
2926 /* Sometimes a vector's contents are merely a pointer internally used
2927 in vector allocation code. On the rare platforms where a null
2928 pointer cannot be tagged, represent it with a Lisp 0.
2929 Usually you don't want to touch this. */
2931 static struct Lisp_Vector *
2932 next_vector (struct Lisp_Vector *v)
2934 return XUNTAG (v->contents[0], Lisp_Int0);
2937 static void
2938 set_next_vector (struct Lisp_Vector *v, struct Lisp_Vector *p)
2940 v->contents[0] = make_lisp_ptr (p, Lisp_Int0);
2943 /* This value is balanced well enough to avoid too much internal overhead
2944 for the most common cases; it's not required to be a power of two, but
2945 it's expected to be a mult-of-ROUNDUP_SIZE (see below). */
2947 #define VECTOR_BLOCK_SIZE 4096
2949 enum
2951 /* Alignment of struct Lisp_Vector objects. */
2952 vector_alignment = COMMON_MULTIPLE (FLEXALIGNOF (struct Lisp_Vector),
2953 GCALIGNMENT),
2955 /* Vector size requests are a multiple of this. */
2956 roundup_size = COMMON_MULTIPLE (vector_alignment, word_size)
2959 /* Verify assumptions described above. */
2960 verify (VECTOR_BLOCK_SIZE % roundup_size == 0);
2961 verify (VECTOR_BLOCK_SIZE <= (1 << PSEUDOVECTOR_SIZE_BITS));
2963 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at compile time. */
2964 #define vroundup_ct(x) ROUNDUP (x, roundup_size)
2965 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at runtime. */
2966 #define vroundup(x) (eassume ((x) >= 0), vroundup_ct (x))
2968 /* Rounding helps to maintain alignment constraints if USE_LSB_TAG. */
2970 #define VECTOR_BLOCK_BYTES (VECTOR_BLOCK_SIZE - vroundup_ct (sizeof (void *)))
2972 /* Size of the minimal vector allocated from block. */
2974 #define VBLOCK_BYTES_MIN vroundup_ct (header_size + sizeof (Lisp_Object))
2976 /* Size of the largest vector allocated from block. */
2978 #define VBLOCK_BYTES_MAX \
2979 vroundup ((VECTOR_BLOCK_BYTES / 2) - word_size)
2981 /* We maintain one free list for each possible block-allocated
2982 vector size, and this is the number of free lists we have. */
2984 #define VECTOR_MAX_FREE_LIST_INDEX \
2985 ((VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN) / roundup_size + 1)
2987 /* Common shortcut to advance vector pointer over a block data. */
2989 #define ADVANCE(v, nbytes) ((struct Lisp_Vector *) ((char *) (v) + (nbytes)))
2991 /* Common shortcut to calculate NBYTES-vector index in VECTOR_FREE_LISTS. */
2993 #define VINDEX(nbytes) (((nbytes) - VBLOCK_BYTES_MIN) / roundup_size)
2995 /* Common shortcut to setup vector on a free list. */
2997 #define SETUP_ON_FREE_LIST(v, nbytes, tmp) \
2998 do { \
2999 (tmp) = ((nbytes - header_size) / word_size); \
3000 XSETPVECTYPESIZE (v, PVEC_FREE, 0, (tmp)); \
3001 eassert ((nbytes) % roundup_size == 0); \
3002 (tmp) = VINDEX (nbytes); \
3003 eassert ((tmp) < VECTOR_MAX_FREE_LIST_INDEX); \
3004 set_next_vector (v, vector_free_lists[tmp]); \
3005 vector_free_lists[tmp] = (v); \
3006 total_free_vector_slots += (nbytes) / word_size; \
3007 } while (0)
3009 /* This internal type is used to maintain the list of large vectors
3010 which are allocated at their own, e.g. outside of vector blocks.
3012 struct large_vector itself cannot contain a struct Lisp_Vector, as
3013 the latter contains a flexible array member and C99 does not allow
3014 such structs to be nested. Instead, each struct large_vector
3015 object LV is followed by a struct Lisp_Vector, which is at offset
3016 large_vector_offset from LV, and whose address is therefore
3017 large_vector_vec (&LV). */
3019 struct large_vector
3021 struct large_vector *next;
3024 enum
3026 large_vector_offset = ROUNDUP (sizeof (struct large_vector), vector_alignment)
3029 static struct Lisp_Vector *
3030 large_vector_vec (struct large_vector *p)
3032 return (struct Lisp_Vector *) ((char *) p + large_vector_offset);
3035 /* This internal type is used to maintain an underlying storage
3036 for small vectors. */
3038 struct vector_block
3040 char data[VECTOR_BLOCK_BYTES];
3041 struct vector_block *next;
3044 /* Chain of vector blocks. */
3046 static struct vector_block *vector_blocks;
3048 /* Vector free lists, where NTH item points to a chain of free
3049 vectors of the same NBYTES size, so NTH == VINDEX (NBYTES). */
3051 static struct Lisp_Vector *vector_free_lists[VECTOR_MAX_FREE_LIST_INDEX];
3053 /* Singly-linked list of large vectors. */
3055 static struct large_vector *large_vectors;
3057 /* The only vector with 0 slots, allocated from pure space. */
3059 Lisp_Object zero_vector;
3061 /* Number of live vectors. */
3063 static EMACS_INT total_vectors;
3065 /* Total size of live and free vectors, in Lisp_Object units. */
3067 static EMACS_INT total_vector_slots, total_free_vector_slots;
3069 /* Get a new vector block. */
3071 static struct vector_block *
3072 allocate_vector_block (void)
3074 struct vector_block *block = xmalloc (sizeof *block);
3076 #ifndef GC_MALLOC_CHECK
3077 mem_insert (block->data, block->data + VECTOR_BLOCK_BYTES,
3078 MEM_TYPE_VECTOR_BLOCK);
3079 #endif
3081 block->next = vector_blocks;
3082 vector_blocks = block;
3083 return block;
3086 /* Called once to initialize vector allocation. */
3088 static void
3089 init_vectors (void)
3091 zero_vector = make_pure_vector (0);
3094 /* Allocate vector from a vector block. */
3096 static struct Lisp_Vector *
3097 allocate_vector_from_block (size_t nbytes)
3099 struct Lisp_Vector *vector;
3100 struct vector_block *block;
3101 size_t index, restbytes;
3103 eassert (VBLOCK_BYTES_MIN <= nbytes && nbytes <= VBLOCK_BYTES_MAX);
3104 eassert (nbytes % roundup_size == 0);
3106 /* First, try to allocate from a free list
3107 containing vectors of the requested size. */
3108 index = VINDEX (nbytes);
3109 if (vector_free_lists[index])
3111 vector = vector_free_lists[index];
3112 vector_free_lists[index] = next_vector (vector);
3113 total_free_vector_slots -= nbytes / word_size;
3114 return vector;
3117 /* Next, check free lists containing larger vectors. Since
3118 we will split the result, we should have remaining space
3119 large enough to use for one-slot vector at least. */
3120 for (index = VINDEX (nbytes + VBLOCK_BYTES_MIN);
3121 index < VECTOR_MAX_FREE_LIST_INDEX; index++)
3122 if (vector_free_lists[index])
3124 /* This vector is larger than requested. */
3125 vector = vector_free_lists[index];
3126 vector_free_lists[index] = next_vector (vector);
3127 total_free_vector_slots -= nbytes / word_size;
3129 /* Excess bytes are used for the smaller vector,
3130 which should be set on an appropriate free list. */
3131 restbytes = index * roundup_size + VBLOCK_BYTES_MIN - nbytes;
3132 eassert (restbytes % roundup_size == 0);
3133 SETUP_ON_FREE_LIST (ADVANCE (vector, nbytes), restbytes, index);
3134 return vector;
3137 /* Finally, need a new vector block. */
3138 block = allocate_vector_block ();
3140 /* New vector will be at the beginning of this block. */
3141 vector = (struct Lisp_Vector *) block->data;
3143 /* If the rest of space from this block is large enough
3144 for one-slot vector at least, set up it on a free list. */
3145 restbytes = VECTOR_BLOCK_BYTES - nbytes;
3146 if (restbytes >= VBLOCK_BYTES_MIN)
3148 eassert (restbytes % roundup_size == 0);
3149 SETUP_ON_FREE_LIST (ADVANCE (vector, nbytes), restbytes, index);
3151 return vector;
3154 /* Nonzero if VECTOR pointer is valid pointer inside BLOCK. */
3156 #define VECTOR_IN_BLOCK(vector, block) \
3157 ((char *) (vector) <= (block)->data \
3158 + VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN)
3160 /* Return the memory footprint of V in bytes. */
3162 static ptrdiff_t
3163 vector_nbytes (struct Lisp_Vector *v)
3165 ptrdiff_t size = v->header.size & ~ARRAY_MARK_FLAG;
3166 ptrdiff_t nwords;
3168 if (size & PSEUDOVECTOR_FLAG)
3170 if (PSEUDOVECTOR_TYPEP (&v->header, PVEC_BOOL_VECTOR))
3172 struct Lisp_Bool_Vector *bv = (struct Lisp_Bool_Vector *) v;
3173 ptrdiff_t word_bytes = (bool_vector_words (bv->size)
3174 * sizeof (bits_word));
3175 ptrdiff_t boolvec_bytes = bool_header_size + word_bytes;
3176 verify (header_size <= bool_header_size);
3177 nwords = (boolvec_bytes - header_size + word_size - 1) / word_size;
3179 else
3180 nwords = ((size & PSEUDOVECTOR_SIZE_MASK)
3181 + ((size & PSEUDOVECTOR_REST_MASK)
3182 >> PSEUDOVECTOR_SIZE_BITS));
3184 else
3185 nwords = size;
3186 return vroundup (header_size + word_size * nwords);
3189 /* Release extra resources still in use by VECTOR, which may be any
3190 vector-like object. For now, this is used just to free data in
3191 font objects. */
3193 static void
3194 cleanup_vector (struct Lisp_Vector *vector)
3196 detect_suspicious_free (vector);
3197 if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FONT)
3198 && ((vector->header.size & PSEUDOVECTOR_SIZE_MASK)
3199 == FONT_OBJECT_MAX))
3201 struct font_driver *drv = ((struct font *) vector)->driver;
3203 /* The font driver might sometimes be NULL, e.g. if Emacs was
3204 interrupted before it had time to set it up. */
3205 if (drv)
3207 /* Attempt to catch subtle bugs like Bug#16140. */
3208 eassert (valid_font_driver (drv));
3209 drv->close ((struct font *) vector);
3214 /* Reclaim space used by unmarked vectors. */
3216 NO_INLINE /* For better stack traces */
3217 static void
3218 sweep_vectors (void)
3220 struct vector_block *block, **bprev = &vector_blocks;
3221 struct large_vector *lv, **lvprev = &large_vectors;
3222 struct Lisp_Vector *vector, *next;
3224 total_vectors = total_vector_slots = total_free_vector_slots = 0;
3225 memset (vector_free_lists, 0, sizeof (vector_free_lists));
3227 /* Looking through vector blocks. */
3229 for (block = vector_blocks; block; block = *bprev)
3231 bool free_this_block = 0;
3232 ptrdiff_t nbytes;
3234 for (vector = (struct Lisp_Vector *) block->data;
3235 VECTOR_IN_BLOCK (vector, block); vector = next)
3237 if (VECTOR_MARKED_P (vector))
3239 VECTOR_UNMARK (vector);
3240 total_vectors++;
3241 nbytes = vector_nbytes (vector);
3242 total_vector_slots += nbytes / word_size;
3243 next = ADVANCE (vector, nbytes);
3245 else
3247 ptrdiff_t total_bytes;
3249 cleanup_vector (vector);
3250 nbytes = vector_nbytes (vector);
3251 total_bytes = nbytes;
3252 next = ADVANCE (vector, nbytes);
3254 /* While NEXT is not marked, try to coalesce with VECTOR,
3255 thus making VECTOR of the largest possible size. */
3257 while (VECTOR_IN_BLOCK (next, block))
3259 if (VECTOR_MARKED_P (next))
3260 break;
3261 cleanup_vector (next);
3262 nbytes = vector_nbytes (next);
3263 total_bytes += nbytes;
3264 next = ADVANCE (next, nbytes);
3267 eassert (total_bytes % roundup_size == 0);
3269 if (vector == (struct Lisp_Vector *) block->data
3270 && !VECTOR_IN_BLOCK (next, block))
3271 /* This block should be freed because all of its
3272 space was coalesced into the only free vector. */
3273 free_this_block = 1;
3274 else
3276 size_t tmp;
3277 SETUP_ON_FREE_LIST (vector, total_bytes, tmp);
3282 if (free_this_block)
3284 *bprev = block->next;
3285 #ifndef GC_MALLOC_CHECK
3286 mem_delete (mem_find (block->data));
3287 #endif
3288 xfree (block);
3290 else
3291 bprev = &block->next;
3294 /* Sweep large vectors. */
3296 for (lv = large_vectors; lv; lv = *lvprev)
3298 vector = large_vector_vec (lv);
3299 if (VECTOR_MARKED_P (vector))
3301 VECTOR_UNMARK (vector);
3302 total_vectors++;
3303 if (vector->header.size & PSEUDOVECTOR_FLAG)
3305 /* All non-bool pseudovectors are small enough to be allocated
3306 from vector blocks. This code should be redesigned if some
3307 pseudovector type grows beyond VBLOCK_BYTES_MAX. */
3308 eassert (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_BOOL_VECTOR));
3309 total_vector_slots += vector_nbytes (vector) / word_size;
3311 else
3312 total_vector_slots
3313 += header_size / word_size + vector->header.size;
3314 lvprev = &lv->next;
3316 else
3318 *lvprev = lv->next;
3319 lisp_free (lv);
3324 /* Value is a pointer to a newly allocated Lisp_Vector structure
3325 with room for LEN Lisp_Objects. */
3327 static struct Lisp_Vector *
3328 allocate_vectorlike (ptrdiff_t len)
3330 struct Lisp_Vector *p;
3332 MALLOC_BLOCK_INPUT;
3334 if (len == 0)
3335 p = XVECTOR (zero_vector);
3336 else
3338 size_t nbytes = header_size + len * word_size;
3340 #ifdef DOUG_LEA_MALLOC
3341 if (!mmap_lisp_allowed_p ())
3342 mallopt (M_MMAP_MAX, 0);
3343 #endif
3345 if (nbytes <= VBLOCK_BYTES_MAX)
3346 p = allocate_vector_from_block (vroundup (nbytes));
3347 else
3349 struct large_vector *lv
3350 = lisp_malloc ((large_vector_offset + header_size
3351 + len * word_size),
3352 MEM_TYPE_VECTORLIKE);
3353 lv->next = large_vectors;
3354 large_vectors = lv;
3355 p = large_vector_vec (lv);
3358 #ifdef DOUG_LEA_MALLOC
3359 if (!mmap_lisp_allowed_p ())
3360 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
3361 #endif
3363 if (find_suspicious_object_in_range (p, (char *) p + nbytes))
3364 emacs_abort ();
3366 consing_since_gc += nbytes;
3367 vector_cells_consed += len;
3370 MALLOC_UNBLOCK_INPUT;
3372 return p;
3376 /* Allocate a vector with LEN slots. */
3378 struct Lisp_Vector *
3379 allocate_vector (EMACS_INT len)
3381 struct Lisp_Vector *v;
3382 ptrdiff_t nbytes_max = min (PTRDIFF_MAX, SIZE_MAX);
3384 if (min ((nbytes_max - header_size) / word_size, MOST_POSITIVE_FIXNUM) < len)
3385 memory_full (SIZE_MAX);
3386 v = allocate_vectorlike (len);
3387 if (len)
3388 v->header.size = len;
3389 return v;
3393 /* Allocate other vector-like structures. */
3395 struct Lisp_Vector *
3396 allocate_pseudovector (int memlen, int lisplen,
3397 int zerolen, enum pvec_type tag)
3399 struct Lisp_Vector *v = allocate_vectorlike (memlen);
3401 /* Catch bogus values. */
3402 eassert (0 <= tag && tag <= PVEC_FONT);
3403 eassert (0 <= lisplen && lisplen <= zerolen && zerolen <= memlen);
3404 eassert (memlen - lisplen <= (1 << PSEUDOVECTOR_REST_BITS) - 1);
3405 eassert (lisplen <= (1 << PSEUDOVECTOR_SIZE_BITS) - 1);
3407 /* Only the first LISPLEN slots will be traced normally by the GC. */
3408 memclear (v->contents, zerolen * word_size);
3409 XSETPVECTYPESIZE (v, tag, lisplen, memlen - lisplen);
3410 return v;
3413 struct buffer *
3414 allocate_buffer (void)
3416 struct buffer *b = lisp_malloc (sizeof *b, MEM_TYPE_BUFFER);
3418 BUFFER_PVEC_INIT (b);
3419 /* Put B on the chain of all buffers including killed ones. */
3420 b->next = all_buffers;
3421 all_buffers = b;
3422 /* Note that the rest fields of B are not initialized. */
3423 return b;
3426 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
3427 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
3428 See also the function `vector'. */)
3429 (Lisp_Object length, Lisp_Object init)
3431 CHECK_NATNUM (length);
3432 struct Lisp_Vector *p = allocate_vector (XFASTINT (length));
3433 for (ptrdiff_t i = 0; i < XFASTINT (length); i++)
3434 p->contents[i] = init;
3435 return make_lisp_ptr (p, Lisp_Vectorlike);
3438 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3439 doc: /* Return a newly created vector with specified arguments as elements.
3440 Any number of arguments, even zero arguments, are allowed.
3441 usage: (vector &rest OBJECTS) */)
3442 (ptrdiff_t nargs, Lisp_Object *args)
3444 Lisp_Object val = make_uninit_vector (nargs);
3445 struct Lisp_Vector *p = XVECTOR (val);
3446 memcpy (p->contents, args, nargs * sizeof *args);
3447 return val;
3450 void
3451 make_byte_code (struct Lisp_Vector *v)
3453 /* Don't allow the global zero_vector to become a byte code object. */
3454 eassert (0 < v->header.size);
3456 if (v->header.size > 1 && STRINGP (v->contents[1])
3457 && STRING_MULTIBYTE (v->contents[1]))
3458 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3459 earlier because they produced a raw 8-bit string for byte-code
3460 and now such a byte-code string is loaded as multibyte while
3461 raw 8-bit characters converted to multibyte form. Thus, now we
3462 must convert them back to the original unibyte form. */
3463 v->contents[1] = Fstring_as_unibyte (v->contents[1]);
3464 XSETPVECTYPE (v, PVEC_COMPILED);
3467 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3468 doc: /* Create a byte-code object with specified arguments as elements.
3469 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3470 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3471 and (optional) INTERACTIVE-SPEC.
3472 The first four arguments are required; at most six have any
3473 significance.
3474 The ARGLIST can be either like the one of `lambda', in which case the arguments
3475 will be dynamically bound before executing the byte code, or it can be an
3476 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3477 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3478 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3479 argument to catch the left-over arguments. If such an integer is used, the
3480 arguments will not be dynamically bound but will be instead pushed on the
3481 stack before executing the byte-code.
3482 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3483 (ptrdiff_t nargs, Lisp_Object *args)
3485 Lisp_Object val = make_uninit_vector (nargs);
3486 struct Lisp_Vector *p = XVECTOR (val);
3488 /* We used to purecopy everything here, if purify-flag was set. This worked
3489 OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
3490 dangerous, since make-byte-code is used during execution to build
3491 closures, so any closure built during the preload phase would end up
3492 copied into pure space, including its free variables, which is sometimes
3493 just wasteful and other times plainly wrong (e.g. those free vars may want
3494 to be setcar'd). */
3496 memcpy (p->contents, args, nargs * sizeof *args);
3497 make_byte_code (p);
3498 XSETCOMPILED (val, p);
3499 return val;
3504 /***********************************************************************
3505 Symbol Allocation
3506 ***********************************************************************/
3508 /* Like struct Lisp_Symbol, but padded so that the size is a multiple
3509 of the required alignment. */
3511 union aligned_Lisp_Symbol
3513 struct Lisp_Symbol s;
3514 unsigned char c[(sizeof (struct Lisp_Symbol) + GCALIGNMENT - 1)
3515 & -GCALIGNMENT];
3518 /* Each symbol_block is just under 1020 bytes long, since malloc
3519 really allocates in units of powers of two and uses 4 bytes for its
3520 own overhead. */
3522 #define SYMBOL_BLOCK_SIZE \
3523 ((1020 - sizeof (struct symbol_block *)) / sizeof (union aligned_Lisp_Symbol))
3525 struct symbol_block
3527 /* Place `symbols' first, to preserve alignment. */
3528 union aligned_Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3529 struct symbol_block *next;
3532 /* Current symbol block and index of first unused Lisp_Symbol
3533 structure in it. */
3535 static struct symbol_block *symbol_block;
3536 static int symbol_block_index = SYMBOL_BLOCK_SIZE;
3537 /* Pointer to the first symbol_block that contains pinned symbols.
3538 Tests for 24.4 showed that at dump-time, Emacs contains about 15K symbols,
3539 10K of which are pinned (and all but 250 of them are interned in obarray),
3540 whereas a "typical session" has in the order of 30K symbols.
3541 `symbol_block_pinned' lets mark_pinned_symbols scan only 15K symbols rather
3542 than 30K to find the 10K symbols we need to mark. */
3543 static struct symbol_block *symbol_block_pinned;
3545 /* List of free symbols. */
3547 static struct Lisp_Symbol *symbol_free_list;
3549 static void
3550 set_symbol_name (Lisp_Object sym, Lisp_Object name)
3552 XSYMBOL (sym)->name = name;
3555 void
3556 init_symbol (Lisp_Object val, Lisp_Object name)
3558 struct Lisp_Symbol *p = XSYMBOL (val);
3559 set_symbol_name (val, name);
3560 set_symbol_plist (val, Qnil);
3561 p->redirect = SYMBOL_PLAINVAL;
3562 SET_SYMBOL_VAL (p, Qunbound);
3563 set_symbol_function (val, Qnil);
3564 set_symbol_next (val, NULL);
3565 p->gcmarkbit = false;
3566 p->interned = SYMBOL_UNINTERNED;
3567 p->constant = 0;
3568 p->declared_special = false;
3569 p->pinned = false;
3572 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3573 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3574 Its value is void, and its function definition and property list are nil. */)
3575 (Lisp_Object name)
3577 Lisp_Object val;
3579 CHECK_STRING (name);
3581 MALLOC_BLOCK_INPUT;
3583 if (symbol_free_list)
3585 XSETSYMBOL (val, symbol_free_list);
3586 symbol_free_list = symbol_free_list->next;
3588 else
3590 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3592 struct symbol_block *new
3593 = lisp_malloc (sizeof *new, MEM_TYPE_SYMBOL);
3594 new->next = symbol_block;
3595 symbol_block = new;
3596 symbol_block_index = 0;
3597 total_free_symbols += SYMBOL_BLOCK_SIZE;
3599 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index].s);
3600 symbol_block_index++;
3603 MALLOC_UNBLOCK_INPUT;
3605 init_symbol (val, name);
3606 consing_since_gc += sizeof (struct Lisp_Symbol);
3607 symbols_consed++;
3608 total_free_symbols--;
3609 return val;
3614 /***********************************************************************
3615 Marker (Misc) Allocation
3616 ***********************************************************************/
3618 /* Like union Lisp_Misc, but padded so that its size is a multiple of
3619 the required alignment. */
3621 union aligned_Lisp_Misc
3623 union Lisp_Misc m;
3624 unsigned char c[(sizeof (union Lisp_Misc) + GCALIGNMENT - 1)
3625 & -GCALIGNMENT];
3628 /* Allocation of markers and other objects that share that structure.
3629 Works like allocation of conses. */
3631 #define MARKER_BLOCK_SIZE \
3632 ((1020 - sizeof (struct marker_block *)) / sizeof (union aligned_Lisp_Misc))
3634 struct marker_block
3636 /* Place `markers' first, to preserve alignment. */
3637 union aligned_Lisp_Misc markers[MARKER_BLOCK_SIZE];
3638 struct marker_block *next;
3641 static struct marker_block *marker_block;
3642 static int marker_block_index = MARKER_BLOCK_SIZE;
3644 static union Lisp_Misc *marker_free_list;
3646 /* Return a newly allocated Lisp_Misc object of specified TYPE. */
3648 static Lisp_Object
3649 allocate_misc (enum Lisp_Misc_Type type)
3651 Lisp_Object val;
3653 MALLOC_BLOCK_INPUT;
3655 if (marker_free_list)
3657 XSETMISC (val, marker_free_list);
3658 marker_free_list = marker_free_list->u_free.chain;
3660 else
3662 if (marker_block_index == MARKER_BLOCK_SIZE)
3664 struct marker_block *new = lisp_malloc (sizeof *new, MEM_TYPE_MISC);
3665 new->next = marker_block;
3666 marker_block = new;
3667 marker_block_index = 0;
3668 total_free_markers += MARKER_BLOCK_SIZE;
3670 XSETMISC (val, &marker_block->markers[marker_block_index].m);
3671 marker_block_index++;
3674 MALLOC_UNBLOCK_INPUT;
3676 --total_free_markers;
3677 consing_since_gc += sizeof (union Lisp_Misc);
3678 misc_objects_consed++;
3679 XMISCANY (val)->type = type;
3680 XMISCANY (val)->gcmarkbit = 0;
3681 return val;
3684 /* Free a Lisp_Misc object. */
3686 void
3687 free_misc (Lisp_Object misc)
3689 XMISCANY (misc)->type = Lisp_Misc_Free;
3690 XMISC (misc)->u_free.chain = marker_free_list;
3691 marker_free_list = XMISC (misc);
3692 consing_since_gc -= sizeof (union Lisp_Misc);
3693 total_free_markers++;
3696 /* Verify properties of Lisp_Save_Value's representation
3697 that are assumed here and elsewhere. */
3699 verify (SAVE_UNUSED == 0);
3700 verify (((SAVE_INTEGER | SAVE_POINTER | SAVE_FUNCPOINTER | SAVE_OBJECT)
3701 >> SAVE_SLOT_BITS)
3702 == 0);
3704 /* Return Lisp_Save_Value objects for the various combinations
3705 that callers need. */
3707 Lisp_Object
3708 make_save_int_int_int (ptrdiff_t a, ptrdiff_t b, ptrdiff_t c)
3710 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3711 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3712 p->save_type = SAVE_TYPE_INT_INT_INT;
3713 p->data[0].integer = a;
3714 p->data[1].integer = b;
3715 p->data[2].integer = c;
3716 return val;
3719 Lisp_Object
3720 make_save_obj_obj_obj_obj (Lisp_Object a, Lisp_Object b, Lisp_Object c,
3721 Lisp_Object d)
3723 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3724 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3725 p->save_type = SAVE_TYPE_OBJ_OBJ_OBJ_OBJ;
3726 p->data[0].object = a;
3727 p->data[1].object = b;
3728 p->data[2].object = c;
3729 p->data[3].object = d;
3730 return val;
3733 Lisp_Object
3734 make_save_ptr (void *a)
3736 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3737 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3738 p->save_type = SAVE_POINTER;
3739 p->data[0].pointer = a;
3740 return val;
3743 Lisp_Object
3744 make_save_ptr_int (void *a, ptrdiff_t b)
3746 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3747 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3748 p->save_type = SAVE_TYPE_PTR_INT;
3749 p->data[0].pointer = a;
3750 p->data[1].integer = b;
3751 return val;
3754 Lisp_Object
3755 make_save_ptr_ptr (void *a, void *b)
3757 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3758 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3759 p->save_type = SAVE_TYPE_PTR_PTR;
3760 p->data[0].pointer = a;
3761 p->data[1].pointer = b;
3762 return val;
3765 Lisp_Object
3766 make_save_funcptr_ptr_obj (void (*a) (void), void *b, Lisp_Object c)
3768 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3769 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3770 p->save_type = SAVE_TYPE_FUNCPTR_PTR_OBJ;
3771 p->data[0].funcpointer = a;
3772 p->data[1].pointer = b;
3773 p->data[2].object = c;
3774 return val;
3777 /* Return a Lisp_Save_Value object that represents an array A
3778 of N Lisp objects. */
3780 Lisp_Object
3781 make_save_memory (Lisp_Object *a, ptrdiff_t n)
3783 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3784 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3785 p->save_type = SAVE_TYPE_MEMORY;
3786 p->data[0].pointer = a;
3787 p->data[1].integer = n;
3788 return val;
3791 /* Free a Lisp_Save_Value object. Do not use this function
3792 if SAVE contains pointer other than returned by xmalloc. */
3794 void
3795 free_save_value (Lisp_Object save)
3797 xfree (XSAVE_POINTER (save, 0));
3798 free_misc (save);
3801 /* Return a Lisp_Misc_Overlay object with specified START, END and PLIST. */
3803 Lisp_Object
3804 build_overlay (Lisp_Object start, Lisp_Object end, Lisp_Object plist)
3806 register Lisp_Object overlay;
3808 overlay = allocate_misc (Lisp_Misc_Overlay);
3809 OVERLAY_START (overlay) = start;
3810 OVERLAY_END (overlay) = end;
3811 set_overlay_plist (overlay, plist);
3812 XOVERLAY (overlay)->next = NULL;
3813 return overlay;
3816 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3817 doc: /* Return a newly allocated marker which does not point at any place. */)
3818 (void)
3820 register Lisp_Object val;
3821 register struct Lisp_Marker *p;
3823 val = allocate_misc (Lisp_Misc_Marker);
3824 p = XMARKER (val);
3825 p->buffer = 0;
3826 p->bytepos = 0;
3827 p->charpos = 0;
3828 p->next = NULL;
3829 p->insertion_type = 0;
3830 p->need_adjustment = 0;
3831 return val;
3834 /* Return a newly allocated marker which points into BUF
3835 at character position CHARPOS and byte position BYTEPOS. */
3837 Lisp_Object
3838 build_marker (struct buffer *buf, ptrdiff_t charpos, ptrdiff_t bytepos)
3840 Lisp_Object obj;
3841 struct Lisp_Marker *m;
3843 /* No dead buffers here. */
3844 eassert (BUFFER_LIVE_P (buf));
3846 /* Every character is at least one byte. */
3847 eassert (charpos <= bytepos);
3849 obj = allocate_misc (Lisp_Misc_Marker);
3850 m = XMARKER (obj);
3851 m->buffer = buf;
3852 m->charpos = charpos;
3853 m->bytepos = bytepos;
3854 m->insertion_type = 0;
3855 m->need_adjustment = 0;
3856 m->next = BUF_MARKERS (buf);
3857 BUF_MARKERS (buf) = m;
3858 return obj;
3861 /* Put MARKER back on the free list after using it temporarily. */
3863 void
3864 free_marker (Lisp_Object marker)
3866 unchain_marker (XMARKER (marker));
3867 free_misc (marker);
3871 /* Return a newly created vector or string with specified arguments as
3872 elements. If all the arguments are characters that can fit
3873 in a string of events, make a string; otherwise, make a vector.
3875 Any number of arguments, even zero arguments, are allowed. */
3877 Lisp_Object
3878 make_event_array (ptrdiff_t nargs, Lisp_Object *args)
3880 ptrdiff_t i;
3882 for (i = 0; i < nargs; i++)
3883 /* The things that fit in a string
3884 are characters that are in 0...127,
3885 after discarding the meta bit and all the bits above it. */
3886 if (!INTEGERP (args[i])
3887 || (XINT (args[i]) & ~(-CHAR_META)) >= 0200)
3888 return Fvector (nargs, args);
3890 /* Since the loop exited, we know that all the things in it are
3891 characters, so we can make a string. */
3893 Lisp_Object result;
3895 result = Fmake_string (make_number (nargs), make_number (0));
3896 for (i = 0; i < nargs; i++)
3898 SSET (result, i, XINT (args[i]));
3899 /* Move the meta bit to the right place for a string char. */
3900 if (XINT (args[i]) & CHAR_META)
3901 SSET (result, i, SREF (result, i) | 0x80);
3904 return result;
3908 #ifdef HAVE_MODULES
3909 /* Create a new module user ptr object. */
3910 Lisp_Object
3911 make_user_ptr (void (*finalizer) (void *), void *p)
3913 Lisp_Object obj;
3914 struct Lisp_User_Ptr *uptr;
3916 obj = allocate_misc (Lisp_Misc_User_Ptr);
3917 uptr = XUSER_PTR (obj);
3918 uptr->finalizer = finalizer;
3919 uptr->p = p;
3920 return obj;
3923 #endif
3925 static void
3926 init_finalizer_list (struct Lisp_Finalizer *head)
3928 head->prev = head->next = head;
3931 /* Insert FINALIZER before ELEMENT. */
3933 static void
3934 finalizer_insert (struct Lisp_Finalizer *element,
3935 struct Lisp_Finalizer *finalizer)
3937 eassert (finalizer->prev == NULL);
3938 eassert (finalizer->next == NULL);
3939 finalizer->next = element;
3940 finalizer->prev = element->prev;
3941 finalizer->prev->next = finalizer;
3942 element->prev = finalizer;
3945 static void
3946 unchain_finalizer (struct Lisp_Finalizer *finalizer)
3948 if (finalizer->prev != NULL)
3950 eassert (finalizer->next != NULL);
3951 finalizer->prev->next = finalizer->next;
3952 finalizer->next->prev = finalizer->prev;
3953 finalizer->prev = finalizer->next = NULL;
3957 static void
3958 mark_finalizer_list (struct Lisp_Finalizer *head)
3960 for (struct Lisp_Finalizer *finalizer = head->next;
3961 finalizer != head;
3962 finalizer = finalizer->next)
3964 finalizer->base.gcmarkbit = true;
3965 mark_object (finalizer->function);
3969 /* Move doomed finalizers to list DEST from list SRC. A doomed
3970 finalizer is one that is not GC-reachable and whose
3971 finalizer->function is non-nil. */
3973 static void
3974 queue_doomed_finalizers (struct Lisp_Finalizer *dest,
3975 struct Lisp_Finalizer *src)
3977 struct Lisp_Finalizer *finalizer = src->next;
3978 while (finalizer != src)
3980 struct Lisp_Finalizer *next = finalizer->next;
3981 if (!finalizer->base.gcmarkbit && !NILP (finalizer->function))
3983 unchain_finalizer (finalizer);
3984 finalizer_insert (dest, finalizer);
3987 finalizer = next;
3991 static Lisp_Object
3992 run_finalizer_handler (Lisp_Object args)
3994 add_to_log ("finalizer failed: %S", args);
3995 return Qnil;
3998 static void
3999 run_finalizer_function (Lisp_Object function)
4001 ptrdiff_t count = SPECPDL_INDEX ();
4003 specbind (Qinhibit_quit, Qt);
4004 internal_condition_case_1 (call0, function, Qt, run_finalizer_handler);
4005 unbind_to (count, Qnil);
4008 static void
4009 run_finalizers (struct Lisp_Finalizer *finalizers)
4011 struct Lisp_Finalizer *finalizer;
4012 Lisp_Object function;
4014 while (finalizers->next != finalizers)
4016 finalizer = finalizers->next;
4017 eassert (finalizer->base.type == Lisp_Misc_Finalizer);
4018 unchain_finalizer (finalizer);
4019 function = finalizer->function;
4020 if (!NILP (function))
4022 finalizer->function = Qnil;
4023 run_finalizer_function (function);
4028 DEFUN ("make-finalizer", Fmake_finalizer, Smake_finalizer, 1, 1, 0,
4029 doc: /* Make a finalizer that will run FUNCTION.
4030 FUNCTION will be called after garbage collection when the returned
4031 finalizer object becomes unreachable. If the finalizer object is
4032 reachable only through references from finalizer objects, it does not
4033 count as reachable for the purpose of deciding whether to run
4034 FUNCTION. FUNCTION will be run once per finalizer object. */)
4035 (Lisp_Object function)
4037 Lisp_Object val = allocate_misc (Lisp_Misc_Finalizer);
4038 struct Lisp_Finalizer *finalizer = XFINALIZER (val);
4039 finalizer->function = function;
4040 finalizer->prev = finalizer->next = NULL;
4041 finalizer_insert (&finalizers, finalizer);
4042 return val;
4046 /************************************************************************
4047 Memory Full Handling
4048 ************************************************************************/
4051 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
4052 there may have been size_t overflow so that malloc was never
4053 called, or perhaps malloc was invoked successfully but the
4054 resulting pointer had problems fitting into a tagged EMACS_INT. In
4055 either case this counts as memory being full even though malloc did
4056 not fail. */
4058 void
4059 memory_full (size_t nbytes)
4061 /* Do not go into hysterics merely because a large request failed. */
4062 bool enough_free_memory = 0;
4063 if (SPARE_MEMORY < nbytes)
4065 void *p;
4067 MALLOC_BLOCK_INPUT;
4068 p = malloc (SPARE_MEMORY);
4069 if (p)
4071 free (p);
4072 enough_free_memory = 1;
4074 MALLOC_UNBLOCK_INPUT;
4077 if (! enough_free_memory)
4079 int i;
4081 Vmemory_full = Qt;
4083 memory_full_cons_threshold = sizeof (struct cons_block);
4085 /* The first time we get here, free the spare memory. */
4086 for (i = 0; i < ARRAYELTS (spare_memory); i++)
4087 if (spare_memory[i])
4089 if (i == 0)
4090 free (spare_memory[i]);
4091 else if (i >= 1 && i <= 4)
4092 lisp_align_free (spare_memory[i]);
4093 else
4094 lisp_free (spare_memory[i]);
4095 spare_memory[i] = 0;
4099 /* This used to call error, but if we've run out of memory, we could
4100 get infinite recursion trying to build the string. */
4101 xsignal (Qnil, Vmemory_signal_data);
4104 /* If we released our reserve (due to running out of memory),
4105 and we have a fair amount free once again,
4106 try to set aside another reserve in case we run out once more.
4108 This is called when a relocatable block is freed in ralloc.c,
4109 and also directly from this file, in case we're not using ralloc.c. */
4111 void
4112 refill_memory_reserve (void)
4114 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
4115 if (spare_memory[0] == 0)
4116 spare_memory[0] = malloc (SPARE_MEMORY);
4117 if (spare_memory[1] == 0)
4118 spare_memory[1] = lisp_align_malloc (sizeof (struct cons_block),
4119 MEM_TYPE_SPARE);
4120 if (spare_memory[2] == 0)
4121 spare_memory[2] = lisp_align_malloc (sizeof (struct cons_block),
4122 MEM_TYPE_SPARE);
4123 if (spare_memory[3] == 0)
4124 spare_memory[3] = lisp_align_malloc (sizeof (struct cons_block),
4125 MEM_TYPE_SPARE);
4126 if (spare_memory[4] == 0)
4127 spare_memory[4] = lisp_align_malloc (sizeof (struct cons_block),
4128 MEM_TYPE_SPARE);
4129 if (spare_memory[5] == 0)
4130 spare_memory[5] = lisp_malloc (sizeof (struct string_block),
4131 MEM_TYPE_SPARE);
4132 if (spare_memory[6] == 0)
4133 spare_memory[6] = lisp_malloc (sizeof (struct string_block),
4134 MEM_TYPE_SPARE);
4135 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
4136 Vmemory_full = Qnil;
4137 #endif
4140 /************************************************************************
4141 C Stack Marking
4142 ************************************************************************/
4144 /* Conservative C stack marking requires a method to identify possibly
4145 live Lisp objects given a pointer value. We do this by keeping
4146 track of blocks of Lisp data that are allocated in a red-black tree
4147 (see also the comment of mem_node which is the type of nodes in
4148 that tree). Function lisp_malloc adds information for an allocated
4149 block to the red-black tree with calls to mem_insert, and function
4150 lisp_free removes it with mem_delete. Functions live_string_p etc
4151 call mem_find to lookup information about a given pointer in the
4152 tree, and use that to determine if the pointer points to a Lisp
4153 object or not. */
4155 /* Initialize this part of alloc.c. */
4157 static void
4158 mem_init (void)
4160 mem_z.left = mem_z.right = MEM_NIL;
4161 mem_z.parent = NULL;
4162 mem_z.color = MEM_BLACK;
4163 mem_z.start = mem_z.end = NULL;
4164 mem_root = MEM_NIL;
4168 /* Value is a pointer to the mem_node containing START. Value is
4169 MEM_NIL if there is no node in the tree containing START. */
4171 static struct mem_node *
4172 mem_find (void *start)
4174 struct mem_node *p;
4176 if (start < min_heap_address || start > max_heap_address)
4177 return MEM_NIL;
4179 /* Make the search always successful to speed up the loop below. */
4180 mem_z.start = start;
4181 mem_z.end = (char *) start + 1;
4183 p = mem_root;
4184 while (start < p->start || start >= p->end)
4185 p = start < p->start ? p->left : p->right;
4186 return p;
4190 /* Insert a new node into the tree for a block of memory with start
4191 address START, end address END, and type TYPE. Value is a
4192 pointer to the node that was inserted. */
4194 static struct mem_node *
4195 mem_insert (void *start, void *end, enum mem_type type)
4197 struct mem_node *c, *parent, *x;
4199 if (min_heap_address == NULL || start < min_heap_address)
4200 min_heap_address = start;
4201 if (max_heap_address == NULL || end > max_heap_address)
4202 max_heap_address = end;
4204 /* See where in the tree a node for START belongs. In this
4205 particular application, it shouldn't happen that a node is already
4206 present. For debugging purposes, let's check that. */
4207 c = mem_root;
4208 parent = NULL;
4210 while (c != MEM_NIL)
4212 parent = c;
4213 c = start < c->start ? c->left : c->right;
4216 /* Create a new node. */
4217 #ifdef GC_MALLOC_CHECK
4218 x = malloc (sizeof *x);
4219 if (x == NULL)
4220 emacs_abort ();
4221 #else
4222 x = xmalloc (sizeof *x);
4223 #endif
4224 x->start = start;
4225 x->end = end;
4226 x->type = type;
4227 x->parent = parent;
4228 x->left = x->right = MEM_NIL;
4229 x->color = MEM_RED;
4231 /* Insert it as child of PARENT or install it as root. */
4232 if (parent)
4234 if (start < parent->start)
4235 parent->left = x;
4236 else
4237 parent->right = x;
4239 else
4240 mem_root = x;
4242 /* Re-establish red-black tree properties. */
4243 mem_insert_fixup (x);
4245 return x;
4249 /* Re-establish the red-black properties of the tree, and thereby
4250 balance the tree, after node X has been inserted; X is always red. */
4252 static void
4253 mem_insert_fixup (struct mem_node *x)
4255 while (x != mem_root && x->parent->color == MEM_RED)
4257 /* X is red and its parent is red. This is a violation of
4258 red-black tree property #3. */
4260 if (x->parent == x->parent->parent->left)
4262 /* We're on the left side of our grandparent, and Y is our
4263 "uncle". */
4264 struct mem_node *y = x->parent->parent->right;
4266 if (y->color == MEM_RED)
4268 /* Uncle and parent are red but should be black because
4269 X is red. Change the colors accordingly and proceed
4270 with the grandparent. */
4271 x->parent->color = MEM_BLACK;
4272 y->color = MEM_BLACK;
4273 x->parent->parent->color = MEM_RED;
4274 x = x->parent->parent;
4276 else
4278 /* Parent and uncle have different colors; parent is
4279 red, uncle is black. */
4280 if (x == x->parent->right)
4282 x = x->parent;
4283 mem_rotate_left (x);
4286 x->parent->color = MEM_BLACK;
4287 x->parent->parent->color = MEM_RED;
4288 mem_rotate_right (x->parent->parent);
4291 else
4293 /* This is the symmetrical case of above. */
4294 struct mem_node *y = x->parent->parent->left;
4296 if (y->color == MEM_RED)
4298 x->parent->color = MEM_BLACK;
4299 y->color = MEM_BLACK;
4300 x->parent->parent->color = MEM_RED;
4301 x = x->parent->parent;
4303 else
4305 if (x == x->parent->left)
4307 x = x->parent;
4308 mem_rotate_right (x);
4311 x->parent->color = MEM_BLACK;
4312 x->parent->parent->color = MEM_RED;
4313 mem_rotate_left (x->parent->parent);
4318 /* The root may have been changed to red due to the algorithm. Set
4319 it to black so that property #5 is satisfied. */
4320 mem_root->color = MEM_BLACK;
4324 /* (x) (y)
4325 / \ / \
4326 a (y) ===> (x) c
4327 / \ / \
4328 b c a b */
4330 static void
4331 mem_rotate_left (struct mem_node *x)
4333 struct mem_node *y;
4335 /* Turn y's left sub-tree into x's right sub-tree. */
4336 y = x->right;
4337 x->right = y->left;
4338 if (y->left != MEM_NIL)
4339 y->left->parent = x;
4341 /* Y's parent was x's parent. */
4342 if (y != MEM_NIL)
4343 y->parent = x->parent;
4345 /* Get the parent to point to y instead of x. */
4346 if (x->parent)
4348 if (x == x->parent->left)
4349 x->parent->left = y;
4350 else
4351 x->parent->right = y;
4353 else
4354 mem_root = y;
4356 /* Put x on y's left. */
4357 y->left = x;
4358 if (x != MEM_NIL)
4359 x->parent = y;
4363 /* (x) (Y)
4364 / \ / \
4365 (y) c ===> a (x)
4366 / \ / \
4367 a b b c */
4369 static void
4370 mem_rotate_right (struct mem_node *x)
4372 struct mem_node *y = x->left;
4374 x->left = y->right;
4375 if (y->right != MEM_NIL)
4376 y->right->parent = x;
4378 if (y != MEM_NIL)
4379 y->parent = x->parent;
4380 if (x->parent)
4382 if (x == x->parent->right)
4383 x->parent->right = y;
4384 else
4385 x->parent->left = y;
4387 else
4388 mem_root = y;
4390 y->right = x;
4391 if (x != MEM_NIL)
4392 x->parent = y;
4396 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
4398 static void
4399 mem_delete (struct mem_node *z)
4401 struct mem_node *x, *y;
4403 if (!z || z == MEM_NIL)
4404 return;
4406 if (z->left == MEM_NIL || z->right == MEM_NIL)
4407 y = z;
4408 else
4410 y = z->right;
4411 while (y->left != MEM_NIL)
4412 y = y->left;
4415 if (y->left != MEM_NIL)
4416 x = y->left;
4417 else
4418 x = y->right;
4420 x->parent = y->parent;
4421 if (y->parent)
4423 if (y == y->parent->left)
4424 y->parent->left = x;
4425 else
4426 y->parent->right = x;
4428 else
4429 mem_root = x;
4431 if (y != z)
4433 z->start = y->start;
4434 z->end = y->end;
4435 z->type = y->type;
4438 if (y->color == MEM_BLACK)
4439 mem_delete_fixup (x);
4441 #ifdef GC_MALLOC_CHECK
4442 free (y);
4443 #else
4444 xfree (y);
4445 #endif
4449 /* Re-establish the red-black properties of the tree, after a
4450 deletion. */
4452 static void
4453 mem_delete_fixup (struct mem_node *x)
4455 while (x != mem_root && x->color == MEM_BLACK)
4457 if (x == x->parent->left)
4459 struct mem_node *w = x->parent->right;
4461 if (w->color == MEM_RED)
4463 w->color = MEM_BLACK;
4464 x->parent->color = MEM_RED;
4465 mem_rotate_left (x->parent);
4466 w = x->parent->right;
4469 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
4471 w->color = MEM_RED;
4472 x = x->parent;
4474 else
4476 if (w->right->color == MEM_BLACK)
4478 w->left->color = MEM_BLACK;
4479 w->color = MEM_RED;
4480 mem_rotate_right (w);
4481 w = x->parent->right;
4483 w->color = x->parent->color;
4484 x->parent->color = MEM_BLACK;
4485 w->right->color = MEM_BLACK;
4486 mem_rotate_left (x->parent);
4487 x = mem_root;
4490 else
4492 struct mem_node *w = x->parent->left;
4494 if (w->color == MEM_RED)
4496 w->color = MEM_BLACK;
4497 x->parent->color = MEM_RED;
4498 mem_rotate_right (x->parent);
4499 w = x->parent->left;
4502 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
4504 w->color = MEM_RED;
4505 x = x->parent;
4507 else
4509 if (w->left->color == MEM_BLACK)
4511 w->right->color = MEM_BLACK;
4512 w->color = MEM_RED;
4513 mem_rotate_left (w);
4514 w = x->parent->left;
4517 w->color = x->parent->color;
4518 x->parent->color = MEM_BLACK;
4519 w->left->color = MEM_BLACK;
4520 mem_rotate_right (x->parent);
4521 x = mem_root;
4526 x->color = MEM_BLACK;
4530 /* Value is non-zero if P is a pointer to a live Lisp string on
4531 the heap. M is a pointer to the mem_block for P. */
4533 static bool
4534 live_string_p (struct mem_node *m, void *p)
4536 if (m->type == MEM_TYPE_STRING)
4538 struct string_block *b = m->start;
4539 ptrdiff_t offset = (char *) p - (char *) &b->strings[0];
4541 /* P must point to the start of a Lisp_String structure, and it
4542 must not be on the free-list. */
4543 return (offset >= 0
4544 && offset % sizeof b->strings[0] == 0
4545 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
4546 && ((struct Lisp_String *) p)->data != NULL);
4548 else
4549 return 0;
4553 /* Value is non-zero if P is a pointer to a live Lisp cons on
4554 the heap. M is a pointer to the mem_block for P. */
4556 static bool
4557 live_cons_p (struct mem_node *m, void *p)
4559 if (m->type == MEM_TYPE_CONS)
4561 struct cons_block *b = m->start;
4562 ptrdiff_t offset = (char *) p - (char *) &b->conses[0];
4564 /* P must point to the start of a Lisp_Cons, not be
4565 one of the unused cells in the current cons block,
4566 and not be on the free-list. */
4567 return (offset >= 0
4568 && offset % sizeof b->conses[0] == 0
4569 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
4570 && (b != cons_block
4571 || offset / sizeof b->conses[0] < cons_block_index)
4572 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
4574 else
4575 return 0;
4579 /* Value is non-zero if P is a pointer to a live Lisp symbol on
4580 the heap. M is a pointer to the mem_block for P. */
4582 static bool
4583 live_symbol_p (struct mem_node *m, void *p)
4585 if (m->type == MEM_TYPE_SYMBOL)
4587 struct symbol_block *b = m->start;
4588 ptrdiff_t offset = (char *) p - (char *) &b->symbols[0];
4590 /* P must point to the start of a Lisp_Symbol, not be
4591 one of the unused cells in the current symbol block,
4592 and not be on the free-list. */
4593 return (offset >= 0
4594 && offset % sizeof b->symbols[0] == 0
4595 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
4596 && (b != symbol_block
4597 || offset / sizeof b->symbols[0] < symbol_block_index)
4598 && !EQ (((struct Lisp_Symbol *)p)->function, Vdead));
4600 else
4601 return 0;
4605 /* Value is non-zero if P is a pointer to a live Lisp float on
4606 the heap. M is a pointer to the mem_block for P. */
4608 static bool
4609 live_float_p (struct mem_node *m, void *p)
4611 if (m->type == MEM_TYPE_FLOAT)
4613 struct float_block *b = m->start;
4614 ptrdiff_t offset = (char *) p - (char *) &b->floats[0];
4616 /* P must point to the start of a Lisp_Float and not be
4617 one of the unused cells in the current float block. */
4618 return (offset >= 0
4619 && offset % sizeof b->floats[0] == 0
4620 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
4621 && (b != float_block
4622 || offset / sizeof b->floats[0] < float_block_index));
4624 else
4625 return 0;
4629 /* Value is non-zero if P is a pointer to a live Lisp Misc on
4630 the heap. M is a pointer to the mem_block for P. */
4632 static bool
4633 live_misc_p (struct mem_node *m, void *p)
4635 if (m->type == MEM_TYPE_MISC)
4637 struct marker_block *b = m->start;
4638 ptrdiff_t offset = (char *) p - (char *) &b->markers[0];
4640 /* P must point to the start of a Lisp_Misc, not be
4641 one of the unused cells in the current misc block,
4642 and not be on the free-list. */
4643 return (offset >= 0
4644 && offset % sizeof b->markers[0] == 0
4645 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
4646 && (b != marker_block
4647 || offset / sizeof b->markers[0] < marker_block_index)
4648 && ((union Lisp_Misc *) p)->u_any.type != Lisp_Misc_Free);
4650 else
4651 return 0;
4655 /* Value is non-zero if P is a pointer to a live vector-like object.
4656 M is a pointer to the mem_block for P. */
4658 static bool
4659 live_vector_p (struct mem_node *m, void *p)
4661 if (m->type == MEM_TYPE_VECTOR_BLOCK)
4663 /* This memory node corresponds to a vector block. */
4664 struct vector_block *block = m->start;
4665 struct Lisp_Vector *vector = (struct Lisp_Vector *) block->data;
4667 /* P is in the block's allocation range. Scan the block
4668 up to P and see whether P points to the start of some
4669 vector which is not on a free list. FIXME: check whether
4670 some allocation patterns (probably a lot of short vectors)
4671 may cause a substantial overhead of this loop. */
4672 while (VECTOR_IN_BLOCK (vector, block)
4673 && vector <= (struct Lisp_Vector *) p)
4675 if (!PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FREE) && vector == p)
4676 return 1;
4677 else
4678 vector = ADVANCE (vector, vector_nbytes (vector));
4681 else if (m->type == MEM_TYPE_VECTORLIKE && p == large_vector_vec (m->start))
4682 /* This memory node corresponds to a large vector. */
4683 return 1;
4684 return 0;
4688 /* Value is non-zero if P is a pointer to a live buffer. M is a
4689 pointer to the mem_block for P. */
4691 static bool
4692 live_buffer_p (struct mem_node *m, void *p)
4694 /* P must point to the start of the block, and the buffer
4695 must not have been killed. */
4696 return (m->type == MEM_TYPE_BUFFER
4697 && p == m->start
4698 && !NILP (((struct buffer *) p)->name_));
4701 /* Mark OBJ if we can prove it's a Lisp_Object. */
4703 static void
4704 mark_maybe_object (Lisp_Object obj)
4706 #if USE_VALGRIND
4707 if (valgrind_p)
4708 VALGRIND_MAKE_MEM_DEFINED (&obj, sizeof (obj));
4709 #endif
4711 if (INTEGERP (obj))
4712 return;
4714 void *po = XPNTR (obj);
4715 struct mem_node *m = mem_find (po);
4717 if (m != MEM_NIL)
4719 bool mark_p = false;
4721 switch (XTYPE (obj))
4723 case Lisp_String:
4724 mark_p = (live_string_p (m, po)
4725 && !STRING_MARKED_P ((struct Lisp_String *) po));
4726 break;
4728 case Lisp_Cons:
4729 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4730 break;
4732 case Lisp_Symbol:
4733 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4734 break;
4736 case Lisp_Float:
4737 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4738 break;
4740 case Lisp_Vectorlike:
4741 /* Note: can't check BUFFERP before we know it's a
4742 buffer because checking that dereferences the pointer
4743 PO which might point anywhere. */
4744 if (live_vector_p (m, po))
4745 mark_p = !SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4746 else if (live_buffer_p (m, po))
4747 mark_p = BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4748 break;
4750 case Lisp_Misc:
4751 mark_p = (live_misc_p (m, po) && !XMISCANY (obj)->gcmarkbit);
4752 break;
4754 default:
4755 break;
4758 if (mark_p)
4759 mark_object (obj);
4763 /* Return true if P can point to Lisp data, and false otherwise.
4764 Symbols are implemented via offsets not pointers, but the offsets
4765 are also multiples of GCALIGNMENT. */
4767 static bool
4768 maybe_lisp_pointer (void *p)
4770 return (uintptr_t) p % GCALIGNMENT == 0;
4773 #ifndef HAVE_MODULES
4774 enum { HAVE_MODULES = false };
4775 #endif
4777 /* If P points to Lisp data, mark that as live if it isn't already
4778 marked. */
4780 static void
4781 mark_maybe_pointer (void *p)
4783 struct mem_node *m;
4785 #if USE_VALGRIND
4786 if (valgrind_p)
4787 VALGRIND_MAKE_MEM_DEFINED (&p, sizeof (p));
4788 #endif
4790 if (sizeof (Lisp_Object) == sizeof (void *) || !HAVE_MODULES)
4792 if (!maybe_lisp_pointer (p))
4793 return;
4795 else
4797 /* For the wide-int case, also mark emacs_value tagged pointers,
4798 which can be generated by emacs-module.c's value_to_lisp. */
4799 p = (void *) ((uintptr_t) p & ~(GCALIGNMENT - 1));
4802 m = mem_find (p);
4803 if (m != MEM_NIL)
4805 Lisp_Object obj = Qnil;
4807 switch (m->type)
4809 case MEM_TYPE_NON_LISP:
4810 case MEM_TYPE_SPARE:
4811 /* Nothing to do; not a pointer to Lisp memory. */
4812 break;
4814 case MEM_TYPE_BUFFER:
4815 if (live_buffer_p (m, p) && !VECTOR_MARKED_P ((struct buffer *)p))
4816 XSETVECTOR (obj, p);
4817 break;
4819 case MEM_TYPE_CONS:
4820 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4821 XSETCONS (obj, p);
4822 break;
4824 case MEM_TYPE_STRING:
4825 if (live_string_p (m, p)
4826 && !STRING_MARKED_P ((struct Lisp_String *) p))
4827 XSETSTRING (obj, p);
4828 break;
4830 case MEM_TYPE_MISC:
4831 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4832 XSETMISC (obj, p);
4833 break;
4835 case MEM_TYPE_SYMBOL:
4836 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4837 XSETSYMBOL (obj, p);
4838 break;
4840 case MEM_TYPE_FLOAT:
4841 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4842 XSETFLOAT (obj, p);
4843 break;
4845 case MEM_TYPE_VECTORLIKE:
4846 case MEM_TYPE_VECTOR_BLOCK:
4847 if (live_vector_p (m, p))
4849 Lisp_Object tem;
4850 XSETVECTOR (tem, p);
4851 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4852 obj = tem;
4854 break;
4856 default:
4857 emacs_abort ();
4860 if (!NILP (obj))
4861 mark_object (obj);
4866 /* Alignment of pointer values. Use alignof, as it sometimes returns
4867 a smaller alignment than GCC's __alignof__ and mark_memory might
4868 miss objects if __alignof__ were used. */
4869 #define GC_POINTER_ALIGNMENT alignof (void *)
4871 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4872 or END+OFFSET..START. */
4874 static void ATTRIBUTE_NO_SANITIZE_ADDRESS
4875 mark_memory (void *start, void *end)
4877 char *pp;
4879 /* Make START the pointer to the start of the memory region,
4880 if it isn't already. */
4881 if (end < start)
4883 void *tem = start;
4884 start = end;
4885 end = tem;
4888 eassert (((uintptr_t) start) % GC_POINTER_ALIGNMENT == 0);
4890 /* Mark Lisp data pointed to. This is necessary because, in some
4891 situations, the C compiler optimizes Lisp objects away, so that
4892 only a pointer to them remains. Example:
4894 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4897 Lisp_Object obj = build_string ("test");
4898 struct Lisp_String *s = XSTRING (obj);
4899 Fgarbage_collect ();
4900 fprintf (stderr, "test '%s'\n", s->data);
4901 return Qnil;
4904 Here, `obj' isn't really used, and the compiler optimizes it
4905 away. The only reference to the life string is through the
4906 pointer `s'. */
4908 for (pp = start; (void *) pp < end; pp += GC_POINTER_ALIGNMENT)
4910 mark_maybe_pointer (*(void **) pp);
4911 mark_maybe_object (*(Lisp_Object *) pp);
4915 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4917 static bool setjmp_tested_p;
4918 static int longjmps_done;
4920 #define SETJMP_WILL_LIKELY_WORK "\
4922 Emacs garbage collector has been changed to use conservative stack\n\
4923 marking. Emacs has determined that the method it uses to do the\n\
4924 marking will likely work on your system, but this isn't sure.\n\
4926 If you are a system-programmer, or can get the help of a local wizard\n\
4927 who is, please take a look at the function mark_stack in alloc.c, and\n\
4928 verify that the methods used are appropriate for your system.\n\
4930 Please mail the result to <emacs-devel@gnu.org>.\n\
4933 #define SETJMP_WILL_NOT_WORK "\
4935 Emacs garbage collector has been changed to use conservative stack\n\
4936 marking. Emacs has determined that the default method it uses to do the\n\
4937 marking will not work on your system. We will need a system-dependent\n\
4938 solution for your system.\n\
4940 Please take a look at the function mark_stack in alloc.c, and\n\
4941 try to find a way to make it work on your system.\n\
4943 Note that you may get false negatives, depending on the compiler.\n\
4944 In particular, you need to use -O with GCC for this test.\n\
4946 Please mail the result to <emacs-devel@gnu.org>.\n\
4950 /* Perform a quick check if it looks like setjmp saves registers in a
4951 jmp_buf. Print a message to stderr saying so. When this test
4952 succeeds, this is _not_ a proof that setjmp is sufficient for
4953 conservative stack marking. Only the sources or a disassembly
4954 can prove that. */
4956 static void
4957 test_setjmp (void)
4959 char buf[10];
4960 register int x;
4961 sys_jmp_buf jbuf;
4963 /* Arrange for X to be put in a register. */
4964 sprintf (buf, "1");
4965 x = strlen (buf);
4966 x = 2 * x - 1;
4968 sys_setjmp (jbuf);
4969 if (longjmps_done == 1)
4971 /* Came here after the longjmp at the end of the function.
4973 If x == 1, the longjmp has restored the register to its
4974 value before the setjmp, and we can hope that setjmp
4975 saves all such registers in the jmp_buf, although that
4976 isn't sure.
4978 For other values of X, either something really strange is
4979 taking place, or the setjmp just didn't save the register. */
4981 if (x == 1)
4982 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4983 else
4985 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4986 exit (1);
4990 ++longjmps_done;
4991 x = 2;
4992 if (longjmps_done == 1)
4993 sys_longjmp (jbuf, 1);
4996 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4999 /* Mark live Lisp objects on the C stack.
5001 There are several system-dependent problems to consider when
5002 porting this to new architectures:
5004 Processor Registers
5006 We have to mark Lisp objects in CPU registers that can hold local
5007 variables or are used to pass parameters.
5009 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
5010 something that either saves relevant registers on the stack, or
5011 calls mark_maybe_object passing it each register's contents.
5013 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
5014 implementation assumes that calling setjmp saves registers we need
5015 to see in a jmp_buf which itself lies on the stack. This doesn't
5016 have to be true! It must be verified for each system, possibly
5017 by taking a look at the source code of setjmp.
5019 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
5020 can use it as a machine independent method to store all registers
5021 to the stack. In this case the macros described in the previous
5022 two paragraphs are not used.
5024 Stack Layout
5026 Architectures differ in the way their processor stack is organized.
5027 For example, the stack might look like this
5029 +----------------+
5030 | Lisp_Object | size = 4
5031 +----------------+
5032 | something else | size = 2
5033 +----------------+
5034 | Lisp_Object | size = 4
5035 +----------------+
5036 | ... |
5038 In such a case, not every Lisp_Object will be aligned equally. To
5039 find all Lisp_Object on the stack it won't be sufficient to walk
5040 the stack in steps of 4 bytes. Instead, two passes will be
5041 necessary, one starting at the start of the stack, and a second
5042 pass starting at the start of the stack + 2. Likewise, if the
5043 minimal alignment of Lisp_Objects on the stack is 1, four passes
5044 would be necessary, each one starting with one byte more offset
5045 from the stack start. */
5047 static void
5048 mark_stack (void *end)
5051 /* This assumes that the stack is a contiguous region in memory. If
5052 that's not the case, something has to be done here to iterate
5053 over the stack segments. */
5054 mark_memory (stack_base, end);
5056 /* Allow for marking a secondary stack, like the register stack on the
5057 ia64. */
5058 #ifdef GC_MARK_SECONDARY_STACK
5059 GC_MARK_SECONDARY_STACK ();
5060 #endif
5063 static bool
5064 c_symbol_p (struct Lisp_Symbol *sym)
5066 char *lispsym_ptr = (char *) lispsym;
5067 char *sym_ptr = (char *) sym;
5068 ptrdiff_t lispsym_offset = sym_ptr - lispsym_ptr;
5069 return 0 <= lispsym_offset && lispsym_offset < sizeof lispsym;
5072 /* Determine whether it is safe to access memory at address P. */
5073 static int
5074 valid_pointer_p (void *p)
5076 #ifdef WINDOWSNT
5077 return w32_valid_pointer_p (p, 16);
5078 #else
5080 if (ADDRESS_SANITIZER)
5081 return p ? -1 : 0;
5083 int fd[2];
5085 /* Obviously, we cannot just access it (we would SEGV trying), so we
5086 trick the o/s to tell us whether p is a valid pointer.
5087 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
5088 not validate p in that case. */
5090 if (emacs_pipe (fd) == 0)
5092 bool valid = emacs_write (fd[1], p, 16) == 16;
5093 emacs_close (fd[1]);
5094 emacs_close (fd[0]);
5095 return valid;
5098 return -1;
5099 #endif
5102 /* Return 2 if OBJ is a killed or special buffer object, 1 if OBJ is a
5103 valid lisp object, 0 if OBJ is NOT a valid lisp object, or -1 if we
5104 cannot validate OBJ. This function can be quite slow, so its primary
5105 use is the manual debugging. The only exception is print_object, where
5106 we use it to check whether the memory referenced by the pointer of
5107 Lisp_Save_Value object contains valid objects. */
5110 valid_lisp_object_p (Lisp_Object obj)
5112 if (INTEGERP (obj))
5113 return 1;
5115 void *p = XPNTR (obj);
5116 if (PURE_P (p))
5117 return 1;
5119 if (SYMBOLP (obj) && c_symbol_p (p))
5120 return ((char *) p - (char *) lispsym) % sizeof lispsym[0] == 0;
5122 if (p == &buffer_defaults || p == &buffer_local_symbols)
5123 return 2;
5125 struct mem_node *m = mem_find (p);
5127 if (m == MEM_NIL)
5129 int valid = valid_pointer_p (p);
5130 if (valid <= 0)
5131 return valid;
5133 if (SUBRP (obj))
5134 return 1;
5136 return 0;
5139 switch (m->type)
5141 case MEM_TYPE_NON_LISP:
5142 case MEM_TYPE_SPARE:
5143 return 0;
5145 case MEM_TYPE_BUFFER:
5146 return live_buffer_p (m, p) ? 1 : 2;
5148 case MEM_TYPE_CONS:
5149 return live_cons_p (m, p);
5151 case MEM_TYPE_STRING:
5152 return live_string_p (m, p);
5154 case MEM_TYPE_MISC:
5155 return live_misc_p (m, p);
5157 case MEM_TYPE_SYMBOL:
5158 return live_symbol_p (m, p);
5160 case MEM_TYPE_FLOAT:
5161 return live_float_p (m, p);
5163 case MEM_TYPE_VECTORLIKE:
5164 case MEM_TYPE_VECTOR_BLOCK:
5165 return live_vector_p (m, p);
5167 default:
5168 break;
5171 return 0;
5174 /***********************************************************************
5175 Pure Storage Management
5176 ***********************************************************************/
5178 /* Allocate room for SIZE bytes from pure Lisp storage and return a
5179 pointer to it. TYPE is the Lisp type for which the memory is
5180 allocated. TYPE < 0 means it's not used for a Lisp object. */
5182 static void *
5183 pure_alloc (size_t size, int type)
5185 void *result;
5187 again:
5188 if (type >= 0)
5190 /* Allocate space for a Lisp object from the beginning of the free
5191 space with taking account of alignment. */
5192 result = pointer_align (purebeg + pure_bytes_used_lisp, GCALIGNMENT);
5193 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
5195 else
5197 /* Allocate space for a non-Lisp object from the end of the free
5198 space. */
5199 pure_bytes_used_non_lisp += size;
5200 result = purebeg + pure_size - pure_bytes_used_non_lisp;
5202 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
5204 if (pure_bytes_used <= pure_size)
5205 return result;
5207 /* Don't allocate a large amount here,
5208 because it might get mmap'd and then its address
5209 might not be usable. */
5210 purebeg = xmalloc (10000);
5211 pure_size = 10000;
5212 pure_bytes_used_before_overflow += pure_bytes_used - size;
5213 pure_bytes_used = 0;
5214 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
5215 goto again;
5219 /* Print a warning if PURESIZE is too small. */
5221 void
5222 check_pure_size (void)
5224 if (pure_bytes_used_before_overflow)
5225 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI"d"
5226 " bytes needed)"),
5227 pure_bytes_used + pure_bytes_used_before_overflow);
5231 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
5232 the non-Lisp data pool of the pure storage, and return its start
5233 address. Return NULL if not found. */
5235 static char *
5236 find_string_data_in_pure (const char *data, ptrdiff_t nbytes)
5238 int i;
5239 ptrdiff_t skip, bm_skip[256], last_char_skip, infinity, start, start_max;
5240 const unsigned char *p;
5241 char *non_lisp_beg;
5243 if (pure_bytes_used_non_lisp <= nbytes)
5244 return NULL;
5246 /* Set up the Boyer-Moore table. */
5247 skip = nbytes + 1;
5248 for (i = 0; i < 256; i++)
5249 bm_skip[i] = skip;
5251 p = (const unsigned char *) data;
5252 while (--skip > 0)
5253 bm_skip[*p++] = skip;
5255 last_char_skip = bm_skip['\0'];
5257 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
5258 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
5260 /* See the comments in the function `boyer_moore' (search.c) for the
5261 use of `infinity'. */
5262 infinity = pure_bytes_used_non_lisp + 1;
5263 bm_skip['\0'] = infinity;
5265 p = (const unsigned char *) non_lisp_beg + nbytes;
5266 start = 0;
5269 /* Check the last character (== '\0'). */
5272 start += bm_skip[*(p + start)];
5274 while (start <= start_max);
5276 if (start < infinity)
5277 /* Couldn't find the last character. */
5278 return NULL;
5280 /* No less than `infinity' means we could find the last
5281 character at `p[start - infinity]'. */
5282 start -= infinity;
5284 /* Check the remaining characters. */
5285 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
5286 /* Found. */
5287 return non_lisp_beg + start;
5289 start += last_char_skip;
5291 while (start <= start_max);
5293 return NULL;
5297 /* Return a string allocated in pure space. DATA is a buffer holding
5298 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
5299 means make the result string multibyte.
5301 Must get an error if pure storage is full, since if it cannot hold
5302 a large string it may be able to hold conses that point to that
5303 string; then the string is not protected from gc. */
5305 Lisp_Object
5306 make_pure_string (const char *data,
5307 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
5309 Lisp_Object string;
5310 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5311 s->data = (unsigned char *) find_string_data_in_pure (data, nbytes);
5312 if (s->data == NULL)
5314 s->data = pure_alloc (nbytes + 1, -1);
5315 memcpy (s->data, data, nbytes);
5316 s->data[nbytes] = '\0';
5318 s->size = nchars;
5319 s->size_byte = multibyte ? nbytes : -1;
5320 s->intervals = NULL;
5321 XSETSTRING (string, s);
5322 return string;
5325 /* Return a string allocated in pure space. Do not
5326 allocate the string data, just point to DATA. */
5328 Lisp_Object
5329 make_pure_c_string (const char *data, ptrdiff_t nchars)
5331 Lisp_Object string;
5332 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5333 s->size = nchars;
5334 s->size_byte = -1;
5335 s->data = (unsigned char *) data;
5336 s->intervals = NULL;
5337 XSETSTRING (string, s);
5338 return string;
5341 static Lisp_Object purecopy (Lisp_Object obj);
5343 /* Return a cons allocated from pure space. Give it pure copies
5344 of CAR as car and CDR as cdr. */
5346 Lisp_Object
5347 pure_cons (Lisp_Object car, Lisp_Object cdr)
5349 Lisp_Object new;
5350 struct Lisp_Cons *p = pure_alloc (sizeof *p, Lisp_Cons);
5351 XSETCONS (new, p);
5352 XSETCAR (new, purecopy (car));
5353 XSETCDR (new, purecopy (cdr));
5354 return new;
5358 /* Value is a float object with value NUM allocated from pure space. */
5360 static Lisp_Object
5361 make_pure_float (double num)
5363 Lisp_Object new;
5364 struct Lisp_Float *p = pure_alloc (sizeof *p, Lisp_Float);
5365 XSETFLOAT (new, p);
5366 XFLOAT_INIT (new, num);
5367 return new;
5371 /* Return a vector with room for LEN Lisp_Objects allocated from
5372 pure space. */
5374 static Lisp_Object
5375 make_pure_vector (ptrdiff_t len)
5377 Lisp_Object new;
5378 size_t size = header_size + len * word_size;
5379 struct Lisp_Vector *p = pure_alloc (size, Lisp_Vectorlike);
5380 XSETVECTOR (new, p);
5381 XVECTOR (new)->header.size = len;
5382 return new;
5385 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
5386 doc: /* Make a copy of object OBJ in pure storage.
5387 Recursively copies contents of vectors and cons cells.
5388 Does not copy symbols. Copies strings without text properties. */)
5389 (register Lisp_Object obj)
5391 if (NILP (Vpurify_flag))
5392 return obj;
5393 else if (MARKERP (obj) || OVERLAYP (obj)
5394 || HASH_TABLE_P (obj) || SYMBOLP (obj))
5395 /* Can't purify those. */
5396 return obj;
5397 else
5398 return purecopy (obj);
5401 static Lisp_Object
5402 purecopy (Lisp_Object obj)
5404 if (INTEGERP (obj)
5405 || (! SYMBOLP (obj) && PURE_P (XPNTR_OR_SYMBOL_OFFSET (obj)))
5406 || SUBRP (obj))
5407 return obj; /* Already pure. */
5409 if (STRINGP (obj) && XSTRING (obj)->intervals)
5410 message_with_string ("Dropping text-properties while making string `%s' pure",
5411 obj, true);
5413 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5415 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
5416 if (!NILP (tmp))
5417 return tmp;
5420 if (CONSP (obj))
5421 obj = pure_cons (XCAR (obj), XCDR (obj));
5422 else if (FLOATP (obj))
5423 obj = make_pure_float (XFLOAT_DATA (obj));
5424 else if (STRINGP (obj))
5425 obj = make_pure_string (SSDATA (obj), SCHARS (obj),
5426 SBYTES (obj),
5427 STRING_MULTIBYTE (obj));
5428 else if (COMPILEDP (obj) || VECTORP (obj) || HASH_TABLE_P (obj))
5430 struct Lisp_Vector *objp = XVECTOR (obj);
5431 ptrdiff_t nbytes = vector_nbytes (objp);
5432 struct Lisp_Vector *vec = pure_alloc (nbytes, Lisp_Vectorlike);
5433 register ptrdiff_t i;
5434 ptrdiff_t size = ASIZE (obj);
5435 if (size & PSEUDOVECTOR_FLAG)
5436 size &= PSEUDOVECTOR_SIZE_MASK;
5437 memcpy (vec, objp, nbytes);
5438 for (i = 0; i < size; i++)
5439 vec->contents[i] = purecopy (vec->contents[i]);
5440 XSETVECTOR (obj, vec);
5442 else if (SYMBOLP (obj))
5444 if (!XSYMBOL (obj)->pinned && !c_symbol_p (XSYMBOL (obj)))
5445 { /* We can't purify them, but they appear in many pure objects.
5446 Mark them as `pinned' so we know to mark them at every GC cycle. */
5447 XSYMBOL (obj)->pinned = true;
5448 symbol_block_pinned = symbol_block;
5450 /* Don't hash-cons it. */
5451 return obj;
5453 else
5455 AUTO_STRING (fmt, "Don't know how to purify: %S");
5456 Fsignal (Qerror, list1 (CALLN (Fformat, fmt, obj)));
5459 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5460 Fputhash (obj, obj, Vpurify_flag);
5462 return obj;
5467 /***********************************************************************
5468 Protection from GC
5469 ***********************************************************************/
5471 /* Put an entry in staticvec, pointing at the variable with address
5472 VARADDRESS. */
5474 void
5475 staticpro (Lisp_Object *varaddress)
5477 if (staticidx >= NSTATICS)
5478 fatal ("NSTATICS too small; try increasing and recompiling Emacs.");
5479 staticvec[staticidx++] = varaddress;
5483 /***********************************************************************
5484 Protection from GC
5485 ***********************************************************************/
5487 /* Temporarily prevent garbage collection. */
5489 ptrdiff_t
5490 inhibit_garbage_collection (void)
5492 ptrdiff_t count = SPECPDL_INDEX ();
5494 specbind (Qgc_cons_threshold, make_number (MOST_POSITIVE_FIXNUM));
5495 return count;
5498 /* Used to avoid possible overflows when
5499 converting from C to Lisp integers. */
5501 static Lisp_Object
5502 bounded_number (EMACS_INT number)
5504 return make_number (min (MOST_POSITIVE_FIXNUM, number));
5507 /* Calculate total bytes of live objects. */
5509 static size_t
5510 total_bytes_of_live_objects (void)
5512 size_t tot = 0;
5513 tot += total_conses * sizeof (struct Lisp_Cons);
5514 tot += total_symbols * sizeof (struct Lisp_Symbol);
5515 tot += total_markers * sizeof (union Lisp_Misc);
5516 tot += total_string_bytes;
5517 tot += total_vector_slots * word_size;
5518 tot += total_floats * sizeof (struct Lisp_Float);
5519 tot += total_intervals * sizeof (struct interval);
5520 tot += total_strings * sizeof (struct Lisp_String);
5521 return tot;
5524 #ifdef HAVE_WINDOW_SYSTEM
5526 /* Remove unmarked font-spec and font-entity objects from ENTRY, which is
5527 (DRIVER-TYPE NUM-FRAMES FONT-CACHE-DATA ...), and return changed entry. */
5529 static Lisp_Object
5530 compact_font_cache_entry (Lisp_Object entry)
5532 Lisp_Object tail, *prev = &entry;
5534 for (tail = entry; CONSP (tail); tail = XCDR (tail))
5536 bool drop = 0;
5537 Lisp_Object obj = XCAR (tail);
5539 /* Consider OBJ if it is (font-spec . [font-entity font-entity ...]). */
5540 if (CONSP (obj) && GC_FONT_SPEC_P (XCAR (obj))
5541 && !VECTOR_MARKED_P (GC_XFONT_SPEC (XCAR (obj)))
5542 /* Don't use VECTORP here, as that calls ASIZE, which could
5543 hit assertion violation during GC. */
5544 && (VECTORLIKEP (XCDR (obj))
5545 && ! (gc_asize (XCDR (obj)) & PSEUDOVECTOR_FLAG)))
5547 ptrdiff_t i, size = gc_asize (XCDR (obj));
5548 Lisp_Object obj_cdr = XCDR (obj);
5550 /* If font-spec is not marked, most likely all font-entities
5551 are not marked too. But we must be sure that nothing is
5552 marked within OBJ before we really drop it. */
5553 for (i = 0; i < size; i++)
5555 Lisp_Object objlist;
5557 if (VECTOR_MARKED_P (GC_XFONT_ENTITY (AREF (obj_cdr, i))))
5558 break;
5560 objlist = AREF (AREF (obj_cdr, i), FONT_OBJLIST_INDEX);
5561 for (; CONSP (objlist); objlist = XCDR (objlist))
5563 Lisp_Object val = XCAR (objlist);
5564 struct font *font = GC_XFONT_OBJECT (val);
5566 if (!NILP (AREF (val, FONT_TYPE_INDEX))
5567 && VECTOR_MARKED_P(font))
5568 break;
5570 if (CONSP (objlist))
5572 /* Found a marked font, bail out. */
5573 break;
5577 if (i == size)
5579 /* No marked fonts were found, so this entire font
5580 entity can be dropped. */
5581 drop = 1;
5584 if (drop)
5585 *prev = XCDR (tail);
5586 else
5587 prev = xcdr_addr (tail);
5589 return entry;
5592 /* Compact font caches on all terminals and mark
5593 everything which is still here after compaction. */
5595 static void
5596 compact_font_caches (void)
5598 struct terminal *t;
5600 for (t = terminal_list; t; t = t->next_terminal)
5602 Lisp_Object cache = TERMINAL_FONT_CACHE (t);
5603 /* Inhibit compacting the caches if the user so wishes. Some of
5604 the users don't mind a larger memory footprint, but do mind
5605 slower redisplay. */
5606 if (!inhibit_compacting_font_caches
5607 && CONSP (cache))
5609 Lisp_Object entry;
5611 for (entry = XCDR (cache); CONSP (entry); entry = XCDR (entry))
5612 XSETCAR (entry, compact_font_cache_entry (XCAR (entry)));
5614 mark_object (cache);
5618 #else /* not HAVE_WINDOW_SYSTEM */
5620 #define compact_font_caches() (void)(0)
5622 #endif /* HAVE_WINDOW_SYSTEM */
5624 /* Remove (MARKER . DATA) entries with unmarked MARKER
5625 from buffer undo LIST and return changed list. */
5627 static Lisp_Object
5628 compact_undo_list (Lisp_Object list)
5630 Lisp_Object tail, *prev = &list;
5632 for (tail = list; CONSP (tail); tail = XCDR (tail))
5634 if (CONSP (XCAR (tail))
5635 && MARKERP (XCAR (XCAR (tail)))
5636 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5637 *prev = XCDR (tail);
5638 else
5639 prev = xcdr_addr (tail);
5641 return list;
5644 static void
5645 mark_pinned_symbols (void)
5647 struct symbol_block *sblk;
5648 int lim = (symbol_block_pinned == symbol_block
5649 ? symbol_block_index : SYMBOL_BLOCK_SIZE);
5651 for (sblk = symbol_block_pinned; sblk; sblk = sblk->next)
5653 union aligned_Lisp_Symbol *sym = sblk->symbols, *end = sym + lim;
5654 for (; sym < end; ++sym)
5655 if (sym->s.pinned)
5656 mark_object (make_lisp_symbol (&sym->s));
5658 lim = SYMBOL_BLOCK_SIZE;
5662 /* Subroutine of Fgarbage_collect that does most of the work. It is a
5663 separate function so that we could limit mark_stack in searching
5664 the stack frames below this function, thus avoiding the rare cases
5665 where mark_stack finds values that look like live Lisp objects on
5666 portions of stack that couldn't possibly contain such live objects.
5667 For more details of this, see the discussion at
5668 http://lists.gnu.org/archive/html/emacs-devel/2014-05/msg00270.html. */
5669 static Lisp_Object
5670 garbage_collect_1 (void *end)
5672 struct buffer *nextb;
5673 char stack_top_variable;
5674 ptrdiff_t i;
5675 bool message_p;
5676 ptrdiff_t count = SPECPDL_INDEX ();
5677 struct timespec start;
5678 Lisp_Object retval = Qnil;
5679 size_t tot_before = 0;
5681 /* Can't GC if pure storage overflowed because we can't determine
5682 if something is a pure object or not. */
5683 if (pure_bytes_used_before_overflow)
5684 return Qnil;
5686 /* Record this function, so it appears on the profiler's backtraces. */
5687 record_in_backtrace (QAutomatic_GC, 0, 0);
5689 check_cons_list ();
5691 /* Don't keep undo information around forever.
5692 Do this early on, so it is no problem if the user quits. */
5693 FOR_EACH_BUFFER (nextb)
5694 compact_buffer (nextb);
5696 if (profiler_memory_running)
5697 tot_before = total_bytes_of_live_objects ();
5699 start = current_timespec ();
5701 /* In case user calls debug_print during GC,
5702 don't let that cause a recursive GC. */
5703 consing_since_gc = 0;
5705 /* Save what's currently displayed in the echo area. Don't do that
5706 if we are GC'ing because we've run out of memory, since
5707 push_message will cons, and we might have no memory for that. */
5708 if (NILP (Vmemory_full))
5710 message_p = push_message ();
5711 record_unwind_protect_void (pop_message_unwind);
5713 else
5714 message_p = false;
5716 /* Save a copy of the contents of the stack, for debugging. */
5717 #if MAX_SAVE_STACK > 0
5718 if (NILP (Vpurify_flag))
5720 char *stack;
5721 ptrdiff_t stack_size;
5722 if (&stack_top_variable < stack_bottom)
5724 stack = &stack_top_variable;
5725 stack_size = stack_bottom - &stack_top_variable;
5727 else
5729 stack = stack_bottom;
5730 stack_size = &stack_top_variable - stack_bottom;
5732 if (stack_size <= MAX_SAVE_STACK)
5734 if (stack_copy_size < stack_size)
5736 stack_copy = xrealloc (stack_copy, stack_size);
5737 stack_copy_size = stack_size;
5739 no_sanitize_memcpy (stack_copy, stack, stack_size);
5742 #endif /* MAX_SAVE_STACK > 0 */
5744 if (garbage_collection_messages)
5745 message1_nolog ("Garbage collecting...");
5747 block_input ();
5749 shrink_regexp_cache ();
5751 gc_in_progress = 1;
5753 /* Mark all the special slots that serve as the roots of accessibility. */
5755 mark_buffer (&buffer_defaults);
5756 mark_buffer (&buffer_local_symbols);
5758 for (i = 0; i < ARRAYELTS (lispsym); i++)
5759 mark_object (builtin_lisp_symbol (i));
5761 for (i = 0; i < staticidx; i++)
5762 mark_object (*staticvec[i]);
5764 mark_pinned_symbols ();
5765 mark_specpdl ();
5766 mark_terminals ();
5767 mark_kboards ();
5769 #ifdef USE_GTK
5770 xg_mark_data ();
5771 #endif
5773 mark_stack (end);
5776 struct handler *handler;
5777 for (handler = handlerlist; handler; handler = handler->next)
5779 mark_object (handler->tag_or_ch);
5780 mark_object (handler->val);
5783 #ifdef HAVE_WINDOW_SYSTEM
5784 mark_fringe_data ();
5785 #endif
5787 /* Everything is now marked, except for the data in font caches,
5788 undo lists, and finalizers. The first two are compacted by
5789 removing an items which aren't reachable otherwise. */
5791 compact_font_caches ();
5793 FOR_EACH_BUFFER (nextb)
5795 if (!EQ (BVAR (nextb, undo_list), Qt))
5796 bset_undo_list (nextb, compact_undo_list (BVAR (nextb, undo_list)));
5797 /* Now that we have stripped the elements that need not be
5798 in the undo_list any more, we can finally mark the list. */
5799 mark_object (BVAR (nextb, undo_list));
5802 /* Now pre-sweep finalizers. Here, we add any unmarked finalizers
5803 to doomed_finalizers so we can run their associated functions
5804 after GC. It's important to scan finalizers at this stage so
5805 that we can be sure that unmarked finalizers are really
5806 unreachable except for references from their associated functions
5807 and from other finalizers. */
5809 queue_doomed_finalizers (&doomed_finalizers, &finalizers);
5810 mark_finalizer_list (&doomed_finalizers);
5812 gc_sweep ();
5814 /* Clear the mark bits that we set in certain root slots. */
5815 VECTOR_UNMARK (&buffer_defaults);
5816 VECTOR_UNMARK (&buffer_local_symbols);
5818 check_cons_list ();
5820 gc_in_progress = 0;
5822 unblock_input ();
5824 consing_since_gc = 0;
5825 if (gc_cons_threshold < GC_DEFAULT_THRESHOLD / 10)
5826 gc_cons_threshold = GC_DEFAULT_THRESHOLD / 10;
5828 gc_relative_threshold = 0;
5829 if (FLOATP (Vgc_cons_percentage))
5830 { /* Set gc_cons_combined_threshold. */
5831 double tot = total_bytes_of_live_objects ();
5833 tot *= XFLOAT_DATA (Vgc_cons_percentage);
5834 if (0 < tot)
5836 if (tot < TYPE_MAXIMUM (EMACS_INT))
5837 gc_relative_threshold = tot;
5838 else
5839 gc_relative_threshold = TYPE_MAXIMUM (EMACS_INT);
5843 if (garbage_collection_messages && NILP (Vmemory_full))
5845 if (message_p || minibuf_level > 0)
5846 restore_message ();
5847 else
5848 message1_nolog ("Garbage collecting...done");
5851 unbind_to (count, Qnil);
5853 Lisp_Object total[] = {
5854 list4 (Qconses, make_number (sizeof (struct Lisp_Cons)),
5855 bounded_number (total_conses),
5856 bounded_number (total_free_conses)),
5857 list4 (Qsymbols, make_number (sizeof (struct Lisp_Symbol)),
5858 bounded_number (total_symbols),
5859 bounded_number (total_free_symbols)),
5860 list4 (Qmiscs, make_number (sizeof (union Lisp_Misc)),
5861 bounded_number (total_markers),
5862 bounded_number (total_free_markers)),
5863 list4 (Qstrings, make_number (sizeof (struct Lisp_String)),
5864 bounded_number (total_strings),
5865 bounded_number (total_free_strings)),
5866 list3 (Qstring_bytes, make_number (1),
5867 bounded_number (total_string_bytes)),
5868 list3 (Qvectors,
5869 make_number (header_size + sizeof (Lisp_Object)),
5870 bounded_number (total_vectors)),
5871 list4 (Qvector_slots, make_number (word_size),
5872 bounded_number (total_vector_slots),
5873 bounded_number (total_free_vector_slots)),
5874 list4 (Qfloats, make_number (sizeof (struct Lisp_Float)),
5875 bounded_number (total_floats),
5876 bounded_number (total_free_floats)),
5877 list4 (Qintervals, make_number (sizeof (struct interval)),
5878 bounded_number (total_intervals),
5879 bounded_number (total_free_intervals)),
5880 list3 (Qbuffers, make_number (sizeof (struct buffer)),
5881 bounded_number (total_buffers)),
5883 #ifdef DOUG_LEA_MALLOC
5884 list4 (Qheap, make_number (1024),
5885 bounded_number ((mallinfo ().uordblks + 1023) >> 10),
5886 bounded_number ((mallinfo ().fordblks + 1023) >> 10)),
5887 #endif
5889 retval = CALLMANY (Flist, total);
5891 /* GC is complete: now we can run our finalizer callbacks. */
5892 run_finalizers (&doomed_finalizers);
5894 if (!NILP (Vpost_gc_hook))
5896 ptrdiff_t gc_count = inhibit_garbage_collection ();
5897 safe_run_hooks (Qpost_gc_hook);
5898 unbind_to (gc_count, Qnil);
5901 /* Accumulate statistics. */
5902 if (FLOATP (Vgc_elapsed))
5904 struct timespec since_start = timespec_sub (current_timespec (), start);
5905 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed)
5906 + timespectod (since_start));
5909 gcs_done++;
5911 /* Collect profiling data. */
5912 if (profiler_memory_running)
5914 size_t swept = 0;
5915 size_t tot_after = total_bytes_of_live_objects ();
5916 if (tot_before > tot_after)
5917 swept = tot_before - tot_after;
5918 malloc_probe (swept);
5921 return retval;
5924 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
5925 doc: /* Reclaim storage for Lisp objects no longer needed.
5926 Garbage collection happens automatically if you cons more than
5927 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5928 `garbage-collect' normally returns a list with info on amount of space in use,
5929 where each entry has the form (NAME SIZE USED FREE), where:
5930 - NAME is a symbol describing the kind of objects this entry represents,
5931 - SIZE is the number of bytes used by each one,
5932 - USED is the number of those objects that were found live in the heap,
5933 - FREE is the number of those objects that are not live but that Emacs
5934 keeps around for future allocations (maybe because it does not know how
5935 to return them to the OS).
5936 However, if there was overflow in pure space, `garbage-collect'
5937 returns nil, because real GC can't be done.
5938 See Info node `(elisp)Garbage Collection'. */)
5939 (void)
5941 void *end;
5943 #ifdef HAVE___BUILTIN_UNWIND_INIT
5944 /* Force callee-saved registers and register windows onto the stack.
5945 This is the preferred method if available, obviating the need for
5946 machine dependent methods. */
5947 __builtin_unwind_init ();
5948 end = &end;
5949 #else /* not HAVE___BUILTIN_UNWIND_INIT */
5950 #ifndef GC_SAVE_REGISTERS_ON_STACK
5951 /* jmp_buf may not be aligned enough on darwin-ppc64 */
5952 union aligned_jmpbuf {
5953 Lisp_Object o;
5954 sys_jmp_buf j;
5955 } j;
5956 volatile bool stack_grows_down_p = (char *) &j > (char *) stack_base;
5957 #endif
5958 /* This trick flushes the register windows so that all the state of
5959 the process is contained in the stack. */
5960 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
5961 needed on ia64 too. See mach_dep.c, where it also says inline
5962 assembler doesn't work with relevant proprietary compilers. */
5963 #ifdef __sparc__
5964 #if defined (__sparc64__) && defined (__FreeBSD__)
5965 /* FreeBSD does not have a ta 3 handler. */
5966 asm ("flushw");
5967 #else
5968 asm ("ta 3");
5969 #endif
5970 #endif
5972 /* Save registers that we need to see on the stack. We need to see
5973 registers used to hold register variables and registers used to
5974 pass parameters. */
5975 #ifdef GC_SAVE_REGISTERS_ON_STACK
5976 GC_SAVE_REGISTERS_ON_STACK (end);
5977 #else /* not GC_SAVE_REGISTERS_ON_STACK */
5979 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
5980 setjmp will definitely work, test it
5981 and print a message with the result
5982 of the test. */
5983 if (!setjmp_tested_p)
5985 setjmp_tested_p = 1;
5986 test_setjmp ();
5988 #endif /* GC_SETJMP_WORKS */
5990 sys_setjmp (j.j);
5991 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
5992 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
5993 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
5994 return garbage_collect_1 (end);
5997 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5998 only interesting objects referenced from glyphs are strings. */
6000 static void
6001 mark_glyph_matrix (struct glyph_matrix *matrix)
6003 struct glyph_row *row = matrix->rows;
6004 struct glyph_row *end = row + matrix->nrows;
6006 for (; row < end; ++row)
6007 if (row->enabled_p)
6009 int area;
6010 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
6012 struct glyph *glyph = row->glyphs[area];
6013 struct glyph *end_glyph = glyph + row->used[area];
6015 for (; glyph < end_glyph; ++glyph)
6016 if (STRINGP (glyph->object)
6017 && !STRING_MARKED_P (XSTRING (glyph->object)))
6018 mark_object (glyph->object);
6023 /* Mark reference to a Lisp_Object.
6024 If the object referred to has not been seen yet, recursively mark
6025 all the references contained in it. */
6027 #define LAST_MARKED_SIZE 500
6028 Lisp_Object last_marked[LAST_MARKED_SIZE] EXTERNALLY_VISIBLE;
6029 static int last_marked_index;
6031 /* For debugging--call abort when we cdr down this many
6032 links of a list, in mark_object. In debugging,
6033 the call to abort will hit a breakpoint.
6034 Normally this is zero and the check never goes off. */
6035 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE;
6037 static void
6038 mark_vectorlike (struct Lisp_Vector *ptr)
6040 ptrdiff_t size = ptr->header.size;
6041 ptrdiff_t i;
6043 eassert (!VECTOR_MARKED_P (ptr));
6044 VECTOR_MARK (ptr); /* Else mark it. */
6045 if (size & PSEUDOVECTOR_FLAG)
6046 size &= PSEUDOVECTOR_SIZE_MASK;
6048 /* Note that this size is not the memory-footprint size, but only
6049 the number of Lisp_Object fields that we should trace.
6050 The distinction is used e.g. by Lisp_Process which places extra
6051 non-Lisp_Object fields at the end of the structure... */
6052 for (i = 0; i < size; i++) /* ...and then mark its elements. */
6053 mark_object (ptr->contents[i]);
6056 /* Like mark_vectorlike but optimized for char-tables (and
6057 sub-char-tables) assuming that the contents are mostly integers or
6058 symbols. */
6060 static void
6061 mark_char_table (struct Lisp_Vector *ptr, enum pvec_type pvectype)
6063 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
6064 /* Consult the Lisp_Sub_Char_Table layout before changing this. */
6065 int i, idx = (pvectype == PVEC_SUB_CHAR_TABLE ? SUB_CHAR_TABLE_OFFSET : 0);
6067 eassert (!VECTOR_MARKED_P (ptr));
6068 VECTOR_MARK (ptr);
6069 for (i = idx; i < size; i++)
6071 Lisp_Object val = ptr->contents[i];
6073 if (INTEGERP (val) || (SYMBOLP (val) && XSYMBOL (val)->gcmarkbit))
6074 continue;
6075 if (SUB_CHAR_TABLE_P (val))
6077 if (! VECTOR_MARKED_P (XVECTOR (val)))
6078 mark_char_table (XVECTOR (val), PVEC_SUB_CHAR_TABLE);
6080 else
6081 mark_object (val);
6085 NO_INLINE /* To reduce stack depth in mark_object. */
6086 static Lisp_Object
6087 mark_compiled (struct Lisp_Vector *ptr)
6089 int i, size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
6091 VECTOR_MARK (ptr);
6092 for (i = 0; i < size; i++)
6093 if (i != COMPILED_CONSTANTS)
6094 mark_object (ptr->contents[i]);
6095 return size > COMPILED_CONSTANTS ? ptr->contents[COMPILED_CONSTANTS] : Qnil;
6098 /* Mark the chain of overlays starting at PTR. */
6100 static void
6101 mark_overlay (struct Lisp_Overlay *ptr)
6103 for (; ptr && !ptr->gcmarkbit; ptr = ptr->next)
6105 ptr->gcmarkbit = 1;
6106 /* These two are always markers and can be marked fast. */
6107 XMARKER (ptr->start)->gcmarkbit = 1;
6108 XMARKER (ptr->end)->gcmarkbit = 1;
6109 mark_object (ptr->plist);
6113 /* Mark Lisp_Objects and special pointers in BUFFER. */
6115 static void
6116 mark_buffer (struct buffer *buffer)
6118 /* This is handled much like other pseudovectors... */
6119 mark_vectorlike ((struct Lisp_Vector *) buffer);
6121 /* ...but there are some buffer-specific things. */
6123 MARK_INTERVAL_TREE (buffer_intervals (buffer));
6125 /* For now, we just don't mark the undo_list. It's done later in
6126 a special way just before the sweep phase, and after stripping
6127 some of its elements that are not needed any more. */
6129 mark_overlay (buffer->overlays_before);
6130 mark_overlay (buffer->overlays_after);
6132 /* If this is an indirect buffer, mark its base buffer. */
6133 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
6134 mark_buffer (buffer->base_buffer);
6137 /* Mark Lisp faces in the face cache C. */
6139 NO_INLINE /* To reduce stack depth in mark_object. */
6140 static void
6141 mark_face_cache (struct face_cache *c)
6143 if (c)
6145 int i, j;
6146 for (i = 0; i < c->used; ++i)
6148 struct face *face = FACE_FROM_ID_OR_NULL (c->f, i);
6150 if (face)
6152 if (face->font && !VECTOR_MARKED_P (face->font))
6153 mark_vectorlike ((struct Lisp_Vector *) face->font);
6155 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
6156 mark_object (face->lface[j]);
6162 NO_INLINE /* To reduce stack depth in mark_object. */
6163 static void
6164 mark_localized_symbol (struct Lisp_Symbol *ptr)
6166 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
6167 Lisp_Object where = blv->where;
6168 /* If the value is set up for a killed buffer or deleted
6169 frame, restore its global binding. If the value is
6170 forwarded to a C variable, either it's not a Lisp_Object
6171 var, or it's staticpro'd already. */
6172 if ((BUFFERP (where) && !BUFFER_LIVE_P (XBUFFER (where)))
6173 || (FRAMEP (where) && !FRAME_LIVE_P (XFRAME (where))))
6174 swap_in_global_binding (ptr);
6175 mark_object (blv->where);
6176 mark_object (blv->valcell);
6177 mark_object (blv->defcell);
6180 NO_INLINE /* To reduce stack depth in mark_object. */
6181 static void
6182 mark_save_value (struct Lisp_Save_Value *ptr)
6184 /* If `save_type' is zero, `data[0].pointer' is the address
6185 of a memory area containing `data[1].integer' potential
6186 Lisp_Objects. */
6187 if (ptr->save_type == SAVE_TYPE_MEMORY)
6189 Lisp_Object *p = ptr->data[0].pointer;
6190 ptrdiff_t nelt;
6191 for (nelt = ptr->data[1].integer; nelt > 0; nelt--, p++)
6192 mark_maybe_object (*p);
6194 else
6196 /* Find Lisp_Objects in `data[N]' slots and mark them. */
6197 int i;
6198 for (i = 0; i < SAVE_VALUE_SLOTS; i++)
6199 if (save_type (ptr, i) == SAVE_OBJECT)
6200 mark_object (ptr->data[i].object);
6204 /* Remove killed buffers or items whose car is a killed buffer from
6205 LIST, and mark other items. Return changed LIST, which is marked. */
6207 static Lisp_Object
6208 mark_discard_killed_buffers (Lisp_Object list)
6210 Lisp_Object tail, *prev = &list;
6212 for (tail = list; CONSP (tail) && !CONS_MARKED_P (XCONS (tail));
6213 tail = XCDR (tail))
6215 Lisp_Object tem = XCAR (tail);
6216 if (CONSP (tem))
6217 tem = XCAR (tem);
6218 if (BUFFERP (tem) && !BUFFER_LIVE_P (XBUFFER (tem)))
6219 *prev = XCDR (tail);
6220 else
6222 CONS_MARK (XCONS (tail));
6223 mark_object (XCAR (tail));
6224 prev = xcdr_addr (tail);
6227 mark_object (tail);
6228 return list;
6231 /* Determine type of generic Lisp_Object and mark it accordingly.
6233 This function implements a straightforward depth-first marking
6234 algorithm and so the recursion depth may be very high (a few
6235 tens of thousands is not uncommon). To minimize stack usage,
6236 a few cold paths are moved out to NO_INLINE functions above.
6237 In general, inlining them doesn't help you to gain more speed. */
6239 void
6240 mark_object (Lisp_Object arg)
6242 register Lisp_Object obj;
6243 void *po;
6244 #ifdef GC_CHECK_MARKED_OBJECTS
6245 struct mem_node *m;
6246 #endif
6247 ptrdiff_t cdr_count = 0;
6249 obj = arg;
6250 loop:
6252 po = XPNTR (obj);
6253 if (PURE_P (po))
6254 return;
6256 last_marked[last_marked_index++] = obj;
6257 if (last_marked_index == LAST_MARKED_SIZE)
6258 last_marked_index = 0;
6260 /* Perform some sanity checks on the objects marked here. Abort if
6261 we encounter an object we know is bogus. This increases GC time
6262 by ~80%. */
6263 #ifdef GC_CHECK_MARKED_OBJECTS
6265 /* Check that the object pointed to by PO is known to be a Lisp
6266 structure allocated from the heap. */
6267 #define CHECK_ALLOCATED() \
6268 do { \
6269 m = mem_find (po); \
6270 if (m == MEM_NIL) \
6271 emacs_abort (); \
6272 } while (0)
6274 /* Check that the object pointed to by PO is live, using predicate
6275 function LIVEP. */
6276 #define CHECK_LIVE(LIVEP) \
6277 do { \
6278 if (!LIVEP (m, po)) \
6279 emacs_abort (); \
6280 } while (0)
6282 /* Check both of the above conditions, for non-symbols. */
6283 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
6284 do { \
6285 CHECK_ALLOCATED (); \
6286 CHECK_LIVE (LIVEP); \
6287 } while (0) \
6289 /* Check both of the above conditions, for symbols. */
6290 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() \
6291 do { \
6292 if (!c_symbol_p (ptr)) \
6294 CHECK_ALLOCATED (); \
6295 CHECK_LIVE (live_symbol_p); \
6297 } while (0) \
6299 #else /* not GC_CHECK_MARKED_OBJECTS */
6301 #define CHECK_LIVE(LIVEP) ((void) 0)
6302 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) ((void) 0)
6303 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() ((void) 0)
6305 #endif /* not GC_CHECK_MARKED_OBJECTS */
6307 switch (XTYPE (obj))
6309 case Lisp_String:
6311 register struct Lisp_String *ptr = XSTRING (obj);
6312 if (STRING_MARKED_P (ptr))
6313 break;
6314 CHECK_ALLOCATED_AND_LIVE (live_string_p);
6315 MARK_STRING (ptr);
6316 MARK_INTERVAL_TREE (ptr->intervals);
6317 #ifdef GC_CHECK_STRING_BYTES
6318 /* Check that the string size recorded in the string is the
6319 same as the one recorded in the sdata structure. */
6320 string_bytes (ptr);
6321 #endif /* GC_CHECK_STRING_BYTES */
6323 break;
6325 case Lisp_Vectorlike:
6327 register struct Lisp_Vector *ptr = XVECTOR (obj);
6328 register ptrdiff_t pvectype;
6330 if (VECTOR_MARKED_P (ptr))
6331 break;
6333 #ifdef GC_CHECK_MARKED_OBJECTS
6334 m = mem_find (po);
6335 if (m == MEM_NIL && !SUBRP (obj))
6336 emacs_abort ();
6337 #endif /* GC_CHECK_MARKED_OBJECTS */
6339 if (ptr->header.size & PSEUDOVECTOR_FLAG)
6340 pvectype = ((ptr->header.size & PVEC_TYPE_MASK)
6341 >> PSEUDOVECTOR_AREA_BITS);
6342 else
6343 pvectype = PVEC_NORMAL_VECTOR;
6345 if (pvectype != PVEC_SUBR && pvectype != PVEC_BUFFER)
6346 CHECK_LIVE (live_vector_p);
6348 switch (pvectype)
6350 case PVEC_BUFFER:
6351 #ifdef GC_CHECK_MARKED_OBJECTS
6353 struct buffer *b;
6354 FOR_EACH_BUFFER (b)
6355 if (b == po)
6356 break;
6357 if (b == NULL)
6358 emacs_abort ();
6360 #endif /* GC_CHECK_MARKED_OBJECTS */
6361 mark_buffer ((struct buffer *) ptr);
6362 break;
6364 case PVEC_COMPILED:
6365 /* Although we could treat this just like a vector, mark_compiled
6366 returns the COMPILED_CONSTANTS element, which is marked at the
6367 next iteration of goto-loop here. This is done to avoid a few
6368 recursive calls to mark_object. */
6369 obj = mark_compiled (ptr);
6370 if (!NILP (obj))
6371 goto loop;
6372 break;
6374 case PVEC_FRAME:
6376 struct frame *f = (struct frame *) ptr;
6378 mark_vectorlike (ptr);
6379 mark_face_cache (f->face_cache);
6380 #ifdef HAVE_WINDOW_SYSTEM
6381 if (FRAME_WINDOW_P (f) && FRAME_X_OUTPUT (f))
6383 struct font *font = FRAME_FONT (f);
6385 if (font && !VECTOR_MARKED_P (font))
6386 mark_vectorlike ((struct Lisp_Vector *) font);
6388 #endif
6390 break;
6392 case PVEC_WINDOW:
6394 struct window *w = (struct window *) ptr;
6396 mark_vectorlike (ptr);
6398 /* Mark glyph matrices, if any. Marking window
6399 matrices is sufficient because frame matrices
6400 use the same glyph memory. */
6401 if (w->current_matrix)
6403 mark_glyph_matrix (w->current_matrix);
6404 mark_glyph_matrix (w->desired_matrix);
6407 /* Filter out killed buffers from both buffer lists
6408 in attempt to help GC to reclaim killed buffers faster.
6409 We can do it elsewhere for live windows, but this is the
6410 best place to do it for dead windows. */
6411 wset_prev_buffers
6412 (w, mark_discard_killed_buffers (w->prev_buffers));
6413 wset_next_buffers
6414 (w, mark_discard_killed_buffers (w->next_buffers));
6416 break;
6418 case PVEC_HASH_TABLE:
6420 struct Lisp_Hash_Table *h = (struct Lisp_Hash_Table *) ptr;
6422 mark_vectorlike (ptr);
6423 mark_object (h->test.name);
6424 mark_object (h->test.user_hash_function);
6425 mark_object (h->test.user_cmp_function);
6426 /* If hash table is not weak, mark all keys and values.
6427 For weak tables, mark only the vector. */
6428 if (NILP (h->weak))
6429 mark_object (h->key_and_value);
6430 else
6431 VECTOR_MARK (XVECTOR (h->key_and_value));
6433 break;
6435 case PVEC_CHAR_TABLE:
6436 case PVEC_SUB_CHAR_TABLE:
6437 mark_char_table (ptr, (enum pvec_type) pvectype);
6438 break;
6440 case PVEC_BOOL_VECTOR:
6441 /* No Lisp_Objects to mark in a bool vector. */
6442 VECTOR_MARK (ptr);
6443 break;
6445 case PVEC_SUBR:
6446 break;
6448 case PVEC_FREE:
6449 emacs_abort ();
6451 default:
6452 mark_vectorlike (ptr);
6455 break;
6457 case Lisp_Symbol:
6459 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
6460 nextsym:
6461 if (ptr->gcmarkbit)
6462 break;
6463 CHECK_ALLOCATED_AND_LIVE_SYMBOL ();
6464 ptr->gcmarkbit = 1;
6465 /* Attempt to catch bogus objects. */
6466 eassert (valid_lisp_object_p (ptr->function));
6467 mark_object (ptr->function);
6468 mark_object (ptr->plist);
6469 switch (ptr->redirect)
6471 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
6472 case SYMBOL_VARALIAS:
6474 Lisp_Object tem;
6475 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
6476 mark_object (tem);
6477 break;
6479 case SYMBOL_LOCALIZED:
6480 mark_localized_symbol (ptr);
6481 break;
6482 case SYMBOL_FORWARDED:
6483 /* If the value is forwarded to a buffer or keyboard field,
6484 these are marked when we see the corresponding object.
6485 And if it's forwarded to a C variable, either it's not
6486 a Lisp_Object var, or it's staticpro'd already. */
6487 break;
6488 default: emacs_abort ();
6490 if (!PURE_P (XSTRING (ptr->name)))
6491 MARK_STRING (XSTRING (ptr->name));
6492 MARK_INTERVAL_TREE (string_intervals (ptr->name));
6493 /* Inner loop to mark next symbol in this bucket, if any. */
6494 po = ptr = ptr->next;
6495 if (ptr)
6496 goto nextsym;
6498 break;
6500 case Lisp_Misc:
6501 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
6503 if (XMISCANY (obj)->gcmarkbit)
6504 break;
6506 switch (XMISCTYPE (obj))
6508 case Lisp_Misc_Marker:
6509 /* DO NOT mark thru the marker's chain.
6510 The buffer's markers chain does not preserve markers from gc;
6511 instead, markers are removed from the chain when freed by gc. */
6512 XMISCANY (obj)->gcmarkbit = 1;
6513 break;
6515 case Lisp_Misc_Save_Value:
6516 XMISCANY (obj)->gcmarkbit = 1;
6517 mark_save_value (XSAVE_VALUE (obj));
6518 break;
6520 case Lisp_Misc_Overlay:
6521 mark_overlay (XOVERLAY (obj));
6522 break;
6524 case Lisp_Misc_Finalizer:
6525 XMISCANY (obj)->gcmarkbit = true;
6526 mark_object (XFINALIZER (obj)->function);
6527 break;
6529 #ifdef HAVE_MODULES
6530 case Lisp_Misc_User_Ptr:
6531 XMISCANY (obj)->gcmarkbit = true;
6532 break;
6533 #endif
6535 default:
6536 emacs_abort ();
6538 break;
6540 case Lisp_Cons:
6542 register struct Lisp_Cons *ptr = XCONS (obj);
6543 if (CONS_MARKED_P (ptr))
6544 break;
6545 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
6546 CONS_MARK (ptr);
6547 /* If the cdr is nil, avoid recursion for the car. */
6548 if (EQ (ptr->u.cdr, Qnil))
6550 obj = ptr->car;
6551 cdr_count = 0;
6552 goto loop;
6554 mark_object (ptr->car);
6555 obj = ptr->u.cdr;
6556 cdr_count++;
6557 if (cdr_count == mark_object_loop_halt)
6558 emacs_abort ();
6559 goto loop;
6562 case Lisp_Float:
6563 CHECK_ALLOCATED_AND_LIVE (live_float_p);
6564 FLOAT_MARK (XFLOAT (obj));
6565 break;
6567 case_Lisp_Int:
6568 break;
6570 default:
6571 emacs_abort ();
6574 #undef CHECK_LIVE
6575 #undef CHECK_ALLOCATED
6576 #undef CHECK_ALLOCATED_AND_LIVE
6578 /* Mark the Lisp pointers in the terminal objects.
6579 Called by Fgarbage_collect. */
6581 static void
6582 mark_terminals (void)
6584 struct terminal *t;
6585 for (t = terminal_list; t; t = t->next_terminal)
6587 eassert (t->name != NULL);
6588 #ifdef HAVE_WINDOW_SYSTEM
6589 /* If a terminal object is reachable from a stacpro'ed object,
6590 it might have been marked already. Make sure the image cache
6591 gets marked. */
6592 mark_image_cache (t->image_cache);
6593 #endif /* HAVE_WINDOW_SYSTEM */
6594 if (!VECTOR_MARKED_P (t))
6595 mark_vectorlike ((struct Lisp_Vector *)t);
6601 /* Value is non-zero if OBJ will survive the current GC because it's
6602 either marked or does not need to be marked to survive. */
6604 bool
6605 survives_gc_p (Lisp_Object obj)
6607 bool survives_p;
6609 switch (XTYPE (obj))
6611 case_Lisp_Int:
6612 survives_p = 1;
6613 break;
6615 case Lisp_Symbol:
6616 survives_p = XSYMBOL (obj)->gcmarkbit;
6617 break;
6619 case Lisp_Misc:
6620 survives_p = XMISCANY (obj)->gcmarkbit;
6621 break;
6623 case Lisp_String:
6624 survives_p = STRING_MARKED_P (XSTRING (obj));
6625 break;
6627 case Lisp_Vectorlike:
6628 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
6629 break;
6631 case Lisp_Cons:
6632 survives_p = CONS_MARKED_P (XCONS (obj));
6633 break;
6635 case Lisp_Float:
6636 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
6637 break;
6639 default:
6640 emacs_abort ();
6643 return survives_p || PURE_P (XPNTR (obj));
6649 NO_INLINE /* For better stack traces */
6650 static void
6651 sweep_conses (void)
6653 struct cons_block *cblk;
6654 struct cons_block **cprev = &cons_block;
6655 int lim = cons_block_index;
6656 EMACS_INT num_free = 0, num_used = 0;
6658 cons_free_list = 0;
6660 for (cblk = cons_block; cblk; cblk = *cprev)
6662 int i = 0;
6663 int this_free = 0;
6664 int ilim = (lim + BITS_PER_BITS_WORD - 1) / BITS_PER_BITS_WORD;
6666 /* Scan the mark bits an int at a time. */
6667 for (i = 0; i < ilim; i++)
6669 if (cblk->gcmarkbits[i] == BITS_WORD_MAX)
6671 /* Fast path - all cons cells for this int are marked. */
6672 cblk->gcmarkbits[i] = 0;
6673 num_used += BITS_PER_BITS_WORD;
6675 else
6677 /* Some cons cells for this int are not marked.
6678 Find which ones, and free them. */
6679 int start, pos, stop;
6681 start = i * BITS_PER_BITS_WORD;
6682 stop = lim - start;
6683 if (stop > BITS_PER_BITS_WORD)
6684 stop = BITS_PER_BITS_WORD;
6685 stop += start;
6687 for (pos = start; pos < stop; pos++)
6689 if (!CONS_MARKED_P (&cblk->conses[pos]))
6691 this_free++;
6692 cblk->conses[pos].u.chain = cons_free_list;
6693 cons_free_list = &cblk->conses[pos];
6694 cons_free_list->car = Vdead;
6696 else
6698 num_used++;
6699 CONS_UNMARK (&cblk->conses[pos]);
6705 lim = CONS_BLOCK_SIZE;
6706 /* If this block contains only free conses and we have already
6707 seen more than two blocks worth of free conses then deallocate
6708 this block. */
6709 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
6711 *cprev = cblk->next;
6712 /* Unhook from the free list. */
6713 cons_free_list = cblk->conses[0].u.chain;
6714 lisp_align_free (cblk);
6716 else
6718 num_free += this_free;
6719 cprev = &cblk->next;
6722 total_conses = num_used;
6723 total_free_conses = num_free;
6726 NO_INLINE /* For better stack traces */
6727 static void
6728 sweep_floats (void)
6730 register struct float_block *fblk;
6731 struct float_block **fprev = &float_block;
6732 register int lim = float_block_index;
6733 EMACS_INT num_free = 0, num_used = 0;
6735 float_free_list = 0;
6737 for (fblk = float_block; fblk; fblk = *fprev)
6739 register int i;
6740 int this_free = 0;
6741 for (i = 0; i < lim; i++)
6742 if (!FLOAT_MARKED_P (&fblk->floats[i]))
6744 this_free++;
6745 fblk->floats[i].u.chain = float_free_list;
6746 float_free_list = &fblk->floats[i];
6748 else
6750 num_used++;
6751 FLOAT_UNMARK (&fblk->floats[i]);
6753 lim = FLOAT_BLOCK_SIZE;
6754 /* If this block contains only free floats and we have already
6755 seen more than two blocks worth of free floats then deallocate
6756 this block. */
6757 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6759 *fprev = fblk->next;
6760 /* Unhook from the free list. */
6761 float_free_list = fblk->floats[0].u.chain;
6762 lisp_align_free (fblk);
6764 else
6766 num_free += this_free;
6767 fprev = &fblk->next;
6770 total_floats = num_used;
6771 total_free_floats = num_free;
6774 NO_INLINE /* For better stack traces */
6775 static void
6776 sweep_intervals (void)
6778 register struct interval_block *iblk;
6779 struct interval_block **iprev = &interval_block;
6780 register int lim = interval_block_index;
6781 EMACS_INT num_free = 0, num_used = 0;
6783 interval_free_list = 0;
6785 for (iblk = interval_block; iblk; iblk = *iprev)
6787 register int i;
6788 int this_free = 0;
6790 for (i = 0; i < lim; i++)
6792 if (!iblk->intervals[i].gcmarkbit)
6794 set_interval_parent (&iblk->intervals[i], interval_free_list);
6795 interval_free_list = &iblk->intervals[i];
6796 this_free++;
6798 else
6800 num_used++;
6801 iblk->intervals[i].gcmarkbit = 0;
6804 lim = INTERVAL_BLOCK_SIZE;
6805 /* If this block contains only free intervals and we have already
6806 seen more than two blocks worth of free intervals then
6807 deallocate this block. */
6808 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6810 *iprev = iblk->next;
6811 /* Unhook from the free list. */
6812 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
6813 lisp_free (iblk);
6815 else
6817 num_free += this_free;
6818 iprev = &iblk->next;
6821 total_intervals = num_used;
6822 total_free_intervals = num_free;
6825 NO_INLINE /* For better stack traces */
6826 static void
6827 sweep_symbols (void)
6829 struct symbol_block *sblk;
6830 struct symbol_block **sprev = &symbol_block;
6831 int lim = symbol_block_index;
6832 EMACS_INT num_free = 0, num_used = ARRAYELTS (lispsym);
6834 symbol_free_list = NULL;
6836 for (int i = 0; i < ARRAYELTS (lispsym); i++)
6837 lispsym[i].gcmarkbit = 0;
6839 for (sblk = symbol_block; sblk; sblk = *sprev)
6841 int this_free = 0;
6842 union aligned_Lisp_Symbol *sym = sblk->symbols;
6843 union aligned_Lisp_Symbol *end = sym + lim;
6845 for (; sym < end; ++sym)
6847 if (!sym->s.gcmarkbit)
6849 if (sym->s.redirect == SYMBOL_LOCALIZED)
6850 xfree (SYMBOL_BLV (&sym->s));
6851 sym->s.next = symbol_free_list;
6852 symbol_free_list = &sym->s;
6853 symbol_free_list->function = Vdead;
6854 ++this_free;
6856 else
6858 ++num_used;
6859 sym->s.gcmarkbit = 0;
6860 /* Attempt to catch bogus objects. */
6861 eassert (valid_lisp_object_p (sym->s.function));
6865 lim = SYMBOL_BLOCK_SIZE;
6866 /* If this block contains only free symbols and we have already
6867 seen more than two blocks worth of free symbols then deallocate
6868 this block. */
6869 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6871 *sprev = sblk->next;
6872 /* Unhook from the free list. */
6873 symbol_free_list = sblk->symbols[0].s.next;
6874 lisp_free (sblk);
6876 else
6878 num_free += this_free;
6879 sprev = &sblk->next;
6882 total_symbols = num_used;
6883 total_free_symbols = num_free;
6886 NO_INLINE /* For better stack traces. */
6887 static void
6888 sweep_misc (void)
6890 register struct marker_block *mblk;
6891 struct marker_block **mprev = &marker_block;
6892 register int lim = marker_block_index;
6893 EMACS_INT num_free = 0, num_used = 0;
6895 /* Put all unmarked misc's on free list. For a marker, first
6896 unchain it from the buffer it points into. */
6898 marker_free_list = 0;
6900 for (mblk = marker_block; mblk; mblk = *mprev)
6902 register int i;
6903 int this_free = 0;
6905 for (i = 0; i < lim; i++)
6907 if (!mblk->markers[i].m.u_any.gcmarkbit)
6909 if (mblk->markers[i].m.u_any.type == Lisp_Misc_Marker)
6910 unchain_marker (&mblk->markers[i].m.u_marker);
6911 else if (mblk->markers[i].m.u_any.type == Lisp_Misc_Finalizer)
6912 unchain_finalizer (&mblk->markers[i].m.u_finalizer);
6913 #ifdef HAVE_MODULES
6914 else if (mblk->markers[i].m.u_any.type == Lisp_Misc_User_Ptr)
6916 struct Lisp_User_Ptr *uptr = &mblk->markers[i].m.u_user_ptr;
6917 if (uptr->finalizer)
6918 uptr->finalizer (uptr->p);
6920 #endif
6921 /* Set the type of the freed object to Lisp_Misc_Free.
6922 We could leave the type alone, since nobody checks it,
6923 but this might catch bugs faster. */
6924 mblk->markers[i].m.u_marker.type = Lisp_Misc_Free;
6925 mblk->markers[i].m.u_free.chain = marker_free_list;
6926 marker_free_list = &mblk->markers[i].m;
6927 this_free++;
6929 else
6931 num_used++;
6932 mblk->markers[i].m.u_any.gcmarkbit = 0;
6935 lim = MARKER_BLOCK_SIZE;
6936 /* If this block contains only free markers and we have already
6937 seen more than two blocks worth of free markers then deallocate
6938 this block. */
6939 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6941 *mprev = mblk->next;
6942 /* Unhook from the free list. */
6943 marker_free_list = mblk->markers[0].m.u_free.chain;
6944 lisp_free (mblk);
6946 else
6948 num_free += this_free;
6949 mprev = &mblk->next;
6953 total_markers = num_used;
6954 total_free_markers = num_free;
6957 NO_INLINE /* For better stack traces */
6958 static void
6959 sweep_buffers (void)
6961 register struct buffer *buffer, **bprev = &all_buffers;
6963 total_buffers = 0;
6964 for (buffer = all_buffers; buffer; buffer = *bprev)
6965 if (!VECTOR_MARKED_P (buffer))
6967 *bprev = buffer->next;
6968 lisp_free (buffer);
6970 else
6972 VECTOR_UNMARK (buffer);
6973 /* Do not use buffer_(set|get)_intervals here. */
6974 buffer->text->intervals = balance_intervals (buffer->text->intervals);
6975 total_buffers++;
6976 bprev = &buffer->next;
6980 /* Sweep: find all structures not marked, and free them. */
6981 static void
6982 gc_sweep (void)
6984 /* Remove or mark entries in weak hash tables.
6985 This must be done before any object is unmarked. */
6986 sweep_weak_hash_tables ();
6988 sweep_strings ();
6989 check_string_bytes (!noninteractive);
6990 sweep_conses ();
6991 sweep_floats ();
6992 sweep_intervals ();
6993 sweep_symbols ();
6994 sweep_misc ();
6995 sweep_buffers ();
6996 sweep_vectors ();
6997 check_string_bytes (!noninteractive);
7000 DEFUN ("memory-info", Fmemory_info, Smemory_info, 0, 0, 0,
7001 doc: /* Return a list of (TOTAL-RAM FREE-RAM TOTAL-SWAP FREE-SWAP).
7002 All values are in Kbytes. If there is no swap space,
7003 last two values are zero. If the system is not supported
7004 or memory information can't be obtained, return nil. */)
7005 (void)
7007 #if defined HAVE_LINUX_SYSINFO
7008 struct sysinfo si;
7009 uintmax_t units;
7011 if (sysinfo (&si))
7012 return Qnil;
7013 #ifdef LINUX_SYSINFO_UNIT
7014 units = si.mem_unit;
7015 #else
7016 units = 1;
7017 #endif
7018 return list4i ((uintmax_t) si.totalram * units / 1024,
7019 (uintmax_t) si.freeram * units / 1024,
7020 (uintmax_t) si.totalswap * units / 1024,
7021 (uintmax_t) si.freeswap * units / 1024);
7022 #elif defined WINDOWSNT
7023 unsigned long long totalram, freeram, totalswap, freeswap;
7025 if (w32_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 #elif defined MSDOS
7033 unsigned long totalram, freeram, totalswap, freeswap;
7035 if (dos_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
7036 return list4i ((uintmax_t) totalram / 1024,
7037 (uintmax_t) freeram / 1024,
7038 (uintmax_t) totalswap / 1024,
7039 (uintmax_t) freeswap / 1024);
7040 else
7041 return Qnil;
7042 #else /* not HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
7043 /* FIXME: add more systems. */
7044 return Qnil;
7045 #endif /* HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
7048 /* Debugging aids. */
7050 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
7051 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
7052 This may be helpful in debugging Emacs's memory usage.
7053 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
7054 (void)
7056 Lisp_Object end;
7058 #if defined HAVE_NS || !HAVE_SBRK
7059 /* Avoid warning. sbrk has no relation to memory allocated anyway. */
7060 XSETINT (end, 0);
7061 #else
7062 XSETINT (end, (intptr_t) (char *) sbrk (0) / 1024);
7063 #endif
7065 return end;
7068 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
7069 doc: /* Return a list of counters that measure how much consing there has been.
7070 Each of these counters increments for a certain kind of object.
7071 The counters wrap around from the largest positive integer to zero.
7072 Garbage collection does not decrease them.
7073 The elements of the value are as follows:
7074 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
7075 All are in units of 1 = one object consed
7076 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
7077 objects consed.
7078 MISCS include overlays, markers, and some internal types.
7079 Frames, windows, buffers, and subprocesses count as vectors
7080 (but the contents of a buffer's text do not count here). */)
7081 (void)
7083 return listn (CONSTYPE_HEAP, 8,
7084 bounded_number (cons_cells_consed),
7085 bounded_number (floats_consed),
7086 bounded_number (vector_cells_consed),
7087 bounded_number (symbols_consed),
7088 bounded_number (string_chars_consed),
7089 bounded_number (misc_objects_consed),
7090 bounded_number (intervals_consed),
7091 bounded_number (strings_consed));
7094 static bool
7095 symbol_uses_obj (Lisp_Object symbol, Lisp_Object obj)
7097 struct Lisp_Symbol *sym = XSYMBOL (symbol);
7098 Lisp_Object val = find_symbol_value (symbol);
7099 return (EQ (val, obj)
7100 || EQ (sym->function, obj)
7101 || (!NILP (sym->function)
7102 && COMPILEDP (sym->function)
7103 && EQ (AREF (sym->function, COMPILED_BYTECODE), obj))
7104 || (!NILP (val)
7105 && COMPILEDP (val)
7106 && EQ (AREF (val, COMPILED_BYTECODE), obj)));
7109 /* Find at most FIND_MAX symbols which have OBJ as their value or
7110 function. This is used in gdbinit's `xwhichsymbols' command. */
7112 Lisp_Object
7113 which_symbols (Lisp_Object obj, EMACS_INT find_max)
7115 struct symbol_block *sblk;
7116 ptrdiff_t gc_count = inhibit_garbage_collection ();
7117 Lisp_Object found = Qnil;
7119 if (! DEADP (obj))
7121 for (int i = 0; i < ARRAYELTS (lispsym); i++)
7123 Lisp_Object sym = builtin_lisp_symbol (i);
7124 if (symbol_uses_obj (sym, obj))
7126 found = Fcons (sym, found);
7127 if (--find_max == 0)
7128 goto out;
7132 for (sblk = symbol_block; sblk; sblk = sblk->next)
7134 union aligned_Lisp_Symbol *aligned_sym = sblk->symbols;
7135 int bn;
7137 for (bn = 0; bn < SYMBOL_BLOCK_SIZE; bn++, aligned_sym++)
7139 if (sblk == symbol_block && bn >= symbol_block_index)
7140 break;
7142 Lisp_Object sym = make_lisp_symbol (&aligned_sym->s);
7143 if (symbol_uses_obj (sym, obj))
7145 found = Fcons (sym, found);
7146 if (--find_max == 0)
7147 goto out;
7153 out:
7154 unbind_to (gc_count, Qnil);
7155 return found;
7158 #ifdef SUSPICIOUS_OBJECT_CHECKING
7160 static void *
7161 find_suspicious_object_in_range (void *begin, void *end)
7163 char *begin_a = begin;
7164 char *end_a = end;
7165 int i;
7167 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
7169 char *suspicious_object = suspicious_objects[i];
7170 if (begin_a <= suspicious_object && suspicious_object < end_a)
7171 return suspicious_object;
7174 return NULL;
7177 static void
7178 note_suspicious_free (void* ptr)
7180 struct suspicious_free_record* rec;
7182 rec = &suspicious_free_history[suspicious_free_history_index++];
7183 if (suspicious_free_history_index ==
7184 ARRAYELTS (suspicious_free_history))
7186 suspicious_free_history_index = 0;
7189 memset (rec, 0, sizeof (*rec));
7190 rec->suspicious_object = ptr;
7191 backtrace (&rec->backtrace[0], ARRAYELTS (rec->backtrace));
7194 static void
7195 detect_suspicious_free (void* ptr)
7197 int i;
7199 eassert (ptr != NULL);
7201 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
7202 if (suspicious_objects[i] == ptr)
7204 note_suspicious_free (ptr);
7205 suspicious_objects[i] = NULL;
7209 #endif /* SUSPICIOUS_OBJECT_CHECKING */
7211 DEFUN ("suspicious-object", Fsuspicious_object, Ssuspicious_object, 1, 1, 0,
7212 doc: /* Return OBJ, maybe marking it for extra scrutiny.
7213 If Emacs is compiled with suspicious object checking, capture
7214 a stack trace when OBJ is freed in order to help track down
7215 garbage collection bugs. Otherwise, do nothing and return OBJ. */)
7216 (Lisp_Object obj)
7218 #ifdef SUSPICIOUS_OBJECT_CHECKING
7219 /* Right now, we care only about vectors. */
7220 if (VECTORLIKEP (obj))
7222 suspicious_objects[suspicious_object_index++] = XVECTOR (obj);
7223 if (suspicious_object_index == ARRAYELTS (suspicious_objects))
7224 suspicious_object_index = 0;
7226 #endif
7227 return obj;
7230 #ifdef ENABLE_CHECKING
7232 bool suppress_checking;
7234 void
7235 die (const char *msg, const char *file, int line)
7237 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: assertion failed: %s\r\n",
7238 file, line, msg);
7239 terminate_due_to_signal (SIGABRT, INT_MAX);
7242 #endif /* ENABLE_CHECKING */
7244 #if defined (ENABLE_CHECKING) && USE_STACK_LISP_OBJECTS
7246 /* Stress alloca with inconveniently sized requests and check
7247 whether all allocated areas may be used for Lisp_Object. */
7249 NO_INLINE static void
7250 verify_alloca (void)
7252 int i;
7253 enum { ALLOCA_CHECK_MAX = 256 };
7254 /* Start from size of the smallest Lisp object. */
7255 for (i = sizeof (struct Lisp_Cons); i <= ALLOCA_CHECK_MAX; i++)
7257 void *ptr = alloca (i);
7258 make_lisp_ptr (ptr, Lisp_Cons);
7262 #else /* not ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7264 #define verify_alloca() ((void) 0)
7266 #endif /* ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7268 /* Initialization. */
7270 void
7271 init_alloc_once (void)
7273 /* Even though Qt's contents are not set up, its address is known. */
7274 Vpurify_flag = Qt;
7276 purebeg = PUREBEG;
7277 pure_size = PURESIZE;
7279 verify_alloca ();
7280 init_finalizer_list (&finalizers);
7281 init_finalizer_list (&doomed_finalizers);
7283 mem_init ();
7284 Vdead = make_pure_string ("DEAD", 4, 4, 0);
7286 #ifdef DOUG_LEA_MALLOC
7287 mallopt (M_TRIM_THRESHOLD, 128 * 1024); /* Trim threshold. */
7288 mallopt (M_MMAP_THRESHOLD, 64 * 1024); /* Mmap threshold. */
7289 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* Max. number of mmap'ed areas. */
7290 #endif
7291 init_strings ();
7292 init_vectors ();
7294 refill_memory_reserve ();
7295 gc_cons_threshold = GC_DEFAULT_THRESHOLD;
7298 void
7299 init_alloc (void)
7301 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
7302 setjmp_tested_p = longjmps_done = 0;
7303 #endif
7304 Vgc_elapsed = make_float (0.0);
7305 gcs_done = 0;
7307 #if USE_VALGRIND
7308 valgrind_p = RUNNING_ON_VALGRIND != 0;
7309 #endif
7312 void
7313 syms_of_alloc (void)
7315 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
7316 doc: /* Number of bytes of consing between garbage collections.
7317 Garbage collection can happen automatically once this many bytes have been
7318 allocated since the last garbage collection. All data types count.
7320 Garbage collection happens automatically only when `eval' is called.
7322 By binding this temporarily to a large number, you can effectively
7323 prevent garbage collection during a part of the program.
7324 See also `gc-cons-percentage'. */);
7326 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
7327 doc: /* Portion of the heap used for allocation.
7328 Garbage collection can happen automatically once this portion of the heap
7329 has been allocated since the last garbage collection.
7330 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
7331 Vgc_cons_percentage = make_float (0.1);
7333 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
7334 doc: /* Number of bytes of shareable Lisp data allocated so far. */);
7336 DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
7337 doc: /* Number of cons cells that have been consed so far. */);
7339 DEFVAR_INT ("floats-consed", floats_consed,
7340 doc: /* Number of floats that have been consed so far. */);
7342 DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
7343 doc: /* Number of vector cells that have been consed so far. */);
7345 DEFVAR_INT ("symbols-consed", symbols_consed,
7346 doc: /* Number of symbols that have been consed so far. */);
7347 symbols_consed += ARRAYELTS (lispsym);
7349 DEFVAR_INT ("string-chars-consed", string_chars_consed,
7350 doc: /* Number of string characters that have been consed so far. */);
7352 DEFVAR_INT ("misc-objects-consed", misc_objects_consed,
7353 doc: /* Number of miscellaneous objects that have been consed so far.
7354 These include markers and overlays, plus certain objects not visible
7355 to users. */);
7357 DEFVAR_INT ("intervals-consed", intervals_consed,
7358 doc: /* Number of intervals that have been consed so far. */);
7360 DEFVAR_INT ("strings-consed", strings_consed,
7361 doc: /* Number of strings that have been consed so far. */);
7363 DEFVAR_LISP ("purify-flag", Vpurify_flag,
7364 doc: /* Non-nil means loading Lisp code in order to dump an executable.
7365 This means that certain objects should be allocated in shared (pure) space.
7366 It can also be set to a hash-table, in which case this table is used to
7367 do hash-consing of the objects allocated to pure space. */);
7369 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
7370 doc: /* Non-nil means display messages at start and end of garbage collection. */);
7371 garbage_collection_messages = 0;
7373 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
7374 doc: /* Hook run after garbage collection has finished. */);
7375 Vpost_gc_hook = Qnil;
7376 DEFSYM (Qpost_gc_hook, "post-gc-hook");
7378 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
7379 doc: /* Precomputed `signal' argument for memory-full error. */);
7380 /* We build this in advance because if we wait until we need it, we might
7381 not be able to allocate the memory to hold it. */
7382 Vmemory_signal_data
7383 = listn (CONSTYPE_PURE, 2, Qerror,
7384 build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
7386 DEFVAR_LISP ("memory-full", Vmemory_full,
7387 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
7388 Vmemory_full = Qnil;
7390 DEFSYM (Qconses, "conses");
7391 DEFSYM (Qsymbols, "symbols");
7392 DEFSYM (Qmiscs, "miscs");
7393 DEFSYM (Qstrings, "strings");
7394 DEFSYM (Qvectors, "vectors");
7395 DEFSYM (Qfloats, "floats");
7396 DEFSYM (Qintervals, "intervals");
7397 DEFSYM (Qbuffers, "buffers");
7398 DEFSYM (Qstring_bytes, "string-bytes");
7399 DEFSYM (Qvector_slots, "vector-slots");
7400 DEFSYM (Qheap, "heap");
7401 DEFSYM (QAutomatic_GC, "Automatic GC");
7403 DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
7404 DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
7406 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
7407 doc: /* Accumulated time elapsed in garbage collections.
7408 The time is in seconds as a floating point value. */);
7409 DEFVAR_INT ("gcs-done", gcs_done,
7410 doc: /* Accumulated number of garbage collections done. */);
7412 defsubr (&Scons);
7413 defsubr (&Slist);
7414 defsubr (&Svector);
7415 defsubr (&Sbool_vector);
7416 defsubr (&Smake_byte_code);
7417 defsubr (&Smake_list);
7418 defsubr (&Smake_vector);
7419 defsubr (&Smake_string);
7420 defsubr (&Smake_bool_vector);
7421 defsubr (&Smake_symbol);
7422 defsubr (&Smake_marker);
7423 defsubr (&Smake_finalizer);
7424 defsubr (&Spurecopy);
7425 defsubr (&Sgarbage_collect);
7426 defsubr (&Smemory_limit);
7427 defsubr (&Smemory_info);
7428 defsubr (&Smemory_use_counts);
7429 defsubr (&Ssuspicious_object);
7432 /* When compiled with GCC, GDB might say "No enum type named
7433 pvec_type" if we don't have at least one symbol with that type, and
7434 then xbacktrace could fail. Similarly for the other enums and
7435 their values. Some non-GCC compilers don't like these constructs. */
7436 #ifdef __GNUC__
7437 union
7439 enum CHARTAB_SIZE_BITS CHARTAB_SIZE_BITS;
7440 enum char_table_specials char_table_specials;
7441 enum char_bits char_bits;
7442 enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE;
7443 enum DEFAULT_HASH_SIZE DEFAULT_HASH_SIZE;
7444 enum Lisp_Bits Lisp_Bits;
7445 enum Lisp_Compiled Lisp_Compiled;
7446 enum maxargs maxargs;
7447 enum MAX_ALLOCA MAX_ALLOCA;
7448 enum More_Lisp_Bits More_Lisp_Bits;
7449 enum pvec_type pvec_type;
7450 } const EXTERNALLY_VISIBLE gdb_make_enums_visible = {0};
7451 #endif /* __GNUC__ */