1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2015 Free Software
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/>. */
24 #include <limits.h> /* For CHAR_BIT. */
26 #ifdef ENABLE_CHECKING
27 #include <signal.h> /* For SIGABRT. */
36 #include "intervals.h"
38 #include "character.h"
43 #include "blockinput.h"
44 #include "termhooks.h" /* For struct terminal. */
45 #ifdef HAVE_WINDOW_SYSTEM
47 #endif /* HAVE_WINDOW_SYSTEM */
50 #include <execinfo.h> /* For backtrace. */
52 #ifdef HAVE_LINUX_SYSINFO
53 #include <sys/sysinfo.h>
57 #include "dosfns.h" /* For dos_memory_info. */
60 #if (defined ENABLE_CHECKING \
61 && defined HAVE_VALGRIND_VALGRIND_H \
62 && !defined USE_VALGRIND)
63 # define USE_VALGRIND 1
67 #include <valgrind/valgrind.h>
68 #include <valgrind/memcheck.h>
69 static bool valgrind_p
;
72 /* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects. */
74 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
75 memory. Can do this only if using gmalloc.c and if not checking
78 #if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
79 || defined HYBRID_MALLOC || defined GC_CHECK_MARKED_OBJECTS)
80 #undef GC_MALLOC_CHECK
91 #include "w32heap.h" /* for sbrk */
94 #ifdef DOUG_LEA_MALLOC
98 /* Specify maximum number of areas to mmap. It would be nice to use a
99 value that explicitly means "no limit". */
101 #define MMAP_MAX_AREAS 100000000
103 #endif /* not DOUG_LEA_MALLOC */
105 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
106 to a struct Lisp_String. */
108 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
109 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
110 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
112 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
113 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
114 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
116 /* Default value of gc_cons_threshold (see below). */
118 #define GC_DEFAULT_THRESHOLD (100000 * word_size)
120 /* Global variables. */
121 struct emacs_globals globals
;
123 /* Number of bytes of consing done since the last gc. */
125 EMACS_INT consing_since_gc
;
127 /* Similar minimum, computed from Vgc_cons_percentage. */
129 EMACS_INT gc_relative_threshold
;
131 /* Minimum number of bytes of consing since GC before next GC,
132 when memory is full. */
134 EMACS_INT memory_full_cons_threshold
;
136 /* True during GC. */
140 /* True means abort if try to GC.
141 This is for code which is written on the assumption that
142 no GC will happen, so as to verify that assumption. */
146 /* Number of live and free conses etc. */
148 static EMACS_INT total_conses
, total_markers
, total_symbols
, total_buffers
;
149 static EMACS_INT total_free_conses
, total_free_markers
, total_free_symbols
;
150 static EMACS_INT total_free_floats
, total_floats
;
152 /* Points to memory space allocated as "spare", to be freed if we run
153 out of memory. We keep one large block, four cons-blocks, and
154 two string blocks. */
156 static char *spare_memory
[7];
158 /* Amount of spare memory to keep in large reserve block, or to see
159 whether this much is available when malloc fails on a larger request. */
161 #define SPARE_MEMORY (1 << 14)
163 /* Initialize it to a nonzero value to force it into data space
164 (rather than bss space). That way unexec will remap it into text
165 space (pure), on some systems. We have not implemented the
166 remapping on more recent systems because this is less important
167 nowadays than in the days of small memories and timesharing. */
169 EMACS_INT pure
[(PURESIZE
+ sizeof (EMACS_INT
) - 1) / sizeof (EMACS_INT
)] = {1,};
170 #define PUREBEG (char *) pure
172 /* Pointer to the pure area, and its size. */
174 static char *purebeg
;
175 static ptrdiff_t pure_size
;
177 /* Number of bytes of pure storage used before pure storage overflowed.
178 If this is non-zero, this implies that an overflow occurred. */
180 static ptrdiff_t pure_bytes_used_before_overflow
;
182 /* True if P points into pure space. */
184 #define PURE_POINTER_P(P) \
185 ((uintptr_t) (P) - (uintptr_t) purebeg <= pure_size)
187 /* Index in pure at which next pure Lisp object will be allocated.. */
189 static ptrdiff_t pure_bytes_used_lisp
;
191 /* Number of bytes allocated for non-Lisp objects in pure storage. */
193 static ptrdiff_t pure_bytes_used_non_lisp
;
195 /* If nonzero, this is a warning delivered by malloc and not yet
198 const char *pending_malloc_warning
;
200 #if 0 /* Normally, pointer sanity only on request... */
201 #ifdef ENABLE_CHECKING
202 #define SUSPICIOUS_OBJECT_CHECKING 1
206 /* ... but unconditionally use SUSPICIOUS_OBJECT_CHECKING while the GC
207 bug is unresolved. */
208 #define SUSPICIOUS_OBJECT_CHECKING 1
210 #ifdef SUSPICIOUS_OBJECT_CHECKING
211 struct suspicious_free_record
213 void *suspicious_object
;
214 void *backtrace
[128];
216 static void *suspicious_objects
[32];
217 static int suspicious_object_index
;
218 struct suspicious_free_record suspicious_free_history
[64] EXTERNALLY_VISIBLE
;
219 static int suspicious_free_history_index
;
220 /* Find the first currently-monitored suspicious pointer in range
221 [begin,end) or NULL if no such pointer exists. */
222 static void *find_suspicious_object_in_range (void *begin
, void *end
);
223 static void detect_suspicious_free (void *ptr
);
225 # define find_suspicious_object_in_range(begin, end) NULL
226 # define detect_suspicious_free(ptr) (void)
229 /* Maximum amount of C stack to save when a GC happens. */
231 #ifndef MAX_SAVE_STACK
232 #define MAX_SAVE_STACK 16000
235 /* Buffer in which we save a copy of the C stack at each GC. */
237 #if MAX_SAVE_STACK > 0
238 static char *stack_copy
;
239 static ptrdiff_t stack_copy_size
;
241 /* Copy to DEST a block of memory from SRC of size SIZE bytes,
242 avoiding any address sanitization. */
244 static void * ATTRIBUTE_NO_SANITIZE_ADDRESS
245 no_sanitize_memcpy (void *dest
, void const *src
, size_t size
)
247 if (! ADDRESS_SANITIZER
)
248 return memcpy (dest
, src
, size
);
254 for (i
= 0; i
< size
; i
++)
260 #endif /* MAX_SAVE_STACK > 0 */
262 static void mark_terminals (void);
263 static void gc_sweep (void);
264 static Lisp_Object
make_pure_vector (ptrdiff_t);
265 static void mark_buffer (struct buffer
*);
267 #if !defined REL_ALLOC || defined SYSTEM_MALLOC || defined HYBRID_MALLOC
268 static void refill_memory_reserve (void);
270 static void compact_small_strings (void);
271 static void free_large_strings (void);
272 extern Lisp_Object
which_symbols (Lisp_Object
, EMACS_INT
) EXTERNALLY_VISIBLE
;
274 /* When scanning the C stack for live Lisp objects, Emacs keeps track of
275 what memory allocated via lisp_malloc and lisp_align_malloc is intended
276 for what purpose. This enumeration specifies the type of memory. */
287 /* Since all non-bool pseudovectors are small enough to be
288 allocated from vector blocks, this memory type denotes
289 large regular vectors and large bool pseudovectors. */
291 /* Special type to denote vector blocks. */
292 MEM_TYPE_VECTOR_BLOCK
,
293 /* Special type to denote reserved memory. */
297 /* A unique object in pure space used to make some Lisp objects
298 on free lists recognizable in O(1). */
300 static Lisp_Object Vdead
;
301 #define DEADP(x) EQ (x, Vdead)
303 #ifdef GC_MALLOC_CHECK
305 enum mem_type allocated_mem_type
;
307 #endif /* GC_MALLOC_CHECK */
309 /* A node in the red-black tree describing allocated memory containing
310 Lisp data. Each such block is recorded with its start and end
311 address when it is allocated, and removed from the tree when it
314 A red-black tree is a balanced binary tree with the following
317 1. Every node is either red or black.
318 2. Every leaf is black.
319 3. If a node is red, then both of its children are black.
320 4. Every simple path from a node to a descendant leaf contains
321 the same number of black nodes.
322 5. The root is always black.
324 When nodes are inserted into the tree, or deleted from the tree,
325 the tree is "fixed" so that these properties are always true.
327 A red-black tree with N internal nodes has height at most 2
328 log(N+1). Searches, insertions and deletions are done in O(log N).
329 Please see a text book about data structures for a detailed
330 description of red-black trees. Any book worth its salt should
335 /* Children of this node. These pointers are never NULL. When there
336 is no child, the value is MEM_NIL, which points to a dummy node. */
337 struct mem_node
*left
, *right
;
339 /* The parent of this node. In the root node, this is NULL. */
340 struct mem_node
*parent
;
342 /* Start and end of allocated region. */
346 enum {MEM_BLACK
, MEM_RED
} color
;
352 /* Base address of stack. Set in main. */
354 Lisp_Object
*stack_base
;
356 /* Root of the tree describing allocated Lisp memory. */
358 static struct mem_node
*mem_root
;
360 /* Lowest and highest known address in the heap. */
362 static void *min_heap_address
, *max_heap_address
;
364 /* Sentinel node of the tree. */
366 static struct mem_node mem_z
;
367 #define MEM_NIL &mem_z
369 static struct mem_node
*mem_insert (void *, void *, enum mem_type
);
370 static void mem_insert_fixup (struct mem_node
*);
371 static void mem_rotate_left (struct mem_node
*);
372 static void mem_rotate_right (struct mem_node
*);
373 static void mem_delete (struct mem_node
*);
374 static void mem_delete_fixup (struct mem_node
*);
375 static struct mem_node
*mem_find (void *);
381 /* Addresses of staticpro'd variables. Initialize it to a nonzero
382 value; otherwise some compilers put it into BSS. */
384 enum { NSTATICS
= 2048 };
385 static Lisp_Object
*staticvec
[NSTATICS
] = {&Vpurify_flag
};
387 /* Index of next unused slot in staticvec. */
389 static int staticidx
;
391 static void *pure_alloc (size_t, int);
393 /* Return X rounded to the next multiple of Y. Arguments should not
394 have side effects, as they are evaluated more than once. Assume X
395 + Y - 1 does not overflow. Tune for Y being a power of 2. */
397 #define ROUNDUP(x, y) ((y) & ((y) - 1) \
398 ? ((x) + (y) - 1) - ((x) + (y) - 1) % (y) \
399 : ((x) + (y) - 1) & ~ ((y) - 1))
401 /* Return PTR rounded up to the next multiple of ALIGNMENT. */
404 ALIGN (void *ptr
, int alignment
)
406 return (void *) ROUNDUP ((uintptr_t) ptr
, alignment
);
410 XFLOAT_INIT (Lisp_Object f
, double n
)
412 XFLOAT (f
)->u
.data
= n
;
416 pointers_fit_in_lispobj_p (void)
418 return (UINTPTR_MAX
<= VAL_MAX
) || USE_LSB_TAG
;
422 mmap_lisp_allowed_p (void)
424 /* If we can't store all memory addresses in our lisp objects, it's
425 risky to let the heap use mmap and give us addresses from all
426 over our address space. We also can't use mmap for lisp objects
427 if we might dump: unexec doesn't preserve the contents of mmapped
429 return pointers_fit_in_lispobj_p () && !might_dump
;
432 /* Head of a circularly-linked list of extant finalizers. */
433 static struct Lisp_Finalizer finalizers
;
435 /* Head of a circularly-linked list of finalizers that must be invoked
436 because we deemed them unreachable. This list must be global, and
437 not a local inside garbage_collect_1, in case we GC again while
438 running finalizers. */
439 static struct Lisp_Finalizer doomed_finalizers
;
442 /************************************************************************
444 ************************************************************************/
446 /* Function malloc calls this if it finds we are near exhausting storage. */
449 malloc_warning (const char *str
)
451 pending_malloc_warning
= str
;
455 /* Display an already-pending malloc warning. */
458 display_malloc_warning (void)
460 call3 (intern ("display-warning"),
462 build_string (pending_malloc_warning
),
463 intern ("emergency"));
464 pending_malloc_warning
= 0;
467 /* Called if we can't allocate relocatable space for a buffer. */
470 buffer_memory_full (ptrdiff_t nbytes
)
472 /* If buffers use the relocating allocator, no need to free
473 spare_memory, because we may have plenty of malloc space left
474 that we could get, and if we don't, the malloc that fails will
475 itself cause spare_memory to be freed. If buffers don't use the
476 relocating allocator, treat this like any other failing
480 memory_full (nbytes
);
482 /* This used to call error, but if we've run out of memory, we could
483 get infinite recursion trying to build the string. */
484 xsignal (Qnil
, Vmemory_signal_data
);
488 /* A common multiple of the positive integers A and B. Ideally this
489 would be the least common multiple, but there's no way to do that
490 as a constant expression in C, so do the best that we can easily do. */
491 #define COMMON_MULTIPLE(a, b) \
492 ((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
494 #ifndef XMALLOC_OVERRUN_CHECK
495 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
498 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
501 The header consists of XMALLOC_OVERRUN_CHECK_SIZE fixed bytes
502 followed by XMALLOC_OVERRUN_SIZE_SIZE bytes containing the original
503 block size in little-endian order. The trailer consists of
504 XMALLOC_OVERRUN_CHECK_SIZE fixed bytes.
506 The header is used to detect whether this block has been allocated
507 through these functions, as some low-level libc functions may
508 bypass the malloc hooks. */
510 #define XMALLOC_OVERRUN_CHECK_SIZE 16
511 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
512 (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)
514 /* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
515 hold a size_t value and (2) the header size is a multiple of the
516 alignment that Emacs needs for C types and for USE_LSB_TAG. */
517 #define XMALLOC_BASE_ALIGNMENT alignof (max_align_t)
519 #define XMALLOC_HEADER_ALIGNMENT \
520 COMMON_MULTIPLE (GCALIGNMENT, XMALLOC_BASE_ALIGNMENT)
521 #define XMALLOC_OVERRUN_SIZE_SIZE \
522 (((XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t) \
523 + XMALLOC_HEADER_ALIGNMENT - 1) \
524 / XMALLOC_HEADER_ALIGNMENT * XMALLOC_HEADER_ALIGNMENT) \
525 - XMALLOC_OVERRUN_CHECK_SIZE)
527 static char const xmalloc_overrun_check_header
[XMALLOC_OVERRUN_CHECK_SIZE
] =
528 { '\x9a', '\x9b', '\xae', '\xaf',
529 '\xbf', '\xbe', '\xce', '\xcf',
530 '\xea', '\xeb', '\xec', '\xed',
531 '\xdf', '\xde', '\x9c', '\x9d' };
533 static char const xmalloc_overrun_check_trailer
[XMALLOC_OVERRUN_CHECK_SIZE
] =
534 { '\xaa', '\xab', '\xac', '\xad',
535 '\xba', '\xbb', '\xbc', '\xbd',
536 '\xca', '\xcb', '\xcc', '\xcd',
537 '\xda', '\xdb', '\xdc', '\xdd' };
539 /* Insert and extract the block size in the header. */
542 xmalloc_put_size (unsigned char *ptr
, size_t size
)
545 for (i
= 0; i
< XMALLOC_OVERRUN_SIZE_SIZE
; i
++)
547 *--ptr
= size
& ((1 << CHAR_BIT
) - 1);
553 xmalloc_get_size (unsigned char *ptr
)
557 ptr
-= XMALLOC_OVERRUN_SIZE_SIZE
;
558 for (i
= 0; i
< XMALLOC_OVERRUN_SIZE_SIZE
; i
++)
567 /* Like malloc, but wraps allocated block with header and trailer. */
570 overrun_check_malloc (size_t size
)
572 register unsigned char *val
;
573 if (SIZE_MAX
- XMALLOC_OVERRUN_CHECK_OVERHEAD
< size
)
576 val
= malloc (size
+ XMALLOC_OVERRUN_CHECK_OVERHEAD
);
579 memcpy (val
, xmalloc_overrun_check_header
, XMALLOC_OVERRUN_CHECK_SIZE
);
580 val
+= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
581 xmalloc_put_size (val
, size
);
582 memcpy (val
+ size
, xmalloc_overrun_check_trailer
,
583 XMALLOC_OVERRUN_CHECK_SIZE
);
589 /* Like realloc, but checks old block for overrun, and wraps new block
590 with header and trailer. */
593 overrun_check_realloc (void *block
, size_t size
)
595 register unsigned char *val
= (unsigned char *) block
;
596 if (SIZE_MAX
- XMALLOC_OVERRUN_CHECK_OVERHEAD
< size
)
600 && memcmp (xmalloc_overrun_check_header
,
601 val
- XMALLOC_OVERRUN_CHECK_SIZE
- XMALLOC_OVERRUN_SIZE_SIZE
,
602 XMALLOC_OVERRUN_CHECK_SIZE
) == 0)
604 size_t osize
= xmalloc_get_size (val
);
605 if (memcmp (xmalloc_overrun_check_trailer
, val
+ osize
,
606 XMALLOC_OVERRUN_CHECK_SIZE
))
608 memset (val
+ osize
, 0, XMALLOC_OVERRUN_CHECK_SIZE
);
609 val
-= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
610 memset (val
, 0, XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
);
613 val
= realloc (val
, size
+ XMALLOC_OVERRUN_CHECK_OVERHEAD
);
617 memcpy (val
, xmalloc_overrun_check_header
, XMALLOC_OVERRUN_CHECK_SIZE
);
618 val
+= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
619 xmalloc_put_size (val
, size
);
620 memcpy (val
+ size
, xmalloc_overrun_check_trailer
,
621 XMALLOC_OVERRUN_CHECK_SIZE
);
626 /* Like free, but checks block for overrun. */
629 overrun_check_free (void *block
)
631 unsigned char *val
= (unsigned char *) block
;
634 && memcmp (xmalloc_overrun_check_header
,
635 val
- XMALLOC_OVERRUN_CHECK_SIZE
- XMALLOC_OVERRUN_SIZE_SIZE
,
636 XMALLOC_OVERRUN_CHECK_SIZE
) == 0)
638 size_t osize
= xmalloc_get_size (val
);
639 if (memcmp (xmalloc_overrun_check_trailer
, val
+ osize
,
640 XMALLOC_OVERRUN_CHECK_SIZE
))
642 #ifdef XMALLOC_CLEAR_FREE_MEMORY
643 val
-= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
644 memset (val
, 0xff, osize
+ XMALLOC_OVERRUN_CHECK_OVERHEAD
);
646 memset (val
+ osize
, 0, XMALLOC_OVERRUN_CHECK_SIZE
);
647 val
-= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
648 memset (val
, 0, XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
);
658 #define malloc overrun_check_malloc
659 #define realloc overrun_check_realloc
660 #define free overrun_check_free
663 /* If compiled with XMALLOC_BLOCK_INPUT_CHECK, define a symbol
664 BLOCK_INPUT_IN_MEMORY_ALLOCATORS that is visible to the debugger.
665 If that variable is set, block input while in one of Emacs's memory
666 allocation functions. There should be no need for this debugging
667 option, since signal handlers do not allocate memory, but Emacs
668 formerly allocated memory in signal handlers and this compile-time
669 option remains as a way to help debug the issue should it rear its
671 #ifdef XMALLOC_BLOCK_INPUT_CHECK
672 bool block_input_in_memory_allocators EXTERNALLY_VISIBLE
;
674 malloc_block_input (void)
676 if (block_input_in_memory_allocators
)
680 malloc_unblock_input (void)
682 if (block_input_in_memory_allocators
)
685 # define MALLOC_BLOCK_INPUT malloc_block_input ()
686 # define MALLOC_UNBLOCK_INPUT malloc_unblock_input ()
688 # define MALLOC_BLOCK_INPUT ((void) 0)
689 # define MALLOC_UNBLOCK_INPUT ((void) 0)
692 #define MALLOC_PROBE(size) \
694 if (profiler_memory_running) \
695 malloc_probe (size); \
699 /* Like malloc but check for no memory and block interrupt input.. */
702 xmalloc (size_t size
)
708 MALLOC_UNBLOCK_INPUT
;
716 /* Like the above, but zeroes out the memory just allocated. */
719 xzalloc (size_t size
)
725 MALLOC_UNBLOCK_INPUT
;
729 memset (val
, 0, size
);
734 /* Like realloc but check for no memory and block interrupt input.. */
737 xrealloc (void *block
, size_t size
)
742 /* We must call malloc explicitly when BLOCK is 0, since some
743 reallocs don't do this. */
747 val
= realloc (block
, size
);
748 MALLOC_UNBLOCK_INPUT
;
757 /* Like free but block interrupt input. */
766 MALLOC_UNBLOCK_INPUT
;
767 /* We don't call refill_memory_reserve here
768 because in practice the call in r_alloc_free seems to suffice. */
772 /* Other parts of Emacs pass large int values to allocator functions
773 expecting ptrdiff_t. This is portable in practice, but check it to
775 verify (INT_MAX
<= PTRDIFF_MAX
);
778 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
779 Signal an error on memory exhaustion, and block interrupt input. */
782 xnmalloc (ptrdiff_t nitems
, ptrdiff_t item_size
)
784 eassert (0 <= nitems
&& 0 < item_size
);
785 if (min (PTRDIFF_MAX
, SIZE_MAX
) / item_size
< nitems
)
786 memory_full (SIZE_MAX
);
787 return xmalloc (nitems
* item_size
);
791 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
792 Signal an error on memory exhaustion, and block interrupt input. */
795 xnrealloc (void *pa
, ptrdiff_t nitems
, ptrdiff_t item_size
)
797 eassert (0 <= nitems
&& 0 < item_size
);
798 if (min (PTRDIFF_MAX
, SIZE_MAX
) / item_size
< nitems
)
799 memory_full (SIZE_MAX
);
800 return xrealloc (pa
, nitems
* item_size
);
804 /* Grow PA, which points to an array of *NITEMS items, and return the
805 location of the reallocated array, updating *NITEMS to reflect its
806 new size. The new array will contain at least NITEMS_INCR_MIN more
807 items, but will not contain more than NITEMS_MAX items total.
808 ITEM_SIZE is the size of each item, in bytes.
810 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
811 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
814 If PA is null, then allocate a new array instead of reallocating
817 Block interrupt input as needed. If memory exhaustion occurs, set
818 *NITEMS to zero if PA is null, and signal an error (i.e., do not
821 Thus, to grow an array A without saving its old contents, do
822 { xfree (A); A = NULL; A = xpalloc (NULL, &AITEMS, ...); }.
823 The A = NULL avoids a dangling pointer if xpalloc exhausts memory
824 and signals an error, and later this code is reexecuted and
825 attempts to free A. */
828 xpalloc (void *pa
, ptrdiff_t *nitems
, ptrdiff_t nitems_incr_min
,
829 ptrdiff_t nitems_max
, ptrdiff_t item_size
)
831 /* The approximate size to use for initial small allocation
832 requests. This is the largest "small" request for the GNU C
834 enum { DEFAULT_MXFAST
= 64 * sizeof (size_t) / 4 };
836 /* If the array is tiny, grow it to about (but no greater than)
837 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%. */
838 ptrdiff_t n
= *nitems
;
839 ptrdiff_t tiny_max
= DEFAULT_MXFAST
/ item_size
- n
;
840 ptrdiff_t half_again
= n
>> 1;
841 ptrdiff_t incr_estimate
= max (tiny_max
, half_again
);
843 /* Adjust the increment according to three constraints: NITEMS_INCR_MIN,
844 NITEMS_MAX, and what the C language can represent safely. */
845 ptrdiff_t C_language_max
= min (PTRDIFF_MAX
, SIZE_MAX
) / item_size
;
846 ptrdiff_t n_max
= (0 <= nitems_max
&& nitems_max
< C_language_max
847 ? nitems_max
: C_language_max
);
848 ptrdiff_t nitems_incr_max
= n_max
- n
;
849 ptrdiff_t incr
= max (nitems_incr_min
, min (incr_estimate
, nitems_incr_max
));
851 eassert (0 < item_size
&& 0 < nitems_incr_min
&& 0 <= n
&& -1 <= nitems_max
);
854 if (nitems_incr_max
< incr
)
855 memory_full (SIZE_MAX
);
857 pa
= xrealloc (pa
, n
* item_size
);
863 /* Like strdup, but uses xmalloc. */
866 xstrdup (const char *s
)
870 size
= strlen (s
) + 1;
871 return memcpy (xmalloc (size
), s
, size
);
874 /* Like above, but duplicates Lisp string to C string. */
877 xlispstrdup (Lisp_Object string
)
879 ptrdiff_t size
= SBYTES (string
) + 1;
880 return memcpy (xmalloc (size
), SSDATA (string
), size
);
883 /* Assign to *PTR a copy of STRING, freeing any storage *PTR formerly
884 pointed to. If STRING is null, assign it without copying anything.
885 Allocate before freeing, to avoid a dangling pointer if allocation
889 dupstring (char **ptr
, char const *string
)
892 *ptr
= string
? xstrdup (string
) : 0;
897 /* Like putenv, but (1) use the equivalent of xmalloc and (2) the
898 argument is a const pointer. */
901 xputenv (char const *string
)
903 if (putenv ((char *) string
) != 0)
907 /* Return a newly allocated memory block of SIZE bytes, remembering
908 to free it when unwinding. */
910 record_xmalloc (size_t size
)
912 void *p
= xmalloc (size
);
913 record_unwind_protect_ptr (xfree
, p
);
918 /* Like malloc but used for allocating Lisp data. NBYTES is the
919 number of bytes to allocate, TYPE describes the intended use of the
920 allocated memory block (for strings, for conses, ...). */
923 void *lisp_malloc_loser EXTERNALLY_VISIBLE
;
927 lisp_malloc (size_t nbytes
, enum mem_type type
)
933 #ifdef GC_MALLOC_CHECK
934 allocated_mem_type
= type
;
937 val
= malloc (nbytes
);
940 /* If the memory just allocated cannot be addressed thru a Lisp
941 object's pointer, and it needs to be,
942 that's equivalent to running out of memory. */
943 if (val
&& type
!= MEM_TYPE_NON_LISP
)
946 XSETCONS (tem
, (char *) val
+ nbytes
- 1);
947 if ((char *) XCONS (tem
) != (char *) val
+ nbytes
- 1)
949 lisp_malloc_loser
= val
;
956 #ifndef GC_MALLOC_CHECK
957 if (val
&& type
!= MEM_TYPE_NON_LISP
)
958 mem_insert (val
, (char *) val
+ nbytes
, type
);
961 MALLOC_UNBLOCK_INPUT
;
963 memory_full (nbytes
);
964 MALLOC_PROBE (nbytes
);
968 /* Free BLOCK. This must be called to free memory allocated with a
969 call to lisp_malloc. */
972 lisp_free (void *block
)
976 #ifndef GC_MALLOC_CHECK
977 mem_delete (mem_find (block
));
979 MALLOC_UNBLOCK_INPUT
;
982 /***** Allocation of aligned blocks of memory to store Lisp data. *****/
984 /* The entry point is lisp_align_malloc which returns blocks of at most
985 BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
987 /* Use aligned_alloc if it or a simple substitute is available.
988 Address sanitization breaks aligned allocation, as of gcc 4.8.2 and
991 #if ! ADDRESS_SANITIZER
992 # if !defined SYSTEM_MALLOC && !defined DOUG_LEA_MALLOC && !defined HYBRID_MALLOC
993 # define USE_ALIGNED_ALLOC 1
994 /* Defined in gmalloc.c. */
995 void *aligned_alloc (size_t, size_t);
996 # elif defined HYBRID_MALLOC
997 # if defined ALIGNED_ALLOC || defined HAVE_POSIX_MEMALIGN
998 # define USE_ALIGNED_ALLOC 1
999 # define aligned_alloc hybrid_aligned_alloc
1000 /* Defined in gmalloc.c. */
1001 void *aligned_alloc (size_t, size_t);
1003 # elif defined HAVE_ALIGNED_ALLOC
1004 # define USE_ALIGNED_ALLOC 1
1005 # elif defined HAVE_POSIX_MEMALIGN
1006 # define USE_ALIGNED_ALLOC 1
1008 aligned_alloc (size_t alignment
, size_t size
)
1011 return posix_memalign (&p
, alignment
, size
) == 0 ? p
: 0;
1016 /* BLOCK_ALIGN has to be a power of 2. */
1017 #define BLOCK_ALIGN (1 << 10)
1019 /* Padding to leave at the end of a malloc'd block. This is to give
1020 malloc a chance to minimize the amount of memory wasted to alignment.
1021 It should be tuned to the particular malloc library used.
1022 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
1023 aligned_alloc on the other hand would ideally prefer a value of 4
1024 because otherwise, there's 1020 bytes wasted between each ablocks.
1025 In Emacs, testing shows that those 1020 can most of the time be
1026 efficiently used by malloc to place other objects, so a value of 0 can
1027 still preferable unless you have a lot of aligned blocks and virtually
1029 #define BLOCK_PADDING 0
1030 #define BLOCK_BYTES \
1031 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
1033 /* Internal data structures and constants. */
1035 #define ABLOCKS_SIZE 16
1037 /* An aligned block of memory. */
1042 char payload
[BLOCK_BYTES
];
1043 struct ablock
*next_free
;
1045 /* `abase' is the aligned base of the ablocks. */
1046 /* It is overloaded to hold the virtual `busy' field that counts
1047 the number of used ablock in the parent ablocks.
1048 The first ablock has the `busy' field, the others have the `abase'
1049 field. To tell the difference, we assume that pointers will have
1050 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
1051 is used to tell whether the real base of the parent ablocks is `abase'
1052 (if not, the word before the first ablock holds a pointer to the
1054 struct ablocks
*abase
;
1055 /* The padding of all but the last ablock is unused. The padding of
1056 the last ablock in an ablocks is not allocated. */
1058 char padding
[BLOCK_PADDING
];
1062 /* A bunch of consecutive aligned blocks. */
1065 struct ablock blocks
[ABLOCKS_SIZE
];
1068 /* Size of the block requested from malloc or aligned_alloc. */
1069 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
1071 #define ABLOCK_ABASE(block) \
1072 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
1073 ? (struct ablocks *)(block) \
1076 /* Virtual `busy' field. */
1077 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
1079 /* Pointer to the (not necessarily aligned) malloc block. */
1080 #ifdef USE_ALIGNED_ALLOC
1081 #define ABLOCKS_BASE(abase) (abase)
1083 #define ABLOCKS_BASE(abase) \
1084 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void **)abase)[-1])
1087 /* The list of free ablock. */
1088 static struct ablock
*free_ablock
;
1090 /* Allocate an aligned block of nbytes.
1091 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
1092 smaller or equal to BLOCK_BYTES. */
1094 lisp_align_malloc (size_t nbytes
, enum mem_type type
)
1097 struct ablocks
*abase
;
1099 eassert (nbytes
<= BLOCK_BYTES
);
1103 #ifdef GC_MALLOC_CHECK
1104 allocated_mem_type
= type
;
1110 intptr_t aligned
; /* int gets warning casting to 64-bit pointer. */
1112 #ifdef DOUG_LEA_MALLOC
1113 if (!mmap_lisp_allowed_p ())
1114 mallopt (M_MMAP_MAX
, 0);
1117 #ifdef USE_ALIGNED_ALLOC
1118 abase
= base
= aligned_alloc (BLOCK_ALIGN
, ABLOCKS_BYTES
);
1120 base
= malloc (ABLOCKS_BYTES
);
1121 abase
= ALIGN (base
, BLOCK_ALIGN
);
1126 MALLOC_UNBLOCK_INPUT
;
1127 memory_full (ABLOCKS_BYTES
);
1130 aligned
= (base
== abase
);
1132 ((void **) abase
)[-1] = base
;
1134 #ifdef DOUG_LEA_MALLOC
1135 if (!mmap_lisp_allowed_p ())
1136 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
);
1140 /* If the memory just allocated cannot be addressed thru a Lisp
1141 object's pointer, and it needs to be, that's equivalent to
1142 running out of memory. */
1143 if (type
!= MEM_TYPE_NON_LISP
)
1146 char *end
= (char *) base
+ ABLOCKS_BYTES
- 1;
1147 XSETCONS (tem
, end
);
1148 if ((char *) XCONS (tem
) != end
)
1150 lisp_malloc_loser
= base
;
1152 MALLOC_UNBLOCK_INPUT
;
1153 memory_full (SIZE_MAX
);
1158 /* Initialize the blocks and put them on the free list.
1159 If `base' was not properly aligned, we can't use the last block. */
1160 for (i
= 0; i
< (aligned
? ABLOCKS_SIZE
: ABLOCKS_SIZE
- 1); i
++)
1162 abase
->blocks
[i
].abase
= abase
;
1163 abase
->blocks
[i
].x
.next_free
= free_ablock
;
1164 free_ablock
= &abase
->blocks
[i
];
1166 ABLOCKS_BUSY (abase
) = (struct ablocks
*) aligned
;
1168 eassert (0 == ((uintptr_t) abase
) % BLOCK_ALIGN
);
1169 eassert (ABLOCK_ABASE (&abase
->blocks
[3]) == abase
); /* 3 is arbitrary */
1170 eassert (ABLOCK_ABASE (&abase
->blocks
[0]) == abase
);
1171 eassert (ABLOCKS_BASE (abase
) == base
);
1172 eassert (aligned
== (intptr_t) ABLOCKS_BUSY (abase
));
1175 abase
= ABLOCK_ABASE (free_ablock
);
1176 ABLOCKS_BUSY (abase
)
1177 = (struct ablocks
*) (2 + (intptr_t) ABLOCKS_BUSY (abase
));
1179 free_ablock
= free_ablock
->x
.next_free
;
1181 #ifndef GC_MALLOC_CHECK
1182 if (type
!= MEM_TYPE_NON_LISP
)
1183 mem_insert (val
, (char *) val
+ nbytes
, type
);
1186 MALLOC_UNBLOCK_INPUT
;
1188 MALLOC_PROBE (nbytes
);
1190 eassert (0 == ((uintptr_t) val
) % BLOCK_ALIGN
);
1195 lisp_align_free (void *block
)
1197 struct ablock
*ablock
= block
;
1198 struct ablocks
*abase
= ABLOCK_ABASE (ablock
);
1201 #ifndef GC_MALLOC_CHECK
1202 mem_delete (mem_find (block
));
1204 /* Put on free list. */
1205 ablock
->x
.next_free
= free_ablock
;
1206 free_ablock
= ablock
;
1207 /* Update busy count. */
1208 ABLOCKS_BUSY (abase
)
1209 = (struct ablocks
*) (-2 + (intptr_t) ABLOCKS_BUSY (abase
));
1211 if (2 > (intptr_t) ABLOCKS_BUSY (abase
))
1212 { /* All the blocks are free. */
1213 int i
= 0, aligned
= (intptr_t) ABLOCKS_BUSY (abase
);
1214 struct ablock
**tem
= &free_ablock
;
1215 struct ablock
*atop
= &abase
->blocks
[aligned
? ABLOCKS_SIZE
: ABLOCKS_SIZE
- 1];
1219 if (*tem
>= (struct ablock
*) abase
&& *tem
< atop
)
1222 *tem
= (*tem
)->x
.next_free
;
1225 tem
= &(*tem
)->x
.next_free
;
1227 eassert ((aligned
& 1) == aligned
);
1228 eassert (i
== (aligned
? ABLOCKS_SIZE
: ABLOCKS_SIZE
- 1));
1229 #ifdef USE_POSIX_MEMALIGN
1230 eassert ((uintptr_t) ABLOCKS_BASE (abase
) % BLOCK_ALIGN
== 0);
1232 free (ABLOCKS_BASE (abase
));
1234 MALLOC_UNBLOCK_INPUT
;
1238 /***********************************************************************
1240 ***********************************************************************/
1242 /* Number of intervals allocated in an interval_block structure.
1243 The 1020 is 1024 minus malloc overhead. */
1245 #define INTERVAL_BLOCK_SIZE \
1246 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1248 /* Intervals are allocated in chunks in the form of an interval_block
1251 struct interval_block
1253 /* Place `intervals' first, to preserve alignment. */
1254 struct interval intervals
[INTERVAL_BLOCK_SIZE
];
1255 struct interval_block
*next
;
1258 /* Current interval block. Its `next' pointer points to older
1261 static struct interval_block
*interval_block
;
1263 /* Index in interval_block above of the next unused interval
1266 static int interval_block_index
= INTERVAL_BLOCK_SIZE
;
1268 /* Number of free and live intervals. */
1270 static EMACS_INT total_free_intervals
, total_intervals
;
1272 /* List of free intervals. */
1274 static INTERVAL interval_free_list
;
1276 /* Return a new interval. */
1279 make_interval (void)
1285 if (interval_free_list
)
1287 val
= interval_free_list
;
1288 interval_free_list
= INTERVAL_PARENT (interval_free_list
);
1292 if (interval_block_index
== INTERVAL_BLOCK_SIZE
)
1294 struct interval_block
*newi
1295 = lisp_malloc (sizeof *newi
, MEM_TYPE_NON_LISP
);
1297 newi
->next
= interval_block
;
1298 interval_block
= newi
;
1299 interval_block_index
= 0;
1300 total_free_intervals
+= INTERVAL_BLOCK_SIZE
;
1302 val
= &interval_block
->intervals
[interval_block_index
++];
1305 MALLOC_UNBLOCK_INPUT
;
1307 consing_since_gc
+= sizeof (struct interval
);
1309 total_free_intervals
--;
1310 RESET_INTERVAL (val
);
1316 /* Mark Lisp objects in interval I. */
1319 mark_interval (register INTERVAL i
, Lisp_Object dummy
)
1321 /* Intervals should never be shared. So, if extra internal checking is
1322 enabled, GC aborts if it seems to have visited an interval twice. */
1323 eassert (!i
->gcmarkbit
);
1325 mark_object (i
->plist
);
1328 /* Mark the interval tree rooted in I. */
1330 #define MARK_INTERVAL_TREE(i) \
1332 if (i && !i->gcmarkbit) \
1333 traverse_intervals_noorder (i, mark_interval, Qnil); \
1336 /***********************************************************************
1338 ***********************************************************************/
1340 /* Lisp_Strings are allocated in string_block structures. When a new
1341 string_block is allocated, all the Lisp_Strings it contains are
1342 added to a free-list string_free_list. When a new Lisp_String is
1343 needed, it is taken from that list. During the sweep phase of GC,
1344 string_blocks that are entirely free are freed, except two which
1347 String data is allocated from sblock structures. Strings larger
1348 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1349 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1351 Sblocks consist internally of sdata structures, one for each
1352 Lisp_String. The sdata structure points to the Lisp_String it
1353 belongs to. The Lisp_String points back to the `u.data' member of
1354 its sdata structure.
1356 When a Lisp_String is freed during GC, it is put back on
1357 string_free_list, and its `data' member and its sdata's `string'
1358 pointer is set to null. The size of the string is recorded in the
1359 `n.nbytes' member of the sdata. So, sdata structures that are no
1360 longer used, can be easily recognized, and it's easy to compact the
1361 sblocks of small strings which we do in compact_small_strings. */
1363 /* Size in bytes of an sblock structure used for small strings. This
1364 is 8192 minus malloc overhead. */
1366 #define SBLOCK_SIZE 8188
1368 /* Strings larger than this are considered large strings. String data
1369 for large strings is allocated from individual sblocks. */
1371 #define LARGE_STRING_BYTES 1024
1373 /* The SDATA typedef is a struct or union describing string memory
1374 sub-allocated from an sblock. This is where the contents of Lisp
1375 strings are stored. */
1379 /* Back-pointer to the string this sdata belongs to. If null, this
1380 structure is free, and NBYTES (in this structure or in the union below)
1381 contains the string's byte size (the same value that STRING_BYTES
1382 would return if STRING were non-null). If non-null, STRING_BYTES
1383 (STRING) is the size of the data, and DATA contains the string's
1385 struct Lisp_String
*string
;
1387 #ifdef GC_CHECK_STRING_BYTES
1391 unsigned char data
[FLEXIBLE_ARRAY_MEMBER
];
1394 #ifdef GC_CHECK_STRING_BYTES
1396 typedef struct sdata sdata
;
1397 #define SDATA_NBYTES(S) (S)->nbytes
1398 #define SDATA_DATA(S) (S)->data
1404 struct Lisp_String
*string
;
1406 /* When STRING is nonnull, this union is actually of type 'struct sdata',
1407 which has a flexible array member. However, if implemented by
1408 giving this union a member of type 'struct sdata', the union
1409 could not be the last (flexible) member of 'struct sblock',
1410 because C99 prohibits a flexible array member from having a type
1411 that is itself a flexible array. So, comment this member out here,
1412 but remember that the option's there when using this union. */
1417 /* When STRING is null. */
1420 struct Lisp_String
*string
;
1425 #define SDATA_NBYTES(S) (S)->n.nbytes
1426 #define SDATA_DATA(S) ((struct sdata *) (S))->data
1428 #endif /* not GC_CHECK_STRING_BYTES */
1430 enum { SDATA_DATA_OFFSET
= offsetof (struct sdata
, data
) };
1432 /* Structure describing a block of memory which is sub-allocated to
1433 obtain string data memory for strings. Blocks for small strings
1434 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1435 as large as needed. */
1440 struct sblock
*next
;
1442 /* Pointer to the next free sdata block. This points past the end
1443 of the sblock if there isn't any space left in this block. */
1447 sdata data
[FLEXIBLE_ARRAY_MEMBER
];
1450 /* Number of Lisp strings in a string_block structure. The 1020 is
1451 1024 minus malloc overhead. */
1453 #define STRING_BLOCK_SIZE \
1454 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1456 /* Structure describing a block from which Lisp_String structures
1461 /* Place `strings' first, to preserve alignment. */
1462 struct Lisp_String strings
[STRING_BLOCK_SIZE
];
1463 struct string_block
*next
;
1466 /* Head and tail of the list of sblock structures holding Lisp string
1467 data. We always allocate from current_sblock. The NEXT pointers
1468 in the sblock structures go from oldest_sblock to current_sblock. */
1470 static struct sblock
*oldest_sblock
, *current_sblock
;
1472 /* List of sblocks for large strings. */
1474 static struct sblock
*large_sblocks
;
1476 /* List of string_block structures. */
1478 static struct string_block
*string_blocks
;
1480 /* Free-list of Lisp_Strings. */
1482 static struct Lisp_String
*string_free_list
;
1484 /* Number of live and free Lisp_Strings. */
1486 static EMACS_INT total_strings
, total_free_strings
;
1488 /* Number of bytes used by live strings. */
1490 static EMACS_INT total_string_bytes
;
1492 /* Given a pointer to a Lisp_String S which is on the free-list
1493 string_free_list, return a pointer to its successor in the
1496 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1498 /* Return a pointer to the sdata structure belonging to Lisp string S.
1499 S must be live, i.e. S->data must not be null. S->data is actually
1500 a pointer to the `u.data' member of its sdata structure; the
1501 structure starts at a constant offset in front of that. */
1503 #define SDATA_OF_STRING(S) ((sdata *) ((S)->data - SDATA_DATA_OFFSET))
1506 #ifdef GC_CHECK_STRING_OVERRUN
1508 /* We check for overrun in string data blocks by appending a small
1509 "cookie" after each allocated string data block, and check for the
1510 presence of this cookie during GC. */
1512 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1513 static char const string_overrun_cookie
[GC_STRING_OVERRUN_COOKIE_SIZE
] =
1514 { '\xde', '\xad', '\xbe', '\xef' };
1517 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1520 /* Value is the size of an sdata structure large enough to hold NBYTES
1521 bytes of string data. The value returned includes a terminating
1522 NUL byte, the size of the sdata structure, and padding. */
1524 #ifdef GC_CHECK_STRING_BYTES
1526 #define SDATA_SIZE(NBYTES) \
1527 ((SDATA_DATA_OFFSET \
1529 + sizeof (ptrdiff_t) - 1) \
1530 & ~(sizeof (ptrdiff_t) - 1))
1532 #else /* not GC_CHECK_STRING_BYTES */
1534 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1535 less than the size of that member. The 'max' is not needed when
1536 SDATA_DATA_OFFSET is a multiple of sizeof (ptrdiff_t), because then the
1537 alignment code reserves enough space. */
1539 #define SDATA_SIZE(NBYTES) \
1540 ((SDATA_DATA_OFFSET \
1541 + (SDATA_DATA_OFFSET % sizeof (ptrdiff_t) == 0 \
1543 : max (NBYTES, sizeof (ptrdiff_t) - 1)) \
1545 + sizeof (ptrdiff_t) - 1) \
1546 & ~(sizeof (ptrdiff_t) - 1))
1548 #endif /* not GC_CHECK_STRING_BYTES */
1550 /* Extra bytes to allocate for each string. */
1552 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1554 /* Exact bound on the number of bytes in a string, not counting the
1555 terminating null. A string cannot contain more bytes than
1556 STRING_BYTES_BOUND, nor can it be so long that the size_t
1557 arithmetic in allocate_string_data would overflow while it is
1558 calculating a value to be passed to malloc. */
1559 static ptrdiff_t const STRING_BYTES_MAX
=
1560 min (STRING_BYTES_BOUND
,
1561 ((SIZE_MAX
- XMALLOC_OVERRUN_CHECK_OVERHEAD
1563 - offsetof (struct sblock
, data
)
1564 - SDATA_DATA_OFFSET
)
1565 & ~(sizeof (EMACS_INT
) - 1)));
1567 /* Initialize string allocation. Called from init_alloc_once. */
1572 empty_unibyte_string
= make_pure_string ("", 0, 0, 0);
1573 empty_multibyte_string
= make_pure_string ("", 0, 0, 1);
1577 #ifdef GC_CHECK_STRING_BYTES
1579 static int check_string_bytes_count
;
1581 /* Like STRING_BYTES, but with debugging check. Can be
1582 called during GC, so pay attention to the mark bit. */
1585 string_bytes (struct Lisp_String
*s
)
1588 (s
->size_byte
< 0 ? s
->size
& ~ARRAY_MARK_FLAG
: s
->size_byte
);
1590 if (!PURE_POINTER_P (s
)
1592 && nbytes
!= SDATA_NBYTES (SDATA_OF_STRING (s
)))
1597 /* Check validity of Lisp strings' string_bytes member in B. */
1600 check_sblock (struct sblock
*b
)
1602 sdata
*from
, *end
, *from_end
;
1606 for (from
= b
->data
; from
< end
; from
= from_end
)
1608 /* Compute the next FROM here because copying below may
1609 overwrite data we need to compute it. */
1612 /* Check that the string size recorded in the string is the
1613 same as the one recorded in the sdata structure. */
1614 nbytes
= SDATA_SIZE (from
->string
? string_bytes (from
->string
)
1615 : SDATA_NBYTES (from
));
1616 from_end
= (sdata
*) ((char *) from
+ nbytes
+ GC_STRING_EXTRA
);
1621 /* Check validity of Lisp strings' string_bytes member. ALL_P
1622 means check all strings, otherwise check only most
1623 recently allocated strings. Used for hunting a bug. */
1626 check_string_bytes (bool all_p
)
1632 for (b
= large_sblocks
; b
; b
= b
->next
)
1634 struct Lisp_String
*s
= b
->data
[0].string
;
1639 for (b
= oldest_sblock
; b
; b
= b
->next
)
1642 else if (current_sblock
)
1643 check_sblock (current_sblock
);
1646 #else /* not GC_CHECK_STRING_BYTES */
1648 #define check_string_bytes(all) ((void) 0)
1650 #endif /* GC_CHECK_STRING_BYTES */
1652 #ifdef GC_CHECK_STRING_FREE_LIST
1654 /* Walk through the string free list looking for bogus next pointers.
1655 This may catch buffer overrun from a previous string. */
1658 check_string_free_list (void)
1660 struct Lisp_String
*s
;
1662 /* Pop a Lisp_String off the free-list. */
1663 s
= string_free_list
;
1666 if ((uintptr_t) s
< 1024)
1668 s
= NEXT_FREE_LISP_STRING (s
);
1672 #define check_string_free_list()
1675 /* Return a new Lisp_String. */
1677 static struct Lisp_String
*
1678 allocate_string (void)
1680 struct Lisp_String
*s
;
1684 /* If the free-list is empty, allocate a new string_block, and
1685 add all the Lisp_Strings in it to the free-list. */
1686 if (string_free_list
== NULL
)
1688 struct string_block
*b
= lisp_malloc (sizeof *b
, MEM_TYPE_STRING
);
1691 b
->next
= string_blocks
;
1694 for (i
= STRING_BLOCK_SIZE
- 1; i
>= 0; --i
)
1697 /* Every string on a free list should have NULL data pointer. */
1699 NEXT_FREE_LISP_STRING (s
) = string_free_list
;
1700 string_free_list
= s
;
1703 total_free_strings
+= STRING_BLOCK_SIZE
;
1706 check_string_free_list ();
1708 /* Pop a Lisp_String off the free-list. */
1709 s
= string_free_list
;
1710 string_free_list
= NEXT_FREE_LISP_STRING (s
);
1712 MALLOC_UNBLOCK_INPUT
;
1714 --total_free_strings
;
1717 consing_since_gc
+= sizeof *s
;
1719 #ifdef GC_CHECK_STRING_BYTES
1720 if (!noninteractive
)
1722 if (++check_string_bytes_count
== 200)
1724 check_string_bytes_count
= 0;
1725 check_string_bytes (1);
1728 check_string_bytes (0);
1730 #endif /* GC_CHECK_STRING_BYTES */
1736 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1737 plus a NUL byte at the end. Allocate an sdata structure for S, and
1738 set S->data to its `u.data' member. Store a NUL byte at the end of
1739 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1740 S->data if it was initially non-null. */
1743 allocate_string_data (struct Lisp_String
*s
,
1744 EMACS_INT nchars
, EMACS_INT nbytes
)
1746 sdata
*data
, *old_data
;
1748 ptrdiff_t needed
, old_nbytes
;
1750 if (STRING_BYTES_MAX
< nbytes
)
1753 /* Determine the number of bytes needed to store NBYTES bytes
1755 needed
= SDATA_SIZE (nbytes
);
1758 old_data
= SDATA_OF_STRING (s
);
1759 old_nbytes
= STRING_BYTES (s
);
1766 if (nbytes
> LARGE_STRING_BYTES
)
1768 size_t size
= offsetof (struct sblock
, data
) + needed
;
1770 #ifdef DOUG_LEA_MALLOC
1771 if (!mmap_lisp_allowed_p ())
1772 mallopt (M_MMAP_MAX
, 0);
1775 b
= lisp_malloc (size
+ GC_STRING_EXTRA
, MEM_TYPE_NON_LISP
);
1777 #ifdef DOUG_LEA_MALLOC
1778 if (!mmap_lisp_allowed_p ())
1779 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
);
1782 b
->next_free
= b
->data
;
1783 b
->data
[0].string
= NULL
;
1784 b
->next
= large_sblocks
;
1787 else if (current_sblock
== NULL
1788 || (((char *) current_sblock
+ SBLOCK_SIZE
1789 - (char *) current_sblock
->next_free
)
1790 < (needed
+ GC_STRING_EXTRA
)))
1792 /* Not enough room in the current sblock. */
1793 b
= lisp_malloc (SBLOCK_SIZE
, MEM_TYPE_NON_LISP
);
1794 b
->next_free
= b
->data
;
1795 b
->data
[0].string
= NULL
;
1799 current_sblock
->next
= b
;
1807 data
= b
->next_free
;
1808 b
->next_free
= (sdata
*) ((char *) data
+ needed
+ GC_STRING_EXTRA
);
1810 MALLOC_UNBLOCK_INPUT
;
1813 s
->data
= SDATA_DATA (data
);
1814 #ifdef GC_CHECK_STRING_BYTES
1815 SDATA_NBYTES (data
) = nbytes
;
1818 s
->size_byte
= nbytes
;
1819 s
->data
[nbytes
] = '\0';
1820 #ifdef GC_CHECK_STRING_OVERRUN
1821 memcpy ((char *) data
+ needed
, string_overrun_cookie
,
1822 GC_STRING_OVERRUN_COOKIE_SIZE
);
1825 /* Note that Faset may call to this function when S has already data
1826 assigned. In this case, mark data as free by setting it's string
1827 back-pointer to null, and record the size of the data in it. */
1830 SDATA_NBYTES (old_data
) = old_nbytes
;
1831 old_data
->string
= NULL
;
1834 consing_since_gc
+= needed
;
1838 /* Sweep and compact strings. */
1840 NO_INLINE
/* For better stack traces */
1842 sweep_strings (void)
1844 struct string_block
*b
, *next
;
1845 struct string_block
*live_blocks
= NULL
;
1847 string_free_list
= NULL
;
1848 total_strings
= total_free_strings
= 0;
1849 total_string_bytes
= 0;
1851 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1852 for (b
= string_blocks
; b
; b
= next
)
1855 struct Lisp_String
*free_list_before
= string_free_list
;
1859 for (i
= 0; i
< STRING_BLOCK_SIZE
; ++i
)
1861 struct Lisp_String
*s
= b
->strings
+ i
;
1865 /* String was not on free-list before. */
1866 if (STRING_MARKED_P (s
))
1868 /* String is live; unmark it and its intervals. */
1871 /* Do not use string_(set|get)_intervals here. */
1872 s
->intervals
= balance_intervals (s
->intervals
);
1875 total_string_bytes
+= STRING_BYTES (s
);
1879 /* String is dead. Put it on the free-list. */
1880 sdata
*data
= SDATA_OF_STRING (s
);
1882 /* Save the size of S in its sdata so that we know
1883 how large that is. Reset the sdata's string
1884 back-pointer so that we know it's free. */
1885 #ifdef GC_CHECK_STRING_BYTES
1886 if (string_bytes (s
) != SDATA_NBYTES (data
))
1889 data
->n
.nbytes
= STRING_BYTES (s
);
1891 data
->string
= NULL
;
1893 /* Reset the strings's `data' member so that we
1897 /* Put the string on the free-list. */
1898 NEXT_FREE_LISP_STRING (s
) = string_free_list
;
1899 string_free_list
= s
;
1905 /* S was on the free-list before. Put it there again. */
1906 NEXT_FREE_LISP_STRING (s
) = string_free_list
;
1907 string_free_list
= s
;
1912 /* Free blocks that contain free Lisp_Strings only, except
1913 the first two of them. */
1914 if (nfree
== STRING_BLOCK_SIZE
1915 && total_free_strings
> STRING_BLOCK_SIZE
)
1918 string_free_list
= free_list_before
;
1922 total_free_strings
+= nfree
;
1923 b
->next
= live_blocks
;
1928 check_string_free_list ();
1930 string_blocks
= live_blocks
;
1931 free_large_strings ();
1932 compact_small_strings ();
1934 check_string_free_list ();
1938 /* Free dead large strings. */
1941 free_large_strings (void)
1943 struct sblock
*b
, *next
;
1944 struct sblock
*live_blocks
= NULL
;
1946 for (b
= large_sblocks
; b
; b
= next
)
1950 if (b
->data
[0].string
== NULL
)
1954 b
->next
= live_blocks
;
1959 large_sblocks
= live_blocks
;
1963 /* Compact data of small strings. Free sblocks that don't contain
1964 data of live strings after compaction. */
1967 compact_small_strings (void)
1969 struct sblock
*b
, *tb
, *next
;
1970 sdata
*from
, *to
, *end
, *tb_end
;
1971 sdata
*to_end
, *from_end
;
1973 /* TB is the sblock we copy to, TO is the sdata within TB we copy
1974 to, and TB_END is the end of TB. */
1976 tb_end
= (sdata
*) ((char *) tb
+ SBLOCK_SIZE
);
1979 /* Step through the blocks from the oldest to the youngest. We
1980 expect that old blocks will stabilize over time, so that less
1981 copying will happen this way. */
1982 for (b
= oldest_sblock
; b
; b
= b
->next
)
1985 eassert ((char *) end
<= (char *) b
+ SBLOCK_SIZE
);
1987 for (from
= b
->data
; from
< end
; from
= from_end
)
1989 /* Compute the next FROM here because copying below may
1990 overwrite data we need to compute it. */
1992 struct Lisp_String
*s
= from
->string
;
1994 #ifdef GC_CHECK_STRING_BYTES
1995 /* Check that the string size recorded in the string is the
1996 same as the one recorded in the sdata structure. */
1997 if (s
&& string_bytes (s
) != SDATA_NBYTES (from
))
1999 #endif /* GC_CHECK_STRING_BYTES */
2001 nbytes
= s
? STRING_BYTES (s
) : SDATA_NBYTES (from
);
2002 eassert (nbytes
<= LARGE_STRING_BYTES
);
2004 nbytes
= SDATA_SIZE (nbytes
);
2005 from_end
= (sdata
*) ((char *) from
+ nbytes
+ GC_STRING_EXTRA
);
2007 #ifdef GC_CHECK_STRING_OVERRUN
2008 if (memcmp (string_overrun_cookie
,
2009 (char *) from_end
- GC_STRING_OVERRUN_COOKIE_SIZE
,
2010 GC_STRING_OVERRUN_COOKIE_SIZE
))
2014 /* Non-NULL S means it's alive. Copy its data. */
2017 /* If TB is full, proceed with the next sblock. */
2018 to_end
= (sdata
*) ((char *) to
+ nbytes
+ GC_STRING_EXTRA
);
2019 if (to_end
> tb_end
)
2023 tb_end
= (sdata
*) ((char *) tb
+ SBLOCK_SIZE
);
2025 to_end
= (sdata
*) ((char *) to
+ nbytes
+ GC_STRING_EXTRA
);
2028 /* Copy, and update the string's `data' pointer. */
2031 eassert (tb
!= b
|| to
< from
);
2032 memmove (to
, from
, nbytes
+ GC_STRING_EXTRA
);
2033 to
->string
->data
= SDATA_DATA (to
);
2036 /* Advance past the sdata we copied to. */
2042 /* The rest of the sblocks following TB don't contain live data, so
2043 we can free them. */
2044 for (b
= tb
->next
; b
; b
= next
)
2052 current_sblock
= tb
;
2056 string_overflow (void)
2058 error ("Maximum string size exceeded");
2061 DEFUN ("make-string", Fmake_string
, Smake_string
, 2, 2, 0,
2062 doc
: /* Return a newly created string of length LENGTH, with INIT in each element.
2063 LENGTH must be an integer.
2064 INIT must be an integer that represents a character. */)
2065 (Lisp_Object length
, Lisp_Object init
)
2067 register Lisp_Object val
;
2071 CHECK_NATNUM (length
);
2072 CHECK_CHARACTER (init
);
2074 c
= XFASTINT (init
);
2075 if (ASCII_CHAR_P (c
))
2077 nbytes
= XINT (length
);
2078 val
= make_uninit_string (nbytes
);
2079 memset (SDATA (val
), c
, nbytes
);
2080 SDATA (val
)[nbytes
] = 0;
2084 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
2085 ptrdiff_t len
= CHAR_STRING (c
, str
);
2086 EMACS_INT string_len
= XINT (length
);
2087 unsigned char *p
, *beg
, *end
;
2089 if (string_len
> STRING_BYTES_MAX
/ len
)
2091 nbytes
= len
* string_len
;
2092 val
= make_uninit_multibyte_string (string_len
, nbytes
);
2093 for (beg
= SDATA (val
), p
= beg
, end
= beg
+ nbytes
; p
< end
; p
+= len
)
2095 /* First time we just copy `str' to the data of `val'. */
2097 memcpy (p
, str
, len
);
2100 /* Next time we copy largest possible chunk from
2101 initialized to uninitialized part of `val'. */
2102 len
= min (p
- beg
, end
- p
);
2103 memcpy (p
, beg
, len
);
2112 /* Fill A with 1 bits if INIT is non-nil, and with 0 bits otherwise.
2116 bool_vector_fill (Lisp_Object a
, Lisp_Object init
)
2118 EMACS_INT nbits
= bool_vector_size (a
);
2121 unsigned char *data
= bool_vector_uchar_data (a
);
2122 int pattern
= NILP (init
) ? 0 : (1 << BOOL_VECTOR_BITS_PER_CHAR
) - 1;
2123 ptrdiff_t nbytes
= bool_vector_bytes (nbits
);
2124 int last_mask
= ~ (~0u << ((nbits
- 1) % BOOL_VECTOR_BITS_PER_CHAR
+ 1));
2125 memset (data
, pattern
, nbytes
- 1);
2126 data
[nbytes
- 1] = pattern
& last_mask
;
2131 /* Return a newly allocated, uninitialized bool vector of size NBITS. */
2134 make_uninit_bool_vector (EMACS_INT nbits
)
2137 EMACS_INT words
= bool_vector_words (nbits
);
2138 EMACS_INT word_bytes
= words
* sizeof (bits_word
);
2139 EMACS_INT needed_elements
= ((bool_header_size
- header_size
+ word_bytes
2142 struct Lisp_Bool_Vector
*p
2143 = (struct Lisp_Bool_Vector
*) allocate_vector (needed_elements
);
2144 XSETVECTOR (val
, p
);
2145 XSETPVECTYPESIZE (XVECTOR (val
), PVEC_BOOL_VECTOR
, 0, 0);
2148 /* Clear padding at the end. */
2150 p
->data
[words
- 1] = 0;
2155 DEFUN ("make-bool-vector", Fmake_bool_vector
, Smake_bool_vector
, 2, 2, 0,
2156 doc
: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2157 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2158 (Lisp_Object length
, Lisp_Object init
)
2162 CHECK_NATNUM (length
);
2163 val
= make_uninit_bool_vector (XFASTINT (length
));
2164 return bool_vector_fill (val
, init
);
2167 DEFUN ("bool-vector", Fbool_vector
, Sbool_vector
, 0, MANY
, 0,
2168 doc
: /* Return a new bool-vector with specified arguments as elements.
2169 Any number of arguments, even zero arguments, are allowed.
2170 usage: (bool-vector &rest OBJECTS) */)
2171 (ptrdiff_t nargs
, Lisp_Object
*args
)
2176 vector
= make_uninit_bool_vector (nargs
);
2177 for (i
= 0; i
< nargs
; i
++)
2178 bool_vector_set (vector
, i
, !NILP (args
[i
]));
2183 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2184 of characters from the contents. This string may be unibyte or
2185 multibyte, depending on the contents. */
2188 make_string (const char *contents
, ptrdiff_t nbytes
)
2190 register Lisp_Object val
;
2191 ptrdiff_t nchars
, multibyte_nbytes
;
2193 parse_str_as_multibyte ((const unsigned char *) contents
, nbytes
,
2194 &nchars
, &multibyte_nbytes
);
2195 if (nbytes
== nchars
|| nbytes
!= multibyte_nbytes
)
2196 /* CONTENTS contains no multibyte sequences or contains an invalid
2197 multibyte sequence. We must make unibyte string. */
2198 val
= make_unibyte_string (contents
, nbytes
);
2200 val
= make_multibyte_string (contents
, nchars
, nbytes
);
2204 /* Make a unibyte string from LENGTH bytes at CONTENTS. */
2207 make_unibyte_string (const char *contents
, ptrdiff_t length
)
2209 register Lisp_Object val
;
2210 val
= make_uninit_string (length
);
2211 memcpy (SDATA (val
), contents
, length
);
2216 /* Make a multibyte string from NCHARS characters occupying NBYTES
2217 bytes at CONTENTS. */
2220 make_multibyte_string (const char *contents
,
2221 ptrdiff_t nchars
, ptrdiff_t nbytes
)
2223 register Lisp_Object val
;
2224 val
= make_uninit_multibyte_string (nchars
, nbytes
);
2225 memcpy (SDATA (val
), contents
, nbytes
);
2230 /* Make a string from NCHARS characters occupying NBYTES bytes at
2231 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2234 make_string_from_bytes (const char *contents
,
2235 ptrdiff_t nchars
, ptrdiff_t nbytes
)
2237 register Lisp_Object val
;
2238 val
= make_uninit_multibyte_string (nchars
, nbytes
);
2239 memcpy (SDATA (val
), contents
, nbytes
);
2240 if (SBYTES (val
) == SCHARS (val
))
2241 STRING_SET_UNIBYTE (val
);
2246 /* Make a string from NCHARS characters occupying NBYTES bytes at
2247 CONTENTS. The argument MULTIBYTE controls whether to label the
2248 string as multibyte. If NCHARS is negative, it counts the number of
2249 characters by itself. */
2252 make_specified_string (const char *contents
,
2253 ptrdiff_t nchars
, ptrdiff_t nbytes
, bool multibyte
)
2260 nchars
= multibyte_chars_in_text ((const unsigned char *) contents
,
2265 val
= make_uninit_multibyte_string (nchars
, nbytes
);
2266 memcpy (SDATA (val
), contents
, nbytes
);
2268 STRING_SET_UNIBYTE (val
);
2273 /* Return a unibyte Lisp_String set up to hold LENGTH characters
2274 occupying LENGTH bytes. */
2277 make_uninit_string (EMACS_INT length
)
2282 return empty_unibyte_string
;
2283 val
= make_uninit_multibyte_string (length
, length
);
2284 STRING_SET_UNIBYTE (val
);
2289 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2290 which occupy NBYTES bytes. */
2293 make_uninit_multibyte_string (EMACS_INT nchars
, EMACS_INT nbytes
)
2296 struct Lisp_String
*s
;
2301 return empty_multibyte_string
;
2303 s
= allocate_string ();
2304 s
->intervals
= NULL
;
2305 allocate_string_data (s
, nchars
, nbytes
);
2306 XSETSTRING (string
, s
);
2307 string_chars_consed
+= nbytes
;
2311 /* Print arguments to BUF according to a FORMAT, then return
2312 a Lisp_String initialized with the data from BUF. */
2315 make_formatted_string (char *buf
, const char *format
, ...)
2320 va_start (ap
, format
);
2321 length
= vsprintf (buf
, format
, ap
);
2323 return make_string (buf
, length
);
2327 /***********************************************************************
2329 ***********************************************************************/
2331 /* We store float cells inside of float_blocks, allocating a new
2332 float_block with malloc whenever necessary. Float cells reclaimed
2333 by GC are put on a free list to be reallocated before allocating
2334 any new float cells from the latest float_block. */
2336 #define FLOAT_BLOCK_SIZE \
2337 (((BLOCK_BYTES - sizeof (struct float_block *) \
2338 /* The compiler might add padding at the end. */ \
2339 - (sizeof (struct Lisp_Float) - sizeof (bits_word))) * CHAR_BIT) \
2340 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2342 #define GETMARKBIT(block,n) \
2343 (((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2344 >> ((n) % BITS_PER_BITS_WORD)) \
2347 #define SETMARKBIT(block,n) \
2348 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2349 |= (bits_word) 1 << ((n) % BITS_PER_BITS_WORD))
2351 #define UNSETMARKBIT(block,n) \
2352 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2353 &= ~((bits_word) 1 << ((n) % BITS_PER_BITS_WORD)))
2355 #define FLOAT_BLOCK(fptr) \
2356 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2358 #define FLOAT_INDEX(fptr) \
2359 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2363 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2364 struct Lisp_Float floats
[FLOAT_BLOCK_SIZE
];
2365 bits_word gcmarkbits
[1 + FLOAT_BLOCK_SIZE
/ BITS_PER_BITS_WORD
];
2366 struct float_block
*next
;
2369 #define FLOAT_MARKED_P(fptr) \
2370 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2372 #define FLOAT_MARK(fptr) \
2373 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2375 #define FLOAT_UNMARK(fptr) \
2376 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2378 /* Current float_block. */
2380 static struct float_block
*float_block
;
2382 /* Index of first unused Lisp_Float in the current float_block. */
2384 static int float_block_index
= FLOAT_BLOCK_SIZE
;
2386 /* Free-list of Lisp_Floats. */
2388 static struct Lisp_Float
*float_free_list
;
2390 /* Return a new float object with value FLOAT_VALUE. */
2393 make_float (double float_value
)
2395 register Lisp_Object val
;
2399 if (float_free_list
)
2401 /* We use the data field for chaining the free list
2402 so that we won't use the same field that has the mark bit. */
2403 XSETFLOAT (val
, float_free_list
);
2404 float_free_list
= float_free_list
->u
.chain
;
2408 if (float_block_index
== FLOAT_BLOCK_SIZE
)
2410 struct float_block
*new
2411 = lisp_align_malloc (sizeof *new, MEM_TYPE_FLOAT
);
2412 new->next
= float_block
;
2413 memset (new->gcmarkbits
, 0, sizeof new->gcmarkbits
);
2415 float_block_index
= 0;
2416 total_free_floats
+= FLOAT_BLOCK_SIZE
;
2418 XSETFLOAT (val
, &float_block
->floats
[float_block_index
]);
2419 float_block_index
++;
2422 MALLOC_UNBLOCK_INPUT
;
2424 XFLOAT_INIT (val
, float_value
);
2425 eassert (!FLOAT_MARKED_P (XFLOAT (val
)));
2426 consing_since_gc
+= sizeof (struct Lisp_Float
);
2428 total_free_floats
--;
2434 /***********************************************************************
2436 ***********************************************************************/
2438 /* We store cons cells inside of cons_blocks, allocating a new
2439 cons_block with malloc whenever necessary. Cons cells reclaimed by
2440 GC are put on a free list to be reallocated before allocating
2441 any new cons cells from the latest cons_block. */
2443 #define CONS_BLOCK_SIZE \
2444 (((BLOCK_BYTES - sizeof (struct cons_block *) \
2445 /* The compiler might add padding at the end. */ \
2446 - (sizeof (struct Lisp_Cons) - sizeof (bits_word))) * CHAR_BIT) \
2447 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2449 #define CONS_BLOCK(fptr) \
2450 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2452 #define CONS_INDEX(fptr) \
2453 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2457 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2458 struct Lisp_Cons conses
[CONS_BLOCK_SIZE
];
2459 bits_word gcmarkbits
[1 + CONS_BLOCK_SIZE
/ BITS_PER_BITS_WORD
];
2460 struct cons_block
*next
;
2463 #define CONS_MARKED_P(fptr) \
2464 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2466 #define CONS_MARK(fptr) \
2467 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2469 #define CONS_UNMARK(fptr) \
2470 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2472 /* Current cons_block. */
2474 static struct cons_block
*cons_block
;
2476 /* Index of first unused Lisp_Cons in the current block. */
2478 static int cons_block_index
= CONS_BLOCK_SIZE
;
2480 /* Free-list of Lisp_Cons structures. */
2482 static struct Lisp_Cons
*cons_free_list
;
2484 /* Explicitly free a cons cell by putting it on the free-list. */
2487 free_cons (struct Lisp_Cons
*ptr
)
2489 ptr
->u
.chain
= cons_free_list
;
2491 cons_free_list
= ptr
;
2492 consing_since_gc
-= sizeof *ptr
;
2493 total_free_conses
++;
2496 DEFUN ("cons", Fcons
, Scons
, 2, 2, 0,
2497 doc
: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2498 (Lisp_Object car
, Lisp_Object cdr
)
2500 register Lisp_Object val
;
2506 /* We use the cdr for chaining the free list
2507 so that we won't use the same field that has the mark bit. */
2508 XSETCONS (val
, cons_free_list
);
2509 cons_free_list
= cons_free_list
->u
.chain
;
2513 if (cons_block_index
== CONS_BLOCK_SIZE
)
2515 struct cons_block
*new
2516 = lisp_align_malloc (sizeof *new, MEM_TYPE_CONS
);
2517 memset (new->gcmarkbits
, 0, sizeof new->gcmarkbits
);
2518 new->next
= cons_block
;
2520 cons_block_index
= 0;
2521 total_free_conses
+= CONS_BLOCK_SIZE
;
2523 XSETCONS (val
, &cons_block
->conses
[cons_block_index
]);
2527 MALLOC_UNBLOCK_INPUT
;
2531 eassert (!CONS_MARKED_P (XCONS (val
)));
2532 consing_since_gc
+= sizeof (struct Lisp_Cons
);
2533 total_free_conses
--;
2534 cons_cells_consed
++;
2538 #ifdef GC_CHECK_CONS_LIST
2539 /* Get an error now if there's any junk in the cons free list. */
2541 check_cons_list (void)
2543 struct Lisp_Cons
*tail
= cons_free_list
;
2546 tail
= tail
->u
.chain
;
2550 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2553 list1 (Lisp_Object arg1
)
2555 return Fcons (arg1
, Qnil
);
2559 list2 (Lisp_Object arg1
, Lisp_Object arg2
)
2561 return Fcons (arg1
, Fcons (arg2
, Qnil
));
2566 list3 (Lisp_Object arg1
, Lisp_Object arg2
, Lisp_Object arg3
)
2568 return Fcons (arg1
, Fcons (arg2
, Fcons (arg3
, Qnil
)));
2573 list4 (Lisp_Object arg1
, Lisp_Object arg2
, Lisp_Object arg3
, Lisp_Object arg4
)
2575 return Fcons (arg1
, Fcons (arg2
, Fcons (arg3
, Fcons (arg4
, Qnil
))));
2580 list5 (Lisp_Object arg1
, Lisp_Object arg2
, Lisp_Object arg3
, Lisp_Object arg4
, Lisp_Object arg5
)
2582 return Fcons (arg1
, Fcons (arg2
, Fcons (arg3
, Fcons (arg4
,
2583 Fcons (arg5
, Qnil
)))));
2586 /* Make a list of COUNT Lisp_Objects, where ARG is the
2587 first one. Allocate conses from pure space if TYPE
2588 is CONSTYPE_PURE, or allocate as usual if type is CONSTYPE_HEAP. */
2591 listn (enum constype type
, ptrdiff_t count
, Lisp_Object arg
, ...)
2593 Lisp_Object (*cons
) (Lisp_Object
, Lisp_Object
);
2596 case CONSTYPE_PURE
: cons
= pure_cons
; break;
2597 case CONSTYPE_HEAP
: cons
= Fcons
; break;
2598 default: emacs_abort ();
2601 eassume (0 < count
);
2602 Lisp_Object val
= cons (arg
, Qnil
);
2603 Lisp_Object tail
= val
;
2607 for (ptrdiff_t i
= 1; i
< count
; i
++)
2609 Lisp_Object elem
= cons (va_arg (ap
, Lisp_Object
), Qnil
);
2610 XSETCDR (tail
, elem
);
2618 DEFUN ("list", Flist
, Slist
, 0, MANY
, 0,
2619 doc
: /* Return a newly created list with specified arguments as elements.
2620 Any number of arguments, even zero arguments, are allowed.
2621 usage: (list &rest OBJECTS) */)
2622 (ptrdiff_t nargs
, Lisp_Object
*args
)
2624 register Lisp_Object val
;
2630 val
= Fcons (args
[nargs
], val
);
2636 DEFUN ("make-list", Fmake_list
, Smake_list
, 2, 2, 0,
2637 doc
: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2638 (register Lisp_Object length
, Lisp_Object init
)
2640 register Lisp_Object val
;
2641 register EMACS_INT size
;
2643 CHECK_NATNUM (length
);
2644 size
= XFASTINT (length
);
2649 val
= Fcons (init
, val
);
2654 val
= Fcons (init
, val
);
2659 val
= Fcons (init
, val
);
2664 val
= Fcons (init
, val
);
2669 val
= Fcons (init
, val
);
2684 /***********************************************************************
2686 ***********************************************************************/
2688 /* Sometimes a vector's contents are merely a pointer internally used
2689 in vector allocation code. On the rare platforms where a null
2690 pointer cannot be tagged, represent it with a Lisp 0.
2691 Usually you don't want to touch this. */
2693 static struct Lisp_Vector
*
2694 next_vector (struct Lisp_Vector
*v
)
2696 return XUNTAG (v
->contents
[0], Lisp_Int0
);
2700 set_next_vector (struct Lisp_Vector
*v
, struct Lisp_Vector
*p
)
2702 v
->contents
[0] = make_lisp_ptr (p
, Lisp_Int0
);
2705 /* This value is balanced well enough to avoid too much internal overhead
2706 for the most common cases; it's not required to be a power of two, but
2707 it's expected to be a mult-of-ROUNDUP_SIZE (see below). */
2709 #define VECTOR_BLOCK_SIZE 4096
2713 /* Alignment of struct Lisp_Vector objects. */
2714 vector_alignment
= COMMON_MULTIPLE (ALIGNOF_STRUCT_LISP_VECTOR
,
2717 /* Vector size requests are a multiple of this. */
2718 roundup_size
= COMMON_MULTIPLE (vector_alignment
, word_size
)
2721 /* Verify assumptions described above. */
2722 verify ((VECTOR_BLOCK_SIZE
% roundup_size
) == 0);
2723 verify (VECTOR_BLOCK_SIZE
<= (1 << PSEUDOVECTOR_SIZE_BITS
));
2725 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at compile time. */
2726 #define vroundup_ct(x) ROUNDUP (x, roundup_size)
2727 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at runtime. */
2728 #define vroundup(x) (eassume ((x) >= 0), vroundup_ct (x))
2730 /* Rounding helps to maintain alignment constraints if USE_LSB_TAG. */
2732 #define VECTOR_BLOCK_BYTES (VECTOR_BLOCK_SIZE - vroundup_ct (sizeof (void *)))
2734 /* Size of the minimal vector allocated from block. */
2736 #define VBLOCK_BYTES_MIN vroundup_ct (header_size + sizeof (Lisp_Object))
2738 /* Size of the largest vector allocated from block. */
2740 #define VBLOCK_BYTES_MAX \
2741 vroundup ((VECTOR_BLOCK_BYTES / 2) - word_size)
2743 /* We maintain one free list for each possible block-allocated
2744 vector size, and this is the number of free lists we have. */
2746 #define VECTOR_MAX_FREE_LIST_INDEX \
2747 ((VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN) / roundup_size + 1)
2749 /* Common shortcut to advance vector pointer over a block data. */
2751 #define ADVANCE(v, nbytes) ((struct Lisp_Vector *) ((char *) (v) + (nbytes)))
2753 /* Common shortcut to calculate NBYTES-vector index in VECTOR_FREE_LISTS. */
2755 #define VINDEX(nbytes) (((nbytes) - VBLOCK_BYTES_MIN) / roundup_size)
2757 /* Common shortcut to setup vector on a free list. */
2759 #define SETUP_ON_FREE_LIST(v, nbytes, tmp) \
2761 (tmp) = ((nbytes - header_size) / word_size); \
2762 XSETPVECTYPESIZE (v, PVEC_FREE, 0, (tmp)); \
2763 eassert ((nbytes) % roundup_size == 0); \
2764 (tmp) = VINDEX (nbytes); \
2765 eassert ((tmp) < VECTOR_MAX_FREE_LIST_INDEX); \
2766 set_next_vector (v, vector_free_lists[tmp]); \
2767 vector_free_lists[tmp] = (v); \
2768 total_free_vector_slots += (nbytes) / word_size; \
2771 /* This internal type is used to maintain the list of large vectors
2772 which are allocated at their own, e.g. outside of vector blocks.
2774 struct large_vector itself cannot contain a struct Lisp_Vector, as
2775 the latter contains a flexible array member and C99 does not allow
2776 such structs to be nested. Instead, each struct large_vector
2777 object LV is followed by a struct Lisp_Vector, which is at offset
2778 large_vector_offset from LV, and whose address is therefore
2779 large_vector_vec (&LV). */
2783 struct large_vector
*next
;
2788 large_vector_offset
= ROUNDUP (sizeof (struct large_vector
), vector_alignment
)
2791 static struct Lisp_Vector
*
2792 large_vector_vec (struct large_vector
*p
)
2794 return (struct Lisp_Vector
*) ((char *) p
+ large_vector_offset
);
2797 /* This internal type is used to maintain an underlying storage
2798 for small vectors. */
2802 char data
[VECTOR_BLOCK_BYTES
];
2803 struct vector_block
*next
;
2806 /* Chain of vector blocks. */
2808 static struct vector_block
*vector_blocks
;
2810 /* Vector free lists, where NTH item points to a chain of free
2811 vectors of the same NBYTES size, so NTH == VINDEX (NBYTES). */
2813 static struct Lisp_Vector
*vector_free_lists
[VECTOR_MAX_FREE_LIST_INDEX
];
2815 /* Singly-linked list of large vectors. */
2817 static struct large_vector
*large_vectors
;
2819 /* The only vector with 0 slots, allocated from pure space. */
2821 Lisp_Object zero_vector
;
2823 /* Number of live vectors. */
2825 static EMACS_INT total_vectors
;
2827 /* Total size of live and free vectors, in Lisp_Object units. */
2829 static EMACS_INT total_vector_slots
, total_free_vector_slots
;
2831 /* Get a new vector block. */
2833 static struct vector_block
*
2834 allocate_vector_block (void)
2836 struct vector_block
*block
= xmalloc (sizeof *block
);
2838 #ifndef GC_MALLOC_CHECK
2839 mem_insert (block
->data
, block
->data
+ VECTOR_BLOCK_BYTES
,
2840 MEM_TYPE_VECTOR_BLOCK
);
2843 block
->next
= vector_blocks
;
2844 vector_blocks
= block
;
2848 /* Called once to initialize vector allocation. */
2853 zero_vector
= make_pure_vector (0);
2856 /* Allocate vector from a vector block. */
2858 static struct Lisp_Vector
*
2859 allocate_vector_from_block (size_t nbytes
)
2861 struct Lisp_Vector
*vector
;
2862 struct vector_block
*block
;
2863 size_t index
, restbytes
;
2865 eassert (VBLOCK_BYTES_MIN
<= nbytes
&& nbytes
<= VBLOCK_BYTES_MAX
);
2866 eassert (nbytes
% roundup_size
== 0);
2868 /* First, try to allocate from a free list
2869 containing vectors of the requested size. */
2870 index
= VINDEX (nbytes
);
2871 if (vector_free_lists
[index
])
2873 vector
= vector_free_lists
[index
];
2874 vector_free_lists
[index
] = next_vector (vector
);
2875 total_free_vector_slots
-= nbytes
/ word_size
;
2879 /* Next, check free lists containing larger vectors. Since
2880 we will split the result, we should have remaining space
2881 large enough to use for one-slot vector at least. */
2882 for (index
= VINDEX (nbytes
+ VBLOCK_BYTES_MIN
);
2883 index
< VECTOR_MAX_FREE_LIST_INDEX
; index
++)
2884 if (vector_free_lists
[index
])
2886 /* This vector is larger than requested. */
2887 vector
= vector_free_lists
[index
];
2888 vector_free_lists
[index
] = next_vector (vector
);
2889 total_free_vector_slots
-= nbytes
/ word_size
;
2891 /* Excess bytes are used for the smaller vector,
2892 which should be set on an appropriate free list. */
2893 restbytes
= index
* roundup_size
+ VBLOCK_BYTES_MIN
- nbytes
;
2894 eassert (restbytes
% roundup_size
== 0);
2895 SETUP_ON_FREE_LIST (ADVANCE (vector
, nbytes
), restbytes
, index
);
2899 /* Finally, need a new vector block. */
2900 block
= allocate_vector_block ();
2902 /* New vector will be at the beginning of this block. */
2903 vector
= (struct Lisp_Vector
*) block
->data
;
2905 /* If the rest of space from this block is large enough
2906 for one-slot vector at least, set up it on a free list. */
2907 restbytes
= VECTOR_BLOCK_BYTES
- nbytes
;
2908 if (restbytes
>= VBLOCK_BYTES_MIN
)
2910 eassert (restbytes
% roundup_size
== 0);
2911 SETUP_ON_FREE_LIST (ADVANCE (vector
, nbytes
), restbytes
, index
);
2916 /* Nonzero if VECTOR pointer is valid pointer inside BLOCK. */
2918 #define VECTOR_IN_BLOCK(vector, block) \
2919 ((char *) (vector) <= (block)->data \
2920 + VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN)
2922 /* Return the memory footprint of V in bytes. */
2925 vector_nbytes (struct Lisp_Vector
*v
)
2927 ptrdiff_t size
= v
->header
.size
& ~ARRAY_MARK_FLAG
;
2930 if (size
& PSEUDOVECTOR_FLAG
)
2932 if (PSEUDOVECTOR_TYPEP (&v
->header
, PVEC_BOOL_VECTOR
))
2934 struct Lisp_Bool_Vector
*bv
= (struct Lisp_Bool_Vector
*) v
;
2935 ptrdiff_t word_bytes
= (bool_vector_words (bv
->size
)
2936 * sizeof (bits_word
));
2937 ptrdiff_t boolvec_bytes
= bool_header_size
+ word_bytes
;
2938 verify (header_size
<= bool_header_size
);
2939 nwords
= (boolvec_bytes
- header_size
+ word_size
- 1) / word_size
;
2942 nwords
= ((size
& PSEUDOVECTOR_SIZE_MASK
)
2943 + ((size
& PSEUDOVECTOR_REST_MASK
)
2944 >> PSEUDOVECTOR_SIZE_BITS
));
2948 return vroundup (header_size
+ word_size
* nwords
);
2951 /* Release extra resources still in use by VECTOR, which may be any
2952 vector-like object. For now, this is used just to free data in
2956 cleanup_vector (struct Lisp_Vector
*vector
)
2958 detect_suspicious_free (vector
);
2959 if (PSEUDOVECTOR_TYPEP (&vector
->header
, PVEC_FONT
)
2960 && ((vector
->header
.size
& PSEUDOVECTOR_SIZE_MASK
)
2961 == FONT_OBJECT_MAX
))
2963 struct font_driver
*drv
= ((struct font
*) vector
)->driver
;
2965 /* The font driver might sometimes be NULL, e.g. if Emacs was
2966 interrupted before it had time to set it up. */
2969 /* Attempt to catch subtle bugs like Bug#16140. */
2970 eassert (valid_font_driver (drv
));
2971 drv
->close ((struct font
*) vector
);
2976 /* Reclaim space used by unmarked vectors. */
2978 NO_INLINE
/* For better stack traces */
2980 sweep_vectors (void)
2982 struct vector_block
*block
, **bprev
= &vector_blocks
;
2983 struct large_vector
*lv
, **lvprev
= &large_vectors
;
2984 struct Lisp_Vector
*vector
, *next
;
2986 total_vectors
= total_vector_slots
= total_free_vector_slots
= 0;
2987 memset (vector_free_lists
, 0, sizeof (vector_free_lists
));
2989 /* Looking through vector blocks. */
2991 for (block
= vector_blocks
; block
; block
= *bprev
)
2993 bool free_this_block
= 0;
2996 for (vector
= (struct Lisp_Vector
*) block
->data
;
2997 VECTOR_IN_BLOCK (vector
, block
); vector
= next
)
2999 if (VECTOR_MARKED_P (vector
))
3001 VECTOR_UNMARK (vector
);
3003 nbytes
= vector_nbytes (vector
);
3004 total_vector_slots
+= nbytes
/ word_size
;
3005 next
= ADVANCE (vector
, nbytes
);
3009 ptrdiff_t total_bytes
;
3011 cleanup_vector (vector
);
3012 nbytes
= vector_nbytes (vector
);
3013 total_bytes
= nbytes
;
3014 next
= ADVANCE (vector
, nbytes
);
3016 /* While NEXT is not marked, try to coalesce with VECTOR,
3017 thus making VECTOR of the largest possible size. */
3019 while (VECTOR_IN_BLOCK (next
, block
))
3021 if (VECTOR_MARKED_P (next
))
3023 cleanup_vector (next
);
3024 nbytes
= vector_nbytes (next
);
3025 total_bytes
+= nbytes
;
3026 next
= ADVANCE (next
, nbytes
);
3029 eassert (total_bytes
% roundup_size
== 0);
3031 if (vector
== (struct Lisp_Vector
*) block
->data
3032 && !VECTOR_IN_BLOCK (next
, block
))
3033 /* This block should be freed because all of its
3034 space was coalesced into the only free vector. */
3035 free_this_block
= 1;
3039 SETUP_ON_FREE_LIST (vector
, total_bytes
, tmp
);
3044 if (free_this_block
)
3046 *bprev
= block
->next
;
3047 #ifndef GC_MALLOC_CHECK
3048 mem_delete (mem_find (block
->data
));
3053 bprev
= &block
->next
;
3056 /* Sweep large vectors. */
3058 for (lv
= large_vectors
; lv
; lv
= *lvprev
)
3060 vector
= large_vector_vec (lv
);
3061 if (VECTOR_MARKED_P (vector
))
3063 VECTOR_UNMARK (vector
);
3065 if (vector
->header
.size
& PSEUDOVECTOR_FLAG
)
3067 /* All non-bool pseudovectors are small enough to be allocated
3068 from vector blocks. This code should be redesigned if some
3069 pseudovector type grows beyond VBLOCK_BYTES_MAX. */
3070 eassert (PSEUDOVECTOR_TYPEP (&vector
->header
, PVEC_BOOL_VECTOR
));
3071 total_vector_slots
+= vector_nbytes (vector
) / word_size
;
3075 += header_size
/ word_size
+ vector
->header
.size
;
3086 /* Value is a pointer to a newly allocated Lisp_Vector structure
3087 with room for LEN Lisp_Objects. */
3089 static struct Lisp_Vector
*
3090 allocate_vectorlike (ptrdiff_t len
)
3092 struct Lisp_Vector
*p
;
3097 p
= XVECTOR (zero_vector
);
3100 size_t nbytes
= header_size
+ len
* word_size
;
3102 #ifdef DOUG_LEA_MALLOC
3103 if (!mmap_lisp_allowed_p ())
3104 mallopt (M_MMAP_MAX
, 0);
3107 if (nbytes
<= VBLOCK_BYTES_MAX
)
3108 p
= allocate_vector_from_block (vroundup (nbytes
));
3111 struct large_vector
*lv
3112 = lisp_malloc ((large_vector_offset
+ header_size
3114 MEM_TYPE_VECTORLIKE
);
3115 lv
->next
= large_vectors
;
3117 p
= large_vector_vec (lv
);
3120 #ifdef DOUG_LEA_MALLOC
3121 if (!mmap_lisp_allowed_p ())
3122 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
);
3125 if (find_suspicious_object_in_range (p
, (char *) p
+ nbytes
))
3128 consing_since_gc
+= nbytes
;
3129 vector_cells_consed
+= len
;
3132 MALLOC_UNBLOCK_INPUT
;
3138 /* Allocate a vector with LEN slots. */
3140 struct Lisp_Vector
*
3141 allocate_vector (EMACS_INT len
)
3143 struct Lisp_Vector
*v
;
3144 ptrdiff_t nbytes_max
= min (PTRDIFF_MAX
, SIZE_MAX
);
3146 if (min ((nbytes_max
- header_size
) / word_size
, MOST_POSITIVE_FIXNUM
) < len
)
3147 memory_full (SIZE_MAX
);
3148 v
= allocate_vectorlike (len
);
3149 v
->header
.size
= len
;
3154 /* Allocate other vector-like structures. */
3156 struct Lisp_Vector
*
3157 allocate_pseudovector (int memlen
, int lisplen
,
3158 int zerolen
, enum pvec_type tag
)
3160 struct Lisp_Vector
*v
= allocate_vectorlike (memlen
);
3162 /* Catch bogus values. */
3163 eassert (0 <= tag
&& tag
<= PVEC_FONT
);
3164 eassert (0 <= lisplen
&& lisplen
<= zerolen
&& zerolen
<= memlen
);
3165 eassert (memlen
- lisplen
<= (1 << PSEUDOVECTOR_REST_BITS
) - 1);
3166 eassert (lisplen
<= (1 << PSEUDOVECTOR_SIZE_BITS
) - 1);
3168 /* Only the first LISPLEN slots will be traced normally by the GC. */
3169 memclear (v
->contents
, zerolen
* word_size
);
3170 XSETPVECTYPESIZE (v
, tag
, lisplen
, memlen
- lisplen
);
3175 allocate_buffer (void)
3177 struct buffer
*b
= lisp_malloc (sizeof *b
, MEM_TYPE_BUFFER
);
3179 BUFFER_PVEC_INIT (b
);
3180 /* Put B on the chain of all buffers including killed ones. */
3181 b
->next
= all_buffers
;
3183 /* Note that the rest fields of B are not initialized. */
3187 DEFUN ("make-vector", Fmake_vector
, Smake_vector
, 2, 2, 0,
3188 doc
: /* Return a newly created vector of length LENGTH, with each element being INIT.
3189 See also the function `vector'. */)
3190 (register Lisp_Object length
, Lisp_Object init
)
3193 register ptrdiff_t sizei
;
3194 register ptrdiff_t i
;
3195 register struct Lisp_Vector
*p
;
3197 CHECK_NATNUM (length
);
3199 p
= allocate_vector (XFASTINT (length
));
3200 sizei
= XFASTINT (length
);
3201 for (i
= 0; i
< sizei
; i
++)
3202 p
->contents
[i
] = init
;
3204 XSETVECTOR (vector
, p
);
3208 DEFUN ("vector", Fvector
, Svector
, 0, MANY
, 0,
3209 doc
: /* Return a newly created vector with specified arguments as elements.
3210 Any number of arguments, even zero arguments, are allowed.
3211 usage: (vector &rest OBJECTS) */)
3212 (ptrdiff_t nargs
, Lisp_Object
*args
)
3215 register Lisp_Object val
= make_uninit_vector (nargs
);
3216 register struct Lisp_Vector
*p
= XVECTOR (val
);
3218 for (i
= 0; i
< nargs
; i
++)
3219 p
->contents
[i
] = args
[i
];
3224 make_byte_code (struct Lisp_Vector
*v
)
3226 /* Don't allow the global zero_vector to become a byte code object. */
3227 eassert (0 < v
->header
.size
);
3229 if (v
->header
.size
> 1 && STRINGP (v
->contents
[1])
3230 && STRING_MULTIBYTE (v
->contents
[1]))
3231 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3232 earlier because they produced a raw 8-bit string for byte-code
3233 and now such a byte-code string is loaded as multibyte while
3234 raw 8-bit characters converted to multibyte form. Thus, now we
3235 must convert them back to the original unibyte form. */
3236 v
->contents
[1] = Fstring_as_unibyte (v
->contents
[1]);
3237 XSETPVECTYPE (v
, PVEC_COMPILED
);
3240 DEFUN ("make-byte-code", Fmake_byte_code
, Smake_byte_code
, 4, MANY
, 0,
3241 doc
: /* Create a byte-code object with specified arguments as elements.
3242 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3243 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3244 and (optional) INTERACTIVE-SPEC.
3245 The first four arguments are required; at most six have any
3247 The ARGLIST can be either like the one of `lambda', in which case the arguments
3248 will be dynamically bound before executing the byte code, or it can be an
3249 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3250 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3251 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3252 argument to catch the left-over arguments. If such an integer is used, the
3253 arguments will not be dynamically bound but will be instead pushed on the
3254 stack before executing the byte-code.
3255 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3256 (ptrdiff_t nargs
, Lisp_Object
*args
)
3259 register Lisp_Object val
= make_uninit_vector (nargs
);
3260 register struct Lisp_Vector
*p
= XVECTOR (val
);
3262 /* We used to purecopy everything here, if purify-flag was set. This worked
3263 OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
3264 dangerous, since make-byte-code is used during execution to build
3265 closures, so any closure built during the preload phase would end up
3266 copied into pure space, including its free variables, which is sometimes
3267 just wasteful and other times plainly wrong (e.g. those free vars may want
3270 for (i
= 0; i
< nargs
; i
++)
3271 p
->contents
[i
] = args
[i
];
3273 XSETCOMPILED (val
, p
);
3279 /***********************************************************************
3281 ***********************************************************************/
3283 /* Like struct Lisp_Symbol, but padded so that the size is a multiple
3284 of the required alignment. */
3286 union aligned_Lisp_Symbol
3288 struct Lisp_Symbol s
;
3289 unsigned char c
[(sizeof (struct Lisp_Symbol
) + GCALIGNMENT
- 1)
3293 /* Each symbol_block is just under 1020 bytes long, since malloc
3294 really allocates in units of powers of two and uses 4 bytes for its
3297 #define SYMBOL_BLOCK_SIZE \
3298 ((1020 - sizeof (struct symbol_block *)) / sizeof (union aligned_Lisp_Symbol))
3302 /* Place `symbols' first, to preserve alignment. */
3303 union aligned_Lisp_Symbol symbols
[SYMBOL_BLOCK_SIZE
];
3304 struct symbol_block
*next
;
3307 /* Current symbol block and index of first unused Lisp_Symbol
3310 static struct symbol_block
*symbol_block
;
3311 static int symbol_block_index
= SYMBOL_BLOCK_SIZE
;
3312 /* Pointer to the first symbol_block that contains pinned symbols.
3313 Tests for 24.4 showed that at dump-time, Emacs contains about 15K symbols,
3314 10K of which are pinned (and all but 250 of them are interned in obarray),
3315 whereas a "typical session" has in the order of 30K symbols.
3316 `symbol_block_pinned' lets mark_pinned_symbols scan only 15K symbols rather
3317 than 30K to find the 10K symbols we need to mark. */
3318 static struct symbol_block
*symbol_block_pinned
;
3320 /* List of free symbols. */
3322 static struct Lisp_Symbol
*symbol_free_list
;
3325 set_symbol_name (Lisp_Object sym
, Lisp_Object name
)
3327 XSYMBOL (sym
)->name
= name
;
3331 init_symbol (Lisp_Object val
, Lisp_Object name
)
3333 struct Lisp_Symbol
*p
= XSYMBOL (val
);
3334 set_symbol_name (val
, name
);
3335 set_symbol_plist (val
, Qnil
);
3336 p
->redirect
= SYMBOL_PLAINVAL
;
3337 SET_SYMBOL_VAL (p
, Qunbound
);
3338 set_symbol_function (val
, Qnil
);
3339 set_symbol_next (val
, NULL
);
3340 p
->gcmarkbit
= false;
3341 p
->interned
= SYMBOL_UNINTERNED
;
3343 p
->declared_special
= false;
3347 DEFUN ("make-symbol", Fmake_symbol
, Smake_symbol
, 1, 1, 0,
3348 doc
: /* Return a newly allocated uninterned symbol whose name is NAME.
3349 Its value is void, and its function definition and property list are nil. */)
3354 CHECK_STRING (name
);
3358 if (symbol_free_list
)
3360 XSETSYMBOL (val
, symbol_free_list
);
3361 symbol_free_list
= symbol_free_list
->next
;
3365 if (symbol_block_index
== SYMBOL_BLOCK_SIZE
)
3367 struct symbol_block
*new
3368 = lisp_malloc (sizeof *new, MEM_TYPE_SYMBOL
);
3369 new->next
= symbol_block
;
3371 symbol_block_index
= 0;
3372 total_free_symbols
+= SYMBOL_BLOCK_SIZE
;
3374 XSETSYMBOL (val
, &symbol_block
->symbols
[symbol_block_index
].s
);
3375 symbol_block_index
++;
3378 MALLOC_UNBLOCK_INPUT
;
3380 init_symbol (val
, name
);
3381 consing_since_gc
+= sizeof (struct Lisp_Symbol
);
3383 total_free_symbols
--;
3389 /***********************************************************************
3390 Marker (Misc) Allocation
3391 ***********************************************************************/
3393 /* Like union Lisp_Misc, but padded so that its size is a multiple of
3394 the required alignment. */
3396 union aligned_Lisp_Misc
3399 unsigned char c
[(sizeof (union Lisp_Misc
) + GCALIGNMENT
- 1)
3403 /* Allocation of markers and other objects that share that structure.
3404 Works like allocation of conses. */
3406 #define MARKER_BLOCK_SIZE \
3407 ((1020 - sizeof (struct marker_block *)) / sizeof (union aligned_Lisp_Misc))
3411 /* Place `markers' first, to preserve alignment. */
3412 union aligned_Lisp_Misc markers
[MARKER_BLOCK_SIZE
];
3413 struct marker_block
*next
;
3416 static struct marker_block
*marker_block
;
3417 static int marker_block_index
= MARKER_BLOCK_SIZE
;
3419 static union Lisp_Misc
*marker_free_list
;
3421 /* Return a newly allocated Lisp_Misc object of specified TYPE. */
3424 allocate_misc (enum Lisp_Misc_Type type
)
3430 if (marker_free_list
)
3432 XSETMISC (val
, marker_free_list
);
3433 marker_free_list
= marker_free_list
->u_free
.chain
;
3437 if (marker_block_index
== MARKER_BLOCK_SIZE
)
3439 struct marker_block
*new = lisp_malloc (sizeof *new, MEM_TYPE_MISC
);
3440 new->next
= marker_block
;
3442 marker_block_index
= 0;
3443 total_free_markers
+= MARKER_BLOCK_SIZE
;
3445 XSETMISC (val
, &marker_block
->markers
[marker_block_index
].m
);
3446 marker_block_index
++;
3449 MALLOC_UNBLOCK_INPUT
;
3451 --total_free_markers
;
3452 consing_since_gc
+= sizeof (union Lisp_Misc
);
3453 misc_objects_consed
++;
3454 XMISCANY (val
)->type
= type
;
3455 XMISCANY (val
)->gcmarkbit
= 0;
3459 /* Free a Lisp_Misc object. */
3462 free_misc (Lisp_Object misc
)
3464 XMISCANY (misc
)->type
= Lisp_Misc_Free
;
3465 XMISC (misc
)->u_free
.chain
= marker_free_list
;
3466 marker_free_list
= XMISC (misc
);
3467 consing_since_gc
-= sizeof (union Lisp_Misc
);
3468 total_free_markers
++;
3471 /* Verify properties of Lisp_Save_Value's representation
3472 that are assumed here and elsewhere. */
3474 verify (SAVE_UNUSED
== 0);
3475 verify (((SAVE_INTEGER
| SAVE_POINTER
| SAVE_FUNCPOINTER
| SAVE_OBJECT
)
3479 /* Return Lisp_Save_Value objects for the various combinations
3480 that callers need. */
3483 make_save_int_int_int (ptrdiff_t a
, ptrdiff_t b
, ptrdiff_t c
)
3485 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3486 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3487 p
->save_type
= SAVE_TYPE_INT_INT_INT
;
3488 p
->data
[0].integer
= a
;
3489 p
->data
[1].integer
= b
;
3490 p
->data
[2].integer
= c
;
3495 make_save_obj_obj_obj_obj (Lisp_Object a
, Lisp_Object b
, Lisp_Object c
,
3498 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3499 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3500 p
->save_type
= SAVE_TYPE_OBJ_OBJ_OBJ_OBJ
;
3501 p
->data
[0].object
= a
;
3502 p
->data
[1].object
= b
;
3503 p
->data
[2].object
= c
;
3504 p
->data
[3].object
= d
;
3509 make_save_ptr (void *a
)
3511 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3512 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3513 p
->save_type
= SAVE_POINTER
;
3514 p
->data
[0].pointer
= a
;
3519 make_save_ptr_int (void *a
, ptrdiff_t b
)
3521 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3522 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3523 p
->save_type
= SAVE_TYPE_PTR_INT
;
3524 p
->data
[0].pointer
= a
;
3525 p
->data
[1].integer
= b
;
3529 #if ! (defined USE_X_TOOLKIT || defined USE_GTK)
3531 make_save_ptr_ptr (void *a
, void *b
)
3533 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3534 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3535 p
->save_type
= SAVE_TYPE_PTR_PTR
;
3536 p
->data
[0].pointer
= a
;
3537 p
->data
[1].pointer
= b
;
3543 make_save_funcptr_ptr_obj (void (*a
) (void), void *b
, Lisp_Object c
)
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_FUNCPTR_PTR_OBJ
;
3548 p
->data
[0].funcpointer
= a
;
3549 p
->data
[1].pointer
= b
;
3550 p
->data
[2].object
= c
;
3554 /* Return a Lisp_Save_Value object that represents an array A
3555 of N Lisp objects. */
3558 make_save_memory (Lisp_Object
*a
, ptrdiff_t n
)
3560 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3561 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3562 p
->save_type
= SAVE_TYPE_MEMORY
;
3563 p
->data
[0].pointer
= a
;
3564 p
->data
[1].integer
= n
;
3568 /* Free a Lisp_Save_Value object. Do not use this function
3569 if SAVE contains pointer other than returned by xmalloc. */
3572 free_save_value (Lisp_Object save
)
3574 xfree (XSAVE_POINTER (save
, 0));
3578 /* Return a Lisp_Misc_Overlay object with specified START, END and PLIST. */
3581 build_overlay (Lisp_Object start
, Lisp_Object end
, Lisp_Object plist
)
3583 register Lisp_Object overlay
;
3585 overlay
= allocate_misc (Lisp_Misc_Overlay
);
3586 OVERLAY_START (overlay
) = start
;
3587 OVERLAY_END (overlay
) = end
;
3588 set_overlay_plist (overlay
, plist
);
3589 XOVERLAY (overlay
)->next
= NULL
;
3593 DEFUN ("make-marker", Fmake_marker
, Smake_marker
, 0, 0, 0,
3594 doc
: /* Return a newly allocated marker which does not point at any place. */)
3597 register Lisp_Object val
;
3598 register struct Lisp_Marker
*p
;
3600 val
= allocate_misc (Lisp_Misc_Marker
);
3606 p
->insertion_type
= 0;
3607 p
->need_adjustment
= 0;
3611 /* Return a newly allocated marker which points into BUF
3612 at character position CHARPOS and byte position BYTEPOS. */
3615 build_marker (struct buffer
*buf
, ptrdiff_t charpos
, ptrdiff_t bytepos
)
3618 struct Lisp_Marker
*m
;
3620 /* No dead buffers here. */
3621 eassert (BUFFER_LIVE_P (buf
));
3623 /* Every character is at least one byte. */
3624 eassert (charpos
<= bytepos
);
3626 obj
= allocate_misc (Lisp_Misc_Marker
);
3629 m
->charpos
= charpos
;
3630 m
->bytepos
= bytepos
;
3631 m
->insertion_type
= 0;
3632 m
->need_adjustment
= 0;
3633 m
->next
= BUF_MARKERS (buf
);
3634 BUF_MARKERS (buf
) = m
;
3638 /* Put MARKER back on the free list after using it temporarily. */
3641 free_marker (Lisp_Object marker
)
3643 unchain_marker (XMARKER (marker
));
3648 /* Return a newly created vector or string with specified arguments as
3649 elements. If all the arguments are characters that can fit
3650 in a string of events, make a string; otherwise, make a vector.
3652 Any number of arguments, even zero arguments, are allowed. */
3655 make_event_array (ptrdiff_t nargs
, Lisp_Object
*args
)
3659 for (i
= 0; i
< nargs
; i
++)
3660 /* The things that fit in a string
3661 are characters that are in 0...127,
3662 after discarding the meta bit and all the bits above it. */
3663 if (!INTEGERP (args
[i
])
3664 || (XINT (args
[i
]) & ~(-CHAR_META
)) >= 0200)
3665 return Fvector (nargs
, args
);
3667 /* Since the loop exited, we know that all the things in it are
3668 characters, so we can make a string. */
3672 result
= Fmake_string (make_number (nargs
), make_number (0));
3673 for (i
= 0; i
< nargs
; i
++)
3675 SSET (result
, i
, XINT (args
[i
]));
3676 /* Move the meta bit to the right place for a string char. */
3677 if (XINT (args
[i
]) & CHAR_META
)
3678 SSET (result
, i
, SREF (result
, i
) | 0x80);
3686 init_finalizer_list (struct Lisp_Finalizer
*head
)
3688 head
->prev
= head
->next
= head
;
3691 /* Insert FINALIZER before ELEMENT. */
3694 finalizer_insert (struct Lisp_Finalizer
*element
,
3695 struct Lisp_Finalizer
*finalizer
)
3697 eassert (finalizer
->prev
== NULL
);
3698 eassert (finalizer
->next
== NULL
);
3699 finalizer
->next
= element
;
3700 finalizer
->prev
= element
->prev
;
3701 finalizer
->prev
->next
= finalizer
;
3702 element
->prev
= finalizer
;
3706 unchain_finalizer (struct Lisp_Finalizer
*finalizer
)
3708 if (finalizer
->prev
!= NULL
)
3710 eassert (finalizer
->next
!= NULL
);
3711 finalizer
->prev
->next
= finalizer
->next
;
3712 finalizer
->next
->prev
= finalizer
->prev
;
3713 finalizer
->prev
= finalizer
->next
= NULL
;
3718 mark_finalizer_list (struct Lisp_Finalizer
*head
)
3720 for (struct Lisp_Finalizer
*finalizer
= head
->next
;
3722 finalizer
= finalizer
->next
)
3724 finalizer
->base
.gcmarkbit
= true;
3725 mark_object (finalizer
->function
);
3729 /* Move doomed finalizers to list DEST from list SRC. A doomed
3730 finalizer is one that is not GC-reachable and whose
3731 finalizer->function is non-nil. */
3734 queue_doomed_finalizers (struct Lisp_Finalizer
*dest
,
3735 struct Lisp_Finalizer
*src
)
3737 struct Lisp_Finalizer
*finalizer
= src
->next
;
3738 while (finalizer
!= src
)
3740 struct Lisp_Finalizer
*next
= finalizer
->next
;
3741 if (!finalizer
->base
.gcmarkbit
&& !NILP (finalizer
->function
))
3743 unchain_finalizer (finalizer
);
3744 finalizer_insert (dest
, finalizer
);
3752 run_finalizer_handler (Lisp_Object args
)
3754 add_to_log ("finalizer failed: %S", args
);
3759 run_finalizer_function (Lisp_Object function
)
3761 ptrdiff_t count
= SPECPDL_INDEX ();
3763 specbind (Qinhibit_quit
, Qt
);
3764 internal_condition_case_1 (call0
, function
, Qt
, run_finalizer_handler
);
3765 unbind_to (count
, Qnil
);
3769 run_finalizers (struct Lisp_Finalizer
*finalizers
)
3771 struct Lisp_Finalizer
*finalizer
;
3772 Lisp_Object function
;
3774 while (finalizers
->next
!= finalizers
)
3776 finalizer
= finalizers
->next
;
3777 eassert (finalizer
->base
.type
== Lisp_Misc_Finalizer
);
3778 unchain_finalizer (finalizer
);
3779 function
= finalizer
->function
;
3780 if (!NILP (function
))
3782 finalizer
->function
= Qnil
;
3783 run_finalizer_function (function
);
3788 DEFUN ("make-finalizer", Fmake_finalizer
, Smake_finalizer
, 1, 1, 0,
3789 doc
: /* Make a finalizer that will run FUNCTION.
3790 FUNCTION will be called after garbage collection when the returned
3791 finalizer object becomes unreachable. If the finalizer object is
3792 reachable only through references from finalizer objects, it does not
3793 count as reachable for the purpose of deciding whether to run
3794 FUNCTION. FUNCTION will be run once per finalizer object. */)
3795 (Lisp_Object function
)
3797 Lisp_Object val
= allocate_misc (Lisp_Misc_Finalizer
);
3798 struct Lisp_Finalizer
*finalizer
= XFINALIZER (val
);
3799 finalizer
->function
= function
;
3800 finalizer
->prev
= finalizer
->next
= NULL
;
3801 finalizer_insert (&finalizers
, finalizer
);
3806 /************************************************************************
3807 Memory Full Handling
3808 ************************************************************************/
3811 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
3812 there may have been size_t overflow so that malloc was never
3813 called, or perhaps malloc was invoked successfully but the
3814 resulting pointer had problems fitting into a tagged EMACS_INT. In
3815 either case this counts as memory being full even though malloc did
3819 memory_full (size_t nbytes
)
3821 /* Do not go into hysterics merely because a large request failed. */
3822 bool enough_free_memory
= 0;
3823 if (SPARE_MEMORY
< nbytes
)
3828 p
= malloc (SPARE_MEMORY
);
3832 enough_free_memory
= 1;
3834 MALLOC_UNBLOCK_INPUT
;
3837 if (! enough_free_memory
)
3843 memory_full_cons_threshold
= sizeof (struct cons_block
);
3845 /* The first time we get here, free the spare memory. */
3846 for (i
= 0; i
< ARRAYELTS (spare_memory
); i
++)
3847 if (spare_memory
[i
])
3850 free (spare_memory
[i
]);
3851 else if (i
>= 1 && i
<= 4)
3852 lisp_align_free (spare_memory
[i
]);
3854 lisp_free (spare_memory
[i
]);
3855 spare_memory
[i
] = 0;
3859 /* This used to call error, but if we've run out of memory, we could
3860 get infinite recursion trying to build the string. */
3861 xsignal (Qnil
, Vmemory_signal_data
);
3864 /* If we released our reserve (due to running out of memory),
3865 and we have a fair amount free once again,
3866 try to set aside another reserve in case we run out once more.
3868 This is called when a relocatable block is freed in ralloc.c,
3869 and also directly from this file, in case we're not using ralloc.c. */
3872 refill_memory_reserve (void)
3874 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
3875 if (spare_memory
[0] == 0)
3876 spare_memory
[0] = malloc (SPARE_MEMORY
);
3877 if (spare_memory
[1] == 0)
3878 spare_memory
[1] = lisp_align_malloc (sizeof (struct cons_block
),
3880 if (spare_memory
[2] == 0)
3881 spare_memory
[2] = lisp_align_malloc (sizeof (struct cons_block
),
3883 if (spare_memory
[3] == 0)
3884 spare_memory
[3] = lisp_align_malloc (sizeof (struct cons_block
),
3886 if (spare_memory
[4] == 0)
3887 spare_memory
[4] = lisp_align_malloc (sizeof (struct cons_block
),
3889 if (spare_memory
[5] == 0)
3890 spare_memory
[5] = lisp_malloc (sizeof (struct string_block
),
3892 if (spare_memory
[6] == 0)
3893 spare_memory
[6] = lisp_malloc (sizeof (struct string_block
),
3895 if (spare_memory
[0] && spare_memory
[1] && spare_memory
[5])
3896 Vmemory_full
= Qnil
;
3900 /************************************************************************
3902 ************************************************************************/
3904 /* Conservative C stack marking requires a method to identify possibly
3905 live Lisp objects given a pointer value. We do this by keeping
3906 track of blocks of Lisp data that are allocated in a red-black tree
3907 (see also the comment of mem_node which is the type of nodes in
3908 that tree). Function lisp_malloc adds information for an allocated
3909 block to the red-black tree with calls to mem_insert, and function
3910 lisp_free removes it with mem_delete. Functions live_string_p etc
3911 call mem_find to lookup information about a given pointer in the
3912 tree, and use that to determine if the pointer points to a Lisp
3915 /* Initialize this part of alloc.c. */
3920 mem_z
.left
= mem_z
.right
= MEM_NIL
;
3921 mem_z
.parent
= NULL
;
3922 mem_z
.color
= MEM_BLACK
;
3923 mem_z
.start
= mem_z
.end
= NULL
;
3928 /* Value is a pointer to the mem_node containing START. Value is
3929 MEM_NIL if there is no node in the tree containing START. */
3931 static struct mem_node
*
3932 mem_find (void *start
)
3936 if (start
< min_heap_address
|| start
> max_heap_address
)
3939 /* Make the search always successful to speed up the loop below. */
3940 mem_z
.start
= start
;
3941 mem_z
.end
= (char *) start
+ 1;
3944 while (start
< p
->start
|| start
>= p
->end
)
3945 p
= start
< p
->start
? p
->left
: p
->right
;
3950 /* Insert a new node into the tree for a block of memory with start
3951 address START, end address END, and type TYPE. Value is a
3952 pointer to the node that was inserted. */
3954 static struct mem_node
*
3955 mem_insert (void *start
, void *end
, enum mem_type type
)
3957 struct mem_node
*c
, *parent
, *x
;
3959 if (min_heap_address
== NULL
|| start
< min_heap_address
)
3960 min_heap_address
= start
;
3961 if (max_heap_address
== NULL
|| end
> max_heap_address
)
3962 max_heap_address
= end
;
3964 /* See where in the tree a node for START belongs. In this
3965 particular application, it shouldn't happen that a node is already
3966 present. For debugging purposes, let's check that. */
3970 while (c
!= MEM_NIL
)
3973 c
= start
< c
->start
? c
->left
: c
->right
;
3976 /* Create a new node. */
3977 #ifdef GC_MALLOC_CHECK
3978 x
= malloc (sizeof *x
);
3982 x
= xmalloc (sizeof *x
);
3988 x
->left
= x
->right
= MEM_NIL
;
3991 /* Insert it as child of PARENT or install it as root. */
3994 if (start
< parent
->start
)
4002 /* Re-establish red-black tree properties. */
4003 mem_insert_fixup (x
);
4009 /* Re-establish the red-black properties of the tree, and thereby
4010 balance the tree, after node X has been inserted; X is always red. */
4013 mem_insert_fixup (struct mem_node
*x
)
4015 while (x
!= mem_root
&& x
->parent
->color
== MEM_RED
)
4017 /* X is red and its parent is red. This is a violation of
4018 red-black tree property #3. */
4020 if (x
->parent
== x
->parent
->parent
->left
)
4022 /* We're on the left side of our grandparent, and Y is our
4024 struct mem_node
*y
= x
->parent
->parent
->right
;
4026 if (y
->color
== MEM_RED
)
4028 /* Uncle and parent are red but should be black because
4029 X is red. Change the colors accordingly and proceed
4030 with the grandparent. */
4031 x
->parent
->color
= MEM_BLACK
;
4032 y
->color
= MEM_BLACK
;
4033 x
->parent
->parent
->color
= MEM_RED
;
4034 x
= x
->parent
->parent
;
4038 /* Parent and uncle have different colors; parent is
4039 red, uncle is black. */
4040 if (x
== x
->parent
->right
)
4043 mem_rotate_left (x
);
4046 x
->parent
->color
= MEM_BLACK
;
4047 x
->parent
->parent
->color
= MEM_RED
;
4048 mem_rotate_right (x
->parent
->parent
);
4053 /* This is the symmetrical case of above. */
4054 struct mem_node
*y
= x
->parent
->parent
->left
;
4056 if (y
->color
== MEM_RED
)
4058 x
->parent
->color
= MEM_BLACK
;
4059 y
->color
= MEM_BLACK
;
4060 x
->parent
->parent
->color
= MEM_RED
;
4061 x
= x
->parent
->parent
;
4065 if (x
== x
->parent
->left
)
4068 mem_rotate_right (x
);
4071 x
->parent
->color
= MEM_BLACK
;
4072 x
->parent
->parent
->color
= MEM_RED
;
4073 mem_rotate_left (x
->parent
->parent
);
4078 /* The root may have been changed to red due to the algorithm. Set
4079 it to black so that property #5 is satisfied. */
4080 mem_root
->color
= MEM_BLACK
;
4091 mem_rotate_left (struct mem_node
*x
)
4095 /* Turn y's left sub-tree into x's right sub-tree. */
4098 if (y
->left
!= MEM_NIL
)
4099 y
->left
->parent
= x
;
4101 /* Y's parent was x's parent. */
4103 y
->parent
= x
->parent
;
4105 /* Get the parent to point to y instead of x. */
4108 if (x
== x
->parent
->left
)
4109 x
->parent
->left
= y
;
4111 x
->parent
->right
= y
;
4116 /* Put x on y's left. */
4130 mem_rotate_right (struct mem_node
*x
)
4132 struct mem_node
*y
= x
->left
;
4135 if (y
->right
!= MEM_NIL
)
4136 y
->right
->parent
= x
;
4139 y
->parent
= x
->parent
;
4142 if (x
== x
->parent
->right
)
4143 x
->parent
->right
= y
;
4145 x
->parent
->left
= y
;
4156 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
4159 mem_delete (struct mem_node
*z
)
4161 struct mem_node
*x
, *y
;
4163 if (!z
|| z
== MEM_NIL
)
4166 if (z
->left
== MEM_NIL
|| z
->right
== MEM_NIL
)
4171 while (y
->left
!= MEM_NIL
)
4175 if (y
->left
!= MEM_NIL
)
4180 x
->parent
= y
->parent
;
4183 if (y
== y
->parent
->left
)
4184 y
->parent
->left
= x
;
4186 y
->parent
->right
= x
;
4193 z
->start
= y
->start
;
4198 if (y
->color
== MEM_BLACK
)
4199 mem_delete_fixup (x
);
4201 #ifdef GC_MALLOC_CHECK
4209 /* Re-establish the red-black properties of the tree, after a
4213 mem_delete_fixup (struct mem_node
*x
)
4215 while (x
!= mem_root
&& x
->color
== MEM_BLACK
)
4217 if (x
== x
->parent
->left
)
4219 struct mem_node
*w
= x
->parent
->right
;
4221 if (w
->color
== MEM_RED
)
4223 w
->color
= MEM_BLACK
;
4224 x
->parent
->color
= MEM_RED
;
4225 mem_rotate_left (x
->parent
);
4226 w
= x
->parent
->right
;
4229 if (w
->left
->color
== MEM_BLACK
&& w
->right
->color
== MEM_BLACK
)
4236 if (w
->right
->color
== MEM_BLACK
)
4238 w
->left
->color
= MEM_BLACK
;
4240 mem_rotate_right (w
);
4241 w
= x
->parent
->right
;
4243 w
->color
= x
->parent
->color
;
4244 x
->parent
->color
= MEM_BLACK
;
4245 w
->right
->color
= MEM_BLACK
;
4246 mem_rotate_left (x
->parent
);
4252 struct mem_node
*w
= x
->parent
->left
;
4254 if (w
->color
== MEM_RED
)
4256 w
->color
= MEM_BLACK
;
4257 x
->parent
->color
= MEM_RED
;
4258 mem_rotate_right (x
->parent
);
4259 w
= x
->parent
->left
;
4262 if (w
->right
->color
== MEM_BLACK
&& w
->left
->color
== MEM_BLACK
)
4269 if (w
->left
->color
== MEM_BLACK
)
4271 w
->right
->color
= MEM_BLACK
;
4273 mem_rotate_left (w
);
4274 w
= x
->parent
->left
;
4277 w
->color
= x
->parent
->color
;
4278 x
->parent
->color
= MEM_BLACK
;
4279 w
->left
->color
= MEM_BLACK
;
4280 mem_rotate_right (x
->parent
);
4286 x
->color
= MEM_BLACK
;
4290 /* Value is non-zero if P is a pointer to a live Lisp string on
4291 the heap. M is a pointer to the mem_block for P. */
4294 live_string_p (struct mem_node
*m
, void *p
)
4296 if (m
->type
== MEM_TYPE_STRING
)
4298 struct string_block
*b
= m
->start
;
4299 ptrdiff_t offset
= (char *) p
- (char *) &b
->strings
[0];
4301 /* P must point to the start of a Lisp_String structure, and it
4302 must not be on the free-list. */
4304 && offset
% sizeof b
->strings
[0] == 0
4305 && offset
< (STRING_BLOCK_SIZE
* sizeof b
->strings
[0])
4306 && ((struct Lisp_String
*) p
)->data
!= NULL
);
4313 /* Value is non-zero if P is a pointer to a live Lisp cons on
4314 the heap. M is a pointer to the mem_block for P. */
4317 live_cons_p (struct mem_node
*m
, void *p
)
4319 if (m
->type
== MEM_TYPE_CONS
)
4321 struct cons_block
*b
= m
->start
;
4322 ptrdiff_t offset
= (char *) p
- (char *) &b
->conses
[0];
4324 /* P must point to the start of a Lisp_Cons, not be
4325 one of the unused cells in the current cons block,
4326 and not be on the free-list. */
4328 && offset
% sizeof b
->conses
[0] == 0
4329 && offset
< (CONS_BLOCK_SIZE
* sizeof b
->conses
[0])
4331 || offset
/ sizeof b
->conses
[0] < cons_block_index
)
4332 && !EQ (((struct Lisp_Cons
*) p
)->car
, Vdead
));
4339 /* Value is non-zero if P is a pointer to a live Lisp symbol on
4340 the heap. M is a pointer to the mem_block for P. */
4343 live_symbol_p (struct mem_node
*m
, void *p
)
4345 if (m
->type
== MEM_TYPE_SYMBOL
)
4347 struct symbol_block
*b
= m
->start
;
4348 ptrdiff_t offset
= (char *) p
- (char *) &b
->symbols
[0];
4350 /* P must point to the start of a Lisp_Symbol, not be
4351 one of the unused cells in the current symbol block,
4352 and not be on the free-list. */
4354 && offset
% sizeof b
->symbols
[0] == 0
4355 && offset
< (SYMBOL_BLOCK_SIZE
* sizeof b
->symbols
[0])
4356 && (b
!= symbol_block
4357 || offset
/ sizeof b
->symbols
[0] < symbol_block_index
)
4358 && !EQ (((struct Lisp_Symbol
*)p
)->function
, Vdead
));
4365 /* Value is non-zero if P is a pointer to a live Lisp float on
4366 the heap. M is a pointer to the mem_block for P. */
4369 live_float_p (struct mem_node
*m
, void *p
)
4371 if (m
->type
== MEM_TYPE_FLOAT
)
4373 struct float_block
*b
= m
->start
;
4374 ptrdiff_t offset
= (char *) p
- (char *) &b
->floats
[0];
4376 /* P must point to the start of a Lisp_Float and not be
4377 one of the unused cells in the current float block. */
4379 && offset
% sizeof b
->floats
[0] == 0
4380 && offset
< (FLOAT_BLOCK_SIZE
* sizeof b
->floats
[0])
4381 && (b
!= float_block
4382 || offset
/ sizeof b
->floats
[0] < float_block_index
));
4389 /* Value is non-zero if P is a pointer to a live Lisp Misc on
4390 the heap. M is a pointer to the mem_block for P. */
4393 live_misc_p (struct mem_node
*m
, void *p
)
4395 if (m
->type
== MEM_TYPE_MISC
)
4397 struct marker_block
*b
= m
->start
;
4398 ptrdiff_t offset
= (char *) p
- (char *) &b
->markers
[0];
4400 /* P must point to the start of a Lisp_Misc, not be
4401 one of the unused cells in the current misc block,
4402 and not be on the free-list. */
4404 && offset
% sizeof b
->markers
[0] == 0
4405 && offset
< (MARKER_BLOCK_SIZE
* sizeof b
->markers
[0])
4406 && (b
!= marker_block
4407 || offset
/ sizeof b
->markers
[0] < marker_block_index
)
4408 && ((union Lisp_Misc
*) p
)->u_any
.type
!= Lisp_Misc_Free
);
4415 /* Value is non-zero if P is a pointer to a live vector-like object.
4416 M is a pointer to the mem_block for P. */
4419 live_vector_p (struct mem_node
*m
, void *p
)
4421 if (m
->type
== MEM_TYPE_VECTOR_BLOCK
)
4423 /* This memory node corresponds to a vector block. */
4424 struct vector_block
*block
= m
->start
;
4425 struct Lisp_Vector
*vector
= (struct Lisp_Vector
*) block
->data
;
4427 /* P is in the block's allocation range. Scan the block
4428 up to P and see whether P points to the start of some
4429 vector which is not on a free list. FIXME: check whether
4430 some allocation patterns (probably a lot of short vectors)
4431 may cause a substantial overhead of this loop. */
4432 while (VECTOR_IN_BLOCK (vector
, block
)
4433 && vector
<= (struct Lisp_Vector
*) p
)
4435 if (!PSEUDOVECTOR_TYPEP (&vector
->header
, PVEC_FREE
) && vector
== p
)
4438 vector
= ADVANCE (vector
, vector_nbytes (vector
));
4441 else if (m
->type
== MEM_TYPE_VECTORLIKE
&& p
== large_vector_vec (m
->start
))
4442 /* This memory node corresponds to a large vector. */
4448 /* Value is non-zero if P is a pointer to a live buffer. M is a
4449 pointer to the mem_block for P. */
4452 live_buffer_p (struct mem_node
*m
, void *p
)
4454 /* P must point to the start of the block, and the buffer
4455 must not have been killed. */
4456 return (m
->type
== MEM_TYPE_BUFFER
4458 && !NILP (((struct buffer
*) p
)->name_
));
4461 /* Mark OBJ if we can prove it's a Lisp_Object. */
4464 mark_maybe_object (Lisp_Object obj
)
4471 VALGRIND_MAKE_MEM_DEFINED (&obj
, sizeof (obj
));
4477 po
= (void *) XPNTR (obj
);
4484 switch (XTYPE (obj
))
4487 mark_p
= (live_string_p (m
, po
)
4488 && !STRING_MARKED_P ((struct Lisp_String
*) po
));
4492 mark_p
= (live_cons_p (m
, po
) && !CONS_MARKED_P (XCONS (obj
)));
4496 mark_p
= (live_symbol_p (m
, po
) && !XSYMBOL (obj
)->gcmarkbit
);
4500 mark_p
= (live_float_p (m
, po
) && !FLOAT_MARKED_P (XFLOAT (obj
)));
4503 case Lisp_Vectorlike
:
4504 /* Note: can't check BUFFERP before we know it's a
4505 buffer because checking that dereferences the pointer
4506 PO which might point anywhere. */
4507 if (live_vector_p (m
, po
))
4508 mark_p
= !SUBRP (obj
) && !VECTOR_MARKED_P (XVECTOR (obj
));
4509 else if (live_buffer_p (m
, po
))
4510 mark_p
= BUFFERP (obj
) && !VECTOR_MARKED_P (XBUFFER (obj
));
4514 mark_p
= (live_misc_p (m
, po
) && !XMISCANY (obj
)->gcmarkbit
);
4526 /* Return true if P can point to Lisp data, and false otherwise.
4527 Symbols are implemented via offsets not pointers, but the offsets
4528 are also multiples of GCALIGNMENT. */
4531 maybe_lisp_pointer (void *p
)
4533 return (uintptr_t) p
% GCALIGNMENT
== 0;
4536 /* If P points to Lisp data, mark that as live if it isn't already
4540 mark_maybe_pointer (void *p
)
4546 VALGRIND_MAKE_MEM_DEFINED (&p
, sizeof (p
));
4549 if (!maybe_lisp_pointer (p
))
4555 Lisp_Object obj
= Qnil
;
4559 case MEM_TYPE_NON_LISP
:
4560 case MEM_TYPE_SPARE
:
4561 /* Nothing to do; not a pointer to Lisp memory. */
4564 case MEM_TYPE_BUFFER
:
4565 if (live_buffer_p (m
, p
) && !VECTOR_MARKED_P ((struct buffer
*)p
))
4566 XSETVECTOR (obj
, p
);
4570 if (live_cons_p (m
, p
) && !CONS_MARKED_P ((struct Lisp_Cons
*) p
))
4574 case MEM_TYPE_STRING
:
4575 if (live_string_p (m
, p
)
4576 && !STRING_MARKED_P ((struct Lisp_String
*) p
))
4577 XSETSTRING (obj
, p
);
4581 if (live_misc_p (m
, p
) && !((struct Lisp_Free
*) p
)->gcmarkbit
)
4585 case MEM_TYPE_SYMBOL
:
4586 if (live_symbol_p (m
, p
) && !((struct Lisp_Symbol
*) p
)->gcmarkbit
)
4587 XSETSYMBOL (obj
, p
);
4590 case MEM_TYPE_FLOAT
:
4591 if (live_float_p (m
, p
) && !FLOAT_MARKED_P (p
))
4595 case MEM_TYPE_VECTORLIKE
:
4596 case MEM_TYPE_VECTOR_BLOCK
:
4597 if (live_vector_p (m
, p
))
4600 XSETVECTOR (tem
, p
);
4601 if (!SUBRP (tem
) && !VECTOR_MARKED_P (XVECTOR (tem
)))
4616 /* Alignment of pointer values. Use alignof, as it sometimes returns
4617 a smaller alignment than GCC's __alignof__ and mark_memory might
4618 miss objects if __alignof__ were used. */
4619 #define GC_POINTER_ALIGNMENT alignof (void *)
4621 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4622 or END+OFFSET..START. */
4624 static void ATTRIBUTE_NO_SANITIZE_ADDRESS
4625 mark_memory (void *start
, void *end
)
4630 /* Make START the pointer to the start of the memory region,
4631 if it isn't already. */
4639 /* Mark Lisp data pointed to. This is necessary because, in some
4640 situations, the C compiler optimizes Lisp objects away, so that
4641 only a pointer to them remains. Example:
4643 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4646 Lisp_Object obj = build_string ("test");
4647 struct Lisp_String *s = XSTRING (obj);
4648 Fgarbage_collect ();
4649 fprintf (stderr, "test '%s'\n", s->data);
4653 Here, `obj' isn't really used, and the compiler optimizes it
4654 away. The only reference to the life string is through the
4657 for (pp
= start
; (void *) pp
< end
; pp
++)
4658 for (i
= 0; i
< sizeof *pp
; i
+= GC_POINTER_ALIGNMENT
)
4660 void *p
= *(void **) ((char *) pp
+ i
);
4661 mark_maybe_pointer (p
);
4662 mark_maybe_object (XIL ((intptr_t) p
));
4666 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4668 static bool setjmp_tested_p
;
4669 static int longjmps_done
;
4671 #define SETJMP_WILL_LIKELY_WORK "\
4673 Emacs garbage collector has been changed to use conservative stack\n\
4674 marking. Emacs has determined that the method it uses to do the\n\
4675 marking will likely work on your system, but this isn't sure.\n\
4677 If you are a system-programmer, or can get the help of a local wizard\n\
4678 who is, please take a look at the function mark_stack in alloc.c, and\n\
4679 verify that the methods used are appropriate for your system.\n\
4681 Please mail the result to <emacs-devel@gnu.org>.\n\
4684 #define SETJMP_WILL_NOT_WORK "\
4686 Emacs garbage collector has been changed to use conservative stack\n\
4687 marking. Emacs has determined that the default method it uses to do the\n\
4688 marking will not work on your system. We will need a system-dependent\n\
4689 solution for your system.\n\
4691 Please take a look at the function mark_stack in alloc.c, and\n\
4692 try to find a way to make it work on your system.\n\
4694 Note that you may get false negatives, depending on the compiler.\n\
4695 In particular, you need to use -O with GCC for this test.\n\
4697 Please mail the result to <emacs-devel@gnu.org>.\n\
4701 /* Perform a quick check if it looks like setjmp saves registers in a
4702 jmp_buf. Print a message to stderr saying so. When this test
4703 succeeds, this is _not_ a proof that setjmp is sufficient for
4704 conservative stack marking. Only the sources or a disassembly
4714 /* Arrange for X to be put in a register. */
4720 if (longjmps_done
== 1)
4722 /* Came here after the longjmp at the end of the function.
4724 If x == 1, the longjmp has restored the register to its
4725 value before the setjmp, and we can hope that setjmp
4726 saves all such registers in the jmp_buf, although that
4729 For other values of X, either something really strange is
4730 taking place, or the setjmp just didn't save the register. */
4733 fprintf (stderr
, SETJMP_WILL_LIKELY_WORK
);
4736 fprintf (stderr
, SETJMP_WILL_NOT_WORK
);
4743 if (longjmps_done
== 1)
4744 sys_longjmp (jbuf
, 1);
4747 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4750 /* Mark live Lisp objects on the C stack.
4752 There are several system-dependent problems to consider when
4753 porting this to new architectures:
4757 We have to mark Lisp objects in CPU registers that can hold local
4758 variables or are used to pass parameters.
4760 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4761 something that either saves relevant registers on the stack, or
4762 calls mark_maybe_object passing it each register's contents.
4764 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4765 implementation assumes that calling setjmp saves registers we need
4766 to see in a jmp_buf which itself lies on the stack. This doesn't
4767 have to be true! It must be verified for each system, possibly
4768 by taking a look at the source code of setjmp.
4770 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4771 can use it as a machine independent method to store all registers
4772 to the stack. In this case the macros described in the previous
4773 two paragraphs are not used.
4777 Architectures differ in the way their processor stack is organized.
4778 For example, the stack might look like this
4781 | Lisp_Object | size = 4
4783 | something else | size = 2
4785 | Lisp_Object | size = 4
4789 In such a case, not every Lisp_Object will be aligned equally. To
4790 find all Lisp_Object on the stack it won't be sufficient to walk
4791 the stack in steps of 4 bytes. Instead, two passes will be
4792 necessary, one starting at the start of the stack, and a second
4793 pass starting at the start of the stack + 2. Likewise, if the
4794 minimal alignment of Lisp_Objects on the stack is 1, four passes
4795 would be necessary, each one starting with one byte more offset
4796 from the stack start. */
4799 mark_stack (void *end
)
4802 /* This assumes that the stack is a contiguous region in memory. If
4803 that's not the case, something has to be done here to iterate
4804 over the stack segments. */
4805 mark_memory (stack_base
, end
);
4807 /* Allow for marking a secondary stack, like the register stack on the
4809 #ifdef GC_MARK_SECONDARY_STACK
4810 GC_MARK_SECONDARY_STACK ();
4815 c_symbol_p (struct Lisp_Symbol
*sym
)
4817 char *lispsym_ptr
= (char *) lispsym
;
4818 char *sym_ptr
= (char *) sym
;
4819 ptrdiff_t lispsym_offset
= sym_ptr
- lispsym_ptr
;
4820 return 0 <= lispsym_offset
&& lispsym_offset
< sizeof lispsym
;
4823 /* Determine whether it is safe to access memory at address P. */
4825 valid_pointer_p (void *p
)
4828 return w32_valid_pointer_p (p
, 16);
4831 if (ADDRESS_SANITIZER
)
4836 /* Obviously, we cannot just access it (we would SEGV trying), so we
4837 trick the o/s to tell us whether p is a valid pointer.
4838 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4839 not validate p in that case. */
4841 if (emacs_pipe (fd
) == 0)
4843 bool valid
= emacs_write (fd
[1], p
, 16) == 16;
4844 emacs_close (fd
[1]);
4845 emacs_close (fd
[0]);
4853 /* Return 2 if OBJ is a killed or special buffer object, 1 if OBJ is a
4854 valid lisp object, 0 if OBJ is NOT a valid lisp object, or -1 if we
4855 cannot validate OBJ. This function can be quite slow, so its primary
4856 use is the manual debugging. The only exception is print_object, where
4857 we use it to check whether the memory referenced by the pointer of
4858 Lisp_Save_Value object contains valid objects. */
4861 valid_lisp_object_p (Lisp_Object obj
)
4869 p
= (void *) XPNTR (obj
);
4870 if (PURE_POINTER_P (p
))
4873 if (SYMBOLP (obj
) && c_symbol_p (p
))
4874 return ((char *) p
- (char *) lispsym
) % sizeof lispsym
[0] == 0;
4876 if (p
== &buffer_defaults
|| p
== &buffer_local_symbols
)
4883 int valid
= valid_pointer_p (p
);
4895 case MEM_TYPE_NON_LISP
:
4896 case MEM_TYPE_SPARE
:
4899 case MEM_TYPE_BUFFER
:
4900 return live_buffer_p (m
, p
) ? 1 : 2;
4903 return live_cons_p (m
, p
);
4905 case MEM_TYPE_STRING
:
4906 return live_string_p (m
, p
);
4909 return live_misc_p (m
, p
);
4911 case MEM_TYPE_SYMBOL
:
4912 return live_symbol_p (m
, p
);
4914 case MEM_TYPE_FLOAT
:
4915 return live_float_p (m
, p
);
4917 case MEM_TYPE_VECTORLIKE
:
4918 case MEM_TYPE_VECTOR_BLOCK
:
4919 return live_vector_p (m
, p
);
4928 /***********************************************************************
4929 Pure Storage Management
4930 ***********************************************************************/
4932 /* Allocate room for SIZE bytes from pure Lisp storage and return a
4933 pointer to it. TYPE is the Lisp type for which the memory is
4934 allocated. TYPE < 0 means it's not used for a Lisp object. */
4937 pure_alloc (size_t size
, int type
)
4944 /* Allocate space for a Lisp object from the beginning of the free
4945 space with taking account of alignment. */
4946 result
= ALIGN (purebeg
+ pure_bytes_used_lisp
, GCALIGNMENT
);
4947 pure_bytes_used_lisp
= ((char *)result
- (char *)purebeg
) + size
;
4951 /* Allocate space for a non-Lisp object from the end of the free
4953 pure_bytes_used_non_lisp
+= size
;
4954 result
= purebeg
+ pure_size
- pure_bytes_used_non_lisp
;
4956 pure_bytes_used
= pure_bytes_used_lisp
+ pure_bytes_used_non_lisp
;
4958 if (pure_bytes_used
<= pure_size
)
4961 /* Don't allocate a large amount here,
4962 because it might get mmap'd and then its address
4963 might not be usable. */
4964 purebeg
= xmalloc (10000);
4966 pure_bytes_used_before_overflow
+= pure_bytes_used
- size
;
4967 pure_bytes_used
= 0;
4968 pure_bytes_used_lisp
= pure_bytes_used_non_lisp
= 0;
4973 /* Print a warning if PURESIZE is too small. */
4976 check_pure_size (void)
4978 if (pure_bytes_used_before_overflow
)
4979 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI
"d"
4981 pure_bytes_used
+ pure_bytes_used_before_overflow
);
4985 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
4986 the non-Lisp data pool of the pure storage, and return its start
4987 address. Return NULL if not found. */
4990 find_string_data_in_pure (const char *data
, ptrdiff_t nbytes
)
4993 ptrdiff_t skip
, bm_skip
[256], last_char_skip
, infinity
, start
, start_max
;
4994 const unsigned char *p
;
4997 if (pure_bytes_used_non_lisp
<= nbytes
)
5000 /* Set up the Boyer-Moore table. */
5002 for (i
= 0; i
< 256; i
++)
5005 p
= (const unsigned char *) data
;
5007 bm_skip
[*p
++] = skip
;
5009 last_char_skip
= bm_skip
['\0'];
5011 non_lisp_beg
= purebeg
+ pure_size
- pure_bytes_used_non_lisp
;
5012 start_max
= pure_bytes_used_non_lisp
- (nbytes
+ 1);
5014 /* See the comments in the function `boyer_moore' (search.c) for the
5015 use of `infinity'. */
5016 infinity
= pure_bytes_used_non_lisp
+ 1;
5017 bm_skip
['\0'] = infinity
;
5019 p
= (const unsigned char *) non_lisp_beg
+ nbytes
;
5023 /* Check the last character (== '\0'). */
5026 start
+= bm_skip
[*(p
+ start
)];
5028 while (start
<= start_max
);
5030 if (start
< infinity
)
5031 /* Couldn't find the last character. */
5034 /* No less than `infinity' means we could find the last
5035 character at `p[start - infinity]'. */
5038 /* Check the remaining characters. */
5039 if (memcmp (data
, non_lisp_beg
+ start
, nbytes
) == 0)
5041 return non_lisp_beg
+ start
;
5043 start
+= last_char_skip
;
5045 while (start
<= start_max
);
5051 /* Return a string allocated in pure space. DATA is a buffer holding
5052 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
5053 means make the result string multibyte.
5055 Must get an error if pure storage is full, since if it cannot hold
5056 a large string it may be able to hold conses that point to that
5057 string; then the string is not protected from gc. */
5060 make_pure_string (const char *data
,
5061 ptrdiff_t nchars
, ptrdiff_t nbytes
, bool multibyte
)
5064 struct Lisp_String
*s
= pure_alloc (sizeof *s
, Lisp_String
);
5065 s
->data
= (unsigned char *) find_string_data_in_pure (data
, nbytes
);
5066 if (s
->data
== NULL
)
5068 s
->data
= pure_alloc (nbytes
+ 1, -1);
5069 memcpy (s
->data
, data
, nbytes
);
5070 s
->data
[nbytes
] = '\0';
5073 s
->size_byte
= multibyte
? nbytes
: -1;
5074 s
->intervals
= NULL
;
5075 XSETSTRING (string
, s
);
5079 /* Return a string allocated in pure space. Do not
5080 allocate the string data, just point to DATA. */
5083 make_pure_c_string (const char *data
, ptrdiff_t nchars
)
5086 struct Lisp_String
*s
= pure_alloc (sizeof *s
, Lisp_String
);
5089 s
->data
= (unsigned char *) data
;
5090 s
->intervals
= NULL
;
5091 XSETSTRING (string
, s
);
5095 static Lisp_Object
purecopy (Lisp_Object obj
);
5097 /* Return a cons allocated from pure space. Give it pure copies
5098 of CAR as car and CDR as cdr. */
5101 pure_cons (Lisp_Object car
, Lisp_Object cdr
)
5104 struct Lisp_Cons
*p
= pure_alloc (sizeof *p
, Lisp_Cons
);
5106 XSETCAR (new, purecopy (car
));
5107 XSETCDR (new, purecopy (cdr
));
5112 /* Value is a float object with value NUM allocated from pure space. */
5115 make_pure_float (double num
)
5118 struct Lisp_Float
*p
= pure_alloc (sizeof *p
, Lisp_Float
);
5120 XFLOAT_INIT (new, num
);
5125 /* Return a vector with room for LEN Lisp_Objects allocated from
5129 make_pure_vector (ptrdiff_t len
)
5132 size_t size
= header_size
+ len
* word_size
;
5133 struct Lisp_Vector
*p
= pure_alloc (size
, Lisp_Vectorlike
);
5134 XSETVECTOR (new, p
);
5135 XVECTOR (new)->header
.size
= len
;
5139 DEFUN ("purecopy", Fpurecopy
, Spurecopy
, 1, 1, 0,
5140 doc
: /* Make a copy of object OBJ in pure storage.
5141 Recursively copies contents of vectors and cons cells.
5142 Does not copy symbols. Copies strings without text properties. */)
5143 (register Lisp_Object obj
)
5145 if (NILP (Vpurify_flag
))
5147 else if (MARKERP (obj
) || OVERLAYP (obj
)
5148 || HASH_TABLE_P (obj
) || SYMBOLP (obj
))
5149 /* Can't purify those. */
5152 return purecopy (obj
);
5156 purecopy (Lisp_Object obj
)
5158 if (PURE_POINTER_P (XPNTR (obj
)) || INTEGERP (obj
) || SUBRP (obj
))
5159 return obj
; /* Already pure. */
5161 if (STRINGP (obj
) && XSTRING (obj
)->intervals
)
5162 message_with_string ("Dropping text-properties while making string `%s' pure",
5165 if (HASH_TABLE_P (Vpurify_flag
)) /* Hash consing. */
5167 Lisp_Object tmp
= Fgethash (obj
, Vpurify_flag
, Qnil
);
5173 obj
= pure_cons (XCAR (obj
), XCDR (obj
));
5174 else if (FLOATP (obj
))
5175 obj
= make_pure_float (XFLOAT_DATA (obj
));
5176 else if (STRINGP (obj
))
5177 obj
= make_pure_string (SSDATA (obj
), SCHARS (obj
),
5179 STRING_MULTIBYTE (obj
));
5180 else if (COMPILEDP (obj
) || VECTORP (obj
) || HASH_TABLE_P (obj
))
5182 struct Lisp_Vector
*objp
= XVECTOR (obj
);
5183 ptrdiff_t nbytes
= vector_nbytes (objp
);
5184 struct Lisp_Vector
*vec
= pure_alloc (nbytes
, Lisp_Vectorlike
);
5185 register ptrdiff_t i
;
5186 ptrdiff_t size
= ASIZE (obj
);
5187 if (size
& PSEUDOVECTOR_FLAG
)
5188 size
&= PSEUDOVECTOR_SIZE_MASK
;
5189 memcpy (vec
, objp
, nbytes
);
5190 for (i
= 0; i
< size
; i
++)
5191 vec
->contents
[i
] = purecopy (vec
->contents
[i
]);
5192 XSETVECTOR (obj
, vec
);
5194 else if (SYMBOLP (obj
))
5196 if (!XSYMBOL (obj
)->pinned
&& !c_symbol_p (XSYMBOL (obj
)))
5197 { /* We can't purify them, but they appear in many pure objects.
5198 Mark them as `pinned' so we know to mark them at every GC cycle. */
5199 XSYMBOL (obj
)->pinned
= true;
5200 symbol_block_pinned
= symbol_block
;
5202 /* Don't hash-cons it. */
5207 Lisp_Object fmt
= build_pure_c_string ("Don't know how to purify: %S");
5208 Fsignal (Qerror
, list1 (CALLN (Fformat
, fmt
, obj
)));
5211 if (HASH_TABLE_P (Vpurify_flag
)) /* Hash consing. */
5212 Fputhash (obj
, obj
, Vpurify_flag
);
5219 /***********************************************************************
5221 ***********************************************************************/
5223 /* Put an entry in staticvec, pointing at the variable with address
5227 staticpro (Lisp_Object
*varaddress
)
5229 if (staticidx
>= NSTATICS
)
5230 fatal ("NSTATICS too small; try increasing and recompiling Emacs.");
5231 staticvec
[staticidx
++] = varaddress
;
5235 /***********************************************************************
5237 ***********************************************************************/
5239 /* Temporarily prevent garbage collection. */
5242 inhibit_garbage_collection (void)
5244 ptrdiff_t count
= SPECPDL_INDEX ();
5246 specbind (Qgc_cons_threshold
, make_number (MOST_POSITIVE_FIXNUM
));
5250 /* Used to avoid possible overflows when
5251 converting from C to Lisp integers. */
5254 bounded_number (EMACS_INT number
)
5256 return make_number (min (MOST_POSITIVE_FIXNUM
, number
));
5259 /* Calculate total bytes of live objects. */
5262 total_bytes_of_live_objects (void)
5265 tot
+= total_conses
* sizeof (struct Lisp_Cons
);
5266 tot
+= total_symbols
* sizeof (struct Lisp_Symbol
);
5267 tot
+= total_markers
* sizeof (union Lisp_Misc
);
5268 tot
+= total_string_bytes
;
5269 tot
+= total_vector_slots
* word_size
;
5270 tot
+= total_floats
* sizeof (struct Lisp_Float
);
5271 tot
+= total_intervals
* sizeof (struct interval
);
5272 tot
+= total_strings
* sizeof (struct Lisp_String
);
5276 #ifdef HAVE_WINDOW_SYSTEM
5278 /* This code has a few issues on MS-Windows, see Bug#15876 and Bug#16140. */
5280 #if !defined (HAVE_NTGUI)
5282 /* Remove unmarked font-spec and font-entity objects from ENTRY, which is
5283 (DRIVER-TYPE NUM-FRAMES FONT-CACHE-DATA ...), and return changed entry. */
5286 compact_font_cache_entry (Lisp_Object entry
)
5288 Lisp_Object tail
, *prev
= &entry
;
5290 for (tail
= entry
; CONSP (tail
); tail
= XCDR (tail
))
5293 Lisp_Object obj
= XCAR (tail
);
5295 /* Consider OBJ if it is (font-spec . [font-entity font-entity ...]). */
5296 if (CONSP (obj
) && FONT_SPEC_P (XCAR (obj
))
5297 && !VECTOR_MARKED_P (XFONT_SPEC (XCAR (obj
)))
5298 && VECTORP (XCDR (obj
)))
5300 ptrdiff_t i
, size
= ASIZE (XCDR (obj
)) & ~ARRAY_MARK_FLAG
;
5302 /* If font-spec is not marked, most likely all font-entities
5303 are not marked too. But we must be sure that nothing is
5304 marked within OBJ before we really drop it. */
5305 for (i
= 0; i
< size
; i
++)
5306 if (VECTOR_MARKED_P (XFONT_ENTITY (AREF (XCDR (obj
), i
))))
5313 *prev
= XCDR (tail
);
5315 prev
= xcdr_addr (tail
);
5320 #endif /* not HAVE_NTGUI */
5322 /* Compact font caches on all terminals and mark
5323 everything which is still here after compaction. */
5326 compact_font_caches (void)
5330 for (t
= terminal_list
; t
; t
= t
->next_terminal
)
5332 Lisp_Object cache
= TERMINAL_FONT_CACHE (t
);
5333 #if !defined (HAVE_NTGUI)
5338 for (entry
= XCDR (cache
); CONSP (entry
); entry
= XCDR (entry
))
5339 XSETCAR (entry
, compact_font_cache_entry (XCAR (entry
)));
5341 #endif /* not HAVE_NTGUI */
5342 mark_object (cache
);
5346 #else /* not HAVE_WINDOW_SYSTEM */
5348 #define compact_font_caches() (void)(0)
5350 #endif /* HAVE_WINDOW_SYSTEM */
5352 /* Remove (MARKER . DATA) entries with unmarked MARKER
5353 from buffer undo LIST and return changed list. */
5356 compact_undo_list (Lisp_Object list
)
5358 Lisp_Object tail
, *prev
= &list
;
5360 for (tail
= list
; CONSP (tail
); tail
= XCDR (tail
))
5362 if (CONSP (XCAR (tail
))
5363 && MARKERP (XCAR (XCAR (tail
)))
5364 && !XMARKER (XCAR (XCAR (tail
)))->gcmarkbit
)
5365 *prev
= XCDR (tail
);
5367 prev
= xcdr_addr (tail
);
5373 mark_pinned_symbols (void)
5375 struct symbol_block
*sblk
;
5376 int lim
= (symbol_block_pinned
== symbol_block
5377 ? symbol_block_index
: SYMBOL_BLOCK_SIZE
);
5379 for (sblk
= symbol_block_pinned
; sblk
; sblk
= sblk
->next
)
5381 union aligned_Lisp_Symbol
*sym
= sblk
->symbols
, *end
= sym
+ lim
;
5382 for (; sym
< end
; ++sym
)
5384 mark_object (make_lisp_symbol (&sym
->s
));
5386 lim
= SYMBOL_BLOCK_SIZE
;
5390 /* Subroutine of Fgarbage_collect that does most of the work. It is a
5391 separate function so that we could limit mark_stack in searching
5392 the stack frames below this function, thus avoiding the rare cases
5393 where mark_stack finds values that look like live Lisp objects on
5394 portions of stack that couldn't possibly contain such live objects.
5395 For more details of this, see the discussion at
5396 http://lists.gnu.org/archive/html/emacs-devel/2014-05/msg00270.html. */
5398 garbage_collect_1 (void *end
)
5400 struct buffer
*nextb
;
5401 char stack_top_variable
;
5404 ptrdiff_t count
= SPECPDL_INDEX ();
5405 struct timespec start
;
5406 Lisp_Object retval
= Qnil
;
5407 size_t tot_before
= 0;
5412 /* Can't GC if pure storage overflowed because we can't determine
5413 if something is a pure object or not. */
5414 if (pure_bytes_used_before_overflow
)
5417 /* Record this function, so it appears on the profiler's backtraces. */
5418 record_in_backtrace (Qautomatic_gc
, 0, 0);
5422 /* Don't keep undo information around forever.
5423 Do this early on, so it is no problem if the user quits. */
5424 FOR_EACH_BUFFER (nextb
)
5425 compact_buffer (nextb
);
5427 if (profiler_memory_running
)
5428 tot_before
= total_bytes_of_live_objects ();
5430 start
= current_timespec ();
5432 /* In case user calls debug_print during GC,
5433 don't let that cause a recursive GC. */
5434 consing_since_gc
= 0;
5436 /* Save what's currently displayed in the echo area. */
5437 message_p
= push_message ();
5438 record_unwind_protect_void (pop_message_unwind
);
5440 /* Save a copy of the contents of the stack, for debugging. */
5441 #if MAX_SAVE_STACK > 0
5442 if (NILP (Vpurify_flag
))
5445 ptrdiff_t stack_size
;
5446 if (&stack_top_variable
< stack_bottom
)
5448 stack
= &stack_top_variable
;
5449 stack_size
= stack_bottom
- &stack_top_variable
;
5453 stack
= stack_bottom
;
5454 stack_size
= &stack_top_variable
- stack_bottom
;
5456 if (stack_size
<= MAX_SAVE_STACK
)
5458 if (stack_copy_size
< stack_size
)
5460 stack_copy
= xrealloc (stack_copy
, stack_size
);
5461 stack_copy_size
= stack_size
;
5463 no_sanitize_memcpy (stack_copy
, stack
, stack_size
);
5466 #endif /* MAX_SAVE_STACK > 0 */
5468 if (garbage_collection_messages
)
5469 message1_nolog ("Garbage collecting...");
5473 shrink_regexp_cache ();
5477 /* Mark all the special slots that serve as the roots of accessibility. */
5479 mark_buffer (&buffer_defaults
);
5480 mark_buffer (&buffer_local_symbols
);
5482 for (i
= 0; i
< ARRAYELTS (lispsym
); i
++)
5483 mark_object (builtin_lisp_symbol (i
));
5485 for (i
= 0; i
< staticidx
; i
++)
5486 mark_object (*staticvec
[i
]);
5488 mark_pinned_symbols ();
5500 struct handler
*handler
;
5501 for (handler
= handlerlist
; handler
; handler
= handler
->next
)
5503 mark_object (handler
->tag_or_ch
);
5504 mark_object (handler
->val
);
5507 #ifdef HAVE_WINDOW_SYSTEM
5508 mark_fringe_data ();
5511 /* Everything is now marked, except for the data in font caches,
5512 undo lists, and finalizers. The first two are compacted by
5513 removing an items which aren't reachable otherwise. */
5515 compact_font_caches ();
5517 FOR_EACH_BUFFER (nextb
)
5519 if (!EQ (BVAR (nextb
, undo_list
), Qt
))
5520 bset_undo_list (nextb
, compact_undo_list (BVAR (nextb
, undo_list
)));
5521 /* Now that we have stripped the elements that need not be
5522 in the undo_list any more, we can finally mark the list. */
5523 mark_object (BVAR (nextb
, undo_list
));
5526 /* Now pre-sweep finalizers. Here, we add any unmarked finalizers
5527 to doomed_finalizers so we can run their associated functions
5528 after GC. It's important to scan finalizers at this stage so
5529 that we can be sure that unmarked finalizers are really
5530 unreachable except for references from their associated functions
5531 and from other finalizers. */
5533 queue_doomed_finalizers (&doomed_finalizers
, &finalizers
);
5534 mark_finalizer_list (&doomed_finalizers
);
5538 relocate_byte_stack ();
5540 /* Clear the mark bits that we set in certain root slots. */
5541 VECTOR_UNMARK (&buffer_defaults
);
5542 VECTOR_UNMARK (&buffer_local_symbols
);
5550 consing_since_gc
= 0;
5551 if (gc_cons_threshold
< GC_DEFAULT_THRESHOLD
/ 10)
5552 gc_cons_threshold
= GC_DEFAULT_THRESHOLD
/ 10;
5554 gc_relative_threshold
= 0;
5555 if (FLOATP (Vgc_cons_percentage
))
5556 { /* Set gc_cons_combined_threshold. */
5557 double tot
= total_bytes_of_live_objects ();
5559 tot
*= XFLOAT_DATA (Vgc_cons_percentage
);
5562 if (tot
< TYPE_MAXIMUM (EMACS_INT
))
5563 gc_relative_threshold
= tot
;
5565 gc_relative_threshold
= TYPE_MAXIMUM (EMACS_INT
);
5569 if (garbage_collection_messages
)
5571 if (message_p
|| minibuf_level
> 0)
5574 message1_nolog ("Garbage collecting...done");
5577 unbind_to (count
, Qnil
);
5579 Lisp_Object total
[] = {
5580 list4 (Qconses
, make_number (sizeof (struct Lisp_Cons
)),
5581 bounded_number (total_conses
),
5582 bounded_number (total_free_conses
)),
5583 list4 (Qsymbols
, make_number (sizeof (struct Lisp_Symbol
)),
5584 bounded_number (total_symbols
),
5585 bounded_number (total_free_symbols
)),
5586 list4 (Qmiscs
, make_number (sizeof (union Lisp_Misc
)),
5587 bounded_number (total_markers
),
5588 bounded_number (total_free_markers
)),
5589 list4 (Qstrings
, make_number (sizeof (struct Lisp_String
)),
5590 bounded_number (total_strings
),
5591 bounded_number (total_free_strings
)),
5592 list3 (Qstring_bytes
, make_number (1),
5593 bounded_number (total_string_bytes
)),
5595 make_number (header_size
+ sizeof (Lisp_Object
)),
5596 bounded_number (total_vectors
)),
5597 list4 (Qvector_slots
, make_number (word_size
),
5598 bounded_number (total_vector_slots
),
5599 bounded_number (total_free_vector_slots
)),
5600 list4 (Qfloats
, make_number (sizeof (struct Lisp_Float
)),
5601 bounded_number (total_floats
),
5602 bounded_number (total_free_floats
)),
5603 list4 (Qintervals
, make_number (sizeof (struct interval
)),
5604 bounded_number (total_intervals
),
5605 bounded_number (total_free_intervals
)),
5606 list3 (Qbuffers
, make_number (sizeof (struct buffer
)),
5607 bounded_number (total_buffers
)),
5609 #ifdef DOUG_LEA_MALLOC
5610 list4 (Qheap
, make_number (1024),
5611 bounded_number ((mallinfo ().uordblks
+ 1023) >> 10),
5612 bounded_number ((mallinfo ().fordblks
+ 1023) >> 10)),
5615 retval
= CALLMANY (Flist
, total
);
5617 /* GC is complete: now we can run our finalizer callbacks. */
5618 run_finalizers (&doomed_finalizers
);
5620 if (!NILP (Vpost_gc_hook
))
5622 ptrdiff_t gc_count
= inhibit_garbage_collection ();
5623 safe_run_hooks (Qpost_gc_hook
);
5624 unbind_to (gc_count
, Qnil
);
5627 /* Accumulate statistics. */
5628 if (FLOATP (Vgc_elapsed
))
5630 struct timespec since_start
= timespec_sub (current_timespec (), start
);
5631 Vgc_elapsed
= make_float (XFLOAT_DATA (Vgc_elapsed
)
5632 + timespectod (since_start
));
5637 /* Collect profiling data. */
5638 if (profiler_memory_running
)
5641 size_t tot_after
= total_bytes_of_live_objects ();
5642 if (tot_before
> tot_after
)
5643 swept
= tot_before
- tot_after
;
5644 malloc_probe (swept
);
5650 DEFUN ("garbage-collect", Fgarbage_collect
, Sgarbage_collect
, 0, 0, "",
5651 doc
: /* Reclaim storage for Lisp objects no longer needed.
5652 Garbage collection happens automatically if you cons more than
5653 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5654 `garbage-collect' normally returns a list with info on amount of space in use,
5655 where each entry has the form (NAME SIZE USED FREE), where:
5656 - NAME is a symbol describing the kind of objects this entry represents,
5657 - SIZE is the number of bytes used by each one,
5658 - USED is the number of those objects that were found live in the heap,
5659 - FREE is the number of those objects that are not live but that Emacs
5660 keeps around for future allocations (maybe because it does not know how
5661 to return them to the OS).
5662 However, if there was overflow in pure space, `garbage-collect'
5663 returns nil, because real GC can't be done.
5664 See Info node `(elisp)Garbage Collection'. */)
5669 #ifdef HAVE___BUILTIN_UNWIND_INIT
5670 /* Force callee-saved registers and register windows onto the stack.
5671 This is the preferred method if available, obviating the need for
5672 machine dependent methods. */
5673 __builtin_unwind_init ();
5675 #else /* not HAVE___BUILTIN_UNWIND_INIT */
5676 #ifndef GC_SAVE_REGISTERS_ON_STACK
5677 /* jmp_buf may not be aligned enough on darwin-ppc64 */
5678 union aligned_jmpbuf
{
5682 volatile bool stack_grows_down_p
= (char *) &j
> (char *) stack_base
;
5684 /* This trick flushes the register windows so that all the state of
5685 the process is contained in the stack. */
5686 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
5687 needed on ia64 too. See mach_dep.c, where it also says inline
5688 assembler doesn't work with relevant proprietary compilers. */
5690 #if defined (__sparc64__) && defined (__FreeBSD__)
5691 /* FreeBSD does not have a ta 3 handler. */
5698 /* Save registers that we need to see on the stack. We need to see
5699 registers used to hold register variables and registers used to
5701 #ifdef GC_SAVE_REGISTERS_ON_STACK
5702 GC_SAVE_REGISTERS_ON_STACK (end
);
5703 #else /* not GC_SAVE_REGISTERS_ON_STACK */
5705 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
5706 setjmp will definitely work, test it
5707 and print a message with the result
5709 if (!setjmp_tested_p
)
5711 setjmp_tested_p
= 1;
5714 #endif /* GC_SETJMP_WORKS */
5717 end
= stack_grows_down_p
? (char *) &j
+ sizeof j
: (char *) &j
;
5718 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
5719 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
5720 return garbage_collect_1 (end
);
5723 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5724 only interesting objects referenced from glyphs are strings. */
5727 mark_glyph_matrix (struct glyph_matrix
*matrix
)
5729 struct glyph_row
*row
= matrix
->rows
;
5730 struct glyph_row
*end
= row
+ matrix
->nrows
;
5732 for (; row
< end
; ++row
)
5736 for (area
= LEFT_MARGIN_AREA
; area
< LAST_AREA
; ++area
)
5738 struct glyph
*glyph
= row
->glyphs
[area
];
5739 struct glyph
*end_glyph
= glyph
+ row
->used
[area
];
5741 for (; glyph
< end_glyph
; ++glyph
)
5742 if (STRINGP (glyph
->object
)
5743 && !STRING_MARKED_P (XSTRING (glyph
->object
)))
5744 mark_object (glyph
->object
);
5749 /* Mark reference to a Lisp_Object.
5750 If the object referred to has not been seen yet, recursively mark
5751 all the references contained in it. */
5753 #define LAST_MARKED_SIZE 500
5754 static Lisp_Object last_marked
[LAST_MARKED_SIZE
];
5755 static int last_marked_index
;
5757 /* For debugging--call abort when we cdr down this many
5758 links of a list, in mark_object. In debugging,
5759 the call to abort will hit a breakpoint.
5760 Normally this is zero and the check never goes off. */
5761 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE
;
5764 mark_vectorlike (struct Lisp_Vector
*ptr
)
5766 ptrdiff_t size
= ptr
->header
.size
;
5769 eassert (!VECTOR_MARKED_P (ptr
));
5770 VECTOR_MARK (ptr
); /* Else mark it. */
5771 if (size
& PSEUDOVECTOR_FLAG
)
5772 size
&= PSEUDOVECTOR_SIZE_MASK
;
5774 /* Note that this size is not the memory-footprint size, but only
5775 the number of Lisp_Object fields that we should trace.
5776 The distinction is used e.g. by Lisp_Process which places extra
5777 non-Lisp_Object fields at the end of the structure... */
5778 for (i
= 0; i
< size
; i
++) /* ...and then mark its elements. */
5779 mark_object (ptr
->contents
[i
]);
5782 /* Like mark_vectorlike but optimized for char-tables (and
5783 sub-char-tables) assuming that the contents are mostly integers or
5787 mark_char_table (struct Lisp_Vector
*ptr
, enum pvec_type pvectype
)
5789 int size
= ptr
->header
.size
& PSEUDOVECTOR_SIZE_MASK
;
5790 /* Consult the Lisp_Sub_Char_Table layout before changing this. */
5791 int i
, idx
= (pvectype
== PVEC_SUB_CHAR_TABLE
? SUB_CHAR_TABLE_OFFSET
: 0);
5793 eassert (!VECTOR_MARKED_P (ptr
));
5795 for (i
= idx
; i
< size
; i
++)
5797 Lisp_Object val
= ptr
->contents
[i
];
5799 if (INTEGERP (val
) || (SYMBOLP (val
) && XSYMBOL (val
)->gcmarkbit
))
5801 if (SUB_CHAR_TABLE_P (val
))
5803 if (! VECTOR_MARKED_P (XVECTOR (val
)))
5804 mark_char_table (XVECTOR (val
), PVEC_SUB_CHAR_TABLE
);
5811 NO_INLINE
/* To reduce stack depth in mark_object. */
5813 mark_compiled (struct Lisp_Vector
*ptr
)
5815 int i
, size
= ptr
->header
.size
& PSEUDOVECTOR_SIZE_MASK
;
5818 for (i
= 0; i
< size
; i
++)
5819 if (i
!= COMPILED_CONSTANTS
)
5820 mark_object (ptr
->contents
[i
]);
5821 return size
> COMPILED_CONSTANTS
? ptr
->contents
[COMPILED_CONSTANTS
] : Qnil
;
5824 /* Mark the chain of overlays starting at PTR. */
5827 mark_overlay (struct Lisp_Overlay
*ptr
)
5829 for (; ptr
&& !ptr
->gcmarkbit
; ptr
= ptr
->next
)
5832 /* These two are always markers and can be marked fast. */
5833 XMARKER (ptr
->start
)->gcmarkbit
= 1;
5834 XMARKER (ptr
->end
)->gcmarkbit
= 1;
5835 mark_object (ptr
->plist
);
5839 /* Mark Lisp_Objects and special pointers in BUFFER. */
5842 mark_buffer (struct buffer
*buffer
)
5844 /* This is handled much like other pseudovectors... */
5845 mark_vectorlike ((struct Lisp_Vector
*) buffer
);
5847 /* ...but there are some buffer-specific things. */
5849 MARK_INTERVAL_TREE (buffer_intervals (buffer
));
5851 /* For now, we just don't mark the undo_list. It's done later in
5852 a special way just before the sweep phase, and after stripping
5853 some of its elements that are not needed any more. */
5855 mark_overlay (buffer
->overlays_before
);
5856 mark_overlay (buffer
->overlays_after
);
5858 /* If this is an indirect buffer, mark its base buffer. */
5859 if (buffer
->base_buffer
&& !VECTOR_MARKED_P (buffer
->base_buffer
))
5860 mark_buffer (buffer
->base_buffer
);
5863 /* Mark Lisp faces in the face cache C. */
5865 NO_INLINE
/* To reduce stack depth in mark_object. */
5867 mark_face_cache (struct face_cache
*c
)
5872 for (i
= 0; i
< c
->used
; ++i
)
5874 struct face
*face
= FACE_FROM_ID (c
->f
, i
);
5878 if (face
->font
&& !VECTOR_MARKED_P (face
->font
))
5879 mark_vectorlike ((struct Lisp_Vector
*) face
->font
);
5881 for (j
= 0; j
< LFACE_VECTOR_SIZE
; ++j
)
5882 mark_object (face
->lface
[j
]);
5888 NO_INLINE
/* To reduce stack depth in mark_object. */
5890 mark_localized_symbol (struct Lisp_Symbol
*ptr
)
5892 struct Lisp_Buffer_Local_Value
*blv
= SYMBOL_BLV (ptr
);
5893 Lisp_Object where
= blv
->where
;
5894 /* If the value is set up for a killed buffer or deleted
5895 frame, restore its global binding. If the value is
5896 forwarded to a C variable, either it's not a Lisp_Object
5897 var, or it's staticpro'd already. */
5898 if ((BUFFERP (where
) && !BUFFER_LIVE_P (XBUFFER (where
)))
5899 || (FRAMEP (where
) && !FRAME_LIVE_P (XFRAME (where
))))
5900 swap_in_global_binding (ptr
);
5901 mark_object (blv
->where
);
5902 mark_object (blv
->valcell
);
5903 mark_object (blv
->defcell
);
5906 NO_INLINE
/* To reduce stack depth in mark_object. */
5908 mark_save_value (struct Lisp_Save_Value
*ptr
)
5910 /* If `save_type' is zero, `data[0].pointer' is the address
5911 of a memory area containing `data[1].integer' potential
5913 if (ptr
->save_type
== SAVE_TYPE_MEMORY
)
5915 Lisp_Object
*p
= ptr
->data
[0].pointer
;
5917 for (nelt
= ptr
->data
[1].integer
; nelt
> 0; nelt
--, p
++)
5918 mark_maybe_object (*p
);
5922 /* Find Lisp_Objects in `data[N]' slots and mark them. */
5924 for (i
= 0; i
< SAVE_VALUE_SLOTS
; i
++)
5925 if (save_type (ptr
, i
) == SAVE_OBJECT
)
5926 mark_object (ptr
->data
[i
].object
);
5930 /* Remove killed buffers or items whose car is a killed buffer from
5931 LIST, and mark other items. Return changed LIST, which is marked. */
5934 mark_discard_killed_buffers (Lisp_Object list
)
5936 Lisp_Object tail
, *prev
= &list
;
5938 for (tail
= list
; CONSP (tail
) && !CONS_MARKED_P (XCONS (tail
));
5941 Lisp_Object tem
= XCAR (tail
);
5944 if (BUFFERP (tem
) && !BUFFER_LIVE_P (XBUFFER (tem
)))
5945 *prev
= XCDR (tail
);
5948 CONS_MARK (XCONS (tail
));
5949 mark_object (XCAR (tail
));
5950 prev
= xcdr_addr (tail
);
5957 /* Determine type of generic Lisp_Object and mark it accordingly.
5959 This function implements a straightforward depth-first marking
5960 algorithm and so the recursion depth may be very high (a few
5961 tens of thousands is not uncommon). To minimize stack usage,
5962 a few cold paths are moved out to NO_INLINE functions above.
5963 In general, inlining them doesn't help you to gain more speed. */
5966 mark_object (Lisp_Object arg
)
5968 register Lisp_Object obj
;
5970 #ifdef GC_CHECK_MARKED_OBJECTS
5973 ptrdiff_t cdr_count
= 0;
5979 if (PURE_POINTER_P (po
))
5982 last_marked
[last_marked_index
++] = obj
;
5983 if (last_marked_index
== LAST_MARKED_SIZE
)
5984 last_marked_index
= 0;
5986 /* Perform some sanity checks on the objects marked here. Abort if
5987 we encounter an object we know is bogus. This increases GC time
5989 #ifdef GC_CHECK_MARKED_OBJECTS
5991 /* Check that the object pointed to by PO is known to be a Lisp
5992 structure allocated from the heap. */
5993 #define CHECK_ALLOCATED() \
5995 m = mem_find (po); \
6000 /* Check that the object pointed to by PO is live, using predicate
6002 #define CHECK_LIVE(LIVEP) \
6004 if (!LIVEP (m, po)) \
6008 /* Check both of the above conditions, for non-symbols. */
6009 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
6011 CHECK_ALLOCATED (); \
6012 CHECK_LIVE (LIVEP); \
6015 /* Check both of the above conditions, for symbols. */
6016 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() \
6018 if (!c_symbol_p (ptr)) \
6020 CHECK_ALLOCATED (); \
6021 CHECK_LIVE (live_symbol_p); \
6025 #else /* not GC_CHECK_MARKED_OBJECTS */
6027 #define CHECK_LIVE(LIVEP) ((void) 0)
6028 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) ((void) 0)
6029 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() ((void) 0)
6031 #endif /* not GC_CHECK_MARKED_OBJECTS */
6033 switch (XTYPE (obj
))
6037 register struct Lisp_String
*ptr
= XSTRING (obj
);
6038 if (STRING_MARKED_P (ptr
))
6040 CHECK_ALLOCATED_AND_LIVE (live_string_p
);
6042 MARK_INTERVAL_TREE (ptr
->intervals
);
6043 #ifdef GC_CHECK_STRING_BYTES
6044 /* Check that the string size recorded in the string is the
6045 same as the one recorded in the sdata structure. */
6047 #endif /* GC_CHECK_STRING_BYTES */
6051 case Lisp_Vectorlike
:
6053 register struct Lisp_Vector
*ptr
= XVECTOR (obj
);
6054 register ptrdiff_t pvectype
;
6056 if (VECTOR_MARKED_P (ptr
))
6059 #ifdef GC_CHECK_MARKED_OBJECTS
6061 if (m
== MEM_NIL
&& !SUBRP (obj
))
6063 #endif /* GC_CHECK_MARKED_OBJECTS */
6065 if (ptr
->header
.size
& PSEUDOVECTOR_FLAG
)
6066 pvectype
= ((ptr
->header
.size
& PVEC_TYPE_MASK
)
6067 >> PSEUDOVECTOR_AREA_BITS
);
6069 pvectype
= PVEC_NORMAL_VECTOR
;
6071 if (pvectype
!= PVEC_SUBR
&& pvectype
!= PVEC_BUFFER
)
6072 CHECK_LIVE (live_vector_p
);
6077 #ifdef GC_CHECK_MARKED_OBJECTS
6086 #endif /* GC_CHECK_MARKED_OBJECTS */
6087 mark_buffer ((struct buffer
*) ptr
);
6091 /* Although we could treat this just like a vector, mark_compiled
6092 returns the COMPILED_CONSTANTS element, which is marked at the
6093 next iteration of goto-loop here. This is done to avoid a few
6094 recursive calls to mark_object. */
6095 obj
= mark_compiled (ptr
);
6102 struct frame
*f
= (struct frame
*) ptr
;
6104 mark_vectorlike (ptr
);
6105 mark_face_cache (f
->face_cache
);
6106 #ifdef HAVE_WINDOW_SYSTEM
6107 if (FRAME_WINDOW_P (f
) && FRAME_X_OUTPUT (f
))
6109 struct font
*font
= FRAME_FONT (f
);
6111 if (font
&& !VECTOR_MARKED_P (font
))
6112 mark_vectorlike ((struct Lisp_Vector
*) font
);
6120 struct window
*w
= (struct window
*) ptr
;
6122 mark_vectorlike (ptr
);
6124 /* Mark glyph matrices, if any. Marking window
6125 matrices is sufficient because frame matrices
6126 use the same glyph memory. */
6127 if (w
->current_matrix
)
6129 mark_glyph_matrix (w
->current_matrix
);
6130 mark_glyph_matrix (w
->desired_matrix
);
6133 /* Filter out killed buffers from both buffer lists
6134 in attempt to help GC to reclaim killed buffers faster.
6135 We can do it elsewhere for live windows, but this is the
6136 best place to do it for dead windows. */
6138 (w
, mark_discard_killed_buffers (w
->prev_buffers
));
6140 (w
, mark_discard_killed_buffers (w
->next_buffers
));
6144 case PVEC_HASH_TABLE
:
6146 struct Lisp_Hash_Table
*h
= (struct Lisp_Hash_Table
*) ptr
;
6148 mark_vectorlike (ptr
);
6149 mark_object (h
->test
.name
);
6150 mark_object (h
->test
.user_hash_function
);
6151 mark_object (h
->test
.user_cmp_function
);
6152 /* If hash table is not weak, mark all keys and values.
6153 For weak tables, mark only the vector. */
6155 mark_object (h
->key_and_value
);
6157 VECTOR_MARK (XVECTOR (h
->key_and_value
));
6161 case PVEC_CHAR_TABLE
:
6162 case PVEC_SUB_CHAR_TABLE
:
6163 mark_char_table (ptr
, (enum pvec_type
) pvectype
);
6166 case PVEC_BOOL_VECTOR
:
6167 /* No Lisp_Objects to mark in a bool vector. */
6178 mark_vectorlike (ptr
);
6185 register struct Lisp_Symbol
*ptr
= XSYMBOL (obj
);
6189 CHECK_ALLOCATED_AND_LIVE_SYMBOL ();
6191 /* Attempt to catch bogus objects. */
6192 eassert (valid_lisp_object_p (ptr
->function
));
6193 mark_object (ptr
->function
);
6194 mark_object (ptr
->plist
);
6195 switch (ptr
->redirect
)
6197 case SYMBOL_PLAINVAL
: mark_object (SYMBOL_VAL (ptr
)); break;
6198 case SYMBOL_VARALIAS
:
6201 XSETSYMBOL (tem
, SYMBOL_ALIAS (ptr
));
6205 case SYMBOL_LOCALIZED
:
6206 mark_localized_symbol (ptr
);
6208 case SYMBOL_FORWARDED
:
6209 /* If the value is forwarded to a buffer or keyboard field,
6210 these are marked when we see the corresponding object.
6211 And if it's forwarded to a C variable, either it's not
6212 a Lisp_Object var, or it's staticpro'd already. */
6214 default: emacs_abort ();
6216 if (!PURE_POINTER_P (XSTRING (ptr
->name
)))
6217 MARK_STRING (XSTRING (ptr
->name
));
6218 MARK_INTERVAL_TREE (string_intervals (ptr
->name
));
6219 /* Inner loop to mark next symbol in this bucket, if any. */
6227 CHECK_ALLOCATED_AND_LIVE (live_misc_p
);
6229 if (XMISCANY (obj
)->gcmarkbit
)
6232 switch (XMISCTYPE (obj
))
6234 case Lisp_Misc_Marker
:
6235 /* DO NOT mark thru the marker's chain.
6236 The buffer's markers chain does not preserve markers from gc;
6237 instead, markers are removed from the chain when freed by gc. */
6238 XMISCANY (obj
)->gcmarkbit
= 1;
6241 case Lisp_Misc_Save_Value
:
6242 XMISCANY (obj
)->gcmarkbit
= 1;
6243 mark_save_value (XSAVE_VALUE (obj
));
6246 case Lisp_Misc_Overlay
:
6247 mark_overlay (XOVERLAY (obj
));
6250 case Lisp_Misc_Finalizer
:
6251 XMISCANY (obj
)->gcmarkbit
= true;
6252 mark_object (XFINALIZER (obj
)->function
);
6262 register struct Lisp_Cons
*ptr
= XCONS (obj
);
6263 if (CONS_MARKED_P (ptr
))
6265 CHECK_ALLOCATED_AND_LIVE (live_cons_p
);
6267 /* If the cdr is nil, avoid recursion for the car. */
6268 if (EQ (ptr
->u
.cdr
, Qnil
))
6274 mark_object (ptr
->car
);
6277 if (cdr_count
== mark_object_loop_halt
)
6283 CHECK_ALLOCATED_AND_LIVE (live_float_p
);
6284 FLOAT_MARK (XFLOAT (obj
));
6295 #undef CHECK_ALLOCATED
6296 #undef CHECK_ALLOCATED_AND_LIVE
6298 /* Mark the Lisp pointers in the terminal objects.
6299 Called by Fgarbage_collect. */
6302 mark_terminals (void)
6305 for (t
= terminal_list
; t
; t
= t
->next_terminal
)
6307 eassert (t
->name
!= NULL
);
6308 #ifdef HAVE_WINDOW_SYSTEM
6309 /* If a terminal object is reachable from a stacpro'ed object,
6310 it might have been marked already. Make sure the image cache
6312 mark_image_cache (t
->image_cache
);
6313 #endif /* HAVE_WINDOW_SYSTEM */
6314 if (!VECTOR_MARKED_P (t
))
6315 mark_vectorlike ((struct Lisp_Vector
*)t
);
6321 /* Value is non-zero if OBJ will survive the current GC because it's
6322 either marked or does not need to be marked to survive. */
6325 survives_gc_p (Lisp_Object obj
)
6329 switch (XTYPE (obj
))
6336 survives_p
= XSYMBOL (obj
)->gcmarkbit
;
6340 survives_p
= XMISCANY (obj
)->gcmarkbit
;
6344 survives_p
= STRING_MARKED_P (XSTRING (obj
));
6347 case Lisp_Vectorlike
:
6348 survives_p
= SUBRP (obj
) || VECTOR_MARKED_P (XVECTOR (obj
));
6352 survives_p
= CONS_MARKED_P (XCONS (obj
));
6356 survives_p
= FLOAT_MARKED_P (XFLOAT (obj
));
6363 return survives_p
|| PURE_POINTER_P ((void *) XPNTR (obj
));
6369 NO_INLINE
/* For better stack traces */
6373 struct cons_block
*cblk
;
6374 struct cons_block
**cprev
= &cons_block
;
6375 int lim
= cons_block_index
;
6376 EMACS_INT num_free
= 0, num_used
= 0;
6380 for (cblk
= cons_block
; cblk
; cblk
= *cprev
)
6384 int ilim
= (lim
+ BITS_PER_BITS_WORD
- 1) / BITS_PER_BITS_WORD
;
6386 /* Scan the mark bits an int at a time. */
6387 for (i
= 0; i
< ilim
; i
++)
6389 if (cblk
->gcmarkbits
[i
] == BITS_WORD_MAX
)
6391 /* Fast path - all cons cells for this int are marked. */
6392 cblk
->gcmarkbits
[i
] = 0;
6393 num_used
+= BITS_PER_BITS_WORD
;
6397 /* Some cons cells for this int are not marked.
6398 Find which ones, and free them. */
6399 int start
, pos
, stop
;
6401 start
= i
* BITS_PER_BITS_WORD
;
6403 if (stop
> BITS_PER_BITS_WORD
)
6404 stop
= BITS_PER_BITS_WORD
;
6407 for (pos
= start
; pos
< stop
; pos
++)
6409 if (!CONS_MARKED_P (&cblk
->conses
[pos
]))
6412 cblk
->conses
[pos
].u
.chain
= cons_free_list
;
6413 cons_free_list
= &cblk
->conses
[pos
];
6414 cons_free_list
->car
= Vdead
;
6419 CONS_UNMARK (&cblk
->conses
[pos
]);
6425 lim
= CONS_BLOCK_SIZE
;
6426 /* If this block contains only free conses and we have already
6427 seen more than two blocks worth of free conses then deallocate
6429 if (this_free
== CONS_BLOCK_SIZE
&& num_free
> CONS_BLOCK_SIZE
)
6431 *cprev
= cblk
->next
;
6432 /* Unhook from the free list. */
6433 cons_free_list
= cblk
->conses
[0].u
.chain
;
6434 lisp_align_free (cblk
);
6438 num_free
+= this_free
;
6439 cprev
= &cblk
->next
;
6442 total_conses
= num_used
;
6443 total_free_conses
= num_free
;
6446 NO_INLINE
/* For better stack traces */
6450 register struct float_block
*fblk
;
6451 struct float_block
**fprev
= &float_block
;
6452 register int lim
= float_block_index
;
6453 EMACS_INT num_free
= 0, num_used
= 0;
6455 float_free_list
= 0;
6457 for (fblk
= float_block
; fblk
; fblk
= *fprev
)
6461 for (i
= 0; i
< lim
; i
++)
6462 if (!FLOAT_MARKED_P (&fblk
->floats
[i
]))
6465 fblk
->floats
[i
].u
.chain
= float_free_list
;
6466 float_free_list
= &fblk
->floats
[i
];
6471 FLOAT_UNMARK (&fblk
->floats
[i
]);
6473 lim
= FLOAT_BLOCK_SIZE
;
6474 /* If this block contains only free floats and we have already
6475 seen more than two blocks worth of free floats then deallocate
6477 if (this_free
== FLOAT_BLOCK_SIZE
&& num_free
> FLOAT_BLOCK_SIZE
)
6479 *fprev
= fblk
->next
;
6480 /* Unhook from the free list. */
6481 float_free_list
= fblk
->floats
[0].u
.chain
;
6482 lisp_align_free (fblk
);
6486 num_free
+= this_free
;
6487 fprev
= &fblk
->next
;
6490 total_floats
= num_used
;
6491 total_free_floats
= num_free
;
6494 NO_INLINE
/* For better stack traces */
6496 sweep_intervals (void)
6498 register struct interval_block
*iblk
;
6499 struct interval_block
**iprev
= &interval_block
;
6500 register int lim
= interval_block_index
;
6501 EMACS_INT num_free
= 0, num_used
= 0;
6503 interval_free_list
= 0;
6505 for (iblk
= interval_block
; iblk
; iblk
= *iprev
)
6510 for (i
= 0; i
< lim
; i
++)
6512 if (!iblk
->intervals
[i
].gcmarkbit
)
6514 set_interval_parent (&iblk
->intervals
[i
], interval_free_list
);
6515 interval_free_list
= &iblk
->intervals
[i
];
6521 iblk
->intervals
[i
].gcmarkbit
= 0;
6524 lim
= INTERVAL_BLOCK_SIZE
;
6525 /* If this block contains only free intervals and we have already
6526 seen more than two blocks worth of free intervals then
6527 deallocate this block. */
6528 if (this_free
== INTERVAL_BLOCK_SIZE
&& num_free
> INTERVAL_BLOCK_SIZE
)
6530 *iprev
= iblk
->next
;
6531 /* Unhook from the free list. */
6532 interval_free_list
= INTERVAL_PARENT (&iblk
->intervals
[0]);
6537 num_free
+= this_free
;
6538 iprev
= &iblk
->next
;
6541 total_intervals
= num_used
;
6542 total_free_intervals
= num_free
;
6545 NO_INLINE
/* For better stack traces */
6547 sweep_symbols (void)
6549 struct symbol_block
*sblk
;
6550 struct symbol_block
**sprev
= &symbol_block
;
6551 int lim
= symbol_block_index
;
6552 EMACS_INT num_free
= 0, num_used
= ARRAYELTS (lispsym
);
6554 symbol_free_list
= NULL
;
6556 for (int i
= 0; i
< ARRAYELTS (lispsym
); i
++)
6557 lispsym
[i
].gcmarkbit
= 0;
6559 for (sblk
= symbol_block
; sblk
; sblk
= *sprev
)
6562 union aligned_Lisp_Symbol
*sym
= sblk
->symbols
;
6563 union aligned_Lisp_Symbol
*end
= sym
+ lim
;
6565 for (; sym
< end
; ++sym
)
6567 if (!sym
->s
.gcmarkbit
)
6569 if (sym
->s
.redirect
== SYMBOL_LOCALIZED
)
6570 xfree (SYMBOL_BLV (&sym
->s
));
6571 sym
->s
.next
= symbol_free_list
;
6572 symbol_free_list
= &sym
->s
;
6573 symbol_free_list
->function
= Vdead
;
6579 sym
->s
.gcmarkbit
= 0;
6580 /* Attempt to catch bogus objects. */
6581 eassert (valid_lisp_object_p (sym
->s
.function
));
6585 lim
= SYMBOL_BLOCK_SIZE
;
6586 /* If this block contains only free symbols and we have already
6587 seen more than two blocks worth of free symbols then deallocate
6589 if (this_free
== SYMBOL_BLOCK_SIZE
&& num_free
> SYMBOL_BLOCK_SIZE
)
6591 *sprev
= sblk
->next
;
6592 /* Unhook from the free list. */
6593 symbol_free_list
= sblk
->symbols
[0].s
.next
;
6598 num_free
+= this_free
;
6599 sprev
= &sblk
->next
;
6602 total_symbols
= num_used
;
6603 total_free_symbols
= num_free
;
6606 NO_INLINE
/* For better stack traces. */
6610 register struct marker_block
*mblk
;
6611 struct marker_block
**mprev
= &marker_block
;
6612 register int lim
= marker_block_index
;
6613 EMACS_INT num_free
= 0, num_used
= 0;
6615 /* Put all unmarked misc's on free list. For a marker, first
6616 unchain it from the buffer it points into. */
6618 marker_free_list
= 0;
6620 for (mblk
= marker_block
; mblk
; mblk
= *mprev
)
6625 for (i
= 0; i
< lim
; i
++)
6627 if (!mblk
->markers
[i
].m
.u_any
.gcmarkbit
)
6629 if (mblk
->markers
[i
].m
.u_any
.type
== Lisp_Misc_Marker
)
6630 unchain_marker (&mblk
->markers
[i
].m
.u_marker
);
6631 if (mblk
->markers
[i
].m
.u_any
.type
== Lisp_Misc_Finalizer
)
6632 unchain_finalizer (&mblk
->markers
[i
].m
.u_finalizer
);
6633 /* Set the type of the freed object to Lisp_Misc_Free.
6634 We could leave the type alone, since nobody checks it,
6635 but this might catch bugs faster. */
6636 mblk
->markers
[i
].m
.u_marker
.type
= Lisp_Misc_Free
;
6637 mblk
->markers
[i
].m
.u_free
.chain
= marker_free_list
;
6638 marker_free_list
= &mblk
->markers
[i
].m
;
6644 mblk
->markers
[i
].m
.u_any
.gcmarkbit
= 0;
6647 lim
= MARKER_BLOCK_SIZE
;
6648 /* If this block contains only free markers and we have already
6649 seen more than two blocks worth of free markers then deallocate
6651 if (this_free
== MARKER_BLOCK_SIZE
&& num_free
> MARKER_BLOCK_SIZE
)
6653 *mprev
= mblk
->next
;
6654 /* Unhook from the free list. */
6655 marker_free_list
= mblk
->markers
[0].m
.u_free
.chain
;
6660 num_free
+= this_free
;
6661 mprev
= &mblk
->next
;
6665 total_markers
= num_used
;
6666 total_free_markers
= num_free
;
6669 NO_INLINE
/* For better stack traces */
6671 sweep_buffers (void)
6673 register struct buffer
*buffer
, **bprev
= &all_buffers
;
6676 for (buffer
= all_buffers
; buffer
; buffer
= *bprev
)
6677 if (!VECTOR_MARKED_P (buffer
))
6679 *bprev
= buffer
->next
;
6684 VECTOR_UNMARK (buffer
);
6685 /* Do not use buffer_(set|get)_intervals here. */
6686 buffer
->text
->intervals
= balance_intervals (buffer
->text
->intervals
);
6688 bprev
= &buffer
->next
;
6692 /* Sweep: find all structures not marked, and free them. */
6696 /* Remove or mark entries in weak hash tables.
6697 This must be done before any object is unmarked. */
6698 sweep_weak_hash_tables ();
6701 check_string_bytes (!noninteractive
);
6709 check_string_bytes (!noninteractive
);
6712 DEFUN ("memory-info", Fmemory_info
, Smemory_info
, 0, 0, 0,
6713 doc
: /* Return a list of (TOTAL-RAM FREE-RAM TOTAL-SWAP FREE-SWAP).
6714 All values are in Kbytes. If there is no swap space,
6715 last two values are zero. If the system is not supported
6716 or memory information can't be obtained, return nil. */)
6719 #if defined HAVE_LINUX_SYSINFO
6725 #ifdef LINUX_SYSINFO_UNIT
6726 units
= si
.mem_unit
;
6730 return list4i ((uintmax_t) si
.totalram
* units
/ 1024,
6731 (uintmax_t) si
.freeram
* units
/ 1024,
6732 (uintmax_t) si
.totalswap
* units
/ 1024,
6733 (uintmax_t) si
.freeswap
* units
/ 1024);
6734 #elif defined WINDOWSNT
6735 unsigned long long totalram
, freeram
, totalswap
, freeswap
;
6737 if (w32_memory_info (&totalram
, &freeram
, &totalswap
, &freeswap
) == 0)
6738 return list4i ((uintmax_t) totalram
/ 1024,
6739 (uintmax_t) freeram
/ 1024,
6740 (uintmax_t) totalswap
/ 1024,
6741 (uintmax_t) freeswap
/ 1024);
6745 unsigned long totalram
, freeram
, totalswap
, freeswap
;
6747 if (dos_memory_info (&totalram
, &freeram
, &totalswap
, &freeswap
) == 0)
6748 return list4i ((uintmax_t) totalram
/ 1024,
6749 (uintmax_t) freeram
/ 1024,
6750 (uintmax_t) totalswap
/ 1024,
6751 (uintmax_t) freeswap
/ 1024);
6754 #else /* not HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
6755 /* FIXME: add more systems. */
6757 #endif /* HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
6760 /* Debugging aids. */
6762 DEFUN ("memory-limit", Fmemory_limit
, Smemory_limit
, 0, 0, 0,
6763 doc
: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6764 This may be helpful in debugging Emacs's memory usage.
6765 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6771 /* Avoid warning. sbrk has no relation to memory allocated anyway. */
6774 XSETINT (end
, (intptr_t) (char *) sbrk (0) / 1024);
6780 DEFUN ("memory-use-counts", Fmemory_use_counts
, Smemory_use_counts
, 0, 0, 0,
6781 doc
: /* Return a list of counters that measure how much consing there has been.
6782 Each of these counters increments for a certain kind of object.
6783 The counters wrap around from the largest positive integer to zero.
6784 Garbage collection does not decrease them.
6785 The elements of the value are as follows:
6786 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6787 All are in units of 1 = one object consed
6788 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6790 MISCS include overlays, markers, and some internal types.
6791 Frames, windows, buffers, and subprocesses count as vectors
6792 (but the contents of a buffer's text do not count here). */)
6795 return listn (CONSTYPE_HEAP
, 8,
6796 bounded_number (cons_cells_consed
),
6797 bounded_number (floats_consed
),
6798 bounded_number (vector_cells_consed
),
6799 bounded_number (symbols_consed
),
6800 bounded_number (string_chars_consed
),
6801 bounded_number (misc_objects_consed
),
6802 bounded_number (intervals_consed
),
6803 bounded_number (strings_consed
));
6807 symbol_uses_obj (Lisp_Object symbol
, Lisp_Object obj
)
6809 struct Lisp_Symbol
*sym
= XSYMBOL (symbol
);
6810 Lisp_Object val
= find_symbol_value (symbol
);
6811 return (EQ (val
, obj
)
6812 || EQ (sym
->function
, obj
)
6813 || (!NILP (sym
->function
)
6814 && COMPILEDP (sym
->function
)
6815 && EQ (AREF (sym
->function
, COMPILED_BYTECODE
), obj
))
6818 && EQ (AREF (val
, COMPILED_BYTECODE
), obj
)));
6821 /* Find at most FIND_MAX symbols which have OBJ as their value or
6822 function. This is used in gdbinit's `xwhichsymbols' command. */
6825 which_symbols (Lisp_Object obj
, EMACS_INT find_max
)
6827 struct symbol_block
*sblk
;
6828 ptrdiff_t gc_count
= inhibit_garbage_collection ();
6829 Lisp_Object found
= Qnil
;
6833 for (int i
= 0; i
< ARRAYELTS (lispsym
); i
++)
6835 Lisp_Object sym
= builtin_lisp_symbol (i
);
6836 if (symbol_uses_obj (sym
, obj
))
6838 found
= Fcons (sym
, found
);
6839 if (--find_max
== 0)
6844 for (sblk
= symbol_block
; sblk
; sblk
= sblk
->next
)
6846 union aligned_Lisp_Symbol
*aligned_sym
= sblk
->symbols
;
6849 for (bn
= 0; bn
< SYMBOL_BLOCK_SIZE
; bn
++, aligned_sym
++)
6851 if (sblk
== symbol_block
&& bn
>= symbol_block_index
)
6854 Lisp_Object sym
= make_lisp_symbol (&aligned_sym
->s
);
6855 if (symbol_uses_obj (sym
, obj
))
6857 found
= Fcons (sym
, found
);
6858 if (--find_max
== 0)
6866 unbind_to (gc_count
, Qnil
);
6870 #ifdef SUSPICIOUS_OBJECT_CHECKING
6873 find_suspicious_object_in_range (void *begin
, void *end
)
6875 char *begin_a
= begin
;
6879 for (i
= 0; i
< ARRAYELTS (suspicious_objects
); ++i
)
6881 char *suspicious_object
= suspicious_objects
[i
];
6882 if (begin_a
<= suspicious_object
&& suspicious_object
< end_a
)
6883 return suspicious_object
;
6890 note_suspicious_free (void* ptr
)
6892 struct suspicious_free_record
* rec
;
6894 rec
= &suspicious_free_history
[suspicious_free_history_index
++];
6895 if (suspicious_free_history_index
==
6896 ARRAYELTS (suspicious_free_history
))
6898 suspicious_free_history_index
= 0;
6901 memset (rec
, 0, sizeof (*rec
));
6902 rec
->suspicious_object
= ptr
;
6903 backtrace (&rec
->backtrace
[0], ARRAYELTS (rec
->backtrace
));
6907 detect_suspicious_free (void* ptr
)
6911 eassert (ptr
!= NULL
);
6913 for (i
= 0; i
< ARRAYELTS (suspicious_objects
); ++i
)
6914 if (suspicious_objects
[i
] == ptr
)
6916 note_suspicious_free (ptr
);
6917 suspicious_objects
[i
] = NULL
;
6921 #endif /* SUSPICIOUS_OBJECT_CHECKING */
6923 DEFUN ("suspicious-object", Fsuspicious_object
, Ssuspicious_object
, 1, 1, 0,
6924 doc
: /* Return OBJ, maybe marking it for extra scrutiny.
6925 If Emacs is compiled with suspicious object checking, capture
6926 a stack trace when OBJ is freed in order to help track down
6927 garbage collection bugs. Otherwise, do nothing and return OBJ. */)
6930 #ifdef SUSPICIOUS_OBJECT_CHECKING
6931 /* Right now, we care only about vectors. */
6932 if (VECTORLIKEP (obj
))
6934 suspicious_objects
[suspicious_object_index
++] = XVECTOR (obj
);
6935 if (suspicious_object_index
== ARRAYELTS (suspicious_objects
))
6936 suspicious_object_index
= 0;
6942 #ifdef ENABLE_CHECKING
6944 bool suppress_checking
;
6947 die (const char *msg
, const char *file
, int line
)
6949 fprintf (stderr
, "\r\n%s:%d: Emacs fatal error: assertion failed: %s\r\n",
6951 terminate_due_to_signal (SIGABRT
, INT_MAX
);
6954 #endif /* ENABLE_CHECKING */
6956 #if defined (ENABLE_CHECKING) && USE_STACK_LISP_OBJECTS
6958 /* Debugging check whether STR is ASCII-only. */
6961 verify_ascii (const char *str
)
6963 const unsigned char *ptr
= (unsigned char *) str
, *end
= ptr
+ strlen (str
);
6966 int c
= STRING_CHAR_ADVANCE (ptr
);
6967 if (!ASCII_CHAR_P (c
))
6973 /* Stress alloca with inconveniently sized requests and check
6974 whether all allocated areas may be used for Lisp_Object. */
6976 NO_INLINE
static void
6977 verify_alloca (void)
6980 enum { ALLOCA_CHECK_MAX
= 256 };
6981 /* Start from size of the smallest Lisp object. */
6982 for (i
= sizeof (struct Lisp_Cons
); i
<= ALLOCA_CHECK_MAX
; i
++)
6984 void *ptr
= alloca (i
);
6985 make_lisp_ptr (ptr
, Lisp_Cons
);
6989 #else /* not ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
6991 #define verify_alloca() ((void) 0)
6993 #endif /* ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
6995 /* Initialization. */
6998 init_alloc_once (void)
7000 /* Even though Qt's contents are not set up, its address is known. */
7004 pure_size
= PURESIZE
;
7007 init_finalizer_list (&finalizers
);
7008 init_finalizer_list (&doomed_finalizers
);
7011 Vdead
= make_pure_string ("DEAD", 4, 4, 0);
7013 #ifdef DOUG_LEA_MALLOC
7014 mallopt (M_TRIM_THRESHOLD
, 128 * 1024); /* Trim threshold. */
7015 mallopt (M_MMAP_THRESHOLD
, 64 * 1024); /* Mmap threshold. */
7016 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
); /* Max. number of mmap'ed areas. */
7021 refill_memory_reserve ();
7022 gc_cons_threshold
= GC_DEFAULT_THRESHOLD
;
7028 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
7029 setjmp_tested_p
= longjmps_done
= 0;
7031 Vgc_elapsed
= make_float (0.0);
7035 valgrind_p
= RUNNING_ON_VALGRIND
!= 0;
7040 syms_of_alloc (void)
7042 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold
,
7043 doc
: /* Number of bytes of consing between garbage collections.
7044 Garbage collection can happen automatically once this many bytes have been
7045 allocated since the last garbage collection. All data types count.
7047 Garbage collection happens automatically only when `eval' is called.
7049 By binding this temporarily to a large number, you can effectively
7050 prevent garbage collection during a part of the program.
7051 See also `gc-cons-percentage'. */);
7053 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage
,
7054 doc
: /* Portion of the heap used for allocation.
7055 Garbage collection can happen automatically once this portion of the heap
7056 has been allocated since the last garbage collection.
7057 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
7058 Vgc_cons_percentage
= make_float (0.1);
7060 DEFVAR_INT ("pure-bytes-used", pure_bytes_used
,
7061 doc
: /* Number of bytes of shareable Lisp data allocated so far. */);
7063 DEFVAR_INT ("cons-cells-consed", cons_cells_consed
,
7064 doc
: /* Number of cons cells that have been consed so far. */);
7066 DEFVAR_INT ("floats-consed", floats_consed
,
7067 doc
: /* Number of floats that have been consed so far. */);
7069 DEFVAR_INT ("vector-cells-consed", vector_cells_consed
,
7070 doc
: /* Number of vector cells that have been consed so far. */);
7072 DEFVAR_INT ("symbols-consed", symbols_consed
,
7073 doc
: /* Number of symbols that have been consed so far. */);
7074 symbols_consed
+= ARRAYELTS (lispsym
);
7076 DEFVAR_INT ("string-chars-consed", string_chars_consed
,
7077 doc
: /* Number of string characters that have been consed so far. */);
7079 DEFVAR_INT ("misc-objects-consed", misc_objects_consed
,
7080 doc
: /* Number of miscellaneous objects that have been consed so far.
7081 These include markers and overlays, plus certain objects not visible
7084 DEFVAR_INT ("intervals-consed", intervals_consed
,
7085 doc
: /* Number of intervals that have been consed so far. */);
7087 DEFVAR_INT ("strings-consed", strings_consed
,
7088 doc
: /* Number of strings that have been consed so far. */);
7090 DEFVAR_LISP ("purify-flag", Vpurify_flag
,
7091 doc
: /* Non-nil means loading Lisp code in order to dump an executable.
7092 This means that certain objects should be allocated in shared (pure) space.
7093 It can also be set to a hash-table, in which case this table is used to
7094 do hash-consing of the objects allocated to pure space. */);
7096 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages
,
7097 doc
: /* Non-nil means display messages at start and end of garbage collection. */);
7098 garbage_collection_messages
= 0;
7100 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook
,
7101 doc
: /* Hook run after garbage collection has finished. */);
7102 Vpost_gc_hook
= Qnil
;
7103 DEFSYM (Qpost_gc_hook
, "post-gc-hook");
7105 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data
,
7106 doc
: /* Precomputed `signal' argument for memory-full error. */);
7107 /* We build this in advance because if we wait until we need it, we might
7108 not be able to allocate the memory to hold it. */
7110 = listn (CONSTYPE_PURE
, 2, Qerror
,
7111 build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
7113 DEFVAR_LISP ("memory-full", Vmemory_full
,
7114 doc
: /* Non-nil means Emacs cannot get much more Lisp memory. */);
7115 Vmemory_full
= Qnil
;
7117 DEFSYM (Qconses
, "conses");
7118 DEFSYM (Qsymbols
, "symbols");
7119 DEFSYM (Qmiscs
, "miscs");
7120 DEFSYM (Qstrings
, "strings");
7121 DEFSYM (Qvectors
, "vectors");
7122 DEFSYM (Qfloats
, "floats");
7123 DEFSYM (Qintervals
, "intervals");
7124 DEFSYM (Qbuffers
, "buffers");
7125 DEFSYM (Qstring_bytes
, "string-bytes");
7126 DEFSYM (Qvector_slots
, "vector-slots");
7127 DEFSYM (Qheap
, "heap");
7128 DEFSYM (Qautomatic_gc
, "Automatic GC");
7130 DEFSYM (Qgc_cons_threshold
, "gc-cons-threshold");
7131 DEFSYM (Qchar_table_extra_slots
, "char-table-extra-slots");
7133 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed
,
7134 doc
: /* Accumulated time elapsed in garbage collections.
7135 The time is in seconds as a floating point value. */);
7136 DEFVAR_INT ("gcs-done", gcs_done
,
7137 doc
: /* Accumulated number of garbage collections done. */);
7142 defsubr (&Sbool_vector
);
7143 defsubr (&Smake_byte_code
);
7144 defsubr (&Smake_list
);
7145 defsubr (&Smake_vector
);
7146 defsubr (&Smake_string
);
7147 defsubr (&Smake_bool_vector
);
7148 defsubr (&Smake_symbol
);
7149 defsubr (&Smake_marker
);
7150 defsubr (&Smake_finalizer
);
7151 defsubr (&Spurecopy
);
7152 defsubr (&Sgarbage_collect
);
7153 defsubr (&Smemory_limit
);
7154 defsubr (&Smemory_info
);
7155 defsubr (&Smemory_use_counts
);
7156 defsubr (&Ssuspicious_object
);
7159 /* When compiled with GCC, GDB might say "No enum type named
7160 pvec_type" if we don't have at least one symbol with that type, and
7161 then xbacktrace could fail. Similarly for the other enums and
7162 their values. Some non-GCC compilers don't like these constructs. */
7166 enum CHARTAB_SIZE_BITS CHARTAB_SIZE_BITS
;
7167 enum char_table_specials char_table_specials
;
7168 enum char_bits char_bits
;
7169 enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE
;
7170 enum DEFAULT_HASH_SIZE DEFAULT_HASH_SIZE
;
7171 enum Lisp_Bits Lisp_Bits
;
7172 enum Lisp_Compiled Lisp_Compiled
;
7173 enum maxargs maxargs
;
7174 enum MAX_ALLOCA MAX_ALLOCA
;
7175 enum More_Lisp_Bits More_Lisp_Bits
;
7176 enum pvec_type pvec_type
;
7177 } const EXTERNALLY_VISIBLE gdb_make_enums_visible
= {0};
7178 #endif /* __GNUC__ */