Prevent spurious recognition of K&R argument declarations. Fixes bug #2203
[emacs.git] / src / alloc.c
blob03dacc77c6ef7e828aa87ec178adf231a563e69f
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
11 (at 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 <stdio.h>
24 #include <limits.h> /* For CHAR_BIT. */
26 #ifdef ENABLE_CHECKING
27 #include <signal.h> /* For SIGABRT. */
28 #endif
30 #ifdef HAVE_PTHREAD
31 #include <pthread.h>
32 #endif
34 #include "lisp.h"
35 #include "dispextern.h"
36 #include "intervals.h"
37 #include "puresize.h"
38 #include "systime.h"
39 #include "character.h"
40 #include "buffer.h"
41 #include "window.h"
42 #include "keyboard.h"
43 #include "frame.h"
44 #include "blockinput.h"
45 #include "termhooks.h" /* For struct terminal. */
46 #ifdef HAVE_WINDOW_SYSTEM
47 #include TERM_HEADER
48 #endif /* HAVE_WINDOW_SYSTEM */
50 #include <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 #if (defined ENABLE_CHECKING \
62 && defined HAVE_VALGRIND_VALGRIND_H \
63 && !defined USE_VALGRIND)
64 # define USE_VALGRIND 1
65 #endif
67 #if USE_VALGRIND
68 #include <valgrind/valgrind.h>
69 #include <valgrind/memcheck.h>
70 static bool valgrind_p;
71 #endif
73 /* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects. */
75 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
76 memory. Can do this only if using gmalloc.c and if not checking
77 marked objects. */
79 #if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
80 || defined HYBRID_MALLOC || defined GC_CHECK_MARKED_OBJECTS)
81 #undef GC_MALLOC_CHECK
82 #endif
84 #include <unistd.h>
85 #include <fcntl.h>
87 #ifdef USE_GTK
88 # include "gtkutil.h"
89 #endif
90 #ifdef WINDOWSNT
91 #include "w32.h"
92 #include "w32heap.h" /* for sbrk */
93 #endif
95 #ifdef DOUG_LEA_MALLOC
97 #include <malloc.h>
99 /* Specify maximum number of areas to mmap. It would be nice to use a
100 value that explicitly means "no limit". */
102 #define MMAP_MAX_AREAS 100000000
104 #endif /* not DOUG_LEA_MALLOC */
106 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
107 to a struct Lisp_String. */
109 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
110 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
111 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
113 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
114 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
115 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
117 /* Default value of gc_cons_threshold (see below). */
119 #define GC_DEFAULT_THRESHOLD (100000 * word_size)
121 /* Global variables. */
122 struct emacs_globals globals;
124 /* Number of bytes of consing done since the last gc. */
126 EMACS_INT consing_since_gc;
128 /* Similar minimum, computed from Vgc_cons_percentage. */
130 EMACS_INT gc_relative_threshold;
132 /* Minimum number of bytes of consing since GC before next GC,
133 when memory is full. */
135 EMACS_INT memory_full_cons_threshold;
137 /* True during GC. */
139 bool gc_in_progress;
141 /* True means abort if try to GC.
142 This is for code which is written on the assumption that
143 no GC will happen, so as to verify that assumption. */
145 bool abort_on_gc;
147 /* Number of live and free conses etc. */
149 static EMACS_INT total_conses, total_markers, total_symbols, total_buffers;
150 static EMACS_INT total_free_conses, total_free_markers, total_free_symbols;
151 static EMACS_INT total_free_floats, total_floats;
153 /* Points to memory space allocated as "spare", to be freed if we run
154 out of memory. We keep one large block, four cons-blocks, and
155 two string blocks. */
157 static char *spare_memory[7];
159 /* Amount of spare memory to keep in large reserve block, or to see
160 whether this much is available when malloc fails on a larger request. */
162 #define SPARE_MEMORY (1 << 14)
164 /* Initialize it to a nonzero value to force it into data space
165 (rather than bss space). That way unexec will remap it into text
166 space (pure), on some systems. We have not implemented the
167 remapping on more recent systems because this is less important
168 nowadays than in the days of small memories and timesharing. */
170 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
171 #define PUREBEG (char *) pure
173 /* Pointer to the pure area, and its size. */
175 static char *purebeg;
176 static ptrdiff_t pure_size;
178 /* Number of bytes of pure storage used before pure storage overflowed.
179 If this is non-zero, this implies that an overflow occurred. */
181 static ptrdiff_t pure_bytes_used_before_overflow;
183 /* Index in pure at which next pure Lisp object will be allocated.. */
185 static ptrdiff_t pure_bytes_used_lisp;
187 /* Number of bytes allocated for non-Lisp objects in pure storage. */
189 static ptrdiff_t pure_bytes_used_non_lisp;
191 /* If nonzero, this is a warning delivered by malloc and not yet
192 displayed. */
194 const char *pending_malloc_warning;
196 #if 0 /* Normally, pointer sanity only on request... */
197 #ifdef ENABLE_CHECKING
198 #define SUSPICIOUS_OBJECT_CHECKING 1
199 #endif
200 #endif
202 /* ... but unconditionally use SUSPICIOUS_OBJECT_CHECKING while the GC
203 bug is unresolved. */
204 #define SUSPICIOUS_OBJECT_CHECKING 1
206 #ifdef SUSPICIOUS_OBJECT_CHECKING
207 struct suspicious_free_record
209 void *suspicious_object;
210 void *backtrace[128];
212 static void *suspicious_objects[32];
213 static int suspicious_object_index;
214 struct suspicious_free_record suspicious_free_history[64] EXTERNALLY_VISIBLE;
215 static int suspicious_free_history_index;
216 /* Find the first currently-monitored suspicious pointer in range
217 [begin,end) or NULL if no such pointer exists. */
218 static void *find_suspicious_object_in_range (void *begin, void *end);
219 static void detect_suspicious_free (void *ptr);
220 #else
221 # define find_suspicious_object_in_range(begin, end) NULL
222 # define detect_suspicious_free(ptr) (void)
223 #endif
225 /* Maximum amount of C stack to save when a GC happens. */
227 #ifndef MAX_SAVE_STACK
228 #define MAX_SAVE_STACK 16000
229 #endif
231 /* Buffer in which we save a copy of the C stack at each GC. */
233 #if MAX_SAVE_STACK > 0
234 static char *stack_copy;
235 static ptrdiff_t stack_copy_size;
237 /* Copy to DEST a block of memory from SRC of size SIZE bytes,
238 avoiding any address sanitization. */
240 static void * ATTRIBUTE_NO_SANITIZE_ADDRESS
241 no_sanitize_memcpy (void *dest, void const *src, size_t size)
243 if (! ADDRESS_SANITIZER)
244 return memcpy (dest, src, size);
245 else
247 size_t i;
248 char *d = dest;
249 char const *s = src;
250 for (i = 0; i < size; i++)
251 d[i] = s[i];
252 return dest;
256 #endif /* MAX_SAVE_STACK > 0 */
258 static void mark_terminals (void);
259 static void gc_sweep (void);
260 static Lisp_Object make_pure_vector (ptrdiff_t);
261 static void mark_buffer (struct buffer *);
263 #if !defined REL_ALLOC || defined SYSTEM_MALLOC || defined HYBRID_MALLOC
264 static void refill_memory_reserve (void);
265 #endif
266 static void compact_small_strings (void);
267 static void free_large_strings (void);
268 extern Lisp_Object which_symbols (Lisp_Object, EMACS_INT) EXTERNALLY_VISIBLE;
270 /* When scanning the C stack for live Lisp objects, Emacs keeps track of
271 what memory allocated via lisp_malloc and lisp_align_malloc is intended
272 for what purpose. This enumeration specifies the type of memory. */
274 enum mem_type
276 MEM_TYPE_NON_LISP,
277 MEM_TYPE_BUFFER,
278 MEM_TYPE_CONS,
279 MEM_TYPE_STRING,
280 MEM_TYPE_MISC,
281 MEM_TYPE_SYMBOL,
282 MEM_TYPE_FLOAT,
283 /* Since all non-bool pseudovectors are small enough to be
284 allocated from vector blocks, this memory type denotes
285 large regular vectors and large bool pseudovectors. */
286 MEM_TYPE_VECTORLIKE,
287 /* Special type to denote vector blocks. */
288 MEM_TYPE_VECTOR_BLOCK,
289 /* Special type to denote reserved memory. */
290 MEM_TYPE_SPARE
293 /* A unique object in pure space used to make some Lisp objects
294 on free lists recognizable in O(1). */
296 static Lisp_Object Vdead;
297 #define DEADP(x) EQ (x, Vdead)
299 #ifdef GC_MALLOC_CHECK
301 enum mem_type allocated_mem_type;
303 #endif /* GC_MALLOC_CHECK */
305 /* A node in the red-black tree describing allocated memory containing
306 Lisp data. Each such block is recorded with its start and end
307 address when it is allocated, and removed from the tree when it
308 is freed.
310 A red-black tree is a balanced binary tree with the following
311 properties:
313 1. Every node is either red or black.
314 2. Every leaf is black.
315 3. If a node is red, then both of its children are black.
316 4. Every simple path from a node to a descendant leaf contains
317 the same number of black nodes.
318 5. The root is always black.
320 When nodes are inserted into the tree, or deleted from the tree,
321 the tree is "fixed" so that these properties are always true.
323 A red-black tree with N internal nodes has height at most 2
324 log(N+1). Searches, insertions and deletions are done in O(log N).
325 Please see a text book about data structures for a detailed
326 description of red-black trees. Any book worth its salt should
327 describe them. */
329 struct mem_node
331 /* Children of this node. These pointers are never NULL. When there
332 is no child, the value is MEM_NIL, which points to a dummy node. */
333 struct mem_node *left, *right;
335 /* The parent of this node. In the root node, this is NULL. */
336 struct mem_node *parent;
338 /* Start and end of allocated region. */
339 void *start, *end;
341 /* Node color. */
342 enum {MEM_BLACK, MEM_RED} color;
344 /* Memory type. */
345 enum mem_type type;
348 /* Base address of stack. Set in main. */
350 Lisp_Object *stack_base;
352 /* Root of the tree describing allocated Lisp memory. */
354 static struct mem_node *mem_root;
356 /* Lowest and highest known address in the heap. */
358 static void *min_heap_address, *max_heap_address;
360 /* Sentinel node of the tree. */
362 static struct mem_node mem_z;
363 #define MEM_NIL &mem_z
365 static struct mem_node *mem_insert (void *, void *, enum mem_type);
366 static void mem_insert_fixup (struct mem_node *);
367 static void mem_rotate_left (struct mem_node *);
368 static void mem_rotate_right (struct mem_node *);
369 static void mem_delete (struct mem_node *);
370 static void mem_delete_fixup (struct mem_node *);
371 static struct mem_node *mem_find (void *);
373 #ifndef DEADP
374 # define DEADP(x) 0
375 #endif
377 /* Addresses of staticpro'd variables. Initialize it to a nonzero
378 value; otherwise some compilers put it into BSS. */
380 enum { NSTATICS = 2048 };
381 static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
383 /* Index of next unused slot in staticvec. */
385 static int staticidx;
387 static void *pure_alloc (size_t, int);
389 /* Return X rounded to the next multiple of Y. Arguments should not
390 have side effects, as they are evaluated more than once. Assume X
391 + Y - 1 does not overflow. Tune for Y being a power of 2. */
393 #define ROUNDUP(x, y) ((y) & ((y) - 1) \
394 ? ((x) + (y) - 1) - ((x) + (y) - 1) % (y) \
395 : ((x) + (y) - 1) & ~ ((y) - 1))
397 /* Return PTR rounded up to the next multiple of ALIGNMENT. */
399 static void *
400 ALIGN (void *ptr, int alignment)
402 return (void *) ROUNDUP ((uintptr_t) ptr, alignment);
405 /* Extract the pointer hidden within A, if A is not a symbol.
406 If A is a symbol, extract the hidden pointer's offset from lispsym,
407 converted to void *. */
409 #define macro_XPNTR_OR_SYMBOL_OFFSET(a) \
410 ((void *) (intptr_t) (USE_LSB_TAG ? XLI (a) - XTYPE (a) : XLI (a) & VALMASK))
412 /* Extract the pointer hidden within A. */
414 #define macro_XPNTR(a) \
415 ((void *) ((intptr_t) XPNTR_OR_SYMBOL_OFFSET (a) \
416 + (SYMBOLP (a) ? (char *) lispsym : NULL)))
418 /* For pointer access, define XPNTR and XPNTR_OR_SYMBOL_OFFSET as
419 functions, as functions are cleaner and can be used in debuggers.
420 Also, define them as macros if being compiled with GCC without
421 optimization, for performance in that case. The macro_* names are
422 private to this section of code. */
424 static ATTRIBUTE_UNUSED void *
425 XPNTR_OR_SYMBOL_OFFSET (Lisp_Object a)
427 return macro_XPNTR_OR_SYMBOL_OFFSET (a);
429 static ATTRIBUTE_UNUSED void *
430 XPNTR (Lisp_Object a)
432 return macro_XPNTR (a);
435 #if DEFINE_KEY_OPS_AS_MACROS
436 # define XPNTR_OR_SYMBOL_OFFSET(a) macro_XPNTR_OR_SYMBOL_OFFSET (a)
437 # define XPNTR(a) macro_XPNTR (a)
438 #endif
440 static void
441 XFLOAT_INIT (Lisp_Object f, double n)
443 XFLOAT (f)->u.data = n;
446 #ifdef DOUG_LEA_MALLOC
447 static bool
448 pointers_fit_in_lispobj_p (void)
450 return (UINTPTR_MAX <= VAL_MAX) || USE_LSB_TAG;
453 static bool
454 mmap_lisp_allowed_p (void)
456 /* If we can't store all memory addresses in our lisp objects, it's
457 risky to let the heap use mmap and give us addresses from all
458 over our address space. We also can't use mmap for lisp objects
459 if we might dump: unexec doesn't preserve the contents of mmapped
460 regions. */
461 return pointers_fit_in_lispobj_p () && !might_dump;
463 #endif
465 /* Head of a circularly-linked list of extant finalizers. */
466 static struct Lisp_Finalizer finalizers;
468 /* Head of a circularly-linked list of finalizers that must be invoked
469 because we deemed them unreachable. This list must be global, and
470 not a local inside garbage_collect_1, in case we GC again while
471 running finalizers. */
472 static struct Lisp_Finalizer doomed_finalizers;
475 /************************************************************************
476 Malloc
477 ************************************************************************/
479 /* Function malloc calls this if it finds we are near exhausting storage. */
481 void
482 malloc_warning (const char *str)
484 pending_malloc_warning = str;
488 /* Display an already-pending malloc warning. */
490 void
491 display_malloc_warning (void)
493 call3 (intern ("display-warning"),
494 intern ("alloc"),
495 build_string (pending_malloc_warning),
496 intern ("emergency"));
497 pending_malloc_warning = 0;
500 /* Called if we can't allocate relocatable space for a buffer. */
502 void
503 buffer_memory_full (ptrdiff_t nbytes)
505 /* If buffers use the relocating allocator, no need to free
506 spare_memory, because we may have plenty of malloc space left
507 that we could get, and if we don't, the malloc that fails will
508 itself cause spare_memory to be freed. If buffers don't use the
509 relocating allocator, treat this like any other failing
510 malloc. */
512 #ifndef REL_ALLOC
513 memory_full (nbytes);
514 #else
515 /* This used to call error, but if we've run out of memory, we could
516 get infinite recursion trying to build the string. */
517 xsignal (Qnil, Vmemory_signal_data);
518 #endif
521 /* A common multiple of the positive integers A and B. Ideally this
522 would be the least common multiple, but there's no way to do that
523 as a constant expression in C, so do the best that we can easily do. */
524 #define COMMON_MULTIPLE(a, b) \
525 ((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
527 #ifndef XMALLOC_OVERRUN_CHECK
528 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
529 #else
531 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
532 around each block.
534 The header consists of XMALLOC_OVERRUN_CHECK_SIZE fixed bytes
535 followed by XMALLOC_OVERRUN_SIZE_SIZE bytes containing the original
536 block size in little-endian order. The trailer consists of
537 XMALLOC_OVERRUN_CHECK_SIZE fixed bytes.
539 The header is used to detect whether this block has been allocated
540 through these functions, as some low-level libc functions may
541 bypass the malloc hooks. */
543 #define XMALLOC_OVERRUN_CHECK_SIZE 16
544 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
545 (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)
547 /* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
548 hold a size_t value and (2) the header size is a multiple of the
549 alignment that Emacs needs for C types and for USE_LSB_TAG. */
550 #define XMALLOC_BASE_ALIGNMENT alignof (max_align_t)
552 #define XMALLOC_HEADER_ALIGNMENT \
553 COMMON_MULTIPLE (GCALIGNMENT, XMALLOC_BASE_ALIGNMENT)
554 #define XMALLOC_OVERRUN_SIZE_SIZE \
555 (((XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t) \
556 + XMALLOC_HEADER_ALIGNMENT - 1) \
557 / XMALLOC_HEADER_ALIGNMENT * XMALLOC_HEADER_ALIGNMENT) \
558 - XMALLOC_OVERRUN_CHECK_SIZE)
560 static char const xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE] =
561 { '\x9a', '\x9b', '\xae', '\xaf',
562 '\xbf', '\xbe', '\xce', '\xcf',
563 '\xea', '\xeb', '\xec', '\xed',
564 '\xdf', '\xde', '\x9c', '\x9d' };
566 static char const xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
567 { '\xaa', '\xab', '\xac', '\xad',
568 '\xba', '\xbb', '\xbc', '\xbd',
569 '\xca', '\xcb', '\xcc', '\xcd',
570 '\xda', '\xdb', '\xdc', '\xdd' };
572 /* Insert and extract the block size in the header. */
574 static void
575 xmalloc_put_size (unsigned char *ptr, size_t size)
577 int i;
578 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
580 *--ptr = size & ((1 << CHAR_BIT) - 1);
581 size >>= CHAR_BIT;
585 static size_t
586 xmalloc_get_size (unsigned char *ptr)
588 size_t size = 0;
589 int i;
590 ptr -= XMALLOC_OVERRUN_SIZE_SIZE;
591 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
593 size <<= CHAR_BIT;
594 size += *ptr++;
596 return size;
600 /* Like malloc, but wraps allocated block with header and trailer. */
602 static void *
603 overrun_check_malloc (size_t size)
605 register unsigned char *val;
606 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
607 emacs_abort ();
609 val = malloc (size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
610 if (val)
612 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
613 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
614 xmalloc_put_size (val, size);
615 memcpy (val + size, xmalloc_overrun_check_trailer,
616 XMALLOC_OVERRUN_CHECK_SIZE);
618 return val;
622 /* Like realloc, but checks old block for overrun, and wraps new block
623 with header and trailer. */
625 static void *
626 overrun_check_realloc (void *block, size_t size)
628 register unsigned char *val = (unsigned char *) block;
629 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
630 emacs_abort ();
632 if (val
633 && memcmp (xmalloc_overrun_check_header,
634 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
635 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
637 size_t osize = xmalloc_get_size (val);
638 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
639 XMALLOC_OVERRUN_CHECK_SIZE))
640 emacs_abort ();
641 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
642 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
643 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
646 val = realloc (val, size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
648 if (val)
650 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
651 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
652 xmalloc_put_size (val, size);
653 memcpy (val + size, xmalloc_overrun_check_trailer,
654 XMALLOC_OVERRUN_CHECK_SIZE);
656 return val;
659 /* Like free, but checks block for overrun. */
661 static void
662 overrun_check_free (void *block)
664 unsigned char *val = (unsigned char *) block;
666 if (val
667 && memcmp (xmalloc_overrun_check_header,
668 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
669 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
671 size_t osize = xmalloc_get_size (val);
672 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
673 XMALLOC_OVERRUN_CHECK_SIZE))
674 emacs_abort ();
675 #ifdef XMALLOC_CLEAR_FREE_MEMORY
676 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
677 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_OVERHEAD);
678 #else
679 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
680 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
681 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
682 #endif
685 free (val);
688 #undef malloc
689 #undef realloc
690 #undef free
691 #define malloc overrun_check_malloc
692 #define realloc overrun_check_realloc
693 #define free overrun_check_free
694 #endif
696 /* If compiled with XMALLOC_BLOCK_INPUT_CHECK, define a symbol
697 BLOCK_INPUT_IN_MEMORY_ALLOCATORS that is visible to the debugger.
698 If that variable is set, block input while in one of Emacs's memory
699 allocation functions. There should be no need for this debugging
700 option, since signal handlers do not allocate memory, but Emacs
701 formerly allocated memory in signal handlers and this compile-time
702 option remains as a way to help debug the issue should it rear its
703 ugly head again. */
704 #ifdef XMALLOC_BLOCK_INPUT_CHECK
705 bool block_input_in_memory_allocators EXTERNALLY_VISIBLE;
706 static void
707 malloc_block_input (void)
709 if (block_input_in_memory_allocators)
710 block_input ();
712 static void
713 malloc_unblock_input (void)
715 if (block_input_in_memory_allocators)
716 unblock_input ();
718 # define MALLOC_BLOCK_INPUT malloc_block_input ()
719 # define MALLOC_UNBLOCK_INPUT malloc_unblock_input ()
720 #else
721 # define MALLOC_BLOCK_INPUT ((void) 0)
722 # define MALLOC_UNBLOCK_INPUT ((void) 0)
723 #endif
725 #define MALLOC_PROBE(size) \
726 do { \
727 if (profiler_memory_running) \
728 malloc_probe (size); \
729 } while (0)
732 /* Like malloc but check for no memory and block interrupt input.. */
734 void *
735 xmalloc (size_t size)
737 void *val;
739 MALLOC_BLOCK_INPUT;
740 val = malloc (size);
741 MALLOC_UNBLOCK_INPUT;
743 if (!val && size)
744 memory_full (size);
745 MALLOC_PROBE (size);
746 return val;
749 /* Like the above, but zeroes out the memory just allocated. */
751 void *
752 xzalloc (size_t size)
754 void *val;
756 MALLOC_BLOCK_INPUT;
757 val = malloc (size);
758 MALLOC_UNBLOCK_INPUT;
760 if (!val && size)
761 memory_full (size);
762 memset (val, 0, size);
763 MALLOC_PROBE (size);
764 return val;
767 /* Like realloc but check for no memory and block interrupt input.. */
769 void *
770 xrealloc (void *block, size_t size)
772 void *val;
774 MALLOC_BLOCK_INPUT;
775 /* We must call malloc explicitly when BLOCK is 0, since some
776 reallocs don't do this. */
777 if (! block)
778 val = malloc (size);
779 else
780 val = realloc (block, size);
781 MALLOC_UNBLOCK_INPUT;
783 if (!val && size)
784 memory_full (size);
785 MALLOC_PROBE (size);
786 return val;
790 /* Like free but block interrupt input. */
792 void
793 xfree (void *block)
795 if (!block)
796 return;
797 MALLOC_BLOCK_INPUT;
798 free (block);
799 MALLOC_UNBLOCK_INPUT;
800 /* We don't call refill_memory_reserve here
801 because in practice the call in r_alloc_free seems to suffice. */
805 /* Other parts of Emacs pass large int values to allocator functions
806 expecting ptrdiff_t. This is portable in practice, but check it to
807 be safe. */
808 verify (INT_MAX <= PTRDIFF_MAX);
811 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
812 Signal an error on memory exhaustion, and block interrupt input. */
814 void *
815 xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
817 eassert (0 <= nitems && 0 < item_size);
818 ptrdiff_t nbytes;
819 if (INT_MULTIPLY_WRAPV (nitems, item_size, &nbytes) || SIZE_MAX < nbytes)
820 memory_full (SIZE_MAX);
821 return xmalloc (nbytes);
825 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
826 Signal an error on memory exhaustion, and block interrupt input. */
828 void *
829 xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
831 eassert (0 <= nitems && 0 < item_size);
832 ptrdiff_t nbytes;
833 if (INT_MULTIPLY_WRAPV (nitems, item_size, &nbytes) || SIZE_MAX < nbytes)
834 memory_full (SIZE_MAX);
835 return xrealloc (pa, nbytes);
839 /* Grow PA, which points to an array of *NITEMS items, and return the
840 location of the reallocated array, updating *NITEMS to reflect its
841 new size. The new array will contain at least NITEMS_INCR_MIN more
842 items, but will not contain more than NITEMS_MAX items total.
843 ITEM_SIZE is the size of each item, in bytes.
845 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
846 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
847 infinity.
849 If PA is null, then allocate a new array instead of reallocating
850 the old one.
852 Block interrupt input as needed. If memory exhaustion occurs, set
853 *NITEMS to zero if PA is null, and signal an error (i.e., do not
854 return).
856 Thus, to grow an array A without saving its old contents, do
857 { xfree (A); A = NULL; A = xpalloc (NULL, &AITEMS, ...); }.
858 The A = NULL avoids a dangling pointer if xpalloc exhausts memory
859 and signals an error, and later this code is reexecuted and
860 attempts to free A. */
862 void *
863 xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
864 ptrdiff_t nitems_max, ptrdiff_t item_size)
866 ptrdiff_t n0 = *nitems;
867 eassume (0 < item_size && 0 < nitems_incr_min && 0 <= n0 && -1 <= nitems_max);
869 /* The approximate size to use for initial small allocation
870 requests. This is the largest "small" request for the GNU C
871 library malloc. */
872 enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
874 /* If the array is tiny, grow it to about (but no greater than)
875 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%.
876 Adjust the growth according to three constraints: NITEMS_INCR_MIN,
877 NITEMS_MAX, and what the C language can represent safely. */
879 ptrdiff_t n, nbytes;
880 if (INT_ADD_WRAPV (n0, n0 >> 1, &n))
881 n = PTRDIFF_MAX;
882 if (0 <= nitems_max && nitems_max < n)
883 n = nitems_max;
885 ptrdiff_t adjusted_nbytes
886 = ((INT_MULTIPLY_WRAPV (n, item_size, &nbytes) || SIZE_MAX < nbytes)
887 ? min (PTRDIFF_MAX, SIZE_MAX)
888 : nbytes < DEFAULT_MXFAST ? DEFAULT_MXFAST : 0);
889 if (adjusted_nbytes)
891 n = adjusted_nbytes / item_size;
892 nbytes = adjusted_nbytes - adjusted_nbytes % item_size;
895 if (! pa)
896 *nitems = 0;
897 if (n - n0 < nitems_incr_min
898 && (INT_ADD_WRAPV (n0, nitems_incr_min, &n)
899 || (0 <= nitems_max && nitems_max < n)
900 || INT_MULTIPLY_WRAPV (n, item_size, &nbytes)))
901 memory_full (SIZE_MAX);
902 pa = xrealloc (pa, nbytes);
903 *nitems = n;
904 return pa;
908 /* Like strdup, but uses xmalloc. */
910 char *
911 xstrdup (const char *s)
913 ptrdiff_t size;
914 eassert (s);
915 size = strlen (s) + 1;
916 return memcpy (xmalloc (size), s, size);
919 /* Like above, but duplicates Lisp string to C string. */
921 char *
922 xlispstrdup (Lisp_Object string)
924 ptrdiff_t size = SBYTES (string) + 1;
925 return memcpy (xmalloc (size), SSDATA (string), size);
928 /* Assign to *PTR a copy of STRING, freeing any storage *PTR formerly
929 pointed to. If STRING is null, assign it without copying anything.
930 Allocate before freeing, to avoid a dangling pointer if allocation
931 fails. */
933 void
934 dupstring (char **ptr, char const *string)
936 char *old = *ptr;
937 *ptr = string ? xstrdup (string) : 0;
938 xfree (old);
942 /* Like putenv, but (1) use the equivalent of xmalloc and (2) the
943 argument is a const pointer. */
945 void
946 xputenv (char const *string)
948 if (putenv ((char *) string) != 0)
949 memory_full (0);
952 /* Return a newly allocated memory block of SIZE bytes, remembering
953 to free it when unwinding. */
954 void *
955 record_xmalloc (size_t size)
957 void *p = xmalloc (size);
958 record_unwind_protect_ptr (xfree, p);
959 return p;
963 /* Like malloc but used for allocating Lisp data. NBYTES is the
964 number of bytes to allocate, TYPE describes the intended use of the
965 allocated memory block (for strings, for conses, ...). */
967 #if ! USE_LSB_TAG
968 void *lisp_malloc_loser EXTERNALLY_VISIBLE;
969 #endif
971 static void *
972 lisp_malloc (size_t nbytes, enum mem_type type)
974 register void *val;
976 MALLOC_BLOCK_INPUT;
978 #ifdef GC_MALLOC_CHECK
979 allocated_mem_type = type;
980 #endif
982 val = malloc (nbytes);
984 #if ! USE_LSB_TAG
985 /* If the memory just allocated cannot be addressed thru a Lisp
986 object's pointer, and it needs to be,
987 that's equivalent to running out of memory. */
988 if (val && type != MEM_TYPE_NON_LISP)
990 Lisp_Object tem;
991 XSETCONS (tem, (char *) val + nbytes - 1);
992 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
994 lisp_malloc_loser = val;
995 free (val);
996 val = 0;
999 #endif
1001 #ifndef GC_MALLOC_CHECK
1002 if (val && type != MEM_TYPE_NON_LISP)
1003 mem_insert (val, (char *) val + nbytes, type);
1004 #endif
1006 MALLOC_UNBLOCK_INPUT;
1007 if (!val && nbytes)
1008 memory_full (nbytes);
1009 MALLOC_PROBE (nbytes);
1010 return val;
1013 /* Free BLOCK. This must be called to free memory allocated with a
1014 call to lisp_malloc. */
1016 static void
1017 lisp_free (void *block)
1019 MALLOC_BLOCK_INPUT;
1020 free (block);
1021 #ifndef GC_MALLOC_CHECK
1022 mem_delete (mem_find (block));
1023 #endif
1024 MALLOC_UNBLOCK_INPUT;
1027 /***** Allocation of aligned blocks of memory to store Lisp data. *****/
1029 /* The entry point is lisp_align_malloc which returns blocks of at most
1030 BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
1032 /* Use aligned_alloc if it or a simple substitute is available.
1033 Address sanitization breaks aligned allocation, as of gcc 4.8.2 and
1034 clang 3.3 anyway. */
1036 #if ! ADDRESS_SANITIZER
1037 # if !defined SYSTEM_MALLOC && !defined DOUG_LEA_MALLOC && !defined HYBRID_MALLOC
1038 # define USE_ALIGNED_ALLOC 1
1039 /* Defined in gmalloc.c. */
1040 void *aligned_alloc (size_t, size_t);
1041 # elif defined HYBRID_MALLOC
1042 # if defined ALIGNED_ALLOC || defined HAVE_POSIX_MEMALIGN
1043 # define USE_ALIGNED_ALLOC 1
1044 # define aligned_alloc hybrid_aligned_alloc
1045 /* Defined in gmalloc.c. */
1046 void *aligned_alloc (size_t, size_t);
1047 # endif
1048 # elif defined HAVE_ALIGNED_ALLOC
1049 # define USE_ALIGNED_ALLOC 1
1050 # elif defined HAVE_POSIX_MEMALIGN
1051 # define USE_ALIGNED_ALLOC 1
1052 static void *
1053 aligned_alloc (size_t alignment, size_t size)
1055 void *p;
1056 return posix_memalign (&p, alignment, size) == 0 ? p : 0;
1058 # endif
1059 #endif
1061 /* BLOCK_ALIGN has to be a power of 2. */
1062 #define BLOCK_ALIGN (1 << 10)
1064 /* Padding to leave at the end of a malloc'd block. This is to give
1065 malloc a chance to minimize the amount of memory wasted to alignment.
1066 It should be tuned to the particular malloc library used.
1067 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
1068 aligned_alloc on the other hand would ideally prefer a value of 4
1069 because otherwise, there's 1020 bytes wasted between each ablocks.
1070 In Emacs, testing shows that those 1020 can most of the time be
1071 efficiently used by malloc to place other objects, so a value of 0 can
1072 still preferable unless you have a lot of aligned blocks and virtually
1073 nothing else. */
1074 #define BLOCK_PADDING 0
1075 #define BLOCK_BYTES \
1076 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
1078 /* Internal data structures and constants. */
1080 #define ABLOCKS_SIZE 16
1082 /* An aligned block of memory. */
1083 struct ablock
1085 union
1087 char payload[BLOCK_BYTES];
1088 struct ablock *next_free;
1089 } x;
1090 /* `abase' is the aligned base of the ablocks. */
1091 /* It is overloaded to hold the virtual `busy' field that counts
1092 the number of used ablock in the parent ablocks.
1093 The first ablock has the `busy' field, the others have the `abase'
1094 field. To tell the difference, we assume that pointers will have
1095 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
1096 is used to tell whether the real base of the parent ablocks is `abase'
1097 (if not, the word before the first ablock holds a pointer to the
1098 real base). */
1099 struct ablocks *abase;
1100 /* The padding of all but the last ablock is unused. The padding of
1101 the last ablock in an ablocks is not allocated. */
1102 #if BLOCK_PADDING
1103 char padding[BLOCK_PADDING];
1104 #endif
1107 /* A bunch of consecutive aligned blocks. */
1108 struct ablocks
1110 struct ablock blocks[ABLOCKS_SIZE];
1113 /* Size of the block requested from malloc or aligned_alloc. */
1114 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
1116 #define ABLOCK_ABASE(block) \
1117 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
1118 ? (struct ablocks *)(block) \
1119 : (block)->abase)
1121 /* Virtual `busy' field. */
1122 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
1124 /* Pointer to the (not necessarily aligned) malloc block. */
1125 #ifdef USE_ALIGNED_ALLOC
1126 #define ABLOCKS_BASE(abase) (abase)
1127 #else
1128 #define ABLOCKS_BASE(abase) \
1129 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void **)abase)[-1])
1130 #endif
1132 /* The list of free ablock. */
1133 static struct ablock *free_ablock;
1135 /* Allocate an aligned block of nbytes.
1136 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
1137 smaller or equal to BLOCK_BYTES. */
1138 static void *
1139 lisp_align_malloc (size_t nbytes, enum mem_type type)
1141 void *base, *val;
1142 struct ablocks *abase;
1144 eassert (nbytes <= BLOCK_BYTES);
1146 MALLOC_BLOCK_INPUT;
1148 #ifdef GC_MALLOC_CHECK
1149 allocated_mem_type = type;
1150 #endif
1152 if (!free_ablock)
1154 int i;
1155 intptr_t aligned; /* int gets warning casting to 64-bit pointer. */
1157 #ifdef DOUG_LEA_MALLOC
1158 if (!mmap_lisp_allowed_p ())
1159 mallopt (M_MMAP_MAX, 0);
1160 #endif
1162 #ifdef USE_ALIGNED_ALLOC
1163 abase = base = aligned_alloc (BLOCK_ALIGN, ABLOCKS_BYTES);
1164 #else
1165 base = malloc (ABLOCKS_BYTES);
1166 abase = ALIGN (base, BLOCK_ALIGN);
1167 #endif
1169 if (base == 0)
1171 MALLOC_UNBLOCK_INPUT;
1172 memory_full (ABLOCKS_BYTES);
1175 aligned = (base == abase);
1176 if (!aligned)
1177 ((void **) abase)[-1] = base;
1179 #ifdef DOUG_LEA_MALLOC
1180 if (!mmap_lisp_allowed_p ())
1181 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1182 #endif
1184 #if ! USE_LSB_TAG
1185 /* If the memory just allocated cannot be addressed thru a Lisp
1186 object's pointer, and it needs to be, that's equivalent to
1187 running out of memory. */
1188 if (type != MEM_TYPE_NON_LISP)
1190 Lisp_Object tem;
1191 char *end = (char *) base + ABLOCKS_BYTES - 1;
1192 XSETCONS (tem, end);
1193 if ((char *) XCONS (tem) != end)
1195 lisp_malloc_loser = base;
1196 free (base);
1197 MALLOC_UNBLOCK_INPUT;
1198 memory_full (SIZE_MAX);
1201 #endif
1203 /* Initialize the blocks and put them on the free list.
1204 If `base' was not properly aligned, we can't use the last block. */
1205 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1207 abase->blocks[i].abase = abase;
1208 abase->blocks[i].x.next_free = free_ablock;
1209 free_ablock = &abase->blocks[i];
1211 ABLOCKS_BUSY (abase) = (struct ablocks *) aligned;
1213 eassert (0 == ((uintptr_t) abase) % BLOCK_ALIGN);
1214 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1215 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1216 eassert (ABLOCKS_BASE (abase) == base);
1217 eassert (aligned == (intptr_t) ABLOCKS_BUSY (abase));
1220 abase = ABLOCK_ABASE (free_ablock);
1221 ABLOCKS_BUSY (abase)
1222 = (struct ablocks *) (2 + (intptr_t) ABLOCKS_BUSY (abase));
1223 val = free_ablock;
1224 free_ablock = free_ablock->x.next_free;
1226 #ifndef GC_MALLOC_CHECK
1227 if (type != MEM_TYPE_NON_LISP)
1228 mem_insert (val, (char *) val + nbytes, type);
1229 #endif
1231 MALLOC_UNBLOCK_INPUT;
1233 MALLOC_PROBE (nbytes);
1235 eassert (0 == ((uintptr_t) val) % BLOCK_ALIGN);
1236 return val;
1239 static void
1240 lisp_align_free (void *block)
1242 struct ablock *ablock = block;
1243 struct ablocks *abase = ABLOCK_ABASE (ablock);
1245 MALLOC_BLOCK_INPUT;
1246 #ifndef GC_MALLOC_CHECK
1247 mem_delete (mem_find (block));
1248 #endif
1249 /* Put on free list. */
1250 ablock->x.next_free = free_ablock;
1251 free_ablock = ablock;
1252 /* Update busy count. */
1253 ABLOCKS_BUSY (abase)
1254 = (struct ablocks *) (-2 + (intptr_t) ABLOCKS_BUSY (abase));
1256 if (2 > (intptr_t) ABLOCKS_BUSY (abase))
1257 { /* All the blocks are free. */
1258 int i = 0, aligned = (intptr_t) ABLOCKS_BUSY (abase);
1259 struct ablock **tem = &free_ablock;
1260 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1262 while (*tem)
1264 if (*tem >= (struct ablock *) abase && *tem < atop)
1266 i++;
1267 *tem = (*tem)->x.next_free;
1269 else
1270 tem = &(*tem)->x.next_free;
1272 eassert ((aligned & 1) == aligned);
1273 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1274 #ifdef USE_POSIX_MEMALIGN
1275 eassert ((uintptr_t) ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1276 #endif
1277 free (ABLOCKS_BASE (abase));
1279 MALLOC_UNBLOCK_INPUT;
1283 /***********************************************************************
1284 Interval Allocation
1285 ***********************************************************************/
1287 /* Number of intervals allocated in an interval_block structure.
1288 The 1020 is 1024 minus malloc overhead. */
1290 #define INTERVAL_BLOCK_SIZE \
1291 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1293 /* Intervals are allocated in chunks in the form of an interval_block
1294 structure. */
1296 struct interval_block
1298 /* Place `intervals' first, to preserve alignment. */
1299 struct interval intervals[INTERVAL_BLOCK_SIZE];
1300 struct interval_block *next;
1303 /* Current interval block. Its `next' pointer points to older
1304 blocks. */
1306 static struct interval_block *interval_block;
1308 /* Index in interval_block above of the next unused interval
1309 structure. */
1311 static int interval_block_index = INTERVAL_BLOCK_SIZE;
1313 /* Number of free and live intervals. */
1315 static EMACS_INT total_free_intervals, total_intervals;
1317 /* List of free intervals. */
1319 static INTERVAL interval_free_list;
1321 /* Return a new interval. */
1323 INTERVAL
1324 make_interval (void)
1326 INTERVAL val;
1328 MALLOC_BLOCK_INPUT;
1330 if (interval_free_list)
1332 val = interval_free_list;
1333 interval_free_list = INTERVAL_PARENT (interval_free_list);
1335 else
1337 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1339 struct interval_block *newi
1340 = lisp_malloc (sizeof *newi, MEM_TYPE_NON_LISP);
1342 newi->next = interval_block;
1343 interval_block = newi;
1344 interval_block_index = 0;
1345 total_free_intervals += INTERVAL_BLOCK_SIZE;
1347 val = &interval_block->intervals[interval_block_index++];
1350 MALLOC_UNBLOCK_INPUT;
1352 consing_since_gc += sizeof (struct interval);
1353 intervals_consed++;
1354 total_free_intervals--;
1355 RESET_INTERVAL (val);
1356 val->gcmarkbit = 0;
1357 return val;
1361 /* Mark Lisp objects in interval I. */
1363 static void
1364 mark_interval (register INTERVAL i, Lisp_Object dummy)
1366 /* Intervals should never be shared. So, if extra internal checking is
1367 enabled, GC aborts if it seems to have visited an interval twice. */
1368 eassert (!i->gcmarkbit);
1369 i->gcmarkbit = 1;
1370 mark_object (i->plist);
1373 /* Mark the interval tree rooted in I. */
1375 #define MARK_INTERVAL_TREE(i) \
1376 do { \
1377 if (i && !i->gcmarkbit) \
1378 traverse_intervals_noorder (i, mark_interval, Qnil); \
1379 } while (0)
1381 /***********************************************************************
1382 String Allocation
1383 ***********************************************************************/
1385 /* Lisp_Strings are allocated in string_block structures. When a new
1386 string_block is allocated, all the Lisp_Strings it contains are
1387 added to a free-list string_free_list. When a new Lisp_String is
1388 needed, it is taken from that list. During the sweep phase of GC,
1389 string_blocks that are entirely free are freed, except two which
1390 we keep.
1392 String data is allocated from sblock structures. Strings larger
1393 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1394 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1396 Sblocks consist internally of sdata structures, one for each
1397 Lisp_String. The sdata structure points to the Lisp_String it
1398 belongs to. The Lisp_String points back to the `u.data' member of
1399 its sdata structure.
1401 When a Lisp_String is freed during GC, it is put back on
1402 string_free_list, and its `data' member and its sdata's `string'
1403 pointer is set to null. The size of the string is recorded in the
1404 `n.nbytes' member of the sdata. So, sdata structures that are no
1405 longer used, can be easily recognized, and it's easy to compact the
1406 sblocks of small strings which we do in compact_small_strings. */
1408 /* Size in bytes of an sblock structure used for small strings. This
1409 is 8192 minus malloc overhead. */
1411 #define SBLOCK_SIZE 8188
1413 /* Strings larger than this are considered large strings. String data
1414 for large strings is allocated from individual sblocks. */
1416 #define LARGE_STRING_BYTES 1024
1418 /* The SDATA typedef is a struct or union describing string memory
1419 sub-allocated from an sblock. This is where the contents of Lisp
1420 strings are stored. */
1422 struct sdata
1424 /* Back-pointer to the string this sdata belongs to. If null, this
1425 structure is free, and NBYTES (in this structure or in the union below)
1426 contains the string's byte size (the same value that STRING_BYTES
1427 would return if STRING were non-null). If non-null, STRING_BYTES
1428 (STRING) is the size of the data, and DATA contains the string's
1429 contents. */
1430 struct Lisp_String *string;
1432 #ifdef GC_CHECK_STRING_BYTES
1433 ptrdiff_t nbytes;
1434 #endif
1436 unsigned char data[FLEXIBLE_ARRAY_MEMBER];
1439 #ifdef GC_CHECK_STRING_BYTES
1441 typedef struct sdata sdata;
1442 #define SDATA_NBYTES(S) (S)->nbytes
1443 #define SDATA_DATA(S) (S)->data
1445 #else
1447 typedef union
1449 struct Lisp_String *string;
1451 /* When STRING is nonnull, this union is actually of type 'struct sdata',
1452 which has a flexible array member. However, if implemented by
1453 giving this union a member of type 'struct sdata', the union
1454 could not be the last (flexible) member of 'struct sblock',
1455 because C99 prohibits a flexible array member from having a type
1456 that is itself a flexible array. So, comment this member out here,
1457 but remember that the option's there when using this union. */
1458 #if 0
1459 struct sdata u;
1460 #endif
1462 /* When STRING is null. */
1463 struct
1465 struct Lisp_String *string;
1466 ptrdiff_t nbytes;
1467 } n;
1468 } sdata;
1470 #define SDATA_NBYTES(S) (S)->n.nbytes
1471 #define SDATA_DATA(S) ((struct sdata *) (S))->data
1473 #endif /* not GC_CHECK_STRING_BYTES */
1475 enum { SDATA_DATA_OFFSET = offsetof (struct sdata, data) };
1477 /* Structure describing a block of memory which is sub-allocated to
1478 obtain string data memory for strings. Blocks for small strings
1479 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1480 as large as needed. */
1482 struct sblock
1484 /* Next in list. */
1485 struct sblock *next;
1487 /* Pointer to the next free sdata block. This points past the end
1488 of the sblock if there isn't any space left in this block. */
1489 sdata *next_free;
1491 /* String data. */
1492 sdata data[FLEXIBLE_ARRAY_MEMBER];
1495 /* Number of Lisp strings in a string_block structure. The 1020 is
1496 1024 minus malloc overhead. */
1498 #define STRING_BLOCK_SIZE \
1499 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1501 /* Structure describing a block from which Lisp_String structures
1502 are allocated. */
1504 struct string_block
1506 /* Place `strings' first, to preserve alignment. */
1507 struct Lisp_String strings[STRING_BLOCK_SIZE];
1508 struct string_block *next;
1511 /* Head and tail of the list of sblock structures holding Lisp string
1512 data. We always allocate from current_sblock. The NEXT pointers
1513 in the sblock structures go from oldest_sblock to current_sblock. */
1515 static struct sblock *oldest_sblock, *current_sblock;
1517 /* List of sblocks for large strings. */
1519 static struct sblock *large_sblocks;
1521 /* List of string_block structures. */
1523 static struct string_block *string_blocks;
1525 /* Free-list of Lisp_Strings. */
1527 static struct Lisp_String *string_free_list;
1529 /* Number of live and free Lisp_Strings. */
1531 static EMACS_INT total_strings, total_free_strings;
1533 /* Number of bytes used by live strings. */
1535 static EMACS_INT total_string_bytes;
1537 /* Given a pointer to a Lisp_String S which is on the free-list
1538 string_free_list, return a pointer to its successor in the
1539 free-list. */
1541 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1543 /* Return a pointer to the sdata structure belonging to Lisp string S.
1544 S must be live, i.e. S->data must not be null. S->data is actually
1545 a pointer to the `u.data' member of its sdata structure; the
1546 structure starts at a constant offset in front of that. */
1548 #define SDATA_OF_STRING(S) ((sdata *) ((S)->data - SDATA_DATA_OFFSET))
1551 #ifdef GC_CHECK_STRING_OVERRUN
1553 /* We check for overrun in string data blocks by appending a small
1554 "cookie" after each allocated string data block, and check for the
1555 presence of this cookie during GC. */
1557 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1558 static char const string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1559 { '\xde', '\xad', '\xbe', '\xef' };
1561 #else
1562 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1563 #endif
1565 /* Value is the size of an sdata structure large enough to hold NBYTES
1566 bytes of string data. The value returned includes a terminating
1567 NUL byte, the size of the sdata structure, and padding. */
1569 #ifdef GC_CHECK_STRING_BYTES
1571 #define SDATA_SIZE(NBYTES) \
1572 ((SDATA_DATA_OFFSET \
1573 + (NBYTES) + 1 \
1574 + sizeof (ptrdiff_t) - 1) \
1575 & ~(sizeof (ptrdiff_t) - 1))
1577 #else /* not GC_CHECK_STRING_BYTES */
1579 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1580 less than the size of that member. The 'max' is not needed when
1581 SDATA_DATA_OFFSET is a multiple of sizeof (ptrdiff_t), because then the
1582 alignment code reserves enough space. */
1584 #define SDATA_SIZE(NBYTES) \
1585 ((SDATA_DATA_OFFSET \
1586 + (SDATA_DATA_OFFSET % sizeof (ptrdiff_t) == 0 \
1587 ? NBYTES \
1588 : max (NBYTES, sizeof (ptrdiff_t) - 1)) \
1589 + 1 \
1590 + sizeof (ptrdiff_t) - 1) \
1591 & ~(sizeof (ptrdiff_t) - 1))
1593 #endif /* not GC_CHECK_STRING_BYTES */
1595 /* Extra bytes to allocate for each string. */
1597 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1599 /* Exact bound on the number of bytes in a string, not counting the
1600 terminating null. A string cannot contain more bytes than
1601 STRING_BYTES_BOUND, nor can it be so long that the size_t
1602 arithmetic in allocate_string_data would overflow while it is
1603 calculating a value to be passed to malloc. */
1604 static ptrdiff_t const STRING_BYTES_MAX =
1605 min (STRING_BYTES_BOUND,
1606 ((SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD
1607 - GC_STRING_EXTRA
1608 - offsetof (struct sblock, data)
1609 - SDATA_DATA_OFFSET)
1610 & ~(sizeof (EMACS_INT) - 1)));
1612 /* Initialize string allocation. Called from init_alloc_once. */
1614 static void
1615 init_strings (void)
1617 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1618 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1622 #ifdef GC_CHECK_STRING_BYTES
1624 static int check_string_bytes_count;
1626 /* Like STRING_BYTES, but with debugging check. Can be
1627 called during GC, so pay attention to the mark bit. */
1629 ptrdiff_t
1630 string_bytes (struct Lisp_String *s)
1632 ptrdiff_t nbytes =
1633 (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1635 if (!PURE_P (s) && s->data && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1636 emacs_abort ();
1637 return nbytes;
1640 /* Check validity of Lisp strings' string_bytes member in B. */
1642 static void
1643 check_sblock (struct sblock *b)
1645 sdata *from, *end, *from_end;
1647 end = b->next_free;
1649 for (from = b->data; from < end; from = from_end)
1651 /* Compute the next FROM here because copying below may
1652 overwrite data we need to compute it. */
1653 ptrdiff_t nbytes;
1655 /* Check that the string size recorded in the string is the
1656 same as the one recorded in the sdata structure. */
1657 nbytes = SDATA_SIZE (from->string ? string_bytes (from->string)
1658 : SDATA_NBYTES (from));
1659 from_end = (sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1664 /* Check validity of Lisp strings' string_bytes member. ALL_P
1665 means check all strings, otherwise check only most
1666 recently allocated strings. Used for hunting a bug. */
1668 static void
1669 check_string_bytes (bool all_p)
1671 if (all_p)
1673 struct sblock *b;
1675 for (b = large_sblocks; b; b = b->next)
1677 struct Lisp_String *s = b->data[0].string;
1678 if (s)
1679 string_bytes (s);
1682 for (b = oldest_sblock; b; b = b->next)
1683 check_sblock (b);
1685 else if (current_sblock)
1686 check_sblock (current_sblock);
1689 #else /* not GC_CHECK_STRING_BYTES */
1691 #define check_string_bytes(all) ((void) 0)
1693 #endif /* GC_CHECK_STRING_BYTES */
1695 #ifdef GC_CHECK_STRING_FREE_LIST
1697 /* Walk through the string free list looking for bogus next pointers.
1698 This may catch buffer overrun from a previous string. */
1700 static void
1701 check_string_free_list (void)
1703 struct Lisp_String *s;
1705 /* Pop a Lisp_String off the free-list. */
1706 s = string_free_list;
1707 while (s != NULL)
1709 if ((uintptr_t) s < 1024)
1710 emacs_abort ();
1711 s = NEXT_FREE_LISP_STRING (s);
1714 #else
1715 #define check_string_free_list()
1716 #endif
1718 /* Return a new Lisp_String. */
1720 static struct Lisp_String *
1721 allocate_string (void)
1723 struct Lisp_String *s;
1725 MALLOC_BLOCK_INPUT;
1727 /* If the free-list is empty, allocate a new string_block, and
1728 add all the Lisp_Strings in it to the free-list. */
1729 if (string_free_list == NULL)
1731 struct string_block *b = lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1732 int i;
1734 b->next = string_blocks;
1735 string_blocks = b;
1737 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1739 s = b->strings + i;
1740 /* Every string on a free list should have NULL data pointer. */
1741 s->data = NULL;
1742 NEXT_FREE_LISP_STRING (s) = string_free_list;
1743 string_free_list = s;
1746 total_free_strings += STRING_BLOCK_SIZE;
1749 check_string_free_list ();
1751 /* Pop a Lisp_String off the free-list. */
1752 s = string_free_list;
1753 string_free_list = NEXT_FREE_LISP_STRING (s);
1755 MALLOC_UNBLOCK_INPUT;
1757 --total_free_strings;
1758 ++total_strings;
1759 ++strings_consed;
1760 consing_since_gc += sizeof *s;
1762 #ifdef GC_CHECK_STRING_BYTES
1763 if (!noninteractive)
1765 if (++check_string_bytes_count == 200)
1767 check_string_bytes_count = 0;
1768 check_string_bytes (1);
1770 else
1771 check_string_bytes (0);
1773 #endif /* GC_CHECK_STRING_BYTES */
1775 return s;
1779 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1780 plus a NUL byte at the end. Allocate an sdata structure for S, and
1781 set S->data to its `u.data' member. Store a NUL byte at the end of
1782 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1783 S->data if it was initially non-null. */
1785 void
1786 allocate_string_data (struct Lisp_String *s,
1787 EMACS_INT nchars, EMACS_INT nbytes)
1789 sdata *data, *old_data;
1790 struct sblock *b;
1791 ptrdiff_t needed, old_nbytes;
1793 if (STRING_BYTES_MAX < nbytes)
1794 string_overflow ();
1796 /* Determine the number of bytes needed to store NBYTES bytes
1797 of string data. */
1798 needed = SDATA_SIZE (nbytes);
1799 if (s->data)
1801 old_data = SDATA_OF_STRING (s);
1802 old_nbytes = STRING_BYTES (s);
1804 else
1805 old_data = NULL;
1807 MALLOC_BLOCK_INPUT;
1809 if (nbytes > LARGE_STRING_BYTES)
1811 size_t size = offsetof (struct sblock, data) + needed;
1813 #ifdef DOUG_LEA_MALLOC
1814 if (!mmap_lisp_allowed_p ())
1815 mallopt (M_MMAP_MAX, 0);
1816 #endif
1818 b = lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
1820 #ifdef DOUG_LEA_MALLOC
1821 if (!mmap_lisp_allowed_p ())
1822 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1823 #endif
1825 b->next_free = b->data;
1826 b->data[0].string = NULL;
1827 b->next = large_sblocks;
1828 large_sblocks = b;
1830 else if (current_sblock == NULL
1831 || (((char *) current_sblock + SBLOCK_SIZE
1832 - (char *) current_sblock->next_free)
1833 < (needed + GC_STRING_EXTRA)))
1835 /* Not enough room in the current sblock. */
1836 b = lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1837 b->next_free = b->data;
1838 b->data[0].string = NULL;
1839 b->next = NULL;
1841 if (current_sblock)
1842 current_sblock->next = b;
1843 else
1844 oldest_sblock = b;
1845 current_sblock = b;
1847 else
1848 b = current_sblock;
1850 data = b->next_free;
1851 b->next_free = (sdata *) ((char *) data + needed + GC_STRING_EXTRA);
1853 MALLOC_UNBLOCK_INPUT;
1855 data->string = s;
1856 s->data = SDATA_DATA (data);
1857 #ifdef GC_CHECK_STRING_BYTES
1858 SDATA_NBYTES (data) = nbytes;
1859 #endif
1860 s->size = nchars;
1861 s->size_byte = nbytes;
1862 s->data[nbytes] = '\0';
1863 #ifdef GC_CHECK_STRING_OVERRUN
1864 memcpy ((char *) data + needed, string_overrun_cookie,
1865 GC_STRING_OVERRUN_COOKIE_SIZE);
1866 #endif
1868 /* Note that Faset may call to this function when S has already data
1869 assigned. In this case, mark data as free by setting it's string
1870 back-pointer to null, and record the size of the data in it. */
1871 if (old_data)
1873 SDATA_NBYTES (old_data) = old_nbytes;
1874 old_data->string = NULL;
1877 consing_since_gc += needed;
1881 /* Sweep and compact strings. */
1883 NO_INLINE /* For better stack traces */
1884 static void
1885 sweep_strings (void)
1887 struct string_block *b, *next;
1888 struct string_block *live_blocks = NULL;
1890 string_free_list = NULL;
1891 total_strings = total_free_strings = 0;
1892 total_string_bytes = 0;
1894 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1895 for (b = string_blocks; b; b = next)
1897 int i, nfree = 0;
1898 struct Lisp_String *free_list_before = string_free_list;
1900 next = b->next;
1902 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
1904 struct Lisp_String *s = b->strings + i;
1906 if (s->data)
1908 /* String was not on free-list before. */
1909 if (STRING_MARKED_P (s))
1911 /* String is live; unmark it and its intervals. */
1912 UNMARK_STRING (s);
1914 /* Do not use string_(set|get)_intervals here. */
1915 s->intervals = balance_intervals (s->intervals);
1917 ++total_strings;
1918 total_string_bytes += STRING_BYTES (s);
1920 else
1922 /* String is dead. Put it on the free-list. */
1923 sdata *data = SDATA_OF_STRING (s);
1925 /* Save the size of S in its sdata so that we know
1926 how large that is. Reset the sdata's string
1927 back-pointer so that we know it's free. */
1928 #ifdef GC_CHECK_STRING_BYTES
1929 if (string_bytes (s) != SDATA_NBYTES (data))
1930 emacs_abort ();
1931 #else
1932 data->n.nbytes = STRING_BYTES (s);
1933 #endif
1934 data->string = NULL;
1936 /* Reset the strings's `data' member so that we
1937 know it's free. */
1938 s->data = NULL;
1940 /* Put the string on the free-list. */
1941 NEXT_FREE_LISP_STRING (s) = string_free_list;
1942 string_free_list = s;
1943 ++nfree;
1946 else
1948 /* S was on the free-list before. Put it there again. */
1949 NEXT_FREE_LISP_STRING (s) = string_free_list;
1950 string_free_list = s;
1951 ++nfree;
1955 /* Free blocks that contain free Lisp_Strings only, except
1956 the first two of them. */
1957 if (nfree == STRING_BLOCK_SIZE
1958 && total_free_strings > STRING_BLOCK_SIZE)
1960 lisp_free (b);
1961 string_free_list = free_list_before;
1963 else
1965 total_free_strings += nfree;
1966 b->next = live_blocks;
1967 live_blocks = b;
1971 check_string_free_list ();
1973 string_blocks = live_blocks;
1974 free_large_strings ();
1975 compact_small_strings ();
1977 check_string_free_list ();
1981 /* Free dead large strings. */
1983 static void
1984 free_large_strings (void)
1986 struct sblock *b, *next;
1987 struct sblock *live_blocks = NULL;
1989 for (b = large_sblocks; b; b = next)
1991 next = b->next;
1993 if (b->data[0].string == NULL)
1994 lisp_free (b);
1995 else
1997 b->next = live_blocks;
1998 live_blocks = b;
2002 large_sblocks = live_blocks;
2006 /* Compact data of small strings. Free sblocks that don't contain
2007 data of live strings after compaction. */
2009 static void
2010 compact_small_strings (void)
2012 struct sblock *b, *tb, *next;
2013 sdata *from, *to, *end, *tb_end;
2014 sdata *to_end, *from_end;
2016 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2017 to, and TB_END is the end of TB. */
2018 tb = oldest_sblock;
2019 tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
2020 to = tb->data;
2022 /* Step through the blocks from the oldest to the youngest. We
2023 expect that old blocks will stabilize over time, so that less
2024 copying will happen this way. */
2025 for (b = oldest_sblock; b; b = b->next)
2027 end = b->next_free;
2028 eassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2030 for (from = b->data; from < end; from = from_end)
2032 /* Compute the next FROM here because copying below may
2033 overwrite data we need to compute it. */
2034 ptrdiff_t nbytes;
2035 struct Lisp_String *s = from->string;
2037 #ifdef GC_CHECK_STRING_BYTES
2038 /* Check that the string size recorded in the string is the
2039 same as the one recorded in the sdata structure. */
2040 if (s && string_bytes (s) != SDATA_NBYTES (from))
2041 emacs_abort ();
2042 #endif /* GC_CHECK_STRING_BYTES */
2044 nbytes = s ? STRING_BYTES (s) : SDATA_NBYTES (from);
2045 eassert (nbytes <= LARGE_STRING_BYTES);
2047 nbytes = SDATA_SIZE (nbytes);
2048 from_end = (sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
2050 #ifdef GC_CHECK_STRING_OVERRUN
2051 if (memcmp (string_overrun_cookie,
2052 (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
2053 GC_STRING_OVERRUN_COOKIE_SIZE))
2054 emacs_abort ();
2055 #endif
2057 /* Non-NULL S means it's alive. Copy its data. */
2058 if (s)
2060 /* If TB is full, proceed with the next sblock. */
2061 to_end = (sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2062 if (to_end > tb_end)
2064 tb->next_free = to;
2065 tb = tb->next;
2066 tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
2067 to = tb->data;
2068 to_end = (sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2071 /* Copy, and update the string's `data' pointer. */
2072 if (from != to)
2074 eassert (tb != b || to < from);
2075 memmove (to, from, nbytes + GC_STRING_EXTRA);
2076 to->string->data = SDATA_DATA (to);
2079 /* Advance past the sdata we copied to. */
2080 to = to_end;
2085 /* The rest of the sblocks following TB don't contain live data, so
2086 we can free them. */
2087 for (b = tb->next; b; b = next)
2089 next = b->next;
2090 lisp_free (b);
2093 tb->next_free = to;
2094 tb->next = NULL;
2095 current_sblock = tb;
2098 void
2099 string_overflow (void)
2101 error ("Maximum string size exceeded");
2104 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2105 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2106 LENGTH must be an integer.
2107 INIT must be an integer that represents a character. */)
2108 (Lisp_Object length, Lisp_Object init)
2110 register Lisp_Object val;
2111 int c;
2112 EMACS_INT nbytes;
2114 CHECK_NATNUM (length);
2115 CHECK_CHARACTER (init);
2117 c = XFASTINT (init);
2118 if (ASCII_CHAR_P (c))
2120 nbytes = XINT (length);
2121 val = make_uninit_string (nbytes);
2122 if (nbytes)
2124 memset (SDATA (val), c, nbytes);
2125 SDATA (val)[nbytes] = 0;
2128 else
2130 unsigned char str[MAX_MULTIBYTE_LENGTH];
2131 ptrdiff_t len = CHAR_STRING (c, str);
2132 EMACS_INT string_len = XINT (length);
2133 unsigned char *p, *beg, *end;
2135 if (INT_MULTIPLY_WRAPV (len, string_len, &nbytes))
2136 string_overflow ();
2137 val = make_uninit_multibyte_string (string_len, nbytes);
2138 for (beg = SDATA (val), p = beg, end = beg + nbytes; p < end; p += len)
2140 /* First time we just copy `str' to the data of `val'. */
2141 if (p == beg)
2142 memcpy (p, str, len);
2143 else
2145 /* Next time we copy largest possible chunk from
2146 initialized to uninitialized part of `val'. */
2147 len = min (p - beg, end - p);
2148 memcpy (p, beg, len);
2151 if (nbytes)
2152 *p = 0;
2155 return val;
2158 /* Fill A with 1 bits if INIT is non-nil, and with 0 bits otherwise.
2159 Return A. */
2161 Lisp_Object
2162 bool_vector_fill (Lisp_Object a, Lisp_Object init)
2164 EMACS_INT nbits = bool_vector_size (a);
2165 if (0 < nbits)
2167 unsigned char *data = bool_vector_uchar_data (a);
2168 int pattern = NILP (init) ? 0 : (1 << BOOL_VECTOR_BITS_PER_CHAR) - 1;
2169 ptrdiff_t nbytes = bool_vector_bytes (nbits);
2170 int last_mask = ~ (~0u << ((nbits - 1) % BOOL_VECTOR_BITS_PER_CHAR + 1));
2171 memset (data, pattern, nbytes - 1);
2172 data[nbytes - 1] = pattern & last_mask;
2174 return a;
2177 /* Return a newly allocated, uninitialized bool vector of size NBITS. */
2179 Lisp_Object
2180 make_uninit_bool_vector (EMACS_INT nbits)
2182 Lisp_Object val;
2183 EMACS_INT words = bool_vector_words (nbits);
2184 EMACS_INT word_bytes = words * sizeof (bits_word);
2185 EMACS_INT needed_elements = ((bool_header_size - header_size + word_bytes
2186 + word_size - 1)
2187 / word_size);
2188 struct Lisp_Bool_Vector *p
2189 = (struct Lisp_Bool_Vector *) allocate_vector (needed_elements);
2190 XSETVECTOR (val, p);
2191 XSETPVECTYPESIZE (XVECTOR (val), PVEC_BOOL_VECTOR, 0, 0);
2192 p->size = nbits;
2194 /* Clear padding at the end. */
2195 if (words)
2196 p->data[words - 1] = 0;
2198 return val;
2201 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2202 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2203 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2204 (Lisp_Object length, Lisp_Object init)
2206 Lisp_Object val;
2208 CHECK_NATNUM (length);
2209 val = make_uninit_bool_vector (XFASTINT (length));
2210 return bool_vector_fill (val, init);
2213 DEFUN ("bool-vector", Fbool_vector, Sbool_vector, 0, MANY, 0,
2214 doc: /* Return a new bool-vector with specified arguments as elements.
2215 Any number of arguments, even zero arguments, are allowed.
2216 usage: (bool-vector &rest OBJECTS) */)
2217 (ptrdiff_t nargs, Lisp_Object *args)
2219 ptrdiff_t i;
2220 Lisp_Object vector;
2222 vector = make_uninit_bool_vector (nargs);
2223 for (i = 0; i < nargs; i++)
2224 bool_vector_set (vector, i, !NILP (args[i]));
2226 return vector;
2229 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2230 of characters from the contents. This string may be unibyte or
2231 multibyte, depending on the contents. */
2233 Lisp_Object
2234 make_string (const char *contents, ptrdiff_t nbytes)
2236 register Lisp_Object val;
2237 ptrdiff_t nchars, multibyte_nbytes;
2239 parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
2240 &nchars, &multibyte_nbytes);
2241 if (nbytes == nchars || nbytes != multibyte_nbytes)
2242 /* CONTENTS contains no multibyte sequences or contains an invalid
2243 multibyte sequence. We must make unibyte string. */
2244 val = make_unibyte_string (contents, nbytes);
2245 else
2246 val = make_multibyte_string (contents, nchars, nbytes);
2247 return val;
2250 /* Make a unibyte string from LENGTH bytes at CONTENTS. */
2252 Lisp_Object
2253 make_unibyte_string (const char *contents, ptrdiff_t length)
2255 register Lisp_Object val;
2256 val = make_uninit_string (length);
2257 memcpy (SDATA (val), contents, length);
2258 return val;
2262 /* Make a multibyte string from NCHARS characters occupying NBYTES
2263 bytes at CONTENTS. */
2265 Lisp_Object
2266 make_multibyte_string (const char *contents,
2267 ptrdiff_t nchars, ptrdiff_t nbytes)
2269 register Lisp_Object val;
2270 val = make_uninit_multibyte_string (nchars, nbytes);
2271 memcpy (SDATA (val), contents, nbytes);
2272 return val;
2276 /* Make a string from NCHARS characters occupying NBYTES bytes at
2277 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2279 Lisp_Object
2280 make_string_from_bytes (const char *contents,
2281 ptrdiff_t nchars, ptrdiff_t nbytes)
2283 register Lisp_Object val;
2284 val = make_uninit_multibyte_string (nchars, nbytes);
2285 memcpy (SDATA (val), contents, nbytes);
2286 if (SBYTES (val) == SCHARS (val))
2287 STRING_SET_UNIBYTE (val);
2288 return val;
2292 /* Make a string from NCHARS characters occupying NBYTES bytes at
2293 CONTENTS. The argument MULTIBYTE controls whether to label the
2294 string as multibyte. If NCHARS is negative, it counts the number of
2295 characters by itself. */
2297 Lisp_Object
2298 make_specified_string (const char *contents,
2299 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
2301 Lisp_Object val;
2303 if (nchars < 0)
2305 if (multibyte)
2306 nchars = multibyte_chars_in_text ((const unsigned char *) contents,
2307 nbytes);
2308 else
2309 nchars = nbytes;
2311 val = make_uninit_multibyte_string (nchars, nbytes);
2312 memcpy (SDATA (val), contents, nbytes);
2313 if (!multibyte)
2314 STRING_SET_UNIBYTE (val);
2315 return val;
2319 /* Return a unibyte Lisp_String set up to hold LENGTH characters
2320 occupying LENGTH bytes. */
2322 Lisp_Object
2323 make_uninit_string (EMACS_INT length)
2325 Lisp_Object val;
2327 if (!length)
2328 return empty_unibyte_string;
2329 val = make_uninit_multibyte_string (length, length);
2330 STRING_SET_UNIBYTE (val);
2331 return val;
2335 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2336 which occupy NBYTES bytes. */
2338 Lisp_Object
2339 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2341 Lisp_Object string;
2342 struct Lisp_String *s;
2344 if (nchars < 0)
2345 emacs_abort ();
2346 if (!nbytes)
2347 return empty_multibyte_string;
2349 s = allocate_string ();
2350 s->intervals = NULL;
2351 allocate_string_data (s, nchars, nbytes);
2352 XSETSTRING (string, s);
2353 string_chars_consed += nbytes;
2354 return string;
2357 /* Print arguments to BUF according to a FORMAT, then return
2358 a Lisp_String initialized with the data from BUF. */
2360 Lisp_Object
2361 make_formatted_string (char *buf, const char *format, ...)
2363 va_list ap;
2364 int length;
2366 va_start (ap, format);
2367 length = vsprintf (buf, format, ap);
2368 va_end (ap);
2369 return make_string (buf, length);
2373 /***********************************************************************
2374 Float Allocation
2375 ***********************************************************************/
2377 /* We store float cells inside of float_blocks, allocating a new
2378 float_block with malloc whenever necessary. Float cells reclaimed
2379 by GC are put on a free list to be reallocated before allocating
2380 any new float cells from the latest float_block. */
2382 #define FLOAT_BLOCK_SIZE \
2383 (((BLOCK_BYTES - sizeof (struct float_block *) \
2384 /* The compiler might add padding at the end. */ \
2385 - (sizeof (struct Lisp_Float) - sizeof (bits_word))) * CHAR_BIT) \
2386 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2388 #define GETMARKBIT(block,n) \
2389 (((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2390 >> ((n) % BITS_PER_BITS_WORD)) \
2391 & 1)
2393 #define SETMARKBIT(block,n) \
2394 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2395 |= (bits_word) 1 << ((n) % BITS_PER_BITS_WORD))
2397 #define UNSETMARKBIT(block,n) \
2398 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2399 &= ~((bits_word) 1 << ((n) % BITS_PER_BITS_WORD)))
2401 #define FLOAT_BLOCK(fptr) \
2402 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2404 #define FLOAT_INDEX(fptr) \
2405 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2407 struct float_block
2409 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2410 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2411 bits_word gcmarkbits[1 + FLOAT_BLOCK_SIZE / BITS_PER_BITS_WORD];
2412 struct float_block *next;
2415 #define FLOAT_MARKED_P(fptr) \
2416 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2418 #define FLOAT_MARK(fptr) \
2419 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2421 #define FLOAT_UNMARK(fptr) \
2422 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2424 /* Current float_block. */
2426 static struct float_block *float_block;
2428 /* Index of first unused Lisp_Float in the current float_block. */
2430 static int float_block_index = FLOAT_BLOCK_SIZE;
2432 /* Free-list of Lisp_Floats. */
2434 static struct Lisp_Float *float_free_list;
2436 /* Return a new float object with value FLOAT_VALUE. */
2438 Lisp_Object
2439 make_float (double float_value)
2441 register Lisp_Object val;
2443 MALLOC_BLOCK_INPUT;
2445 if (float_free_list)
2447 /* We use the data field for chaining the free list
2448 so that we won't use the same field that has the mark bit. */
2449 XSETFLOAT (val, float_free_list);
2450 float_free_list = float_free_list->u.chain;
2452 else
2454 if (float_block_index == FLOAT_BLOCK_SIZE)
2456 struct float_block *new
2457 = lisp_align_malloc (sizeof *new, MEM_TYPE_FLOAT);
2458 new->next = float_block;
2459 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2460 float_block = new;
2461 float_block_index = 0;
2462 total_free_floats += FLOAT_BLOCK_SIZE;
2464 XSETFLOAT (val, &float_block->floats[float_block_index]);
2465 float_block_index++;
2468 MALLOC_UNBLOCK_INPUT;
2470 XFLOAT_INIT (val, float_value);
2471 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2472 consing_since_gc += sizeof (struct Lisp_Float);
2473 floats_consed++;
2474 total_free_floats--;
2475 return val;
2480 /***********************************************************************
2481 Cons Allocation
2482 ***********************************************************************/
2484 /* We store cons cells inside of cons_blocks, allocating a new
2485 cons_block with malloc whenever necessary. Cons cells reclaimed by
2486 GC are put on a free list to be reallocated before allocating
2487 any new cons cells from the latest cons_block. */
2489 #define CONS_BLOCK_SIZE \
2490 (((BLOCK_BYTES - sizeof (struct cons_block *) \
2491 /* The compiler might add padding at the end. */ \
2492 - (sizeof (struct Lisp_Cons) - sizeof (bits_word))) * CHAR_BIT) \
2493 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2495 #define CONS_BLOCK(fptr) \
2496 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2498 #define CONS_INDEX(fptr) \
2499 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2501 struct cons_block
2503 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2504 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2505 bits_word gcmarkbits[1 + CONS_BLOCK_SIZE / BITS_PER_BITS_WORD];
2506 struct cons_block *next;
2509 #define CONS_MARKED_P(fptr) \
2510 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2512 #define CONS_MARK(fptr) \
2513 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2515 #define CONS_UNMARK(fptr) \
2516 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2518 /* Current cons_block. */
2520 static struct cons_block *cons_block;
2522 /* Index of first unused Lisp_Cons in the current block. */
2524 static int cons_block_index = CONS_BLOCK_SIZE;
2526 /* Free-list of Lisp_Cons structures. */
2528 static struct Lisp_Cons *cons_free_list;
2530 /* Explicitly free a cons cell by putting it on the free-list. */
2532 void
2533 free_cons (struct Lisp_Cons *ptr)
2535 ptr->u.chain = cons_free_list;
2536 ptr->car = Vdead;
2537 cons_free_list = ptr;
2538 consing_since_gc -= sizeof *ptr;
2539 total_free_conses++;
2542 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2543 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2544 (Lisp_Object car, Lisp_Object cdr)
2546 register Lisp_Object val;
2548 MALLOC_BLOCK_INPUT;
2550 if (cons_free_list)
2552 /* We use the cdr for chaining the free list
2553 so that we won't use the same field that has the mark bit. */
2554 XSETCONS (val, cons_free_list);
2555 cons_free_list = cons_free_list->u.chain;
2557 else
2559 if (cons_block_index == CONS_BLOCK_SIZE)
2561 struct cons_block *new
2562 = lisp_align_malloc (sizeof *new, MEM_TYPE_CONS);
2563 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2564 new->next = cons_block;
2565 cons_block = new;
2566 cons_block_index = 0;
2567 total_free_conses += CONS_BLOCK_SIZE;
2569 XSETCONS (val, &cons_block->conses[cons_block_index]);
2570 cons_block_index++;
2573 MALLOC_UNBLOCK_INPUT;
2575 XSETCAR (val, car);
2576 XSETCDR (val, cdr);
2577 eassert (!CONS_MARKED_P (XCONS (val)));
2578 consing_since_gc += sizeof (struct Lisp_Cons);
2579 total_free_conses--;
2580 cons_cells_consed++;
2581 return val;
2584 #ifdef GC_CHECK_CONS_LIST
2585 /* Get an error now if there's any junk in the cons free list. */
2586 void
2587 check_cons_list (void)
2589 struct Lisp_Cons *tail = cons_free_list;
2591 while (tail)
2592 tail = tail->u.chain;
2594 #endif
2596 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2598 Lisp_Object
2599 list1 (Lisp_Object arg1)
2601 return Fcons (arg1, Qnil);
2604 Lisp_Object
2605 list2 (Lisp_Object arg1, Lisp_Object arg2)
2607 return Fcons (arg1, Fcons (arg2, Qnil));
2611 Lisp_Object
2612 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2614 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2618 Lisp_Object
2619 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2621 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2625 Lisp_Object
2626 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2628 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2629 Fcons (arg5, Qnil)))));
2632 /* Make a list of COUNT Lisp_Objects, where ARG is the
2633 first one. Allocate conses from pure space if TYPE
2634 is CONSTYPE_PURE, or allocate as usual if type is CONSTYPE_HEAP. */
2636 Lisp_Object
2637 listn (enum constype type, ptrdiff_t count, Lisp_Object arg, ...)
2639 Lisp_Object (*cons) (Lisp_Object, Lisp_Object);
2640 switch (type)
2642 case CONSTYPE_PURE: cons = pure_cons; break;
2643 case CONSTYPE_HEAP: cons = Fcons; break;
2644 default: emacs_abort ();
2647 eassume (0 < count);
2648 Lisp_Object val = cons (arg, Qnil);
2649 Lisp_Object tail = val;
2651 va_list ap;
2652 va_start (ap, arg);
2653 for (ptrdiff_t i = 1; i < count; i++)
2655 Lisp_Object elem = cons (va_arg (ap, Lisp_Object), Qnil);
2656 XSETCDR (tail, elem);
2657 tail = elem;
2659 va_end (ap);
2661 return val;
2664 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2665 doc: /* Return a newly created list with specified arguments as elements.
2666 Any number of arguments, even zero arguments, are allowed.
2667 usage: (list &rest OBJECTS) */)
2668 (ptrdiff_t nargs, Lisp_Object *args)
2670 register Lisp_Object val;
2671 val = Qnil;
2673 while (nargs > 0)
2675 nargs--;
2676 val = Fcons (args[nargs], val);
2678 return val;
2682 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2683 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2684 (register Lisp_Object length, Lisp_Object init)
2686 register Lisp_Object val;
2687 register EMACS_INT size;
2689 CHECK_NATNUM (length);
2690 size = XFASTINT (length);
2692 val = Qnil;
2693 while (size > 0)
2695 val = Fcons (init, val);
2696 --size;
2698 if (size > 0)
2700 val = Fcons (init, val);
2701 --size;
2703 if (size > 0)
2705 val = Fcons (init, val);
2706 --size;
2708 if (size > 0)
2710 val = Fcons (init, val);
2711 --size;
2713 if (size > 0)
2715 val = Fcons (init, val);
2716 --size;
2722 QUIT;
2725 return val;
2730 /***********************************************************************
2731 Vector Allocation
2732 ***********************************************************************/
2734 /* Sometimes a vector's contents are merely a pointer internally used
2735 in vector allocation code. On the rare platforms where a null
2736 pointer cannot be tagged, represent it with a Lisp 0.
2737 Usually you don't want to touch this. */
2739 static struct Lisp_Vector *
2740 next_vector (struct Lisp_Vector *v)
2742 return XUNTAG (v->contents[0], Lisp_Int0);
2745 static void
2746 set_next_vector (struct Lisp_Vector *v, struct Lisp_Vector *p)
2748 v->contents[0] = make_lisp_ptr (p, Lisp_Int0);
2751 /* This value is balanced well enough to avoid too much internal overhead
2752 for the most common cases; it's not required to be a power of two, but
2753 it's expected to be a mult-of-ROUNDUP_SIZE (see below). */
2755 #define VECTOR_BLOCK_SIZE 4096
2757 enum
2759 /* Alignment of struct Lisp_Vector objects. */
2760 vector_alignment = COMMON_MULTIPLE (ALIGNOF_STRUCT_LISP_VECTOR,
2761 GCALIGNMENT),
2763 /* Vector size requests are a multiple of this. */
2764 roundup_size = COMMON_MULTIPLE (vector_alignment, word_size)
2767 /* Verify assumptions described above. */
2768 verify ((VECTOR_BLOCK_SIZE % roundup_size) == 0);
2769 verify (VECTOR_BLOCK_SIZE <= (1 << PSEUDOVECTOR_SIZE_BITS));
2771 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at compile time. */
2772 #define vroundup_ct(x) ROUNDUP (x, roundup_size)
2773 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at runtime. */
2774 #define vroundup(x) (eassume ((x) >= 0), vroundup_ct (x))
2776 /* Rounding helps to maintain alignment constraints if USE_LSB_TAG. */
2778 #define VECTOR_BLOCK_BYTES (VECTOR_BLOCK_SIZE - vroundup_ct (sizeof (void *)))
2780 /* Size of the minimal vector allocated from block. */
2782 #define VBLOCK_BYTES_MIN vroundup_ct (header_size + sizeof (Lisp_Object))
2784 /* Size of the largest vector allocated from block. */
2786 #define VBLOCK_BYTES_MAX \
2787 vroundup ((VECTOR_BLOCK_BYTES / 2) - word_size)
2789 /* We maintain one free list for each possible block-allocated
2790 vector size, and this is the number of free lists we have. */
2792 #define VECTOR_MAX_FREE_LIST_INDEX \
2793 ((VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN) / roundup_size + 1)
2795 /* Common shortcut to advance vector pointer over a block data. */
2797 #define ADVANCE(v, nbytes) ((struct Lisp_Vector *) ((char *) (v) + (nbytes)))
2799 /* Common shortcut to calculate NBYTES-vector index in VECTOR_FREE_LISTS. */
2801 #define VINDEX(nbytes) (((nbytes) - VBLOCK_BYTES_MIN) / roundup_size)
2803 /* Common shortcut to setup vector on a free list. */
2805 #define SETUP_ON_FREE_LIST(v, nbytes, tmp) \
2806 do { \
2807 (tmp) = ((nbytes - header_size) / word_size); \
2808 XSETPVECTYPESIZE (v, PVEC_FREE, 0, (tmp)); \
2809 eassert ((nbytes) % roundup_size == 0); \
2810 (tmp) = VINDEX (nbytes); \
2811 eassert ((tmp) < VECTOR_MAX_FREE_LIST_INDEX); \
2812 set_next_vector (v, vector_free_lists[tmp]); \
2813 vector_free_lists[tmp] = (v); \
2814 total_free_vector_slots += (nbytes) / word_size; \
2815 } while (0)
2817 /* This internal type is used to maintain the list of large vectors
2818 which are allocated at their own, e.g. outside of vector blocks.
2820 struct large_vector itself cannot contain a struct Lisp_Vector, as
2821 the latter contains a flexible array member and C99 does not allow
2822 such structs to be nested. Instead, each struct large_vector
2823 object LV is followed by a struct Lisp_Vector, which is at offset
2824 large_vector_offset from LV, and whose address is therefore
2825 large_vector_vec (&LV). */
2827 struct large_vector
2829 struct large_vector *next;
2832 enum
2834 large_vector_offset = ROUNDUP (sizeof (struct large_vector), vector_alignment)
2837 static struct Lisp_Vector *
2838 large_vector_vec (struct large_vector *p)
2840 return (struct Lisp_Vector *) ((char *) p + large_vector_offset);
2843 /* This internal type is used to maintain an underlying storage
2844 for small vectors. */
2846 struct vector_block
2848 char data[VECTOR_BLOCK_BYTES];
2849 struct vector_block *next;
2852 /* Chain of vector blocks. */
2854 static struct vector_block *vector_blocks;
2856 /* Vector free lists, where NTH item points to a chain of free
2857 vectors of the same NBYTES size, so NTH == VINDEX (NBYTES). */
2859 static struct Lisp_Vector *vector_free_lists[VECTOR_MAX_FREE_LIST_INDEX];
2861 /* Singly-linked list of large vectors. */
2863 static struct large_vector *large_vectors;
2865 /* The only vector with 0 slots, allocated from pure space. */
2867 Lisp_Object zero_vector;
2869 /* Number of live vectors. */
2871 static EMACS_INT total_vectors;
2873 /* Total size of live and free vectors, in Lisp_Object units. */
2875 static EMACS_INT total_vector_slots, total_free_vector_slots;
2877 /* Get a new vector block. */
2879 static struct vector_block *
2880 allocate_vector_block (void)
2882 struct vector_block *block = xmalloc (sizeof *block);
2884 #ifndef GC_MALLOC_CHECK
2885 mem_insert (block->data, block->data + VECTOR_BLOCK_BYTES,
2886 MEM_TYPE_VECTOR_BLOCK);
2887 #endif
2889 block->next = vector_blocks;
2890 vector_blocks = block;
2891 return block;
2894 /* Called once to initialize vector allocation. */
2896 static void
2897 init_vectors (void)
2899 zero_vector = make_pure_vector (0);
2902 /* Allocate vector from a vector block. */
2904 static struct Lisp_Vector *
2905 allocate_vector_from_block (size_t nbytes)
2907 struct Lisp_Vector *vector;
2908 struct vector_block *block;
2909 size_t index, restbytes;
2911 eassert (VBLOCK_BYTES_MIN <= nbytes && nbytes <= VBLOCK_BYTES_MAX);
2912 eassert (nbytes % roundup_size == 0);
2914 /* First, try to allocate from a free list
2915 containing vectors of the requested size. */
2916 index = VINDEX (nbytes);
2917 if (vector_free_lists[index])
2919 vector = vector_free_lists[index];
2920 vector_free_lists[index] = next_vector (vector);
2921 total_free_vector_slots -= nbytes / word_size;
2922 return vector;
2925 /* Next, check free lists containing larger vectors. Since
2926 we will split the result, we should have remaining space
2927 large enough to use for one-slot vector at least. */
2928 for (index = VINDEX (nbytes + VBLOCK_BYTES_MIN);
2929 index < VECTOR_MAX_FREE_LIST_INDEX; index++)
2930 if (vector_free_lists[index])
2932 /* This vector is larger than requested. */
2933 vector = vector_free_lists[index];
2934 vector_free_lists[index] = next_vector (vector);
2935 total_free_vector_slots -= nbytes / word_size;
2937 /* Excess bytes are used for the smaller vector,
2938 which should be set on an appropriate free list. */
2939 restbytes = index * roundup_size + VBLOCK_BYTES_MIN - nbytes;
2940 eassert (restbytes % roundup_size == 0);
2941 SETUP_ON_FREE_LIST (ADVANCE (vector, nbytes), restbytes, index);
2942 return vector;
2945 /* Finally, need a new vector block. */
2946 block = allocate_vector_block ();
2948 /* New vector will be at the beginning of this block. */
2949 vector = (struct Lisp_Vector *) block->data;
2951 /* If the rest of space from this block is large enough
2952 for one-slot vector at least, set up it on a free list. */
2953 restbytes = VECTOR_BLOCK_BYTES - nbytes;
2954 if (restbytes >= VBLOCK_BYTES_MIN)
2956 eassert (restbytes % roundup_size == 0);
2957 SETUP_ON_FREE_LIST (ADVANCE (vector, nbytes), restbytes, index);
2959 return vector;
2962 /* Nonzero if VECTOR pointer is valid pointer inside BLOCK. */
2964 #define VECTOR_IN_BLOCK(vector, block) \
2965 ((char *) (vector) <= (block)->data \
2966 + VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN)
2968 /* Return the memory footprint of V in bytes. */
2970 static ptrdiff_t
2971 vector_nbytes (struct Lisp_Vector *v)
2973 ptrdiff_t size = v->header.size & ~ARRAY_MARK_FLAG;
2974 ptrdiff_t nwords;
2976 if (size & PSEUDOVECTOR_FLAG)
2978 if (PSEUDOVECTOR_TYPEP (&v->header, PVEC_BOOL_VECTOR))
2980 struct Lisp_Bool_Vector *bv = (struct Lisp_Bool_Vector *) v;
2981 ptrdiff_t word_bytes = (bool_vector_words (bv->size)
2982 * sizeof (bits_word));
2983 ptrdiff_t boolvec_bytes = bool_header_size + word_bytes;
2984 verify (header_size <= bool_header_size);
2985 nwords = (boolvec_bytes - header_size + word_size - 1) / word_size;
2987 else
2988 nwords = ((size & PSEUDOVECTOR_SIZE_MASK)
2989 + ((size & PSEUDOVECTOR_REST_MASK)
2990 >> PSEUDOVECTOR_SIZE_BITS));
2992 else
2993 nwords = size;
2994 return vroundup (header_size + word_size * nwords);
2997 /* Release extra resources still in use by VECTOR, which may be any
2998 vector-like object. For now, this is used just to free data in
2999 font objects. */
3001 static void
3002 cleanup_vector (struct Lisp_Vector *vector)
3004 detect_suspicious_free (vector);
3005 if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FONT)
3006 && ((vector->header.size & PSEUDOVECTOR_SIZE_MASK)
3007 == FONT_OBJECT_MAX))
3009 struct font_driver *drv = ((struct font *) vector)->driver;
3011 /* The font driver might sometimes be NULL, e.g. if Emacs was
3012 interrupted before it had time to set it up. */
3013 if (drv)
3015 /* Attempt to catch subtle bugs like Bug#16140. */
3016 eassert (valid_font_driver (drv));
3017 drv->close ((struct font *) vector);
3022 /* Reclaim space used by unmarked vectors. */
3024 NO_INLINE /* For better stack traces */
3025 static void
3026 sweep_vectors (void)
3028 struct vector_block *block, **bprev = &vector_blocks;
3029 struct large_vector *lv, **lvprev = &large_vectors;
3030 struct Lisp_Vector *vector, *next;
3032 total_vectors = total_vector_slots = total_free_vector_slots = 0;
3033 memset (vector_free_lists, 0, sizeof (vector_free_lists));
3035 /* Looking through vector blocks. */
3037 for (block = vector_blocks; block; block = *bprev)
3039 bool free_this_block = 0;
3040 ptrdiff_t nbytes;
3042 for (vector = (struct Lisp_Vector *) block->data;
3043 VECTOR_IN_BLOCK (vector, block); vector = next)
3045 if (VECTOR_MARKED_P (vector))
3047 VECTOR_UNMARK (vector);
3048 total_vectors++;
3049 nbytes = vector_nbytes (vector);
3050 total_vector_slots += nbytes / word_size;
3051 next = ADVANCE (vector, nbytes);
3053 else
3055 ptrdiff_t total_bytes;
3057 cleanup_vector (vector);
3058 nbytes = vector_nbytes (vector);
3059 total_bytes = nbytes;
3060 next = ADVANCE (vector, nbytes);
3062 /* While NEXT is not marked, try to coalesce with VECTOR,
3063 thus making VECTOR of the largest possible size. */
3065 while (VECTOR_IN_BLOCK (next, block))
3067 if (VECTOR_MARKED_P (next))
3068 break;
3069 cleanup_vector (next);
3070 nbytes = vector_nbytes (next);
3071 total_bytes += nbytes;
3072 next = ADVANCE (next, nbytes);
3075 eassert (total_bytes % roundup_size == 0);
3077 if (vector == (struct Lisp_Vector *) block->data
3078 && !VECTOR_IN_BLOCK (next, block))
3079 /* This block should be freed because all of its
3080 space was coalesced into the only free vector. */
3081 free_this_block = 1;
3082 else
3084 size_t tmp;
3085 SETUP_ON_FREE_LIST (vector, total_bytes, tmp);
3090 if (free_this_block)
3092 *bprev = block->next;
3093 #ifndef GC_MALLOC_CHECK
3094 mem_delete (mem_find (block->data));
3095 #endif
3096 xfree (block);
3098 else
3099 bprev = &block->next;
3102 /* Sweep large vectors. */
3104 for (lv = large_vectors; lv; lv = *lvprev)
3106 vector = large_vector_vec (lv);
3107 if (VECTOR_MARKED_P (vector))
3109 VECTOR_UNMARK (vector);
3110 total_vectors++;
3111 if (vector->header.size & PSEUDOVECTOR_FLAG)
3113 /* All non-bool pseudovectors are small enough to be allocated
3114 from vector blocks. This code should be redesigned if some
3115 pseudovector type grows beyond VBLOCK_BYTES_MAX. */
3116 eassert (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_BOOL_VECTOR));
3117 total_vector_slots += vector_nbytes (vector) / word_size;
3119 else
3120 total_vector_slots
3121 += header_size / word_size + vector->header.size;
3122 lvprev = &lv->next;
3124 else
3126 *lvprev = lv->next;
3127 lisp_free (lv);
3132 /* Value is a pointer to a newly allocated Lisp_Vector structure
3133 with room for LEN Lisp_Objects. */
3135 static struct Lisp_Vector *
3136 allocate_vectorlike (ptrdiff_t len)
3138 struct Lisp_Vector *p;
3140 MALLOC_BLOCK_INPUT;
3142 if (len == 0)
3143 p = XVECTOR (zero_vector);
3144 else
3146 size_t nbytes = header_size + len * word_size;
3148 #ifdef DOUG_LEA_MALLOC
3149 if (!mmap_lisp_allowed_p ())
3150 mallopt (M_MMAP_MAX, 0);
3151 #endif
3153 if (nbytes <= VBLOCK_BYTES_MAX)
3154 p = allocate_vector_from_block (vroundup (nbytes));
3155 else
3157 struct large_vector *lv
3158 = lisp_malloc ((large_vector_offset + header_size
3159 + len * word_size),
3160 MEM_TYPE_VECTORLIKE);
3161 lv->next = large_vectors;
3162 large_vectors = lv;
3163 p = large_vector_vec (lv);
3166 #ifdef DOUG_LEA_MALLOC
3167 if (!mmap_lisp_allowed_p ())
3168 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
3169 #endif
3171 if (find_suspicious_object_in_range (p, (char *) p + nbytes))
3172 emacs_abort ();
3174 consing_since_gc += nbytes;
3175 vector_cells_consed += len;
3178 MALLOC_UNBLOCK_INPUT;
3180 return p;
3184 /* Allocate a vector with LEN slots. */
3186 struct Lisp_Vector *
3187 allocate_vector (EMACS_INT len)
3189 struct Lisp_Vector *v;
3190 ptrdiff_t nbytes_max = min (PTRDIFF_MAX, SIZE_MAX);
3192 if (min ((nbytes_max - header_size) / word_size, MOST_POSITIVE_FIXNUM) < len)
3193 memory_full (SIZE_MAX);
3194 v = allocate_vectorlike (len);
3195 if (len)
3196 v->header.size = len;
3197 return v;
3201 /* Allocate other vector-like structures. */
3203 struct Lisp_Vector *
3204 allocate_pseudovector (int memlen, int lisplen,
3205 int zerolen, enum pvec_type tag)
3207 struct Lisp_Vector *v = allocate_vectorlike (memlen);
3209 /* Catch bogus values. */
3210 eassert (0 <= tag && tag <= PVEC_FONT);
3211 eassert (0 <= lisplen && lisplen <= zerolen && zerolen <= memlen);
3212 eassert (memlen - lisplen <= (1 << PSEUDOVECTOR_REST_BITS) - 1);
3213 eassert (lisplen <= (1 << PSEUDOVECTOR_SIZE_BITS) - 1);
3215 /* Only the first LISPLEN slots will be traced normally by the GC. */
3216 memclear (v->contents, zerolen * word_size);
3217 XSETPVECTYPESIZE (v, tag, lisplen, memlen - lisplen);
3218 return v;
3221 struct buffer *
3222 allocate_buffer (void)
3224 struct buffer *b = lisp_malloc (sizeof *b, MEM_TYPE_BUFFER);
3226 BUFFER_PVEC_INIT (b);
3227 /* Put B on the chain of all buffers including killed ones. */
3228 b->next = all_buffers;
3229 all_buffers = b;
3230 /* Note that the rest fields of B are not initialized. */
3231 return b;
3234 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
3235 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
3236 See also the function `vector'. */)
3237 (register Lisp_Object length, Lisp_Object init)
3239 Lisp_Object vector;
3240 register ptrdiff_t sizei;
3241 register ptrdiff_t i;
3242 register struct Lisp_Vector *p;
3244 CHECK_NATNUM (length);
3246 p = allocate_vector (XFASTINT (length));
3247 sizei = XFASTINT (length);
3248 for (i = 0; i < sizei; i++)
3249 p->contents[i] = init;
3251 XSETVECTOR (vector, p);
3252 return vector;
3255 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3256 doc: /* Return a newly created vector with specified arguments as elements.
3257 Any number of arguments, even zero arguments, are allowed.
3258 usage: (vector &rest OBJECTS) */)
3259 (ptrdiff_t nargs, Lisp_Object *args)
3261 ptrdiff_t i;
3262 register Lisp_Object val = make_uninit_vector (nargs);
3263 register struct Lisp_Vector *p = XVECTOR (val);
3265 for (i = 0; i < nargs; i++)
3266 p->contents[i] = args[i];
3267 return val;
3270 void
3271 make_byte_code (struct Lisp_Vector *v)
3273 /* Don't allow the global zero_vector to become a byte code object. */
3274 eassert (0 < v->header.size);
3276 if (v->header.size > 1 && STRINGP (v->contents[1])
3277 && STRING_MULTIBYTE (v->contents[1]))
3278 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3279 earlier because they produced a raw 8-bit string for byte-code
3280 and now such a byte-code string is loaded as multibyte while
3281 raw 8-bit characters converted to multibyte form. Thus, now we
3282 must convert them back to the original unibyte form. */
3283 v->contents[1] = Fstring_as_unibyte (v->contents[1]);
3284 XSETPVECTYPE (v, PVEC_COMPILED);
3287 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3288 doc: /* Create a byte-code object with specified arguments as elements.
3289 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3290 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3291 and (optional) INTERACTIVE-SPEC.
3292 The first four arguments are required; at most six have any
3293 significance.
3294 The ARGLIST can be either like the one of `lambda', in which case the arguments
3295 will be dynamically bound before executing the byte code, or it can be an
3296 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3297 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3298 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3299 argument to catch the left-over arguments. If such an integer is used, the
3300 arguments will not be dynamically bound but will be instead pushed on the
3301 stack before executing the byte-code.
3302 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3303 (ptrdiff_t nargs, Lisp_Object *args)
3305 ptrdiff_t i;
3306 register Lisp_Object val = make_uninit_vector (nargs);
3307 register struct Lisp_Vector *p = XVECTOR (val);
3309 /* We used to purecopy everything here, if purify-flag was set. This worked
3310 OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
3311 dangerous, since make-byte-code is used during execution to build
3312 closures, so any closure built during the preload phase would end up
3313 copied into pure space, including its free variables, which is sometimes
3314 just wasteful and other times plainly wrong (e.g. those free vars may want
3315 to be setcar'd). */
3317 for (i = 0; i < nargs; i++)
3318 p->contents[i] = args[i];
3319 make_byte_code (p);
3320 XSETCOMPILED (val, p);
3321 return val;
3326 /***********************************************************************
3327 Symbol Allocation
3328 ***********************************************************************/
3330 /* Like struct Lisp_Symbol, but padded so that the size is a multiple
3331 of the required alignment. */
3333 union aligned_Lisp_Symbol
3335 struct Lisp_Symbol s;
3336 unsigned char c[(sizeof (struct Lisp_Symbol) + GCALIGNMENT - 1)
3337 & -GCALIGNMENT];
3340 /* Each symbol_block is just under 1020 bytes long, since malloc
3341 really allocates in units of powers of two and uses 4 bytes for its
3342 own overhead. */
3344 #define SYMBOL_BLOCK_SIZE \
3345 ((1020 - sizeof (struct symbol_block *)) / sizeof (union aligned_Lisp_Symbol))
3347 struct symbol_block
3349 /* Place `symbols' first, to preserve alignment. */
3350 union aligned_Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3351 struct symbol_block *next;
3354 /* Current symbol block and index of first unused Lisp_Symbol
3355 structure in it. */
3357 static struct symbol_block *symbol_block;
3358 static int symbol_block_index = SYMBOL_BLOCK_SIZE;
3359 /* Pointer to the first symbol_block that contains pinned symbols.
3360 Tests for 24.4 showed that at dump-time, Emacs contains about 15K symbols,
3361 10K of which are pinned (and all but 250 of them are interned in obarray),
3362 whereas a "typical session" has in the order of 30K symbols.
3363 `symbol_block_pinned' lets mark_pinned_symbols scan only 15K symbols rather
3364 than 30K to find the 10K symbols we need to mark. */
3365 static struct symbol_block *symbol_block_pinned;
3367 /* List of free symbols. */
3369 static struct Lisp_Symbol *symbol_free_list;
3371 static void
3372 set_symbol_name (Lisp_Object sym, Lisp_Object name)
3374 XSYMBOL (sym)->name = name;
3377 void
3378 init_symbol (Lisp_Object val, Lisp_Object name)
3380 struct Lisp_Symbol *p = XSYMBOL (val);
3381 set_symbol_name (val, name);
3382 set_symbol_plist (val, Qnil);
3383 p->redirect = SYMBOL_PLAINVAL;
3384 SET_SYMBOL_VAL (p, Qunbound);
3385 set_symbol_function (val, Qnil);
3386 set_symbol_next (val, NULL);
3387 p->gcmarkbit = false;
3388 p->interned = SYMBOL_UNINTERNED;
3389 p->constant = 0;
3390 p->declared_special = false;
3391 p->pinned = false;
3394 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3395 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3396 Its value is void, and its function definition and property list are nil. */)
3397 (Lisp_Object name)
3399 Lisp_Object val;
3401 CHECK_STRING (name);
3403 MALLOC_BLOCK_INPUT;
3405 if (symbol_free_list)
3407 XSETSYMBOL (val, symbol_free_list);
3408 symbol_free_list = symbol_free_list->next;
3410 else
3412 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3414 struct symbol_block *new
3415 = lisp_malloc (sizeof *new, MEM_TYPE_SYMBOL);
3416 new->next = symbol_block;
3417 symbol_block = new;
3418 symbol_block_index = 0;
3419 total_free_symbols += SYMBOL_BLOCK_SIZE;
3421 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index].s);
3422 symbol_block_index++;
3425 MALLOC_UNBLOCK_INPUT;
3427 init_symbol (val, name);
3428 consing_since_gc += sizeof (struct Lisp_Symbol);
3429 symbols_consed++;
3430 total_free_symbols--;
3431 return val;
3436 /***********************************************************************
3437 Marker (Misc) Allocation
3438 ***********************************************************************/
3440 /* Like union Lisp_Misc, but padded so that its size is a multiple of
3441 the required alignment. */
3443 union aligned_Lisp_Misc
3445 union Lisp_Misc m;
3446 unsigned char c[(sizeof (union Lisp_Misc) + GCALIGNMENT - 1)
3447 & -GCALIGNMENT];
3450 /* Allocation of markers and other objects that share that structure.
3451 Works like allocation of conses. */
3453 #define MARKER_BLOCK_SIZE \
3454 ((1020 - sizeof (struct marker_block *)) / sizeof (union aligned_Lisp_Misc))
3456 struct marker_block
3458 /* Place `markers' first, to preserve alignment. */
3459 union aligned_Lisp_Misc markers[MARKER_BLOCK_SIZE];
3460 struct marker_block *next;
3463 static struct marker_block *marker_block;
3464 static int marker_block_index = MARKER_BLOCK_SIZE;
3466 static union Lisp_Misc *marker_free_list;
3468 /* Return a newly allocated Lisp_Misc object of specified TYPE. */
3470 static Lisp_Object
3471 allocate_misc (enum Lisp_Misc_Type type)
3473 Lisp_Object val;
3475 MALLOC_BLOCK_INPUT;
3477 if (marker_free_list)
3479 XSETMISC (val, marker_free_list);
3480 marker_free_list = marker_free_list->u_free.chain;
3482 else
3484 if (marker_block_index == MARKER_BLOCK_SIZE)
3486 struct marker_block *new = lisp_malloc (sizeof *new, MEM_TYPE_MISC);
3487 new->next = marker_block;
3488 marker_block = new;
3489 marker_block_index = 0;
3490 total_free_markers += MARKER_BLOCK_SIZE;
3492 XSETMISC (val, &marker_block->markers[marker_block_index].m);
3493 marker_block_index++;
3496 MALLOC_UNBLOCK_INPUT;
3498 --total_free_markers;
3499 consing_since_gc += sizeof (union Lisp_Misc);
3500 misc_objects_consed++;
3501 XMISCANY (val)->type = type;
3502 XMISCANY (val)->gcmarkbit = 0;
3503 return val;
3506 /* Free a Lisp_Misc object. */
3508 void
3509 free_misc (Lisp_Object misc)
3511 XMISCANY (misc)->type = Lisp_Misc_Free;
3512 XMISC (misc)->u_free.chain = marker_free_list;
3513 marker_free_list = XMISC (misc);
3514 consing_since_gc -= sizeof (union Lisp_Misc);
3515 total_free_markers++;
3518 /* Verify properties of Lisp_Save_Value's representation
3519 that are assumed here and elsewhere. */
3521 verify (SAVE_UNUSED == 0);
3522 verify (((SAVE_INTEGER | SAVE_POINTER | SAVE_FUNCPOINTER | SAVE_OBJECT)
3523 >> SAVE_SLOT_BITS)
3524 == 0);
3526 /* Return Lisp_Save_Value objects for the various combinations
3527 that callers need. */
3529 Lisp_Object
3530 make_save_int_int_int (ptrdiff_t a, ptrdiff_t b, ptrdiff_t c)
3532 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3533 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3534 p->save_type = SAVE_TYPE_INT_INT_INT;
3535 p->data[0].integer = a;
3536 p->data[1].integer = b;
3537 p->data[2].integer = c;
3538 return val;
3541 Lisp_Object
3542 make_save_obj_obj_obj_obj (Lisp_Object a, Lisp_Object b, Lisp_Object c,
3543 Lisp_Object d)
3545 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3546 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3547 p->save_type = SAVE_TYPE_OBJ_OBJ_OBJ_OBJ;
3548 p->data[0].object = a;
3549 p->data[1].object = b;
3550 p->data[2].object = c;
3551 p->data[3].object = d;
3552 return val;
3555 Lisp_Object
3556 make_save_ptr (void *a)
3558 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3559 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3560 p->save_type = SAVE_POINTER;
3561 p->data[0].pointer = a;
3562 return val;
3565 Lisp_Object
3566 make_save_ptr_int (void *a, ptrdiff_t b)
3568 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3569 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3570 p->save_type = SAVE_TYPE_PTR_INT;
3571 p->data[0].pointer = a;
3572 p->data[1].integer = b;
3573 return val;
3576 #if ! (defined USE_X_TOOLKIT || defined USE_GTK)
3577 Lisp_Object
3578 make_save_ptr_ptr (void *a, void *b)
3580 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3581 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3582 p->save_type = SAVE_TYPE_PTR_PTR;
3583 p->data[0].pointer = a;
3584 p->data[1].pointer = b;
3585 return val;
3587 #endif
3589 Lisp_Object
3590 make_save_funcptr_ptr_obj (void (*a) (void), void *b, Lisp_Object c)
3592 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3593 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3594 p->save_type = SAVE_TYPE_FUNCPTR_PTR_OBJ;
3595 p->data[0].funcpointer = a;
3596 p->data[1].pointer = b;
3597 p->data[2].object = c;
3598 return val;
3601 /* Return a Lisp_Save_Value object that represents an array A
3602 of N Lisp objects. */
3604 Lisp_Object
3605 make_save_memory (Lisp_Object *a, ptrdiff_t n)
3607 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3608 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3609 p->save_type = SAVE_TYPE_MEMORY;
3610 p->data[0].pointer = a;
3611 p->data[1].integer = n;
3612 return val;
3615 /* Free a Lisp_Save_Value object. Do not use this function
3616 if SAVE contains pointer other than returned by xmalloc. */
3618 void
3619 free_save_value (Lisp_Object save)
3621 xfree (XSAVE_POINTER (save, 0));
3622 free_misc (save);
3625 /* Return a Lisp_Misc_Overlay object with specified START, END and PLIST. */
3627 Lisp_Object
3628 build_overlay (Lisp_Object start, Lisp_Object end, Lisp_Object plist)
3630 register Lisp_Object overlay;
3632 overlay = allocate_misc (Lisp_Misc_Overlay);
3633 OVERLAY_START (overlay) = start;
3634 OVERLAY_END (overlay) = end;
3635 set_overlay_plist (overlay, plist);
3636 XOVERLAY (overlay)->next = NULL;
3637 return overlay;
3640 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3641 doc: /* Return a newly allocated marker which does not point at any place. */)
3642 (void)
3644 register Lisp_Object val;
3645 register struct Lisp_Marker *p;
3647 val = allocate_misc (Lisp_Misc_Marker);
3648 p = XMARKER (val);
3649 p->buffer = 0;
3650 p->bytepos = 0;
3651 p->charpos = 0;
3652 p->next = NULL;
3653 p->insertion_type = 0;
3654 p->need_adjustment = 0;
3655 return val;
3658 /* Return a newly allocated marker which points into BUF
3659 at character position CHARPOS and byte position BYTEPOS. */
3661 Lisp_Object
3662 build_marker (struct buffer *buf, ptrdiff_t charpos, ptrdiff_t bytepos)
3664 Lisp_Object obj;
3665 struct Lisp_Marker *m;
3667 /* No dead buffers here. */
3668 eassert (BUFFER_LIVE_P (buf));
3670 /* Every character is at least one byte. */
3671 eassert (charpos <= bytepos);
3673 obj = allocate_misc (Lisp_Misc_Marker);
3674 m = XMARKER (obj);
3675 m->buffer = buf;
3676 m->charpos = charpos;
3677 m->bytepos = bytepos;
3678 m->insertion_type = 0;
3679 m->need_adjustment = 0;
3680 m->next = BUF_MARKERS (buf);
3681 BUF_MARKERS (buf) = m;
3682 return obj;
3685 /* Put MARKER back on the free list after using it temporarily. */
3687 void
3688 free_marker (Lisp_Object marker)
3690 unchain_marker (XMARKER (marker));
3691 free_misc (marker);
3695 /* Return a newly created vector or string with specified arguments as
3696 elements. If all the arguments are characters that can fit
3697 in a string of events, make a string; otherwise, make a vector.
3699 Any number of arguments, even zero arguments, are allowed. */
3701 Lisp_Object
3702 make_event_array (ptrdiff_t nargs, Lisp_Object *args)
3704 ptrdiff_t i;
3706 for (i = 0; i < nargs; i++)
3707 /* The things that fit in a string
3708 are characters that are in 0...127,
3709 after discarding the meta bit and all the bits above it. */
3710 if (!INTEGERP (args[i])
3711 || (XINT (args[i]) & ~(-CHAR_META)) >= 0200)
3712 return Fvector (nargs, args);
3714 /* Since the loop exited, we know that all the things in it are
3715 characters, so we can make a string. */
3717 Lisp_Object result;
3719 result = Fmake_string (make_number (nargs), make_number (0));
3720 for (i = 0; i < nargs; i++)
3722 SSET (result, i, XINT (args[i]));
3723 /* Move the meta bit to the right place for a string char. */
3724 if (XINT (args[i]) & CHAR_META)
3725 SSET (result, i, SREF (result, i) | 0x80);
3728 return result;
3732 #ifdef HAVE_MODULES
3733 /* Create a new module user ptr object. */
3734 Lisp_Object
3735 make_user_ptr (void (*finalizer) (void *), void *p)
3737 Lisp_Object obj;
3738 struct Lisp_User_Ptr *uptr;
3740 obj = allocate_misc (Lisp_Misc_User_Ptr);
3741 uptr = XUSER_PTR (obj);
3742 uptr->finalizer = finalizer;
3743 uptr->p = p;
3744 return obj;
3747 #endif
3749 static void
3750 init_finalizer_list (struct Lisp_Finalizer *head)
3752 head->prev = head->next = head;
3755 /* Insert FINALIZER before ELEMENT. */
3757 static void
3758 finalizer_insert (struct Lisp_Finalizer *element,
3759 struct Lisp_Finalizer *finalizer)
3761 eassert (finalizer->prev == NULL);
3762 eassert (finalizer->next == NULL);
3763 finalizer->next = element;
3764 finalizer->prev = element->prev;
3765 finalizer->prev->next = finalizer;
3766 element->prev = finalizer;
3769 static void
3770 unchain_finalizer (struct Lisp_Finalizer *finalizer)
3772 if (finalizer->prev != NULL)
3774 eassert (finalizer->next != NULL);
3775 finalizer->prev->next = finalizer->next;
3776 finalizer->next->prev = finalizer->prev;
3777 finalizer->prev = finalizer->next = NULL;
3781 static void
3782 mark_finalizer_list (struct Lisp_Finalizer *head)
3784 for (struct Lisp_Finalizer *finalizer = head->next;
3785 finalizer != head;
3786 finalizer = finalizer->next)
3788 finalizer->base.gcmarkbit = true;
3789 mark_object (finalizer->function);
3793 /* Move doomed finalizers to list DEST from list SRC. A doomed
3794 finalizer is one that is not GC-reachable and whose
3795 finalizer->function is non-nil. */
3797 static void
3798 queue_doomed_finalizers (struct Lisp_Finalizer *dest,
3799 struct Lisp_Finalizer *src)
3801 struct Lisp_Finalizer *finalizer = src->next;
3802 while (finalizer != src)
3804 struct Lisp_Finalizer *next = finalizer->next;
3805 if (!finalizer->base.gcmarkbit && !NILP (finalizer->function))
3807 unchain_finalizer (finalizer);
3808 finalizer_insert (dest, finalizer);
3811 finalizer = next;
3815 static Lisp_Object
3816 run_finalizer_handler (Lisp_Object args)
3818 add_to_log ("finalizer failed: %S", args);
3819 return Qnil;
3822 static void
3823 run_finalizer_function (Lisp_Object function)
3825 ptrdiff_t count = SPECPDL_INDEX ();
3827 specbind (Qinhibit_quit, Qt);
3828 internal_condition_case_1 (call0, function, Qt, run_finalizer_handler);
3829 unbind_to (count, Qnil);
3832 static void
3833 run_finalizers (struct Lisp_Finalizer *finalizers)
3835 struct Lisp_Finalizer *finalizer;
3836 Lisp_Object function;
3838 while (finalizers->next != finalizers)
3840 finalizer = finalizers->next;
3841 eassert (finalizer->base.type == Lisp_Misc_Finalizer);
3842 unchain_finalizer (finalizer);
3843 function = finalizer->function;
3844 if (!NILP (function))
3846 finalizer->function = Qnil;
3847 run_finalizer_function (function);
3852 DEFUN ("make-finalizer", Fmake_finalizer, Smake_finalizer, 1, 1, 0,
3853 doc: /* Make a finalizer that will run FUNCTION.
3854 FUNCTION will be called after garbage collection when the returned
3855 finalizer object becomes unreachable. If the finalizer object is
3856 reachable only through references from finalizer objects, it does not
3857 count as reachable for the purpose of deciding whether to run
3858 FUNCTION. FUNCTION will be run once per finalizer object. */)
3859 (Lisp_Object function)
3861 Lisp_Object val = allocate_misc (Lisp_Misc_Finalizer);
3862 struct Lisp_Finalizer *finalizer = XFINALIZER (val);
3863 finalizer->function = function;
3864 finalizer->prev = finalizer->next = NULL;
3865 finalizer_insert (&finalizers, finalizer);
3866 return val;
3870 /************************************************************************
3871 Memory Full Handling
3872 ************************************************************************/
3875 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
3876 there may have been size_t overflow so that malloc was never
3877 called, or perhaps malloc was invoked successfully but the
3878 resulting pointer had problems fitting into a tagged EMACS_INT. In
3879 either case this counts as memory being full even though malloc did
3880 not fail. */
3882 void
3883 memory_full (size_t nbytes)
3885 /* Do not go into hysterics merely because a large request failed. */
3886 bool enough_free_memory = 0;
3887 if (SPARE_MEMORY < nbytes)
3889 void *p;
3891 MALLOC_BLOCK_INPUT;
3892 p = malloc (SPARE_MEMORY);
3893 if (p)
3895 free (p);
3896 enough_free_memory = 1;
3898 MALLOC_UNBLOCK_INPUT;
3901 if (! enough_free_memory)
3903 int i;
3905 Vmemory_full = Qt;
3907 memory_full_cons_threshold = sizeof (struct cons_block);
3909 /* The first time we get here, free the spare memory. */
3910 for (i = 0; i < ARRAYELTS (spare_memory); i++)
3911 if (spare_memory[i])
3913 if (i == 0)
3914 free (spare_memory[i]);
3915 else if (i >= 1 && i <= 4)
3916 lisp_align_free (spare_memory[i]);
3917 else
3918 lisp_free (spare_memory[i]);
3919 spare_memory[i] = 0;
3923 /* This used to call error, but if we've run out of memory, we could
3924 get infinite recursion trying to build the string. */
3925 xsignal (Qnil, Vmemory_signal_data);
3928 /* If we released our reserve (due to running out of memory),
3929 and we have a fair amount free once again,
3930 try to set aside another reserve in case we run out once more.
3932 This is called when a relocatable block is freed in ralloc.c,
3933 and also directly from this file, in case we're not using ralloc.c. */
3935 void
3936 refill_memory_reserve (void)
3938 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
3939 if (spare_memory[0] == 0)
3940 spare_memory[0] = malloc (SPARE_MEMORY);
3941 if (spare_memory[1] == 0)
3942 spare_memory[1] = lisp_align_malloc (sizeof (struct cons_block),
3943 MEM_TYPE_SPARE);
3944 if (spare_memory[2] == 0)
3945 spare_memory[2] = lisp_align_malloc (sizeof (struct cons_block),
3946 MEM_TYPE_SPARE);
3947 if (spare_memory[3] == 0)
3948 spare_memory[3] = lisp_align_malloc (sizeof (struct cons_block),
3949 MEM_TYPE_SPARE);
3950 if (spare_memory[4] == 0)
3951 spare_memory[4] = lisp_align_malloc (sizeof (struct cons_block),
3952 MEM_TYPE_SPARE);
3953 if (spare_memory[5] == 0)
3954 spare_memory[5] = lisp_malloc (sizeof (struct string_block),
3955 MEM_TYPE_SPARE);
3956 if (spare_memory[6] == 0)
3957 spare_memory[6] = lisp_malloc (sizeof (struct string_block),
3958 MEM_TYPE_SPARE);
3959 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
3960 Vmemory_full = Qnil;
3961 #endif
3964 /************************************************************************
3965 C Stack Marking
3966 ************************************************************************/
3968 /* Conservative C stack marking requires a method to identify possibly
3969 live Lisp objects given a pointer value. We do this by keeping
3970 track of blocks of Lisp data that are allocated in a red-black tree
3971 (see also the comment of mem_node which is the type of nodes in
3972 that tree). Function lisp_malloc adds information for an allocated
3973 block to the red-black tree with calls to mem_insert, and function
3974 lisp_free removes it with mem_delete. Functions live_string_p etc
3975 call mem_find to lookup information about a given pointer in the
3976 tree, and use that to determine if the pointer points to a Lisp
3977 object or not. */
3979 /* Initialize this part of alloc.c. */
3981 static void
3982 mem_init (void)
3984 mem_z.left = mem_z.right = MEM_NIL;
3985 mem_z.parent = NULL;
3986 mem_z.color = MEM_BLACK;
3987 mem_z.start = mem_z.end = NULL;
3988 mem_root = MEM_NIL;
3992 /* Value is a pointer to the mem_node containing START. Value is
3993 MEM_NIL if there is no node in the tree containing START. */
3995 static struct mem_node *
3996 mem_find (void *start)
3998 struct mem_node *p;
4000 if (start < min_heap_address || start > max_heap_address)
4001 return MEM_NIL;
4003 /* Make the search always successful to speed up the loop below. */
4004 mem_z.start = start;
4005 mem_z.end = (char *) start + 1;
4007 p = mem_root;
4008 while (start < p->start || start >= p->end)
4009 p = start < p->start ? p->left : p->right;
4010 return p;
4014 /* Insert a new node into the tree for a block of memory with start
4015 address START, end address END, and type TYPE. Value is a
4016 pointer to the node that was inserted. */
4018 static struct mem_node *
4019 mem_insert (void *start, void *end, enum mem_type type)
4021 struct mem_node *c, *parent, *x;
4023 if (min_heap_address == NULL || start < min_heap_address)
4024 min_heap_address = start;
4025 if (max_heap_address == NULL || end > max_heap_address)
4026 max_heap_address = end;
4028 /* See where in the tree a node for START belongs. In this
4029 particular application, it shouldn't happen that a node is already
4030 present. For debugging purposes, let's check that. */
4031 c = mem_root;
4032 parent = NULL;
4034 while (c != MEM_NIL)
4036 parent = c;
4037 c = start < c->start ? c->left : c->right;
4040 /* Create a new node. */
4041 #ifdef GC_MALLOC_CHECK
4042 x = malloc (sizeof *x);
4043 if (x == NULL)
4044 emacs_abort ();
4045 #else
4046 x = xmalloc (sizeof *x);
4047 #endif
4048 x->start = start;
4049 x->end = end;
4050 x->type = type;
4051 x->parent = parent;
4052 x->left = x->right = MEM_NIL;
4053 x->color = MEM_RED;
4055 /* Insert it as child of PARENT or install it as root. */
4056 if (parent)
4058 if (start < parent->start)
4059 parent->left = x;
4060 else
4061 parent->right = x;
4063 else
4064 mem_root = x;
4066 /* Re-establish red-black tree properties. */
4067 mem_insert_fixup (x);
4069 return x;
4073 /* Re-establish the red-black properties of the tree, and thereby
4074 balance the tree, after node X has been inserted; X is always red. */
4076 static void
4077 mem_insert_fixup (struct mem_node *x)
4079 while (x != mem_root && x->parent->color == MEM_RED)
4081 /* X is red and its parent is red. This is a violation of
4082 red-black tree property #3. */
4084 if (x->parent == x->parent->parent->left)
4086 /* We're on the left side of our grandparent, and Y is our
4087 "uncle". */
4088 struct mem_node *y = x->parent->parent->right;
4090 if (y->color == MEM_RED)
4092 /* Uncle and parent are red but should be black because
4093 X is red. Change the colors accordingly and proceed
4094 with the grandparent. */
4095 x->parent->color = MEM_BLACK;
4096 y->color = MEM_BLACK;
4097 x->parent->parent->color = MEM_RED;
4098 x = x->parent->parent;
4100 else
4102 /* Parent and uncle have different colors; parent is
4103 red, uncle is black. */
4104 if (x == x->parent->right)
4106 x = x->parent;
4107 mem_rotate_left (x);
4110 x->parent->color = MEM_BLACK;
4111 x->parent->parent->color = MEM_RED;
4112 mem_rotate_right (x->parent->parent);
4115 else
4117 /* This is the symmetrical case of above. */
4118 struct mem_node *y = x->parent->parent->left;
4120 if (y->color == MEM_RED)
4122 x->parent->color = MEM_BLACK;
4123 y->color = MEM_BLACK;
4124 x->parent->parent->color = MEM_RED;
4125 x = x->parent->parent;
4127 else
4129 if (x == x->parent->left)
4131 x = x->parent;
4132 mem_rotate_right (x);
4135 x->parent->color = MEM_BLACK;
4136 x->parent->parent->color = MEM_RED;
4137 mem_rotate_left (x->parent->parent);
4142 /* The root may have been changed to red due to the algorithm. Set
4143 it to black so that property #5 is satisfied. */
4144 mem_root->color = MEM_BLACK;
4148 /* (x) (y)
4149 / \ / \
4150 a (y) ===> (x) c
4151 / \ / \
4152 b c a b */
4154 static void
4155 mem_rotate_left (struct mem_node *x)
4157 struct mem_node *y;
4159 /* Turn y's left sub-tree into x's right sub-tree. */
4160 y = x->right;
4161 x->right = y->left;
4162 if (y->left != MEM_NIL)
4163 y->left->parent = x;
4165 /* Y's parent was x's parent. */
4166 if (y != MEM_NIL)
4167 y->parent = x->parent;
4169 /* Get the parent to point to y instead of x. */
4170 if (x->parent)
4172 if (x == x->parent->left)
4173 x->parent->left = y;
4174 else
4175 x->parent->right = y;
4177 else
4178 mem_root = y;
4180 /* Put x on y's left. */
4181 y->left = x;
4182 if (x != MEM_NIL)
4183 x->parent = y;
4187 /* (x) (Y)
4188 / \ / \
4189 (y) c ===> a (x)
4190 / \ / \
4191 a b b c */
4193 static void
4194 mem_rotate_right (struct mem_node *x)
4196 struct mem_node *y = x->left;
4198 x->left = y->right;
4199 if (y->right != MEM_NIL)
4200 y->right->parent = x;
4202 if (y != MEM_NIL)
4203 y->parent = x->parent;
4204 if (x->parent)
4206 if (x == x->parent->right)
4207 x->parent->right = y;
4208 else
4209 x->parent->left = y;
4211 else
4212 mem_root = y;
4214 y->right = x;
4215 if (x != MEM_NIL)
4216 x->parent = y;
4220 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
4222 static void
4223 mem_delete (struct mem_node *z)
4225 struct mem_node *x, *y;
4227 if (!z || z == MEM_NIL)
4228 return;
4230 if (z->left == MEM_NIL || z->right == MEM_NIL)
4231 y = z;
4232 else
4234 y = z->right;
4235 while (y->left != MEM_NIL)
4236 y = y->left;
4239 if (y->left != MEM_NIL)
4240 x = y->left;
4241 else
4242 x = y->right;
4244 x->parent = y->parent;
4245 if (y->parent)
4247 if (y == y->parent->left)
4248 y->parent->left = x;
4249 else
4250 y->parent->right = x;
4252 else
4253 mem_root = x;
4255 if (y != z)
4257 z->start = y->start;
4258 z->end = y->end;
4259 z->type = y->type;
4262 if (y->color == MEM_BLACK)
4263 mem_delete_fixup (x);
4265 #ifdef GC_MALLOC_CHECK
4266 free (y);
4267 #else
4268 xfree (y);
4269 #endif
4273 /* Re-establish the red-black properties of the tree, after a
4274 deletion. */
4276 static void
4277 mem_delete_fixup (struct mem_node *x)
4279 while (x != mem_root && x->color == MEM_BLACK)
4281 if (x == x->parent->left)
4283 struct mem_node *w = x->parent->right;
4285 if (w->color == MEM_RED)
4287 w->color = MEM_BLACK;
4288 x->parent->color = MEM_RED;
4289 mem_rotate_left (x->parent);
4290 w = x->parent->right;
4293 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
4295 w->color = MEM_RED;
4296 x = x->parent;
4298 else
4300 if (w->right->color == MEM_BLACK)
4302 w->left->color = MEM_BLACK;
4303 w->color = MEM_RED;
4304 mem_rotate_right (w);
4305 w = x->parent->right;
4307 w->color = x->parent->color;
4308 x->parent->color = MEM_BLACK;
4309 w->right->color = MEM_BLACK;
4310 mem_rotate_left (x->parent);
4311 x = mem_root;
4314 else
4316 struct mem_node *w = x->parent->left;
4318 if (w->color == MEM_RED)
4320 w->color = MEM_BLACK;
4321 x->parent->color = MEM_RED;
4322 mem_rotate_right (x->parent);
4323 w = x->parent->left;
4326 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
4328 w->color = MEM_RED;
4329 x = x->parent;
4331 else
4333 if (w->left->color == MEM_BLACK)
4335 w->right->color = MEM_BLACK;
4336 w->color = MEM_RED;
4337 mem_rotate_left (w);
4338 w = x->parent->left;
4341 w->color = x->parent->color;
4342 x->parent->color = MEM_BLACK;
4343 w->left->color = MEM_BLACK;
4344 mem_rotate_right (x->parent);
4345 x = mem_root;
4350 x->color = MEM_BLACK;
4354 /* Value is non-zero if P is a pointer to a live Lisp string on
4355 the heap. M is a pointer to the mem_block for P. */
4357 static bool
4358 live_string_p (struct mem_node *m, void *p)
4360 if (m->type == MEM_TYPE_STRING)
4362 struct string_block *b = m->start;
4363 ptrdiff_t offset = (char *) p - (char *) &b->strings[0];
4365 /* P must point to the start of a Lisp_String structure, and it
4366 must not be on the free-list. */
4367 return (offset >= 0
4368 && offset % sizeof b->strings[0] == 0
4369 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
4370 && ((struct Lisp_String *) p)->data != NULL);
4372 else
4373 return 0;
4377 /* Value is non-zero if P is a pointer to a live Lisp cons on
4378 the heap. M is a pointer to the mem_block for P. */
4380 static bool
4381 live_cons_p (struct mem_node *m, void *p)
4383 if (m->type == MEM_TYPE_CONS)
4385 struct cons_block *b = m->start;
4386 ptrdiff_t offset = (char *) p - (char *) &b->conses[0];
4388 /* P must point to the start of a Lisp_Cons, not be
4389 one of the unused cells in the current cons block,
4390 and not be on the free-list. */
4391 return (offset >= 0
4392 && offset % sizeof b->conses[0] == 0
4393 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
4394 && (b != cons_block
4395 || offset / sizeof b->conses[0] < cons_block_index)
4396 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
4398 else
4399 return 0;
4403 /* Value is non-zero if P is a pointer to a live Lisp symbol on
4404 the heap. M is a pointer to the mem_block for P. */
4406 static bool
4407 live_symbol_p (struct mem_node *m, void *p)
4409 if (m->type == MEM_TYPE_SYMBOL)
4411 struct symbol_block *b = m->start;
4412 ptrdiff_t offset = (char *) p - (char *) &b->symbols[0];
4414 /* P must point to the start of a Lisp_Symbol, not be
4415 one of the unused cells in the current symbol block,
4416 and not be on the free-list. */
4417 return (offset >= 0
4418 && offset % sizeof b->symbols[0] == 0
4419 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
4420 && (b != symbol_block
4421 || offset / sizeof b->symbols[0] < symbol_block_index)
4422 && !EQ (((struct Lisp_Symbol *)p)->function, Vdead));
4424 else
4425 return 0;
4429 /* Value is non-zero if P is a pointer to a live Lisp float on
4430 the heap. M is a pointer to the mem_block for P. */
4432 static bool
4433 live_float_p (struct mem_node *m, void *p)
4435 if (m->type == MEM_TYPE_FLOAT)
4437 struct float_block *b = m->start;
4438 ptrdiff_t offset = (char *) p - (char *) &b->floats[0];
4440 /* P must point to the start of a Lisp_Float and not be
4441 one of the unused cells in the current float block. */
4442 return (offset >= 0
4443 && offset % sizeof b->floats[0] == 0
4444 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
4445 && (b != float_block
4446 || offset / sizeof b->floats[0] < float_block_index));
4448 else
4449 return 0;
4453 /* Value is non-zero if P is a pointer to a live Lisp Misc on
4454 the heap. M is a pointer to the mem_block for P. */
4456 static bool
4457 live_misc_p (struct mem_node *m, void *p)
4459 if (m->type == MEM_TYPE_MISC)
4461 struct marker_block *b = m->start;
4462 ptrdiff_t offset = (char *) p - (char *) &b->markers[0];
4464 /* P must point to the start of a Lisp_Misc, not be
4465 one of the unused cells in the current misc block,
4466 and not be on the free-list. */
4467 return (offset >= 0
4468 && offset % sizeof b->markers[0] == 0
4469 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
4470 && (b != marker_block
4471 || offset / sizeof b->markers[0] < marker_block_index)
4472 && ((union Lisp_Misc *) p)->u_any.type != Lisp_Misc_Free);
4474 else
4475 return 0;
4479 /* Value is non-zero if P is a pointer to a live vector-like object.
4480 M is a pointer to the mem_block for P. */
4482 static bool
4483 live_vector_p (struct mem_node *m, void *p)
4485 if (m->type == MEM_TYPE_VECTOR_BLOCK)
4487 /* This memory node corresponds to a vector block. */
4488 struct vector_block *block = m->start;
4489 struct Lisp_Vector *vector = (struct Lisp_Vector *) block->data;
4491 /* P is in the block's allocation range. Scan the block
4492 up to P and see whether P points to the start of some
4493 vector which is not on a free list. FIXME: check whether
4494 some allocation patterns (probably a lot of short vectors)
4495 may cause a substantial overhead of this loop. */
4496 while (VECTOR_IN_BLOCK (vector, block)
4497 && vector <= (struct Lisp_Vector *) p)
4499 if (!PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FREE) && vector == p)
4500 return 1;
4501 else
4502 vector = ADVANCE (vector, vector_nbytes (vector));
4505 else if (m->type == MEM_TYPE_VECTORLIKE && p == large_vector_vec (m->start))
4506 /* This memory node corresponds to a large vector. */
4507 return 1;
4508 return 0;
4512 /* Value is non-zero if P is a pointer to a live buffer. M is a
4513 pointer to the mem_block for P. */
4515 static bool
4516 live_buffer_p (struct mem_node *m, void *p)
4518 /* P must point to the start of the block, and the buffer
4519 must not have been killed. */
4520 return (m->type == MEM_TYPE_BUFFER
4521 && p == m->start
4522 && !NILP (((struct buffer *) p)->name_));
4525 /* Mark OBJ if we can prove it's a Lisp_Object. */
4527 static void
4528 mark_maybe_object (Lisp_Object obj)
4530 #if USE_VALGRIND
4531 if (valgrind_p)
4532 VALGRIND_MAKE_MEM_DEFINED (&obj, sizeof (obj));
4533 #endif
4535 if (INTEGERP (obj))
4536 return;
4538 void *po = XPNTR (obj);
4539 struct mem_node *m = mem_find (po);
4541 if (m != MEM_NIL)
4543 bool mark_p = false;
4545 switch (XTYPE (obj))
4547 case Lisp_String:
4548 mark_p = (live_string_p (m, po)
4549 && !STRING_MARKED_P ((struct Lisp_String *) po));
4550 break;
4552 case Lisp_Cons:
4553 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4554 break;
4556 case Lisp_Symbol:
4557 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4558 break;
4560 case Lisp_Float:
4561 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4562 break;
4564 case Lisp_Vectorlike:
4565 /* Note: can't check BUFFERP before we know it's a
4566 buffer because checking that dereferences the pointer
4567 PO which might point anywhere. */
4568 if (live_vector_p (m, po))
4569 mark_p = !SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4570 else if (live_buffer_p (m, po))
4571 mark_p = BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4572 break;
4574 case Lisp_Misc:
4575 mark_p = (live_misc_p (m, po) && !XMISCANY (obj)->gcmarkbit);
4576 break;
4578 default:
4579 break;
4582 if (mark_p)
4583 mark_object (obj);
4587 /* Return true if P can point to Lisp data, and false otherwise.
4588 Symbols are implemented via offsets not pointers, but the offsets
4589 are also multiples of GCALIGNMENT. */
4591 static bool
4592 maybe_lisp_pointer (void *p)
4594 return (uintptr_t) p % GCALIGNMENT == 0;
4597 #ifndef HAVE_MODULES
4598 enum { HAVE_MODULES = false };
4599 #endif
4601 /* If P points to Lisp data, mark that as live if it isn't already
4602 marked. */
4604 static void
4605 mark_maybe_pointer (void *p)
4607 struct mem_node *m;
4609 #if USE_VALGRIND
4610 if (valgrind_p)
4611 VALGRIND_MAKE_MEM_DEFINED (&p, sizeof (p));
4612 #endif
4614 if (sizeof (Lisp_Object) == sizeof (void *) || !HAVE_MODULES)
4616 if (!maybe_lisp_pointer (p))
4617 return;
4619 else
4621 /* For the wide-int case, also mark emacs_value tagged pointers,
4622 which can be generated by emacs-module.c's value_to_lisp. */
4623 p = (void *) ((uintptr_t) p & ~(GCALIGNMENT - 1));
4626 m = mem_find (p);
4627 if (m != MEM_NIL)
4629 Lisp_Object obj = Qnil;
4631 switch (m->type)
4633 case MEM_TYPE_NON_LISP:
4634 case MEM_TYPE_SPARE:
4635 /* Nothing to do; not a pointer to Lisp memory. */
4636 break;
4638 case MEM_TYPE_BUFFER:
4639 if (live_buffer_p (m, p) && !VECTOR_MARKED_P ((struct buffer *)p))
4640 XSETVECTOR (obj, p);
4641 break;
4643 case MEM_TYPE_CONS:
4644 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4645 XSETCONS (obj, p);
4646 break;
4648 case MEM_TYPE_STRING:
4649 if (live_string_p (m, p)
4650 && !STRING_MARKED_P ((struct Lisp_String *) p))
4651 XSETSTRING (obj, p);
4652 break;
4654 case MEM_TYPE_MISC:
4655 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4656 XSETMISC (obj, p);
4657 break;
4659 case MEM_TYPE_SYMBOL:
4660 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4661 XSETSYMBOL (obj, p);
4662 break;
4664 case MEM_TYPE_FLOAT:
4665 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4666 XSETFLOAT (obj, p);
4667 break;
4669 case MEM_TYPE_VECTORLIKE:
4670 case MEM_TYPE_VECTOR_BLOCK:
4671 if (live_vector_p (m, p))
4673 Lisp_Object tem;
4674 XSETVECTOR (tem, p);
4675 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4676 obj = tem;
4678 break;
4680 default:
4681 emacs_abort ();
4684 if (!NILP (obj))
4685 mark_object (obj);
4690 /* Alignment of pointer values. Use alignof, as it sometimes returns
4691 a smaller alignment than GCC's __alignof__ and mark_memory might
4692 miss objects if __alignof__ were used. */
4693 #define GC_POINTER_ALIGNMENT alignof (void *)
4695 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4696 or END+OFFSET..START. */
4698 static void ATTRIBUTE_NO_SANITIZE_ADDRESS
4699 mark_memory (void *start, void *end)
4701 char *pp;
4703 /* Make START the pointer to the start of the memory region,
4704 if it isn't already. */
4705 if (end < start)
4707 void *tem = start;
4708 start = end;
4709 end = tem;
4712 eassert (((uintptr_t) start) % GC_POINTER_ALIGNMENT == 0);
4714 /* Mark Lisp data pointed to. This is necessary because, in some
4715 situations, the C compiler optimizes Lisp objects away, so that
4716 only a pointer to them remains. Example:
4718 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4721 Lisp_Object obj = build_string ("test");
4722 struct Lisp_String *s = XSTRING (obj);
4723 Fgarbage_collect ();
4724 fprintf (stderr, "test '%s'\n", s->data);
4725 return Qnil;
4728 Here, `obj' isn't really used, and the compiler optimizes it
4729 away. The only reference to the life string is through the
4730 pointer `s'. */
4732 for (pp = start; (void *) pp < end; pp += GC_POINTER_ALIGNMENT)
4734 mark_maybe_pointer (*(void **) pp);
4735 mark_maybe_object (*(Lisp_Object *) pp);
4739 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4741 static bool setjmp_tested_p;
4742 static int longjmps_done;
4744 #define SETJMP_WILL_LIKELY_WORK "\
4746 Emacs garbage collector has been changed to use conservative stack\n\
4747 marking. Emacs has determined that the method it uses to do the\n\
4748 marking will likely work on your system, but this isn't sure.\n\
4750 If you are a system-programmer, or can get the help of a local wizard\n\
4751 who is, please take a look at the function mark_stack in alloc.c, and\n\
4752 verify that the methods used are appropriate for your system.\n\
4754 Please mail the result to <emacs-devel@gnu.org>.\n\
4757 #define SETJMP_WILL_NOT_WORK "\
4759 Emacs garbage collector has been changed to use conservative stack\n\
4760 marking. Emacs has determined that the default method it uses to do the\n\
4761 marking will not work on your system. We will need a system-dependent\n\
4762 solution for your system.\n\
4764 Please take a look at the function mark_stack in alloc.c, and\n\
4765 try to find a way to make it work on your system.\n\
4767 Note that you may get false negatives, depending on the compiler.\n\
4768 In particular, you need to use -O with GCC for this test.\n\
4770 Please mail the result to <emacs-devel@gnu.org>.\n\
4774 /* Perform a quick check if it looks like setjmp saves registers in a
4775 jmp_buf. Print a message to stderr saying so. When this test
4776 succeeds, this is _not_ a proof that setjmp is sufficient for
4777 conservative stack marking. Only the sources or a disassembly
4778 can prove that. */
4780 static void
4781 test_setjmp (void)
4783 char buf[10];
4784 register int x;
4785 sys_jmp_buf jbuf;
4787 /* Arrange for X to be put in a register. */
4788 sprintf (buf, "1");
4789 x = strlen (buf);
4790 x = 2 * x - 1;
4792 sys_setjmp (jbuf);
4793 if (longjmps_done == 1)
4795 /* Came here after the longjmp at the end of the function.
4797 If x == 1, the longjmp has restored the register to its
4798 value before the setjmp, and we can hope that setjmp
4799 saves all such registers in the jmp_buf, although that
4800 isn't sure.
4802 For other values of X, either something really strange is
4803 taking place, or the setjmp just didn't save the register. */
4805 if (x == 1)
4806 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4807 else
4809 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4810 exit (1);
4814 ++longjmps_done;
4815 x = 2;
4816 if (longjmps_done == 1)
4817 sys_longjmp (jbuf, 1);
4820 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4823 /* Mark live Lisp objects on the C stack.
4825 There are several system-dependent problems to consider when
4826 porting this to new architectures:
4828 Processor Registers
4830 We have to mark Lisp objects in CPU registers that can hold local
4831 variables or are used to pass parameters.
4833 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4834 something that either saves relevant registers on the stack, or
4835 calls mark_maybe_object passing it each register's contents.
4837 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4838 implementation assumes that calling setjmp saves registers we need
4839 to see in a jmp_buf which itself lies on the stack. This doesn't
4840 have to be true! It must be verified for each system, possibly
4841 by taking a look at the source code of setjmp.
4843 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4844 can use it as a machine independent method to store all registers
4845 to the stack. In this case the macros described in the previous
4846 two paragraphs are not used.
4848 Stack Layout
4850 Architectures differ in the way their processor stack is organized.
4851 For example, the stack might look like this
4853 +----------------+
4854 | Lisp_Object | size = 4
4855 +----------------+
4856 | something else | size = 2
4857 +----------------+
4858 | Lisp_Object | size = 4
4859 +----------------+
4860 | ... |
4862 In such a case, not every Lisp_Object will be aligned equally. To
4863 find all Lisp_Object on the stack it won't be sufficient to walk
4864 the stack in steps of 4 bytes. Instead, two passes will be
4865 necessary, one starting at the start of the stack, and a second
4866 pass starting at the start of the stack + 2. Likewise, if the
4867 minimal alignment of Lisp_Objects on the stack is 1, four passes
4868 would be necessary, each one starting with one byte more offset
4869 from the stack start. */
4871 static void
4872 mark_stack (void *end)
4875 /* This assumes that the stack is a contiguous region in memory. If
4876 that's not the case, something has to be done here to iterate
4877 over the stack segments. */
4878 mark_memory (stack_base, end);
4880 /* Allow for marking a secondary stack, like the register stack on the
4881 ia64. */
4882 #ifdef GC_MARK_SECONDARY_STACK
4883 GC_MARK_SECONDARY_STACK ();
4884 #endif
4887 static bool
4888 c_symbol_p (struct Lisp_Symbol *sym)
4890 char *lispsym_ptr = (char *) lispsym;
4891 char *sym_ptr = (char *) sym;
4892 ptrdiff_t lispsym_offset = sym_ptr - lispsym_ptr;
4893 return 0 <= lispsym_offset && lispsym_offset < sizeof lispsym;
4896 /* Determine whether it is safe to access memory at address P. */
4897 static int
4898 valid_pointer_p (void *p)
4900 #ifdef WINDOWSNT
4901 return w32_valid_pointer_p (p, 16);
4902 #else
4904 if (ADDRESS_SANITIZER)
4905 return p ? -1 : 0;
4907 int fd[2];
4909 /* Obviously, we cannot just access it (we would SEGV trying), so we
4910 trick the o/s to tell us whether p is a valid pointer.
4911 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4912 not validate p in that case. */
4914 if (emacs_pipe (fd) == 0)
4916 bool valid = emacs_write (fd[1], p, 16) == 16;
4917 emacs_close (fd[1]);
4918 emacs_close (fd[0]);
4919 return valid;
4922 return -1;
4923 #endif
4926 /* Return 2 if OBJ is a killed or special buffer object, 1 if OBJ is a
4927 valid lisp object, 0 if OBJ is NOT a valid lisp object, or -1 if we
4928 cannot validate OBJ. This function can be quite slow, so its primary
4929 use is the manual debugging. The only exception is print_object, where
4930 we use it to check whether the memory referenced by the pointer of
4931 Lisp_Save_Value object contains valid objects. */
4934 valid_lisp_object_p (Lisp_Object obj)
4936 if (INTEGERP (obj))
4937 return 1;
4939 void *p = XPNTR (obj);
4940 if (PURE_P (p))
4941 return 1;
4943 if (SYMBOLP (obj) && c_symbol_p (p))
4944 return ((char *) p - (char *) lispsym) % sizeof lispsym[0] == 0;
4946 if (p == &buffer_defaults || p == &buffer_local_symbols)
4947 return 2;
4949 struct mem_node *m = mem_find (p);
4951 if (m == MEM_NIL)
4953 int valid = valid_pointer_p (p);
4954 if (valid <= 0)
4955 return valid;
4957 if (SUBRP (obj))
4958 return 1;
4960 return 0;
4963 switch (m->type)
4965 case MEM_TYPE_NON_LISP:
4966 case MEM_TYPE_SPARE:
4967 return 0;
4969 case MEM_TYPE_BUFFER:
4970 return live_buffer_p (m, p) ? 1 : 2;
4972 case MEM_TYPE_CONS:
4973 return live_cons_p (m, p);
4975 case MEM_TYPE_STRING:
4976 return live_string_p (m, p);
4978 case MEM_TYPE_MISC:
4979 return live_misc_p (m, p);
4981 case MEM_TYPE_SYMBOL:
4982 return live_symbol_p (m, p);
4984 case MEM_TYPE_FLOAT:
4985 return live_float_p (m, p);
4987 case MEM_TYPE_VECTORLIKE:
4988 case MEM_TYPE_VECTOR_BLOCK:
4989 return live_vector_p (m, p);
4991 default:
4992 break;
4995 return 0;
4998 /***********************************************************************
4999 Pure Storage Management
5000 ***********************************************************************/
5002 /* Allocate room for SIZE bytes from pure Lisp storage and return a
5003 pointer to it. TYPE is the Lisp type for which the memory is
5004 allocated. TYPE < 0 means it's not used for a Lisp object. */
5006 static void *
5007 pure_alloc (size_t size, int type)
5009 void *result;
5011 again:
5012 if (type >= 0)
5014 /* Allocate space for a Lisp object from the beginning of the free
5015 space with taking account of alignment. */
5016 result = ALIGN (purebeg + pure_bytes_used_lisp, GCALIGNMENT);
5017 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
5019 else
5021 /* Allocate space for a non-Lisp object from the end of the free
5022 space. */
5023 pure_bytes_used_non_lisp += size;
5024 result = purebeg + pure_size - pure_bytes_used_non_lisp;
5026 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
5028 if (pure_bytes_used <= pure_size)
5029 return result;
5031 /* Don't allocate a large amount here,
5032 because it might get mmap'd and then its address
5033 might not be usable. */
5034 purebeg = xmalloc (10000);
5035 pure_size = 10000;
5036 pure_bytes_used_before_overflow += pure_bytes_used - size;
5037 pure_bytes_used = 0;
5038 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
5039 goto again;
5043 /* Print a warning if PURESIZE is too small. */
5045 void
5046 check_pure_size (void)
5048 if (pure_bytes_used_before_overflow)
5049 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI"d"
5050 " bytes needed)"),
5051 pure_bytes_used + pure_bytes_used_before_overflow);
5055 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
5056 the non-Lisp data pool of the pure storage, and return its start
5057 address. Return NULL if not found. */
5059 static char *
5060 find_string_data_in_pure (const char *data, ptrdiff_t nbytes)
5062 int i;
5063 ptrdiff_t skip, bm_skip[256], last_char_skip, infinity, start, start_max;
5064 const unsigned char *p;
5065 char *non_lisp_beg;
5067 if (pure_bytes_used_non_lisp <= nbytes)
5068 return NULL;
5070 /* Set up the Boyer-Moore table. */
5071 skip = nbytes + 1;
5072 for (i = 0; i < 256; i++)
5073 bm_skip[i] = skip;
5075 p = (const unsigned char *) data;
5076 while (--skip > 0)
5077 bm_skip[*p++] = skip;
5079 last_char_skip = bm_skip['\0'];
5081 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
5082 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
5084 /* See the comments in the function `boyer_moore' (search.c) for the
5085 use of `infinity'. */
5086 infinity = pure_bytes_used_non_lisp + 1;
5087 bm_skip['\0'] = infinity;
5089 p = (const unsigned char *) non_lisp_beg + nbytes;
5090 start = 0;
5093 /* Check the last character (== '\0'). */
5096 start += bm_skip[*(p + start)];
5098 while (start <= start_max);
5100 if (start < infinity)
5101 /* Couldn't find the last character. */
5102 return NULL;
5104 /* No less than `infinity' means we could find the last
5105 character at `p[start - infinity]'. */
5106 start -= infinity;
5108 /* Check the remaining characters. */
5109 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
5110 /* Found. */
5111 return non_lisp_beg + start;
5113 start += last_char_skip;
5115 while (start <= start_max);
5117 return NULL;
5121 /* Return a string allocated in pure space. DATA is a buffer holding
5122 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
5123 means make the result string multibyte.
5125 Must get an error if pure storage is full, since if it cannot hold
5126 a large string it may be able to hold conses that point to that
5127 string; then the string is not protected from gc. */
5129 Lisp_Object
5130 make_pure_string (const char *data,
5131 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
5133 Lisp_Object string;
5134 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5135 s->data = (unsigned char *) find_string_data_in_pure (data, nbytes);
5136 if (s->data == NULL)
5138 s->data = pure_alloc (nbytes + 1, -1);
5139 memcpy (s->data, data, nbytes);
5140 s->data[nbytes] = '\0';
5142 s->size = nchars;
5143 s->size_byte = multibyte ? nbytes : -1;
5144 s->intervals = NULL;
5145 XSETSTRING (string, s);
5146 return string;
5149 /* Return a string allocated in pure space. Do not
5150 allocate the string data, just point to DATA. */
5152 Lisp_Object
5153 make_pure_c_string (const char *data, ptrdiff_t nchars)
5155 Lisp_Object string;
5156 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5157 s->size = nchars;
5158 s->size_byte = -1;
5159 s->data = (unsigned char *) data;
5160 s->intervals = NULL;
5161 XSETSTRING (string, s);
5162 return string;
5165 static Lisp_Object purecopy (Lisp_Object obj);
5167 /* Return a cons allocated from pure space. Give it pure copies
5168 of CAR as car and CDR as cdr. */
5170 Lisp_Object
5171 pure_cons (Lisp_Object car, Lisp_Object cdr)
5173 Lisp_Object new;
5174 struct Lisp_Cons *p = pure_alloc (sizeof *p, Lisp_Cons);
5175 XSETCONS (new, p);
5176 XSETCAR (new, purecopy (car));
5177 XSETCDR (new, purecopy (cdr));
5178 return new;
5182 /* Value is a float object with value NUM allocated from pure space. */
5184 static Lisp_Object
5185 make_pure_float (double num)
5187 Lisp_Object new;
5188 struct Lisp_Float *p = pure_alloc (sizeof *p, Lisp_Float);
5189 XSETFLOAT (new, p);
5190 XFLOAT_INIT (new, num);
5191 return new;
5195 /* Return a vector with room for LEN Lisp_Objects allocated from
5196 pure space. */
5198 static Lisp_Object
5199 make_pure_vector (ptrdiff_t len)
5201 Lisp_Object new;
5202 size_t size = header_size + len * word_size;
5203 struct Lisp_Vector *p = pure_alloc (size, Lisp_Vectorlike);
5204 XSETVECTOR (new, p);
5205 XVECTOR (new)->header.size = len;
5206 return new;
5209 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
5210 doc: /* Make a copy of object OBJ in pure storage.
5211 Recursively copies contents of vectors and cons cells.
5212 Does not copy symbols. Copies strings without text properties. */)
5213 (register Lisp_Object obj)
5215 if (NILP (Vpurify_flag))
5216 return obj;
5217 else if (MARKERP (obj) || OVERLAYP (obj)
5218 || HASH_TABLE_P (obj) || SYMBOLP (obj))
5219 /* Can't purify those. */
5220 return obj;
5221 else
5222 return purecopy (obj);
5225 static Lisp_Object
5226 purecopy (Lisp_Object obj)
5228 if (INTEGERP (obj)
5229 || (! SYMBOLP (obj) && PURE_P (XPNTR_OR_SYMBOL_OFFSET (obj)))
5230 || SUBRP (obj))
5231 return obj; /* Already pure. */
5233 if (STRINGP (obj) && XSTRING (obj)->intervals)
5234 message_with_string ("Dropping text-properties while making string `%s' pure",
5235 obj, true);
5237 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5239 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
5240 if (!NILP (tmp))
5241 return tmp;
5244 if (CONSP (obj))
5245 obj = pure_cons (XCAR (obj), XCDR (obj));
5246 else if (FLOATP (obj))
5247 obj = make_pure_float (XFLOAT_DATA (obj));
5248 else if (STRINGP (obj))
5249 obj = make_pure_string (SSDATA (obj), SCHARS (obj),
5250 SBYTES (obj),
5251 STRING_MULTIBYTE (obj));
5252 else if (COMPILEDP (obj) || VECTORP (obj) || HASH_TABLE_P (obj))
5254 struct Lisp_Vector *objp = XVECTOR (obj);
5255 ptrdiff_t nbytes = vector_nbytes (objp);
5256 struct Lisp_Vector *vec = pure_alloc (nbytes, Lisp_Vectorlike);
5257 register ptrdiff_t i;
5258 ptrdiff_t size = ASIZE (obj);
5259 if (size & PSEUDOVECTOR_FLAG)
5260 size &= PSEUDOVECTOR_SIZE_MASK;
5261 memcpy (vec, objp, nbytes);
5262 for (i = 0; i < size; i++)
5263 vec->contents[i] = purecopy (vec->contents[i]);
5264 XSETVECTOR (obj, vec);
5266 else if (SYMBOLP (obj))
5268 if (!XSYMBOL (obj)->pinned && !c_symbol_p (XSYMBOL (obj)))
5269 { /* We can't purify them, but they appear in many pure objects.
5270 Mark them as `pinned' so we know to mark them at every GC cycle. */
5271 XSYMBOL (obj)->pinned = true;
5272 symbol_block_pinned = symbol_block;
5274 /* Don't hash-cons it. */
5275 return obj;
5277 else
5279 Lisp_Object fmt = build_pure_c_string ("Don't know how to purify: %S");
5280 Fsignal (Qerror, list1 (CALLN (Fformat, fmt, obj)));
5283 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5284 Fputhash (obj, obj, Vpurify_flag);
5286 return obj;
5291 /***********************************************************************
5292 Protection from GC
5293 ***********************************************************************/
5295 /* Put an entry in staticvec, pointing at the variable with address
5296 VARADDRESS. */
5298 void
5299 staticpro (Lisp_Object *varaddress)
5301 if (staticidx >= NSTATICS)
5302 fatal ("NSTATICS too small; try increasing and recompiling Emacs.");
5303 staticvec[staticidx++] = varaddress;
5307 /***********************************************************************
5308 Protection from GC
5309 ***********************************************************************/
5311 /* Temporarily prevent garbage collection. */
5313 ptrdiff_t
5314 inhibit_garbage_collection (void)
5316 ptrdiff_t count = SPECPDL_INDEX ();
5318 specbind (Qgc_cons_threshold, make_number (MOST_POSITIVE_FIXNUM));
5319 return count;
5322 /* Used to avoid possible overflows when
5323 converting from C to Lisp integers. */
5325 static Lisp_Object
5326 bounded_number (EMACS_INT number)
5328 return make_number (min (MOST_POSITIVE_FIXNUM, number));
5331 /* Calculate total bytes of live objects. */
5333 static size_t
5334 total_bytes_of_live_objects (void)
5336 size_t tot = 0;
5337 tot += total_conses * sizeof (struct Lisp_Cons);
5338 tot += total_symbols * sizeof (struct Lisp_Symbol);
5339 tot += total_markers * sizeof (union Lisp_Misc);
5340 tot += total_string_bytes;
5341 tot += total_vector_slots * word_size;
5342 tot += total_floats * sizeof (struct Lisp_Float);
5343 tot += total_intervals * sizeof (struct interval);
5344 tot += total_strings * sizeof (struct Lisp_String);
5345 return tot;
5348 #ifdef HAVE_WINDOW_SYSTEM
5350 /* Remove unmarked font-spec and font-entity objects from ENTRY, which is
5351 (DRIVER-TYPE NUM-FRAMES FONT-CACHE-DATA ...), and return changed entry. */
5353 static Lisp_Object
5354 compact_font_cache_entry (Lisp_Object entry)
5356 Lisp_Object tail, *prev = &entry;
5358 for (tail = entry; CONSP (tail); tail = XCDR (tail))
5360 bool drop = 0;
5361 Lisp_Object obj = XCAR (tail);
5363 /* Consider OBJ if it is (font-spec . [font-entity font-entity ...]). */
5364 if (CONSP (obj) && GC_FONT_SPEC_P (XCAR (obj))
5365 && !VECTOR_MARKED_P (GC_XFONT_SPEC (XCAR (obj)))
5366 /* Don't use VECTORP here, as that calls ASIZE, which could
5367 hit assertion violation during GC. */
5368 && (VECTORLIKEP (XCDR (obj))
5369 && ! (gc_asize (XCDR (obj)) & PSEUDOVECTOR_FLAG)))
5371 ptrdiff_t i, size = gc_asize (XCDR (obj));
5372 Lisp_Object obj_cdr = XCDR (obj);
5374 /* If font-spec is not marked, most likely all font-entities
5375 are not marked too. But we must be sure that nothing is
5376 marked within OBJ before we really drop it. */
5377 for (i = 0; i < size; i++)
5379 Lisp_Object objlist;
5381 if (VECTOR_MARKED_P (GC_XFONT_ENTITY (AREF (obj_cdr, i))))
5382 break;
5384 objlist = AREF (AREF (obj_cdr, i), FONT_OBJLIST_INDEX);
5385 for (; CONSP (objlist); objlist = XCDR (objlist))
5387 Lisp_Object val = XCAR (objlist);
5388 struct font *font = GC_XFONT_OBJECT (val);
5390 if (!NILP (AREF (val, FONT_TYPE_INDEX))
5391 && VECTOR_MARKED_P(font))
5392 break;
5394 if (CONSP (objlist))
5396 /* Found a marked font, bail out. */
5397 break;
5401 if (i == size)
5403 /* No marked fonts were found, so this entire font
5404 entity can be dropped. */
5405 drop = 1;
5408 if (drop)
5409 *prev = XCDR (tail);
5410 else
5411 prev = xcdr_addr (tail);
5413 return entry;
5416 /* Compact font caches on all terminals and mark
5417 everything which is still here after compaction. */
5419 static void
5420 compact_font_caches (void)
5422 struct terminal *t;
5424 for (t = terminal_list; t; t = t->next_terminal)
5426 Lisp_Object cache = TERMINAL_FONT_CACHE (t);
5427 if (CONSP (cache))
5429 Lisp_Object entry;
5431 for (entry = XCDR (cache); CONSP (entry); entry = XCDR (entry))
5432 XSETCAR (entry, compact_font_cache_entry (XCAR (entry)));
5434 mark_object (cache);
5438 #else /* not HAVE_WINDOW_SYSTEM */
5440 #define compact_font_caches() (void)(0)
5442 #endif /* HAVE_WINDOW_SYSTEM */
5444 /* Remove (MARKER . DATA) entries with unmarked MARKER
5445 from buffer undo LIST and return changed list. */
5447 static Lisp_Object
5448 compact_undo_list (Lisp_Object list)
5450 Lisp_Object tail, *prev = &list;
5452 for (tail = list; CONSP (tail); tail = XCDR (tail))
5454 if (CONSP (XCAR (tail))
5455 && MARKERP (XCAR (XCAR (tail)))
5456 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5457 *prev = XCDR (tail);
5458 else
5459 prev = xcdr_addr (tail);
5461 return list;
5464 static void
5465 mark_pinned_symbols (void)
5467 struct symbol_block *sblk;
5468 int lim = (symbol_block_pinned == symbol_block
5469 ? symbol_block_index : SYMBOL_BLOCK_SIZE);
5471 for (sblk = symbol_block_pinned; sblk; sblk = sblk->next)
5473 union aligned_Lisp_Symbol *sym = sblk->symbols, *end = sym + lim;
5474 for (; sym < end; ++sym)
5475 if (sym->s.pinned)
5476 mark_object (make_lisp_symbol (&sym->s));
5478 lim = SYMBOL_BLOCK_SIZE;
5482 /* Subroutine of Fgarbage_collect that does most of the work. It is a
5483 separate function so that we could limit mark_stack in searching
5484 the stack frames below this function, thus avoiding the rare cases
5485 where mark_stack finds values that look like live Lisp objects on
5486 portions of stack that couldn't possibly contain such live objects.
5487 For more details of this, see the discussion at
5488 http://lists.gnu.org/archive/html/emacs-devel/2014-05/msg00270.html. */
5489 static Lisp_Object
5490 garbage_collect_1 (void *end)
5492 struct buffer *nextb;
5493 char stack_top_variable;
5494 ptrdiff_t i;
5495 bool message_p;
5496 ptrdiff_t count = SPECPDL_INDEX ();
5497 struct timespec start;
5498 Lisp_Object retval = Qnil;
5499 size_t tot_before = 0;
5501 if (abort_on_gc)
5502 emacs_abort ();
5504 /* Can't GC if pure storage overflowed because we can't determine
5505 if something is a pure object or not. */
5506 if (pure_bytes_used_before_overflow)
5507 return Qnil;
5509 /* Record this function, so it appears on the profiler's backtraces. */
5510 record_in_backtrace (Qautomatic_gc, 0, 0);
5512 check_cons_list ();
5514 /* Don't keep undo information around forever.
5515 Do this early on, so it is no problem if the user quits. */
5516 FOR_EACH_BUFFER (nextb)
5517 compact_buffer (nextb);
5519 if (profiler_memory_running)
5520 tot_before = total_bytes_of_live_objects ();
5522 start = current_timespec ();
5524 /* In case user calls debug_print during GC,
5525 don't let that cause a recursive GC. */
5526 consing_since_gc = 0;
5528 /* Save what's currently displayed in the echo area. Don't do that
5529 if we are GC'ing because we've run out of memory, since
5530 push_message will cons, and we might have no memory for that. */
5531 if (NILP (Vmemory_full))
5533 message_p = push_message ();
5534 record_unwind_protect_void (pop_message_unwind);
5536 else
5537 message_p = false;
5539 /* Save a copy of the contents of the stack, for debugging. */
5540 #if MAX_SAVE_STACK > 0
5541 if (NILP (Vpurify_flag))
5543 char *stack;
5544 ptrdiff_t stack_size;
5545 if (&stack_top_variable < stack_bottom)
5547 stack = &stack_top_variable;
5548 stack_size = stack_bottom - &stack_top_variable;
5550 else
5552 stack = stack_bottom;
5553 stack_size = &stack_top_variable - stack_bottom;
5555 if (stack_size <= MAX_SAVE_STACK)
5557 if (stack_copy_size < stack_size)
5559 stack_copy = xrealloc (stack_copy, stack_size);
5560 stack_copy_size = stack_size;
5562 no_sanitize_memcpy (stack_copy, stack, stack_size);
5565 #endif /* MAX_SAVE_STACK > 0 */
5567 if (garbage_collection_messages)
5568 message1_nolog ("Garbage collecting...");
5570 block_input ();
5572 shrink_regexp_cache ();
5574 gc_in_progress = 1;
5576 /* Mark all the special slots that serve as the roots of accessibility. */
5578 mark_buffer (&buffer_defaults);
5579 mark_buffer (&buffer_local_symbols);
5581 for (i = 0; i < ARRAYELTS (lispsym); i++)
5582 mark_object (builtin_lisp_symbol (i));
5584 for (i = 0; i < staticidx; i++)
5585 mark_object (*staticvec[i]);
5587 mark_pinned_symbols ();
5588 mark_specpdl ();
5589 mark_terminals ();
5590 mark_kboards ();
5592 #ifdef USE_GTK
5593 xg_mark_data ();
5594 #endif
5596 mark_stack (end);
5599 struct handler *handler;
5600 for (handler = handlerlist; handler; handler = handler->next)
5602 mark_object (handler->tag_or_ch);
5603 mark_object (handler->val);
5606 #ifdef HAVE_WINDOW_SYSTEM
5607 mark_fringe_data ();
5608 #endif
5610 /* Everything is now marked, except for the data in font caches,
5611 undo lists, and finalizers. The first two are compacted by
5612 removing an items which aren't reachable otherwise. */
5614 compact_font_caches ();
5616 FOR_EACH_BUFFER (nextb)
5618 if (!EQ (BVAR (nextb, undo_list), Qt))
5619 bset_undo_list (nextb, compact_undo_list (BVAR (nextb, undo_list)));
5620 /* Now that we have stripped the elements that need not be
5621 in the undo_list any more, we can finally mark the list. */
5622 mark_object (BVAR (nextb, undo_list));
5625 /* Now pre-sweep finalizers. Here, we add any unmarked finalizers
5626 to doomed_finalizers so we can run their associated functions
5627 after GC. It's important to scan finalizers at this stage so
5628 that we can be sure that unmarked finalizers are really
5629 unreachable except for references from their associated functions
5630 and from other finalizers. */
5632 queue_doomed_finalizers (&doomed_finalizers, &finalizers);
5633 mark_finalizer_list (&doomed_finalizers);
5635 gc_sweep ();
5637 relocate_byte_stack ();
5639 /* Clear the mark bits that we set in certain root slots. */
5640 VECTOR_UNMARK (&buffer_defaults);
5641 VECTOR_UNMARK (&buffer_local_symbols);
5643 check_cons_list ();
5645 gc_in_progress = 0;
5647 unblock_input ();
5649 consing_since_gc = 0;
5650 if (gc_cons_threshold < GC_DEFAULT_THRESHOLD / 10)
5651 gc_cons_threshold = GC_DEFAULT_THRESHOLD / 10;
5653 gc_relative_threshold = 0;
5654 if (FLOATP (Vgc_cons_percentage))
5655 { /* Set gc_cons_combined_threshold. */
5656 double tot = total_bytes_of_live_objects ();
5658 tot *= XFLOAT_DATA (Vgc_cons_percentage);
5659 if (0 < tot)
5661 if (tot < TYPE_MAXIMUM (EMACS_INT))
5662 gc_relative_threshold = tot;
5663 else
5664 gc_relative_threshold = TYPE_MAXIMUM (EMACS_INT);
5668 if (garbage_collection_messages && NILP (Vmemory_full))
5670 if (message_p || minibuf_level > 0)
5671 restore_message ();
5672 else
5673 message1_nolog ("Garbage collecting...done");
5676 unbind_to (count, Qnil);
5678 Lisp_Object total[] = {
5679 list4 (Qconses, make_number (sizeof (struct Lisp_Cons)),
5680 bounded_number (total_conses),
5681 bounded_number (total_free_conses)),
5682 list4 (Qsymbols, make_number (sizeof (struct Lisp_Symbol)),
5683 bounded_number (total_symbols),
5684 bounded_number (total_free_symbols)),
5685 list4 (Qmiscs, make_number (sizeof (union Lisp_Misc)),
5686 bounded_number (total_markers),
5687 bounded_number (total_free_markers)),
5688 list4 (Qstrings, make_number (sizeof (struct Lisp_String)),
5689 bounded_number (total_strings),
5690 bounded_number (total_free_strings)),
5691 list3 (Qstring_bytes, make_number (1),
5692 bounded_number (total_string_bytes)),
5693 list3 (Qvectors,
5694 make_number (header_size + sizeof (Lisp_Object)),
5695 bounded_number (total_vectors)),
5696 list4 (Qvector_slots, make_number (word_size),
5697 bounded_number (total_vector_slots),
5698 bounded_number (total_free_vector_slots)),
5699 list4 (Qfloats, make_number (sizeof (struct Lisp_Float)),
5700 bounded_number (total_floats),
5701 bounded_number (total_free_floats)),
5702 list4 (Qintervals, make_number (sizeof (struct interval)),
5703 bounded_number (total_intervals),
5704 bounded_number (total_free_intervals)),
5705 list3 (Qbuffers, make_number (sizeof (struct buffer)),
5706 bounded_number (total_buffers)),
5708 #ifdef DOUG_LEA_MALLOC
5709 list4 (Qheap, make_number (1024),
5710 bounded_number ((mallinfo ().uordblks + 1023) >> 10),
5711 bounded_number ((mallinfo ().fordblks + 1023) >> 10)),
5712 #endif
5714 retval = CALLMANY (Flist, total);
5716 /* GC is complete: now we can run our finalizer callbacks. */
5717 run_finalizers (&doomed_finalizers);
5719 if (!NILP (Vpost_gc_hook))
5721 ptrdiff_t gc_count = inhibit_garbage_collection ();
5722 safe_run_hooks (Qpost_gc_hook);
5723 unbind_to (gc_count, Qnil);
5726 /* Accumulate statistics. */
5727 if (FLOATP (Vgc_elapsed))
5729 struct timespec since_start = timespec_sub (current_timespec (), start);
5730 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed)
5731 + timespectod (since_start));
5734 gcs_done++;
5736 /* Collect profiling data. */
5737 if (profiler_memory_running)
5739 size_t swept = 0;
5740 size_t tot_after = total_bytes_of_live_objects ();
5741 if (tot_before > tot_after)
5742 swept = tot_before - tot_after;
5743 malloc_probe (swept);
5746 return retval;
5749 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
5750 doc: /* Reclaim storage for Lisp objects no longer needed.
5751 Garbage collection happens automatically if you cons more than
5752 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5753 `garbage-collect' normally returns a list with info on amount of space in use,
5754 where each entry has the form (NAME SIZE USED FREE), where:
5755 - NAME is a symbol describing the kind of objects this entry represents,
5756 - SIZE is the number of bytes used by each one,
5757 - USED is the number of those objects that were found live in the heap,
5758 - FREE is the number of those objects that are not live but that Emacs
5759 keeps around for future allocations (maybe because it does not know how
5760 to return them to the OS).
5761 However, if there was overflow in pure space, `garbage-collect'
5762 returns nil, because real GC can't be done.
5763 See Info node `(elisp)Garbage Collection'. */)
5764 (void)
5766 void *end;
5768 #ifdef HAVE___BUILTIN_UNWIND_INIT
5769 /* Force callee-saved registers and register windows onto the stack.
5770 This is the preferred method if available, obviating the need for
5771 machine dependent methods. */
5772 __builtin_unwind_init ();
5773 end = &end;
5774 #else /* not HAVE___BUILTIN_UNWIND_INIT */
5775 #ifndef GC_SAVE_REGISTERS_ON_STACK
5776 /* jmp_buf may not be aligned enough on darwin-ppc64 */
5777 union aligned_jmpbuf {
5778 Lisp_Object o;
5779 sys_jmp_buf j;
5780 } j;
5781 volatile bool stack_grows_down_p = (char *) &j > (char *) stack_base;
5782 #endif
5783 /* This trick flushes the register windows so that all the state of
5784 the process is contained in the stack. */
5785 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
5786 needed on ia64 too. See mach_dep.c, where it also says inline
5787 assembler doesn't work with relevant proprietary compilers. */
5788 #ifdef __sparc__
5789 #if defined (__sparc64__) && defined (__FreeBSD__)
5790 /* FreeBSD does not have a ta 3 handler. */
5791 asm ("flushw");
5792 #else
5793 asm ("ta 3");
5794 #endif
5795 #endif
5797 /* Save registers that we need to see on the stack. We need to see
5798 registers used to hold register variables and registers used to
5799 pass parameters. */
5800 #ifdef GC_SAVE_REGISTERS_ON_STACK
5801 GC_SAVE_REGISTERS_ON_STACK (end);
5802 #else /* not GC_SAVE_REGISTERS_ON_STACK */
5804 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
5805 setjmp will definitely work, test it
5806 and print a message with the result
5807 of the test. */
5808 if (!setjmp_tested_p)
5810 setjmp_tested_p = 1;
5811 test_setjmp ();
5813 #endif /* GC_SETJMP_WORKS */
5815 sys_setjmp (j.j);
5816 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
5817 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
5818 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
5819 return garbage_collect_1 (end);
5822 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5823 only interesting objects referenced from glyphs are strings. */
5825 static void
5826 mark_glyph_matrix (struct glyph_matrix *matrix)
5828 struct glyph_row *row = matrix->rows;
5829 struct glyph_row *end = row + matrix->nrows;
5831 for (; row < end; ++row)
5832 if (row->enabled_p)
5834 int area;
5835 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
5837 struct glyph *glyph = row->glyphs[area];
5838 struct glyph *end_glyph = glyph + row->used[area];
5840 for (; glyph < end_glyph; ++glyph)
5841 if (STRINGP (glyph->object)
5842 && !STRING_MARKED_P (XSTRING (glyph->object)))
5843 mark_object (glyph->object);
5848 /* Mark reference to a Lisp_Object.
5849 If the object referred to has not been seen yet, recursively mark
5850 all the references contained in it. */
5852 #define LAST_MARKED_SIZE 500
5853 static Lisp_Object last_marked[LAST_MARKED_SIZE];
5854 static int last_marked_index;
5856 /* For debugging--call abort when we cdr down this many
5857 links of a list, in mark_object. In debugging,
5858 the call to abort will hit a breakpoint.
5859 Normally this is zero and the check never goes off. */
5860 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE;
5862 static void
5863 mark_vectorlike (struct Lisp_Vector *ptr)
5865 ptrdiff_t size = ptr->header.size;
5866 ptrdiff_t i;
5868 eassert (!VECTOR_MARKED_P (ptr));
5869 VECTOR_MARK (ptr); /* Else mark it. */
5870 if (size & PSEUDOVECTOR_FLAG)
5871 size &= PSEUDOVECTOR_SIZE_MASK;
5873 /* Note that this size is not the memory-footprint size, but only
5874 the number of Lisp_Object fields that we should trace.
5875 The distinction is used e.g. by Lisp_Process which places extra
5876 non-Lisp_Object fields at the end of the structure... */
5877 for (i = 0; i < size; i++) /* ...and then mark its elements. */
5878 mark_object (ptr->contents[i]);
5881 /* Like mark_vectorlike but optimized for char-tables (and
5882 sub-char-tables) assuming that the contents are mostly integers or
5883 symbols. */
5885 static void
5886 mark_char_table (struct Lisp_Vector *ptr, enum pvec_type pvectype)
5888 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5889 /* Consult the Lisp_Sub_Char_Table layout before changing this. */
5890 int i, idx = (pvectype == PVEC_SUB_CHAR_TABLE ? SUB_CHAR_TABLE_OFFSET : 0);
5892 eassert (!VECTOR_MARKED_P (ptr));
5893 VECTOR_MARK (ptr);
5894 for (i = idx; i < size; i++)
5896 Lisp_Object val = ptr->contents[i];
5898 if (INTEGERP (val) || (SYMBOLP (val) && XSYMBOL (val)->gcmarkbit))
5899 continue;
5900 if (SUB_CHAR_TABLE_P (val))
5902 if (! VECTOR_MARKED_P (XVECTOR (val)))
5903 mark_char_table (XVECTOR (val), PVEC_SUB_CHAR_TABLE);
5905 else
5906 mark_object (val);
5910 NO_INLINE /* To reduce stack depth in mark_object. */
5911 static Lisp_Object
5912 mark_compiled (struct Lisp_Vector *ptr)
5914 int i, size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5916 VECTOR_MARK (ptr);
5917 for (i = 0; i < size; i++)
5918 if (i != COMPILED_CONSTANTS)
5919 mark_object (ptr->contents[i]);
5920 return size > COMPILED_CONSTANTS ? ptr->contents[COMPILED_CONSTANTS] : Qnil;
5923 /* Mark the chain of overlays starting at PTR. */
5925 static void
5926 mark_overlay (struct Lisp_Overlay *ptr)
5928 for (; ptr && !ptr->gcmarkbit; ptr = ptr->next)
5930 ptr->gcmarkbit = 1;
5931 /* These two are always markers and can be marked fast. */
5932 XMARKER (ptr->start)->gcmarkbit = 1;
5933 XMARKER (ptr->end)->gcmarkbit = 1;
5934 mark_object (ptr->plist);
5938 /* Mark Lisp_Objects and special pointers in BUFFER. */
5940 static void
5941 mark_buffer (struct buffer *buffer)
5943 /* This is handled much like other pseudovectors... */
5944 mark_vectorlike ((struct Lisp_Vector *) buffer);
5946 /* ...but there are some buffer-specific things. */
5948 MARK_INTERVAL_TREE (buffer_intervals (buffer));
5950 /* For now, we just don't mark the undo_list. It's done later in
5951 a special way just before the sweep phase, and after stripping
5952 some of its elements that are not needed any more. */
5954 mark_overlay (buffer->overlays_before);
5955 mark_overlay (buffer->overlays_after);
5957 /* If this is an indirect buffer, mark its base buffer. */
5958 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5959 mark_buffer (buffer->base_buffer);
5962 /* Mark Lisp faces in the face cache C. */
5964 NO_INLINE /* To reduce stack depth in mark_object. */
5965 static void
5966 mark_face_cache (struct face_cache *c)
5968 if (c)
5970 int i, j;
5971 for (i = 0; i < c->used; ++i)
5973 struct face *face = FACE_FROM_ID (c->f, i);
5975 if (face)
5977 if (face->font && !VECTOR_MARKED_P (face->font))
5978 mark_vectorlike ((struct Lisp_Vector *) face->font);
5980 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
5981 mark_object (face->lface[j]);
5987 NO_INLINE /* To reduce stack depth in mark_object. */
5988 static void
5989 mark_localized_symbol (struct Lisp_Symbol *ptr)
5991 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
5992 Lisp_Object where = blv->where;
5993 /* If the value is set up for a killed buffer or deleted
5994 frame, restore its global binding. If the value is
5995 forwarded to a C variable, either it's not a Lisp_Object
5996 var, or it's staticpro'd already. */
5997 if ((BUFFERP (where) && !BUFFER_LIVE_P (XBUFFER (where)))
5998 || (FRAMEP (where) && !FRAME_LIVE_P (XFRAME (where))))
5999 swap_in_global_binding (ptr);
6000 mark_object (blv->where);
6001 mark_object (blv->valcell);
6002 mark_object (blv->defcell);
6005 NO_INLINE /* To reduce stack depth in mark_object. */
6006 static void
6007 mark_save_value (struct Lisp_Save_Value *ptr)
6009 /* If `save_type' is zero, `data[0].pointer' is the address
6010 of a memory area containing `data[1].integer' potential
6011 Lisp_Objects. */
6012 if (ptr->save_type == SAVE_TYPE_MEMORY)
6014 Lisp_Object *p = ptr->data[0].pointer;
6015 ptrdiff_t nelt;
6016 for (nelt = ptr->data[1].integer; nelt > 0; nelt--, p++)
6017 mark_maybe_object (*p);
6019 else
6021 /* Find Lisp_Objects in `data[N]' slots and mark them. */
6022 int i;
6023 for (i = 0; i < SAVE_VALUE_SLOTS; i++)
6024 if (save_type (ptr, i) == SAVE_OBJECT)
6025 mark_object (ptr->data[i].object);
6029 /* Remove killed buffers or items whose car is a killed buffer from
6030 LIST, and mark other items. Return changed LIST, which is marked. */
6032 static Lisp_Object
6033 mark_discard_killed_buffers (Lisp_Object list)
6035 Lisp_Object tail, *prev = &list;
6037 for (tail = list; CONSP (tail) && !CONS_MARKED_P (XCONS (tail));
6038 tail = XCDR (tail))
6040 Lisp_Object tem = XCAR (tail);
6041 if (CONSP (tem))
6042 tem = XCAR (tem);
6043 if (BUFFERP (tem) && !BUFFER_LIVE_P (XBUFFER (tem)))
6044 *prev = XCDR (tail);
6045 else
6047 CONS_MARK (XCONS (tail));
6048 mark_object (XCAR (tail));
6049 prev = xcdr_addr (tail);
6052 mark_object (tail);
6053 return list;
6056 /* Determine type of generic Lisp_Object and mark it accordingly.
6058 This function implements a straightforward depth-first marking
6059 algorithm and so the recursion depth may be very high (a few
6060 tens of thousands is not uncommon). To minimize stack usage,
6061 a few cold paths are moved out to NO_INLINE functions above.
6062 In general, inlining them doesn't help you to gain more speed. */
6064 void
6065 mark_object (Lisp_Object arg)
6067 register Lisp_Object obj;
6068 void *po;
6069 #ifdef GC_CHECK_MARKED_OBJECTS
6070 struct mem_node *m;
6071 #endif
6072 ptrdiff_t cdr_count = 0;
6074 obj = arg;
6075 loop:
6077 po = XPNTR (obj);
6078 if (PURE_P (po))
6079 return;
6081 last_marked[last_marked_index++] = obj;
6082 if (last_marked_index == LAST_MARKED_SIZE)
6083 last_marked_index = 0;
6085 /* Perform some sanity checks on the objects marked here. Abort if
6086 we encounter an object we know is bogus. This increases GC time
6087 by ~80%. */
6088 #ifdef GC_CHECK_MARKED_OBJECTS
6090 /* Check that the object pointed to by PO is known to be a Lisp
6091 structure allocated from the heap. */
6092 #define CHECK_ALLOCATED() \
6093 do { \
6094 m = mem_find (po); \
6095 if (m == MEM_NIL) \
6096 emacs_abort (); \
6097 } while (0)
6099 /* Check that the object pointed to by PO is live, using predicate
6100 function LIVEP. */
6101 #define CHECK_LIVE(LIVEP) \
6102 do { \
6103 if (!LIVEP (m, po)) \
6104 emacs_abort (); \
6105 } while (0)
6107 /* Check both of the above conditions, for non-symbols. */
6108 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
6109 do { \
6110 CHECK_ALLOCATED (); \
6111 CHECK_LIVE (LIVEP); \
6112 } while (0) \
6114 /* Check both of the above conditions, for symbols. */
6115 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() \
6116 do { \
6117 if (!c_symbol_p (ptr)) \
6119 CHECK_ALLOCATED (); \
6120 CHECK_LIVE (live_symbol_p); \
6122 } while (0) \
6124 #else /* not GC_CHECK_MARKED_OBJECTS */
6126 #define CHECK_LIVE(LIVEP) ((void) 0)
6127 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) ((void) 0)
6128 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() ((void) 0)
6130 #endif /* not GC_CHECK_MARKED_OBJECTS */
6132 switch (XTYPE (obj))
6134 case Lisp_String:
6136 register struct Lisp_String *ptr = XSTRING (obj);
6137 if (STRING_MARKED_P (ptr))
6138 break;
6139 CHECK_ALLOCATED_AND_LIVE (live_string_p);
6140 MARK_STRING (ptr);
6141 MARK_INTERVAL_TREE (ptr->intervals);
6142 #ifdef GC_CHECK_STRING_BYTES
6143 /* Check that the string size recorded in the string is the
6144 same as the one recorded in the sdata structure. */
6145 string_bytes (ptr);
6146 #endif /* GC_CHECK_STRING_BYTES */
6148 break;
6150 case Lisp_Vectorlike:
6152 register struct Lisp_Vector *ptr = XVECTOR (obj);
6153 register ptrdiff_t pvectype;
6155 if (VECTOR_MARKED_P (ptr))
6156 break;
6158 #ifdef GC_CHECK_MARKED_OBJECTS
6159 m = mem_find (po);
6160 if (m == MEM_NIL && !SUBRP (obj))
6161 emacs_abort ();
6162 #endif /* GC_CHECK_MARKED_OBJECTS */
6164 if (ptr->header.size & PSEUDOVECTOR_FLAG)
6165 pvectype = ((ptr->header.size & PVEC_TYPE_MASK)
6166 >> PSEUDOVECTOR_AREA_BITS);
6167 else
6168 pvectype = PVEC_NORMAL_VECTOR;
6170 if (pvectype != PVEC_SUBR && pvectype != PVEC_BUFFER)
6171 CHECK_LIVE (live_vector_p);
6173 switch (pvectype)
6175 case PVEC_BUFFER:
6176 #ifdef GC_CHECK_MARKED_OBJECTS
6178 struct buffer *b;
6179 FOR_EACH_BUFFER (b)
6180 if (b == po)
6181 break;
6182 if (b == NULL)
6183 emacs_abort ();
6185 #endif /* GC_CHECK_MARKED_OBJECTS */
6186 mark_buffer ((struct buffer *) ptr);
6187 break;
6189 case PVEC_COMPILED:
6190 /* Although we could treat this just like a vector, mark_compiled
6191 returns the COMPILED_CONSTANTS element, which is marked at the
6192 next iteration of goto-loop here. This is done to avoid a few
6193 recursive calls to mark_object. */
6194 obj = mark_compiled (ptr);
6195 if (!NILP (obj))
6196 goto loop;
6197 break;
6199 case PVEC_FRAME:
6201 struct frame *f = (struct frame *) ptr;
6203 mark_vectorlike (ptr);
6204 mark_face_cache (f->face_cache);
6205 #ifdef HAVE_WINDOW_SYSTEM
6206 if (FRAME_WINDOW_P (f) && FRAME_X_OUTPUT (f))
6208 struct font *font = FRAME_FONT (f);
6210 if (font && !VECTOR_MARKED_P (font))
6211 mark_vectorlike ((struct Lisp_Vector *) font);
6213 #endif
6215 break;
6217 case PVEC_WINDOW:
6219 struct window *w = (struct window *) ptr;
6221 mark_vectorlike (ptr);
6223 /* Mark glyph matrices, if any. Marking window
6224 matrices is sufficient because frame matrices
6225 use the same glyph memory. */
6226 if (w->current_matrix)
6228 mark_glyph_matrix (w->current_matrix);
6229 mark_glyph_matrix (w->desired_matrix);
6232 /* Filter out killed buffers from both buffer lists
6233 in attempt to help GC to reclaim killed buffers faster.
6234 We can do it elsewhere for live windows, but this is the
6235 best place to do it for dead windows. */
6236 wset_prev_buffers
6237 (w, mark_discard_killed_buffers (w->prev_buffers));
6238 wset_next_buffers
6239 (w, mark_discard_killed_buffers (w->next_buffers));
6241 break;
6243 case PVEC_HASH_TABLE:
6245 struct Lisp_Hash_Table *h = (struct Lisp_Hash_Table *) ptr;
6247 mark_vectorlike (ptr);
6248 mark_object (h->test.name);
6249 mark_object (h->test.user_hash_function);
6250 mark_object (h->test.user_cmp_function);
6251 /* If hash table is not weak, mark all keys and values.
6252 For weak tables, mark only the vector. */
6253 if (NILP (h->weak))
6254 mark_object (h->key_and_value);
6255 else
6256 VECTOR_MARK (XVECTOR (h->key_and_value));
6258 break;
6260 case PVEC_CHAR_TABLE:
6261 case PVEC_SUB_CHAR_TABLE:
6262 mark_char_table (ptr, (enum pvec_type) pvectype);
6263 break;
6265 case PVEC_BOOL_VECTOR:
6266 /* No Lisp_Objects to mark in a bool vector. */
6267 VECTOR_MARK (ptr);
6268 break;
6270 case PVEC_SUBR:
6271 break;
6273 case PVEC_FREE:
6274 emacs_abort ();
6276 default:
6277 mark_vectorlike (ptr);
6280 break;
6282 case Lisp_Symbol:
6284 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
6285 nextsym:
6286 if (ptr->gcmarkbit)
6287 break;
6288 CHECK_ALLOCATED_AND_LIVE_SYMBOL ();
6289 ptr->gcmarkbit = 1;
6290 /* Attempt to catch bogus objects. */
6291 eassert (valid_lisp_object_p (ptr->function));
6292 mark_object (ptr->function);
6293 mark_object (ptr->plist);
6294 switch (ptr->redirect)
6296 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
6297 case SYMBOL_VARALIAS:
6299 Lisp_Object tem;
6300 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
6301 mark_object (tem);
6302 break;
6304 case SYMBOL_LOCALIZED:
6305 mark_localized_symbol (ptr);
6306 break;
6307 case SYMBOL_FORWARDED:
6308 /* If the value is forwarded to a buffer or keyboard field,
6309 these are marked when we see the corresponding object.
6310 And if it's forwarded to a C variable, either it's not
6311 a Lisp_Object var, or it's staticpro'd already. */
6312 break;
6313 default: emacs_abort ();
6315 if (!PURE_P (XSTRING (ptr->name)))
6316 MARK_STRING (XSTRING (ptr->name));
6317 MARK_INTERVAL_TREE (string_intervals (ptr->name));
6318 /* Inner loop to mark next symbol in this bucket, if any. */
6319 po = ptr = ptr->next;
6320 if (ptr)
6321 goto nextsym;
6323 break;
6325 case Lisp_Misc:
6326 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
6328 if (XMISCANY (obj)->gcmarkbit)
6329 break;
6331 switch (XMISCTYPE (obj))
6333 case Lisp_Misc_Marker:
6334 /* DO NOT mark thru the marker's chain.
6335 The buffer's markers chain does not preserve markers from gc;
6336 instead, markers are removed from the chain when freed by gc. */
6337 XMISCANY (obj)->gcmarkbit = 1;
6338 break;
6340 case Lisp_Misc_Save_Value:
6341 XMISCANY (obj)->gcmarkbit = 1;
6342 mark_save_value (XSAVE_VALUE (obj));
6343 break;
6345 case Lisp_Misc_Overlay:
6346 mark_overlay (XOVERLAY (obj));
6347 break;
6349 case Lisp_Misc_Finalizer:
6350 XMISCANY (obj)->gcmarkbit = true;
6351 mark_object (XFINALIZER (obj)->function);
6352 break;
6354 #ifdef HAVE_MODULES
6355 case Lisp_Misc_User_Ptr:
6356 XMISCANY (obj)->gcmarkbit = true;
6357 break;
6358 #endif
6360 default:
6361 emacs_abort ();
6363 break;
6365 case Lisp_Cons:
6367 register struct Lisp_Cons *ptr = XCONS (obj);
6368 if (CONS_MARKED_P (ptr))
6369 break;
6370 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
6371 CONS_MARK (ptr);
6372 /* If the cdr is nil, avoid recursion for the car. */
6373 if (EQ (ptr->u.cdr, Qnil))
6375 obj = ptr->car;
6376 cdr_count = 0;
6377 goto loop;
6379 mark_object (ptr->car);
6380 obj = ptr->u.cdr;
6381 cdr_count++;
6382 if (cdr_count == mark_object_loop_halt)
6383 emacs_abort ();
6384 goto loop;
6387 case Lisp_Float:
6388 CHECK_ALLOCATED_AND_LIVE (live_float_p);
6389 FLOAT_MARK (XFLOAT (obj));
6390 break;
6392 case_Lisp_Int:
6393 break;
6395 default:
6396 emacs_abort ();
6399 #undef CHECK_LIVE
6400 #undef CHECK_ALLOCATED
6401 #undef CHECK_ALLOCATED_AND_LIVE
6403 /* Mark the Lisp pointers in the terminal objects.
6404 Called by Fgarbage_collect. */
6406 static void
6407 mark_terminals (void)
6409 struct terminal *t;
6410 for (t = terminal_list; t; t = t->next_terminal)
6412 eassert (t->name != NULL);
6413 #ifdef HAVE_WINDOW_SYSTEM
6414 /* If a terminal object is reachable from a stacpro'ed object,
6415 it might have been marked already. Make sure the image cache
6416 gets marked. */
6417 mark_image_cache (t->image_cache);
6418 #endif /* HAVE_WINDOW_SYSTEM */
6419 if (!VECTOR_MARKED_P (t))
6420 mark_vectorlike ((struct Lisp_Vector *)t);
6426 /* Value is non-zero if OBJ will survive the current GC because it's
6427 either marked or does not need to be marked to survive. */
6429 bool
6430 survives_gc_p (Lisp_Object obj)
6432 bool survives_p;
6434 switch (XTYPE (obj))
6436 case_Lisp_Int:
6437 survives_p = 1;
6438 break;
6440 case Lisp_Symbol:
6441 survives_p = XSYMBOL (obj)->gcmarkbit;
6442 break;
6444 case Lisp_Misc:
6445 survives_p = XMISCANY (obj)->gcmarkbit;
6446 break;
6448 case Lisp_String:
6449 survives_p = STRING_MARKED_P (XSTRING (obj));
6450 break;
6452 case Lisp_Vectorlike:
6453 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
6454 break;
6456 case Lisp_Cons:
6457 survives_p = CONS_MARKED_P (XCONS (obj));
6458 break;
6460 case Lisp_Float:
6461 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
6462 break;
6464 default:
6465 emacs_abort ();
6468 return survives_p || PURE_P (XPNTR (obj));
6474 NO_INLINE /* For better stack traces */
6475 static void
6476 sweep_conses (void)
6478 struct cons_block *cblk;
6479 struct cons_block **cprev = &cons_block;
6480 int lim = cons_block_index;
6481 EMACS_INT num_free = 0, num_used = 0;
6483 cons_free_list = 0;
6485 for (cblk = cons_block; cblk; cblk = *cprev)
6487 int i = 0;
6488 int this_free = 0;
6489 int ilim = (lim + BITS_PER_BITS_WORD - 1) / BITS_PER_BITS_WORD;
6491 /* Scan the mark bits an int at a time. */
6492 for (i = 0; i < ilim; i++)
6494 if (cblk->gcmarkbits[i] == BITS_WORD_MAX)
6496 /* Fast path - all cons cells for this int are marked. */
6497 cblk->gcmarkbits[i] = 0;
6498 num_used += BITS_PER_BITS_WORD;
6500 else
6502 /* Some cons cells for this int are not marked.
6503 Find which ones, and free them. */
6504 int start, pos, stop;
6506 start = i * BITS_PER_BITS_WORD;
6507 stop = lim - start;
6508 if (stop > BITS_PER_BITS_WORD)
6509 stop = BITS_PER_BITS_WORD;
6510 stop += start;
6512 for (pos = start; pos < stop; pos++)
6514 if (!CONS_MARKED_P (&cblk->conses[pos]))
6516 this_free++;
6517 cblk->conses[pos].u.chain = cons_free_list;
6518 cons_free_list = &cblk->conses[pos];
6519 cons_free_list->car = Vdead;
6521 else
6523 num_used++;
6524 CONS_UNMARK (&cblk->conses[pos]);
6530 lim = CONS_BLOCK_SIZE;
6531 /* If this block contains only free conses and we have already
6532 seen more than two blocks worth of free conses then deallocate
6533 this block. */
6534 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
6536 *cprev = cblk->next;
6537 /* Unhook from the free list. */
6538 cons_free_list = cblk->conses[0].u.chain;
6539 lisp_align_free (cblk);
6541 else
6543 num_free += this_free;
6544 cprev = &cblk->next;
6547 total_conses = num_used;
6548 total_free_conses = num_free;
6551 NO_INLINE /* For better stack traces */
6552 static void
6553 sweep_floats (void)
6555 register struct float_block *fblk;
6556 struct float_block **fprev = &float_block;
6557 register int lim = float_block_index;
6558 EMACS_INT num_free = 0, num_used = 0;
6560 float_free_list = 0;
6562 for (fblk = float_block; fblk; fblk = *fprev)
6564 register int i;
6565 int this_free = 0;
6566 for (i = 0; i < lim; i++)
6567 if (!FLOAT_MARKED_P (&fblk->floats[i]))
6569 this_free++;
6570 fblk->floats[i].u.chain = float_free_list;
6571 float_free_list = &fblk->floats[i];
6573 else
6575 num_used++;
6576 FLOAT_UNMARK (&fblk->floats[i]);
6578 lim = FLOAT_BLOCK_SIZE;
6579 /* If this block contains only free floats and we have already
6580 seen more than two blocks worth of free floats then deallocate
6581 this block. */
6582 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6584 *fprev = fblk->next;
6585 /* Unhook from the free list. */
6586 float_free_list = fblk->floats[0].u.chain;
6587 lisp_align_free (fblk);
6589 else
6591 num_free += this_free;
6592 fprev = &fblk->next;
6595 total_floats = num_used;
6596 total_free_floats = num_free;
6599 NO_INLINE /* For better stack traces */
6600 static void
6601 sweep_intervals (void)
6603 register struct interval_block *iblk;
6604 struct interval_block **iprev = &interval_block;
6605 register int lim = interval_block_index;
6606 EMACS_INT num_free = 0, num_used = 0;
6608 interval_free_list = 0;
6610 for (iblk = interval_block; iblk; iblk = *iprev)
6612 register int i;
6613 int this_free = 0;
6615 for (i = 0; i < lim; i++)
6617 if (!iblk->intervals[i].gcmarkbit)
6619 set_interval_parent (&iblk->intervals[i], interval_free_list);
6620 interval_free_list = &iblk->intervals[i];
6621 this_free++;
6623 else
6625 num_used++;
6626 iblk->intervals[i].gcmarkbit = 0;
6629 lim = INTERVAL_BLOCK_SIZE;
6630 /* If this block contains only free intervals and we have already
6631 seen more than two blocks worth of free intervals then
6632 deallocate this block. */
6633 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6635 *iprev = iblk->next;
6636 /* Unhook from the free list. */
6637 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
6638 lisp_free (iblk);
6640 else
6642 num_free += this_free;
6643 iprev = &iblk->next;
6646 total_intervals = num_used;
6647 total_free_intervals = num_free;
6650 NO_INLINE /* For better stack traces */
6651 static void
6652 sweep_symbols (void)
6654 struct symbol_block *sblk;
6655 struct symbol_block **sprev = &symbol_block;
6656 int lim = symbol_block_index;
6657 EMACS_INT num_free = 0, num_used = ARRAYELTS (lispsym);
6659 symbol_free_list = NULL;
6661 for (int i = 0; i < ARRAYELTS (lispsym); i++)
6662 lispsym[i].gcmarkbit = 0;
6664 for (sblk = symbol_block; sblk; sblk = *sprev)
6666 int this_free = 0;
6667 union aligned_Lisp_Symbol *sym = sblk->symbols;
6668 union aligned_Lisp_Symbol *end = sym + lim;
6670 for (; sym < end; ++sym)
6672 if (!sym->s.gcmarkbit)
6674 if (sym->s.redirect == SYMBOL_LOCALIZED)
6675 xfree (SYMBOL_BLV (&sym->s));
6676 sym->s.next = symbol_free_list;
6677 symbol_free_list = &sym->s;
6678 symbol_free_list->function = Vdead;
6679 ++this_free;
6681 else
6683 ++num_used;
6684 sym->s.gcmarkbit = 0;
6685 /* Attempt to catch bogus objects. */
6686 eassert (valid_lisp_object_p (sym->s.function));
6690 lim = SYMBOL_BLOCK_SIZE;
6691 /* If this block contains only free symbols and we have already
6692 seen more than two blocks worth of free symbols then deallocate
6693 this block. */
6694 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6696 *sprev = sblk->next;
6697 /* Unhook from the free list. */
6698 symbol_free_list = sblk->symbols[0].s.next;
6699 lisp_free (sblk);
6701 else
6703 num_free += this_free;
6704 sprev = &sblk->next;
6707 total_symbols = num_used;
6708 total_free_symbols = num_free;
6711 NO_INLINE /* For better stack traces. */
6712 static void
6713 sweep_misc (void)
6715 register struct marker_block *mblk;
6716 struct marker_block **mprev = &marker_block;
6717 register int lim = marker_block_index;
6718 EMACS_INT num_free = 0, num_used = 0;
6720 /* Put all unmarked misc's on free list. For a marker, first
6721 unchain it from the buffer it points into. */
6723 marker_free_list = 0;
6725 for (mblk = marker_block; mblk; mblk = *mprev)
6727 register int i;
6728 int this_free = 0;
6730 for (i = 0; i < lim; i++)
6732 if (!mblk->markers[i].m.u_any.gcmarkbit)
6734 if (mblk->markers[i].m.u_any.type == Lisp_Misc_Marker)
6735 unchain_marker (&mblk->markers[i].m.u_marker);
6736 else if (mblk->markers[i].m.u_any.type == Lisp_Misc_Finalizer)
6737 unchain_finalizer (&mblk->markers[i].m.u_finalizer);
6738 #ifdef HAVE_MODULES
6739 else if (mblk->markers[i].m.u_any.type == Lisp_Misc_User_Ptr)
6741 struct Lisp_User_Ptr *uptr = &mblk->markers[i].m.u_user_ptr;
6742 uptr->finalizer (uptr->p);
6744 #endif
6745 /* Set the type of the freed object to Lisp_Misc_Free.
6746 We could leave the type alone, since nobody checks it,
6747 but this might catch bugs faster. */
6748 mblk->markers[i].m.u_marker.type = Lisp_Misc_Free;
6749 mblk->markers[i].m.u_free.chain = marker_free_list;
6750 marker_free_list = &mblk->markers[i].m;
6751 this_free++;
6753 else
6755 num_used++;
6756 mblk->markers[i].m.u_any.gcmarkbit = 0;
6759 lim = MARKER_BLOCK_SIZE;
6760 /* If this block contains only free markers and we have already
6761 seen more than two blocks worth of free markers then deallocate
6762 this block. */
6763 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6765 *mprev = mblk->next;
6766 /* Unhook from the free list. */
6767 marker_free_list = mblk->markers[0].m.u_free.chain;
6768 lisp_free (mblk);
6770 else
6772 num_free += this_free;
6773 mprev = &mblk->next;
6777 total_markers = num_used;
6778 total_free_markers = num_free;
6781 NO_INLINE /* For better stack traces */
6782 static void
6783 sweep_buffers (void)
6785 register struct buffer *buffer, **bprev = &all_buffers;
6787 total_buffers = 0;
6788 for (buffer = all_buffers; buffer; buffer = *bprev)
6789 if (!VECTOR_MARKED_P (buffer))
6791 *bprev = buffer->next;
6792 lisp_free (buffer);
6794 else
6796 VECTOR_UNMARK (buffer);
6797 /* Do not use buffer_(set|get)_intervals here. */
6798 buffer->text->intervals = balance_intervals (buffer->text->intervals);
6799 total_buffers++;
6800 bprev = &buffer->next;
6804 /* Sweep: find all structures not marked, and free them. */
6805 static void
6806 gc_sweep (void)
6808 /* Remove or mark entries in weak hash tables.
6809 This must be done before any object is unmarked. */
6810 sweep_weak_hash_tables ();
6812 sweep_strings ();
6813 check_string_bytes (!noninteractive);
6814 sweep_conses ();
6815 sweep_floats ();
6816 sweep_intervals ();
6817 sweep_symbols ();
6818 sweep_misc ();
6819 sweep_buffers ();
6820 sweep_vectors ();
6821 check_string_bytes (!noninteractive);
6824 DEFUN ("memory-info", Fmemory_info, Smemory_info, 0, 0, 0,
6825 doc: /* Return a list of (TOTAL-RAM FREE-RAM TOTAL-SWAP FREE-SWAP).
6826 All values are in Kbytes. If there is no swap space,
6827 last two values are zero. If the system is not supported
6828 or memory information can't be obtained, return nil. */)
6829 (void)
6831 #if defined HAVE_LINUX_SYSINFO
6832 struct sysinfo si;
6833 uintmax_t units;
6835 if (sysinfo (&si))
6836 return Qnil;
6837 #ifdef LINUX_SYSINFO_UNIT
6838 units = si.mem_unit;
6839 #else
6840 units = 1;
6841 #endif
6842 return list4i ((uintmax_t) si.totalram * units / 1024,
6843 (uintmax_t) si.freeram * units / 1024,
6844 (uintmax_t) si.totalswap * units / 1024,
6845 (uintmax_t) si.freeswap * units / 1024);
6846 #elif defined WINDOWSNT
6847 unsigned long long totalram, freeram, totalswap, freeswap;
6849 if (w32_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
6850 return list4i ((uintmax_t) totalram / 1024,
6851 (uintmax_t) freeram / 1024,
6852 (uintmax_t) totalswap / 1024,
6853 (uintmax_t) freeswap / 1024);
6854 else
6855 return Qnil;
6856 #elif defined MSDOS
6857 unsigned long totalram, freeram, totalswap, freeswap;
6859 if (dos_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
6860 return list4i ((uintmax_t) totalram / 1024,
6861 (uintmax_t) freeram / 1024,
6862 (uintmax_t) totalswap / 1024,
6863 (uintmax_t) freeswap / 1024);
6864 else
6865 return Qnil;
6866 #else /* not HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
6867 /* FIXME: add more systems. */
6868 return Qnil;
6869 #endif /* HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
6872 /* Debugging aids. */
6874 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
6875 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6876 This may be helpful in debugging Emacs's memory usage.
6877 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6878 (void)
6880 Lisp_Object end;
6882 #ifdef HAVE_NS
6883 /* Avoid warning. sbrk has no relation to memory allocated anyway. */
6884 XSETINT (end, 0);
6885 #else
6886 XSETINT (end, (intptr_t) (char *) sbrk (0) / 1024);
6887 #endif
6889 return end;
6892 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
6893 doc: /* Return a list of counters that measure how much consing there has been.
6894 Each of these counters increments for a certain kind of object.
6895 The counters wrap around from the largest positive integer to zero.
6896 Garbage collection does not decrease them.
6897 The elements of the value are as follows:
6898 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6899 All are in units of 1 = one object consed
6900 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6901 objects consed.
6902 MISCS include overlays, markers, and some internal types.
6903 Frames, windows, buffers, and subprocesses count as vectors
6904 (but the contents of a buffer's text do not count here). */)
6905 (void)
6907 return listn (CONSTYPE_HEAP, 8,
6908 bounded_number (cons_cells_consed),
6909 bounded_number (floats_consed),
6910 bounded_number (vector_cells_consed),
6911 bounded_number (symbols_consed),
6912 bounded_number (string_chars_consed),
6913 bounded_number (misc_objects_consed),
6914 bounded_number (intervals_consed),
6915 bounded_number (strings_consed));
6918 static bool
6919 symbol_uses_obj (Lisp_Object symbol, Lisp_Object obj)
6921 struct Lisp_Symbol *sym = XSYMBOL (symbol);
6922 Lisp_Object val = find_symbol_value (symbol);
6923 return (EQ (val, obj)
6924 || EQ (sym->function, obj)
6925 || (!NILP (sym->function)
6926 && COMPILEDP (sym->function)
6927 && EQ (AREF (sym->function, COMPILED_BYTECODE), obj))
6928 || (!NILP (val)
6929 && COMPILEDP (val)
6930 && EQ (AREF (val, COMPILED_BYTECODE), obj)));
6933 /* Find at most FIND_MAX symbols which have OBJ as their value or
6934 function. This is used in gdbinit's `xwhichsymbols' command. */
6936 Lisp_Object
6937 which_symbols (Lisp_Object obj, EMACS_INT find_max)
6939 struct symbol_block *sblk;
6940 ptrdiff_t gc_count = inhibit_garbage_collection ();
6941 Lisp_Object found = Qnil;
6943 if (! DEADP (obj))
6945 for (int i = 0; i < ARRAYELTS (lispsym); i++)
6947 Lisp_Object sym = builtin_lisp_symbol (i);
6948 if (symbol_uses_obj (sym, obj))
6950 found = Fcons (sym, found);
6951 if (--find_max == 0)
6952 goto out;
6956 for (sblk = symbol_block; sblk; sblk = sblk->next)
6958 union aligned_Lisp_Symbol *aligned_sym = sblk->symbols;
6959 int bn;
6961 for (bn = 0; bn < SYMBOL_BLOCK_SIZE; bn++, aligned_sym++)
6963 if (sblk == symbol_block && bn >= symbol_block_index)
6964 break;
6966 Lisp_Object sym = make_lisp_symbol (&aligned_sym->s);
6967 if (symbol_uses_obj (sym, obj))
6969 found = Fcons (sym, found);
6970 if (--find_max == 0)
6971 goto out;
6977 out:
6978 unbind_to (gc_count, Qnil);
6979 return found;
6982 #ifdef SUSPICIOUS_OBJECT_CHECKING
6984 static void *
6985 find_suspicious_object_in_range (void *begin, void *end)
6987 char *begin_a = begin;
6988 char *end_a = end;
6989 int i;
6991 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
6993 char *suspicious_object = suspicious_objects[i];
6994 if (begin_a <= suspicious_object && suspicious_object < end_a)
6995 return suspicious_object;
6998 return NULL;
7001 static void
7002 note_suspicious_free (void* ptr)
7004 struct suspicious_free_record* rec;
7006 rec = &suspicious_free_history[suspicious_free_history_index++];
7007 if (suspicious_free_history_index ==
7008 ARRAYELTS (suspicious_free_history))
7010 suspicious_free_history_index = 0;
7013 memset (rec, 0, sizeof (*rec));
7014 rec->suspicious_object = ptr;
7015 backtrace (&rec->backtrace[0], ARRAYELTS (rec->backtrace));
7018 static void
7019 detect_suspicious_free (void* ptr)
7021 int i;
7023 eassert (ptr != NULL);
7025 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
7026 if (suspicious_objects[i] == ptr)
7028 note_suspicious_free (ptr);
7029 suspicious_objects[i] = NULL;
7033 #endif /* SUSPICIOUS_OBJECT_CHECKING */
7035 DEFUN ("suspicious-object", Fsuspicious_object, Ssuspicious_object, 1, 1, 0,
7036 doc: /* Return OBJ, maybe marking it for extra scrutiny.
7037 If Emacs is compiled with suspicious object checking, capture
7038 a stack trace when OBJ is freed in order to help track down
7039 garbage collection bugs. Otherwise, do nothing and return OBJ. */)
7040 (Lisp_Object obj)
7042 #ifdef SUSPICIOUS_OBJECT_CHECKING
7043 /* Right now, we care only about vectors. */
7044 if (VECTORLIKEP (obj))
7046 suspicious_objects[suspicious_object_index++] = XVECTOR (obj);
7047 if (suspicious_object_index == ARRAYELTS (suspicious_objects))
7048 suspicious_object_index = 0;
7050 #endif
7051 return obj;
7054 #ifdef ENABLE_CHECKING
7056 bool suppress_checking;
7058 void
7059 die (const char *msg, const char *file, int line)
7061 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: assertion failed: %s\r\n",
7062 file, line, msg);
7063 terminate_due_to_signal (SIGABRT, INT_MAX);
7066 #endif /* ENABLE_CHECKING */
7068 #if defined (ENABLE_CHECKING) && USE_STACK_LISP_OBJECTS
7070 /* Debugging check whether STR is ASCII-only. */
7072 const char *
7073 verify_ascii (const char *str)
7075 const unsigned char *ptr = (unsigned char *) str, *end = ptr + strlen (str);
7076 while (ptr < end)
7078 int c = STRING_CHAR_ADVANCE (ptr);
7079 if (!ASCII_CHAR_P (c))
7080 emacs_abort ();
7082 return str;
7085 /* Stress alloca with inconveniently sized requests and check
7086 whether all allocated areas may be used for Lisp_Object. */
7088 NO_INLINE static void
7089 verify_alloca (void)
7091 int i;
7092 enum { ALLOCA_CHECK_MAX = 256 };
7093 /* Start from size of the smallest Lisp object. */
7094 for (i = sizeof (struct Lisp_Cons); i <= ALLOCA_CHECK_MAX; i++)
7096 void *ptr = alloca (i);
7097 make_lisp_ptr (ptr, Lisp_Cons);
7101 #else /* not ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7103 #define verify_alloca() ((void) 0)
7105 #endif /* ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7107 /* Initialization. */
7109 void
7110 init_alloc_once (void)
7112 /* Even though Qt's contents are not set up, its address is known. */
7113 Vpurify_flag = Qt;
7115 purebeg = PUREBEG;
7116 pure_size = PURESIZE;
7118 verify_alloca ();
7119 init_finalizer_list (&finalizers);
7120 init_finalizer_list (&doomed_finalizers);
7122 mem_init ();
7123 Vdead = make_pure_string ("DEAD", 4, 4, 0);
7125 #ifdef DOUG_LEA_MALLOC
7126 mallopt (M_TRIM_THRESHOLD, 128 * 1024); /* Trim threshold. */
7127 mallopt (M_MMAP_THRESHOLD, 64 * 1024); /* Mmap threshold. */
7128 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* Max. number of mmap'ed areas. */
7129 #endif
7130 init_strings ();
7131 init_vectors ();
7133 refill_memory_reserve ();
7134 gc_cons_threshold = GC_DEFAULT_THRESHOLD;
7137 void
7138 init_alloc (void)
7140 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
7141 setjmp_tested_p = longjmps_done = 0;
7142 #endif
7143 Vgc_elapsed = make_float (0.0);
7144 gcs_done = 0;
7146 #if USE_VALGRIND
7147 valgrind_p = RUNNING_ON_VALGRIND != 0;
7148 #endif
7151 void
7152 syms_of_alloc (void)
7154 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
7155 doc: /* Number of bytes of consing between garbage collections.
7156 Garbage collection can happen automatically once this many bytes have been
7157 allocated since the last garbage collection. All data types count.
7159 Garbage collection happens automatically only when `eval' is called.
7161 By binding this temporarily to a large number, you can effectively
7162 prevent garbage collection during a part of the program.
7163 See also `gc-cons-percentage'. */);
7165 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
7166 doc: /* Portion of the heap used for allocation.
7167 Garbage collection can happen automatically once this portion of the heap
7168 has been allocated since the last garbage collection.
7169 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
7170 Vgc_cons_percentage = make_float (0.1);
7172 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
7173 doc: /* Number of bytes of shareable Lisp data allocated so far. */);
7175 DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
7176 doc: /* Number of cons cells that have been consed so far. */);
7178 DEFVAR_INT ("floats-consed", floats_consed,
7179 doc: /* Number of floats that have been consed so far. */);
7181 DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
7182 doc: /* Number of vector cells that have been consed so far. */);
7184 DEFVAR_INT ("symbols-consed", symbols_consed,
7185 doc: /* Number of symbols that have been consed so far. */);
7186 symbols_consed += ARRAYELTS (lispsym);
7188 DEFVAR_INT ("string-chars-consed", string_chars_consed,
7189 doc: /* Number of string characters that have been consed so far. */);
7191 DEFVAR_INT ("misc-objects-consed", misc_objects_consed,
7192 doc: /* Number of miscellaneous objects that have been consed so far.
7193 These include markers and overlays, plus certain objects not visible
7194 to users. */);
7196 DEFVAR_INT ("intervals-consed", intervals_consed,
7197 doc: /* Number of intervals that have been consed so far. */);
7199 DEFVAR_INT ("strings-consed", strings_consed,
7200 doc: /* Number of strings that have been consed so far. */);
7202 DEFVAR_LISP ("purify-flag", Vpurify_flag,
7203 doc: /* Non-nil means loading Lisp code in order to dump an executable.
7204 This means that certain objects should be allocated in shared (pure) space.
7205 It can also be set to a hash-table, in which case this table is used to
7206 do hash-consing of the objects allocated to pure space. */);
7208 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
7209 doc: /* Non-nil means display messages at start and end of garbage collection. */);
7210 garbage_collection_messages = 0;
7212 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
7213 doc: /* Hook run after garbage collection has finished. */);
7214 Vpost_gc_hook = Qnil;
7215 DEFSYM (Qpost_gc_hook, "post-gc-hook");
7217 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
7218 doc: /* Precomputed `signal' argument for memory-full error. */);
7219 /* We build this in advance because if we wait until we need it, we might
7220 not be able to allocate the memory to hold it. */
7221 Vmemory_signal_data
7222 = listn (CONSTYPE_PURE, 2, Qerror,
7223 build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
7225 DEFVAR_LISP ("memory-full", Vmemory_full,
7226 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
7227 Vmemory_full = Qnil;
7229 DEFSYM (Qconses, "conses");
7230 DEFSYM (Qsymbols, "symbols");
7231 DEFSYM (Qmiscs, "miscs");
7232 DEFSYM (Qstrings, "strings");
7233 DEFSYM (Qvectors, "vectors");
7234 DEFSYM (Qfloats, "floats");
7235 DEFSYM (Qintervals, "intervals");
7236 DEFSYM (Qbuffers, "buffers");
7237 DEFSYM (Qstring_bytes, "string-bytes");
7238 DEFSYM (Qvector_slots, "vector-slots");
7239 DEFSYM (Qheap, "heap");
7240 DEFSYM (Qautomatic_gc, "Automatic GC");
7242 DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
7243 DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
7245 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
7246 doc: /* Accumulated time elapsed in garbage collections.
7247 The time is in seconds as a floating point value. */);
7248 DEFVAR_INT ("gcs-done", gcs_done,
7249 doc: /* Accumulated number of garbage collections done. */);
7251 defsubr (&Scons);
7252 defsubr (&Slist);
7253 defsubr (&Svector);
7254 defsubr (&Sbool_vector);
7255 defsubr (&Smake_byte_code);
7256 defsubr (&Smake_list);
7257 defsubr (&Smake_vector);
7258 defsubr (&Smake_string);
7259 defsubr (&Smake_bool_vector);
7260 defsubr (&Smake_symbol);
7261 defsubr (&Smake_marker);
7262 defsubr (&Smake_finalizer);
7263 defsubr (&Spurecopy);
7264 defsubr (&Sgarbage_collect);
7265 defsubr (&Smemory_limit);
7266 defsubr (&Smemory_info);
7267 defsubr (&Smemory_use_counts);
7268 defsubr (&Ssuspicious_object);
7271 /* When compiled with GCC, GDB might say "No enum type named
7272 pvec_type" if we don't have at least one symbol with that type, and
7273 then xbacktrace could fail. Similarly for the other enums and
7274 their values. Some non-GCC compilers don't like these constructs. */
7275 #ifdef __GNUC__
7276 union
7278 enum CHARTAB_SIZE_BITS CHARTAB_SIZE_BITS;
7279 enum char_table_specials char_table_specials;
7280 enum char_bits char_bits;
7281 enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE;
7282 enum DEFAULT_HASH_SIZE DEFAULT_HASH_SIZE;
7283 enum Lisp_Bits Lisp_Bits;
7284 enum Lisp_Compiled Lisp_Compiled;
7285 enum maxargs maxargs;
7286 enum MAX_ALLOCA MAX_ALLOCA;
7287 enum More_Lisp_Bits More_Lisp_Bits;
7288 enum pvec_type pvec_type;
7289 } const EXTERNALLY_VISIBLE gdb_make_enums_visible = {0};
7290 #endif /* __GNUC__ */