Refactor mml-smime.el, mml1991.el, mml2015.el
[emacs.git] / src / alloc.c
blob9ec44b8a2c35fee16fc257e4b1ec587bbebe4975
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 /* If P points to Lisp data, mark that as live if it isn't already
4598 marked. */
4600 static void
4601 mark_maybe_pointer (void *p)
4603 struct mem_node *m;
4605 #if USE_VALGRIND
4606 if (valgrind_p)
4607 VALGRIND_MAKE_MEM_DEFINED (&p, sizeof (p));
4608 #endif
4610 if (!maybe_lisp_pointer (p))
4611 return;
4613 m = mem_find (p);
4614 if (m != MEM_NIL)
4616 Lisp_Object obj = Qnil;
4618 switch (m->type)
4620 case MEM_TYPE_NON_LISP:
4621 case MEM_TYPE_SPARE:
4622 /* Nothing to do; not a pointer to Lisp memory. */
4623 break;
4625 case MEM_TYPE_BUFFER:
4626 if (live_buffer_p (m, p) && !VECTOR_MARKED_P ((struct buffer *)p))
4627 XSETVECTOR (obj, p);
4628 break;
4630 case MEM_TYPE_CONS:
4631 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4632 XSETCONS (obj, p);
4633 break;
4635 case MEM_TYPE_STRING:
4636 if (live_string_p (m, p)
4637 && !STRING_MARKED_P ((struct Lisp_String *) p))
4638 XSETSTRING (obj, p);
4639 break;
4641 case MEM_TYPE_MISC:
4642 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4643 XSETMISC (obj, p);
4644 break;
4646 case MEM_TYPE_SYMBOL:
4647 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4648 XSETSYMBOL (obj, p);
4649 break;
4651 case MEM_TYPE_FLOAT:
4652 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4653 XSETFLOAT (obj, p);
4654 break;
4656 case MEM_TYPE_VECTORLIKE:
4657 case MEM_TYPE_VECTOR_BLOCK:
4658 if (live_vector_p (m, p))
4660 Lisp_Object tem;
4661 XSETVECTOR (tem, p);
4662 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4663 obj = tem;
4665 break;
4667 default:
4668 emacs_abort ();
4671 if (!NILP (obj))
4672 mark_object (obj);
4677 /* Alignment of pointer values. Use alignof, as it sometimes returns
4678 a smaller alignment than GCC's __alignof__ and mark_memory might
4679 miss objects if __alignof__ were used. */
4680 #define GC_POINTER_ALIGNMENT alignof (void *)
4682 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4683 or END+OFFSET..START. */
4685 static void ATTRIBUTE_NO_SANITIZE_ADDRESS
4686 mark_memory (void *start, void *end)
4688 void **pp;
4689 int i;
4691 /* Make START the pointer to the start of the memory region,
4692 if it isn't already. */
4693 if (end < start)
4695 void *tem = start;
4696 start = end;
4697 end = tem;
4700 /* Mark Lisp data pointed to. This is necessary because, in some
4701 situations, the C compiler optimizes Lisp objects away, so that
4702 only a pointer to them remains. Example:
4704 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4707 Lisp_Object obj = build_string ("test");
4708 struct Lisp_String *s = XSTRING (obj);
4709 Fgarbage_collect ();
4710 fprintf (stderr, "test '%s'\n", s->data);
4711 return Qnil;
4714 Here, `obj' isn't really used, and the compiler optimizes it
4715 away. The only reference to the life string is through the
4716 pointer `s'. */
4718 for (pp = start; (void *) pp < end; pp++)
4719 for (i = 0; i < sizeof *pp; i += GC_POINTER_ALIGNMENT)
4721 void *p = *(void **) ((char *) pp + i);
4722 mark_maybe_pointer (p);
4723 mark_maybe_object (XIL ((intptr_t) p));
4727 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4729 static bool setjmp_tested_p;
4730 static int longjmps_done;
4732 #define SETJMP_WILL_LIKELY_WORK "\
4734 Emacs garbage collector has been changed to use conservative stack\n\
4735 marking. Emacs has determined that the method it uses to do the\n\
4736 marking will likely work on your system, but this isn't sure.\n\
4738 If you are a system-programmer, or can get the help of a local wizard\n\
4739 who is, please take a look at the function mark_stack in alloc.c, and\n\
4740 verify that the methods used are appropriate for your system.\n\
4742 Please mail the result to <emacs-devel@gnu.org>.\n\
4745 #define SETJMP_WILL_NOT_WORK "\
4747 Emacs garbage collector has been changed to use conservative stack\n\
4748 marking. Emacs has determined that the default method it uses to do the\n\
4749 marking will not work on your system. We will need a system-dependent\n\
4750 solution for your system.\n\
4752 Please take a look at the function mark_stack in alloc.c, and\n\
4753 try to find a way to make it work on your system.\n\
4755 Note that you may get false negatives, depending on the compiler.\n\
4756 In particular, you need to use -O with GCC for this test.\n\
4758 Please mail the result to <emacs-devel@gnu.org>.\n\
4762 /* Perform a quick check if it looks like setjmp saves registers in a
4763 jmp_buf. Print a message to stderr saying so. When this test
4764 succeeds, this is _not_ a proof that setjmp is sufficient for
4765 conservative stack marking. Only the sources or a disassembly
4766 can prove that. */
4768 static void
4769 test_setjmp (void)
4771 char buf[10];
4772 register int x;
4773 sys_jmp_buf jbuf;
4775 /* Arrange for X to be put in a register. */
4776 sprintf (buf, "1");
4777 x = strlen (buf);
4778 x = 2 * x - 1;
4780 sys_setjmp (jbuf);
4781 if (longjmps_done == 1)
4783 /* Came here after the longjmp at the end of the function.
4785 If x == 1, the longjmp has restored the register to its
4786 value before the setjmp, and we can hope that setjmp
4787 saves all such registers in the jmp_buf, although that
4788 isn't sure.
4790 For other values of X, either something really strange is
4791 taking place, or the setjmp just didn't save the register. */
4793 if (x == 1)
4794 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4795 else
4797 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4798 exit (1);
4802 ++longjmps_done;
4803 x = 2;
4804 if (longjmps_done == 1)
4805 sys_longjmp (jbuf, 1);
4808 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4811 /* Mark live Lisp objects on the C stack.
4813 There are several system-dependent problems to consider when
4814 porting this to new architectures:
4816 Processor Registers
4818 We have to mark Lisp objects in CPU registers that can hold local
4819 variables or are used to pass parameters.
4821 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4822 something that either saves relevant registers on the stack, or
4823 calls mark_maybe_object passing it each register's contents.
4825 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4826 implementation assumes that calling setjmp saves registers we need
4827 to see in a jmp_buf which itself lies on the stack. This doesn't
4828 have to be true! It must be verified for each system, possibly
4829 by taking a look at the source code of setjmp.
4831 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4832 can use it as a machine independent method to store all registers
4833 to the stack. In this case the macros described in the previous
4834 two paragraphs are not used.
4836 Stack Layout
4838 Architectures differ in the way their processor stack is organized.
4839 For example, the stack might look like this
4841 +----------------+
4842 | Lisp_Object | size = 4
4843 +----------------+
4844 | something else | size = 2
4845 +----------------+
4846 | Lisp_Object | size = 4
4847 +----------------+
4848 | ... |
4850 In such a case, not every Lisp_Object will be aligned equally. To
4851 find all Lisp_Object on the stack it won't be sufficient to walk
4852 the stack in steps of 4 bytes. Instead, two passes will be
4853 necessary, one starting at the start of the stack, and a second
4854 pass starting at the start of the stack + 2. Likewise, if the
4855 minimal alignment of Lisp_Objects on the stack is 1, four passes
4856 would be necessary, each one starting with one byte more offset
4857 from the stack start. */
4859 static void
4860 mark_stack (void *end)
4863 /* This assumes that the stack is a contiguous region in memory. If
4864 that's not the case, something has to be done here to iterate
4865 over the stack segments. */
4866 mark_memory (stack_base, end);
4868 /* Allow for marking a secondary stack, like the register stack on the
4869 ia64. */
4870 #ifdef GC_MARK_SECONDARY_STACK
4871 GC_MARK_SECONDARY_STACK ();
4872 #endif
4875 static bool
4876 c_symbol_p (struct Lisp_Symbol *sym)
4878 char *lispsym_ptr = (char *) lispsym;
4879 char *sym_ptr = (char *) sym;
4880 ptrdiff_t lispsym_offset = sym_ptr - lispsym_ptr;
4881 return 0 <= lispsym_offset && lispsym_offset < sizeof lispsym;
4884 /* Determine whether it is safe to access memory at address P. */
4885 static int
4886 valid_pointer_p (void *p)
4888 #ifdef WINDOWSNT
4889 return w32_valid_pointer_p (p, 16);
4890 #else
4892 if (ADDRESS_SANITIZER)
4893 return p ? -1 : 0;
4895 int fd[2];
4897 /* Obviously, we cannot just access it (we would SEGV trying), so we
4898 trick the o/s to tell us whether p is a valid pointer.
4899 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4900 not validate p in that case. */
4902 if (emacs_pipe (fd) == 0)
4904 bool valid = emacs_write (fd[1], p, 16) == 16;
4905 emacs_close (fd[1]);
4906 emacs_close (fd[0]);
4907 return valid;
4910 return -1;
4911 #endif
4914 /* Return 2 if OBJ is a killed or special buffer object, 1 if OBJ is a
4915 valid lisp object, 0 if OBJ is NOT a valid lisp object, or -1 if we
4916 cannot validate OBJ. This function can be quite slow, so its primary
4917 use is the manual debugging. The only exception is print_object, where
4918 we use it to check whether the memory referenced by the pointer of
4919 Lisp_Save_Value object contains valid objects. */
4922 valid_lisp_object_p (Lisp_Object obj)
4924 if (INTEGERP (obj))
4925 return 1;
4927 void *p = XPNTR (obj);
4928 if (PURE_P (p))
4929 return 1;
4931 if (SYMBOLP (obj) && c_symbol_p (p))
4932 return ((char *) p - (char *) lispsym) % sizeof lispsym[0] == 0;
4934 if (p == &buffer_defaults || p == &buffer_local_symbols)
4935 return 2;
4937 struct mem_node *m = mem_find (p);
4939 if (m == MEM_NIL)
4941 int valid = valid_pointer_p (p);
4942 if (valid <= 0)
4943 return valid;
4945 if (SUBRP (obj))
4946 return 1;
4948 return 0;
4951 switch (m->type)
4953 case MEM_TYPE_NON_LISP:
4954 case MEM_TYPE_SPARE:
4955 return 0;
4957 case MEM_TYPE_BUFFER:
4958 return live_buffer_p (m, p) ? 1 : 2;
4960 case MEM_TYPE_CONS:
4961 return live_cons_p (m, p);
4963 case MEM_TYPE_STRING:
4964 return live_string_p (m, p);
4966 case MEM_TYPE_MISC:
4967 return live_misc_p (m, p);
4969 case MEM_TYPE_SYMBOL:
4970 return live_symbol_p (m, p);
4972 case MEM_TYPE_FLOAT:
4973 return live_float_p (m, p);
4975 case MEM_TYPE_VECTORLIKE:
4976 case MEM_TYPE_VECTOR_BLOCK:
4977 return live_vector_p (m, p);
4979 default:
4980 break;
4983 return 0;
4986 /***********************************************************************
4987 Pure Storage Management
4988 ***********************************************************************/
4990 /* Allocate room for SIZE bytes from pure Lisp storage and return a
4991 pointer to it. TYPE is the Lisp type for which the memory is
4992 allocated. TYPE < 0 means it's not used for a Lisp object. */
4994 static void *
4995 pure_alloc (size_t size, int type)
4997 void *result;
4999 again:
5000 if (type >= 0)
5002 /* Allocate space for a Lisp object from the beginning of the free
5003 space with taking account of alignment. */
5004 result = ALIGN (purebeg + pure_bytes_used_lisp, GCALIGNMENT);
5005 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
5007 else
5009 /* Allocate space for a non-Lisp object from the end of the free
5010 space. */
5011 pure_bytes_used_non_lisp += size;
5012 result = purebeg + pure_size - pure_bytes_used_non_lisp;
5014 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
5016 if (pure_bytes_used <= pure_size)
5017 return result;
5019 /* Don't allocate a large amount here,
5020 because it might get mmap'd and then its address
5021 might not be usable. */
5022 purebeg = xmalloc (10000);
5023 pure_size = 10000;
5024 pure_bytes_used_before_overflow += pure_bytes_used - size;
5025 pure_bytes_used = 0;
5026 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
5027 goto again;
5031 /* Print a warning if PURESIZE is too small. */
5033 void
5034 check_pure_size (void)
5036 if (pure_bytes_used_before_overflow)
5037 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI"d"
5038 " bytes needed)"),
5039 pure_bytes_used + pure_bytes_used_before_overflow);
5043 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
5044 the non-Lisp data pool of the pure storage, and return its start
5045 address. Return NULL if not found. */
5047 static char *
5048 find_string_data_in_pure (const char *data, ptrdiff_t nbytes)
5050 int i;
5051 ptrdiff_t skip, bm_skip[256], last_char_skip, infinity, start, start_max;
5052 const unsigned char *p;
5053 char *non_lisp_beg;
5055 if (pure_bytes_used_non_lisp <= nbytes)
5056 return NULL;
5058 /* Set up the Boyer-Moore table. */
5059 skip = nbytes + 1;
5060 for (i = 0; i < 256; i++)
5061 bm_skip[i] = skip;
5063 p = (const unsigned char *) data;
5064 while (--skip > 0)
5065 bm_skip[*p++] = skip;
5067 last_char_skip = bm_skip['\0'];
5069 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
5070 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
5072 /* See the comments in the function `boyer_moore' (search.c) for the
5073 use of `infinity'. */
5074 infinity = pure_bytes_used_non_lisp + 1;
5075 bm_skip['\0'] = infinity;
5077 p = (const unsigned char *) non_lisp_beg + nbytes;
5078 start = 0;
5081 /* Check the last character (== '\0'). */
5084 start += bm_skip[*(p + start)];
5086 while (start <= start_max);
5088 if (start < infinity)
5089 /* Couldn't find the last character. */
5090 return NULL;
5092 /* No less than `infinity' means we could find the last
5093 character at `p[start - infinity]'. */
5094 start -= infinity;
5096 /* Check the remaining characters. */
5097 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
5098 /* Found. */
5099 return non_lisp_beg + start;
5101 start += last_char_skip;
5103 while (start <= start_max);
5105 return NULL;
5109 /* Return a string allocated in pure space. DATA is a buffer holding
5110 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
5111 means make the result string multibyte.
5113 Must get an error if pure storage is full, since if it cannot hold
5114 a large string it may be able to hold conses that point to that
5115 string; then the string is not protected from gc. */
5117 Lisp_Object
5118 make_pure_string (const char *data,
5119 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
5121 Lisp_Object string;
5122 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5123 s->data = (unsigned char *) find_string_data_in_pure (data, nbytes);
5124 if (s->data == NULL)
5126 s->data = pure_alloc (nbytes + 1, -1);
5127 memcpy (s->data, data, nbytes);
5128 s->data[nbytes] = '\0';
5130 s->size = nchars;
5131 s->size_byte = multibyte ? nbytes : -1;
5132 s->intervals = NULL;
5133 XSETSTRING (string, s);
5134 return string;
5137 /* Return a string allocated in pure space. Do not
5138 allocate the string data, just point to DATA. */
5140 Lisp_Object
5141 make_pure_c_string (const char *data, ptrdiff_t nchars)
5143 Lisp_Object string;
5144 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5145 s->size = nchars;
5146 s->size_byte = -1;
5147 s->data = (unsigned char *) data;
5148 s->intervals = NULL;
5149 XSETSTRING (string, s);
5150 return string;
5153 static Lisp_Object purecopy (Lisp_Object obj);
5155 /* Return a cons allocated from pure space. Give it pure copies
5156 of CAR as car and CDR as cdr. */
5158 Lisp_Object
5159 pure_cons (Lisp_Object car, Lisp_Object cdr)
5161 Lisp_Object new;
5162 struct Lisp_Cons *p = pure_alloc (sizeof *p, Lisp_Cons);
5163 XSETCONS (new, p);
5164 XSETCAR (new, purecopy (car));
5165 XSETCDR (new, purecopy (cdr));
5166 return new;
5170 /* Value is a float object with value NUM allocated from pure space. */
5172 static Lisp_Object
5173 make_pure_float (double num)
5175 Lisp_Object new;
5176 struct Lisp_Float *p = pure_alloc (sizeof *p, Lisp_Float);
5177 XSETFLOAT (new, p);
5178 XFLOAT_INIT (new, num);
5179 return new;
5183 /* Return a vector with room for LEN Lisp_Objects allocated from
5184 pure space. */
5186 static Lisp_Object
5187 make_pure_vector (ptrdiff_t len)
5189 Lisp_Object new;
5190 size_t size = header_size + len * word_size;
5191 struct Lisp_Vector *p = pure_alloc (size, Lisp_Vectorlike);
5192 XSETVECTOR (new, p);
5193 XVECTOR (new)->header.size = len;
5194 return new;
5197 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
5198 doc: /* Make a copy of object OBJ in pure storage.
5199 Recursively copies contents of vectors and cons cells.
5200 Does not copy symbols. Copies strings without text properties. */)
5201 (register Lisp_Object obj)
5203 if (NILP (Vpurify_flag))
5204 return obj;
5205 else if (MARKERP (obj) || OVERLAYP (obj)
5206 || HASH_TABLE_P (obj) || SYMBOLP (obj))
5207 /* Can't purify those. */
5208 return obj;
5209 else
5210 return purecopy (obj);
5213 static Lisp_Object
5214 purecopy (Lisp_Object obj)
5216 if (INTEGERP (obj)
5217 || (! SYMBOLP (obj) && PURE_P (XPNTR_OR_SYMBOL_OFFSET (obj)))
5218 || SUBRP (obj))
5219 return obj; /* Already pure. */
5221 if (STRINGP (obj) && XSTRING (obj)->intervals)
5222 message_with_string ("Dropping text-properties while making string `%s' pure",
5223 obj, true);
5225 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5227 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
5228 if (!NILP (tmp))
5229 return tmp;
5232 if (CONSP (obj))
5233 obj = pure_cons (XCAR (obj), XCDR (obj));
5234 else if (FLOATP (obj))
5235 obj = make_pure_float (XFLOAT_DATA (obj));
5236 else if (STRINGP (obj))
5237 obj = make_pure_string (SSDATA (obj), SCHARS (obj),
5238 SBYTES (obj),
5239 STRING_MULTIBYTE (obj));
5240 else if (COMPILEDP (obj) || VECTORP (obj) || HASH_TABLE_P (obj))
5242 struct Lisp_Vector *objp = XVECTOR (obj);
5243 ptrdiff_t nbytes = vector_nbytes (objp);
5244 struct Lisp_Vector *vec = pure_alloc (nbytes, Lisp_Vectorlike);
5245 register ptrdiff_t i;
5246 ptrdiff_t size = ASIZE (obj);
5247 if (size & PSEUDOVECTOR_FLAG)
5248 size &= PSEUDOVECTOR_SIZE_MASK;
5249 memcpy (vec, objp, nbytes);
5250 for (i = 0; i < size; i++)
5251 vec->contents[i] = purecopy (vec->contents[i]);
5252 XSETVECTOR (obj, vec);
5254 else if (SYMBOLP (obj))
5256 if (!XSYMBOL (obj)->pinned && !c_symbol_p (XSYMBOL (obj)))
5257 { /* We can't purify them, but they appear in many pure objects.
5258 Mark them as `pinned' so we know to mark them at every GC cycle. */
5259 XSYMBOL (obj)->pinned = true;
5260 symbol_block_pinned = symbol_block;
5262 /* Don't hash-cons it. */
5263 return obj;
5265 else
5267 Lisp_Object fmt = build_pure_c_string ("Don't know how to purify: %S");
5268 Fsignal (Qerror, list1 (CALLN (Fformat, fmt, obj)));
5271 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5272 Fputhash (obj, obj, Vpurify_flag);
5274 return obj;
5279 /***********************************************************************
5280 Protection from GC
5281 ***********************************************************************/
5283 /* Put an entry in staticvec, pointing at the variable with address
5284 VARADDRESS. */
5286 void
5287 staticpro (Lisp_Object *varaddress)
5289 if (staticidx >= NSTATICS)
5290 fatal ("NSTATICS too small; try increasing and recompiling Emacs.");
5291 staticvec[staticidx++] = varaddress;
5295 /***********************************************************************
5296 Protection from GC
5297 ***********************************************************************/
5299 /* Temporarily prevent garbage collection. */
5301 ptrdiff_t
5302 inhibit_garbage_collection (void)
5304 ptrdiff_t count = SPECPDL_INDEX ();
5306 specbind (Qgc_cons_threshold, make_number (MOST_POSITIVE_FIXNUM));
5307 return count;
5310 /* Used to avoid possible overflows when
5311 converting from C to Lisp integers. */
5313 static Lisp_Object
5314 bounded_number (EMACS_INT number)
5316 return make_number (min (MOST_POSITIVE_FIXNUM, number));
5319 /* Calculate total bytes of live objects. */
5321 static size_t
5322 total_bytes_of_live_objects (void)
5324 size_t tot = 0;
5325 tot += total_conses * sizeof (struct Lisp_Cons);
5326 tot += total_symbols * sizeof (struct Lisp_Symbol);
5327 tot += total_markers * sizeof (union Lisp_Misc);
5328 tot += total_string_bytes;
5329 tot += total_vector_slots * word_size;
5330 tot += total_floats * sizeof (struct Lisp_Float);
5331 tot += total_intervals * sizeof (struct interval);
5332 tot += total_strings * sizeof (struct Lisp_String);
5333 return tot;
5336 #ifdef HAVE_WINDOW_SYSTEM
5338 /* Remove unmarked font-spec and font-entity objects from ENTRY, which is
5339 (DRIVER-TYPE NUM-FRAMES FONT-CACHE-DATA ...), and return changed entry. */
5341 static Lisp_Object
5342 compact_font_cache_entry (Lisp_Object entry)
5344 Lisp_Object tail, *prev = &entry;
5346 for (tail = entry; CONSP (tail); tail = XCDR (tail))
5348 bool drop = 0;
5349 Lisp_Object obj = XCAR (tail);
5351 /* Consider OBJ if it is (font-spec . [font-entity font-entity ...]). */
5352 if (CONSP (obj) && GC_FONT_SPEC_P (XCAR (obj))
5353 && !VECTOR_MARKED_P (GC_XFONT_SPEC (XCAR (obj)))
5354 /* Don't use VECTORP here, as that calls ASIZE, which could
5355 hit assertion violation during GC. */
5356 && (VECTORLIKEP (XCDR (obj))
5357 && ! (gc_asize (XCDR (obj)) & PSEUDOVECTOR_FLAG)))
5359 ptrdiff_t i, size = gc_asize (XCDR (obj));
5360 Lisp_Object obj_cdr = XCDR (obj);
5362 /* If font-spec is not marked, most likely all font-entities
5363 are not marked too. But we must be sure that nothing is
5364 marked within OBJ before we really drop it. */
5365 for (i = 0; i < size; i++)
5367 Lisp_Object objlist;
5369 if (VECTOR_MARKED_P (GC_XFONT_ENTITY (AREF (obj_cdr, i))))
5370 break;
5372 objlist = AREF (AREF (obj_cdr, i), FONT_OBJLIST_INDEX);
5373 for (; CONSP (objlist); objlist = XCDR (objlist))
5375 Lisp_Object val = XCAR (objlist);
5376 struct font *font = GC_XFONT_OBJECT (val);
5378 if (!NILP (AREF (val, FONT_TYPE_INDEX))
5379 && VECTOR_MARKED_P(font))
5380 break;
5382 if (CONSP (objlist))
5384 /* Found a marked font, bail out. */
5385 break;
5389 if (i == size)
5391 /* No marked fonts were found, so this entire font
5392 entity can be dropped. */
5393 drop = 1;
5396 if (drop)
5397 *prev = XCDR (tail);
5398 else
5399 prev = xcdr_addr (tail);
5401 return entry;
5404 /* Compact font caches on all terminals and mark
5405 everything which is still here after compaction. */
5407 static void
5408 compact_font_caches (void)
5410 struct terminal *t;
5412 for (t = terminal_list; t; t = t->next_terminal)
5414 Lisp_Object cache = TERMINAL_FONT_CACHE (t);
5415 if (CONSP (cache))
5417 Lisp_Object entry;
5419 for (entry = XCDR (cache); CONSP (entry); entry = XCDR (entry))
5420 XSETCAR (entry, compact_font_cache_entry (XCAR (entry)));
5422 mark_object (cache);
5426 #else /* not HAVE_WINDOW_SYSTEM */
5428 #define compact_font_caches() (void)(0)
5430 #endif /* HAVE_WINDOW_SYSTEM */
5432 /* Remove (MARKER . DATA) entries with unmarked MARKER
5433 from buffer undo LIST and return changed list. */
5435 static Lisp_Object
5436 compact_undo_list (Lisp_Object list)
5438 Lisp_Object tail, *prev = &list;
5440 for (tail = list; CONSP (tail); tail = XCDR (tail))
5442 if (CONSP (XCAR (tail))
5443 && MARKERP (XCAR (XCAR (tail)))
5444 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5445 *prev = XCDR (tail);
5446 else
5447 prev = xcdr_addr (tail);
5449 return list;
5452 static void
5453 mark_pinned_symbols (void)
5455 struct symbol_block *sblk;
5456 int lim = (symbol_block_pinned == symbol_block
5457 ? symbol_block_index : SYMBOL_BLOCK_SIZE);
5459 for (sblk = symbol_block_pinned; sblk; sblk = sblk->next)
5461 union aligned_Lisp_Symbol *sym = sblk->symbols, *end = sym + lim;
5462 for (; sym < end; ++sym)
5463 if (sym->s.pinned)
5464 mark_object (make_lisp_symbol (&sym->s));
5466 lim = SYMBOL_BLOCK_SIZE;
5470 /* Subroutine of Fgarbage_collect that does most of the work. It is a
5471 separate function so that we could limit mark_stack in searching
5472 the stack frames below this function, thus avoiding the rare cases
5473 where mark_stack finds values that look like live Lisp objects on
5474 portions of stack that couldn't possibly contain such live objects.
5475 For more details of this, see the discussion at
5476 http://lists.gnu.org/archive/html/emacs-devel/2014-05/msg00270.html. */
5477 static Lisp_Object
5478 garbage_collect_1 (void *end)
5480 struct buffer *nextb;
5481 char stack_top_variable;
5482 ptrdiff_t i;
5483 bool message_p;
5484 ptrdiff_t count = SPECPDL_INDEX ();
5485 struct timespec start;
5486 Lisp_Object retval = Qnil;
5487 size_t tot_before = 0;
5489 if (abort_on_gc)
5490 emacs_abort ();
5492 /* Can't GC if pure storage overflowed because we can't determine
5493 if something is a pure object or not. */
5494 if (pure_bytes_used_before_overflow)
5495 return Qnil;
5497 /* Record this function, so it appears on the profiler's backtraces. */
5498 record_in_backtrace (Qautomatic_gc, 0, 0);
5500 check_cons_list ();
5502 /* Don't keep undo information around forever.
5503 Do this early on, so it is no problem if the user quits. */
5504 FOR_EACH_BUFFER (nextb)
5505 compact_buffer (nextb);
5507 if (profiler_memory_running)
5508 tot_before = total_bytes_of_live_objects ();
5510 start = current_timespec ();
5512 /* In case user calls debug_print during GC,
5513 don't let that cause a recursive GC. */
5514 consing_since_gc = 0;
5516 /* Save what's currently displayed in the echo area. */
5517 message_p = push_message ();
5518 record_unwind_protect_void (pop_message_unwind);
5520 /* Save a copy of the contents of the stack, for debugging. */
5521 #if MAX_SAVE_STACK > 0
5522 if (NILP (Vpurify_flag))
5524 char *stack;
5525 ptrdiff_t stack_size;
5526 if (&stack_top_variable < stack_bottom)
5528 stack = &stack_top_variable;
5529 stack_size = stack_bottom - &stack_top_variable;
5531 else
5533 stack = stack_bottom;
5534 stack_size = &stack_top_variable - stack_bottom;
5536 if (stack_size <= MAX_SAVE_STACK)
5538 if (stack_copy_size < stack_size)
5540 stack_copy = xrealloc (stack_copy, stack_size);
5541 stack_copy_size = stack_size;
5543 no_sanitize_memcpy (stack_copy, stack, stack_size);
5546 #endif /* MAX_SAVE_STACK > 0 */
5548 if (garbage_collection_messages)
5549 message1_nolog ("Garbage collecting...");
5551 block_input ();
5553 shrink_regexp_cache ();
5555 gc_in_progress = 1;
5557 /* Mark all the special slots that serve as the roots of accessibility. */
5559 mark_buffer (&buffer_defaults);
5560 mark_buffer (&buffer_local_symbols);
5562 for (i = 0; i < ARRAYELTS (lispsym); i++)
5563 mark_object (builtin_lisp_symbol (i));
5565 for (i = 0; i < staticidx; i++)
5566 mark_object (*staticvec[i]);
5568 mark_pinned_symbols ();
5569 mark_specpdl ();
5570 mark_terminals ();
5571 mark_kboards ();
5573 #ifdef USE_GTK
5574 xg_mark_data ();
5575 #endif
5577 mark_stack (end);
5580 struct handler *handler;
5581 for (handler = handlerlist; handler; handler = handler->next)
5583 mark_object (handler->tag_or_ch);
5584 mark_object (handler->val);
5587 #ifdef HAVE_WINDOW_SYSTEM
5588 mark_fringe_data ();
5589 #endif
5591 /* Everything is now marked, except for the data in font caches,
5592 undo lists, and finalizers. The first two are compacted by
5593 removing an items which aren't reachable otherwise. */
5595 compact_font_caches ();
5597 FOR_EACH_BUFFER (nextb)
5599 if (!EQ (BVAR (nextb, undo_list), Qt))
5600 bset_undo_list (nextb, compact_undo_list (BVAR (nextb, undo_list)));
5601 /* Now that we have stripped the elements that need not be
5602 in the undo_list any more, we can finally mark the list. */
5603 mark_object (BVAR (nextb, undo_list));
5606 /* Now pre-sweep finalizers. Here, we add any unmarked finalizers
5607 to doomed_finalizers so we can run their associated functions
5608 after GC. It's important to scan finalizers at this stage so
5609 that we can be sure that unmarked finalizers are really
5610 unreachable except for references from their associated functions
5611 and from other finalizers. */
5613 queue_doomed_finalizers (&doomed_finalizers, &finalizers);
5614 mark_finalizer_list (&doomed_finalizers);
5616 gc_sweep ();
5618 relocate_byte_stack ();
5620 /* Clear the mark bits that we set in certain root slots. */
5621 VECTOR_UNMARK (&buffer_defaults);
5622 VECTOR_UNMARK (&buffer_local_symbols);
5624 check_cons_list ();
5626 gc_in_progress = 0;
5628 unblock_input ();
5630 consing_since_gc = 0;
5631 if (gc_cons_threshold < GC_DEFAULT_THRESHOLD / 10)
5632 gc_cons_threshold = GC_DEFAULT_THRESHOLD / 10;
5634 gc_relative_threshold = 0;
5635 if (FLOATP (Vgc_cons_percentage))
5636 { /* Set gc_cons_combined_threshold. */
5637 double tot = total_bytes_of_live_objects ();
5639 tot *= XFLOAT_DATA (Vgc_cons_percentage);
5640 if (0 < tot)
5642 if (tot < TYPE_MAXIMUM (EMACS_INT))
5643 gc_relative_threshold = tot;
5644 else
5645 gc_relative_threshold = TYPE_MAXIMUM (EMACS_INT);
5649 if (garbage_collection_messages)
5651 if (message_p || minibuf_level > 0)
5652 restore_message ();
5653 else
5654 message1_nolog ("Garbage collecting...done");
5657 unbind_to (count, Qnil);
5659 Lisp_Object total[] = {
5660 list4 (Qconses, make_number (sizeof (struct Lisp_Cons)),
5661 bounded_number (total_conses),
5662 bounded_number (total_free_conses)),
5663 list4 (Qsymbols, make_number (sizeof (struct Lisp_Symbol)),
5664 bounded_number (total_symbols),
5665 bounded_number (total_free_symbols)),
5666 list4 (Qmiscs, make_number (sizeof (union Lisp_Misc)),
5667 bounded_number (total_markers),
5668 bounded_number (total_free_markers)),
5669 list4 (Qstrings, make_number (sizeof (struct Lisp_String)),
5670 bounded_number (total_strings),
5671 bounded_number (total_free_strings)),
5672 list3 (Qstring_bytes, make_number (1),
5673 bounded_number (total_string_bytes)),
5674 list3 (Qvectors,
5675 make_number (header_size + sizeof (Lisp_Object)),
5676 bounded_number (total_vectors)),
5677 list4 (Qvector_slots, make_number (word_size),
5678 bounded_number (total_vector_slots),
5679 bounded_number (total_free_vector_slots)),
5680 list4 (Qfloats, make_number (sizeof (struct Lisp_Float)),
5681 bounded_number (total_floats),
5682 bounded_number (total_free_floats)),
5683 list4 (Qintervals, make_number (sizeof (struct interval)),
5684 bounded_number (total_intervals),
5685 bounded_number (total_free_intervals)),
5686 list3 (Qbuffers, make_number (sizeof (struct buffer)),
5687 bounded_number (total_buffers)),
5689 #ifdef DOUG_LEA_MALLOC
5690 list4 (Qheap, make_number (1024),
5691 bounded_number ((mallinfo ().uordblks + 1023) >> 10),
5692 bounded_number ((mallinfo ().fordblks + 1023) >> 10)),
5693 #endif
5695 retval = CALLMANY (Flist, total);
5697 /* GC is complete: now we can run our finalizer callbacks. */
5698 run_finalizers (&doomed_finalizers);
5700 if (!NILP (Vpost_gc_hook))
5702 ptrdiff_t gc_count = inhibit_garbage_collection ();
5703 safe_run_hooks (Qpost_gc_hook);
5704 unbind_to (gc_count, Qnil);
5707 /* Accumulate statistics. */
5708 if (FLOATP (Vgc_elapsed))
5710 struct timespec since_start = timespec_sub (current_timespec (), start);
5711 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed)
5712 + timespectod (since_start));
5715 gcs_done++;
5717 /* Collect profiling data. */
5718 if (profiler_memory_running)
5720 size_t swept = 0;
5721 size_t tot_after = total_bytes_of_live_objects ();
5722 if (tot_before > tot_after)
5723 swept = tot_before - tot_after;
5724 malloc_probe (swept);
5727 return retval;
5730 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
5731 doc: /* Reclaim storage for Lisp objects no longer needed.
5732 Garbage collection happens automatically if you cons more than
5733 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5734 `garbage-collect' normally returns a list with info on amount of space in use,
5735 where each entry has the form (NAME SIZE USED FREE), where:
5736 - NAME is a symbol describing the kind of objects this entry represents,
5737 - SIZE is the number of bytes used by each one,
5738 - USED is the number of those objects that were found live in the heap,
5739 - FREE is the number of those objects that are not live but that Emacs
5740 keeps around for future allocations (maybe because it does not know how
5741 to return them to the OS).
5742 However, if there was overflow in pure space, `garbage-collect'
5743 returns nil, because real GC can't be done.
5744 See Info node `(elisp)Garbage Collection'. */)
5745 (void)
5747 void *end;
5749 #ifdef HAVE___BUILTIN_UNWIND_INIT
5750 /* Force callee-saved registers and register windows onto the stack.
5751 This is the preferred method if available, obviating the need for
5752 machine dependent methods. */
5753 __builtin_unwind_init ();
5754 end = &end;
5755 #else /* not HAVE___BUILTIN_UNWIND_INIT */
5756 #ifndef GC_SAVE_REGISTERS_ON_STACK
5757 /* jmp_buf may not be aligned enough on darwin-ppc64 */
5758 union aligned_jmpbuf {
5759 Lisp_Object o;
5760 sys_jmp_buf j;
5761 } j;
5762 volatile bool stack_grows_down_p = (char *) &j > (char *) stack_base;
5763 #endif
5764 /* This trick flushes the register windows so that all the state of
5765 the process is contained in the stack. */
5766 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
5767 needed on ia64 too. See mach_dep.c, where it also says inline
5768 assembler doesn't work with relevant proprietary compilers. */
5769 #ifdef __sparc__
5770 #if defined (__sparc64__) && defined (__FreeBSD__)
5771 /* FreeBSD does not have a ta 3 handler. */
5772 asm ("flushw");
5773 #else
5774 asm ("ta 3");
5775 #endif
5776 #endif
5778 /* Save registers that we need to see on the stack. We need to see
5779 registers used to hold register variables and registers used to
5780 pass parameters. */
5781 #ifdef GC_SAVE_REGISTERS_ON_STACK
5782 GC_SAVE_REGISTERS_ON_STACK (end);
5783 #else /* not GC_SAVE_REGISTERS_ON_STACK */
5785 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
5786 setjmp will definitely work, test it
5787 and print a message with the result
5788 of the test. */
5789 if (!setjmp_tested_p)
5791 setjmp_tested_p = 1;
5792 test_setjmp ();
5794 #endif /* GC_SETJMP_WORKS */
5796 sys_setjmp (j.j);
5797 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
5798 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
5799 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
5800 return garbage_collect_1 (end);
5803 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5804 only interesting objects referenced from glyphs are strings. */
5806 static void
5807 mark_glyph_matrix (struct glyph_matrix *matrix)
5809 struct glyph_row *row = matrix->rows;
5810 struct glyph_row *end = row + matrix->nrows;
5812 for (; row < end; ++row)
5813 if (row->enabled_p)
5815 int area;
5816 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
5818 struct glyph *glyph = row->glyphs[area];
5819 struct glyph *end_glyph = glyph + row->used[area];
5821 for (; glyph < end_glyph; ++glyph)
5822 if (STRINGP (glyph->object)
5823 && !STRING_MARKED_P (XSTRING (glyph->object)))
5824 mark_object (glyph->object);
5829 /* Mark reference to a Lisp_Object.
5830 If the object referred to has not been seen yet, recursively mark
5831 all the references contained in it. */
5833 #define LAST_MARKED_SIZE 500
5834 static Lisp_Object last_marked[LAST_MARKED_SIZE];
5835 static int last_marked_index;
5837 /* For debugging--call abort when we cdr down this many
5838 links of a list, in mark_object. In debugging,
5839 the call to abort will hit a breakpoint.
5840 Normally this is zero and the check never goes off. */
5841 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE;
5843 static void
5844 mark_vectorlike (struct Lisp_Vector *ptr)
5846 ptrdiff_t size = ptr->header.size;
5847 ptrdiff_t i;
5849 eassert (!VECTOR_MARKED_P (ptr));
5850 VECTOR_MARK (ptr); /* Else mark it. */
5851 if (size & PSEUDOVECTOR_FLAG)
5852 size &= PSEUDOVECTOR_SIZE_MASK;
5854 /* Note that this size is not the memory-footprint size, but only
5855 the number of Lisp_Object fields that we should trace.
5856 The distinction is used e.g. by Lisp_Process which places extra
5857 non-Lisp_Object fields at the end of the structure... */
5858 for (i = 0; i < size; i++) /* ...and then mark its elements. */
5859 mark_object (ptr->contents[i]);
5862 /* Like mark_vectorlike but optimized for char-tables (and
5863 sub-char-tables) assuming that the contents are mostly integers or
5864 symbols. */
5866 static void
5867 mark_char_table (struct Lisp_Vector *ptr, enum pvec_type pvectype)
5869 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5870 /* Consult the Lisp_Sub_Char_Table layout before changing this. */
5871 int i, idx = (pvectype == PVEC_SUB_CHAR_TABLE ? SUB_CHAR_TABLE_OFFSET : 0);
5873 eassert (!VECTOR_MARKED_P (ptr));
5874 VECTOR_MARK (ptr);
5875 for (i = idx; i < size; i++)
5877 Lisp_Object val = ptr->contents[i];
5879 if (INTEGERP (val) || (SYMBOLP (val) && XSYMBOL (val)->gcmarkbit))
5880 continue;
5881 if (SUB_CHAR_TABLE_P (val))
5883 if (! VECTOR_MARKED_P (XVECTOR (val)))
5884 mark_char_table (XVECTOR (val), PVEC_SUB_CHAR_TABLE);
5886 else
5887 mark_object (val);
5891 NO_INLINE /* To reduce stack depth in mark_object. */
5892 static Lisp_Object
5893 mark_compiled (struct Lisp_Vector *ptr)
5895 int i, size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5897 VECTOR_MARK (ptr);
5898 for (i = 0; i < size; i++)
5899 if (i != COMPILED_CONSTANTS)
5900 mark_object (ptr->contents[i]);
5901 return size > COMPILED_CONSTANTS ? ptr->contents[COMPILED_CONSTANTS] : Qnil;
5904 /* Mark the chain of overlays starting at PTR. */
5906 static void
5907 mark_overlay (struct Lisp_Overlay *ptr)
5909 for (; ptr && !ptr->gcmarkbit; ptr = ptr->next)
5911 ptr->gcmarkbit = 1;
5912 /* These two are always markers and can be marked fast. */
5913 XMARKER (ptr->start)->gcmarkbit = 1;
5914 XMARKER (ptr->end)->gcmarkbit = 1;
5915 mark_object (ptr->plist);
5919 /* Mark Lisp_Objects and special pointers in BUFFER. */
5921 static void
5922 mark_buffer (struct buffer *buffer)
5924 /* This is handled much like other pseudovectors... */
5925 mark_vectorlike ((struct Lisp_Vector *) buffer);
5927 /* ...but there are some buffer-specific things. */
5929 MARK_INTERVAL_TREE (buffer_intervals (buffer));
5931 /* For now, we just don't mark the undo_list. It's done later in
5932 a special way just before the sweep phase, and after stripping
5933 some of its elements that are not needed any more. */
5935 mark_overlay (buffer->overlays_before);
5936 mark_overlay (buffer->overlays_after);
5938 /* If this is an indirect buffer, mark its base buffer. */
5939 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5940 mark_buffer (buffer->base_buffer);
5943 /* Mark Lisp faces in the face cache C. */
5945 NO_INLINE /* To reduce stack depth in mark_object. */
5946 static void
5947 mark_face_cache (struct face_cache *c)
5949 if (c)
5951 int i, j;
5952 for (i = 0; i < c->used; ++i)
5954 struct face *face = FACE_FROM_ID (c->f, i);
5956 if (face)
5958 if (face->font && !VECTOR_MARKED_P (face->font))
5959 mark_vectorlike ((struct Lisp_Vector *) face->font);
5961 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
5962 mark_object (face->lface[j]);
5968 NO_INLINE /* To reduce stack depth in mark_object. */
5969 static void
5970 mark_localized_symbol (struct Lisp_Symbol *ptr)
5972 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
5973 Lisp_Object where = blv->where;
5974 /* If the value is set up for a killed buffer or deleted
5975 frame, restore its global binding. If the value is
5976 forwarded to a C variable, either it's not a Lisp_Object
5977 var, or it's staticpro'd already. */
5978 if ((BUFFERP (where) && !BUFFER_LIVE_P (XBUFFER (where)))
5979 || (FRAMEP (where) && !FRAME_LIVE_P (XFRAME (where))))
5980 swap_in_global_binding (ptr);
5981 mark_object (blv->where);
5982 mark_object (blv->valcell);
5983 mark_object (blv->defcell);
5986 NO_INLINE /* To reduce stack depth in mark_object. */
5987 static void
5988 mark_save_value (struct Lisp_Save_Value *ptr)
5990 /* If `save_type' is zero, `data[0].pointer' is the address
5991 of a memory area containing `data[1].integer' potential
5992 Lisp_Objects. */
5993 if (ptr->save_type == SAVE_TYPE_MEMORY)
5995 Lisp_Object *p = ptr->data[0].pointer;
5996 ptrdiff_t nelt;
5997 for (nelt = ptr->data[1].integer; nelt > 0; nelt--, p++)
5998 mark_maybe_object (*p);
6000 else
6002 /* Find Lisp_Objects in `data[N]' slots and mark them. */
6003 int i;
6004 for (i = 0; i < SAVE_VALUE_SLOTS; i++)
6005 if (save_type (ptr, i) == SAVE_OBJECT)
6006 mark_object (ptr->data[i].object);
6010 /* Remove killed buffers or items whose car is a killed buffer from
6011 LIST, and mark other items. Return changed LIST, which is marked. */
6013 static Lisp_Object
6014 mark_discard_killed_buffers (Lisp_Object list)
6016 Lisp_Object tail, *prev = &list;
6018 for (tail = list; CONSP (tail) && !CONS_MARKED_P (XCONS (tail));
6019 tail = XCDR (tail))
6021 Lisp_Object tem = XCAR (tail);
6022 if (CONSP (tem))
6023 tem = XCAR (tem);
6024 if (BUFFERP (tem) && !BUFFER_LIVE_P (XBUFFER (tem)))
6025 *prev = XCDR (tail);
6026 else
6028 CONS_MARK (XCONS (tail));
6029 mark_object (XCAR (tail));
6030 prev = xcdr_addr (tail);
6033 mark_object (tail);
6034 return list;
6037 /* Determine type of generic Lisp_Object and mark it accordingly.
6039 This function implements a straightforward depth-first marking
6040 algorithm and so the recursion depth may be very high (a few
6041 tens of thousands is not uncommon). To minimize stack usage,
6042 a few cold paths are moved out to NO_INLINE functions above.
6043 In general, inlining them doesn't help you to gain more speed. */
6045 void
6046 mark_object (Lisp_Object arg)
6048 register Lisp_Object obj;
6049 void *po;
6050 #ifdef GC_CHECK_MARKED_OBJECTS
6051 struct mem_node *m;
6052 #endif
6053 ptrdiff_t cdr_count = 0;
6055 obj = arg;
6056 loop:
6058 po = XPNTR (obj);
6059 if (PURE_P (po))
6060 return;
6062 last_marked[last_marked_index++] = obj;
6063 if (last_marked_index == LAST_MARKED_SIZE)
6064 last_marked_index = 0;
6066 /* Perform some sanity checks on the objects marked here. Abort if
6067 we encounter an object we know is bogus. This increases GC time
6068 by ~80%. */
6069 #ifdef GC_CHECK_MARKED_OBJECTS
6071 /* Check that the object pointed to by PO is known to be a Lisp
6072 structure allocated from the heap. */
6073 #define CHECK_ALLOCATED() \
6074 do { \
6075 m = mem_find (po); \
6076 if (m == MEM_NIL) \
6077 emacs_abort (); \
6078 } while (0)
6080 /* Check that the object pointed to by PO is live, using predicate
6081 function LIVEP. */
6082 #define CHECK_LIVE(LIVEP) \
6083 do { \
6084 if (!LIVEP (m, po)) \
6085 emacs_abort (); \
6086 } while (0)
6088 /* Check both of the above conditions, for non-symbols. */
6089 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
6090 do { \
6091 CHECK_ALLOCATED (); \
6092 CHECK_LIVE (LIVEP); \
6093 } while (0) \
6095 /* Check both of the above conditions, for symbols. */
6096 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() \
6097 do { \
6098 if (!c_symbol_p (ptr)) \
6100 CHECK_ALLOCATED (); \
6101 CHECK_LIVE (live_symbol_p); \
6103 } while (0) \
6105 #else /* not GC_CHECK_MARKED_OBJECTS */
6107 #define CHECK_LIVE(LIVEP) ((void) 0)
6108 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) ((void) 0)
6109 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() ((void) 0)
6111 #endif /* not GC_CHECK_MARKED_OBJECTS */
6113 switch (XTYPE (obj))
6115 case Lisp_String:
6117 register struct Lisp_String *ptr = XSTRING (obj);
6118 if (STRING_MARKED_P (ptr))
6119 break;
6120 CHECK_ALLOCATED_AND_LIVE (live_string_p);
6121 MARK_STRING (ptr);
6122 MARK_INTERVAL_TREE (ptr->intervals);
6123 #ifdef GC_CHECK_STRING_BYTES
6124 /* Check that the string size recorded in the string is the
6125 same as the one recorded in the sdata structure. */
6126 string_bytes (ptr);
6127 #endif /* GC_CHECK_STRING_BYTES */
6129 break;
6131 case Lisp_Vectorlike:
6133 register struct Lisp_Vector *ptr = XVECTOR (obj);
6134 register ptrdiff_t pvectype;
6136 if (VECTOR_MARKED_P (ptr))
6137 break;
6139 #ifdef GC_CHECK_MARKED_OBJECTS
6140 m = mem_find (po);
6141 if (m == MEM_NIL && !SUBRP (obj))
6142 emacs_abort ();
6143 #endif /* GC_CHECK_MARKED_OBJECTS */
6145 if (ptr->header.size & PSEUDOVECTOR_FLAG)
6146 pvectype = ((ptr->header.size & PVEC_TYPE_MASK)
6147 >> PSEUDOVECTOR_AREA_BITS);
6148 else
6149 pvectype = PVEC_NORMAL_VECTOR;
6151 if (pvectype != PVEC_SUBR && pvectype != PVEC_BUFFER)
6152 CHECK_LIVE (live_vector_p);
6154 switch (pvectype)
6156 case PVEC_BUFFER:
6157 #ifdef GC_CHECK_MARKED_OBJECTS
6159 struct buffer *b;
6160 FOR_EACH_BUFFER (b)
6161 if (b == po)
6162 break;
6163 if (b == NULL)
6164 emacs_abort ();
6166 #endif /* GC_CHECK_MARKED_OBJECTS */
6167 mark_buffer ((struct buffer *) ptr);
6168 break;
6170 case PVEC_COMPILED:
6171 /* Although we could treat this just like a vector, mark_compiled
6172 returns the COMPILED_CONSTANTS element, which is marked at the
6173 next iteration of goto-loop here. This is done to avoid a few
6174 recursive calls to mark_object. */
6175 obj = mark_compiled (ptr);
6176 if (!NILP (obj))
6177 goto loop;
6178 break;
6180 case PVEC_FRAME:
6182 struct frame *f = (struct frame *) ptr;
6184 mark_vectorlike (ptr);
6185 mark_face_cache (f->face_cache);
6186 #ifdef HAVE_WINDOW_SYSTEM
6187 if (FRAME_WINDOW_P (f) && FRAME_X_OUTPUT (f))
6189 struct font *font = FRAME_FONT (f);
6191 if (font && !VECTOR_MARKED_P (font))
6192 mark_vectorlike ((struct Lisp_Vector *) font);
6194 #endif
6196 break;
6198 case PVEC_WINDOW:
6200 struct window *w = (struct window *) ptr;
6202 mark_vectorlike (ptr);
6204 /* Mark glyph matrices, if any. Marking window
6205 matrices is sufficient because frame matrices
6206 use the same glyph memory. */
6207 if (w->current_matrix)
6209 mark_glyph_matrix (w->current_matrix);
6210 mark_glyph_matrix (w->desired_matrix);
6213 /* Filter out killed buffers from both buffer lists
6214 in attempt to help GC to reclaim killed buffers faster.
6215 We can do it elsewhere for live windows, but this is the
6216 best place to do it for dead windows. */
6217 wset_prev_buffers
6218 (w, mark_discard_killed_buffers (w->prev_buffers));
6219 wset_next_buffers
6220 (w, mark_discard_killed_buffers (w->next_buffers));
6222 break;
6224 case PVEC_HASH_TABLE:
6226 struct Lisp_Hash_Table *h = (struct Lisp_Hash_Table *) ptr;
6228 mark_vectorlike (ptr);
6229 mark_object (h->test.name);
6230 mark_object (h->test.user_hash_function);
6231 mark_object (h->test.user_cmp_function);
6232 /* If hash table is not weak, mark all keys and values.
6233 For weak tables, mark only the vector. */
6234 if (NILP (h->weak))
6235 mark_object (h->key_and_value);
6236 else
6237 VECTOR_MARK (XVECTOR (h->key_and_value));
6239 break;
6241 case PVEC_CHAR_TABLE:
6242 case PVEC_SUB_CHAR_TABLE:
6243 mark_char_table (ptr, (enum pvec_type) pvectype);
6244 break;
6246 case PVEC_BOOL_VECTOR:
6247 /* No Lisp_Objects to mark in a bool vector. */
6248 VECTOR_MARK (ptr);
6249 break;
6251 case PVEC_SUBR:
6252 break;
6254 case PVEC_FREE:
6255 emacs_abort ();
6257 default:
6258 mark_vectorlike (ptr);
6261 break;
6263 case Lisp_Symbol:
6265 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
6266 nextsym:
6267 if (ptr->gcmarkbit)
6268 break;
6269 CHECK_ALLOCATED_AND_LIVE_SYMBOL ();
6270 ptr->gcmarkbit = 1;
6271 /* Attempt to catch bogus objects. */
6272 eassert (valid_lisp_object_p (ptr->function));
6273 mark_object (ptr->function);
6274 mark_object (ptr->plist);
6275 switch (ptr->redirect)
6277 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
6278 case SYMBOL_VARALIAS:
6280 Lisp_Object tem;
6281 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
6282 mark_object (tem);
6283 break;
6285 case SYMBOL_LOCALIZED:
6286 mark_localized_symbol (ptr);
6287 break;
6288 case SYMBOL_FORWARDED:
6289 /* If the value is forwarded to a buffer or keyboard field,
6290 these are marked when we see the corresponding object.
6291 And if it's forwarded to a C variable, either it's not
6292 a Lisp_Object var, or it's staticpro'd already. */
6293 break;
6294 default: emacs_abort ();
6296 if (!PURE_P (XSTRING (ptr->name)))
6297 MARK_STRING (XSTRING (ptr->name));
6298 MARK_INTERVAL_TREE (string_intervals (ptr->name));
6299 /* Inner loop to mark next symbol in this bucket, if any. */
6300 po = ptr = ptr->next;
6301 if (ptr)
6302 goto nextsym;
6304 break;
6306 case Lisp_Misc:
6307 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
6309 if (XMISCANY (obj)->gcmarkbit)
6310 break;
6312 switch (XMISCTYPE (obj))
6314 case Lisp_Misc_Marker:
6315 /* DO NOT mark thru the marker's chain.
6316 The buffer's markers chain does not preserve markers from gc;
6317 instead, markers are removed from the chain when freed by gc. */
6318 XMISCANY (obj)->gcmarkbit = 1;
6319 break;
6321 case Lisp_Misc_Save_Value:
6322 XMISCANY (obj)->gcmarkbit = 1;
6323 mark_save_value (XSAVE_VALUE (obj));
6324 break;
6326 case Lisp_Misc_Overlay:
6327 mark_overlay (XOVERLAY (obj));
6328 break;
6330 case Lisp_Misc_Finalizer:
6331 XMISCANY (obj)->gcmarkbit = true;
6332 mark_object (XFINALIZER (obj)->function);
6333 break;
6335 #ifdef HAVE_MODULES
6336 case Lisp_Misc_User_Ptr:
6337 XMISCANY (obj)->gcmarkbit = true;
6338 break;
6339 #endif
6341 default:
6342 emacs_abort ();
6344 break;
6346 case Lisp_Cons:
6348 register struct Lisp_Cons *ptr = XCONS (obj);
6349 if (CONS_MARKED_P (ptr))
6350 break;
6351 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
6352 CONS_MARK (ptr);
6353 /* If the cdr is nil, avoid recursion for the car. */
6354 if (EQ (ptr->u.cdr, Qnil))
6356 obj = ptr->car;
6357 cdr_count = 0;
6358 goto loop;
6360 mark_object (ptr->car);
6361 obj = ptr->u.cdr;
6362 cdr_count++;
6363 if (cdr_count == mark_object_loop_halt)
6364 emacs_abort ();
6365 goto loop;
6368 case Lisp_Float:
6369 CHECK_ALLOCATED_AND_LIVE (live_float_p);
6370 FLOAT_MARK (XFLOAT (obj));
6371 break;
6373 case_Lisp_Int:
6374 break;
6376 default:
6377 emacs_abort ();
6380 #undef CHECK_LIVE
6381 #undef CHECK_ALLOCATED
6382 #undef CHECK_ALLOCATED_AND_LIVE
6384 /* Mark the Lisp pointers in the terminal objects.
6385 Called by Fgarbage_collect. */
6387 static void
6388 mark_terminals (void)
6390 struct terminal *t;
6391 for (t = terminal_list; t; t = t->next_terminal)
6393 eassert (t->name != NULL);
6394 #ifdef HAVE_WINDOW_SYSTEM
6395 /* If a terminal object is reachable from a stacpro'ed object,
6396 it might have been marked already. Make sure the image cache
6397 gets marked. */
6398 mark_image_cache (t->image_cache);
6399 #endif /* HAVE_WINDOW_SYSTEM */
6400 if (!VECTOR_MARKED_P (t))
6401 mark_vectorlike ((struct Lisp_Vector *)t);
6407 /* Value is non-zero if OBJ will survive the current GC because it's
6408 either marked or does not need to be marked to survive. */
6410 bool
6411 survives_gc_p (Lisp_Object obj)
6413 bool survives_p;
6415 switch (XTYPE (obj))
6417 case_Lisp_Int:
6418 survives_p = 1;
6419 break;
6421 case Lisp_Symbol:
6422 survives_p = XSYMBOL (obj)->gcmarkbit;
6423 break;
6425 case Lisp_Misc:
6426 survives_p = XMISCANY (obj)->gcmarkbit;
6427 break;
6429 case Lisp_String:
6430 survives_p = STRING_MARKED_P (XSTRING (obj));
6431 break;
6433 case Lisp_Vectorlike:
6434 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
6435 break;
6437 case Lisp_Cons:
6438 survives_p = CONS_MARKED_P (XCONS (obj));
6439 break;
6441 case Lisp_Float:
6442 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
6443 break;
6445 default:
6446 emacs_abort ();
6449 return survives_p || PURE_P (XPNTR (obj));
6455 NO_INLINE /* For better stack traces */
6456 static void
6457 sweep_conses (void)
6459 struct cons_block *cblk;
6460 struct cons_block **cprev = &cons_block;
6461 int lim = cons_block_index;
6462 EMACS_INT num_free = 0, num_used = 0;
6464 cons_free_list = 0;
6466 for (cblk = cons_block; cblk; cblk = *cprev)
6468 int i = 0;
6469 int this_free = 0;
6470 int ilim = (lim + BITS_PER_BITS_WORD - 1) / BITS_PER_BITS_WORD;
6472 /* Scan the mark bits an int at a time. */
6473 for (i = 0; i < ilim; i++)
6475 if (cblk->gcmarkbits[i] == BITS_WORD_MAX)
6477 /* Fast path - all cons cells for this int are marked. */
6478 cblk->gcmarkbits[i] = 0;
6479 num_used += BITS_PER_BITS_WORD;
6481 else
6483 /* Some cons cells for this int are not marked.
6484 Find which ones, and free them. */
6485 int start, pos, stop;
6487 start = i * BITS_PER_BITS_WORD;
6488 stop = lim - start;
6489 if (stop > BITS_PER_BITS_WORD)
6490 stop = BITS_PER_BITS_WORD;
6491 stop += start;
6493 for (pos = start; pos < stop; pos++)
6495 if (!CONS_MARKED_P (&cblk->conses[pos]))
6497 this_free++;
6498 cblk->conses[pos].u.chain = cons_free_list;
6499 cons_free_list = &cblk->conses[pos];
6500 cons_free_list->car = Vdead;
6502 else
6504 num_used++;
6505 CONS_UNMARK (&cblk->conses[pos]);
6511 lim = CONS_BLOCK_SIZE;
6512 /* If this block contains only free conses and we have already
6513 seen more than two blocks worth of free conses then deallocate
6514 this block. */
6515 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
6517 *cprev = cblk->next;
6518 /* Unhook from the free list. */
6519 cons_free_list = cblk->conses[0].u.chain;
6520 lisp_align_free (cblk);
6522 else
6524 num_free += this_free;
6525 cprev = &cblk->next;
6528 total_conses = num_used;
6529 total_free_conses = num_free;
6532 NO_INLINE /* For better stack traces */
6533 static void
6534 sweep_floats (void)
6536 register struct float_block *fblk;
6537 struct float_block **fprev = &float_block;
6538 register int lim = float_block_index;
6539 EMACS_INT num_free = 0, num_used = 0;
6541 float_free_list = 0;
6543 for (fblk = float_block; fblk; fblk = *fprev)
6545 register int i;
6546 int this_free = 0;
6547 for (i = 0; i < lim; i++)
6548 if (!FLOAT_MARKED_P (&fblk->floats[i]))
6550 this_free++;
6551 fblk->floats[i].u.chain = float_free_list;
6552 float_free_list = &fblk->floats[i];
6554 else
6556 num_used++;
6557 FLOAT_UNMARK (&fblk->floats[i]);
6559 lim = FLOAT_BLOCK_SIZE;
6560 /* If this block contains only free floats and we have already
6561 seen more than two blocks worth of free floats then deallocate
6562 this block. */
6563 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6565 *fprev = fblk->next;
6566 /* Unhook from the free list. */
6567 float_free_list = fblk->floats[0].u.chain;
6568 lisp_align_free (fblk);
6570 else
6572 num_free += this_free;
6573 fprev = &fblk->next;
6576 total_floats = num_used;
6577 total_free_floats = num_free;
6580 NO_INLINE /* For better stack traces */
6581 static void
6582 sweep_intervals (void)
6584 register struct interval_block *iblk;
6585 struct interval_block **iprev = &interval_block;
6586 register int lim = interval_block_index;
6587 EMACS_INT num_free = 0, num_used = 0;
6589 interval_free_list = 0;
6591 for (iblk = interval_block; iblk; iblk = *iprev)
6593 register int i;
6594 int this_free = 0;
6596 for (i = 0; i < lim; i++)
6598 if (!iblk->intervals[i].gcmarkbit)
6600 set_interval_parent (&iblk->intervals[i], interval_free_list);
6601 interval_free_list = &iblk->intervals[i];
6602 this_free++;
6604 else
6606 num_used++;
6607 iblk->intervals[i].gcmarkbit = 0;
6610 lim = INTERVAL_BLOCK_SIZE;
6611 /* If this block contains only free intervals and we have already
6612 seen more than two blocks worth of free intervals then
6613 deallocate this block. */
6614 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6616 *iprev = iblk->next;
6617 /* Unhook from the free list. */
6618 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
6619 lisp_free (iblk);
6621 else
6623 num_free += this_free;
6624 iprev = &iblk->next;
6627 total_intervals = num_used;
6628 total_free_intervals = num_free;
6631 NO_INLINE /* For better stack traces */
6632 static void
6633 sweep_symbols (void)
6635 struct symbol_block *sblk;
6636 struct symbol_block **sprev = &symbol_block;
6637 int lim = symbol_block_index;
6638 EMACS_INT num_free = 0, num_used = ARRAYELTS (lispsym);
6640 symbol_free_list = NULL;
6642 for (int i = 0; i < ARRAYELTS (lispsym); i++)
6643 lispsym[i].gcmarkbit = 0;
6645 for (sblk = symbol_block; sblk; sblk = *sprev)
6647 int this_free = 0;
6648 union aligned_Lisp_Symbol *sym = sblk->symbols;
6649 union aligned_Lisp_Symbol *end = sym + lim;
6651 for (; sym < end; ++sym)
6653 if (!sym->s.gcmarkbit)
6655 if (sym->s.redirect == SYMBOL_LOCALIZED)
6656 xfree (SYMBOL_BLV (&sym->s));
6657 sym->s.next = symbol_free_list;
6658 symbol_free_list = &sym->s;
6659 symbol_free_list->function = Vdead;
6660 ++this_free;
6662 else
6664 ++num_used;
6665 sym->s.gcmarkbit = 0;
6666 /* Attempt to catch bogus objects. */
6667 eassert (valid_lisp_object_p (sym->s.function));
6671 lim = SYMBOL_BLOCK_SIZE;
6672 /* If this block contains only free symbols and we have already
6673 seen more than two blocks worth of free symbols then deallocate
6674 this block. */
6675 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6677 *sprev = sblk->next;
6678 /* Unhook from the free list. */
6679 symbol_free_list = sblk->symbols[0].s.next;
6680 lisp_free (sblk);
6682 else
6684 num_free += this_free;
6685 sprev = &sblk->next;
6688 total_symbols = num_used;
6689 total_free_symbols = num_free;
6692 NO_INLINE /* For better stack traces. */
6693 static void
6694 sweep_misc (void)
6696 register struct marker_block *mblk;
6697 struct marker_block **mprev = &marker_block;
6698 register int lim = marker_block_index;
6699 EMACS_INT num_free = 0, num_used = 0;
6701 /* Put all unmarked misc's on free list. For a marker, first
6702 unchain it from the buffer it points into. */
6704 marker_free_list = 0;
6706 for (mblk = marker_block; mblk; mblk = *mprev)
6708 register int i;
6709 int this_free = 0;
6711 for (i = 0; i < lim; i++)
6713 if (!mblk->markers[i].m.u_any.gcmarkbit)
6715 if (mblk->markers[i].m.u_any.type == Lisp_Misc_Marker)
6716 unchain_marker (&mblk->markers[i].m.u_marker);
6717 else if (mblk->markers[i].m.u_any.type == Lisp_Misc_Finalizer)
6718 unchain_finalizer (&mblk->markers[i].m.u_finalizer);
6719 #ifdef HAVE_MODULES
6720 else if (mblk->markers[i].m.u_any.type == Lisp_Misc_User_Ptr)
6722 struct Lisp_User_Ptr *uptr = &mblk->markers[i].m.u_user_ptr;
6723 uptr->finalizer (uptr->p);
6725 #endif
6726 /* Set the type of the freed object to Lisp_Misc_Free.
6727 We could leave the type alone, since nobody checks it,
6728 but this might catch bugs faster. */
6729 mblk->markers[i].m.u_marker.type = Lisp_Misc_Free;
6730 mblk->markers[i].m.u_free.chain = marker_free_list;
6731 marker_free_list = &mblk->markers[i].m;
6732 this_free++;
6734 else
6736 num_used++;
6737 mblk->markers[i].m.u_any.gcmarkbit = 0;
6740 lim = MARKER_BLOCK_SIZE;
6741 /* If this block contains only free markers and we have already
6742 seen more than two blocks worth of free markers then deallocate
6743 this block. */
6744 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6746 *mprev = mblk->next;
6747 /* Unhook from the free list. */
6748 marker_free_list = mblk->markers[0].m.u_free.chain;
6749 lisp_free (mblk);
6751 else
6753 num_free += this_free;
6754 mprev = &mblk->next;
6758 total_markers = num_used;
6759 total_free_markers = num_free;
6762 NO_INLINE /* For better stack traces */
6763 static void
6764 sweep_buffers (void)
6766 register struct buffer *buffer, **bprev = &all_buffers;
6768 total_buffers = 0;
6769 for (buffer = all_buffers; buffer; buffer = *bprev)
6770 if (!VECTOR_MARKED_P (buffer))
6772 *bprev = buffer->next;
6773 lisp_free (buffer);
6775 else
6777 VECTOR_UNMARK (buffer);
6778 /* Do not use buffer_(set|get)_intervals here. */
6779 buffer->text->intervals = balance_intervals (buffer->text->intervals);
6780 total_buffers++;
6781 bprev = &buffer->next;
6785 /* Sweep: find all structures not marked, and free them. */
6786 static void
6787 gc_sweep (void)
6789 /* Remove or mark entries in weak hash tables.
6790 This must be done before any object is unmarked. */
6791 sweep_weak_hash_tables ();
6793 sweep_strings ();
6794 check_string_bytes (!noninteractive);
6795 sweep_conses ();
6796 sweep_floats ();
6797 sweep_intervals ();
6798 sweep_symbols ();
6799 sweep_misc ();
6800 sweep_buffers ();
6801 sweep_vectors ();
6802 check_string_bytes (!noninteractive);
6805 DEFUN ("memory-info", Fmemory_info, Smemory_info, 0, 0, 0,
6806 doc: /* Return a list of (TOTAL-RAM FREE-RAM TOTAL-SWAP FREE-SWAP).
6807 All values are in Kbytes. If there is no swap space,
6808 last two values are zero. If the system is not supported
6809 or memory information can't be obtained, return nil. */)
6810 (void)
6812 #if defined HAVE_LINUX_SYSINFO
6813 struct sysinfo si;
6814 uintmax_t units;
6816 if (sysinfo (&si))
6817 return Qnil;
6818 #ifdef LINUX_SYSINFO_UNIT
6819 units = si.mem_unit;
6820 #else
6821 units = 1;
6822 #endif
6823 return list4i ((uintmax_t) si.totalram * units / 1024,
6824 (uintmax_t) si.freeram * units / 1024,
6825 (uintmax_t) si.totalswap * units / 1024,
6826 (uintmax_t) si.freeswap * units / 1024);
6827 #elif defined WINDOWSNT
6828 unsigned long long totalram, freeram, totalswap, freeswap;
6830 if (w32_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
6831 return list4i ((uintmax_t) totalram / 1024,
6832 (uintmax_t) freeram / 1024,
6833 (uintmax_t) totalswap / 1024,
6834 (uintmax_t) freeswap / 1024);
6835 else
6836 return Qnil;
6837 #elif defined MSDOS
6838 unsigned long totalram, freeram, totalswap, freeswap;
6840 if (dos_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
6841 return list4i ((uintmax_t) totalram / 1024,
6842 (uintmax_t) freeram / 1024,
6843 (uintmax_t) totalswap / 1024,
6844 (uintmax_t) freeswap / 1024);
6845 else
6846 return Qnil;
6847 #else /* not HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
6848 /* FIXME: add more systems. */
6849 return Qnil;
6850 #endif /* HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
6853 /* Debugging aids. */
6855 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
6856 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6857 This may be helpful in debugging Emacs's memory usage.
6858 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6859 (void)
6861 Lisp_Object end;
6863 #ifdef HAVE_NS
6864 /* Avoid warning. sbrk has no relation to memory allocated anyway. */
6865 XSETINT (end, 0);
6866 #else
6867 XSETINT (end, (intptr_t) (char *) sbrk (0) / 1024);
6868 #endif
6870 return end;
6873 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
6874 doc: /* Return a list of counters that measure how much consing there has been.
6875 Each of these counters increments for a certain kind of object.
6876 The counters wrap around from the largest positive integer to zero.
6877 Garbage collection does not decrease them.
6878 The elements of the value are as follows:
6879 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6880 All are in units of 1 = one object consed
6881 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6882 objects consed.
6883 MISCS include overlays, markers, and some internal types.
6884 Frames, windows, buffers, and subprocesses count as vectors
6885 (but the contents of a buffer's text do not count here). */)
6886 (void)
6888 return listn (CONSTYPE_HEAP, 8,
6889 bounded_number (cons_cells_consed),
6890 bounded_number (floats_consed),
6891 bounded_number (vector_cells_consed),
6892 bounded_number (symbols_consed),
6893 bounded_number (string_chars_consed),
6894 bounded_number (misc_objects_consed),
6895 bounded_number (intervals_consed),
6896 bounded_number (strings_consed));
6899 static bool
6900 symbol_uses_obj (Lisp_Object symbol, Lisp_Object obj)
6902 struct Lisp_Symbol *sym = XSYMBOL (symbol);
6903 Lisp_Object val = find_symbol_value (symbol);
6904 return (EQ (val, obj)
6905 || EQ (sym->function, obj)
6906 || (!NILP (sym->function)
6907 && COMPILEDP (sym->function)
6908 && EQ (AREF (sym->function, COMPILED_BYTECODE), obj))
6909 || (!NILP (val)
6910 && COMPILEDP (val)
6911 && EQ (AREF (val, COMPILED_BYTECODE), obj)));
6914 /* Find at most FIND_MAX symbols which have OBJ as their value or
6915 function. This is used in gdbinit's `xwhichsymbols' command. */
6917 Lisp_Object
6918 which_symbols (Lisp_Object obj, EMACS_INT find_max)
6920 struct symbol_block *sblk;
6921 ptrdiff_t gc_count = inhibit_garbage_collection ();
6922 Lisp_Object found = Qnil;
6924 if (! DEADP (obj))
6926 for (int i = 0; i < ARRAYELTS (lispsym); i++)
6928 Lisp_Object sym = builtin_lisp_symbol (i);
6929 if (symbol_uses_obj (sym, obj))
6931 found = Fcons (sym, found);
6932 if (--find_max == 0)
6933 goto out;
6937 for (sblk = symbol_block; sblk; sblk = sblk->next)
6939 union aligned_Lisp_Symbol *aligned_sym = sblk->symbols;
6940 int bn;
6942 for (bn = 0; bn < SYMBOL_BLOCK_SIZE; bn++, aligned_sym++)
6944 if (sblk == symbol_block && bn >= symbol_block_index)
6945 break;
6947 Lisp_Object sym = make_lisp_symbol (&aligned_sym->s);
6948 if (symbol_uses_obj (sym, obj))
6950 found = Fcons (sym, found);
6951 if (--find_max == 0)
6952 goto out;
6958 out:
6959 unbind_to (gc_count, Qnil);
6960 return found;
6963 #ifdef SUSPICIOUS_OBJECT_CHECKING
6965 static void *
6966 find_suspicious_object_in_range (void *begin, void *end)
6968 char *begin_a = begin;
6969 char *end_a = end;
6970 int i;
6972 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
6974 char *suspicious_object = suspicious_objects[i];
6975 if (begin_a <= suspicious_object && suspicious_object < end_a)
6976 return suspicious_object;
6979 return NULL;
6982 static void
6983 note_suspicious_free (void* ptr)
6985 struct suspicious_free_record* rec;
6987 rec = &suspicious_free_history[suspicious_free_history_index++];
6988 if (suspicious_free_history_index ==
6989 ARRAYELTS (suspicious_free_history))
6991 suspicious_free_history_index = 0;
6994 memset (rec, 0, sizeof (*rec));
6995 rec->suspicious_object = ptr;
6996 backtrace (&rec->backtrace[0], ARRAYELTS (rec->backtrace));
6999 static void
7000 detect_suspicious_free (void* ptr)
7002 int i;
7004 eassert (ptr != NULL);
7006 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
7007 if (suspicious_objects[i] == ptr)
7009 note_suspicious_free (ptr);
7010 suspicious_objects[i] = NULL;
7014 #endif /* SUSPICIOUS_OBJECT_CHECKING */
7016 DEFUN ("suspicious-object", Fsuspicious_object, Ssuspicious_object, 1, 1, 0,
7017 doc: /* Return OBJ, maybe marking it for extra scrutiny.
7018 If Emacs is compiled with suspicious object checking, capture
7019 a stack trace when OBJ is freed in order to help track down
7020 garbage collection bugs. Otherwise, do nothing and return OBJ. */)
7021 (Lisp_Object obj)
7023 #ifdef SUSPICIOUS_OBJECT_CHECKING
7024 /* Right now, we care only about vectors. */
7025 if (VECTORLIKEP (obj))
7027 suspicious_objects[suspicious_object_index++] = XVECTOR (obj);
7028 if (suspicious_object_index == ARRAYELTS (suspicious_objects))
7029 suspicious_object_index = 0;
7031 #endif
7032 return obj;
7035 #ifdef ENABLE_CHECKING
7037 bool suppress_checking;
7039 void
7040 die (const char *msg, const char *file, int line)
7042 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: assertion failed: %s\r\n",
7043 file, line, msg);
7044 terminate_due_to_signal (SIGABRT, INT_MAX);
7047 #endif /* ENABLE_CHECKING */
7049 #if defined (ENABLE_CHECKING) && USE_STACK_LISP_OBJECTS
7051 /* Debugging check whether STR is ASCII-only. */
7053 const char *
7054 verify_ascii (const char *str)
7056 const unsigned char *ptr = (unsigned char *) str, *end = ptr + strlen (str);
7057 while (ptr < end)
7059 int c = STRING_CHAR_ADVANCE (ptr);
7060 if (!ASCII_CHAR_P (c))
7061 emacs_abort ();
7063 return str;
7066 /* Stress alloca with inconveniently sized requests and check
7067 whether all allocated areas may be used for Lisp_Object. */
7069 NO_INLINE static void
7070 verify_alloca (void)
7072 int i;
7073 enum { ALLOCA_CHECK_MAX = 256 };
7074 /* Start from size of the smallest Lisp object. */
7075 for (i = sizeof (struct Lisp_Cons); i <= ALLOCA_CHECK_MAX; i++)
7077 void *ptr = alloca (i);
7078 make_lisp_ptr (ptr, Lisp_Cons);
7082 #else /* not ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7084 #define verify_alloca() ((void) 0)
7086 #endif /* ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7088 /* Initialization. */
7090 void
7091 init_alloc_once (void)
7093 /* Even though Qt's contents are not set up, its address is known. */
7094 Vpurify_flag = Qt;
7096 purebeg = PUREBEG;
7097 pure_size = PURESIZE;
7099 verify_alloca ();
7100 init_finalizer_list (&finalizers);
7101 init_finalizer_list (&doomed_finalizers);
7103 mem_init ();
7104 Vdead = make_pure_string ("DEAD", 4, 4, 0);
7106 #ifdef DOUG_LEA_MALLOC
7107 mallopt (M_TRIM_THRESHOLD, 128 * 1024); /* Trim threshold. */
7108 mallopt (M_MMAP_THRESHOLD, 64 * 1024); /* Mmap threshold. */
7109 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* Max. number of mmap'ed areas. */
7110 #endif
7111 init_strings ();
7112 init_vectors ();
7114 refill_memory_reserve ();
7115 gc_cons_threshold = GC_DEFAULT_THRESHOLD;
7118 void
7119 init_alloc (void)
7121 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
7122 setjmp_tested_p = longjmps_done = 0;
7123 #endif
7124 Vgc_elapsed = make_float (0.0);
7125 gcs_done = 0;
7127 #if USE_VALGRIND
7128 valgrind_p = RUNNING_ON_VALGRIND != 0;
7129 #endif
7132 void
7133 syms_of_alloc (void)
7135 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
7136 doc: /* Number of bytes of consing between garbage collections.
7137 Garbage collection can happen automatically once this many bytes have been
7138 allocated since the last garbage collection. All data types count.
7140 Garbage collection happens automatically only when `eval' is called.
7142 By binding this temporarily to a large number, you can effectively
7143 prevent garbage collection during a part of the program.
7144 See also `gc-cons-percentage'. */);
7146 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
7147 doc: /* Portion of the heap used for allocation.
7148 Garbage collection can happen automatically once this portion of the heap
7149 has been allocated since the last garbage collection.
7150 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
7151 Vgc_cons_percentage = make_float (0.1);
7153 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
7154 doc: /* Number of bytes of shareable Lisp data allocated so far. */);
7156 DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
7157 doc: /* Number of cons cells that have been consed so far. */);
7159 DEFVAR_INT ("floats-consed", floats_consed,
7160 doc: /* Number of floats that have been consed so far. */);
7162 DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
7163 doc: /* Number of vector cells that have been consed so far. */);
7165 DEFVAR_INT ("symbols-consed", symbols_consed,
7166 doc: /* Number of symbols that have been consed so far. */);
7167 symbols_consed += ARRAYELTS (lispsym);
7169 DEFVAR_INT ("string-chars-consed", string_chars_consed,
7170 doc: /* Number of string characters that have been consed so far. */);
7172 DEFVAR_INT ("misc-objects-consed", misc_objects_consed,
7173 doc: /* Number of miscellaneous objects that have been consed so far.
7174 These include markers and overlays, plus certain objects not visible
7175 to users. */);
7177 DEFVAR_INT ("intervals-consed", intervals_consed,
7178 doc: /* Number of intervals that have been consed so far. */);
7180 DEFVAR_INT ("strings-consed", strings_consed,
7181 doc: /* Number of strings that have been consed so far. */);
7183 DEFVAR_LISP ("purify-flag", Vpurify_flag,
7184 doc: /* Non-nil means loading Lisp code in order to dump an executable.
7185 This means that certain objects should be allocated in shared (pure) space.
7186 It can also be set to a hash-table, in which case this table is used to
7187 do hash-consing of the objects allocated to pure space. */);
7189 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
7190 doc: /* Non-nil means display messages at start and end of garbage collection. */);
7191 garbage_collection_messages = 0;
7193 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
7194 doc: /* Hook run after garbage collection has finished. */);
7195 Vpost_gc_hook = Qnil;
7196 DEFSYM (Qpost_gc_hook, "post-gc-hook");
7198 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
7199 doc: /* Precomputed `signal' argument for memory-full error. */);
7200 /* We build this in advance because if we wait until we need it, we might
7201 not be able to allocate the memory to hold it. */
7202 Vmemory_signal_data
7203 = listn (CONSTYPE_PURE, 2, Qerror,
7204 build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
7206 DEFVAR_LISP ("memory-full", Vmemory_full,
7207 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
7208 Vmemory_full = Qnil;
7210 DEFSYM (Qconses, "conses");
7211 DEFSYM (Qsymbols, "symbols");
7212 DEFSYM (Qmiscs, "miscs");
7213 DEFSYM (Qstrings, "strings");
7214 DEFSYM (Qvectors, "vectors");
7215 DEFSYM (Qfloats, "floats");
7216 DEFSYM (Qintervals, "intervals");
7217 DEFSYM (Qbuffers, "buffers");
7218 DEFSYM (Qstring_bytes, "string-bytes");
7219 DEFSYM (Qvector_slots, "vector-slots");
7220 DEFSYM (Qheap, "heap");
7221 DEFSYM (Qautomatic_gc, "Automatic GC");
7223 DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
7224 DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
7226 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
7227 doc: /* Accumulated time elapsed in garbage collections.
7228 The time is in seconds as a floating point value. */);
7229 DEFVAR_INT ("gcs-done", gcs_done,
7230 doc: /* Accumulated number of garbage collections done. */);
7232 defsubr (&Scons);
7233 defsubr (&Slist);
7234 defsubr (&Svector);
7235 defsubr (&Sbool_vector);
7236 defsubr (&Smake_byte_code);
7237 defsubr (&Smake_list);
7238 defsubr (&Smake_vector);
7239 defsubr (&Smake_string);
7240 defsubr (&Smake_bool_vector);
7241 defsubr (&Smake_symbol);
7242 defsubr (&Smake_marker);
7243 defsubr (&Smake_finalizer);
7244 defsubr (&Spurecopy);
7245 defsubr (&Sgarbage_collect);
7246 defsubr (&Smemory_limit);
7247 defsubr (&Smemory_info);
7248 defsubr (&Smemory_use_counts);
7249 defsubr (&Ssuspicious_object);
7252 /* When compiled with GCC, GDB might say "No enum type named
7253 pvec_type" if we don't have at least one symbol with that type, and
7254 then xbacktrace could fail. Similarly for the other enums and
7255 their values. Some non-GCC compilers don't like these constructs. */
7256 #ifdef __GNUC__
7257 union
7259 enum CHARTAB_SIZE_BITS CHARTAB_SIZE_BITS;
7260 enum char_table_specials char_table_specials;
7261 enum char_bits char_bits;
7262 enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE;
7263 enum DEFAULT_HASH_SIZE DEFAULT_HASH_SIZE;
7264 enum Lisp_Bits Lisp_Bits;
7265 enum Lisp_Compiled Lisp_Compiled;
7266 enum maxargs maxargs;
7267 enum MAX_ALLOCA MAX_ALLOCA;
7268 enum More_Lisp_Bits More_Lisp_Bits;
7269 enum pvec_type pvec_type;
7270 } const EXTERNALLY_VISIBLE gdb_make_enums_visible = {0};
7271 #endif /* __GNUC__ */