Use flexmembers on IBM XL C for AIX
[emacs.git] / src / alloc.c
blob41b2f9e77d20ccf0465e463ef4782659cc3f5955
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2016 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
23 #include <errno.h>
24 #include <stdio.h>
25 #include <limits.h> /* For CHAR_BIT. */
26 #include <signal.h> /* For SIGABRT, SIGDANGER. */
28 #ifdef HAVE_PTHREAD
29 #include <pthread.h>
30 #endif
32 #include "lisp.h"
33 #include "dispextern.h"
34 #include "intervals.h"
35 #include "puresize.h"
36 #include "sheap.h"
37 #include "systime.h"
38 #include "character.h"
39 #include "buffer.h"
40 #include "window.h"
41 #include "keyboard.h"
42 #include "frame.h"
43 #include "blockinput.h"
44 #include "termhooks.h" /* For struct terminal. */
45 #ifdef HAVE_WINDOW_SYSTEM
46 #include TERM_HEADER
47 #endif /* HAVE_WINDOW_SYSTEM */
49 #include <flexmember.h>
50 #include <verify.h>
51 #include <execinfo.h> /* For backtrace. */
53 #ifdef HAVE_LINUX_SYSINFO
54 #include <sys/sysinfo.h>
55 #endif
57 #ifdef MSDOS
58 #include "dosfns.h" /* For dos_memory_info. */
59 #endif
61 #ifdef HAVE_MALLOC_H
62 # include <malloc.h>
63 #endif
65 #if (defined ENABLE_CHECKING \
66 && defined HAVE_VALGRIND_VALGRIND_H \
67 && !defined USE_VALGRIND)
68 # define USE_VALGRIND 1
69 #endif
71 #if USE_VALGRIND
72 #include <valgrind/valgrind.h>
73 #include <valgrind/memcheck.h>
74 static bool valgrind_p;
75 #endif
77 /* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects. */
79 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
80 memory. Can do this only if using gmalloc.c and if not checking
81 marked objects. */
83 #if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
84 || defined HYBRID_MALLOC || defined GC_CHECK_MARKED_OBJECTS)
85 #undef GC_MALLOC_CHECK
86 #endif
88 #include <unistd.h>
89 #include <fcntl.h>
91 #ifdef USE_GTK
92 # include "gtkutil.h"
93 #endif
94 #ifdef WINDOWSNT
95 #include "w32.h"
96 #include "w32heap.h" /* for sbrk */
97 #endif
99 #if defined DOUG_LEA_MALLOC || defined GNU_LINUX
100 /* The address where the heap starts. */
101 void *
102 my_heap_start (void)
104 static void *start;
105 if (! start)
106 start = sbrk (0);
107 return start;
109 #endif
111 #ifdef DOUG_LEA_MALLOC
113 /* Specify maximum number of areas to mmap. It would be nice to use a
114 value that explicitly means "no limit". */
116 #define MMAP_MAX_AREAS 100000000
118 /* A pointer to the memory allocated that copies that static data
119 inside glibc's malloc. */
120 static void *malloc_state_ptr;
122 /* Restore the dumped malloc state. Because malloc can be invoked
123 even before main (e.g. by the dynamic linker), the dumped malloc
124 state must be restored as early as possible using this special hook. */
125 static void
126 malloc_initialize_hook (void)
128 static bool malloc_using_checking;
130 if (! initialized)
132 my_heap_start ();
133 malloc_using_checking = getenv ("MALLOC_CHECK_") != NULL;
135 else
137 if (!malloc_using_checking)
139 /* Work around a bug in glibc's malloc. MALLOC_CHECK_ must be
140 ignored if the heap to be restored was constructed without
141 malloc checking. Can't use unsetenv, since that calls malloc. */
142 char **p = environ;
143 if (p)
144 for (; *p; p++)
145 if (strncmp (*p, "MALLOC_CHECK_=", 14) == 0)
148 *p = p[1];
149 while (*++p);
151 break;
155 if (malloc_set_state (malloc_state_ptr) != 0)
156 emacs_abort ();
157 # ifndef XMALLOC_OVERRUN_CHECK
158 alloc_unexec_post ();
159 # endif
163 /* Declare the malloc initialization hook, which runs before 'main' starts.
164 EXTERNALLY_VISIBLE works around Bug#22522. */
165 # ifndef __MALLOC_HOOK_VOLATILE
166 # define __MALLOC_HOOK_VOLATILE
167 # endif
168 voidfuncptr __MALLOC_HOOK_VOLATILE __malloc_initialize_hook EXTERNALLY_VISIBLE
169 = malloc_initialize_hook;
171 #endif
173 /* Allocator-related actions to do just before and after unexec. */
175 void
176 alloc_unexec_pre (void)
178 #ifdef DOUG_LEA_MALLOC
179 malloc_state_ptr = malloc_get_state ();
180 if (!malloc_state_ptr)
181 fatal ("malloc_get_state: %s", strerror (errno));
182 #endif
183 #ifdef HYBRID_MALLOC
184 bss_sbrk_did_unexec = true;
185 #endif
188 void
189 alloc_unexec_post (void)
191 #ifdef DOUG_LEA_MALLOC
192 free (malloc_state_ptr);
193 #endif
194 #ifdef HYBRID_MALLOC
195 bss_sbrk_did_unexec = false;
196 #endif
199 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
200 to a struct Lisp_String. */
202 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
203 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
204 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
206 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
207 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
208 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
210 /* Default value of gc_cons_threshold (see below). */
212 #define GC_DEFAULT_THRESHOLD (100000 * word_size)
214 /* Global variables. */
215 struct emacs_globals globals;
217 /* Number of bytes of consing done since the last gc. */
219 EMACS_INT consing_since_gc;
221 /* Similar minimum, computed from Vgc_cons_percentage. */
223 EMACS_INT gc_relative_threshold;
225 /* Minimum number of bytes of consing since GC before next GC,
226 when memory is full. */
228 EMACS_INT memory_full_cons_threshold;
230 /* True during GC. */
232 bool gc_in_progress;
234 /* Number of live and free conses etc. */
236 static EMACS_INT total_conses, total_markers, total_symbols, total_buffers;
237 static EMACS_INT total_free_conses, total_free_markers, total_free_symbols;
238 static EMACS_INT total_free_floats, total_floats;
240 /* Points to memory space allocated as "spare", to be freed if we run
241 out of memory. We keep one large block, four cons-blocks, and
242 two string blocks. */
244 static char *spare_memory[7];
246 /* Amount of spare memory to keep in large reserve block, or to see
247 whether this much is available when malloc fails on a larger request. */
249 #define SPARE_MEMORY (1 << 14)
251 /* Initialize it to a nonzero value to force it into data space
252 (rather than bss space). That way unexec will remap it into text
253 space (pure), on some systems. We have not implemented the
254 remapping on more recent systems because this is less important
255 nowadays than in the days of small memories and timesharing. */
257 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
258 #define PUREBEG (char *) pure
260 /* Pointer to the pure area, and its size. */
262 static char *purebeg;
263 static ptrdiff_t pure_size;
265 /* Number of bytes of pure storage used before pure storage overflowed.
266 If this is non-zero, this implies that an overflow occurred. */
268 static ptrdiff_t pure_bytes_used_before_overflow;
270 /* Index in pure at which next pure Lisp object will be allocated.. */
272 static ptrdiff_t pure_bytes_used_lisp;
274 /* Number of bytes allocated for non-Lisp objects in pure storage. */
276 static ptrdiff_t pure_bytes_used_non_lisp;
278 /* If nonzero, this is a warning delivered by malloc and not yet
279 displayed. */
281 const char *pending_malloc_warning;
283 #if 0 /* Normally, pointer sanity only on request... */
284 #ifdef ENABLE_CHECKING
285 #define SUSPICIOUS_OBJECT_CHECKING 1
286 #endif
287 #endif
289 /* ... but unconditionally use SUSPICIOUS_OBJECT_CHECKING while the GC
290 bug is unresolved. */
291 #define SUSPICIOUS_OBJECT_CHECKING 1
293 #ifdef SUSPICIOUS_OBJECT_CHECKING
294 struct suspicious_free_record
296 void *suspicious_object;
297 void *backtrace[128];
299 static void *suspicious_objects[32];
300 static int suspicious_object_index;
301 struct suspicious_free_record suspicious_free_history[64] EXTERNALLY_VISIBLE;
302 static int suspicious_free_history_index;
303 /* Find the first currently-monitored suspicious pointer in range
304 [begin,end) or NULL if no such pointer exists. */
305 static void *find_suspicious_object_in_range (void *begin, void *end);
306 static void detect_suspicious_free (void *ptr);
307 #else
308 # define find_suspicious_object_in_range(begin, end) NULL
309 # define detect_suspicious_free(ptr) (void)
310 #endif
312 /* Maximum amount of C stack to save when a GC happens. */
314 #ifndef MAX_SAVE_STACK
315 #define MAX_SAVE_STACK 16000
316 #endif
318 /* Buffer in which we save a copy of the C stack at each GC. */
320 #if MAX_SAVE_STACK > 0
321 static char *stack_copy;
322 static ptrdiff_t stack_copy_size;
324 /* Copy to DEST a block of memory from SRC of size SIZE bytes,
325 avoiding any address sanitization. */
327 static void * ATTRIBUTE_NO_SANITIZE_ADDRESS
328 no_sanitize_memcpy (void *dest, void const *src, size_t size)
330 if (! ADDRESS_SANITIZER)
331 return memcpy (dest, src, size);
332 else
334 size_t i;
335 char *d = dest;
336 char const *s = src;
337 for (i = 0; i < size; i++)
338 d[i] = s[i];
339 return dest;
343 #endif /* MAX_SAVE_STACK > 0 */
345 static void mark_terminals (void);
346 static void gc_sweep (void);
347 static Lisp_Object make_pure_vector (ptrdiff_t);
348 static void mark_buffer (struct buffer *);
350 #if !defined REL_ALLOC || defined SYSTEM_MALLOC || defined HYBRID_MALLOC
351 static void refill_memory_reserve (void);
352 #endif
353 static void compact_small_strings (void);
354 static void free_large_strings (void);
355 extern Lisp_Object which_symbols (Lisp_Object, EMACS_INT) EXTERNALLY_VISIBLE;
357 /* When scanning the C stack for live Lisp objects, Emacs keeps track of
358 what memory allocated via lisp_malloc and lisp_align_malloc is intended
359 for what purpose. This enumeration specifies the type of memory. */
361 enum mem_type
363 MEM_TYPE_NON_LISP,
364 MEM_TYPE_BUFFER,
365 MEM_TYPE_CONS,
366 MEM_TYPE_STRING,
367 MEM_TYPE_MISC,
368 MEM_TYPE_SYMBOL,
369 MEM_TYPE_FLOAT,
370 /* Since all non-bool pseudovectors are small enough to be
371 allocated from vector blocks, this memory type denotes
372 large regular vectors and large bool pseudovectors. */
373 MEM_TYPE_VECTORLIKE,
374 /* Special type to denote vector blocks. */
375 MEM_TYPE_VECTOR_BLOCK,
376 /* Special type to denote reserved memory. */
377 MEM_TYPE_SPARE
380 /* A unique object in pure space used to make some Lisp objects
381 on free lists recognizable in O(1). */
383 static Lisp_Object Vdead;
384 #define DEADP(x) EQ (x, Vdead)
386 #ifdef GC_MALLOC_CHECK
388 enum mem_type allocated_mem_type;
390 #endif /* GC_MALLOC_CHECK */
392 /* A node in the red-black tree describing allocated memory containing
393 Lisp data. Each such block is recorded with its start and end
394 address when it is allocated, and removed from the tree when it
395 is freed.
397 A red-black tree is a balanced binary tree with the following
398 properties:
400 1. Every node is either red or black.
401 2. Every leaf is black.
402 3. If a node is red, then both of its children are black.
403 4. Every simple path from a node to a descendant leaf contains
404 the same number of black nodes.
405 5. The root is always black.
407 When nodes are inserted into the tree, or deleted from the tree,
408 the tree is "fixed" so that these properties are always true.
410 A red-black tree with N internal nodes has height at most 2
411 log(N+1). Searches, insertions and deletions are done in O(log N).
412 Please see a text book about data structures for a detailed
413 description of red-black trees. Any book worth its salt should
414 describe them. */
416 struct mem_node
418 /* Children of this node. These pointers are never NULL. When there
419 is no child, the value is MEM_NIL, which points to a dummy node. */
420 struct mem_node *left, *right;
422 /* The parent of this node. In the root node, this is NULL. */
423 struct mem_node *parent;
425 /* Start and end of allocated region. */
426 void *start, *end;
428 /* Node color. */
429 enum {MEM_BLACK, MEM_RED} color;
431 /* Memory type. */
432 enum mem_type type;
435 /* Base address of stack. Set in main. */
437 Lisp_Object *stack_base;
439 /* Root of the tree describing allocated Lisp memory. */
441 static struct mem_node *mem_root;
443 /* Lowest and highest known address in the heap. */
445 static void *min_heap_address, *max_heap_address;
447 /* Sentinel node of the tree. */
449 static struct mem_node mem_z;
450 #define MEM_NIL &mem_z
452 static struct mem_node *mem_insert (void *, void *, enum mem_type);
453 static void mem_insert_fixup (struct mem_node *);
454 static void mem_rotate_left (struct mem_node *);
455 static void mem_rotate_right (struct mem_node *);
456 static void mem_delete (struct mem_node *);
457 static void mem_delete_fixup (struct mem_node *);
458 static struct mem_node *mem_find (void *);
460 #ifndef DEADP
461 # define DEADP(x) 0
462 #endif
464 /* Addresses of staticpro'd variables. Initialize it to a nonzero
465 value; otherwise some compilers put it into BSS. */
467 enum { NSTATICS = 2048 };
468 static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
470 /* Index of next unused slot in staticvec. */
472 static int staticidx;
474 static void *pure_alloc (size_t, int);
476 /* True if N is a power of 2. N should be positive. */
478 #define POWER_OF_2(n) (((n) & ((n) - 1)) == 0)
480 /* Return X rounded to the next multiple of Y. Y should be positive,
481 and Y - 1 + X should not overflow. Arguments should not have side
482 effects, as they are evaluated more than once. Tune for Y being a
483 power of 2. */
485 #define ROUNDUP(x, y) (POWER_OF_2 (y) \
486 ? ((y) - 1 + (x)) & ~ ((y) - 1) \
487 : ((y) - 1 + (x)) - ((y) - 1 + (x)) % (y))
489 /* Return PTR rounded up to the next multiple of ALIGNMENT. */
491 static void *
492 pointer_align (void *ptr, int alignment)
494 return (void *) ROUNDUP ((uintptr_t) ptr, alignment);
497 /* Extract the pointer hidden within A, if A is not a symbol.
498 If A is a symbol, extract the hidden pointer's offset from lispsym,
499 converted to void *. */
501 #define macro_XPNTR_OR_SYMBOL_OFFSET(a) \
502 ((void *) (intptr_t) (USE_LSB_TAG ? XLI (a) - XTYPE (a) : XLI (a) & VALMASK))
504 /* Extract the pointer hidden within A. */
506 #define macro_XPNTR(a) \
507 ((void *) ((intptr_t) XPNTR_OR_SYMBOL_OFFSET (a) \
508 + (SYMBOLP (a) ? (char *) lispsym : NULL)))
510 /* For pointer access, define XPNTR and XPNTR_OR_SYMBOL_OFFSET as
511 functions, as functions are cleaner and can be used in debuggers.
512 Also, define them as macros if being compiled with GCC without
513 optimization, for performance in that case. The macro_* names are
514 private to this section of code. */
516 static ATTRIBUTE_UNUSED void *
517 XPNTR_OR_SYMBOL_OFFSET (Lisp_Object a)
519 return macro_XPNTR_OR_SYMBOL_OFFSET (a);
521 static ATTRIBUTE_UNUSED void *
522 XPNTR (Lisp_Object a)
524 return macro_XPNTR (a);
527 #if DEFINE_KEY_OPS_AS_MACROS
528 # define XPNTR_OR_SYMBOL_OFFSET(a) macro_XPNTR_OR_SYMBOL_OFFSET (a)
529 # define XPNTR(a) macro_XPNTR (a)
530 #endif
532 static void
533 XFLOAT_INIT (Lisp_Object f, double n)
535 XFLOAT (f)->u.data = n;
538 #ifdef DOUG_LEA_MALLOC
539 static bool
540 pointers_fit_in_lispobj_p (void)
542 return (UINTPTR_MAX <= VAL_MAX) || USE_LSB_TAG;
545 static bool
546 mmap_lisp_allowed_p (void)
548 /* If we can't store all memory addresses in our lisp objects, it's
549 risky to let the heap use mmap and give us addresses from all
550 over our address space. We also can't use mmap for lisp objects
551 if we might dump: unexec doesn't preserve the contents of mmapped
552 regions. */
553 return pointers_fit_in_lispobj_p () && !might_dump;
555 #endif
557 /* Head of a circularly-linked list of extant finalizers. */
558 static struct Lisp_Finalizer finalizers;
560 /* Head of a circularly-linked list of finalizers that must be invoked
561 because we deemed them unreachable. This list must be global, and
562 not a local inside garbage_collect_1, in case we GC again while
563 running finalizers. */
564 static struct Lisp_Finalizer doomed_finalizers;
567 /************************************************************************
568 Malloc
569 ************************************************************************/
571 #if defined SIGDANGER || (!defined SYSTEM_MALLOC && !defined HYBRID_MALLOC)
573 /* Function malloc calls this if it finds we are near exhausting storage. */
575 void
576 malloc_warning (const char *str)
578 pending_malloc_warning = str;
581 #endif
583 /* Display an already-pending malloc warning. */
585 void
586 display_malloc_warning (void)
588 call3 (intern ("display-warning"),
589 intern ("alloc"),
590 build_string (pending_malloc_warning),
591 intern ("emergency"));
592 pending_malloc_warning = 0;
595 /* Called if we can't allocate relocatable space for a buffer. */
597 void
598 buffer_memory_full (ptrdiff_t nbytes)
600 /* If buffers use the relocating allocator, no need to free
601 spare_memory, because we may have plenty of malloc space left
602 that we could get, and if we don't, the malloc that fails will
603 itself cause spare_memory to be freed. If buffers don't use the
604 relocating allocator, treat this like any other failing
605 malloc. */
607 #ifndef REL_ALLOC
608 memory_full (nbytes);
609 #else
610 /* This used to call error, but if we've run out of memory, we could
611 get infinite recursion trying to build the string. */
612 xsignal (Qnil, Vmemory_signal_data);
613 #endif
616 /* A common multiple of the positive integers A and B. Ideally this
617 would be the least common multiple, but there's no way to do that
618 as a constant expression in C, so do the best that we can easily do. */
619 #define COMMON_MULTIPLE(a, b) \
620 ((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
622 #ifndef XMALLOC_OVERRUN_CHECK
623 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
624 #else
626 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
627 around each block.
629 The header consists of XMALLOC_OVERRUN_CHECK_SIZE fixed bytes
630 followed by XMALLOC_OVERRUN_SIZE_SIZE bytes containing the original
631 block size in little-endian order. The trailer consists of
632 XMALLOC_OVERRUN_CHECK_SIZE fixed bytes.
634 The header is used to detect whether this block has been allocated
635 through these functions, as some low-level libc functions may
636 bypass the malloc hooks. */
638 #define XMALLOC_OVERRUN_CHECK_SIZE 16
639 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
640 (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)
642 #define XMALLOC_BASE_ALIGNMENT alignof (max_align_t)
644 #define XMALLOC_HEADER_ALIGNMENT \
645 COMMON_MULTIPLE (GCALIGNMENT, XMALLOC_BASE_ALIGNMENT)
647 /* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
648 hold a size_t value and (2) the header size is a multiple of the
649 alignment that Emacs needs for C types and for USE_LSB_TAG. */
650 #define XMALLOC_OVERRUN_SIZE_SIZE \
651 (((XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t) \
652 + XMALLOC_HEADER_ALIGNMENT - 1) \
653 / XMALLOC_HEADER_ALIGNMENT * XMALLOC_HEADER_ALIGNMENT) \
654 - XMALLOC_OVERRUN_CHECK_SIZE)
656 static char const xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE] =
657 { '\x9a', '\x9b', '\xae', '\xaf',
658 '\xbf', '\xbe', '\xce', '\xcf',
659 '\xea', '\xeb', '\xec', '\xed',
660 '\xdf', '\xde', '\x9c', '\x9d' };
662 static char const xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
663 { '\xaa', '\xab', '\xac', '\xad',
664 '\xba', '\xbb', '\xbc', '\xbd',
665 '\xca', '\xcb', '\xcc', '\xcd',
666 '\xda', '\xdb', '\xdc', '\xdd' };
668 /* Insert and extract the block size in the header. */
670 static void
671 xmalloc_put_size (unsigned char *ptr, size_t size)
673 int i;
674 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
676 *--ptr = size & ((1 << CHAR_BIT) - 1);
677 size >>= CHAR_BIT;
681 static size_t
682 xmalloc_get_size (unsigned char *ptr)
684 size_t size = 0;
685 int i;
686 ptr -= XMALLOC_OVERRUN_SIZE_SIZE;
687 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
689 size <<= CHAR_BIT;
690 size += *ptr++;
692 return size;
696 /* Like malloc, but wraps allocated block with header and trailer. */
698 static void *
699 overrun_check_malloc (size_t size)
701 register unsigned char *val;
702 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
703 emacs_abort ();
705 val = malloc (size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
706 if (val)
708 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
709 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
710 xmalloc_put_size (val, size);
711 memcpy (val + size, xmalloc_overrun_check_trailer,
712 XMALLOC_OVERRUN_CHECK_SIZE);
714 return val;
718 /* Like realloc, but checks old block for overrun, and wraps new block
719 with header and trailer. */
721 static void *
722 overrun_check_realloc (void *block, size_t size)
724 register unsigned char *val = (unsigned char *) block;
725 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
726 emacs_abort ();
728 if (val
729 && memcmp (xmalloc_overrun_check_header,
730 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
731 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
733 size_t osize = xmalloc_get_size (val);
734 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
735 XMALLOC_OVERRUN_CHECK_SIZE))
736 emacs_abort ();
737 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
738 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
739 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
742 val = realloc (val, size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
744 if (val)
746 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
747 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
748 xmalloc_put_size (val, size);
749 memcpy (val + size, xmalloc_overrun_check_trailer,
750 XMALLOC_OVERRUN_CHECK_SIZE);
752 return val;
755 /* Like free, but checks block for overrun. */
757 static void
758 overrun_check_free (void *block)
760 unsigned char *val = (unsigned char *) block;
762 if (val
763 && memcmp (xmalloc_overrun_check_header,
764 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
765 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
767 size_t osize = xmalloc_get_size (val);
768 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
769 XMALLOC_OVERRUN_CHECK_SIZE))
770 emacs_abort ();
771 #ifdef XMALLOC_CLEAR_FREE_MEMORY
772 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
773 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_OVERHEAD);
774 #else
775 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
776 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
777 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
778 #endif
781 free (val);
784 #undef malloc
785 #undef realloc
786 #undef free
787 #define malloc overrun_check_malloc
788 #define realloc overrun_check_realloc
789 #define free overrun_check_free
790 #endif
792 /* If compiled with XMALLOC_BLOCK_INPUT_CHECK, define a symbol
793 BLOCK_INPUT_IN_MEMORY_ALLOCATORS that is visible to the debugger.
794 If that variable is set, block input while in one of Emacs's memory
795 allocation functions. There should be no need for this debugging
796 option, since signal handlers do not allocate memory, but Emacs
797 formerly allocated memory in signal handlers and this compile-time
798 option remains as a way to help debug the issue should it rear its
799 ugly head again. */
800 #ifdef XMALLOC_BLOCK_INPUT_CHECK
801 bool block_input_in_memory_allocators EXTERNALLY_VISIBLE;
802 static void
803 malloc_block_input (void)
805 if (block_input_in_memory_allocators)
806 block_input ();
808 static void
809 malloc_unblock_input (void)
811 if (block_input_in_memory_allocators)
812 unblock_input ();
814 # define MALLOC_BLOCK_INPUT malloc_block_input ()
815 # define MALLOC_UNBLOCK_INPUT malloc_unblock_input ()
816 #else
817 # define MALLOC_BLOCK_INPUT ((void) 0)
818 # define MALLOC_UNBLOCK_INPUT ((void) 0)
819 #endif
821 #define MALLOC_PROBE(size) \
822 do { \
823 if (profiler_memory_running) \
824 malloc_probe (size); \
825 } while (0)
827 static void *lmalloc (size_t) ATTRIBUTE_MALLOC_SIZE ((1));
828 static void *lrealloc (void *, size_t);
830 /* Like malloc but check for no memory and block interrupt input. */
832 void *
833 xmalloc (size_t size)
835 void *val;
837 MALLOC_BLOCK_INPUT;
838 val = lmalloc (size);
839 MALLOC_UNBLOCK_INPUT;
841 if (!val && size)
842 memory_full (size);
843 MALLOC_PROBE (size);
844 return val;
847 /* Like the above, but zeroes out the memory just allocated. */
849 void *
850 xzalloc (size_t size)
852 void *val;
854 MALLOC_BLOCK_INPUT;
855 val = lmalloc (size);
856 MALLOC_UNBLOCK_INPUT;
858 if (!val && size)
859 memory_full (size);
860 memset (val, 0, size);
861 MALLOC_PROBE (size);
862 return val;
865 /* Like realloc but check for no memory and block interrupt input.. */
867 void *
868 xrealloc (void *block, size_t size)
870 void *val;
872 MALLOC_BLOCK_INPUT;
873 /* We must call malloc explicitly when BLOCK is 0, since some
874 reallocs don't do this. */
875 if (! block)
876 val = lmalloc (size);
877 else
878 val = lrealloc (block, size);
879 MALLOC_UNBLOCK_INPUT;
881 if (!val && size)
882 memory_full (size);
883 MALLOC_PROBE (size);
884 return val;
888 /* Like free but block interrupt input. */
890 void
891 xfree (void *block)
893 if (!block)
894 return;
895 MALLOC_BLOCK_INPUT;
896 free (block);
897 MALLOC_UNBLOCK_INPUT;
898 /* We don't call refill_memory_reserve here
899 because in practice the call in r_alloc_free seems to suffice. */
903 /* Other parts of Emacs pass large int values to allocator functions
904 expecting ptrdiff_t. This is portable in practice, but check it to
905 be safe. */
906 verify (INT_MAX <= PTRDIFF_MAX);
909 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
910 Signal an error on memory exhaustion, and block interrupt input. */
912 void *
913 xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
915 eassert (0 <= nitems && 0 < item_size);
916 ptrdiff_t nbytes;
917 if (INT_MULTIPLY_WRAPV (nitems, item_size, &nbytes) || SIZE_MAX < nbytes)
918 memory_full (SIZE_MAX);
919 return xmalloc (nbytes);
923 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
924 Signal an error on memory exhaustion, and block interrupt input. */
926 void *
927 xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
929 eassert (0 <= nitems && 0 < item_size);
930 ptrdiff_t nbytes;
931 if (INT_MULTIPLY_WRAPV (nitems, item_size, &nbytes) || SIZE_MAX < nbytes)
932 memory_full (SIZE_MAX);
933 return xrealloc (pa, nbytes);
937 /* Grow PA, which points to an array of *NITEMS items, and return the
938 location of the reallocated array, updating *NITEMS to reflect its
939 new size. The new array will contain at least NITEMS_INCR_MIN more
940 items, but will not contain more than NITEMS_MAX items total.
941 ITEM_SIZE is the size of each item, in bytes.
943 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
944 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
945 infinity.
947 If PA is null, then allocate a new array instead of reallocating
948 the old one.
950 Block interrupt input as needed. If memory exhaustion occurs, set
951 *NITEMS to zero if PA is null, and signal an error (i.e., do not
952 return).
954 Thus, to grow an array A without saving its old contents, do
955 { xfree (A); A = NULL; A = xpalloc (NULL, &AITEMS, ...); }.
956 The A = NULL avoids a dangling pointer if xpalloc exhausts memory
957 and signals an error, and later this code is reexecuted and
958 attempts to free A. */
960 void *
961 xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
962 ptrdiff_t nitems_max, ptrdiff_t item_size)
964 ptrdiff_t n0 = *nitems;
965 eassume (0 < item_size && 0 < nitems_incr_min && 0 <= n0 && -1 <= nitems_max);
967 /* The approximate size to use for initial small allocation
968 requests. This is the largest "small" request for the GNU C
969 library malloc. */
970 enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
972 /* If the array is tiny, grow it to about (but no greater than)
973 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%.
974 Adjust the growth according to three constraints: NITEMS_INCR_MIN,
975 NITEMS_MAX, and what the C language can represent safely. */
977 ptrdiff_t n, nbytes;
978 if (INT_ADD_WRAPV (n0, n0 >> 1, &n))
979 n = PTRDIFF_MAX;
980 if (0 <= nitems_max && nitems_max < n)
981 n = nitems_max;
983 ptrdiff_t adjusted_nbytes
984 = ((INT_MULTIPLY_WRAPV (n, item_size, &nbytes) || SIZE_MAX < nbytes)
985 ? min (PTRDIFF_MAX, SIZE_MAX)
986 : nbytes < DEFAULT_MXFAST ? DEFAULT_MXFAST : 0);
987 if (adjusted_nbytes)
989 n = adjusted_nbytes / item_size;
990 nbytes = adjusted_nbytes - adjusted_nbytes % item_size;
993 if (! pa)
994 *nitems = 0;
995 if (n - n0 < nitems_incr_min
996 && (INT_ADD_WRAPV (n0, nitems_incr_min, &n)
997 || (0 <= nitems_max && nitems_max < n)
998 || INT_MULTIPLY_WRAPV (n, item_size, &nbytes)))
999 memory_full (SIZE_MAX);
1000 pa = xrealloc (pa, nbytes);
1001 *nitems = n;
1002 return pa;
1006 /* Like strdup, but uses xmalloc. */
1008 char *
1009 xstrdup (const char *s)
1011 ptrdiff_t size;
1012 eassert (s);
1013 size = strlen (s) + 1;
1014 return memcpy (xmalloc (size), s, size);
1017 /* Like above, but duplicates Lisp string to C string. */
1019 char *
1020 xlispstrdup (Lisp_Object string)
1022 ptrdiff_t size = SBYTES (string) + 1;
1023 return memcpy (xmalloc (size), SSDATA (string), size);
1026 /* Assign to *PTR a copy of STRING, freeing any storage *PTR formerly
1027 pointed to. If STRING is null, assign it without copying anything.
1028 Allocate before freeing, to avoid a dangling pointer if allocation
1029 fails. */
1031 void
1032 dupstring (char **ptr, char const *string)
1034 char *old = *ptr;
1035 *ptr = string ? xstrdup (string) : 0;
1036 xfree (old);
1040 /* Like putenv, but (1) use the equivalent of xmalloc and (2) the
1041 argument is a const pointer. */
1043 void
1044 xputenv (char const *string)
1046 if (putenv ((char *) string) != 0)
1047 memory_full (0);
1050 /* Return a newly allocated memory block of SIZE bytes, remembering
1051 to free it when unwinding. */
1052 void *
1053 record_xmalloc (size_t size)
1055 void *p = xmalloc (size);
1056 record_unwind_protect_ptr (xfree, p);
1057 return p;
1061 /* Like malloc but used for allocating Lisp data. NBYTES is the
1062 number of bytes to allocate, TYPE describes the intended use of the
1063 allocated memory block (for strings, for conses, ...). */
1065 #if ! USE_LSB_TAG
1066 void *lisp_malloc_loser EXTERNALLY_VISIBLE;
1067 #endif
1069 static void *
1070 lisp_malloc (size_t nbytes, enum mem_type type)
1072 register void *val;
1074 MALLOC_BLOCK_INPUT;
1076 #ifdef GC_MALLOC_CHECK
1077 allocated_mem_type = type;
1078 #endif
1080 val = lmalloc (nbytes);
1082 #if ! USE_LSB_TAG
1083 /* If the memory just allocated cannot be addressed thru a Lisp
1084 object's pointer, and it needs to be,
1085 that's equivalent to running out of memory. */
1086 if (val && type != MEM_TYPE_NON_LISP)
1088 Lisp_Object tem;
1089 XSETCONS (tem, (char *) val + nbytes - 1);
1090 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
1092 lisp_malloc_loser = val;
1093 free (val);
1094 val = 0;
1097 #endif
1099 #ifndef GC_MALLOC_CHECK
1100 if (val && type != MEM_TYPE_NON_LISP)
1101 mem_insert (val, (char *) val + nbytes, type);
1102 #endif
1104 MALLOC_UNBLOCK_INPUT;
1105 if (!val && nbytes)
1106 memory_full (nbytes);
1107 MALLOC_PROBE (nbytes);
1108 return val;
1111 /* Free BLOCK. This must be called to free memory allocated with a
1112 call to lisp_malloc. */
1114 static void
1115 lisp_free (void *block)
1117 MALLOC_BLOCK_INPUT;
1118 free (block);
1119 #ifndef GC_MALLOC_CHECK
1120 mem_delete (mem_find (block));
1121 #endif
1122 MALLOC_UNBLOCK_INPUT;
1125 /***** Allocation of aligned blocks of memory to store Lisp data. *****/
1127 /* The entry point is lisp_align_malloc which returns blocks of at most
1128 BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
1130 /* Byte alignment of storage blocks. */
1131 #define BLOCK_ALIGN (1 << 10)
1132 verify (POWER_OF_2 (BLOCK_ALIGN));
1134 /* Use aligned_alloc if it or a simple substitute is available.
1135 Address sanitization breaks aligned allocation, as of gcc 4.8.2 and
1136 clang 3.3 anyway. Aligned allocation is incompatible with
1137 unexmacosx.c, so don't use it on Darwin. */
1139 #if ! ADDRESS_SANITIZER && !defined DARWIN_OS
1140 # if (defined HAVE_ALIGNED_ALLOC \
1141 || (defined HYBRID_MALLOC \
1142 ? defined HAVE_POSIX_MEMALIGN \
1143 : !defined SYSTEM_MALLOC && !defined DOUG_LEA_MALLOC))
1144 # define USE_ALIGNED_ALLOC 1
1145 # elif !defined HYBRID_MALLOC && defined HAVE_POSIX_MEMALIGN
1146 # define USE_ALIGNED_ALLOC 1
1147 # define aligned_alloc my_aligned_alloc /* Avoid collision with lisp.h. */
1148 static void *
1149 aligned_alloc (size_t alignment, size_t size)
1151 /* POSIX says the alignment must be a power-of-2 multiple of sizeof (void *).
1152 Verify this for all arguments this function is given. */
1153 verify (BLOCK_ALIGN % sizeof (void *) == 0
1154 && POWER_OF_2 (BLOCK_ALIGN / sizeof (void *)));
1155 verify (GCALIGNMENT % sizeof (void *) == 0
1156 && POWER_OF_2 (GCALIGNMENT / sizeof (void *)));
1157 eassert (alignment == BLOCK_ALIGN || alignment == GCALIGNMENT);
1159 void *p;
1160 return posix_memalign (&p, alignment, size) == 0 ? p : 0;
1162 # endif
1163 #endif
1165 /* Padding to leave at the end of a malloc'd block. This is to give
1166 malloc a chance to minimize the amount of memory wasted to alignment.
1167 It should be tuned to the particular malloc library used.
1168 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
1169 aligned_alloc on the other hand would ideally prefer a value of 4
1170 because otherwise, there's 1020 bytes wasted between each ablocks.
1171 In Emacs, testing shows that those 1020 can most of the time be
1172 efficiently used by malloc to place other objects, so a value of 0 can
1173 still preferable unless you have a lot of aligned blocks and virtually
1174 nothing else. */
1175 #define BLOCK_PADDING 0
1176 #define BLOCK_BYTES \
1177 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
1179 /* Internal data structures and constants. */
1181 #define ABLOCKS_SIZE 16
1183 /* An aligned block of memory. */
1184 struct ablock
1186 union
1188 char payload[BLOCK_BYTES];
1189 struct ablock *next_free;
1190 } x;
1192 /* ABASE is the aligned base of the ablocks. It is overloaded to
1193 hold a virtual "busy" field that counts twice the number of used
1194 ablock values in the parent ablocks, plus one if the real base of
1195 the parent ablocks is ABASE (if the "busy" field is even, the
1196 word before the first ablock holds a pointer to the real base).
1197 The first ablock has a "busy" ABASE, and the others have an
1198 ordinary pointer ABASE. To tell the difference, the code assumes
1199 that pointers, when cast to uintptr_t, are at least 2 *
1200 ABLOCKS_SIZE + 1. */
1201 struct ablocks *abase;
1203 /* The padding of all but the last ablock is unused. The padding of
1204 the last ablock in an ablocks is not allocated. */
1205 #if BLOCK_PADDING
1206 char padding[BLOCK_PADDING];
1207 #endif
1210 /* A bunch of consecutive aligned blocks. */
1211 struct ablocks
1213 struct ablock blocks[ABLOCKS_SIZE];
1216 /* Size of the block requested from malloc or aligned_alloc. */
1217 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
1219 #define ABLOCK_ABASE(block) \
1220 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
1221 ? (struct ablocks *) (block) \
1222 : (block)->abase)
1224 /* Virtual `busy' field. */
1225 #define ABLOCKS_BUSY(a_base) ((a_base)->blocks[0].abase)
1227 /* Pointer to the (not necessarily aligned) malloc block. */
1228 #ifdef USE_ALIGNED_ALLOC
1229 #define ABLOCKS_BASE(abase) (abase)
1230 #else
1231 #define ABLOCKS_BASE(abase) \
1232 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void **) (abase))[-1])
1233 #endif
1235 /* The list of free ablock. */
1236 static struct ablock *free_ablock;
1238 /* Allocate an aligned block of nbytes.
1239 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
1240 smaller or equal to BLOCK_BYTES. */
1241 static void *
1242 lisp_align_malloc (size_t nbytes, enum mem_type type)
1244 void *base, *val;
1245 struct ablocks *abase;
1247 eassert (nbytes <= BLOCK_BYTES);
1249 MALLOC_BLOCK_INPUT;
1251 #ifdef GC_MALLOC_CHECK
1252 allocated_mem_type = type;
1253 #endif
1255 if (!free_ablock)
1257 int i;
1258 bool aligned;
1260 #ifdef DOUG_LEA_MALLOC
1261 if (!mmap_lisp_allowed_p ())
1262 mallopt (M_MMAP_MAX, 0);
1263 #endif
1265 #ifdef USE_ALIGNED_ALLOC
1266 verify (ABLOCKS_BYTES % BLOCK_ALIGN == 0);
1267 abase = base = aligned_alloc (BLOCK_ALIGN, ABLOCKS_BYTES);
1268 #else
1269 base = malloc (ABLOCKS_BYTES);
1270 abase = pointer_align (base, BLOCK_ALIGN);
1271 #endif
1273 if (base == 0)
1275 MALLOC_UNBLOCK_INPUT;
1276 memory_full (ABLOCKS_BYTES);
1279 aligned = (base == abase);
1280 if (!aligned)
1281 ((void **) abase)[-1] = base;
1283 #ifdef DOUG_LEA_MALLOC
1284 if (!mmap_lisp_allowed_p ())
1285 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1286 #endif
1288 #if ! USE_LSB_TAG
1289 /* If the memory just allocated cannot be addressed thru a Lisp
1290 object's pointer, and it needs to be, that's equivalent to
1291 running out of memory. */
1292 if (type != MEM_TYPE_NON_LISP)
1294 Lisp_Object tem;
1295 char *end = (char *) base + ABLOCKS_BYTES - 1;
1296 XSETCONS (tem, end);
1297 if ((char *) XCONS (tem) != end)
1299 lisp_malloc_loser = base;
1300 free (base);
1301 MALLOC_UNBLOCK_INPUT;
1302 memory_full (SIZE_MAX);
1305 #endif
1307 /* Initialize the blocks and put them on the free list.
1308 If `base' was not properly aligned, we can't use the last block. */
1309 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1311 abase->blocks[i].abase = abase;
1312 abase->blocks[i].x.next_free = free_ablock;
1313 free_ablock = &abase->blocks[i];
1315 intptr_t ialigned = aligned;
1316 ABLOCKS_BUSY (abase) = (struct ablocks *) ialigned;
1318 eassert ((uintptr_t) abase % BLOCK_ALIGN == 0);
1319 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1320 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1321 eassert (ABLOCKS_BASE (abase) == base);
1322 eassert ((intptr_t) ABLOCKS_BUSY (abase) == aligned);
1325 abase = ABLOCK_ABASE (free_ablock);
1326 ABLOCKS_BUSY (abase)
1327 = (struct ablocks *) (2 + (intptr_t) ABLOCKS_BUSY (abase));
1328 val = free_ablock;
1329 free_ablock = free_ablock->x.next_free;
1331 #ifndef GC_MALLOC_CHECK
1332 if (type != MEM_TYPE_NON_LISP)
1333 mem_insert (val, (char *) val + nbytes, type);
1334 #endif
1336 MALLOC_UNBLOCK_INPUT;
1338 MALLOC_PROBE (nbytes);
1340 eassert (0 == ((uintptr_t) val) % BLOCK_ALIGN);
1341 return val;
1344 static void
1345 lisp_align_free (void *block)
1347 struct ablock *ablock = block;
1348 struct ablocks *abase = ABLOCK_ABASE (ablock);
1350 MALLOC_BLOCK_INPUT;
1351 #ifndef GC_MALLOC_CHECK
1352 mem_delete (mem_find (block));
1353 #endif
1354 /* Put on free list. */
1355 ablock->x.next_free = free_ablock;
1356 free_ablock = ablock;
1357 /* Update busy count. */
1358 intptr_t busy = (intptr_t) ABLOCKS_BUSY (abase) - 2;
1359 eassume (0 <= busy && busy <= 2 * ABLOCKS_SIZE - 1);
1360 ABLOCKS_BUSY (abase) = (struct ablocks *) busy;
1362 if (busy < 2)
1363 { /* All the blocks are free. */
1364 int i = 0;
1365 bool aligned = busy;
1366 struct ablock **tem = &free_ablock;
1367 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1369 while (*tem)
1371 if (*tem >= (struct ablock *) abase && *tem < atop)
1373 i++;
1374 *tem = (*tem)->x.next_free;
1376 else
1377 tem = &(*tem)->x.next_free;
1379 eassert ((aligned & 1) == aligned);
1380 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1381 #ifdef USE_POSIX_MEMALIGN
1382 eassert ((uintptr_t) ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1383 #endif
1384 free (ABLOCKS_BASE (abase));
1386 MALLOC_UNBLOCK_INPUT;
1389 #if !defined __GNUC__ && !defined __alignof__
1390 # define __alignof__(type) alignof (type)
1391 #endif
1393 /* True if malloc (N) is known to return a multiple of GCALIGNMENT
1394 whenever N is also a multiple. In practice this is true if
1395 __alignof__ (max_align_t) is a multiple as well, assuming
1396 GCALIGNMENT is 8; other values of GCALIGNMENT have not been looked
1397 into. Use __alignof__ if available, as otherwise
1398 MALLOC_IS_GC_ALIGNED would be false on GCC x86 even though the
1399 alignment is OK there.
1401 This is a macro, not an enum constant, for portability to HP-UX
1402 10.20 cc and AIX 3.2.5 xlc. */
1403 #define MALLOC_IS_GC_ALIGNED \
1404 (GCALIGNMENT == 8 && __alignof__ (max_align_t) % GCALIGNMENT == 0)
1406 /* True if a malloc-returned pointer P is suitably aligned for SIZE,
1407 where Lisp alignment may be needed if SIZE is Lisp-aligned. */
1409 static bool
1410 laligned (void *p, size_t size)
1412 return (MALLOC_IS_GC_ALIGNED || (intptr_t) p % GCALIGNMENT == 0
1413 || size % GCALIGNMENT != 0);
1416 /* Like malloc and realloc except that if SIZE is Lisp-aligned, make
1417 sure the result is too, if necessary by reallocating (typically
1418 with larger and larger sizes) until the allocator returns a
1419 Lisp-aligned pointer. Code that needs to allocate C heap memory
1420 for a Lisp object should use one of these functions to obtain a
1421 pointer P; that way, if T is an enum Lisp_Type value and L ==
1422 make_lisp_ptr (P, T), then XPNTR (L) == P and XTYPE (L) == T.
1424 On typical modern platforms these functions' loops do not iterate.
1425 On now-rare (and perhaps nonexistent) platforms, the loops in
1426 theory could repeat forever. If an infinite loop is possible on a
1427 platform, a build would surely loop and the builder can then send
1428 us a bug report. Adding a counter to try to detect any such loop
1429 would complicate the code (and possibly introduce bugs, in code
1430 that's never really exercised) for little benefit. */
1432 static void *
1433 lmalloc (size_t size)
1435 #if USE_ALIGNED_ALLOC
1436 if (! MALLOC_IS_GC_ALIGNED && size % GCALIGNMENT == 0)
1437 return aligned_alloc (GCALIGNMENT, size);
1438 #endif
1440 while (true)
1442 void *p = malloc (size);
1443 if (laligned (p, size))
1444 return p;
1445 free (p);
1446 size_t bigger = size + GCALIGNMENT;
1447 if (size < bigger)
1448 size = bigger;
1452 static void *
1453 lrealloc (void *p, size_t size)
1455 while (true)
1457 p = realloc (p, size);
1458 if (laligned (p, size))
1459 return p;
1460 size_t bigger = size + GCALIGNMENT;
1461 if (size < bigger)
1462 size = bigger;
1467 /***********************************************************************
1468 Interval Allocation
1469 ***********************************************************************/
1471 /* Number of intervals allocated in an interval_block structure.
1472 The 1020 is 1024 minus malloc overhead. */
1474 #define INTERVAL_BLOCK_SIZE \
1475 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1477 /* Intervals are allocated in chunks in the form of an interval_block
1478 structure. */
1480 struct interval_block
1482 /* Place `intervals' first, to preserve alignment. */
1483 struct interval intervals[INTERVAL_BLOCK_SIZE];
1484 struct interval_block *next;
1487 /* Current interval block. Its `next' pointer points to older
1488 blocks. */
1490 static struct interval_block *interval_block;
1492 /* Index in interval_block above of the next unused interval
1493 structure. */
1495 static int interval_block_index = INTERVAL_BLOCK_SIZE;
1497 /* Number of free and live intervals. */
1499 static EMACS_INT total_free_intervals, total_intervals;
1501 /* List of free intervals. */
1503 static INTERVAL interval_free_list;
1505 /* Return a new interval. */
1507 INTERVAL
1508 make_interval (void)
1510 INTERVAL val;
1512 MALLOC_BLOCK_INPUT;
1514 if (interval_free_list)
1516 val = interval_free_list;
1517 interval_free_list = INTERVAL_PARENT (interval_free_list);
1519 else
1521 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1523 struct interval_block *newi
1524 = lisp_malloc (sizeof *newi, MEM_TYPE_NON_LISP);
1526 newi->next = interval_block;
1527 interval_block = newi;
1528 interval_block_index = 0;
1529 total_free_intervals += INTERVAL_BLOCK_SIZE;
1531 val = &interval_block->intervals[interval_block_index++];
1534 MALLOC_UNBLOCK_INPUT;
1536 consing_since_gc += sizeof (struct interval);
1537 intervals_consed++;
1538 total_free_intervals--;
1539 RESET_INTERVAL (val);
1540 val->gcmarkbit = 0;
1541 return val;
1545 /* Mark Lisp objects in interval I. */
1547 static void
1548 mark_interval (register INTERVAL i, Lisp_Object dummy)
1550 /* Intervals should never be shared. So, if extra internal checking is
1551 enabled, GC aborts if it seems to have visited an interval twice. */
1552 eassert (!i->gcmarkbit);
1553 i->gcmarkbit = 1;
1554 mark_object (i->plist);
1557 /* Mark the interval tree rooted in I. */
1559 #define MARK_INTERVAL_TREE(i) \
1560 do { \
1561 if (i && !i->gcmarkbit) \
1562 traverse_intervals_noorder (i, mark_interval, Qnil); \
1563 } while (0)
1565 /***********************************************************************
1566 String Allocation
1567 ***********************************************************************/
1569 /* Lisp_Strings are allocated in string_block structures. When a new
1570 string_block is allocated, all the Lisp_Strings it contains are
1571 added to a free-list string_free_list. When a new Lisp_String is
1572 needed, it is taken from that list. During the sweep phase of GC,
1573 string_blocks that are entirely free are freed, except two which
1574 we keep.
1576 String data is allocated from sblock structures. Strings larger
1577 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1578 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1580 Sblocks consist internally of sdata structures, one for each
1581 Lisp_String. The sdata structure points to the Lisp_String it
1582 belongs to. The Lisp_String points back to the `u.data' member of
1583 its sdata structure.
1585 When a Lisp_String is freed during GC, it is put back on
1586 string_free_list, and its `data' member and its sdata's `string'
1587 pointer is set to null. The size of the string is recorded in the
1588 `n.nbytes' member of the sdata. So, sdata structures that are no
1589 longer used, can be easily recognized, and it's easy to compact the
1590 sblocks of small strings which we do in compact_small_strings. */
1592 /* Size in bytes of an sblock structure used for small strings. This
1593 is 8192 minus malloc overhead. */
1595 #define SBLOCK_SIZE 8188
1597 /* Strings larger than this are considered large strings. String data
1598 for large strings is allocated from individual sblocks. */
1600 #define LARGE_STRING_BYTES 1024
1602 /* The SDATA typedef is a struct or union describing string memory
1603 sub-allocated from an sblock. This is where the contents of Lisp
1604 strings are stored. */
1606 struct sdata
1608 /* Back-pointer to the string this sdata belongs to. If null, this
1609 structure is free, and NBYTES (in this structure or in the union below)
1610 contains the string's byte size (the same value that STRING_BYTES
1611 would return if STRING were non-null). If non-null, STRING_BYTES
1612 (STRING) is the size of the data, and DATA contains the string's
1613 contents. */
1614 struct Lisp_String *string;
1616 #ifdef GC_CHECK_STRING_BYTES
1617 ptrdiff_t nbytes;
1618 #endif
1620 unsigned char data[FLEXIBLE_ARRAY_MEMBER];
1623 #ifdef GC_CHECK_STRING_BYTES
1625 typedef struct sdata sdata;
1626 #define SDATA_NBYTES(S) (S)->nbytes
1627 #define SDATA_DATA(S) (S)->data
1629 #else
1631 typedef union
1633 struct Lisp_String *string;
1635 /* When STRING is nonnull, this union is actually of type 'struct sdata',
1636 which has a flexible array member. However, if implemented by
1637 giving this union a member of type 'struct sdata', the union
1638 could not be the last (flexible) member of 'struct sblock',
1639 because C99 prohibits a flexible array member from having a type
1640 that is itself a flexible array. So, comment this member out here,
1641 but remember that the option's there when using this union. */
1642 #if 0
1643 struct sdata u;
1644 #endif
1646 /* When STRING is null. */
1647 struct
1649 struct Lisp_String *string;
1650 ptrdiff_t nbytes;
1651 } n;
1652 } sdata;
1654 #define SDATA_NBYTES(S) (S)->n.nbytes
1655 #define SDATA_DATA(S) ((struct sdata *) (S))->data
1657 #endif /* not GC_CHECK_STRING_BYTES */
1659 enum { SDATA_DATA_OFFSET = offsetof (struct sdata, data) };
1661 /* Structure describing a block of memory which is sub-allocated to
1662 obtain string data memory for strings. Blocks for small strings
1663 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1664 as large as needed. */
1666 struct sblock
1668 /* Next in list. */
1669 struct sblock *next;
1671 /* Pointer to the next free sdata block. This points past the end
1672 of the sblock if there isn't any space left in this block. */
1673 sdata *next_free;
1675 /* String data. */
1676 sdata data[FLEXIBLE_ARRAY_MEMBER];
1679 /* Number of Lisp strings in a string_block structure. The 1020 is
1680 1024 minus malloc overhead. */
1682 #define STRING_BLOCK_SIZE \
1683 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1685 /* Structure describing a block from which Lisp_String structures
1686 are allocated. */
1688 struct string_block
1690 /* Place `strings' first, to preserve alignment. */
1691 struct Lisp_String strings[STRING_BLOCK_SIZE];
1692 struct string_block *next;
1695 /* Head and tail of the list of sblock structures holding Lisp string
1696 data. We always allocate from current_sblock. The NEXT pointers
1697 in the sblock structures go from oldest_sblock to current_sblock. */
1699 static struct sblock *oldest_sblock, *current_sblock;
1701 /* List of sblocks for large strings. */
1703 static struct sblock *large_sblocks;
1705 /* List of string_block structures. */
1707 static struct string_block *string_blocks;
1709 /* Free-list of Lisp_Strings. */
1711 static struct Lisp_String *string_free_list;
1713 /* Number of live and free Lisp_Strings. */
1715 static EMACS_INT total_strings, total_free_strings;
1717 /* Number of bytes used by live strings. */
1719 static EMACS_INT total_string_bytes;
1721 /* Given a pointer to a Lisp_String S which is on the free-list
1722 string_free_list, return a pointer to its successor in the
1723 free-list. */
1725 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1727 /* Return a pointer to the sdata structure belonging to Lisp string S.
1728 S must be live, i.e. S->data must not be null. S->data is actually
1729 a pointer to the `u.data' member of its sdata structure; the
1730 structure starts at a constant offset in front of that. */
1732 #define SDATA_OF_STRING(S) ((sdata *) ((S)->data - SDATA_DATA_OFFSET))
1735 #ifdef GC_CHECK_STRING_OVERRUN
1737 /* We check for overrun in string data blocks by appending a small
1738 "cookie" after each allocated string data block, and check for the
1739 presence of this cookie during GC. */
1741 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1742 static char const string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1743 { '\xde', '\xad', '\xbe', '\xef' };
1745 #else
1746 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1747 #endif
1749 /* Value is the size of an sdata structure large enough to hold NBYTES
1750 bytes of string data. The value returned includes a terminating
1751 NUL byte, the size of the sdata structure, and padding. */
1753 #ifdef GC_CHECK_STRING_BYTES
1755 #define SDATA_SIZE(NBYTES) FLEXSIZEOF (struct sdata, data, NBYTES)
1757 #else /* not GC_CHECK_STRING_BYTES */
1759 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1760 less than the size of that member. The 'max' is not needed when
1761 SDATA_DATA_OFFSET is a multiple of FLEXALIGNOF (struct sdata),
1762 because then the alignment code reserves enough space. */
1764 #define SDATA_SIZE(NBYTES) \
1765 ((SDATA_DATA_OFFSET \
1766 + (SDATA_DATA_OFFSET % FLEXALIGNOF (struct sdata) == 0 \
1767 ? NBYTES \
1768 : max (NBYTES, FLEXALIGNOF (struct sdata) - 1)) \
1769 + 1 \
1770 + FLEXALIGNOF (struct sdata) - 1) \
1771 & ~(FLEXALIGNOF (struct sdata) - 1))
1773 #endif /* not GC_CHECK_STRING_BYTES */
1775 /* Extra bytes to allocate for each string. */
1777 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1779 /* Exact bound on the number of bytes in a string, not counting the
1780 terminating null. A string cannot contain more bytes than
1781 STRING_BYTES_BOUND, nor can it be so long that the size_t
1782 arithmetic in allocate_string_data would overflow while it is
1783 calculating a value to be passed to malloc. */
1784 static ptrdiff_t const STRING_BYTES_MAX =
1785 min (STRING_BYTES_BOUND,
1786 ((SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD
1787 - GC_STRING_EXTRA
1788 - offsetof (struct sblock, data)
1789 - SDATA_DATA_OFFSET)
1790 & ~(sizeof (EMACS_INT) - 1)));
1792 /* Initialize string allocation. Called from init_alloc_once. */
1794 static void
1795 init_strings (void)
1797 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1798 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1802 #ifdef GC_CHECK_STRING_BYTES
1804 static int check_string_bytes_count;
1806 /* Like STRING_BYTES, but with debugging check. Can be
1807 called during GC, so pay attention to the mark bit. */
1809 ptrdiff_t
1810 string_bytes (struct Lisp_String *s)
1812 ptrdiff_t nbytes =
1813 (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1815 if (!PURE_P (s) && s->data && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1816 emacs_abort ();
1817 return nbytes;
1820 /* Check validity of Lisp strings' string_bytes member in B. */
1822 static void
1823 check_sblock (struct sblock *b)
1825 sdata *from, *end, *from_end;
1827 end = b->next_free;
1829 for (from = b->data; from < end; from = from_end)
1831 /* Compute the next FROM here because copying below may
1832 overwrite data we need to compute it. */
1833 ptrdiff_t nbytes;
1835 /* Check that the string size recorded in the string is the
1836 same as the one recorded in the sdata structure. */
1837 nbytes = SDATA_SIZE (from->string ? string_bytes (from->string)
1838 : SDATA_NBYTES (from));
1839 from_end = (sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1844 /* Check validity of Lisp strings' string_bytes member. ALL_P
1845 means check all strings, otherwise check only most
1846 recently allocated strings. Used for hunting a bug. */
1848 static void
1849 check_string_bytes (bool all_p)
1851 if (all_p)
1853 struct sblock *b;
1855 for (b = large_sblocks; b; b = b->next)
1857 struct Lisp_String *s = b->data[0].string;
1858 if (s)
1859 string_bytes (s);
1862 for (b = oldest_sblock; b; b = b->next)
1863 check_sblock (b);
1865 else if (current_sblock)
1866 check_sblock (current_sblock);
1869 #else /* not GC_CHECK_STRING_BYTES */
1871 #define check_string_bytes(all) ((void) 0)
1873 #endif /* GC_CHECK_STRING_BYTES */
1875 #ifdef GC_CHECK_STRING_FREE_LIST
1877 /* Walk through the string free list looking for bogus next pointers.
1878 This may catch buffer overrun from a previous string. */
1880 static void
1881 check_string_free_list (void)
1883 struct Lisp_String *s;
1885 /* Pop a Lisp_String off the free-list. */
1886 s = string_free_list;
1887 while (s != NULL)
1889 if ((uintptr_t) s < 1024)
1890 emacs_abort ();
1891 s = NEXT_FREE_LISP_STRING (s);
1894 #else
1895 #define check_string_free_list()
1896 #endif
1898 /* Return a new Lisp_String. */
1900 static struct Lisp_String *
1901 allocate_string (void)
1903 struct Lisp_String *s;
1905 MALLOC_BLOCK_INPUT;
1907 /* If the free-list is empty, allocate a new string_block, and
1908 add all the Lisp_Strings in it to the free-list. */
1909 if (string_free_list == NULL)
1911 struct string_block *b = lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1912 int i;
1914 b->next = string_blocks;
1915 string_blocks = b;
1917 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1919 s = b->strings + i;
1920 /* Every string on a free list should have NULL data pointer. */
1921 s->data = NULL;
1922 NEXT_FREE_LISP_STRING (s) = string_free_list;
1923 string_free_list = s;
1926 total_free_strings += STRING_BLOCK_SIZE;
1929 check_string_free_list ();
1931 /* Pop a Lisp_String off the free-list. */
1932 s = string_free_list;
1933 string_free_list = NEXT_FREE_LISP_STRING (s);
1935 MALLOC_UNBLOCK_INPUT;
1937 --total_free_strings;
1938 ++total_strings;
1939 ++strings_consed;
1940 consing_since_gc += sizeof *s;
1942 #ifdef GC_CHECK_STRING_BYTES
1943 if (!noninteractive)
1945 if (++check_string_bytes_count == 200)
1947 check_string_bytes_count = 0;
1948 check_string_bytes (1);
1950 else
1951 check_string_bytes (0);
1953 #endif /* GC_CHECK_STRING_BYTES */
1955 return s;
1959 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1960 plus a NUL byte at the end. Allocate an sdata structure for S, and
1961 set S->data to its `u.data' member. Store a NUL byte at the end of
1962 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1963 S->data if it was initially non-null. */
1965 void
1966 allocate_string_data (struct Lisp_String *s,
1967 EMACS_INT nchars, EMACS_INT nbytes)
1969 sdata *data, *old_data;
1970 struct sblock *b;
1971 ptrdiff_t needed, old_nbytes;
1973 if (STRING_BYTES_MAX < nbytes)
1974 string_overflow ();
1976 /* Determine the number of bytes needed to store NBYTES bytes
1977 of string data. */
1978 needed = SDATA_SIZE (nbytes);
1979 if (s->data)
1981 old_data = SDATA_OF_STRING (s);
1982 old_nbytes = STRING_BYTES (s);
1984 else
1985 old_data = NULL;
1987 MALLOC_BLOCK_INPUT;
1989 if (nbytes > LARGE_STRING_BYTES)
1991 size_t size = FLEXSIZEOF (struct sblock, data, needed);
1993 #ifdef DOUG_LEA_MALLOC
1994 if (!mmap_lisp_allowed_p ())
1995 mallopt (M_MMAP_MAX, 0);
1996 #endif
1998 b = lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
2000 #ifdef DOUG_LEA_MALLOC
2001 if (!mmap_lisp_allowed_p ())
2002 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2003 #endif
2005 data = b->data;
2006 b->next = large_sblocks;
2007 b->next_free = data;
2008 large_sblocks = b;
2010 else if (current_sblock == NULL
2011 || (((char *) current_sblock + SBLOCK_SIZE
2012 - (char *) current_sblock->next_free)
2013 < (needed + GC_STRING_EXTRA)))
2015 /* Not enough room in the current sblock. */
2016 b = lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
2017 data = b->data;
2018 b->next = NULL;
2019 b->next_free = data;
2021 if (current_sblock)
2022 current_sblock->next = b;
2023 else
2024 oldest_sblock = b;
2025 current_sblock = b;
2027 else
2029 b = current_sblock;
2030 data = b->next_free;
2033 data->string = s;
2034 b->next_free = (sdata *) ((char *) data + needed + GC_STRING_EXTRA);
2036 MALLOC_UNBLOCK_INPUT;
2038 s->data = SDATA_DATA (data);
2039 #ifdef GC_CHECK_STRING_BYTES
2040 SDATA_NBYTES (data) = nbytes;
2041 #endif
2042 s->size = nchars;
2043 s->size_byte = nbytes;
2044 s->data[nbytes] = '\0';
2045 #ifdef GC_CHECK_STRING_OVERRUN
2046 memcpy ((char *) data + needed, string_overrun_cookie,
2047 GC_STRING_OVERRUN_COOKIE_SIZE);
2048 #endif
2050 /* Note that Faset may call to this function when S has already data
2051 assigned. In this case, mark data as free by setting it's string
2052 back-pointer to null, and record the size of the data in it. */
2053 if (old_data)
2055 SDATA_NBYTES (old_data) = old_nbytes;
2056 old_data->string = NULL;
2059 consing_since_gc += needed;
2063 /* Sweep and compact strings. */
2065 NO_INLINE /* For better stack traces */
2066 static void
2067 sweep_strings (void)
2069 struct string_block *b, *next;
2070 struct string_block *live_blocks = NULL;
2072 string_free_list = NULL;
2073 total_strings = total_free_strings = 0;
2074 total_string_bytes = 0;
2076 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
2077 for (b = string_blocks; b; b = next)
2079 int i, nfree = 0;
2080 struct Lisp_String *free_list_before = string_free_list;
2082 next = b->next;
2084 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
2086 struct Lisp_String *s = b->strings + i;
2088 if (s->data)
2090 /* String was not on free-list before. */
2091 if (STRING_MARKED_P (s))
2093 /* String is live; unmark it and its intervals. */
2094 UNMARK_STRING (s);
2096 /* Do not use string_(set|get)_intervals here. */
2097 s->intervals = balance_intervals (s->intervals);
2099 ++total_strings;
2100 total_string_bytes += STRING_BYTES (s);
2102 else
2104 /* String is dead. Put it on the free-list. */
2105 sdata *data = SDATA_OF_STRING (s);
2107 /* Save the size of S in its sdata so that we know
2108 how large that is. Reset the sdata's string
2109 back-pointer so that we know it's free. */
2110 #ifdef GC_CHECK_STRING_BYTES
2111 if (string_bytes (s) != SDATA_NBYTES (data))
2112 emacs_abort ();
2113 #else
2114 data->n.nbytes = STRING_BYTES (s);
2115 #endif
2116 data->string = NULL;
2118 /* Reset the strings's `data' member so that we
2119 know it's free. */
2120 s->data = NULL;
2122 /* Put the string on the free-list. */
2123 NEXT_FREE_LISP_STRING (s) = string_free_list;
2124 string_free_list = s;
2125 ++nfree;
2128 else
2130 /* S was on the free-list before. Put it there again. */
2131 NEXT_FREE_LISP_STRING (s) = string_free_list;
2132 string_free_list = s;
2133 ++nfree;
2137 /* Free blocks that contain free Lisp_Strings only, except
2138 the first two of them. */
2139 if (nfree == STRING_BLOCK_SIZE
2140 && total_free_strings > STRING_BLOCK_SIZE)
2142 lisp_free (b);
2143 string_free_list = free_list_before;
2145 else
2147 total_free_strings += nfree;
2148 b->next = live_blocks;
2149 live_blocks = b;
2153 check_string_free_list ();
2155 string_blocks = live_blocks;
2156 free_large_strings ();
2157 compact_small_strings ();
2159 check_string_free_list ();
2163 /* Free dead large strings. */
2165 static void
2166 free_large_strings (void)
2168 struct sblock *b, *next;
2169 struct sblock *live_blocks = NULL;
2171 for (b = large_sblocks; b; b = next)
2173 next = b->next;
2175 if (b->data[0].string == NULL)
2176 lisp_free (b);
2177 else
2179 b->next = live_blocks;
2180 live_blocks = b;
2184 large_sblocks = live_blocks;
2188 /* Compact data of small strings. Free sblocks that don't contain
2189 data of live strings after compaction. */
2191 static void
2192 compact_small_strings (void)
2194 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2195 to, and TB_END is the end of TB. */
2196 struct sblock *tb = oldest_sblock;
2197 if (tb)
2199 sdata *tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
2200 sdata *to = tb->data;
2202 /* Step through the blocks from the oldest to the youngest. We
2203 expect that old blocks will stabilize over time, so that less
2204 copying will happen this way. */
2205 struct sblock *b = tb;
2208 sdata *end = b->next_free;
2209 eassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2211 for (sdata *from = b->data; from < end; )
2213 /* Compute the next FROM here because copying below may
2214 overwrite data we need to compute it. */
2215 ptrdiff_t nbytes;
2216 struct Lisp_String *s = from->string;
2218 #ifdef GC_CHECK_STRING_BYTES
2219 /* Check that the string size recorded in the string is the
2220 same as the one recorded in the sdata structure. */
2221 if (s && string_bytes (s) != SDATA_NBYTES (from))
2222 emacs_abort ();
2223 #endif /* GC_CHECK_STRING_BYTES */
2225 nbytes = s ? STRING_BYTES (s) : SDATA_NBYTES (from);
2226 eassert (nbytes <= LARGE_STRING_BYTES);
2228 nbytes = SDATA_SIZE (nbytes);
2229 sdata *from_end = (sdata *) ((char *) from
2230 + nbytes + GC_STRING_EXTRA);
2232 #ifdef GC_CHECK_STRING_OVERRUN
2233 if (memcmp (string_overrun_cookie,
2234 (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
2235 GC_STRING_OVERRUN_COOKIE_SIZE))
2236 emacs_abort ();
2237 #endif
2239 /* Non-NULL S means it's alive. Copy its data. */
2240 if (s)
2242 /* If TB is full, proceed with the next sblock. */
2243 sdata *to_end = (sdata *) ((char *) to
2244 + nbytes + GC_STRING_EXTRA);
2245 if (to_end > tb_end)
2247 tb->next_free = to;
2248 tb = tb->next;
2249 tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
2250 to = tb->data;
2251 to_end = (sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2254 /* Copy, and update the string's `data' pointer. */
2255 if (from != to)
2257 eassert (tb != b || to < from);
2258 memmove (to, from, nbytes + GC_STRING_EXTRA);
2259 to->string->data = SDATA_DATA (to);
2262 /* Advance past the sdata we copied to. */
2263 to = to_end;
2265 from = from_end;
2267 b = b->next;
2269 while (b);
2271 /* The rest of the sblocks following TB don't contain live data, so
2272 we can free them. */
2273 for (b = tb->next; b; )
2275 struct sblock *next = b->next;
2276 lisp_free (b);
2277 b = next;
2280 tb->next_free = to;
2281 tb->next = NULL;
2284 current_sblock = tb;
2287 void
2288 string_overflow (void)
2290 error ("Maximum string size exceeded");
2293 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2294 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2295 LENGTH must be an integer.
2296 INIT must be an integer that represents a character. */)
2297 (Lisp_Object length, Lisp_Object init)
2299 register Lisp_Object val;
2300 int c;
2301 EMACS_INT nbytes;
2303 CHECK_NATNUM (length);
2304 CHECK_CHARACTER (init);
2306 c = XFASTINT (init);
2307 if (ASCII_CHAR_P (c))
2309 nbytes = XINT (length);
2310 val = make_uninit_string (nbytes);
2311 if (nbytes)
2313 memset (SDATA (val), c, nbytes);
2314 SDATA (val)[nbytes] = 0;
2317 else
2319 unsigned char str[MAX_MULTIBYTE_LENGTH];
2320 ptrdiff_t len = CHAR_STRING (c, str);
2321 EMACS_INT string_len = XINT (length);
2322 unsigned char *p, *beg, *end;
2324 if (INT_MULTIPLY_WRAPV (len, string_len, &nbytes))
2325 string_overflow ();
2326 val = make_uninit_multibyte_string (string_len, nbytes);
2327 for (beg = SDATA (val), p = beg, end = beg + nbytes; p < end; p += len)
2329 /* First time we just copy `str' to the data of `val'. */
2330 if (p == beg)
2331 memcpy (p, str, len);
2332 else
2334 /* Next time we copy largest possible chunk from
2335 initialized to uninitialized part of `val'. */
2336 len = min (p - beg, end - p);
2337 memcpy (p, beg, len);
2340 if (nbytes)
2341 *p = 0;
2344 return val;
2347 /* Fill A with 1 bits if INIT is non-nil, and with 0 bits otherwise.
2348 Return A. */
2350 Lisp_Object
2351 bool_vector_fill (Lisp_Object a, Lisp_Object init)
2353 EMACS_INT nbits = bool_vector_size (a);
2354 if (0 < nbits)
2356 unsigned char *data = bool_vector_uchar_data (a);
2357 int pattern = NILP (init) ? 0 : (1 << BOOL_VECTOR_BITS_PER_CHAR) - 1;
2358 ptrdiff_t nbytes = bool_vector_bytes (nbits);
2359 int last_mask = ~ (~0u << ((nbits - 1) % BOOL_VECTOR_BITS_PER_CHAR + 1));
2360 memset (data, pattern, nbytes - 1);
2361 data[nbytes - 1] = pattern & last_mask;
2363 return a;
2366 /* Return a newly allocated, uninitialized bool vector of size NBITS. */
2368 Lisp_Object
2369 make_uninit_bool_vector (EMACS_INT nbits)
2371 Lisp_Object val;
2372 EMACS_INT words = bool_vector_words (nbits);
2373 EMACS_INT word_bytes = words * sizeof (bits_word);
2374 EMACS_INT needed_elements = ((bool_header_size - header_size + word_bytes
2375 + word_size - 1)
2376 / word_size);
2377 struct Lisp_Bool_Vector *p
2378 = (struct Lisp_Bool_Vector *) allocate_vector (needed_elements);
2379 XSETVECTOR (val, p);
2380 XSETPVECTYPESIZE (XVECTOR (val), PVEC_BOOL_VECTOR, 0, 0);
2381 p->size = nbits;
2383 /* Clear padding at the end. */
2384 if (words)
2385 p->data[words - 1] = 0;
2387 return val;
2390 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2391 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2392 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2393 (Lisp_Object length, Lisp_Object init)
2395 Lisp_Object val;
2397 CHECK_NATNUM (length);
2398 val = make_uninit_bool_vector (XFASTINT (length));
2399 return bool_vector_fill (val, init);
2402 DEFUN ("bool-vector", Fbool_vector, Sbool_vector, 0, MANY, 0,
2403 doc: /* Return a new bool-vector with specified arguments as elements.
2404 Any number of arguments, even zero arguments, are allowed.
2405 usage: (bool-vector &rest OBJECTS) */)
2406 (ptrdiff_t nargs, Lisp_Object *args)
2408 ptrdiff_t i;
2409 Lisp_Object vector;
2411 vector = make_uninit_bool_vector (nargs);
2412 for (i = 0; i < nargs; i++)
2413 bool_vector_set (vector, i, !NILP (args[i]));
2415 return vector;
2418 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2419 of characters from the contents. This string may be unibyte or
2420 multibyte, depending on the contents. */
2422 Lisp_Object
2423 make_string (const char *contents, ptrdiff_t nbytes)
2425 register Lisp_Object val;
2426 ptrdiff_t nchars, multibyte_nbytes;
2428 parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
2429 &nchars, &multibyte_nbytes);
2430 if (nbytes == nchars || nbytes != multibyte_nbytes)
2431 /* CONTENTS contains no multibyte sequences or contains an invalid
2432 multibyte sequence. We must make unibyte string. */
2433 val = make_unibyte_string (contents, nbytes);
2434 else
2435 val = make_multibyte_string (contents, nchars, nbytes);
2436 return val;
2439 /* Make a unibyte string from LENGTH bytes at CONTENTS. */
2441 Lisp_Object
2442 make_unibyte_string (const char *contents, ptrdiff_t length)
2444 register Lisp_Object val;
2445 val = make_uninit_string (length);
2446 memcpy (SDATA (val), contents, length);
2447 return val;
2451 /* Make a multibyte string from NCHARS characters occupying NBYTES
2452 bytes at CONTENTS. */
2454 Lisp_Object
2455 make_multibyte_string (const char *contents,
2456 ptrdiff_t nchars, ptrdiff_t nbytes)
2458 register Lisp_Object val;
2459 val = make_uninit_multibyte_string (nchars, nbytes);
2460 memcpy (SDATA (val), contents, nbytes);
2461 return val;
2465 /* Make a string from NCHARS characters occupying NBYTES bytes at
2466 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2468 Lisp_Object
2469 make_string_from_bytes (const char *contents,
2470 ptrdiff_t nchars, ptrdiff_t nbytes)
2472 register Lisp_Object val;
2473 val = make_uninit_multibyte_string (nchars, nbytes);
2474 memcpy (SDATA (val), contents, nbytes);
2475 if (SBYTES (val) == SCHARS (val))
2476 STRING_SET_UNIBYTE (val);
2477 return val;
2481 /* Make a string from NCHARS characters occupying NBYTES bytes at
2482 CONTENTS. The argument MULTIBYTE controls whether to label the
2483 string as multibyte. If NCHARS is negative, it counts the number of
2484 characters by itself. */
2486 Lisp_Object
2487 make_specified_string (const char *contents,
2488 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
2490 Lisp_Object val;
2492 if (nchars < 0)
2494 if (multibyte)
2495 nchars = multibyte_chars_in_text ((const unsigned char *) contents,
2496 nbytes);
2497 else
2498 nchars = nbytes;
2500 val = make_uninit_multibyte_string (nchars, nbytes);
2501 memcpy (SDATA (val), contents, nbytes);
2502 if (!multibyte)
2503 STRING_SET_UNIBYTE (val);
2504 return val;
2508 /* Return a unibyte Lisp_String set up to hold LENGTH characters
2509 occupying LENGTH bytes. */
2511 Lisp_Object
2512 make_uninit_string (EMACS_INT length)
2514 Lisp_Object val;
2516 if (!length)
2517 return empty_unibyte_string;
2518 val = make_uninit_multibyte_string (length, length);
2519 STRING_SET_UNIBYTE (val);
2520 return val;
2524 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2525 which occupy NBYTES bytes. */
2527 Lisp_Object
2528 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2530 Lisp_Object string;
2531 struct Lisp_String *s;
2533 if (nchars < 0)
2534 emacs_abort ();
2535 if (!nbytes)
2536 return empty_multibyte_string;
2538 s = allocate_string ();
2539 s->intervals = NULL;
2540 allocate_string_data (s, nchars, nbytes);
2541 XSETSTRING (string, s);
2542 string_chars_consed += nbytes;
2543 return string;
2546 /* Print arguments to BUF according to a FORMAT, then return
2547 a Lisp_String initialized with the data from BUF. */
2549 Lisp_Object
2550 make_formatted_string (char *buf, const char *format, ...)
2552 va_list ap;
2553 int length;
2555 va_start (ap, format);
2556 length = vsprintf (buf, format, ap);
2557 va_end (ap);
2558 return make_string (buf, length);
2562 /***********************************************************************
2563 Float Allocation
2564 ***********************************************************************/
2566 /* We store float cells inside of float_blocks, allocating a new
2567 float_block with malloc whenever necessary. Float cells reclaimed
2568 by GC are put on a free list to be reallocated before allocating
2569 any new float cells from the latest float_block. */
2571 #define FLOAT_BLOCK_SIZE \
2572 (((BLOCK_BYTES - sizeof (struct float_block *) \
2573 /* The compiler might add padding at the end. */ \
2574 - (sizeof (struct Lisp_Float) - sizeof (bits_word))) * CHAR_BIT) \
2575 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2577 #define GETMARKBIT(block,n) \
2578 (((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2579 >> ((n) % BITS_PER_BITS_WORD)) \
2580 & 1)
2582 #define SETMARKBIT(block,n) \
2583 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2584 |= (bits_word) 1 << ((n) % BITS_PER_BITS_WORD))
2586 #define UNSETMARKBIT(block,n) \
2587 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2588 &= ~((bits_word) 1 << ((n) % BITS_PER_BITS_WORD)))
2590 #define FLOAT_BLOCK(fptr) \
2591 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2593 #define FLOAT_INDEX(fptr) \
2594 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2596 struct float_block
2598 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2599 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2600 bits_word gcmarkbits[1 + FLOAT_BLOCK_SIZE / BITS_PER_BITS_WORD];
2601 struct float_block *next;
2604 #define FLOAT_MARKED_P(fptr) \
2605 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2607 #define FLOAT_MARK(fptr) \
2608 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2610 #define FLOAT_UNMARK(fptr) \
2611 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2613 /* Current float_block. */
2615 static struct float_block *float_block;
2617 /* Index of first unused Lisp_Float in the current float_block. */
2619 static int float_block_index = FLOAT_BLOCK_SIZE;
2621 /* Free-list of Lisp_Floats. */
2623 static struct Lisp_Float *float_free_list;
2625 /* Return a new float object with value FLOAT_VALUE. */
2627 Lisp_Object
2628 make_float (double float_value)
2630 register Lisp_Object val;
2632 MALLOC_BLOCK_INPUT;
2634 if (float_free_list)
2636 /* We use the data field for chaining the free list
2637 so that we won't use the same field that has the mark bit. */
2638 XSETFLOAT (val, float_free_list);
2639 float_free_list = float_free_list->u.chain;
2641 else
2643 if (float_block_index == FLOAT_BLOCK_SIZE)
2645 struct float_block *new
2646 = lisp_align_malloc (sizeof *new, MEM_TYPE_FLOAT);
2647 new->next = float_block;
2648 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2649 float_block = new;
2650 float_block_index = 0;
2651 total_free_floats += FLOAT_BLOCK_SIZE;
2653 XSETFLOAT (val, &float_block->floats[float_block_index]);
2654 float_block_index++;
2657 MALLOC_UNBLOCK_INPUT;
2659 XFLOAT_INIT (val, float_value);
2660 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2661 consing_since_gc += sizeof (struct Lisp_Float);
2662 floats_consed++;
2663 total_free_floats--;
2664 return val;
2669 /***********************************************************************
2670 Cons Allocation
2671 ***********************************************************************/
2673 /* We store cons cells inside of cons_blocks, allocating a new
2674 cons_block with malloc whenever necessary. Cons cells reclaimed by
2675 GC are put on a free list to be reallocated before allocating
2676 any new cons cells from the latest cons_block. */
2678 #define CONS_BLOCK_SIZE \
2679 (((BLOCK_BYTES - sizeof (struct cons_block *) \
2680 /* The compiler might add padding at the end. */ \
2681 - (sizeof (struct Lisp_Cons) - sizeof (bits_word))) * CHAR_BIT) \
2682 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2684 #define CONS_BLOCK(fptr) \
2685 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2687 #define CONS_INDEX(fptr) \
2688 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2690 struct cons_block
2692 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2693 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2694 bits_word gcmarkbits[1 + CONS_BLOCK_SIZE / BITS_PER_BITS_WORD];
2695 struct cons_block *next;
2698 #define CONS_MARKED_P(fptr) \
2699 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2701 #define CONS_MARK(fptr) \
2702 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2704 #define CONS_UNMARK(fptr) \
2705 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2707 /* Current cons_block. */
2709 static struct cons_block *cons_block;
2711 /* Index of first unused Lisp_Cons in the current block. */
2713 static int cons_block_index = CONS_BLOCK_SIZE;
2715 /* Free-list of Lisp_Cons structures. */
2717 static struct Lisp_Cons *cons_free_list;
2719 /* Explicitly free a cons cell by putting it on the free-list. */
2721 void
2722 free_cons (struct Lisp_Cons *ptr)
2724 ptr->u.chain = cons_free_list;
2725 ptr->car = Vdead;
2726 cons_free_list = ptr;
2727 consing_since_gc -= sizeof *ptr;
2728 total_free_conses++;
2731 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2732 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2733 (Lisp_Object car, Lisp_Object cdr)
2735 register Lisp_Object val;
2737 MALLOC_BLOCK_INPUT;
2739 if (cons_free_list)
2741 /* We use the cdr for chaining the free list
2742 so that we won't use the same field that has the mark bit. */
2743 XSETCONS (val, cons_free_list);
2744 cons_free_list = cons_free_list->u.chain;
2746 else
2748 if (cons_block_index == CONS_BLOCK_SIZE)
2750 struct cons_block *new
2751 = lisp_align_malloc (sizeof *new, MEM_TYPE_CONS);
2752 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2753 new->next = cons_block;
2754 cons_block = new;
2755 cons_block_index = 0;
2756 total_free_conses += CONS_BLOCK_SIZE;
2758 XSETCONS (val, &cons_block->conses[cons_block_index]);
2759 cons_block_index++;
2762 MALLOC_UNBLOCK_INPUT;
2764 XSETCAR (val, car);
2765 XSETCDR (val, cdr);
2766 eassert (!CONS_MARKED_P (XCONS (val)));
2767 consing_since_gc += sizeof (struct Lisp_Cons);
2768 total_free_conses--;
2769 cons_cells_consed++;
2770 return val;
2773 #ifdef GC_CHECK_CONS_LIST
2774 /* Get an error now if there's any junk in the cons free list. */
2775 void
2776 check_cons_list (void)
2778 struct Lisp_Cons *tail = cons_free_list;
2780 while (tail)
2781 tail = tail->u.chain;
2783 #endif
2785 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2787 Lisp_Object
2788 list1 (Lisp_Object arg1)
2790 return Fcons (arg1, Qnil);
2793 Lisp_Object
2794 list2 (Lisp_Object arg1, Lisp_Object arg2)
2796 return Fcons (arg1, Fcons (arg2, Qnil));
2800 Lisp_Object
2801 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2803 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2807 Lisp_Object
2808 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2810 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2814 Lisp_Object
2815 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2817 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2818 Fcons (arg5, Qnil)))));
2821 /* Make a list of COUNT Lisp_Objects, where ARG is the
2822 first one. Allocate conses from pure space if TYPE
2823 is CONSTYPE_PURE, or allocate as usual if type is CONSTYPE_HEAP. */
2825 Lisp_Object
2826 listn (enum constype type, ptrdiff_t count, Lisp_Object arg, ...)
2828 Lisp_Object (*cons) (Lisp_Object, Lisp_Object);
2829 switch (type)
2831 case CONSTYPE_PURE: cons = pure_cons; break;
2832 case CONSTYPE_HEAP: cons = Fcons; break;
2833 default: emacs_abort ();
2836 eassume (0 < count);
2837 Lisp_Object val = cons (arg, Qnil);
2838 Lisp_Object tail = val;
2840 va_list ap;
2841 va_start (ap, arg);
2842 for (ptrdiff_t i = 1; i < count; i++)
2844 Lisp_Object elem = cons (va_arg (ap, Lisp_Object), Qnil);
2845 XSETCDR (tail, elem);
2846 tail = elem;
2848 va_end (ap);
2850 return val;
2853 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2854 doc: /* Return a newly created list with specified arguments as elements.
2855 Any number of arguments, even zero arguments, are allowed.
2856 usage: (list &rest OBJECTS) */)
2857 (ptrdiff_t nargs, Lisp_Object *args)
2859 register Lisp_Object val;
2860 val = Qnil;
2862 while (nargs > 0)
2864 nargs--;
2865 val = Fcons (args[nargs], val);
2867 return val;
2871 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2872 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2873 (register Lisp_Object length, Lisp_Object init)
2875 register Lisp_Object val;
2876 register EMACS_INT size;
2878 CHECK_NATNUM (length);
2879 size = XFASTINT (length);
2881 val = Qnil;
2882 while (size > 0)
2884 val = Fcons (init, val);
2885 --size;
2887 if (size > 0)
2889 val = Fcons (init, val);
2890 --size;
2892 if (size > 0)
2894 val = Fcons (init, val);
2895 --size;
2897 if (size > 0)
2899 val = Fcons (init, val);
2900 --size;
2902 if (size > 0)
2904 val = Fcons (init, val);
2905 --size;
2911 QUIT;
2914 return val;
2919 /***********************************************************************
2920 Vector Allocation
2921 ***********************************************************************/
2923 /* Sometimes a vector's contents are merely a pointer internally used
2924 in vector allocation code. On the rare platforms where a null
2925 pointer cannot be tagged, represent it with a Lisp 0.
2926 Usually you don't want to touch this. */
2928 static struct Lisp_Vector *
2929 next_vector (struct Lisp_Vector *v)
2931 return XUNTAG (v->contents[0], Lisp_Int0);
2934 static void
2935 set_next_vector (struct Lisp_Vector *v, struct Lisp_Vector *p)
2937 v->contents[0] = make_lisp_ptr (p, Lisp_Int0);
2940 /* This value is balanced well enough to avoid too much internal overhead
2941 for the most common cases; it's not required to be a power of two, but
2942 it's expected to be a mult-of-ROUNDUP_SIZE (see below). */
2944 #define VECTOR_BLOCK_SIZE 4096
2946 enum
2948 /* Alignment of struct Lisp_Vector objects. */
2949 vector_alignment = COMMON_MULTIPLE (FLEXALIGNOF (struct Lisp_Vector),
2950 GCALIGNMENT),
2952 /* Vector size requests are a multiple of this. */
2953 roundup_size = COMMON_MULTIPLE (vector_alignment, word_size)
2956 /* Verify assumptions described above. */
2957 verify (VECTOR_BLOCK_SIZE % roundup_size == 0);
2958 verify (VECTOR_BLOCK_SIZE <= (1 << PSEUDOVECTOR_SIZE_BITS));
2960 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at compile time. */
2961 #define vroundup_ct(x) ROUNDUP (x, roundup_size)
2962 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at runtime. */
2963 #define vroundup(x) (eassume ((x) >= 0), vroundup_ct (x))
2965 /* Rounding helps to maintain alignment constraints if USE_LSB_TAG. */
2967 #define VECTOR_BLOCK_BYTES (VECTOR_BLOCK_SIZE - vroundup_ct (sizeof (void *)))
2969 /* Size of the minimal vector allocated from block. */
2971 #define VBLOCK_BYTES_MIN vroundup_ct (header_size + sizeof (Lisp_Object))
2973 /* Size of the largest vector allocated from block. */
2975 #define VBLOCK_BYTES_MAX \
2976 vroundup ((VECTOR_BLOCK_BYTES / 2) - word_size)
2978 /* We maintain one free list for each possible block-allocated
2979 vector size, and this is the number of free lists we have. */
2981 #define VECTOR_MAX_FREE_LIST_INDEX \
2982 ((VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN) / roundup_size + 1)
2984 /* Common shortcut to advance vector pointer over a block data. */
2986 #define ADVANCE(v, nbytes) ((struct Lisp_Vector *) ((char *) (v) + (nbytes)))
2988 /* Common shortcut to calculate NBYTES-vector index in VECTOR_FREE_LISTS. */
2990 #define VINDEX(nbytes) (((nbytes) - VBLOCK_BYTES_MIN) / roundup_size)
2992 /* Common shortcut to setup vector on a free list. */
2994 #define SETUP_ON_FREE_LIST(v, nbytes, tmp) \
2995 do { \
2996 (tmp) = ((nbytes - header_size) / word_size); \
2997 XSETPVECTYPESIZE (v, PVEC_FREE, 0, (tmp)); \
2998 eassert ((nbytes) % roundup_size == 0); \
2999 (tmp) = VINDEX (nbytes); \
3000 eassert ((tmp) < VECTOR_MAX_FREE_LIST_INDEX); \
3001 set_next_vector (v, vector_free_lists[tmp]); \
3002 vector_free_lists[tmp] = (v); \
3003 total_free_vector_slots += (nbytes) / word_size; \
3004 } while (0)
3006 /* This internal type is used to maintain the list of large vectors
3007 which are allocated at their own, e.g. outside of vector blocks.
3009 struct large_vector itself cannot contain a struct Lisp_Vector, as
3010 the latter contains a flexible array member and C99 does not allow
3011 such structs to be nested. Instead, each struct large_vector
3012 object LV is followed by a struct Lisp_Vector, which is at offset
3013 large_vector_offset from LV, and whose address is therefore
3014 large_vector_vec (&LV). */
3016 struct large_vector
3018 struct large_vector *next;
3021 enum
3023 large_vector_offset = ROUNDUP (sizeof (struct large_vector), vector_alignment)
3026 static struct Lisp_Vector *
3027 large_vector_vec (struct large_vector *p)
3029 return (struct Lisp_Vector *) ((char *) p + large_vector_offset);
3032 /* This internal type is used to maintain an underlying storage
3033 for small vectors. */
3035 struct vector_block
3037 char data[VECTOR_BLOCK_BYTES];
3038 struct vector_block *next;
3041 /* Chain of vector blocks. */
3043 static struct vector_block *vector_blocks;
3045 /* Vector free lists, where NTH item points to a chain of free
3046 vectors of the same NBYTES size, so NTH == VINDEX (NBYTES). */
3048 static struct Lisp_Vector *vector_free_lists[VECTOR_MAX_FREE_LIST_INDEX];
3050 /* Singly-linked list of large vectors. */
3052 static struct large_vector *large_vectors;
3054 /* The only vector with 0 slots, allocated from pure space. */
3056 Lisp_Object zero_vector;
3058 /* Number of live vectors. */
3060 static EMACS_INT total_vectors;
3062 /* Total size of live and free vectors, in Lisp_Object units. */
3064 static EMACS_INT total_vector_slots, total_free_vector_slots;
3066 /* Get a new vector block. */
3068 static struct vector_block *
3069 allocate_vector_block (void)
3071 struct vector_block *block = xmalloc (sizeof *block);
3073 #ifndef GC_MALLOC_CHECK
3074 mem_insert (block->data, block->data + VECTOR_BLOCK_BYTES,
3075 MEM_TYPE_VECTOR_BLOCK);
3076 #endif
3078 block->next = vector_blocks;
3079 vector_blocks = block;
3080 return block;
3083 /* Called once to initialize vector allocation. */
3085 static void
3086 init_vectors (void)
3088 zero_vector = make_pure_vector (0);
3091 /* Allocate vector from a vector block. */
3093 static struct Lisp_Vector *
3094 allocate_vector_from_block (size_t nbytes)
3096 struct Lisp_Vector *vector;
3097 struct vector_block *block;
3098 size_t index, restbytes;
3100 eassert (VBLOCK_BYTES_MIN <= nbytes && nbytes <= VBLOCK_BYTES_MAX);
3101 eassert (nbytes % roundup_size == 0);
3103 /* First, try to allocate from a free list
3104 containing vectors of the requested size. */
3105 index = VINDEX (nbytes);
3106 if (vector_free_lists[index])
3108 vector = vector_free_lists[index];
3109 vector_free_lists[index] = next_vector (vector);
3110 total_free_vector_slots -= nbytes / word_size;
3111 return vector;
3114 /* Next, check free lists containing larger vectors. Since
3115 we will split the result, we should have remaining space
3116 large enough to use for one-slot vector at least. */
3117 for (index = VINDEX (nbytes + VBLOCK_BYTES_MIN);
3118 index < VECTOR_MAX_FREE_LIST_INDEX; index++)
3119 if (vector_free_lists[index])
3121 /* This vector is larger than requested. */
3122 vector = vector_free_lists[index];
3123 vector_free_lists[index] = next_vector (vector);
3124 total_free_vector_slots -= nbytes / word_size;
3126 /* Excess bytes are used for the smaller vector,
3127 which should be set on an appropriate free list. */
3128 restbytes = index * roundup_size + VBLOCK_BYTES_MIN - nbytes;
3129 eassert (restbytes % roundup_size == 0);
3130 SETUP_ON_FREE_LIST (ADVANCE (vector, nbytes), restbytes, index);
3131 return vector;
3134 /* Finally, need a new vector block. */
3135 block = allocate_vector_block ();
3137 /* New vector will be at the beginning of this block. */
3138 vector = (struct Lisp_Vector *) block->data;
3140 /* If the rest of space from this block is large enough
3141 for one-slot vector at least, set up it on a free list. */
3142 restbytes = VECTOR_BLOCK_BYTES - nbytes;
3143 if (restbytes >= VBLOCK_BYTES_MIN)
3145 eassert (restbytes % roundup_size == 0);
3146 SETUP_ON_FREE_LIST (ADVANCE (vector, nbytes), restbytes, index);
3148 return vector;
3151 /* Nonzero if VECTOR pointer is valid pointer inside BLOCK. */
3153 #define VECTOR_IN_BLOCK(vector, block) \
3154 ((char *) (vector) <= (block)->data \
3155 + VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN)
3157 /* Return the memory footprint of V in bytes. */
3159 static ptrdiff_t
3160 vector_nbytes (struct Lisp_Vector *v)
3162 ptrdiff_t size = v->header.size & ~ARRAY_MARK_FLAG;
3163 ptrdiff_t nwords;
3165 if (size & PSEUDOVECTOR_FLAG)
3167 if (PSEUDOVECTOR_TYPEP (&v->header, PVEC_BOOL_VECTOR))
3169 struct Lisp_Bool_Vector *bv = (struct Lisp_Bool_Vector *) v;
3170 ptrdiff_t word_bytes = (bool_vector_words (bv->size)
3171 * sizeof (bits_word));
3172 ptrdiff_t boolvec_bytes = bool_header_size + word_bytes;
3173 verify (header_size <= bool_header_size);
3174 nwords = (boolvec_bytes - header_size + word_size - 1) / word_size;
3176 else
3177 nwords = ((size & PSEUDOVECTOR_SIZE_MASK)
3178 + ((size & PSEUDOVECTOR_REST_MASK)
3179 >> PSEUDOVECTOR_SIZE_BITS));
3181 else
3182 nwords = size;
3183 return vroundup (header_size + word_size * nwords);
3186 /* Release extra resources still in use by VECTOR, which may be any
3187 vector-like object. For now, this is used just to free data in
3188 font objects. */
3190 static void
3191 cleanup_vector (struct Lisp_Vector *vector)
3193 detect_suspicious_free (vector);
3194 if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FONT)
3195 && ((vector->header.size & PSEUDOVECTOR_SIZE_MASK)
3196 == FONT_OBJECT_MAX))
3198 struct font_driver *drv = ((struct font *) vector)->driver;
3200 /* The font driver might sometimes be NULL, e.g. if Emacs was
3201 interrupted before it had time to set it up. */
3202 if (drv)
3204 /* Attempt to catch subtle bugs like Bug#16140. */
3205 eassert (valid_font_driver (drv));
3206 drv->close ((struct font *) vector);
3211 /* Reclaim space used by unmarked vectors. */
3213 NO_INLINE /* For better stack traces */
3214 static void
3215 sweep_vectors (void)
3217 struct vector_block *block, **bprev = &vector_blocks;
3218 struct large_vector *lv, **lvprev = &large_vectors;
3219 struct Lisp_Vector *vector, *next;
3221 total_vectors = total_vector_slots = total_free_vector_slots = 0;
3222 memset (vector_free_lists, 0, sizeof (vector_free_lists));
3224 /* Looking through vector blocks. */
3226 for (block = vector_blocks; block; block = *bprev)
3228 bool free_this_block = 0;
3229 ptrdiff_t nbytes;
3231 for (vector = (struct Lisp_Vector *) block->data;
3232 VECTOR_IN_BLOCK (vector, block); vector = next)
3234 if (VECTOR_MARKED_P (vector))
3236 VECTOR_UNMARK (vector);
3237 total_vectors++;
3238 nbytes = vector_nbytes (vector);
3239 total_vector_slots += nbytes / word_size;
3240 next = ADVANCE (vector, nbytes);
3242 else
3244 ptrdiff_t total_bytes;
3246 cleanup_vector (vector);
3247 nbytes = vector_nbytes (vector);
3248 total_bytes = nbytes;
3249 next = ADVANCE (vector, nbytes);
3251 /* While NEXT is not marked, try to coalesce with VECTOR,
3252 thus making VECTOR of the largest possible size. */
3254 while (VECTOR_IN_BLOCK (next, block))
3256 if (VECTOR_MARKED_P (next))
3257 break;
3258 cleanup_vector (next);
3259 nbytes = vector_nbytes (next);
3260 total_bytes += nbytes;
3261 next = ADVANCE (next, nbytes);
3264 eassert (total_bytes % roundup_size == 0);
3266 if (vector == (struct Lisp_Vector *) block->data
3267 && !VECTOR_IN_BLOCK (next, block))
3268 /* This block should be freed because all of its
3269 space was coalesced into the only free vector. */
3270 free_this_block = 1;
3271 else
3273 size_t tmp;
3274 SETUP_ON_FREE_LIST (vector, total_bytes, tmp);
3279 if (free_this_block)
3281 *bprev = block->next;
3282 #ifndef GC_MALLOC_CHECK
3283 mem_delete (mem_find (block->data));
3284 #endif
3285 xfree (block);
3287 else
3288 bprev = &block->next;
3291 /* Sweep large vectors. */
3293 for (lv = large_vectors; lv; lv = *lvprev)
3295 vector = large_vector_vec (lv);
3296 if (VECTOR_MARKED_P (vector))
3298 VECTOR_UNMARK (vector);
3299 total_vectors++;
3300 if (vector->header.size & PSEUDOVECTOR_FLAG)
3302 /* All non-bool pseudovectors are small enough to be allocated
3303 from vector blocks. This code should be redesigned if some
3304 pseudovector type grows beyond VBLOCK_BYTES_MAX. */
3305 eassert (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_BOOL_VECTOR));
3306 total_vector_slots += vector_nbytes (vector) / word_size;
3308 else
3309 total_vector_slots
3310 += header_size / word_size + vector->header.size;
3311 lvprev = &lv->next;
3313 else
3315 *lvprev = lv->next;
3316 lisp_free (lv);
3321 /* Value is a pointer to a newly allocated Lisp_Vector structure
3322 with room for LEN Lisp_Objects. */
3324 static struct Lisp_Vector *
3325 allocate_vectorlike (ptrdiff_t len)
3327 struct Lisp_Vector *p;
3329 MALLOC_BLOCK_INPUT;
3331 if (len == 0)
3332 p = XVECTOR (zero_vector);
3333 else
3335 size_t nbytes = header_size + len * word_size;
3337 #ifdef DOUG_LEA_MALLOC
3338 if (!mmap_lisp_allowed_p ())
3339 mallopt (M_MMAP_MAX, 0);
3340 #endif
3342 if (nbytes <= VBLOCK_BYTES_MAX)
3343 p = allocate_vector_from_block (vroundup (nbytes));
3344 else
3346 struct large_vector *lv
3347 = lisp_malloc ((large_vector_offset + header_size
3348 + len * word_size),
3349 MEM_TYPE_VECTORLIKE);
3350 lv->next = large_vectors;
3351 large_vectors = lv;
3352 p = large_vector_vec (lv);
3355 #ifdef DOUG_LEA_MALLOC
3356 if (!mmap_lisp_allowed_p ())
3357 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
3358 #endif
3360 if (find_suspicious_object_in_range (p, (char *) p + nbytes))
3361 emacs_abort ();
3363 consing_since_gc += nbytes;
3364 vector_cells_consed += len;
3367 MALLOC_UNBLOCK_INPUT;
3369 return p;
3373 /* Allocate a vector with LEN slots. */
3375 struct Lisp_Vector *
3376 allocate_vector (EMACS_INT len)
3378 struct Lisp_Vector *v;
3379 ptrdiff_t nbytes_max = min (PTRDIFF_MAX, SIZE_MAX);
3381 if (min ((nbytes_max - header_size) / word_size, MOST_POSITIVE_FIXNUM) < len)
3382 memory_full (SIZE_MAX);
3383 v = allocate_vectorlike (len);
3384 if (len)
3385 v->header.size = len;
3386 return v;
3390 /* Allocate other vector-like structures. */
3392 struct Lisp_Vector *
3393 allocate_pseudovector (int memlen, int lisplen,
3394 int zerolen, enum pvec_type tag)
3396 struct Lisp_Vector *v = allocate_vectorlike (memlen);
3398 /* Catch bogus values. */
3399 eassert (0 <= tag && tag <= PVEC_FONT);
3400 eassert (0 <= lisplen && lisplen <= zerolen && zerolen <= memlen);
3401 eassert (memlen - lisplen <= (1 << PSEUDOVECTOR_REST_BITS) - 1);
3402 eassert (lisplen <= (1 << PSEUDOVECTOR_SIZE_BITS) - 1);
3404 /* Only the first LISPLEN slots will be traced normally by the GC. */
3405 memclear (v->contents, zerolen * word_size);
3406 XSETPVECTYPESIZE (v, tag, lisplen, memlen - lisplen);
3407 return v;
3410 struct buffer *
3411 allocate_buffer (void)
3413 struct buffer *b = lisp_malloc (sizeof *b, MEM_TYPE_BUFFER);
3415 BUFFER_PVEC_INIT (b);
3416 /* Put B on the chain of all buffers including killed ones. */
3417 b->next = all_buffers;
3418 all_buffers = b;
3419 /* Note that the rest fields of B are not initialized. */
3420 return b;
3423 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
3424 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
3425 See also the function `vector'. */)
3426 (Lisp_Object length, Lisp_Object init)
3428 CHECK_NATNUM (length);
3429 struct Lisp_Vector *p = allocate_vector (XFASTINT (length));
3430 for (ptrdiff_t i = 0; i < XFASTINT (length); i++)
3431 p->contents[i] = init;
3432 return make_lisp_ptr (p, Lisp_Vectorlike);
3435 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3436 doc: /* Return a newly created vector with specified arguments as elements.
3437 Any number of arguments, even zero arguments, are allowed.
3438 usage: (vector &rest OBJECTS) */)
3439 (ptrdiff_t nargs, Lisp_Object *args)
3441 Lisp_Object val = make_uninit_vector (nargs);
3442 struct Lisp_Vector *p = XVECTOR (val);
3443 memcpy (p->contents, args, nargs * sizeof *args);
3444 return val;
3447 void
3448 make_byte_code (struct Lisp_Vector *v)
3450 /* Don't allow the global zero_vector to become a byte code object. */
3451 eassert (0 < v->header.size);
3453 if (v->header.size > 1 && STRINGP (v->contents[1])
3454 && STRING_MULTIBYTE (v->contents[1]))
3455 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3456 earlier because they produced a raw 8-bit string for byte-code
3457 and now such a byte-code string is loaded as multibyte while
3458 raw 8-bit characters converted to multibyte form. Thus, now we
3459 must convert them back to the original unibyte form. */
3460 v->contents[1] = Fstring_as_unibyte (v->contents[1]);
3461 XSETPVECTYPE (v, PVEC_COMPILED);
3464 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3465 doc: /* Create a byte-code object with specified arguments as elements.
3466 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3467 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3468 and (optional) INTERACTIVE-SPEC.
3469 The first four arguments are required; at most six have any
3470 significance.
3471 The ARGLIST can be either like the one of `lambda', in which case the arguments
3472 will be dynamically bound before executing the byte code, or it can be an
3473 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3474 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3475 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3476 argument to catch the left-over arguments. If such an integer is used, the
3477 arguments will not be dynamically bound but will be instead pushed on the
3478 stack before executing the byte-code.
3479 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3480 (ptrdiff_t nargs, Lisp_Object *args)
3482 Lisp_Object val = make_uninit_vector (nargs);
3483 struct Lisp_Vector *p = XVECTOR (val);
3485 /* We used to purecopy everything here, if purify-flag was set. This worked
3486 OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
3487 dangerous, since make-byte-code is used during execution to build
3488 closures, so any closure built during the preload phase would end up
3489 copied into pure space, including its free variables, which is sometimes
3490 just wasteful and other times plainly wrong (e.g. those free vars may want
3491 to be setcar'd). */
3493 memcpy (p->contents, args, nargs * sizeof *args);
3494 make_byte_code (p);
3495 XSETCOMPILED (val, p);
3496 return val;
3501 /***********************************************************************
3502 Symbol Allocation
3503 ***********************************************************************/
3505 /* Like struct Lisp_Symbol, but padded so that the size is a multiple
3506 of the required alignment. */
3508 union aligned_Lisp_Symbol
3510 struct Lisp_Symbol s;
3511 unsigned char c[(sizeof (struct Lisp_Symbol) + GCALIGNMENT - 1)
3512 & -GCALIGNMENT];
3515 /* Each symbol_block is just under 1020 bytes long, since malloc
3516 really allocates in units of powers of two and uses 4 bytes for its
3517 own overhead. */
3519 #define SYMBOL_BLOCK_SIZE \
3520 ((1020 - sizeof (struct symbol_block *)) / sizeof (union aligned_Lisp_Symbol))
3522 struct symbol_block
3524 /* Place `symbols' first, to preserve alignment. */
3525 union aligned_Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3526 struct symbol_block *next;
3529 /* Current symbol block and index of first unused Lisp_Symbol
3530 structure in it. */
3532 static struct symbol_block *symbol_block;
3533 static int symbol_block_index = SYMBOL_BLOCK_SIZE;
3534 /* Pointer to the first symbol_block that contains pinned symbols.
3535 Tests for 24.4 showed that at dump-time, Emacs contains about 15K symbols,
3536 10K of which are pinned (and all but 250 of them are interned in obarray),
3537 whereas a "typical session" has in the order of 30K symbols.
3538 `symbol_block_pinned' lets mark_pinned_symbols scan only 15K symbols rather
3539 than 30K to find the 10K symbols we need to mark. */
3540 static struct symbol_block *symbol_block_pinned;
3542 /* List of free symbols. */
3544 static struct Lisp_Symbol *symbol_free_list;
3546 static void
3547 set_symbol_name (Lisp_Object sym, Lisp_Object name)
3549 XSYMBOL (sym)->name = name;
3552 void
3553 init_symbol (Lisp_Object val, Lisp_Object name)
3555 struct Lisp_Symbol *p = XSYMBOL (val);
3556 set_symbol_name (val, name);
3557 set_symbol_plist (val, Qnil);
3558 p->redirect = SYMBOL_PLAINVAL;
3559 SET_SYMBOL_VAL (p, Qunbound);
3560 set_symbol_function (val, Qnil);
3561 set_symbol_next (val, NULL);
3562 p->gcmarkbit = false;
3563 p->interned = SYMBOL_UNINTERNED;
3564 p->constant = 0;
3565 p->declared_special = false;
3566 p->pinned = false;
3569 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3570 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3571 Its value is void, and its function definition and property list are nil. */)
3572 (Lisp_Object name)
3574 Lisp_Object val;
3576 CHECK_STRING (name);
3578 MALLOC_BLOCK_INPUT;
3580 if (symbol_free_list)
3582 XSETSYMBOL (val, symbol_free_list);
3583 symbol_free_list = symbol_free_list->next;
3585 else
3587 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3589 struct symbol_block *new
3590 = lisp_malloc (sizeof *new, MEM_TYPE_SYMBOL);
3591 new->next = symbol_block;
3592 symbol_block = new;
3593 symbol_block_index = 0;
3594 total_free_symbols += SYMBOL_BLOCK_SIZE;
3596 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index].s);
3597 symbol_block_index++;
3600 MALLOC_UNBLOCK_INPUT;
3602 init_symbol (val, name);
3603 consing_since_gc += sizeof (struct Lisp_Symbol);
3604 symbols_consed++;
3605 total_free_symbols--;
3606 return val;
3611 /***********************************************************************
3612 Marker (Misc) Allocation
3613 ***********************************************************************/
3615 /* Like union Lisp_Misc, but padded so that its size is a multiple of
3616 the required alignment. */
3618 union aligned_Lisp_Misc
3620 union Lisp_Misc m;
3621 unsigned char c[(sizeof (union Lisp_Misc) + GCALIGNMENT - 1)
3622 & -GCALIGNMENT];
3625 /* Allocation of markers and other objects that share that structure.
3626 Works like allocation of conses. */
3628 #define MARKER_BLOCK_SIZE \
3629 ((1020 - sizeof (struct marker_block *)) / sizeof (union aligned_Lisp_Misc))
3631 struct marker_block
3633 /* Place `markers' first, to preserve alignment. */
3634 union aligned_Lisp_Misc markers[MARKER_BLOCK_SIZE];
3635 struct marker_block *next;
3638 static struct marker_block *marker_block;
3639 static int marker_block_index = MARKER_BLOCK_SIZE;
3641 static union Lisp_Misc *marker_free_list;
3643 /* Return a newly allocated Lisp_Misc object of specified TYPE. */
3645 static Lisp_Object
3646 allocate_misc (enum Lisp_Misc_Type type)
3648 Lisp_Object val;
3650 MALLOC_BLOCK_INPUT;
3652 if (marker_free_list)
3654 XSETMISC (val, marker_free_list);
3655 marker_free_list = marker_free_list->u_free.chain;
3657 else
3659 if (marker_block_index == MARKER_BLOCK_SIZE)
3661 struct marker_block *new = lisp_malloc (sizeof *new, MEM_TYPE_MISC);
3662 new->next = marker_block;
3663 marker_block = new;
3664 marker_block_index = 0;
3665 total_free_markers += MARKER_BLOCK_SIZE;
3667 XSETMISC (val, &marker_block->markers[marker_block_index].m);
3668 marker_block_index++;
3671 MALLOC_UNBLOCK_INPUT;
3673 --total_free_markers;
3674 consing_since_gc += sizeof (union Lisp_Misc);
3675 misc_objects_consed++;
3676 XMISCANY (val)->type = type;
3677 XMISCANY (val)->gcmarkbit = 0;
3678 return val;
3681 /* Free a Lisp_Misc object. */
3683 void
3684 free_misc (Lisp_Object misc)
3686 XMISCANY (misc)->type = Lisp_Misc_Free;
3687 XMISC (misc)->u_free.chain = marker_free_list;
3688 marker_free_list = XMISC (misc);
3689 consing_since_gc -= sizeof (union Lisp_Misc);
3690 total_free_markers++;
3693 /* Verify properties of Lisp_Save_Value's representation
3694 that are assumed here and elsewhere. */
3696 verify (SAVE_UNUSED == 0);
3697 verify (((SAVE_INTEGER | SAVE_POINTER | SAVE_FUNCPOINTER | SAVE_OBJECT)
3698 >> SAVE_SLOT_BITS)
3699 == 0);
3701 /* Return Lisp_Save_Value objects for the various combinations
3702 that callers need. */
3704 Lisp_Object
3705 make_save_int_int_int (ptrdiff_t a, ptrdiff_t b, ptrdiff_t c)
3707 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3708 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3709 p->save_type = SAVE_TYPE_INT_INT_INT;
3710 p->data[0].integer = a;
3711 p->data[1].integer = b;
3712 p->data[2].integer = c;
3713 return val;
3716 Lisp_Object
3717 make_save_obj_obj_obj_obj (Lisp_Object a, Lisp_Object b, Lisp_Object c,
3718 Lisp_Object d)
3720 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3721 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3722 p->save_type = SAVE_TYPE_OBJ_OBJ_OBJ_OBJ;
3723 p->data[0].object = a;
3724 p->data[1].object = b;
3725 p->data[2].object = c;
3726 p->data[3].object = d;
3727 return val;
3730 Lisp_Object
3731 make_save_ptr (void *a)
3733 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3734 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3735 p->save_type = SAVE_POINTER;
3736 p->data[0].pointer = a;
3737 return val;
3740 Lisp_Object
3741 make_save_ptr_int (void *a, ptrdiff_t b)
3743 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3744 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3745 p->save_type = SAVE_TYPE_PTR_INT;
3746 p->data[0].pointer = a;
3747 p->data[1].integer = b;
3748 return val;
3751 Lisp_Object
3752 make_save_ptr_ptr (void *a, void *b)
3754 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3755 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3756 p->save_type = SAVE_TYPE_PTR_PTR;
3757 p->data[0].pointer = a;
3758 p->data[1].pointer = b;
3759 return val;
3762 Lisp_Object
3763 make_save_funcptr_ptr_obj (void (*a) (void), void *b, Lisp_Object c)
3765 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3766 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3767 p->save_type = SAVE_TYPE_FUNCPTR_PTR_OBJ;
3768 p->data[0].funcpointer = a;
3769 p->data[1].pointer = b;
3770 p->data[2].object = c;
3771 return val;
3774 /* Return a Lisp_Save_Value object that represents an array A
3775 of N Lisp objects. */
3777 Lisp_Object
3778 make_save_memory (Lisp_Object *a, ptrdiff_t n)
3780 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3781 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3782 p->save_type = SAVE_TYPE_MEMORY;
3783 p->data[0].pointer = a;
3784 p->data[1].integer = n;
3785 return val;
3788 /* Free a Lisp_Save_Value object. Do not use this function
3789 if SAVE contains pointer other than returned by xmalloc. */
3791 void
3792 free_save_value (Lisp_Object save)
3794 xfree (XSAVE_POINTER (save, 0));
3795 free_misc (save);
3798 /* Return a Lisp_Misc_Overlay object with specified START, END and PLIST. */
3800 Lisp_Object
3801 build_overlay (Lisp_Object start, Lisp_Object end, Lisp_Object plist)
3803 register Lisp_Object overlay;
3805 overlay = allocate_misc (Lisp_Misc_Overlay);
3806 OVERLAY_START (overlay) = start;
3807 OVERLAY_END (overlay) = end;
3808 set_overlay_plist (overlay, plist);
3809 XOVERLAY (overlay)->next = NULL;
3810 return overlay;
3813 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3814 doc: /* Return a newly allocated marker which does not point at any place. */)
3815 (void)
3817 register Lisp_Object val;
3818 register struct Lisp_Marker *p;
3820 val = allocate_misc (Lisp_Misc_Marker);
3821 p = XMARKER (val);
3822 p->buffer = 0;
3823 p->bytepos = 0;
3824 p->charpos = 0;
3825 p->next = NULL;
3826 p->insertion_type = 0;
3827 p->need_adjustment = 0;
3828 return val;
3831 /* Return a newly allocated marker which points into BUF
3832 at character position CHARPOS and byte position BYTEPOS. */
3834 Lisp_Object
3835 build_marker (struct buffer *buf, ptrdiff_t charpos, ptrdiff_t bytepos)
3837 Lisp_Object obj;
3838 struct Lisp_Marker *m;
3840 /* No dead buffers here. */
3841 eassert (BUFFER_LIVE_P (buf));
3843 /* Every character is at least one byte. */
3844 eassert (charpos <= bytepos);
3846 obj = allocate_misc (Lisp_Misc_Marker);
3847 m = XMARKER (obj);
3848 m->buffer = buf;
3849 m->charpos = charpos;
3850 m->bytepos = bytepos;
3851 m->insertion_type = 0;
3852 m->need_adjustment = 0;
3853 m->next = BUF_MARKERS (buf);
3854 BUF_MARKERS (buf) = m;
3855 return obj;
3858 /* Put MARKER back on the free list after using it temporarily. */
3860 void
3861 free_marker (Lisp_Object marker)
3863 unchain_marker (XMARKER (marker));
3864 free_misc (marker);
3868 /* Return a newly created vector or string with specified arguments as
3869 elements. If all the arguments are characters that can fit
3870 in a string of events, make a string; otherwise, make a vector.
3872 Any number of arguments, even zero arguments, are allowed. */
3874 Lisp_Object
3875 make_event_array (ptrdiff_t nargs, Lisp_Object *args)
3877 ptrdiff_t i;
3879 for (i = 0; i < nargs; i++)
3880 /* The things that fit in a string
3881 are characters that are in 0...127,
3882 after discarding the meta bit and all the bits above it. */
3883 if (!INTEGERP (args[i])
3884 || (XINT (args[i]) & ~(-CHAR_META)) >= 0200)
3885 return Fvector (nargs, args);
3887 /* Since the loop exited, we know that all the things in it are
3888 characters, so we can make a string. */
3890 Lisp_Object result;
3892 result = Fmake_string (make_number (nargs), make_number (0));
3893 for (i = 0; i < nargs; i++)
3895 SSET (result, i, XINT (args[i]));
3896 /* Move the meta bit to the right place for a string char. */
3897 if (XINT (args[i]) & CHAR_META)
3898 SSET (result, i, SREF (result, i) | 0x80);
3901 return result;
3905 #ifdef HAVE_MODULES
3906 /* Create a new module user ptr object. */
3907 Lisp_Object
3908 make_user_ptr (void (*finalizer) (void *), void *p)
3910 Lisp_Object obj;
3911 struct Lisp_User_Ptr *uptr;
3913 obj = allocate_misc (Lisp_Misc_User_Ptr);
3914 uptr = XUSER_PTR (obj);
3915 uptr->finalizer = finalizer;
3916 uptr->p = p;
3917 return obj;
3920 #endif
3922 static void
3923 init_finalizer_list (struct Lisp_Finalizer *head)
3925 head->prev = head->next = head;
3928 /* Insert FINALIZER before ELEMENT. */
3930 static void
3931 finalizer_insert (struct Lisp_Finalizer *element,
3932 struct Lisp_Finalizer *finalizer)
3934 eassert (finalizer->prev == NULL);
3935 eassert (finalizer->next == NULL);
3936 finalizer->next = element;
3937 finalizer->prev = element->prev;
3938 finalizer->prev->next = finalizer;
3939 element->prev = finalizer;
3942 static void
3943 unchain_finalizer (struct Lisp_Finalizer *finalizer)
3945 if (finalizer->prev != NULL)
3947 eassert (finalizer->next != NULL);
3948 finalizer->prev->next = finalizer->next;
3949 finalizer->next->prev = finalizer->prev;
3950 finalizer->prev = finalizer->next = NULL;
3954 static void
3955 mark_finalizer_list (struct Lisp_Finalizer *head)
3957 for (struct Lisp_Finalizer *finalizer = head->next;
3958 finalizer != head;
3959 finalizer = finalizer->next)
3961 finalizer->base.gcmarkbit = true;
3962 mark_object (finalizer->function);
3966 /* Move doomed finalizers to list DEST from list SRC. A doomed
3967 finalizer is one that is not GC-reachable and whose
3968 finalizer->function is non-nil. */
3970 static void
3971 queue_doomed_finalizers (struct Lisp_Finalizer *dest,
3972 struct Lisp_Finalizer *src)
3974 struct Lisp_Finalizer *finalizer = src->next;
3975 while (finalizer != src)
3977 struct Lisp_Finalizer *next = finalizer->next;
3978 if (!finalizer->base.gcmarkbit && !NILP (finalizer->function))
3980 unchain_finalizer (finalizer);
3981 finalizer_insert (dest, finalizer);
3984 finalizer = next;
3988 static Lisp_Object
3989 run_finalizer_handler (Lisp_Object args)
3991 add_to_log ("finalizer failed: %S", args);
3992 return Qnil;
3995 static void
3996 run_finalizer_function (Lisp_Object function)
3998 ptrdiff_t count = SPECPDL_INDEX ();
4000 specbind (Qinhibit_quit, Qt);
4001 internal_condition_case_1 (call0, function, Qt, run_finalizer_handler);
4002 unbind_to (count, Qnil);
4005 static void
4006 run_finalizers (struct Lisp_Finalizer *finalizers)
4008 struct Lisp_Finalizer *finalizer;
4009 Lisp_Object function;
4011 while (finalizers->next != finalizers)
4013 finalizer = finalizers->next;
4014 eassert (finalizer->base.type == Lisp_Misc_Finalizer);
4015 unchain_finalizer (finalizer);
4016 function = finalizer->function;
4017 if (!NILP (function))
4019 finalizer->function = Qnil;
4020 run_finalizer_function (function);
4025 DEFUN ("make-finalizer", Fmake_finalizer, Smake_finalizer, 1, 1, 0,
4026 doc: /* Make a finalizer that will run FUNCTION.
4027 FUNCTION will be called after garbage collection when the returned
4028 finalizer object becomes unreachable. If the finalizer object is
4029 reachable only through references from finalizer objects, it does not
4030 count as reachable for the purpose of deciding whether to run
4031 FUNCTION. FUNCTION will be run once per finalizer object. */)
4032 (Lisp_Object function)
4034 Lisp_Object val = allocate_misc (Lisp_Misc_Finalizer);
4035 struct Lisp_Finalizer *finalizer = XFINALIZER (val);
4036 finalizer->function = function;
4037 finalizer->prev = finalizer->next = NULL;
4038 finalizer_insert (&finalizers, finalizer);
4039 return val;
4043 /************************************************************************
4044 Memory Full Handling
4045 ************************************************************************/
4048 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
4049 there may have been size_t overflow so that malloc was never
4050 called, or perhaps malloc was invoked successfully but the
4051 resulting pointer had problems fitting into a tagged EMACS_INT. In
4052 either case this counts as memory being full even though malloc did
4053 not fail. */
4055 void
4056 memory_full (size_t nbytes)
4058 /* Do not go into hysterics merely because a large request failed. */
4059 bool enough_free_memory = 0;
4060 if (SPARE_MEMORY < nbytes)
4062 void *p;
4064 MALLOC_BLOCK_INPUT;
4065 p = malloc (SPARE_MEMORY);
4066 if (p)
4068 free (p);
4069 enough_free_memory = 1;
4071 MALLOC_UNBLOCK_INPUT;
4074 if (! enough_free_memory)
4076 int i;
4078 Vmemory_full = Qt;
4080 memory_full_cons_threshold = sizeof (struct cons_block);
4082 /* The first time we get here, free the spare memory. */
4083 for (i = 0; i < ARRAYELTS (spare_memory); i++)
4084 if (spare_memory[i])
4086 if (i == 0)
4087 free (spare_memory[i]);
4088 else if (i >= 1 && i <= 4)
4089 lisp_align_free (spare_memory[i]);
4090 else
4091 lisp_free (spare_memory[i]);
4092 spare_memory[i] = 0;
4096 /* This used to call error, but if we've run out of memory, we could
4097 get infinite recursion trying to build the string. */
4098 xsignal (Qnil, Vmemory_signal_data);
4101 /* If we released our reserve (due to running out of memory),
4102 and we have a fair amount free once again,
4103 try to set aside another reserve in case we run out once more.
4105 This is called when a relocatable block is freed in ralloc.c,
4106 and also directly from this file, in case we're not using ralloc.c. */
4108 void
4109 refill_memory_reserve (void)
4111 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
4112 if (spare_memory[0] == 0)
4113 spare_memory[0] = malloc (SPARE_MEMORY);
4114 if (spare_memory[1] == 0)
4115 spare_memory[1] = lisp_align_malloc (sizeof (struct cons_block),
4116 MEM_TYPE_SPARE);
4117 if (spare_memory[2] == 0)
4118 spare_memory[2] = lisp_align_malloc (sizeof (struct cons_block),
4119 MEM_TYPE_SPARE);
4120 if (spare_memory[3] == 0)
4121 spare_memory[3] = lisp_align_malloc (sizeof (struct cons_block),
4122 MEM_TYPE_SPARE);
4123 if (spare_memory[4] == 0)
4124 spare_memory[4] = lisp_align_malloc (sizeof (struct cons_block),
4125 MEM_TYPE_SPARE);
4126 if (spare_memory[5] == 0)
4127 spare_memory[5] = lisp_malloc (sizeof (struct string_block),
4128 MEM_TYPE_SPARE);
4129 if (spare_memory[6] == 0)
4130 spare_memory[6] = lisp_malloc (sizeof (struct string_block),
4131 MEM_TYPE_SPARE);
4132 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
4133 Vmemory_full = Qnil;
4134 #endif
4137 /************************************************************************
4138 C Stack Marking
4139 ************************************************************************/
4141 /* Conservative C stack marking requires a method to identify possibly
4142 live Lisp objects given a pointer value. We do this by keeping
4143 track of blocks of Lisp data that are allocated in a red-black tree
4144 (see also the comment of mem_node which is the type of nodes in
4145 that tree). Function lisp_malloc adds information for an allocated
4146 block to the red-black tree with calls to mem_insert, and function
4147 lisp_free removes it with mem_delete. Functions live_string_p etc
4148 call mem_find to lookup information about a given pointer in the
4149 tree, and use that to determine if the pointer points to a Lisp
4150 object or not. */
4152 /* Initialize this part of alloc.c. */
4154 static void
4155 mem_init (void)
4157 mem_z.left = mem_z.right = MEM_NIL;
4158 mem_z.parent = NULL;
4159 mem_z.color = MEM_BLACK;
4160 mem_z.start = mem_z.end = NULL;
4161 mem_root = MEM_NIL;
4165 /* Value is a pointer to the mem_node containing START. Value is
4166 MEM_NIL if there is no node in the tree containing START. */
4168 static struct mem_node *
4169 mem_find (void *start)
4171 struct mem_node *p;
4173 if (start < min_heap_address || start > max_heap_address)
4174 return MEM_NIL;
4176 /* Make the search always successful to speed up the loop below. */
4177 mem_z.start = start;
4178 mem_z.end = (char *) start + 1;
4180 p = mem_root;
4181 while (start < p->start || start >= p->end)
4182 p = start < p->start ? p->left : p->right;
4183 return p;
4187 /* Insert a new node into the tree for a block of memory with start
4188 address START, end address END, and type TYPE. Value is a
4189 pointer to the node that was inserted. */
4191 static struct mem_node *
4192 mem_insert (void *start, void *end, enum mem_type type)
4194 struct mem_node *c, *parent, *x;
4196 if (min_heap_address == NULL || start < min_heap_address)
4197 min_heap_address = start;
4198 if (max_heap_address == NULL || end > max_heap_address)
4199 max_heap_address = end;
4201 /* See where in the tree a node for START belongs. In this
4202 particular application, it shouldn't happen that a node is already
4203 present. For debugging purposes, let's check that. */
4204 c = mem_root;
4205 parent = NULL;
4207 while (c != MEM_NIL)
4209 parent = c;
4210 c = start < c->start ? c->left : c->right;
4213 /* Create a new node. */
4214 #ifdef GC_MALLOC_CHECK
4215 x = malloc (sizeof *x);
4216 if (x == NULL)
4217 emacs_abort ();
4218 #else
4219 x = xmalloc (sizeof *x);
4220 #endif
4221 x->start = start;
4222 x->end = end;
4223 x->type = type;
4224 x->parent = parent;
4225 x->left = x->right = MEM_NIL;
4226 x->color = MEM_RED;
4228 /* Insert it as child of PARENT or install it as root. */
4229 if (parent)
4231 if (start < parent->start)
4232 parent->left = x;
4233 else
4234 parent->right = x;
4236 else
4237 mem_root = x;
4239 /* Re-establish red-black tree properties. */
4240 mem_insert_fixup (x);
4242 return x;
4246 /* Re-establish the red-black properties of the tree, and thereby
4247 balance the tree, after node X has been inserted; X is always red. */
4249 static void
4250 mem_insert_fixup (struct mem_node *x)
4252 while (x != mem_root && x->parent->color == MEM_RED)
4254 /* X is red and its parent is red. This is a violation of
4255 red-black tree property #3. */
4257 if (x->parent == x->parent->parent->left)
4259 /* We're on the left side of our grandparent, and Y is our
4260 "uncle". */
4261 struct mem_node *y = x->parent->parent->right;
4263 if (y->color == MEM_RED)
4265 /* Uncle and parent are red but should be black because
4266 X is red. Change the colors accordingly and proceed
4267 with the grandparent. */
4268 x->parent->color = MEM_BLACK;
4269 y->color = MEM_BLACK;
4270 x->parent->parent->color = MEM_RED;
4271 x = x->parent->parent;
4273 else
4275 /* Parent and uncle have different colors; parent is
4276 red, uncle is black. */
4277 if (x == x->parent->right)
4279 x = x->parent;
4280 mem_rotate_left (x);
4283 x->parent->color = MEM_BLACK;
4284 x->parent->parent->color = MEM_RED;
4285 mem_rotate_right (x->parent->parent);
4288 else
4290 /* This is the symmetrical case of above. */
4291 struct mem_node *y = x->parent->parent->left;
4293 if (y->color == MEM_RED)
4295 x->parent->color = MEM_BLACK;
4296 y->color = MEM_BLACK;
4297 x->parent->parent->color = MEM_RED;
4298 x = x->parent->parent;
4300 else
4302 if (x == x->parent->left)
4304 x = x->parent;
4305 mem_rotate_right (x);
4308 x->parent->color = MEM_BLACK;
4309 x->parent->parent->color = MEM_RED;
4310 mem_rotate_left (x->parent->parent);
4315 /* The root may have been changed to red due to the algorithm. Set
4316 it to black so that property #5 is satisfied. */
4317 mem_root->color = MEM_BLACK;
4321 /* (x) (y)
4322 / \ / \
4323 a (y) ===> (x) c
4324 / \ / \
4325 b c a b */
4327 static void
4328 mem_rotate_left (struct mem_node *x)
4330 struct mem_node *y;
4332 /* Turn y's left sub-tree into x's right sub-tree. */
4333 y = x->right;
4334 x->right = y->left;
4335 if (y->left != MEM_NIL)
4336 y->left->parent = x;
4338 /* Y's parent was x's parent. */
4339 if (y != MEM_NIL)
4340 y->parent = x->parent;
4342 /* Get the parent to point to y instead of x. */
4343 if (x->parent)
4345 if (x == x->parent->left)
4346 x->parent->left = y;
4347 else
4348 x->parent->right = y;
4350 else
4351 mem_root = y;
4353 /* Put x on y's left. */
4354 y->left = x;
4355 if (x != MEM_NIL)
4356 x->parent = y;
4360 /* (x) (Y)
4361 / \ / \
4362 (y) c ===> a (x)
4363 / \ / \
4364 a b b c */
4366 static void
4367 mem_rotate_right (struct mem_node *x)
4369 struct mem_node *y = x->left;
4371 x->left = y->right;
4372 if (y->right != MEM_NIL)
4373 y->right->parent = x;
4375 if (y != MEM_NIL)
4376 y->parent = x->parent;
4377 if (x->parent)
4379 if (x == x->parent->right)
4380 x->parent->right = y;
4381 else
4382 x->parent->left = y;
4384 else
4385 mem_root = y;
4387 y->right = x;
4388 if (x != MEM_NIL)
4389 x->parent = y;
4393 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
4395 static void
4396 mem_delete (struct mem_node *z)
4398 struct mem_node *x, *y;
4400 if (!z || z == MEM_NIL)
4401 return;
4403 if (z->left == MEM_NIL || z->right == MEM_NIL)
4404 y = z;
4405 else
4407 y = z->right;
4408 while (y->left != MEM_NIL)
4409 y = y->left;
4412 if (y->left != MEM_NIL)
4413 x = y->left;
4414 else
4415 x = y->right;
4417 x->parent = y->parent;
4418 if (y->parent)
4420 if (y == y->parent->left)
4421 y->parent->left = x;
4422 else
4423 y->parent->right = x;
4425 else
4426 mem_root = x;
4428 if (y != z)
4430 z->start = y->start;
4431 z->end = y->end;
4432 z->type = y->type;
4435 if (y->color == MEM_BLACK)
4436 mem_delete_fixup (x);
4438 #ifdef GC_MALLOC_CHECK
4439 free (y);
4440 #else
4441 xfree (y);
4442 #endif
4446 /* Re-establish the red-black properties of the tree, after a
4447 deletion. */
4449 static void
4450 mem_delete_fixup (struct mem_node *x)
4452 while (x != mem_root && x->color == MEM_BLACK)
4454 if (x == x->parent->left)
4456 struct mem_node *w = x->parent->right;
4458 if (w->color == MEM_RED)
4460 w->color = MEM_BLACK;
4461 x->parent->color = MEM_RED;
4462 mem_rotate_left (x->parent);
4463 w = x->parent->right;
4466 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
4468 w->color = MEM_RED;
4469 x = x->parent;
4471 else
4473 if (w->right->color == MEM_BLACK)
4475 w->left->color = MEM_BLACK;
4476 w->color = MEM_RED;
4477 mem_rotate_right (w);
4478 w = x->parent->right;
4480 w->color = x->parent->color;
4481 x->parent->color = MEM_BLACK;
4482 w->right->color = MEM_BLACK;
4483 mem_rotate_left (x->parent);
4484 x = mem_root;
4487 else
4489 struct mem_node *w = x->parent->left;
4491 if (w->color == MEM_RED)
4493 w->color = MEM_BLACK;
4494 x->parent->color = MEM_RED;
4495 mem_rotate_right (x->parent);
4496 w = x->parent->left;
4499 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
4501 w->color = MEM_RED;
4502 x = x->parent;
4504 else
4506 if (w->left->color == MEM_BLACK)
4508 w->right->color = MEM_BLACK;
4509 w->color = MEM_RED;
4510 mem_rotate_left (w);
4511 w = x->parent->left;
4514 w->color = x->parent->color;
4515 x->parent->color = MEM_BLACK;
4516 w->left->color = MEM_BLACK;
4517 mem_rotate_right (x->parent);
4518 x = mem_root;
4523 x->color = MEM_BLACK;
4527 /* Value is non-zero if P is a pointer to a live Lisp string on
4528 the heap. M is a pointer to the mem_block for P. */
4530 static bool
4531 live_string_p (struct mem_node *m, void *p)
4533 if (m->type == MEM_TYPE_STRING)
4535 struct string_block *b = m->start;
4536 ptrdiff_t offset = (char *) p - (char *) &b->strings[0];
4538 /* P must point to the start of a Lisp_String structure, and it
4539 must not be on the free-list. */
4540 return (offset >= 0
4541 && offset % sizeof b->strings[0] == 0
4542 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
4543 && ((struct Lisp_String *) p)->data != NULL);
4545 else
4546 return 0;
4550 /* Value is non-zero if P is a pointer to a live Lisp cons on
4551 the heap. M is a pointer to the mem_block for P. */
4553 static bool
4554 live_cons_p (struct mem_node *m, void *p)
4556 if (m->type == MEM_TYPE_CONS)
4558 struct cons_block *b = m->start;
4559 ptrdiff_t offset = (char *) p - (char *) &b->conses[0];
4561 /* P must point to the start of a Lisp_Cons, not be
4562 one of the unused cells in the current cons block,
4563 and not be on the free-list. */
4564 return (offset >= 0
4565 && offset % sizeof b->conses[0] == 0
4566 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
4567 && (b != cons_block
4568 || offset / sizeof b->conses[0] < cons_block_index)
4569 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
4571 else
4572 return 0;
4576 /* Value is non-zero if P is a pointer to a live Lisp symbol on
4577 the heap. M is a pointer to the mem_block for P. */
4579 static bool
4580 live_symbol_p (struct mem_node *m, void *p)
4582 if (m->type == MEM_TYPE_SYMBOL)
4584 struct symbol_block *b = m->start;
4585 ptrdiff_t offset = (char *) p - (char *) &b->symbols[0];
4587 /* P must point to the start of a Lisp_Symbol, not be
4588 one of the unused cells in the current symbol block,
4589 and not be on the free-list. */
4590 return (offset >= 0
4591 && offset % sizeof b->symbols[0] == 0
4592 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
4593 && (b != symbol_block
4594 || offset / sizeof b->symbols[0] < symbol_block_index)
4595 && !EQ (((struct Lisp_Symbol *)p)->function, Vdead));
4597 else
4598 return 0;
4602 /* Value is non-zero if P is a pointer to a live Lisp float on
4603 the heap. M is a pointer to the mem_block for P. */
4605 static bool
4606 live_float_p (struct mem_node *m, void *p)
4608 if (m->type == MEM_TYPE_FLOAT)
4610 struct float_block *b = m->start;
4611 ptrdiff_t offset = (char *) p - (char *) &b->floats[0];
4613 /* P must point to the start of a Lisp_Float and not be
4614 one of the unused cells in the current float block. */
4615 return (offset >= 0
4616 && offset % sizeof b->floats[0] == 0
4617 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
4618 && (b != float_block
4619 || offset / sizeof b->floats[0] < float_block_index));
4621 else
4622 return 0;
4626 /* Value is non-zero if P is a pointer to a live Lisp Misc on
4627 the heap. M is a pointer to the mem_block for P. */
4629 static bool
4630 live_misc_p (struct mem_node *m, void *p)
4632 if (m->type == MEM_TYPE_MISC)
4634 struct marker_block *b = m->start;
4635 ptrdiff_t offset = (char *) p - (char *) &b->markers[0];
4637 /* P must point to the start of a Lisp_Misc, not be
4638 one of the unused cells in the current misc block,
4639 and not be on the free-list. */
4640 return (offset >= 0
4641 && offset % sizeof b->markers[0] == 0
4642 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
4643 && (b != marker_block
4644 || offset / sizeof b->markers[0] < marker_block_index)
4645 && ((union Lisp_Misc *) p)->u_any.type != Lisp_Misc_Free);
4647 else
4648 return 0;
4652 /* Value is non-zero if P is a pointer to a live vector-like object.
4653 M is a pointer to the mem_block for P. */
4655 static bool
4656 live_vector_p (struct mem_node *m, void *p)
4658 if (m->type == MEM_TYPE_VECTOR_BLOCK)
4660 /* This memory node corresponds to a vector block. */
4661 struct vector_block *block = m->start;
4662 struct Lisp_Vector *vector = (struct Lisp_Vector *) block->data;
4664 /* P is in the block's allocation range. Scan the block
4665 up to P and see whether P points to the start of some
4666 vector which is not on a free list. FIXME: check whether
4667 some allocation patterns (probably a lot of short vectors)
4668 may cause a substantial overhead of this loop. */
4669 while (VECTOR_IN_BLOCK (vector, block)
4670 && vector <= (struct Lisp_Vector *) p)
4672 if (!PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FREE) && vector == p)
4673 return 1;
4674 else
4675 vector = ADVANCE (vector, vector_nbytes (vector));
4678 else if (m->type == MEM_TYPE_VECTORLIKE && p == large_vector_vec (m->start))
4679 /* This memory node corresponds to a large vector. */
4680 return 1;
4681 return 0;
4685 /* Value is non-zero if P is a pointer to a live buffer. M is a
4686 pointer to the mem_block for P. */
4688 static bool
4689 live_buffer_p (struct mem_node *m, void *p)
4691 /* P must point to the start of the block, and the buffer
4692 must not have been killed. */
4693 return (m->type == MEM_TYPE_BUFFER
4694 && p == m->start
4695 && !NILP (((struct buffer *) p)->name_));
4698 /* Mark OBJ if we can prove it's a Lisp_Object. */
4700 static void
4701 mark_maybe_object (Lisp_Object obj)
4703 #if USE_VALGRIND
4704 if (valgrind_p)
4705 VALGRIND_MAKE_MEM_DEFINED (&obj, sizeof (obj));
4706 #endif
4708 if (INTEGERP (obj))
4709 return;
4711 void *po = XPNTR (obj);
4712 struct mem_node *m = mem_find (po);
4714 if (m != MEM_NIL)
4716 bool mark_p = false;
4718 switch (XTYPE (obj))
4720 case Lisp_String:
4721 mark_p = (live_string_p (m, po)
4722 && !STRING_MARKED_P ((struct Lisp_String *) po));
4723 break;
4725 case Lisp_Cons:
4726 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4727 break;
4729 case Lisp_Symbol:
4730 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4731 break;
4733 case Lisp_Float:
4734 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4735 break;
4737 case Lisp_Vectorlike:
4738 /* Note: can't check BUFFERP before we know it's a
4739 buffer because checking that dereferences the pointer
4740 PO which might point anywhere. */
4741 if (live_vector_p (m, po))
4742 mark_p = !SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4743 else if (live_buffer_p (m, po))
4744 mark_p = BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4745 break;
4747 case Lisp_Misc:
4748 mark_p = (live_misc_p (m, po) && !XMISCANY (obj)->gcmarkbit);
4749 break;
4751 default:
4752 break;
4755 if (mark_p)
4756 mark_object (obj);
4760 /* Return true if P can point to Lisp data, and false otherwise.
4761 Symbols are implemented via offsets not pointers, but the offsets
4762 are also multiples of GCALIGNMENT. */
4764 static bool
4765 maybe_lisp_pointer (void *p)
4767 return (uintptr_t) p % GCALIGNMENT == 0;
4770 #ifndef HAVE_MODULES
4771 enum { HAVE_MODULES = false };
4772 #endif
4774 /* If P points to Lisp data, mark that as live if it isn't already
4775 marked. */
4777 static void
4778 mark_maybe_pointer (void *p)
4780 struct mem_node *m;
4782 #if USE_VALGRIND
4783 if (valgrind_p)
4784 VALGRIND_MAKE_MEM_DEFINED (&p, sizeof (p));
4785 #endif
4787 if (sizeof (Lisp_Object) == sizeof (void *) || !HAVE_MODULES)
4789 if (!maybe_lisp_pointer (p))
4790 return;
4792 else
4794 /* For the wide-int case, also mark emacs_value tagged pointers,
4795 which can be generated by emacs-module.c's value_to_lisp. */
4796 p = (void *) ((uintptr_t) p & ~(GCALIGNMENT - 1));
4799 m = mem_find (p);
4800 if (m != MEM_NIL)
4802 Lisp_Object obj = Qnil;
4804 switch (m->type)
4806 case MEM_TYPE_NON_LISP:
4807 case MEM_TYPE_SPARE:
4808 /* Nothing to do; not a pointer to Lisp memory. */
4809 break;
4811 case MEM_TYPE_BUFFER:
4812 if (live_buffer_p (m, p) && !VECTOR_MARKED_P ((struct buffer *)p))
4813 XSETVECTOR (obj, p);
4814 break;
4816 case MEM_TYPE_CONS:
4817 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4818 XSETCONS (obj, p);
4819 break;
4821 case MEM_TYPE_STRING:
4822 if (live_string_p (m, p)
4823 && !STRING_MARKED_P ((struct Lisp_String *) p))
4824 XSETSTRING (obj, p);
4825 break;
4827 case MEM_TYPE_MISC:
4828 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4829 XSETMISC (obj, p);
4830 break;
4832 case MEM_TYPE_SYMBOL:
4833 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4834 XSETSYMBOL (obj, p);
4835 break;
4837 case MEM_TYPE_FLOAT:
4838 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4839 XSETFLOAT (obj, p);
4840 break;
4842 case MEM_TYPE_VECTORLIKE:
4843 case MEM_TYPE_VECTOR_BLOCK:
4844 if (live_vector_p (m, p))
4846 Lisp_Object tem;
4847 XSETVECTOR (tem, p);
4848 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4849 obj = tem;
4851 break;
4853 default:
4854 emacs_abort ();
4857 if (!NILP (obj))
4858 mark_object (obj);
4863 /* Alignment of pointer values. Use alignof, as it sometimes returns
4864 a smaller alignment than GCC's __alignof__ and mark_memory might
4865 miss objects if __alignof__ were used. */
4866 #define GC_POINTER_ALIGNMENT alignof (void *)
4868 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4869 or END+OFFSET..START. */
4871 static void ATTRIBUTE_NO_SANITIZE_ADDRESS
4872 mark_memory (void *start, void *end)
4874 char *pp;
4876 /* Make START the pointer to the start of the memory region,
4877 if it isn't already. */
4878 if (end < start)
4880 void *tem = start;
4881 start = end;
4882 end = tem;
4885 eassert (((uintptr_t) start) % GC_POINTER_ALIGNMENT == 0);
4887 /* Mark Lisp data pointed to. This is necessary because, in some
4888 situations, the C compiler optimizes Lisp objects away, so that
4889 only a pointer to them remains. Example:
4891 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4894 Lisp_Object obj = build_string ("test");
4895 struct Lisp_String *s = XSTRING (obj);
4896 Fgarbage_collect ();
4897 fprintf (stderr, "test '%s'\n", s->data);
4898 return Qnil;
4901 Here, `obj' isn't really used, and the compiler optimizes it
4902 away. The only reference to the life string is through the
4903 pointer `s'. */
4905 for (pp = start; (void *) pp < end; pp += GC_POINTER_ALIGNMENT)
4907 mark_maybe_pointer (*(void **) pp);
4908 mark_maybe_object (*(Lisp_Object *) pp);
4912 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4914 static bool setjmp_tested_p;
4915 static int longjmps_done;
4917 #define SETJMP_WILL_LIKELY_WORK "\
4919 Emacs garbage collector has been changed to use conservative stack\n\
4920 marking. Emacs has determined that the method it uses to do the\n\
4921 marking will likely work on your system, but this isn't sure.\n\
4923 If you are a system-programmer, or can get the help of a local wizard\n\
4924 who is, please take a look at the function mark_stack in alloc.c, and\n\
4925 verify that the methods used are appropriate for your system.\n\
4927 Please mail the result to <emacs-devel@gnu.org>.\n\
4930 #define SETJMP_WILL_NOT_WORK "\
4932 Emacs garbage collector has been changed to use conservative stack\n\
4933 marking. Emacs has determined that the default method it uses to do the\n\
4934 marking will not work on your system. We will need a system-dependent\n\
4935 solution for your system.\n\
4937 Please take a look at the function mark_stack in alloc.c, and\n\
4938 try to find a way to make it work on your system.\n\
4940 Note that you may get false negatives, depending on the compiler.\n\
4941 In particular, you need to use -O with GCC for this test.\n\
4943 Please mail the result to <emacs-devel@gnu.org>.\n\
4947 /* Perform a quick check if it looks like setjmp saves registers in a
4948 jmp_buf. Print a message to stderr saying so. When this test
4949 succeeds, this is _not_ a proof that setjmp is sufficient for
4950 conservative stack marking. Only the sources or a disassembly
4951 can prove that. */
4953 static void
4954 test_setjmp (void)
4956 char buf[10];
4957 register int x;
4958 sys_jmp_buf jbuf;
4960 /* Arrange for X to be put in a register. */
4961 sprintf (buf, "1");
4962 x = strlen (buf);
4963 x = 2 * x - 1;
4965 sys_setjmp (jbuf);
4966 if (longjmps_done == 1)
4968 /* Came here after the longjmp at the end of the function.
4970 If x == 1, the longjmp has restored the register to its
4971 value before the setjmp, and we can hope that setjmp
4972 saves all such registers in the jmp_buf, although that
4973 isn't sure.
4975 For other values of X, either something really strange is
4976 taking place, or the setjmp just didn't save the register. */
4978 if (x == 1)
4979 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4980 else
4982 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4983 exit (1);
4987 ++longjmps_done;
4988 x = 2;
4989 if (longjmps_done == 1)
4990 sys_longjmp (jbuf, 1);
4993 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4996 /* Mark live Lisp objects on the C stack.
4998 There are several system-dependent problems to consider when
4999 porting this to new architectures:
5001 Processor Registers
5003 We have to mark Lisp objects in CPU registers that can hold local
5004 variables or are used to pass parameters.
5006 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
5007 something that either saves relevant registers on the stack, or
5008 calls mark_maybe_object passing it each register's contents.
5010 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
5011 implementation assumes that calling setjmp saves registers we need
5012 to see in a jmp_buf which itself lies on the stack. This doesn't
5013 have to be true! It must be verified for each system, possibly
5014 by taking a look at the source code of setjmp.
5016 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
5017 can use it as a machine independent method to store all registers
5018 to the stack. In this case the macros described in the previous
5019 two paragraphs are not used.
5021 Stack Layout
5023 Architectures differ in the way their processor stack is organized.
5024 For example, the stack might look like this
5026 +----------------+
5027 | Lisp_Object | size = 4
5028 +----------------+
5029 | something else | size = 2
5030 +----------------+
5031 | Lisp_Object | size = 4
5032 +----------------+
5033 | ... |
5035 In such a case, not every Lisp_Object will be aligned equally. To
5036 find all Lisp_Object on the stack it won't be sufficient to walk
5037 the stack in steps of 4 bytes. Instead, two passes will be
5038 necessary, one starting at the start of the stack, and a second
5039 pass starting at the start of the stack + 2. Likewise, if the
5040 minimal alignment of Lisp_Objects on the stack is 1, four passes
5041 would be necessary, each one starting with one byte more offset
5042 from the stack start. */
5044 static void
5045 mark_stack (void *end)
5048 /* This assumes that the stack is a contiguous region in memory. If
5049 that's not the case, something has to be done here to iterate
5050 over the stack segments. */
5051 mark_memory (stack_base, end);
5053 /* Allow for marking a secondary stack, like the register stack on the
5054 ia64. */
5055 #ifdef GC_MARK_SECONDARY_STACK
5056 GC_MARK_SECONDARY_STACK ();
5057 #endif
5060 static bool
5061 c_symbol_p (struct Lisp_Symbol *sym)
5063 char *lispsym_ptr = (char *) lispsym;
5064 char *sym_ptr = (char *) sym;
5065 ptrdiff_t lispsym_offset = sym_ptr - lispsym_ptr;
5066 return 0 <= lispsym_offset && lispsym_offset < sizeof lispsym;
5069 /* Determine whether it is safe to access memory at address P. */
5070 static int
5071 valid_pointer_p (void *p)
5073 #ifdef WINDOWSNT
5074 return w32_valid_pointer_p (p, 16);
5075 #else
5077 if (ADDRESS_SANITIZER)
5078 return p ? -1 : 0;
5080 int fd[2];
5082 /* Obviously, we cannot just access it (we would SEGV trying), so we
5083 trick the o/s to tell us whether p is a valid pointer.
5084 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
5085 not validate p in that case. */
5087 if (emacs_pipe (fd) == 0)
5089 bool valid = emacs_write (fd[1], p, 16) == 16;
5090 emacs_close (fd[1]);
5091 emacs_close (fd[0]);
5092 return valid;
5095 return -1;
5096 #endif
5099 /* Return 2 if OBJ is a killed or special buffer object, 1 if OBJ is a
5100 valid lisp object, 0 if OBJ is NOT a valid lisp object, or -1 if we
5101 cannot validate OBJ. This function can be quite slow, so its primary
5102 use is the manual debugging. The only exception is print_object, where
5103 we use it to check whether the memory referenced by the pointer of
5104 Lisp_Save_Value object contains valid objects. */
5107 valid_lisp_object_p (Lisp_Object obj)
5109 if (INTEGERP (obj))
5110 return 1;
5112 void *p = XPNTR (obj);
5113 if (PURE_P (p))
5114 return 1;
5116 if (SYMBOLP (obj) && c_symbol_p (p))
5117 return ((char *) p - (char *) lispsym) % sizeof lispsym[0] == 0;
5119 if (p == &buffer_defaults || p == &buffer_local_symbols)
5120 return 2;
5122 struct mem_node *m = mem_find (p);
5124 if (m == MEM_NIL)
5126 int valid = valid_pointer_p (p);
5127 if (valid <= 0)
5128 return valid;
5130 if (SUBRP (obj))
5131 return 1;
5133 return 0;
5136 switch (m->type)
5138 case MEM_TYPE_NON_LISP:
5139 case MEM_TYPE_SPARE:
5140 return 0;
5142 case MEM_TYPE_BUFFER:
5143 return live_buffer_p (m, p) ? 1 : 2;
5145 case MEM_TYPE_CONS:
5146 return live_cons_p (m, p);
5148 case MEM_TYPE_STRING:
5149 return live_string_p (m, p);
5151 case MEM_TYPE_MISC:
5152 return live_misc_p (m, p);
5154 case MEM_TYPE_SYMBOL:
5155 return live_symbol_p (m, p);
5157 case MEM_TYPE_FLOAT:
5158 return live_float_p (m, p);
5160 case MEM_TYPE_VECTORLIKE:
5161 case MEM_TYPE_VECTOR_BLOCK:
5162 return live_vector_p (m, p);
5164 default:
5165 break;
5168 return 0;
5171 /***********************************************************************
5172 Pure Storage Management
5173 ***********************************************************************/
5175 /* Allocate room for SIZE bytes from pure Lisp storage and return a
5176 pointer to it. TYPE is the Lisp type for which the memory is
5177 allocated. TYPE < 0 means it's not used for a Lisp object. */
5179 static void *
5180 pure_alloc (size_t size, int type)
5182 void *result;
5184 again:
5185 if (type >= 0)
5187 /* Allocate space for a Lisp object from the beginning of the free
5188 space with taking account of alignment. */
5189 result = pointer_align (purebeg + pure_bytes_used_lisp, GCALIGNMENT);
5190 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
5192 else
5194 /* Allocate space for a non-Lisp object from the end of the free
5195 space. */
5196 pure_bytes_used_non_lisp += size;
5197 result = purebeg + pure_size - pure_bytes_used_non_lisp;
5199 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
5201 if (pure_bytes_used <= pure_size)
5202 return result;
5204 /* Don't allocate a large amount here,
5205 because it might get mmap'd and then its address
5206 might not be usable. */
5207 purebeg = xmalloc (10000);
5208 pure_size = 10000;
5209 pure_bytes_used_before_overflow += pure_bytes_used - size;
5210 pure_bytes_used = 0;
5211 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
5212 goto again;
5216 /* Print a warning if PURESIZE is too small. */
5218 void
5219 check_pure_size (void)
5221 if (pure_bytes_used_before_overflow)
5222 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI"d"
5223 " bytes needed)"),
5224 pure_bytes_used + pure_bytes_used_before_overflow);
5228 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
5229 the non-Lisp data pool of the pure storage, and return its start
5230 address. Return NULL if not found. */
5232 static char *
5233 find_string_data_in_pure (const char *data, ptrdiff_t nbytes)
5235 int i;
5236 ptrdiff_t skip, bm_skip[256], last_char_skip, infinity, start, start_max;
5237 const unsigned char *p;
5238 char *non_lisp_beg;
5240 if (pure_bytes_used_non_lisp <= nbytes)
5241 return NULL;
5243 /* Set up the Boyer-Moore table. */
5244 skip = nbytes + 1;
5245 for (i = 0; i < 256; i++)
5246 bm_skip[i] = skip;
5248 p = (const unsigned char *) data;
5249 while (--skip > 0)
5250 bm_skip[*p++] = skip;
5252 last_char_skip = bm_skip['\0'];
5254 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
5255 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
5257 /* See the comments in the function `boyer_moore' (search.c) for the
5258 use of `infinity'. */
5259 infinity = pure_bytes_used_non_lisp + 1;
5260 bm_skip['\0'] = infinity;
5262 p = (const unsigned char *) non_lisp_beg + nbytes;
5263 start = 0;
5266 /* Check the last character (== '\0'). */
5269 start += bm_skip[*(p + start)];
5271 while (start <= start_max);
5273 if (start < infinity)
5274 /* Couldn't find the last character. */
5275 return NULL;
5277 /* No less than `infinity' means we could find the last
5278 character at `p[start - infinity]'. */
5279 start -= infinity;
5281 /* Check the remaining characters. */
5282 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
5283 /* Found. */
5284 return non_lisp_beg + start;
5286 start += last_char_skip;
5288 while (start <= start_max);
5290 return NULL;
5294 /* Return a string allocated in pure space. DATA is a buffer holding
5295 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
5296 means make the result string multibyte.
5298 Must get an error if pure storage is full, since if it cannot hold
5299 a large string it may be able to hold conses that point to that
5300 string; then the string is not protected from gc. */
5302 Lisp_Object
5303 make_pure_string (const char *data,
5304 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
5306 Lisp_Object string;
5307 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5308 s->data = (unsigned char *) find_string_data_in_pure (data, nbytes);
5309 if (s->data == NULL)
5311 s->data = pure_alloc (nbytes + 1, -1);
5312 memcpy (s->data, data, nbytes);
5313 s->data[nbytes] = '\0';
5315 s->size = nchars;
5316 s->size_byte = multibyte ? nbytes : -1;
5317 s->intervals = NULL;
5318 XSETSTRING (string, s);
5319 return string;
5322 /* Return a string allocated in pure space. Do not
5323 allocate the string data, just point to DATA. */
5325 Lisp_Object
5326 make_pure_c_string (const char *data, ptrdiff_t nchars)
5328 Lisp_Object string;
5329 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5330 s->size = nchars;
5331 s->size_byte = -1;
5332 s->data = (unsigned char *) data;
5333 s->intervals = NULL;
5334 XSETSTRING (string, s);
5335 return string;
5338 static Lisp_Object purecopy (Lisp_Object obj);
5340 /* Return a cons allocated from pure space. Give it pure copies
5341 of CAR as car and CDR as cdr. */
5343 Lisp_Object
5344 pure_cons (Lisp_Object car, Lisp_Object cdr)
5346 Lisp_Object new;
5347 struct Lisp_Cons *p = pure_alloc (sizeof *p, Lisp_Cons);
5348 XSETCONS (new, p);
5349 XSETCAR (new, purecopy (car));
5350 XSETCDR (new, purecopy (cdr));
5351 return new;
5355 /* Value is a float object with value NUM allocated from pure space. */
5357 static Lisp_Object
5358 make_pure_float (double num)
5360 Lisp_Object new;
5361 struct Lisp_Float *p = pure_alloc (sizeof *p, Lisp_Float);
5362 XSETFLOAT (new, p);
5363 XFLOAT_INIT (new, num);
5364 return new;
5368 /* Return a vector with room for LEN Lisp_Objects allocated from
5369 pure space. */
5371 static Lisp_Object
5372 make_pure_vector (ptrdiff_t len)
5374 Lisp_Object new;
5375 size_t size = header_size + len * word_size;
5376 struct Lisp_Vector *p = pure_alloc (size, Lisp_Vectorlike);
5377 XSETVECTOR (new, p);
5378 XVECTOR (new)->header.size = len;
5379 return new;
5382 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
5383 doc: /* Make a copy of object OBJ in pure storage.
5384 Recursively copies contents of vectors and cons cells.
5385 Does not copy symbols. Copies strings without text properties. */)
5386 (register Lisp_Object obj)
5388 if (NILP (Vpurify_flag))
5389 return obj;
5390 else if (MARKERP (obj) || OVERLAYP (obj)
5391 || HASH_TABLE_P (obj) || SYMBOLP (obj))
5392 /* Can't purify those. */
5393 return obj;
5394 else
5395 return purecopy (obj);
5398 static Lisp_Object
5399 purecopy (Lisp_Object obj)
5401 if (INTEGERP (obj)
5402 || (! SYMBOLP (obj) && PURE_P (XPNTR_OR_SYMBOL_OFFSET (obj)))
5403 || SUBRP (obj))
5404 return obj; /* Already pure. */
5406 if (STRINGP (obj) && XSTRING (obj)->intervals)
5407 message_with_string ("Dropping text-properties while making string `%s' pure",
5408 obj, true);
5410 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5412 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
5413 if (!NILP (tmp))
5414 return tmp;
5417 if (CONSP (obj))
5418 obj = pure_cons (XCAR (obj), XCDR (obj));
5419 else if (FLOATP (obj))
5420 obj = make_pure_float (XFLOAT_DATA (obj));
5421 else if (STRINGP (obj))
5422 obj = make_pure_string (SSDATA (obj), SCHARS (obj),
5423 SBYTES (obj),
5424 STRING_MULTIBYTE (obj));
5425 else if (COMPILEDP (obj) || VECTORP (obj) || HASH_TABLE_P (obj))
5427 struct Lisp_Vector *objp = XVECTOR (obj);
5428 ptrdiff_t nbytes = vector_nbytes (objp);
5429 struct Lisp_Vector *vec = pure_alloc (nbytes, Lisp_Vectorlike);
5430 register ptrdiff_t i;
5431 ptrdiff_t size = ASIZE (obj);
5432 if (size & PSEUDOVECTOR_FLAG)
5433 size &= PSEUDOVECTOR_SIZE_MASK;
5434 memcpy (vec, objp, nbytes);
5435 for (i = 0; i < size; i++)
5436 vec->contents[i] = purecopy (vec->contents[i]);
5437 XSETVECTOR (obj, vec);
5439 else if (SYMBOLP (obj))
5441 if (!XSYMBOL (obj)->pinned && !c_symbol_p (XSYMBOL (obj)))
5442 { /* We can't purify them, but they appear in many pure objects.
5443 Mark them as `pinned' so we know to mark them at every GC cycle. */
5444 XSYMBOL (obj)->pinned = true;
5445 symbol_block_pinned = symbol_block;
5447 /* Don't hash-cons it. */
5448 return obj;
5450 else
5452 AUTO_STRING (fmt, "Don't know how to purify: %S");
5453 Fsignal (Qerror, list1 (CALLN (Fformat, fmt, obj)));
5456 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5457 Fputhash (obj, obj, Vpurify_flag);
5459 return obj;
5464 /***********************************************************************
5465 Protection from GC
5466 ***********************************************************************/
5468 /* Put an entry in staticvec, pointing at the variable with address
5469 VARADDRESS. */
5471 void
5472 staticpro (Lisp_Object *varaddress)
5474 if (staticidx >= NSTATICS)
5475 fatal ("NSTATICS too small; try increasing and recompiling Emacs.");
5476 staticvec[staticidx++] = varaddress;
5480 /***********************************************************************
5481 Protection from GC
5482 ***********************************************************************/
5484 /* Temporarily prevent garbage collection. */
5486 ptrdiff_t
5487 inhibit_garbage_collection (void)
5489 ptrdiff_t count = SPECPDL_INDEX ();
5491 specbind (Qgc_cons_threshold, make_number (MOST_POSITIVE_FIXNUM));
5492 return count;
5495 /* Used to avoid possible overflows when
5496 converting from C to Lisp integers. */
5498 static Lisp_Object
5499 bounded_number (EMACS_INT number)
5501 return make_number (min (MOST_POSITIVE_FIXNUM, number));
5504 /* Calculate total bytes of live objects. */
5506 static size_t
5507 total_bytes_of_live_objects (void)
5509 size_t tot = 0;
5510 tot += total_conses * sizeof (struct Lisp_Cons);
5511 tot += total_symbols * sizeof (struct Lisp_Symbol);
5512 tot += total_markers * sizeof (union Lisp_Misc);
5513 tot += total_string_bytes;
5514 tot += total_vector_slots * word_size;
5515 tot += total_floats * sizeof (struct Lisp_Float);
5516 tot += total_intervals * sizeof (struct interval);
5517 tot += total_strings * sizeof (struct Lisp_String);
5518 return tot;
5521 #ifdef HAVE_WINDOW_SYSTEM
5523 /* Remove unmarked font-spec and font-entity objects from ENTRY, which is
5524 (DRIVER-TYPE NUM-FRAMES FONT-CACHE-DATA ...), and return changed entry. */
5526 static Lisp_Object
5527 compact_font_cache_entry (Lisp_Object entry)
5529 Lisp_Object tail, *prev = &entry;
5531 for (tail = entry; CONSP (tail); tail = XCDR (tail))
5533 bool drop = 0;
5534 Lisp_Object obj = XCAR (tail);
5536 /* Consider OBJ if it is (font-spec . [font-entity font-entity ...]). */
5537 if (CONSP (obj) && GC_FONT_SPEC_P (XCAR (obj))
5538 && !VECTOR_MARKED_P (GC_XFONT_SPEC (XCAR (obj)))
5539 /* Don't use VECTORP here, as that calls ASIZE, which could
5540 hit assertion violation during GC. */
5541 && (VECTORLIKEP (XCDR (obj))
5542 && ! (gc_asize (XCDR (obj)) & PSEUDOVECTOR_FLAG)))
5544 ptrdiff_t i, size = gc_asize (XCDR (obj));
5545 Lisp_Object obj_cdr = XCDR (obj);
5547 /* If font-spec is not marked, most likely all font-entities
5548 are not marked too. But we must be sure that nothing is
5549 marked within OBJ before we really drop it. */
5550 for (i = 0; i < size; i++)
5552 Lisp_Object objlist;
5554 if (VECTOR_MARKED_P (GC_XFONT_ENTITY (AREF (obj_cdr, i))))
5555 break;
5557 objlist = AREF (AREF (obj_cdr, i), FONT_OBJLIST_INDEX);
5558 for (; CONSP (objlist); objlist = XCDR (objlist))
5560 Lisp_Object val = XCAR (objlist);
5561 struct font *font = GC_XFONT_OBJECT (val);
5563 if (!NILP (AREF (val, FONT_TYPE_INDEX))
5564 && VECTOR_MARKED_P(font))
5565 break;
5567 if (CONSP (objlist))
5569 /* Found a marked font, bail out. */
5570 break;
5574 if (i == size)
5576 /* No marked fonts were found, so this entire font
5577 entity can be dropped. */
5578 drop = 1;
5581 if (drop)
5582 *prev = XCDR (tail);
5583 else
5584 prev = xcdr_addr (tail);
5586 return entry;
5589 /* Compact font caches on all terminals and mark
5590 everything which is still here after compaction. */
5592 static void
5593 compact_font_caches (void)
5595 struct terminal *t;
5597 for (t = terminal_list; t; t = t->next_terminal)
5599 Lisp_Object cache = TERMINAL_FONT_CACHE (t);
5600 if (CONSP (cache))
5602 Lisp_Object entry;
5604 for (entry = XCDR (cache); CONSP (entry); entry = XCDR (entry))
5605 XSETCAR (entry, compact_font_cache_entry (XCAR (entry)));
5607 mark_object (cache);
5611 #else /* not HAVE_WINDOW_SYSTEM */
5613 #define compact_font_caches() (void)(0)
5615 #endif /* HAVE_WINDOW_SYSTEM */
5617 /* Remove (MARKER . DATA) entries with unmarked MARKER
5618 from buffer undo LIST and return changed list. */
5620 static Lisp_Object
5621 compact_undo_list (Lisp_Object list)
5623 Lisp_Object tail, *prev = &list;
5625 for (tail = list; CONSP (tail); tail = XCDR (tail))
5627 if (CONSP (XCAR (tail))
5628 && MARKERP (XCAR (XCAR (tail)))
5629 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5630 *prev = XCDR (tail);
5631 else
5632 prev = xcdr_addr (tail);
5634 return list;
5637 static void
5638 mark_pinned_symbols (void)
5640 struct symbol_block *sblk;
5641 int lim = (symbol_block_pinned == symbol_block
5642 ? symbol_block_index : SYMBOL_BLOCK_SIZE);
5644 for (sblk = symbol_block_pinned; sblk; sblk = sblk->next)
5646 union aligned_Lisp_Symbol *sym = sblk->symbols, *end = sym + lim;
5647 for (; sym < end; ++sym)
5648 if (sym->s.pinned)
5649 mark_object (make_lisp_symbol (&sym->s));
5651 lim = SYMBOL_BLOCK_SIZE;
5655 /* Subroutine of Fgarbage_collect that does most of the work. It is a
5656 separate function so that we could limit mark_stack in searching
5657 the stack frames below this function, thus avoiding the rare cases
5658 where mark_stack finds values that look like live Lisp objects on
5659 portions of stack that couldn't possibly contain such live objects.
5660 For more details of this, see the discussion at
5661 http://lists.gnu.org/archive/html/emacs-devel/2014-05/msg00270.html. */
5662 static Lisp_Object
5663 garbage_collect_1 (void *end)
5665 struct buffer *nextb;
5666 char stack_top_variable;
5667 ptrdiff_t i;
5668 bool message_p;
5669 ptrdiff_t count = SPECPDL_INDEX ();
5670 struct timespec start;
5671 Lisp_Object retval = Qnil;
5672 size_t tot_before = 0;
5674 /* Can't GC if pure storage overflowed because we can't determine
5675 if something is a pure object or not. */
5676 if (pure_bytes_used_before_overflow)
5677 return Qnil;
5679 /* Record this function, so it appears on the profiler's backtraces. */
5680 record_in_backtrace (QAutomatic_GC, 0, 0);
5682 check_cons_list ();
5684 /* Don't keep undo information around forever.
5685 Do this early on, so it is no problem if the user quits. */
5686 FOR_EACH_BUFFER (nextb)
5687 compact_buffer (nextb);
5689 if (profiler_memory_running)
5690 tot_before = total_bytes_of_live_objects ();
5692 start = current_timespec ();
5694 /* In case user calls debug_print during GC,
5695 don't let that cause a recursive GC. */
5696 consing_since_gc = 0;
5698 /* Save what's currently displayed in the echo area. Don't do that
5699 if we are GC'ing because we've run out of memory, since
5700 push_message will cons, and we might have no memory for that. */
5701 if (NILP (Vmemory_full))
5703 message_p = push_message ();
5704 record_unwind_protect_void (pop_message_unwind);
5706 else
5707 message_p = false;
5709 /* Save a copy of the contents of the stack, for debugging. */
5710 #if MAX_SAVE_STACK > 0
5711 if (NILP (Vpurify_flag))
5713 char *stack;
5714 ptrdiff_t stack_size;
5715 if (&stack_top_variable < stack_bottom)
5717 stack = &stack_top_variable;
5718 stack_size = stack_bottom - &stack_top_variable;
5720 else
5722 stack = stack_bottom;
5723 stack_size = &stack_top_variable - stack_bottom;
5725 if (stack_size <= MAX_SAVE_STACK)
5727 if (stack_copy_size < stack_size)
5729 stack_copy = xrealloc (stack_copy, stack_size);
5730 stack_copy_size = stack_size;
5732 no_sanitize_memcpy (stack_copy, stack, stack_size);
5735 #endif /* MAX_SAVE_STACK > 0 */
5737 if (garbage_collection_messages)
5738 message1_nolog ("Garbage collecting...");
5740 block_input ();
5742 shrink_regexp_cache ();
5744 gc_in_progress = 1;
5746 /* Mark all the special slots that serve as the roots of accessibility. */
5748 mark_buffer (&buffer_defaults);
5749 mark_buffer (&buffer_local_symbols);
5751 for (i = 0; i < ARRAYELTS (lispsym); i++)
5752 mark_object (builtin_lisp_symbol (i));
5754 for (i = 0; i < staticidx; i++)
5755 mark_object (*staticvec[i]);
5757 mark_pinned_symbols ();
5758 mark_specpdl ();
5759 mark_terminals ();
5760 mark_kboards ();
5762 #ifdef USE_GTK
5763 xg_mark_data ();
5764 #endif
5766 mark_stack (end);
5769 struct handler *handler;
5770 for (handler = handlerlist; handler; handler = handler->next)
5772 mark_object (handler->tag_or_ch);
5773 mark_object (handler->val);
5776 #ifdef HAVE_WINDOW_SYSTEM
5777 mark_fringe_data ();
5778 #endif
5780 /* Everything is now marked, except for the data in font caches,
5781 undo lists, and finalizers. The first two are compacted by
5782 removing an items which aren't reachable otherwise. */
5784 compact_font_caches ();
5786 FOR_EACH_BUFFER (nextb)
5788 if (!EQ (BVAR (nextb, undo_list), Qt))
5789 bset_undo_list (nextb, compact_undo_list (BVAR (nextb, undo_list)));
5790 /* Now that we have stripped the elements that need not be
5791 in the undo_list any more, we can finally mark the list. */
5792 mark_object (BVAR (nextb, undo_list));
5795 /* Now pre-sweep finalizers. Here, we add any unmarked finalizers
5796 to doomed_finalizers so we can run their associated functions
5797 after GC. It's important to scan finalizers at this stage so
5798 that we can be sure that unmarked finalizers are really
5799 unreachable except for references from their associated functions
5800 and from other finalizers. */
5802 queue_doomed_finalizers (&doomed_finalizers, &finalizers);
5803 mark_finalizer_list (&doomed_finalizers);
5805 gc_sweep ();
5807 /* Clear the mark bits that we set in certain root slots. */
5808 VECTOR_UNMARK (&buffer_defaults);
5809 VECTOR_UNMARK (&buffer_local_symbols);
5811 check_cons_list ();
5813 gc_in_progress = 0;
5815 unblock_input ();
5817 consing_since_gc = 0;
5818 if (gc_cons_threshold < GC_DEFAULT_THRESHOLD / 10)
5819 gc_cons_threshold = GC_DEFAULT_THRESHOLD / 10;
5821 gc_relative_threshold = 0;
5822 if (FLOATP (Vgc_cons_percentage))
5823 { /* Set gc_cons_combined_threshold. */
5824 double tot = total_bytes_of_live_objects ();
5826 tot *= XFLOAT_DATA (Vgc_cons_percentage);
5827 if (0 < tot)
5829 if (tot < TYPE_MAXIMUM (EMACS_INT))
5830 gc_relative_threshold = tot;
5831 else
5832 gc_relative_threshold = TYPE_MAXIMUM (EMACS_INT);
5836 if (garbage_collection_messages && NILP (Vmemory_full))
5838 if (message_p || minibuf_level > 0)
5839 restore_message ();
5840 else
5841 message1_nolog ("Garbage collecting...done");
5844 unbind_to (count, Qnil);
5846 Lisp_Object total[] = {
5847 list4 (Qconses, make_number (sizeof (struct Lisp_Cons)),
5848 bounded_number (total_conses),
5849 bounded_number (total_free_conses)),
5850 list4 (Qsymbols, make_number (sizeof (struct Lisp_Symbol)),
5851 bounded_number (total_symbols),
5852 bounded_number (total_free_symbols)),
5853 list4 (Qmiscs, make_number (sizeof (union Lisp_Misc)),
5854 bounded_number (total_markers),
5855 bounded_number (total_free_markers)),
5856 list4 (Qstrings, make_number (sizeof (struct Lisp_String)),
5857 bounded_number (total_strings),
5858 bounded_number (total_free_strings)),
5859 list3 (Qstring_bytes, make_number (1),
5860 bounded_number (total_string_bytes)),
5861 list3 (Qvectors,
5862 make_number (header_size + sizeof (Lisp_Object)),
5863 bounded_number (total_vectors)),
5864 list4 (Qvector_slots, make_number (word_size),
5865 bounded_number (total_vector_slots),
5866 bounded_number (total_free_vector_slots)),
5867 list4 (Qfloats, make_number (sizeof (struct Lisp_Float)),
5868 bounded_number (total_floats),
5869 bounded_number (total_free_floats)),
5870 list4 (Qintervals, make_number (sizeof (struct interval)),
5871 bounded_number (total_intervals),
5872 bounded_number (total_free_intervals)),
5873 list3 (Qbuffers, make_number (sizeof (struct buffer)),
5874 bounded_number (total_buffers)),
5876 #ifdef DOUG_LEA_MALLOC
5877 list4 (Qheap, make_number (1024),
5878 bounded_number ((mallinfo ().uordblks + 1023) >> 10),
5879 bounded_number ((mallinfo ().fordblks + 1023) >> 10)),
5880 #endif
5882 retval = CALLMANY (Flist, total);
5884 /* GC is complete: now we can run our finalizer callbacks. */
5885 run_finalizers (&doomed_finalizers);
5887 if (!NILP (Vpost_gc_hook))
5889 ptrdiff_t gc_count = inhibit_garbage_collection ();
5890 safe_run_hooks (Qpost_gc_hook);
5891 unbind_to (gc_count, Qnil);
5894 /* Accumulate statistics. */
5895 if (FLOATP (Vgc_elapsed))
5897 struct timespec since_start = timespec_sub (current_timespec (), start);
5898 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed)
5899 + timespectod (since_start));
5902 gcs_done++;
5904 /* Collect profiling data. */
5905 if (profiler_memory_running)
5907 size_t swept = 0;
5908 size_t tot_after = total_bytes_of_live_objects ();
5909 if (tot_before > tot_after)
5910 swept = tot_before - tot_after;
5911 malloc_probe (swept);
5914 return retval;
5917 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
5918 doc: /* Reclaim storage for Lisp objects no longer needed.
5919 Garbage collection happens automatically if you cons more than
5920 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5921 `garbage-collect' normally returns a list with info on amount of space in use,
5922 where each entry has the form (NAME SIZE USED FREE), where:
5923 - NAME is a symbol describing the kind of objects this entry represents,
5924 - SIZE is the number of bytes used by each one,
5925 - USED is the number of those objects that were found live in the heap,
5926 - FREE is the number of those objects that are not live but that Emacs
5927 keeps around for future allocations (maybe because it does not know how
5928 to return them to the OS).
5929 However, if there was overflow in pure space, `garbage-collect'
5930 returns nil, because real GC can't be done.
5931 See Info node `(elisp)Garbage Collection'. */)
5932 (void)
5934 void *end;
5936 #ifdef HAVE___BUILTIN_UNWIND_INIT
5937 /* Force callee-saved registers and register windows onto the stack.
5938 This is the preferred method if available, obviating the need for
5939 machine dependent methods. */
5940 __builtin_unwind_init ();
5941 end = &end;
5942 #else /* not HAVE___BUILTIN_UNWIND_INIT */
5943 #ifndef GC_SAVE_REGISTERS_ON_STACK
5944 /* jmp_buf may not be aligned enough on darwin-ppc64 */
5945 union aligned_jmpbuf {
5946 Lisp_Object o;
5947 sys_jmp_buf j;
5948 } j;
5949 volatile bool stack_grows_down_p = (char *) &j > (char *) stack_base;
5950 #endif
5951 /* This trick flushes the register windows so that all the state of
5952 the process is contained in the stack. */
5953 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
5954 needed on ia64 too. See mach_dep.c, where it also says inline
5955 assembler doesn't work with relevant proprietary compilers. */
5956 #ifdef __sparc__
5957 #if defined (__sparc64__) && defined (__FreeBSD__)
5958 /* FreeBSD does not have a ta 3 handler. */
5959 asm ("flushw");
5960 #else
5961 asm ("ta 3");
5962 #endif
5963 #endif
5965 /* Save registers that we need to see on the stack. We need to see
5966 registers used to hold register variables and registers used to
5967 pass parameters. */
5968 #ifdef GC_SAVE_REGISTERS_ON_STACK
5969 GC_SAVE_REGISTERS_ON_STACK (end);
5970 #else /* not GC_SAVE_REGISTERS_ON_STACK */
5972 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
5973 setjmp will definitely work, test it
5974 and print a message with the result
5975 of the test. */
5976 if (!setjmp_tested_p)
5978 setjmp_tested_p = 1;
5979 test_setjmp ();
5981 #endif /* GC_SETJMP_WORKS */
5983 sys_setjmp (j.j);
5984 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
5985 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
5986 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
5987 return garbage_collect_1 (end);
5990 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5991 only interesting objects referenced from glyphs are strings. */
5993 static void
5994 mark_glyph_matrix (struct glyph_matrix *matrix)
5996 struct glyph_row *row = matrix->rows;
5997 struct glyph_row *end = row + matrix->nrows;
5999 for (; row < end; ++row)
6000 if (row->enabled_p)
6002 int area;
6003 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
6005 struct glyph *glyph = row->glyphs[area];
6006 struct glyph *end_glyph = glyph + row->used[area];
6008 for (; glyph < end_glyph; ++glyph)
6009 if (STRINGP (glyph->object)
6010 && !STRING_MARKED_P (XSTRING (glyph->object)))
6011 mark_object (glyph->object);
6016 /* Mark reference to a Lisp_Object.
6017 If the object referred to has not been seen yet, recursively mark
6018 all the references contained in it. */
6020 #define LAST_MARKED_SIZE 500
6021 static Lisp_Object last_marked[LAST_MARKED_SIZE];
6022 static int last_marked_index;
6024 /* For debugging--call abort when we cdr down this many
6025 links of a list, in mark_object. In debugging,
6026 the call to abort will hit a breakpoint.
6027 Normally this is zero and the check never goes off. */
6028 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE;
6030 static void
6031 mark_vectorlike (struct Lisp_Vector *ptr)
6033 ptrdiff_t size = ptr->header.size;
6034 ptrdiff_t i;
6036 eassert (!VECTOR_MARKED_P (ptr));
6037 VECTOR_MARK (ptr); /* Else mark it. */
6038 if (size & PSEUDOVECTOR_FLAG)
6039 size &= PSEUDOVECTOR_SIZE_MASK;
6041 /* Note that this size is not the memory-footprint size, but only
6042 the number of Lisp_Object fields that we should trace.
6043 The distinction is used e.g. by Lisp_Process which places extra
6044 non-Lisp_Object fields at the end of the structure... */
6045 for (i = 0; i < size; i++) /* ...and then mark its elements. */
6046 mark_object (ptr->contents[i]);
6049 /* Like mark_vectorlike but optimized for char-tables (and
6050 sub-char-tables) assuming that the contents are mostly integers or
6051 symbols. */
6053 static void
6054 mark_char_table (struct Lisp_Vector *ptr, enum pvec_type pvectype)
6056 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
6057 /* Consult the Lisp_Sub_Char_Table layout before changing this. */
6058 int i, idx = (pvectype == PVEC_SUB_CHAR_TABLE ? SUB_CHAR_TABLE_OFFSET : 0);
6060 eassert (!VECTOR_MARKED_P (ptr));
6061 VECTOR_MARK (ptr);
6062 for (i = idx; i < size; i++)
6064 Lisp_Object val = ptr->contents[i];
6066 if (INTEGERP (val) || (SYMBOLP (val) && XSYMBOL (val)->gcmarkbit))
6067 continue;
6068 if (SUB_CHAR_TABLE_P (val))
6070 if (! VECTOR_MARKED_P (XVECTOR (val)))
6071 mark_char_table (XVECTOR (val), PVEC_SUB_CHAR_TABLE);
6073 else
6074 mark_object (val);
6078 NO_INLINE /* To reduce stack depth in mark_object. */
6079 static Lisp_Object
6080 mark_compiled (struct Lisp_Vector *ptr)
6082 int i, size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
6084 VECTOR_MARK (ptr);
6085 for (i = 0; i < size; i++)
6086 if (i != COMPILED_CONSTANTS)
6087 mark_object (ptr->contents[i]);
6088 return size > COMPILED_CONSTANTS ? ptr->contents[COMPILED_CONSTANTS] : Qnil;
6091 /* Mark the chain of overlays starting at PTR. */
6093 static void
6094 mark_overlay (struct Lisp_Overlay *ptr)
6096 for (; ptr && !ptr->gcmarkbit; ptr = ptr->next)
6098 ptr->gcmarkbit = 1;
6099 /* These two are always markers and can be marked fast. */
6100 XMARKER (ptr->start)->gcmarkbit = 1;
6101 XMARKER (ptr->end)->gcmarkbit = 1;
6102 mark_object (ptr->plist);
6106 /* Mark Lisp_Objects and special pointers in BUFFER. */
6108 static void
6109 mark_buffer (struct buffer *buffer)
6111 /* This is handled much like other pseudovectors... */
6112 mark_vectorlike ((struct Lisp_Vector *) buffer);
6114 /* ...but there are some buffer-specific things. */
6116 MARK_INTERVAL_TREE (buffer_intervals (buffer));
6118 /* For now, we just don't mark the undo_list. It's done later in
6119 a special way just before the sweep phase, and after stripping
6120 some of its elements that are not needed any more. */
6122 mark_overlay (buffer->overlays_before);
6123 mark_overlay (buffer->overlays_after);
6125 /* If this is an indirect buffer, mark its base buffer. */
6126 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
6127 mark_buffer (buffer->base_buffer);
6130 /* Mark Lisp faces in the face cache C. */
6132 NO_INLINE /* To reduce stack depth in mark_object. */
6133 static void
6134 mark_face_cache (struct face_cache *c)
6136 if (c)
6138 int i, j;
6139 for (i = 0; i < c->used; ++i)
6141 struct face *face = FACE_FROM_ID_OR_NULL (c->f, i);
6143 if (face)
6145 if (face->font && !VECTOR_MARKED_P (face->font))
6146 mark_vectorlike ((struct Lisp_Vector *) face->font);
6148 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
6149 mark_object (face->lface[j]);
6155 NO_INLINE /* To reduce stack depth in mark_object. */
6156 static void
6157 mark_localized_symbol (struct Lisp_Symbol *ptr)
6159 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
6160 Lisp_Object where = blv->where;
6161 /* If the value is set up for a killed buffer or deleted
6162 frame, restore its global binding. If the value is
6163 forwarded to a C variable, either it's not a Lisp_Object
6164 var, or it's staticpro'd already. */
6165 if ((BUFFERP (where) && !BUFFER_LIVE_P (XBUFFER (where)))
6166 || (FRAMEP (where) && !FRAME_LIVE_P (XFRAME (where))))
6167 swap_in_global_binding (ptr);
6168 mark_object (blv->where);
6169 mark_object (blv->valcell);
6170 mark_object (blv->defcell);
6173 NO_INLINE /* To reduce stack depth in mark_object. */
6174 static void
6175 mark_save_value (struct Lisp_Save_Value *ptr)
6177 /* If `save_type' is zero, `data[0].pointer' is the address
6178 of a memory area containing `data[1].integer' potential
6179 Lisp_Objects. */
6180 if (ptr->save_type == SAVE_TYPE_MEMORY)
6182 Lisp_Object *p = ptr->data[0].pointer;
6183 ptrdiff_t nelt;
6184 for (nelt = ptr->data[1].integer; nelt > 0; nelt--, p++)
6185 mark_maybe_object (*p);
6187 else
6189 /* Find Lisp_Objects in `data[N]' slots and mark them. */
6190 int i;
6191 for (i = 0; i < SAVE_VALUE_SLOTS; i++)
6192 if (save_type (ptr, i) == SAVE_OBJECT)
6193 mark_object (ptr->data[i].object);
6197 /* Remove killed buffers or items whose car is a killed buffer from
6198 LIST, and mark other items. Return changed LIST, which is marked. */
6200 static Lisp_Object
6201 mark_discard_killed_buffers (Lisp_Object list)
6203 Lisp_Object tail, *prev = &list;
6205 for (tail = list; CONSP (tail) && !CONS_MARKED_P (XCONS (tail));
6206 tail = XCDR (tail))
6208 Lisp_Object tem = XCAR (tail);
6209 if (CONSP (tem))
6210 tem = XCAR (tem);
6211 if (BUFFERP (tem) && !BUFFER_LIVE_P (XBUFFER (tem)))
6212 *prev = XCDR (tail);
6213 else
6215 CONS_MARK (XCONS (tail));
6216 mark_object (XCAR (tail));
6217 prev = xcdr_addr (tail);
6220 mark_object (tail);
6221 return list;
6224 /* Determine type of generic Lisp_Object and mark it accordingly.
6226 This function implements a straightforward depth-first marking
6227 algorithm and so the recursion depth may be very high (a few
6228 tens of thousands is not uncommon). To minimize stack usage,
6229 a few cold paths are moved out to NO_INLINE functions above.
6230 In general, inlining them doesn't help you to gain more speed. */
6232 void
6233 mark_object (Lisp_Object arg)
6235 register Lisp_Object obj;
6236 void *po;
6237 #ifdef GC_CHECK_MARKED_OBJECTS
6238 struct mem_node *m;
6239 #endif
6240 ptrdiff_t cdr_count = 0;
6242 obj = arg;
6243 loop:
6245 po = XPNTR (obj);
6246 if (PURE_P (po))
6247 return;
6249 last_marked[last_marked_index++] = obj;
6250 if (last_marked_index == LAST_MARKED_SIZE)
6251 last_marked_index = 0;
6253 /* Perform some sanity checks on the objects marked here. Abort if
6254 we encounter an object we know is bogus. This increases GC time
6255 by ~80%. */
6256 #ifdef GC_CHECK_MARKED_OBJECTS
6258 /* Check that the object pointed to by PO is known to be a Lisp
6259 structure allocated from the heap. */
6260 #define CHECK_ALLOCATED() \
6261 do { \
6262 m = mem_find (po); \
6263 if (m == MEM_NIL) \
6264 emacs_abort (); \
6265 } while (0)
6267 /* Check that the object pointed to by PO is live, using predicate
6268 function LIVEP. */
6269 #define CHECK_LIVE(LIVEP) \
6270 do { \
6271 if (!LIVEP (m, po)) \
6272 emacs_abort (); \
6273 } while (0)
6275 /* Check both of the above conditions, for non-symbols. */
6276 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
6277 do { \
6278 CHECK_ALLOCATED (); \
6279 CHECK_LIVE (LIVEP); \
6280 } while (0) \
6282 /* Check both of the above conditions, for symbols. */
6283 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() \
6284 do { \
6285 if (!c_symbol_p (ptr)) \
6287 CHECK_ALLOCATED (); \
6288 CHECK_LIVE (live_symbol_p); \
6290 } while (0) \
6292 #else /* not GC_CHECK_MARKED_OBJECTS */
6294 #define CHECK_LIVE(LIVEP) ((void) 0)
6295 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) ((void) 0)
6296 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() ((void) 0)
6298 #endif /* not GC_CHECK_MARKED_OBJECTS */
6300 switch (XTYPE (obj))
6302 case Lisp_String:
6304 register struct Lisp_String *ptr = XSTRING (obj);
6305 if (STRING_MARKED_P (ptr))
6306 break;
6307 CHECK_ALLOCATED_AND_LIVE (live_string_p);
6308 MARK_STRING (ptr);
6309 MARK_INTERVAL_TREE (ptr->intervals);
6310 #ifdef GC_CHECK_STRING_BYTES
6311 /* Check that the string size recorded in the string is the
6312 same as the one recorded in the sdata structure. */
6313 string_bytes (ptr);
6314 #endif /* GC_CHECK_STRING_BYTES */
6316 break;
6318 case Lisp_Vectorlike:
6320 register struct Lisp_Vector *ptr = XVECTOR (obj);
6321 register ptrdiff_t pvectype;
6323 if (VECTOR_MARKED_P (ptr))
6324 break;
6326 #ifdef GC_CHECK_MARKED_OBJECTS
6327 m = mem_find (po);
6328 if (m == MEM_NIL && !SUBRP (obj))
6329 emacs_abort ();
6330 #endif /* GC_CHECK_MARKED_OBJECTS */
6332 if (ptr->header.size & PSEUDOVECTOR_FLAG)
6333 pvectype = ((ptr->header.size & PVEC_TYPE_MASK)
6334 >> PSEUDOVECTOR_AREA_BITS);
6335 else
6336 pvectype = PVEC_NORMAL_VECTOR;
6338 if (pvectype != PVEC_SUBR && pvectype != PVEC_BUFFER)
6339 CHECK_LIVE (live_vector_p);
6341 switch (pvectype)
6343 case PVEC_BUFFER:
6344 #ifdef GC_CHECK_MARKED_OBJECTS
6346 struct buffer *b;
6347 FOR_EACH_BUFFER (b)
6348 if (b == po)
6349 break;
6350 if (b == NULL)
6351 emacs_abort ();
6353 #endif /* GC_CHECK_MARKED_OBJECTS */
6354 mark_buffer ((struct buffer *) ptr);
6355 break;
6357 case PVEC_COMPILED:
6358 /* Although we could treat this just like a vector, mark_compiled
6359 returns the COMPILED_CONSTANTS element, which is marked at the
6360 next iteration of goto-loop here. This is done to avoid a few
6361 recursive calls to mark_object. */
6362 obj = mark_compiled (ptr);
6363 if (!NILP (obj))
6364 goto loop;
6365 break;
6367 case PVEC_FRAME:
6369 struct frame *f = (struct frame *) ptr;
6371 mark_vectorlike (ptr);
6372 mark_face_cache (f->face_cache);
6373 #ifdef HAVE_WINDOW_SYSTEM
6374 if (FRAME_WINDOW_P (f) && FRAME_X_OUTPUT (f))
6376 struct font *font = FRAME_FONT (f);
6378 if (font && !VECTOR_MARKED_P (font))
6379 mark_vectorlike ((struct Lisp_Vector *) font);
6381 #endif
6383 break;
6385 case PVEC_WINDOW:
6387 struct window *w = (struct window *) ptr;
6389 mark_vectorlike (ptr);
6391 /* Mark glyph matrices, if any. Marking window
6392 matrices is sufficient because frame matrices
6393 use the same glyph memory. */
6394 if (w->current_matrix)
6396 mark_glyph_matrix (w->current_matrix);
6397 mark_glyph_matrix (w->desired_matrix);
6400 /* Filter out killed buffers from both buffer lists
6401 in attempt to help GC to reclaim killed buffers faster.
6402 We can do it elsewhere for live windows, but this is the
6403 best place to do it for dead windows. */
6404 wset_prev_buffers
6405 (w, mark_discard_killed_buffers (w->prev_buffers));
6406 wset_next_buffers
6407 (w, mark_discard_killed_buffers (w->next_buffers));
6409 break;
6411 case PVEC_HASH_TABLE:
6413 struct Lisp_Hash_Table *h = (struct Lisp_Hash_Table *) ptr;
6415 mark_vectorlike (ptr);
6416 mark_object (h->test.name);
6417 mark_object (h->test.user_hash_function);
6418 mark_object (h->test.user_cmp_function);
6419 /* If hash table is not weak, mark all keys and values.
6420 For weak tables, mark only the vector. */
6421 if (NILP (h->weak))
6422 mark_object (h->key_and_value);
6423 else
6424 VECTOR_MARK (XVECTOR (h->key_and_value));
6426 break;
6428 case PVEC_CHAR_TABLE:
6429 case PVEC_SUB_CHAR_TABLE:
6430 mark_char_table (ptr, (enum pvec_type) pvectype);
6431 break;
6433 case PVEC_BOOL_VECTOR:
6434 /* No Lisp_Objects to mark in a bool vector. */
6435 VECTOR_MARK (ptr);
6436 break;
6438 case PVEC_SUBR:
6439 break;
6441 case PVEC_FREE:
6442 emacs_abort ();
6444 default:
6445 mark_vectorlike (ptr);
6448 break;
6450 case Lisp_Symbol:
6452 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
6453 nextsym:
6454 if (ptr->gcmarkbit)
6455 break;
6456 CHECK_ALLOCATED_AND_LIVE_SYMBOL ();
6457 ptr->gcmarkbit = 1;
6458 /* Attempt to catch bogus objects. */
6459 eassert (valid_lisp_object_p (ptr->function));
6460 mark_object (ptr->function);
6461 mark_object (ptr->plist);
6462 switch (ptr->redirect)
6464 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
6465 case SYMBOL_VARALIAS:
6467 Lisp_Object tem;
6468 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
6469 mark_object (tem);
6470 break;
6472 case SYMBOL_LOCALIZED:
6473 mark_localized_symbol (ptr);
6474 break;
6475 case SYMBOL_FORWARDED:
6476 /* If the value is forwarded to a buffer or keyboard field,
6477 these are marked when we see the corresponding object.
6478 And if it's forwarded to a C variable, either it's not
6479 a Lisp_Object var, or it's staticpro'd already. */
6480 break;
6481 default: emacs_abort ();
6483 if (!PURE_P (XSTRING (ptr->name)))
6484 MARK_STRING (XSTRING (ptr->name));
6485 MARK_INTERVAL_TREE (string_intervals (ptr->name));
6486 /* Inner loop to mark next symbol in this bucket, if any. */
6487 po = ptr = ptr->next;
6488 if (ptr)
6489 goto nextsym;
6491 break;
6493 case Lisp_Misc:
6494 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
6496 if (XMISCANY (obj)->gcmarkbit)
6497 break;
6499 switch (XMISCTYPE (obj))
6501 case Lisp_Misc_Marker:
6502 /* DO NOT mark thru the marker's chain.
6503 The buffer's markers chain does not preserve markers from gc;
6504 instead, markers are removed from the chain when freed by gc. */
6505 XMISCANY (obj)->gcmarkbit = 1;
6506 break;
6508 case Lisp_Misc_Save_Value:
6509 XMISCANY (obj)->gcmarkbit = 1;
6510 mark_save_value (XSAVE_VALUE (obj));
6511 break;
6513 case Lisp_Misc_Overlay:
6514 mark_overlay (XOVERLAY (obj));
6515 break;
6517 case Lisp_Misc_Finalizer:
6518 XMISCANY (obj)->gcmarkbit = true;
6519 mark_object (XFINALIZER (obj)->function);
6520 break;
6522 #ifdef HAVE_MODULES
6523 case Lisp_Misc_User_Ptr:
6524 XMISCANY (obj)->gcmarkbit = true;
6525 break;
6526 #endif
6528 default:
6529 emacs_abort ();
6531 break;
6533 case Lisp_Cons:
6535 register struct Lisp_Cons *ptr = XCONS (obj);
6536 if (CONS_MARKED_P (ptr))
6537 break;
6538 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
6539 CONS_MARK (ptr);
6540 /* If the cdr is nil, avoid recursion for the car. */
6541 if (EQ (ptr->u.cdr, Qnil))
6543 obj = ptr->car;
6544 cdr_count = 0;
6545 goto loop;
6547 mark_object (ptr->car);
6548 obj = ptr->u.cdr;
6549 cdr_count++;
6550 if (cdr_count == mark_object_loop_halt)
6551 emacs_abort ();
6552 goto loop;
6555 case Lisp_Float:
6556 CHECK_ALLOCATED_AND_LIVE (live_float_p);
6557 FLOAT_MARK (XFLOAT (obj));
6558 break;
6560 case_Lisp_Int:
6561 break;
6563 default:
6564 emacs_abort ();
6567 #undef CHECK_LIVE
6568 #undef CHECK_ALLOCATED
6569 #undef CHECK_ALLOCATED_AND_LIVE
6571 /* Mark the Lisp pointers in the terminal objects.
6572 Called by Fgarbage_collect. */
6574 static void
6575 mark_terminals (void)
6577 struct terminal *t;
6578 for (t = terminal_list; t; t = t->next_terminal)
6580 eassert (t->name != NULL);
6581 #ifdef HAVE_WINDOW_SYSTEM
6582 /* If a terminal object is reachable from a stacpro'ed object,
6583 it might have been marked already. Make sure the image cache
6584 gets marked. */
6585 mark_image_cache (t->image_cache);
6586 #endif /* HAVE_WINDOW_SYSTEM */
6587 if (!VECTOR_MARKED_P (t))
6588 mark_vectorlike ((struct Lisp_Vector *)t);
6594 /* Value is non-zero if OBJ will survive the current GC because it's
6595 either marked or does not need to be marked to survive. */
6597 bool
6598 survives_gc_p (Lisp_Object obj)
6600 bool survives_p;
6602 switch (XTYPE (obj))
6604 case_Lisp_Int:
6605 survives_p = 1;
6606 break;
6608 case Lisp_Symbol:
6609 survives_p = XSYMBOL (obj)->gcmarkbit;
6610 break;
6612 case Lisp_Misc:
6613 survives_p = XMISCANY (obj)->gcmarkbit;
6614 break;
6616 case Lisp_String:
6617 survives_p = STRING_MARKED_P (XSTRING (obj));
6618 break;
6620 case Lisp_Vectorlike:
6621 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
6622 break;
6624 case Lisp_Cons:
6625 survives_p = CONS_MARKED_P (XCONS (obj));
6626 break;
6628 case Lisp_Float:
6629 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
6630 break;
6632 default:
6633 emacs_abort ();
6636 return survives_p || PURE_P (XPNTR (obj));
6642 NO_INLINE /* For better stack traces */
6643 static void
6644 sweep_conses (void)
6646 struct cons_block *cblk;
6647 struct cons_block **cprev = &cons_block;
6648 int lim = cons_block_index;
6649 EMACS_INT num_free = 0, num_used = 0;
6651 cons_free_list = 0;
6653 for (cblk = cons_block; cblk; cblk = *cprev)
6655 int i = 0;
6656 int this_free = 0;
6657 int ilim = (lim + BITS_PER_BITS_WORD - 1) / BITS_PER_BITS_WORD;
6659 /* Scan the mark bits an int at a time. */
6660 for (i = 0; i < ilim; i++)
6662 if (cblk->gcmarkbits[i] == BITS_WORD_MAX)
6664 /* Fast path - all cons cells for this int are marked. */
6665 cblk->gcmarkbits[i] = 0;
6666 num_used += BITS_PER_BITS_WORD;
6668 else
6670 /* Some cons cells for this int are not marked.
6671 Find which ones, and free them. */
6672 int start, pos, stop;
6674 start = i * BITS_PER_BITS_WORD;
6675 stop = lim - start;
6676 if (stop > BITS_PER_BITS_WORD)
6677 stop = BITS_PER_BITS_WORD;
6678 stop += start;
6680 for (pos = start; pos < stop; pos++)
6682 if (!CONS_MARKED_P (&cblk->conses[pos]))
6684 this_free++;
6685 cblk->conses[pos].u.chain = cons_free_list;
6686 cons_free_list = &cblk->conses[pos];
6687 cons_free_list->car = Vdead;
6689 else
6691 num_used++;
6692 CONS_UNMARK (&cblk->conses[pos]);
6698 lim = CONS_BLOCK_SIZE;
6699 /* If this block contains only free conses and we have already
6700 seen more than two blocks worth of free conses then deallocate
6701 this block. */
6702 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
6704 *cprev = cblk->next;
6705 /* Unhook from the free list. */
6706 cons_free_list = cblk->conses[0].u.chain;
6707 lisp_align_free (cblk);
6709 else
6711 num_free += this_free;
6712 cprev = &cblk->next;
6715 total_conses = num_used;
6716 total_free_conses = num_free;
6719 NO_INLINE /* For better stack traces */
6720 static void
6721 sweep_floats (void)
6723 register struct float_block *fblk;
6724 struct float_block **fprev = &float_block;
6725 register int lim = float_block_index;
6726 EMACS_INT num_free = 0, num_used = 0;
6728 float_free_list = 0;
6730 for (fblk = float_block; fblk; fblk = *fprev)
6732 register int i;
6733 int this_free = 0;
6734 for (i = 0; i < lim; i++)
6735 if (!FLOAT_MARKED_P (&fblk->floats[i]))
6737 this_free++;
6738 fblk->floats[i].u.chain = float_free_list;
6739 float_free_list = &fblk->floats[i];
6741 else
6743 num_used++;
6744 FLOAT_UNMARK (&fblk->floats[i]);
6746 lim = FLOAT_BLOCK_SIZE;
6747 /* If this block contains only free floats and we have already
6748 seen more than two blocks worth of free floats then deallocate
6749 this block. */
6750 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6752 *fprev = fblk->next;
6753 /* Unhook from the free list. */
6754 float_free_list = fblk->floats[0].u.chain;
6755 lisp_align_free (fblk);
6757 else
6759 num_free += this_free;
6760 fprev = &fblk->next;
6763 total_floats = num_used;
6764 total_free_floats = num_free;
6767 NO_INLINE /* For better stack traces */
6768 static void
6769 sweep_intervals (void)
6771 register struct interval_block *iblk;
6772 struct interval_block **iprev = &interval_block;
6773 register int lim = interval_block_index;
6774 EMACS_INT num_free = 0, num_used = 0;
6776 interval_free_list = 0;
6778 for (iblk = interval_block; iblk; iblk = *iprev)
6780 register int i;
6781 int this_free = 0;
6783 for (i = 0; i < lim; i++)
6785 if (!iblk->intervals[i].gcmarkbit)
6787 set_interval_parent (&iblk->intervals[i], interval_free_list);
6788 interval_free_list = &iblk->intervals[i];
6789 this_free++;
6791 else
6793 num_used++;
6794 iblk->intervals[i].gcmarkbit = 0;
6797 lim = INTERVAL_BLOCK_SIZE;
6798 /* If this block contains only free intervals and we have already
6799 seen more than two blocks worth of free intervals then
6800 deallocate this block. */
6801 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6803 *iprev = iblk->next;
6804 /* Unhook from the free list. */
6805 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
6806 lisp_free (iblk);
6808 else
6810 num_free += this_free;
6811 iprev = &iblk->next;
6814 total_intervals = num_used;
6815 total_free_intervals = num_free;
6818 NO_INLINE /* For better stack traces */
6819 static void
6820 sweep_symbols (void)
6822 struct symbol_block *sblk;
6823 struct symbol_block **sprev = &symbol_block;
6824 int lim = symbol_block_index;
6825 EMACS_INT num_free = 0, num_used = ARRAYELTS (lispsym);
6827 symbol_free_list = NULL;
6829 for (int i = 0; i < ARRAYELTS (lispsym); i++)
6830 lispsym[i].gcmarkbit = 0;
6832 for (sblk = symbol_block; sblk; sblk = *sprev)
6834 int this_free = 0;
6835 union aligned_Lisp_Symbol *sym = sblk->symbols;
6836 union aligned_Lisp_Symbol *end = sym + lim;
6838 for (; sym < end; ++sym)
6840 if (!sym->s.gcmarkbit)
6842 if (sym->s.redirect == SYMBOL_LOCALIZED)
6843 xfree (SYMBOL_BLV (&sym->s));
6844 sym->s.next = symbol_free_list;
6845 symbol_free_list = &sym->s;
6846 symbol_free_list->function = Vdead;
6847 ++this_free;
6849 else
6851 ++num_used;
6852 sym->s.gcmarkbit = 0;
6853 /* Attempt to catch bogus objects. */
6854 eassert (valid_lisp_object_p (sym->s.function));
6858 lim = SYMBOL_BLOCK_SIZE;
6859 /* If this block contains only free symbols and we have already
6860 seen more than two blocks worth of free symbols then deallocate
6861 this block. */
6862 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6864 *sprev = sblk->next;
6865 /* Unhook from the free list. */
6866 symbol_free_list = sblk->symbols[0].s.next;
6867 lisp_free (sblk);
6869 else
6871 num_free += this_free;
6872 sprev = &sblk->next;
6875 total_symbols = num_used;
6876 total_free_symbols = num_free;
6879 NO_INLINE /* For better stack traces. */
6880 static void
6881 sweep_misc (void)
6883 register struct marker_block *mblk;
6884 struct marker_block **mprev = &marker_block;
6885 register int lim = marker_block_index;
6886 EMACS_INT num_free = 0, num_used = 0;
6888 /* Put all unmarked misc's on free list. For a marker, first
6889 unchain it from the buffer it points into. */
6891 marker_free_list = 0;
6893 for (mblk = marker_block; mblk; mblk = *mprev)
6895 register int i;
6896 int this_free = 0;
6898 for (i = 0; i < lim; i++)
6900 if (!mblk->markers[i].m.u_any.gcmarkbit)
6902 if (mblk->markers[i].m.u_any.type == Lisp_Misc_Marker)
6903 unchain_marker (&mblk->markers[i].m.u_marker);
6904 else if (mblk->markers[i].m.u_any.type == Lisp_Misc_Finalizer)
6905 unchain_finalizer (&mblk->markers[i].m.u_finalizer);
6906 #ifdef HAVE_MODULES
6907 else if (mblk->markers[i].m.u_any.type == Lisp_Misc_User_Ptr)
6909 struct Lisp_User_Ptr *uptr = &mblk->markers[i].m.u_user_ptr;
6910 uptr->finalizer (uptr->p);
6912 #endif
6913 /* Set the type of the freed object to Lisp_Misc_Free.
6914 We could leave the type alone, since nobody checks it,
6915 but this might catch bugs faster. */
6916 mblk->markers[i].m.u_marker.type = Lisp_Misc_Free;
6917 mblk->markers[i].m.u_free.chain = marker_free_list;
6918 marker_free_list = &mblk->markers[i].m;
6919 this_free++;
6921 else
6923 num_used++;
6924 mblk->markers[i].m.u_any.gcmarkbit = 0;
6927 lim = MARKER_BLOCK_SIZE;
6928 /* If this block contains only free markers and we have already
6929 seen more than two blocks worth of free markers then deallocate
6930 this block. */
6931 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6933 *mprev = mblk->next;
6934 /* Unhook from the free list. */
6935 marker_free_list = mblk->markers[0].m.u_free.chain;
6936 lisp_free (mblk);
6938 else
6940 num_free += this_free;
6941 mprev = &mblk->next;
6945 total_markers = num_used;
6946 total_free_markers = num_free;
6949 NO_INLINE /* For better stack traces */
6950 static void
6951 sweep_buffers (void)
6953 register struct buffer *buffer, **bprev = &all_buffers;
6955 total_buffers = 0;
6956 for (buffer = all_buffers; buffer; buffer = *bprev)
6957 if (!VECTOR_MARKED_P (buffer))
6959 *bprev = buffer->next;
6960 lisp_free (buffer);
6962 else
6964 VECTOR_UNMARK (buffer);
6965 /* Do not use buffer_(set|get)_intervals here. */
6966 buffer->text->intervals = balance_intervals (buffer->text->intervals);
6967 total_buffers++;
6968 bprev = &buffer->next;
6972 /* Sweep: find all structures not marked, and free them. */
6973 static void
6974 gc_sweep (void)
6976 /* Remove or mark entries in weak hash tables.
6977 This must be done before any object is unmarked. */
6978 sweep_weak_hash_tables ();
6980 sweep_strings ();
6981 check_string_bytes (!noninteractive);
6982 sweep_conses ();
6983 sweep_floats ();
6984 sweep_intervals ();
6985 sweep_symbols ();
6986 sweep_misc ();
6987 sweep_buffers ();
6988 sweep_vectors ();
6989 check_string_bytes (!noninteractive);
6992 DEFUN ("memory-info", Fmemory_info, Smemory_info, 0, 0, 0,
6993 doc: /* Return a list of (TOTAL-RAM FREE-RAM TOTAL-SWAP FREE-SWAP).
6994 All values are in Kbytes. If there is no swap space,
6995 last two values are zero. If the system is not supported
6996 or memory information can't be obtained, return nil. */)
6997 (void)
6999 #if defined HAVE_LINUX_SYSINFO
7000 struct sysinfo si;
7001 uintmax_t units;
7003 if (sysinfo (&si))
7004 return Qnil;
7005 #ifdef LINUX_SYSINFO_UNIT
7006 units = si.mem_unit;
7007 #else
7008 units = 1;
7009 #endif
7010 return list4i ((uintmax_t) si.totalram * units / 1024,
7011 (uintmax_t) si.freeram * units / 1024,
7012 (uintmax_t) si.totalswap * units / 1024,
7013 (uintmax_t) si.freeswap * units / 1024);
7014 #elif defined WINDOWSNT
7015 unsigned long long totalram, freeram, totalswap, freeswap;
7017 if (w32_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
7018 return list4i ((uintmax_t) totalram / 1024,
7019 (uintmax_t) freeram / 1024,
7020 (uintmax_t) totalswap / 1024,
7021 (uintmax_t) freeswap / 1024);
7022 else
7023 return Qnil;
7024 #elif defined MSDOS
7025 unsigned long totalram, freeram, totalswap, freeswap;
7027 if (dos_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
7028 return list4i ((uintmax_t) totalram / 1024,
7029 (uintmax_t) freeram / 1024,
7030 (uintmax_t) totalswap / 1024,
7031 (uintmax_t) freeswap / 1024);
7032 else
7033 return Qnil;
7034 #else /* not HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
7035 /* FIXME: add more systems. */
7036 return Qnil;
7037 #endif /* HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
7040 /* Debugging aids. */
7042 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
7043 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
7044 This may be helpful in debugging Emacs's memory usage.
7045 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
7046 (void)
7048 Lisp_Object end;
7050 #ifdef HAVE_NS
7051 /* Avoid warning. sbrk has no relation to memory allocated anyway. */
7052 XSETINT (end, 0);
7053 #else
7054 XSETINT (end, (intptr_t) (char *) sbrk (0) / 1024);
7055 #endif
7057 return end;
7060 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
7061 doc: /* Return a list of counters that measure how much consing there has been.
7062 Each of these counters increments for a certain kind of object.
7063 The counters wrap around from the largest positive integer to zero.
7064 Garbage collection does not decrease them.
7065 The elements of the value are as follows:
7066 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
7067 All are in units of 1 = one object consed
7068 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
7069 objects consed.
7070 MISCS include overlays, markers, and some internal types.
7071 Frames, windows, buffers, and subprocesses count as vectors
7072 (but the contents of a buffer's text do not count here). */)
7073 (void)
7075 return listn (CONSTYPE_HEAP, 8,
7076 bounded_number (cons_cells_consed),
7077 bounded_number (floats_consed),
7078 bounded_number (vector_cells_consed),
7079 bounded_number (symbols_consed),
7080 bounded_number (string_chars_consed),
7081 bounded_number (misc_objects_consed),
7082 bounded_number (intervals_consed),
7083 bounded_number (strings_consed));
7086 static bool
7087 symbol_uses_obj (Lisp_Object symbol, Lisp_Object obj)
7089 struct Lisp_Symbol *sym = XSYMBOL (symbol);
7090 Lisp_Object val = find_symbol_value (symbol);
7091 return (EQ (val, obj)
7092 || EQ (sym->function, obj)
7093 || (!NILP (sym->function)
7094 && COMPILEDP (sym->function)
7095 && EQ (AREF (sym->function, COMPILED_BYTECODE), obj))
7096 || (!NILP (val)
7097 && COMPILEDP (val)
7098 && EQ (AREF (val, COMPILED_BYTECODE), obj)));
7101 /* Find at most FIND_MAX symbols which have OBJ as their value or
7102 function. This is used in gdbinit's `xwhichsymbols' command. */
7104 Lisp_Object
7105 which_symbols (Lisp_Object obj, EMACS_INT find_max)
7107 struct symbol_block *sblk;
7108 ptrdiff_t gc_count = inhibit_garbage_collection ();
7109 Lisp_Object found = Qnil;
7111 if (! DEADP (obj))
7113 for (int i = 0; i < ARRAYELTS (lispsym); i++)
7115 Lisp_Object sym = builtin_lisp_symbol (i);
7116 if (symbol_uses_obj (sym, obj))
7118 found = Fcons (sym, found);
7119 if (--find_max == 0)
7120 goto out;
7124 for (sblk = symbol_block; sblk; sblk = sblk->next)
7126 union aligned_Lisp_Symbol *aligned_sym = sblk->symbols;
7127 int bn;
7129 for (bn = 0; bn < SYMBOL_BLOCK_SIZE; bn++, aligned_sym++)
7131 if (sblk == symbol_block && bn >= symbol_block_index)
7132 break;
7134 Lisp_Object sym = make_lisp_symbol (&aligned_sym->s);
7135 if (symbol_uses_obj (sym, obj))
7137 found = Fcons (sym, found);
7138 if (--find_max == 0)
7139 goto out;
7145 out:
7146 unbind_to (gc_count, Qnil);
7147 return found;
7150 #ifdef SUSPICIOUS_OBJECT_CHECKING
7152 static void *
7153 find_suspicious_object_in_range (void *begin, void *end)
7155 char *begin_a = begin;
7156 char *end_a = end;
7157 int i;
7159 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
7161 char *suspicious_object = suspicious_objects[i];
7162 if (begin_a <= suspicious_object && suspicious_object < end_a)
7163 return suspicious_object;
7166 return NULL;
7169 static void
7170 note_suspicious_free (void* ptr)
7172 struct suspicious_free_record* rec;
7174 rec = &suspicious_free_history[suspicious_free_history_index++];
7175 if (suspicious_free_history_index ==
7176 ARRAYELTS (suspicious_free_history))
7178 suspicious_free_history_index = 0;
7181 memset (rec, 0, sizeof (*rec));
7182 rec->suspicious_object = ptr;
7183 backtrace (&rec->backtrace[0], ARRAYELTS (rec->backtrace));
7186 static void
7187 detect_suspicious_free (void* ptr)
7189 int i;
7191 eassert (ptr != NULL);
7193 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
7194 if (suspicious_objects[i] == ptr)
7196 note_suspicious_free (ptr);
7197 suspicious_objects[i] = NULL;
7201 #endif /* SUSPICIOUS_OBJECT_CHECKING */
7203 DEFUN ("suspicious-object", Fsuspicious_object, Ssuspicious_object, 1, 1, 0,
7204 doc: /* Return OBJ, maybe marking it for extra scrutiny.
7205 If Emacs is compiled with suspicious object checking, capture
7206 a stack trace when OBJ is freed in order to help track down
7207 garbage collection bugs. Otherwise, do nothing and return OBJ. */)
7208 (Lisp_Object obj)
7210 #ifdef SUSPICIOUS_OBJECT_CHECKING
7211 /* Right now, we care only about vectors. */
7212 if (VECTORLIKEP (obj))
7214 suspicious_objects[suspicious_object_index++] = XVECTOR (obj);
7215 if (suspicious_object_index == ARRAYELTS (suspicious_objects))
7216 suspicious_object_index = 0;
7218 #endif
7219 return obj;
7222 #ifdef ENABLE_CHECKING
7224 bool suppress_checking;
7226 void
7227 die (const char *msg, const char *file, int line)
7229 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: assertion failed: %s\r\n",
7230 file, line, msg);
7231 terminate_due_to_signal (SIGABRT, INT_MAX);
7234 #endif /* ENABLE_CHECKING */
7236 #if defined (ENABLE_CHECKING) && USE_STACK_LISP_OBJECTS
7238 /* Stress alloca with inconveniently sized requests and check
7239 whether all allocated areas may be used for Lisp_Object. */
7241 NO_INLINE static void
7242 verify_alloca (void)
7244 int i;
7245 enum { ALLOCA_CHECK_MAX = 256 };
7246 /* Start from size of the smallest Lisp object. */
7247 for (i = sizeof (struct Lisp_Cons); i <= ALLOCA_CHECK_MAX; i++)
7249 void *ptr = alloca (i);
7250 make_lisp_ptr (ptr, Lisp_Cons);
7254 #else /* not ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7256 #define verify_alloca() ((void) 0)
7258 #endif /* ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7260 /* Initialization. */
7262 void
7263 init_alloc_once (void)
7265 /* Even though Qt's contents are not set up, its address is known. */
7266 Vpurify_flag = Qt;
7268 purebeg = PUREBEG;
7269 pure_size = PURESIZE;
7271 verify_alloca ();
7272 init_finalizer_list (&finalizers);
7273 init_finalizer_list (&doomed_finalizers);
7275 mem_init ();
7276 Vdead = make_pure_string ("DEAD", 4, 4, 0);
7278 #ifdef DOUG_LEA_MALLOC
7279 mallopt (M_TRIM_THRESHOLD, 128 * 1024); /* Trim threshold. */
7280 mallopt (M_MMAP_THRESHOLD, 64 * 1024); /* Mmap threshold. */
7281 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* Max. number of mmap'ed areas. */
7282 #endif
7283 init_strings ();
7284 init_vectors ();
7286 refill_memory_reserve ();
7287 gc_cons_threshold = GC_DEFAULT_THRESHOLD;
7290 void
7291 init_alloc (void)
7293 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
7294 setjmp_tested_p = longjmps_done = 0;
7295 #endif
7296 Vgc_elapsed = make_float (0.0);
7297 gcs_done = 0;
7299 #if USE_VALGRIND
7300 valgrind_p = RUNNING_ON_VALGRIND != 0;
7301 #endif
7304 void
7305 syms_of_alloc (void)
7307 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
7308 doc: /* Number of bytes of consing between garbage collections.
7309 Garbage collection can happen automatically once this many bytes have been
7310 allocated since the last garbage collection. All data types count.
7312 Garbage collection happens automatically only when `eval' is called.
7314 By binding this temporarily to a large number, you can effectively
7315 prevent garbage collection during a part of the program.
7316 See also `gc-cons-percentage'. */);
7318 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
7319 doc: /* Portion of the heap used for allocation.
7320 Garbage collection can happen automatically once this portion of the heap
7321 has been allocated since the last garbage collection.
7322 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
7323 Vgc_cons_percentage = make_float (0.1);
7325 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
7326 doc: /* Number of bytes of shareable Lisp data allocated so far. */);
7328 DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
7329 doc: /* Number of cons cells that have been consed so far. */);
7331 DEFVAR_INT ("floats-consed", floats_consed,
7332 doc: /* Number of floats that have been consed so far. */);
7334 DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
7335 doc: /* Number of vector cells that have been consed so far. */);
7337 DEFVAR_INT ("symbols-consed", symbols_consed,
7338 doc: /* Number of symbols that have been consed so far. */);
7339 symbols_consed += ARRAYELTS (lispsym);
7341 DEFVAR_INT ("string-chars-consed", string_chars_consed,
7342 doc: /* Number of string characters that have been consed so far. */);
7344 DEFVAR_INT ("misc-objects-consed", misc_objects_consed,
7345 doc: /* Number of miscellaneous objects that have been consed so far.
7346 These include markers and overlays, plus certain objects not visible
7347 to users. */);
7349 DEFVAR_INT ("intervals-consed", intervals_consed,
7350 doc: /* Number of intervals that have been consed so far. */);
7352 DEFVAR_INT ("strings-consed", strings_consed,
7353 doc: /* Number of strings that have been consed so far. */);
7355 DEFVAR_LISP ("purify-flag", Vpurify_flag,
7356 doc: /* Non-nil means loading Lisp code in order to dump an executable.
7357 This means that certain objects should be allocated in shared (pure) space.
7358 It can also be set to a hash-table, in which case this table is used to
7359 do hash-consing of the objects allocated to pure space. */);
7361 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
7362 doc: /* Non-nil means display messages at start and end of garbage collection. */);
7363 garbage_collection_messages = 0;
7365 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
7366 doc: /* Hook run after garbage collection has finished. */);
7367 Vpost_gc_hook = Qnil;
7368 DEFSYM (Qpost_gc_hook, "post-gc-hook");
7370 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
7371 doc: /* Precomputed `signal' argument for memory-full error. */);
7372 /* We build this in advance because if we wait until we need it, we might
7373 not be able to allocate the memory to hold it. */
7374 Vmemory_signal_data
7375 = listn (CONSTYPE_PURE, 2, Qerror,
7376 build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
7378 DEFVAR_LISP ("memory-full", Vmemory_full,
7379 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
7380 Vmemory_full = Qnil;
7382 DEFSYM (Qconses, "conses");
7383 DEFSYM (Qsymbols, "symbols");
7384 DEFSYM (Qmiscs, "miscs");
7385 DEFSYM (Qstrings, "strings");
7386 DEFSYM (Qvectors, "vectors");
7387 DEFSYM (Qfloats, "floats");
7388 DEFSYM (Qintervals, "intervals");
7389 DEFSYM (Qbuffers, "buffers");
7390 DEFSYM (Qstring_bytes, "string-bytes");
7391 DEFSYM (Qvector_slots, "vector-slots");
7392 DEFSYM (Qheap, "heap");
7393 DEFSYM (QAutomatic_GC, "Automatic GC");
7395 DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
7396 DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
7398 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
7399 doc: /* Accumulated time elapsed in garbage collections.
7400 The time is in seconds as a floating point value. */);
7401 DEFVAR_INT ("gcs-done", gcs_done,
7402 doc: /* Accumulated number of garbage collections done. */);
7404 defsubr (&Scons);
7405 defsubr (&Slist);
7406 defsubr (&Svector);
7407 defsubr (&Sbool_vector);
7408 defsubr (&Smake_byte_code);
7409 defsubr (&Smake_list);
7410 defsubr (&Smake_vector);
7411 defsubr (&Smake_string);
7412 defsubr (&Smake_bool_vector);
7413 defsubr (&Smake_symbol);
7414 defsubr (&Smake_marker);
7415 defsubr (&Smake_finalizer);
7416 defsubr (&Spurecopy);
7417 defsubr (&Sgarbage_collect);
7418 defsubr (&Smemory_limit);
7419 defsubr (&Smemory_info);
7420 defsubr (&Smemory_use_counts);
7421 defsubr (&Ssuspicious_object);
7424 /* When compiled with GCC, GDB might say "No enum type named
7425 pvec_type" if we don't have at least one symbol with that type, and
7426 then xbacktrace could fail. Similarly for the other enums and
7427 their values. Some non-GCC compilers don't like these constructs. */
7428 #ifdef __GNUC__
7429 union
7431 enum CHARTAB_SIZE_BITS CHARTAB_SIZE_BITS;
7432 enum char_table_specials char_table_specials;
7433 enum char_bits char_bits;
7434 enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE;
7435 enum DEFAULT_HASH_SIZE DEFAULT_HASH_SIZE;
7436 enum Lisp_Bits Lisp_Bits;
7437 enum Lisp_Compiled Lisp_Compiled;
7438 enum maxargs maxargs;
7439 enum MAX_ALLOCA MAX_ALLOCA;
7440 enum More_Lisp_Bits More_Lisp_Bits;
7441 enum pvec_type pvec_type;
7442 } const EXTERNALLY_VISIBLE gdb_make_enums_visible = {0};
7443 #endif /* __GNUC__ */