1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2016 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. */
35 #include "dispextern.h"
36 #include "intervals.h"
40 #include "character.h"
45 #include "blockinput.h"
46 #include "termhooks.h" /* For struct terminal. */
47 #ifdef HAVE_WINDOW_SYSTEM
49 #endif /* HAVE_WINDOW_SYSTEM */
52 #include <execinfo.h> /* For backtrace. */
54 #ifdef HAVE_LINUX_SYSINFO
55 #include <sys/sysinfo.h>
59 #include "dosfns.h" /* For dos_memory_info. */
66 #if (defined ENABLE_CHECKING \
67 && defined HAVE_VALGRIND_VALGRIND_H \
68 && !defined USE_VALGRIND)
69 # define USE_VALGRIND 1
73 #include <valgrind/valgrind.h>
74 #include <valgrind/memcheck.h>
75 static bool valgrind_p
;
78 /* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects. */
80 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
81 memory. Can do this only if using gmalloc.c and if not checking
84 #if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
85 || defined HYBRID_MALLOC || defined GC_CHECK_MARKED_OBJECTS)
86 #undef GC_MALLOC_CHECK
97 #include "w32heap.h" /* for sbrk */
100 #if defined DOUG_LEA_MALLOC || defined GNU_LINUX
101 /* The address where the heap starts. */
112 #ifdef DOUG_LEA_MALLOC
114 /* Specify maximum number of areas to mmap. It would be nice to use a
115 value that explicitly means "no limit". */
117 #define MMAP_MAX_AREAS 100000000
119 /* A pointer to the memory allocated that copies that static data
120 inside glibc's malloc. */
121 static void *malloc_state_ptr
;
123 /* Restore the dumped malloc state. Because malloc can be invoked
124 even before main (e.g. by the dynamic linker), the dumped malloc
125 state must be restored as early as possible using this special hook. */
127 malloc_initialize_hook (void)
129 static bool malloc_using_checking
;
134 malloc_using_checking
= getenv ("MALLOC_CHECK_") != NULL
;
138 if (!malloc_using_checking
)
140 /* Work around a bug in glibc's malloc. MALLOC_CHECK_ must be
141 ignored if the heap to be restored was constructed without
142 malloc checking. Can't use unsetenv, since that calls malloc. */
146 if (strncmp (*p
, "MALLOC_CHECK_=", 14) == 0)
156 malloc_set_state (malloc_state_ptr
);
157 # ifndef XMALLOC_OVERRUN_CHECK
158 alloc_unexec_post ();
163 # ifndef __MALLOC_HOOK_VOLATILE
164 # define __MALLOC_HOOK_VOLATILE
166 voidfuncptr __MALLOC_HOOK_VOLATILE __malloc_initialize_hook
167 = malloc_initialize_hook
;
171 /* Allocator-related actions to do just before and after unexec. */
174 alloc_unexec_pre (void)
176 #ifdef DOUG_LEA_MALLOC
177 malloc_state_ptr
= malloc_get_state ();
180 bss_sbrk_did_unexec
= true;
185 alloc_unexec_post (void)
187 #ifdef DOUG_LEA_MALLOC
188 free (malloc_state_ptr
);
191 bss_sbrk_did_unexec
= false;
195 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
196 to a struct Lisp_String. */
198 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
199 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
200 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
202 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
203 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
204 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
206 /* Default value of gc_cons_threshold (see below). */
208 #define GC_DEFAULT_THRESHOLD (100000 * word_size)
210 /* Global variables. */
211 struct emacs_globals globals
;
213 /* Number of bytes of consing done since the last gc. */
215 EMACS_INT consing_since_gc
;
217 /* Similar minimum, computed from Vgc_cons_percentage. */
219 EMACS_INT gc_relative_threshold
;
221 /* Minimum number of bytes of consing since GC before next GC,
222 when memory is full. */
224 EMACS_INT memory_full_cons_threshold
;
226 /* True during GC. */
230 /* True means abort if try to GC.
231 This is for code which is written on the assumption that
232 no GC will happen, so as to verify that assumption. */
236 /* Number of live and free conses etc. */
238 static EMACS_INT total_conses
, total_markers
, total_symbols
, total_buffers
;
239 static EMACS_INT total_free_conses
, total_free_markers
, total_free_symbols
;
240 static EMACS_INT total_free_floats
, total_floats
;
242 /* Points to memory space allocated as "spare", to be freed if we run
243 out of memory. We keep one large block, four cons-blocks, and
244 two string blocks. */
246 static char *spare_memory
[7];
248 /* Amount of spare memory to keep in large reserve block, or to see
249 whether this much is available when malloc fails on a larger request. */
251 #define SPARE_MEMORY (1 << 14)
253 /* Initialize it to a nonzero value to force it into data space
254 (rather than bss space). That way unexec will remap it into text
255 space (pure), on some systems. We have not implemented the
256 remapping on more recent systems because this is less important
257 nowadays than in the days of small memories and timesharing. */
259 EMACS_INT pure
[(PURESIZE
+ sizeof (EMACS_INT
) - 1) / sizeof (EMACS_INT
)] = {1,};
260 #define PUREBEG (char *) pure
262 /* Pointer to the pure area, and its size. */
264 static char *purebeg
;
265 static ptrdiff_t pure_size
;
267 /* Number of bytes of pure storage used before pure storage overflowed.
268 If this is non-zero, this implies that an overflow occurred. */
270 static ptrdiff_t pure_bytes_used_before_overflow
;
272 /* Index in pure at which next pure Lisp object will be allocated.. */
274 static ptrdiff_t pure_bytes_used_lisp
;
276 /* Number of bytes allocated for non-Lisp objects in pure storage. */
278 static ptrdiff_t pure_bytes_used_non_lisp
;
280 /* If nonzero, this is a warning delivered by malloc and not yet
283 const char *pending_malloc_warning
;
285 #if 0 /* Normally, pointer sanity only on request... */
286 #ifdef ENABLE_CHECKING
287 #define SUSPICIOUS_OBJECT_CHECKING 1
291 /* ... but unconditionally use SUSPICIOUS_OBJECT_CHECKING while the GC
292 bug is unresolved. */
293 #define SUSPICIOUS_OBJECT_CHECKING 1
295 #ifdef SUSPICIOUS_OBJECT_CHECKING
296 struct suspicious_free_record
298 void *suspicious_object
;
299 void *backtrace
[128];
301 static void *suspicious_objects
[32];
302 static int suspicious_object_index
;
303 struct suspicious_free_record suspicious_free_history
[64] EXTERNALLY_VISIBLE
;
304 static int suspicious_free_history_index
;
305 /* Find the first currently-monitored suspicious pointer in range
306 [begin,end) or NULL if no such pointer exists. */
307 static void *find_suspicious_object_in_range (void *begin
, void *end
);
308 static void detect_suspicious_free (void *ptr
);
310 # define find_suspicious_object_in_range(begin, end) NULL
311 # define detect_suspicious_free(ptr) (void)
314 /* Maximum amount of C stack to save when a GC happens. */
316 #ifndef MAX_SAVE_STACK
317 #define MAX_SAVE_STACK 16000
320 /* Buffer in which we save a copy of the C stack at each GC. */
322 #if MAX_SAVE_STACK > 0
323 static char *stack_copy
;
324 static ptrdiff_t stack_copy_size
;
326 /* Copy to DEST a block of memory from SRC of size SIZE bytes,
327 avoiding any address sanitization. */
329 static void * ATTRIBUTE_NO_SANITIZE_ADDRESS
330 no_sanitize_memcpy (void *dest
, void const *src
, size_t size
)
332 if (! ADDRESS_SANITIZER
)
333 return memcpy (dest
, src
, size
);
339 for (i
= 0; i
< size
; i
++)
345 #endif /* MAX_SAVE_STACK > 0 */
347 static void mark_terminals (void);
348 static void gc_sweep (void);
349 static Lisp_Object
make_pure_vector (ptrdiff_t);
350 static void mark_buffer (struct buffer
*);
352 #if !defined REL_ALLOC || defined SYSTEM_MALLOC || defined HYBRID_MALLOC
353 static void refill_memory_reserve (void);
355 static void compact_small_strings (void);
356 static void free_large_strings (void);
357 extern Lisp_Object
which_symbols (Lisp_Object
, EMACS_INT
) EXTERNALLY_VISIBLE
;
359 /* When scanning the C stack for live Lisp objects, Emacs keeps track of
360 what memory allocated via lisp_malloc and lisp_align_malloc is intended
361 for what purpose. This enumeration specifies the type of memory. */
372 /* Since all non-bool pseudovectors are small enough to be
373 allocated from vector blocks, this memory type denotes
374 large regular vectors and large bool pseudovectors. */
376 /* Special type to denote vector blocks. */
377 MEM_TYPE_VECTOR_BLOCK
,
378 /* Special type to denote reserved memory. */
382 /* A unique object in pure space used to make some Lisp objects
383 on free lists recognizable in O(1). */
385 static Lisp_Object Vdead
;
386 #define DEADP(x) EQ (x, Vdead)
388 #ifdef GC_MALLOC_CHECK
390 enum mem_type allocated_mem_type
;
392 #endif /* GC_MALLOC_CHECK */
394 /* A node in the red-black tree describing allocated memory containing
395 Lisp data. Each such block is recorded with its start and end
396 address when it is allocated, and removed from the tree when it
399 A red-black tree is a balanced binary tree with the following
402 1. Every node is either red or black.
403 2. Every leaf is black.
404 3. If a node is red, then both of its children are black.
405 4. Every simple path from a node to a descendant leaf contains
406 the same number of black nodes.
407 5. The root is always black.
409 When nodes are inserted into the tree, or deleted from the tree,
410 the tree is "fixed" so that these properties are always true.
412 A red-black tree with N internal nodes has height at most 2
413 log(N+1). Searches, insertions and deletions are done in O(log N).
414 Please see a text book about data structures for a detailed
415 description of red-black trees. Any book worth its salt should
420 /* Children of this node. These pointers are never NULL. When there
421 is no child, the value is MEM_NIL, which points to a dummy node. */
422 struct mem_node
*left
, *right
;
424 /* The parent of this node. In the root node, this is NULL. */
425 struct mem_node
*parent
;
427 /* Start and end of allocated region. */
431 enum {MEM_BLACK
, MEM_RED
} color
;
437 /* Base address of stack. Set in main. */
439 Lisp_Object
*stack_base
;
441 /* Root of the tree describing allocated Lisp memory. */
443 static struct mem_node
*mem_root
;
445 /* Lowest and highest known address in the heap. */
447 static void *min_heap_address
, *max_heap_address
;
449 /* Sentinel node of the tree. */
451 static struct mem_node mem_z
;
452 #define MEM_NIL &mem_z
454 static struct mem_node
*mem_insert (void *, void *, enum mem_type
);
455 static void mem_insert_fixup (struct mem_node
*);
456 static void mem_rotate_left (struct mem_node
*);
457 static void mem_rotate_right (struct mem_node
*);
458 static void mem_delete (struct mem_node
*);
459 static void mem_delete_fixup (struct mem_node
*);
460 static struct mem_node
*mem_find (void *);
466 /* Addresses of staticpro'd variables. Initialize it to a nonzero
467 value; otherwise some compilers put it into BSS. */
469 enum { NSTATICS
= 2048 };
470 static Lisp_Object
*staticvec
[NSTATICS
] = {&Vpurify_flag
};
472 /* Index of next unused slot in staticvec. */
474 static int staticidx
;
476 static void *pure_alloc (size_t, int);
478 /* Return X rounded to the next multiple of Y. Arguments should not
479 have side effects, as they are evaluated more than once. Assume X
480 + Y - 1 does not overflow. Tune for Y being a power of 2. */
482 #define ROUNDUP(x, y) ((y) & ((y) - 1) \
483 ? ((x) + (y) - 1) - ((x) + (y) - 1) % (y) \
484 : ((x) + (y) - 1) & ~ ((y) - 1))
486 /* Return PTR rounded up to the next multiple of ALIGNMENT. */
489 ALIGN (void *ptr
, int alignment
)
491 return (void *) ROUNDUP ((uintptr_t) ptr
, alignment
);
494 /* Extract the pointer hidden within A, if A is not a symbol.
495 If A is a symbol, extract the hidden pointer's offset from lispsym,
496 converted to void *. */
498 #define macro_XPNTR_OR_SYMBOL_OFFSET(a) \
499 ((void *) (intptr_t) (USE_LSB_TAG ? XLI (a) - XTYPE (a) : XLI (a) & VALMASK))
501 /* Extract the pointer hidden within A. */
503 #define macro_XPNTR(a) \
504 ((void *) ((intptr_t) XPNTR_OR_SYMBOL_OFFSET (a) \
505 + (SYMBOLP (a) ? (char *) lispsym : NULL)))
507 /* For pointer access, define XPNTR and XPNTR_OR_SYMBOL_OFFSET as
508 functions, as functions are cleaner and can be used in debuggers.
509 Also, define them as macros if being compiled with GCC without
510 optimization, for performance in that case. The macro_* names are
511 private to this section of code. */
513 static ATTRIBUTE_UNUSED
void *
514 XPNTR_OR_SYMBOL_OFFSET (Lisp_Object a
)
516 return macro_XPNTR_OR_SYMBOL_OFFSET (a
);
518 static ATTRIBUTE_UNUSED
void *
519 XPNTR (Lisp_Object a
)
521 return macro_XPNTR (a
);
524 #if DEFINE_KEY_OPS_AS_MACROS
525 # define XPNTR_OR_SYMBOL_OFFSET(a) macro_XPNTR_OR_SYMBOL_OFFSET (a)
526 # define XPNTR(a) macro_XPNTR (a)
530 XFLOAT_INIT (Lisp_Object f
, double n
)
532 XFLOAT (f
)->u
.data
= n
;
535 #ifdef DOUG_LEA_MALLOC
537 pointers_fit_in_lispobj_p (void)
539 return (UINTPTR_MAX
<= VAL_MAX
) || USE_LSB_TAG
;
543 mmap_lisp_allowed_p (void)
545 /* If we can't store all memory addresses in our lisp objects, it's
546 risky to let the heap use mmap and give us addresses from all
547 over our address space. We also can't use mmap for lisp objects
548 if we might dump: unexec doesn't preserve the contents of mmapped
550 return pointers_fit_in_lispobj_p () && !might_dump
;
554 /* Head of a circularly-linked list of extant finalizers. */
555 static struct Lisp_Finalizer finalizers
;
557 /* Head of a circularly-linked list of finalizers that must be invoked
558 because we deemed them unreachable. This list must be global, and
559 not a local inside garbage_collect_1, in case we GC again while
560 running finalizers. */
561 static struct Lisp_Finalizer doomed_finalizers
;
564 /************************************************************************
566 ************************************************************************/
568 /* Function malloc calls this if it finds we are near exhausting storage. */
571 malloc_warning (const char *str
)
573 pending_malloc_warning
= str
;
577 /* Display an already-pending malloc warning. */
580 display_malloc_warning (void)
582 call3 (intern ("display-warning"),
584 build_string (pending_malloc_warning
),
585 intern ("emergency"));
586 pending_malloc_warning
= 0;
589 /* Called if we can't allocate relocatable space for a buffer. */
592 buffer_memory_full (ptrdiff_t nbytes
)
594 /* If buffers use the relocating allocator, no need to free
595 spare_memory, because we may have plenty of malloc space left
596 that we could get, and if we don't, the malloc that fails will
597 itself cause spare_memory to be freed. If buffers don't use the
598 relocating allocator, treat this like any other failing
602 memory_full (nbytes
);
604 /* This used to call error, but if we've run out of memory, we could
605 get infinite recursion trying to build the string. */
606 xsignal (Qnil
, Vmemory_signal_data
);
610 /* A common multiple of the positive integers A and B. Ideally this
611 would be the least common multiple, but there's no way to do that
612 as a constant expression in C, so do the best that we can easily do. */
613 #define COMMON_MULTIPLE(a, b) \
614 ((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
616 #ifndef XMALLOC_OVERRUN_CHECK
617 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
620 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
623 The header consists of XMALLOC_OVERRUN_CHECK_SIZE fixed bytes
624 followed by XMALLOC_OVERRUN_SIZE_SIZE bytes containing the original
625 block size in little-endian order. The trailer consists of
626 XMALLOC_OVERRUN_CHECK_SIZE fixed bytes.
628 The header is used to detect whether this block has been allocated
629 through these functions, as some low-level libc functions may
630 bypass the malloc hooks. */
632 #define XMALLOC_OVERRUN_CHECK_SIZE 16
633 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
634 (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)
636 /* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
637 hold a size_t value and (2) the header size is a multiple of the
638 alignment that Emacs needs for C types and for USE_LSB_TAG. */
639 #define XMALLOC_BASE_ALIGNMENT alignof (max_align_t)
641 #define XMALLOC_HEADER_ALIGNMENT \
642 COMMON_MULTIPLE (GCALIGNMENT, XMALLOC_BASE_ALIGNMENT)
643 #define XMALLOC_OVERRUN_SIZE_SIZE \
644 (((XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t) \
645 + XMALLOC_HEADER_ALIGNMENT - 1) \
646 / XMALLOC_HEADER_ALIGNMENT * XMALLOC_HEADER_ALIGNMENT) \
647 - XMALLOC_OVERRUN_CHECK_SIZE)
649 static char const xmalloc_overrun_check_header
[XMALLOC_OVERRUN_CHECK_SIZE
] =
650 { '\x9a', '\x9b', '\xae', '\xaf',
651 '\xbf', '\xbe', '\xce', '\xcf',
652 '\xea', '\xeb', '\xec', '\xed',
653 '\xdf', '\xde', '\x9c', '\x9d' };
655 static char const xmalloc_overrun_check_trailer
[XMALLOC_OVERRUN_CHECK_SIZE
] =
656 { '\xaa', '\xab', '\xac', '\xad',
657 '\xba', '\xbb', '\xbc', '\xbd',
658 '\xca', '\xcb', '\xcc', '\xcd',
659 '\xda', '\xdb', '\xdc', '\xdd' };
661 /* Insert and extract the block size in the header. */
664 xmalloc_put_size (unsigned char *ptr
, size_t size
)
667 for (i
= 0; i
< XMALLOC_OVERRUN_SIZE_SIZE
; i
++)
669 *--ptr
= size
& ((1 << CHAR_BIT
) - 1);
675 xmalloc_get_size (unsigned char *ptr
)
679 ptr
-= XMALLOC_OVERRUN_SIZE_SIZE
;
680 for (i
= 0; i
< XMALLOC_OVERRUN_SIZE_SIZE
; i
++)
689 /* Like malloc, but wraps allocated block with header and trailer. */
692 overrun_check_malloc (size_t size
)
694 register unsigned char *val
;
695 if (SIZE_MAX
- XMALLOC_OVERRUN_CHECK_OVERHEAD
< size
)
698 val
= malloc (size
+ XMALLOC_OVERRUN_CHECK_OVERHEAD
);
701 memcpy (val
, xmalloc_overrun_check_header
, XMALLOC_OVERRUN_CHECK_SIZE
);
702 val
+= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
703 xmalloc_put_size (val
, size
);
704 memcpy (val
+ size
, xmalloc_overrun_check_trailer
,
705 XMALLOC_OVERRUN_CHECK_SIZE
);
711 /* Like realloc, but checks old block for overrun, and wraps new block
712 with header and trailer. */
715 overrun_check_realloc (void *block
, size_t size
)
717 register unsigned char *val
= (unsigned char *) block
;
718 if (SIZE_MAX
- XMALLOC_OVERRUN_CHECK_OVERHEAD
< size
)
722 && memcmp (xmalloc_overrun_check_header
,
723 val
- XMALLOC_OVERRUN_CHECK_SIZE
- XMALLOC_OVERRUN_SIZE_SIZE
,
724 XMALLOC_OVERRUN_CHECK_SIZE
) == 0)
726 size_t osize
= xmalloc_get_size (val
);
727 if (memcmp (xmalloc_overrun_check_trailer
, val
+ osize
,
728 XMALLOC_OVERRUN_CHECK_SIZE
))
730 memset (val
+ osize
, 0, XMALLOC_OVERRUN_CHECK_SIZE
);
731 val
-= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
732 memset (val
, 0, XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
);
735 val
= realloc (val
, size
+ XMALLOC_OVERRUN_CHECK_OVERHEAD
);
739 memcpy (val
, xmalloc_overrun_check_header
, XMALLOC_OVERRUN_CHECK_SIZE
);
740 val
+= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
741 xmalloc_put_size (val
, size
);
742 memcpy (val
+ size
, xmalloc_overrun_check_trailer
,
743 XMALLOC_OVERRUN_CHECK_SIZE
);
748 /* Like free, but checks block for overrun. */
751 overrun_check_free (void *block
)
753 unsigned char *val
= (unsigned char *) block
;
756 && memcmp (xmalloc_overrun_check_header
,
757 val
- XMALLOC_OVERRUN_CHECK_SIZE
- XMALLOC_OVERRUN_SIZE_SIZE
,
758 XMALLOC_OVERRUN_CHECK_SIZE
) == 0)
760 size_t osize
= xmalloc_get_size (val
);
761 if (memcmp (xmalloc_overrun_check_trailer
, val
+ osize
,
762 XMALLOC_OVERRUN_CHECK_SIZE
))
764 #ifdef XMALLOC_CLEAR_FREE_MEMORY
765 val
-= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
766 memset (val
, 0xff, osize
+ XMALLOC_OVERRUN_CHECK_OVERHEAD
);
768 memset (val
+ osize
, 0, XMALLOC_OVERRUN_CHECK_SIZE
);
769 val
-= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
770 memset (val
, 0, XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
);
780 #define malloc overrun_check_malloc
781 #define realloc overrun_check_realloc
782 #define free overrun_check_free
785 /* If compiled with XMALLOC_BLOCK_INPUT_CHECK, define a symbol
786 BLOCK_INPUT_IN_MEMORY_ALLOCATORS that is visible to the debugger.
787 If that variable is set, block input while in one of Emacs's memory
788 allocation functions. There should be no need for this debugging
789 option, since signal handlers do not allocate memory, but Emacs
790 formerly allocated memory in signal handlers and this compile-time
791 option remains as a way to help debug the issue should it rear its
793 #ifdef XMALLOC_BLOCK_INPUT_CHECK
794 bool block_input_in_memory_allocators EXTERNALLY_VISIBLE
;
796 malloc_block_input (void)
798 if (block_input_in_memory_allocators
)
802 malloc_unblock_input (void)
804 if (block_input_in_memory_allocators
)
807 # define MALLOC_BLOCK_INPUT malloc_block_input ()
808 # define MALLOC_UNBLOCK_INPUT malloc_unblock_input ()
810 # define MALLOC_BLOCK_INPUT ((void) 0)
811 # define MALLOC_UNBLOCK_INPUT ((void) 0)
814 #define MALLOC_PROBE(size) \
816 if (profiler_memory_running) \
817 malloc_probe (size); \
821 /* Like malloc but check for no memory and block interrupt input.. */
824 xmalloc (size_t size
)
830 MALLOC_UNBLOCK_INPUT
;
838 /* Like the above, but zeroes out the memory just allocated. */
841 xzalloc (size_t size
)
847 MALLOC_UNBLOCK_INPUT
;
851 memset (val
, 0, size
);
856 /* Like realloc but check for no memory and block interrupt input.. */
859 xrealloc (void *block
, size_t size
)
864 /* We must call malloc explicitly when BLOCK is 0, since some
865 reallocs don't do this. */
869 val
= realloc (block
, size
);
870 MALLOC_UNBLOCK_INPUT
;
879 /* Like free but block interrupt input. */
888 MALLOC_UNBLOCK_INPUT
;
889 /* We don't call refill_memory_reserve here
890 because in practice the call in r_alloc_free seems to suffice. */
894 /* Other parts of Emacs pass large int values to allocator functions
895 expecting ptrdiff_t. This is portable in practice, but check it to
897 verify (INT_MAX
<= PTRDIFF_MAX
);
900 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
901 Signal an error on memory exhaustion, and block interrupt input. */
904 xnmalloc (ptrdiff_t nitems
, ptrdiff_t item_size
)
906 eassert (0 <= nitems
&& 0 < item_size
);
908 if (INT_MULTIPLY_WRAPV (nitems
, item_size
, &nbytes
) || SIZE_MAX
< nbytes
)
909 memory_full (SIZE_MAX
);
910 return xmalloc (nbytes
);
914 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
915 Signal an error on memory exhaustion, and block interrupt input. */
918 xnrealloc (void *pa
, ptrdiff_t nitems
, ptrdiff_t item_size
)
920 eassert (0 <= nitems
&& 0 < item_size
);
922 if (INT_MULTIPLY_WRAPV (nitems
, item_size
, &nbytes
) || SIZE_MAX
< nbytes
)
923 memory_full (SIZE_MAX
);
924 return xrealloc (pa
, nbytes
);
928 /* Grow PA, which points to an array of *NITEMS items, and return the
929 location of the reallocated array, updating *NITEMS to reflect its
930 new size. The new array will contain at least NITEMS_INCR_MIN more
931 items, but will not contain more than NITEMS_MAX items total.
932 ITEM_SIZE is the size of each item, in bytes.
934 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
935 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
938 If PA is null, then allocate a new array instead of reallocating
941 Block interrupt input as needed. If memory exhaustion occurs, set
942 *NITEMS to zero if PA is null, and signal an error (i.e., do not
945 Thus, to grow an array A without saving its old contents, do
946 { xfree (A); A = NULL; A = xpalloc (NULL, &AITEMS, ...); }.
947 The A = NULL avoids a dangling pointer if xpalloc exhausts memory
948 and signals an error, and later this code is reexecuted and
949 attempts to free A. */
952 xpalloc (void *pa
, ptrdiff_t *nitems
, ptrdiff_t nitems_incr_min
,
953 ptrdiff_t nitems_max
, ptrdiff_t item_size
)
955 ptrdiff_t n0
= *nitems
;
956 eassume (0 < item_size
&& 0 < nitems_incr_min
&& 0 <= n0
&& -1 <= nitems_max
);
958 /* The approximate size to use for initial small allocation
959 requests. This is the largest "small" request for the GNU C
961 enum { DEFAULT_MXFAST
= 64 * sizeof (size_t) / 4 };
963 /* If the array is tiny, grow it to about (but no greater than)
964 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%.
965 Adjust the growth according to three constraints: NITEMS_INCR_MIN,
966 NITEMS_MAX, and what the C language can represent safely. */
969 if (INT_ADD_WRAPV (n0
, n0
>> 1, &n
))
971 if (0 <= nitems_max
&& nitems_max
< n
)
974 ptrdiff_t adjusted_nbytes
975 = ((INT_MULTIPLY_WRAPV (n
, item_size
, &nbytes
) || SIZE_MAX
< nbytes
)
976 ? min (PTRDIFF_MAX
, SIZE_MAX
)
977 : nbytes
< DEFAULT_MXFAST
? DEFAULT_MXFAST
: 0);
980 n
= adjusted_nbytes
/ item_size
;
981 nbytes
= adjusted_nbytes
- adjusted_nbytes
% item_size
;
986 if (n
- n0
< nitems_incr_min
987 && (INT_ADD_WRAPV (n0
, nitems_incr_min
, &n
)
988 || (0 <= nitems_max
&& nitems_max
< n
)
989 || INT_MULTIPLY_WRAPV (n
, item_size
, &nbytes
)))
990 memory_full (SIZE_MAX
);
991 pa
= xrealloc (pa
, nbytes
);
997 /* Like strdup, but uses xmalloc. */
1000 xstrdup (const char *s
)
1004 size
= strlen (s
) + 1;
1005 return memcpy (xmalloc (size
), s
, size
);
1008 /* Like above, but duplicates Lisp string to C string. */
1011 xlispstrdup (Lisp_Object string
)
1013 ptrdiff_t size
= SBYTES (string
) + 1;
1014 return memcpy (xmalloc (size
), SSDATA (string
), size
);
1017 /* Assign to *PTR a copy of STRING, freeing any storage *PTR formerly
1018 pointed to. If STRING is null, assign it without copying anything.
1019 Allocate before freeing, to avoid a dangling pointer if allocation
1023 dupstring (char **ptr
, char const *string
)
1026 *ptr
= string
? xstrdup (string
) : 0;
1031 /* Like putenv, but (1) use the equivalent of xmalloc and (2) the
1032 argument is a const pointer. */
1035 xputenv (char const *string
)
1037 if (putenv ((char *) string
) != 0)
1041 /* Return a newly allocated memory block of SIZE bytes, remembering
1042 to free it when unwinding. */
1044 record_xmalloc (size_t size
)
1046 void *p
= xmalloc (size
);
1047 record_unwind_protect_ptr (xfree
, p
);
1052 /* Like malloc but used for allocating Lisp data. NBYTES is the
1053 number of bytes to allocate, TYPE describes the intended use of the
1054 allocated memory block (for strings, for conses, ...). */
1057 void *lisp_malloc_loser EXTERNALLY_VISIBLE
;
1061 lisp_malloc (size_t nbytes
, enum mem_type type
)
1067 #ifdef GC_MALLOC_CHECK
1068 allocated_mem_type
= type
;
1071 val
= malloc (nbytes
);
1074 /* If the memory just allocated cannot be addressed thru a Lisp
1075 object's pointer, and it needs to be,
1076 that's equivalent to running out of memory. */
1077 if (val
&& type
!= MEM_TYPE_NON_LISP
)
1080 XSETCONS (tem
, (char *) val
+ nbytes
- 1);
1081 if ((char *) XCONS (tem
) != (char *) val
+ nbytes
- 1)
1083 lisp_malloc_loser
= val
;
1090 #ifndef GC_MALLOC_CHECK
1091 if (val
&& type
!= MEM_TYPE_NON_LISP
)
1092 mem_insert (val
, (char *) val
+ nbytes
, type
);
1095 MALLOC_UNBLOCK_INPUT
;
1097 memory_full (nbytes
);
1098 MALLOC_PROBE (nbytes
);
1102 /* Free BLOCK. This must be called to free memory allocated with a
1103 call to lisp_malloc. */
1106 lisp_free (void *block
)
1110 #ifndef GC_MALLOC_CHECK
1111 mem_delete (mem_find (block
));
1113 MALLOC_UNBLOCK_INPUT
;
1116 /***** Allocation of aligned blocks of memory to store Lisp data. *****/
1118 /* The entry point is lisp_align_malloc which returns blocks of at most
1119 BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
1121 /* Use aligned_alloc if it or a simple substitute is available.
1122 Address sanitization breaks aligned allocation, as of gcc 4.8.2 and
1123 clang 3.3 anyway. */
1125 #if ! ADDRESS_SANITIZER
1126 # if !defined SYSTEM_MALLOC && !defined DOUG_LEA_MALLOC && !defined HYBRID_MALLOC
1127 # define USE_ALIGNED_ALLOC 1
1128 /* Defined in gmalloc.c. */
1129 void *aligned_alloc (size_t, size_t);
1130 # elif defined HYBRID_MALLOC
1131 # if defined ALIGNED_ALLOC || defined HAVE_POSIX_MEMALIGN
1132 # define USE_ALIGNED_ALLOC 1
1133 # define aligned_alloc hybrid_aligned_alloc
1134 /* Defined in gmalloc.c. */
1135 void *aligned_alloc (size_t, size_t);
1137 # elif defined HAVE_ALIGNED_ALLOC
1138 # define USE_ALIGNED_ALLOC 1
1139 # elif defined HAVE_POSIX_MEMALIGN
1140 # define USE_ALIGNED_ALLOC 1
1142 aligned_alloc (size_t alignment
, size_t size
)
1145 return posix_memalign (&p
, alignment
, size
) == 0 ? p
: 0;
1150 /* BLOCK_ALIGN has to be a power of 2. */
1151 #define BLOCK_ALIGN (1 << 10)
1153 /* Padding to leave at the end of a malloc'd block. This is to give
1154 malloc a chance to minimize the amount of memory wasted to alignment.
1155 It should be tuned to the particular malloc library used.
1156 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
1157 aligned_alloc on the other hand would ideally prefer a value of 4
1158 because otherwise, there's 1020 bytes wasted between each ablocks.
1159 In Emacs, testing shows that those 1020 can most of the time be
1160 efficiently used by malloc to place other objects, so a value of 0 can
1161 still preferable unless you have a lot of aligned blocks and virtually
1163 #define BLOCK_PADDING 0
1164 #define BLOCK_BYTES \
1165 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
1167 /* Internal data structures and constants. */
1169 #define ABLOCKS_SIZE 16
1171 /* An aligned block of memory. */
1176 char payload
[BLOCK_BYTES
];
1177 struct ablock
*next_free
;
1179 /* `abase' is the aligned base of the ablocks. */
1180 /* It is overloaded to hold the virtual `busy' field that counts
1181 the number of used ablock in the parent ablocks.
1182 The first ablock has the `busy' field, the others have the `abase'
1183 field. To tell the difference, we assume that pointers will have
1184 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
1185 is used to tell whether the real base of the parent ablocks is `abase'
1186 (if not, the word before the first ablock holds a pointer to the
1188 struct ablocks
*abase
;
1189 /* The padding of all but the last ablock is unused. The padding of
1190 the last ablock in an ablocks is not allocated. */
1192 char padding
[BLOCK_PADDING
];
1196 /* A bunch of consecutive aligned blocks. */
1199 struct ablock blocks
[ABLOCKS_SIZE
];
1202 /* Size of the block requested from malloc or aligned_alloc. */
1203 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
1205 #define ABLOCK_ABASE(block) \
1206 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
1207 ? (struct ablocks *)(block) \
1210 /* Virtual `busy' field. */
1211 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
1213 /* Pointer to the (not necessarily aligned) malloc block. */
1214 #ifdef USE_ALIGNED_ALLOC
1215 #define ABLOCKS_BASE(abase) (abase)
1217 #define ABLOCKS_BASE(abase) \
1218 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void **)abase)[-1])
1221 /* The list of free ablock. */
1222 static struct ablock
*free_ablock
;
1224 /* Allocate an aligned block of nbytes.
1225 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
1226 smaller or equal to BLOCK_BYTES. */
1228 lisp_align_malloc (size_t nbytes
, enum mem_type type
)
1231 struct ablocks
*abase
;
1233 eassert (nbytes
<= BLOCK_BYTES
);
1237 #ifdef GC_MALLOC_CHECK
1238 allocated_mem_type
= type
;
1244 intptr_t aligned
; /* int gets warning casting to 64-bit pointer. */
1246 #ifdef DOUG_LEA_MALLOC
1247 if (!mmap_lisp_allowed_p ())
1248 mallopt (M_MMAP_MAX
, 0);
1251 #ifdef USE_ALIGNED_ALLOC
1252 abase
= base
= aligned_alloc (BLOCK_ALIGN
, ABLOCKS_BYTES
);
1254 base
= malloc (ABLOCKS_BYTES
);
1255 abase
= ALIGN (base
, BLOCK_ALIGN
);
1260 MALLOC_UNBLOCK_INPUT
;
1261 memory_full (ABLOCKS_BYTES
);
1264 aligned
= (base
== abase
);
1266 ((void **) abase
)[-1] = base
;
1268 #ifdef DOUG_LEA_MALLOC
1269 if (!mmap_lisp_allowed_p ())
1270 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
);
1274 /* If the memory just allocated cannot be addressed thru a Lisp
1275 object's pointer, and it needs to be, that's equivalent to
1276 running out of memory. */
1277 if (type
!= MEM_TYPE_NON_LISP
)
1280 char *end
= (char *) base
+ ABLOCKS_BYTES
- 1;
1281 XSETCONS (tem
, end
);
1282 if ((char *) XCONS (tem
) != end
)
1284 lisp_malloc_loser
= base
;
1286 MALLOC_UNBLOCK_INPUT
;
1287 memory_full (SIZE_MAX
);
1292 /* Initialize the blocks and put them on the free list.
1293 If `base' was not properly aligned, we can't use the last block. */
1294 for (i
= 0; i
< (aligned
? ABLOCKS_SIZE
: ABLOCKS_SIZE
- 1); i
++)
1296 abase
->blocks
[i
].abase
= abase
;
1297 abase
->blocks
[i
].x
.next_free
= free_ablock
;
1298 free_ablock
= &abase
->blocks
[i
];
1300 ABLOCKS_BUSY (abase
) = (struct ablocks
*) aligned
;
1302 eassert (0 == ((uintptr_t) abase
) % BLOCK_ALIGN
);
1303 eassert (ABLOCK_ABASE (&abase
->blocks
[3]) == abase
); /* 3 is arbitrary */
1304 eassert (ABLOCK_ABASE (&abase
->blocks
[0]) == abase
);
1305 eassert (ABLOCKS_BASE (abase
) == base
);
1306 eassert (aligned
== (intptr_t) ABLOCKS_BUSY (abase
));
1309 abase
= ABLOCK_ABASE (free_ablock
);
1310 ABLOCKS_BUSY (abase
)
1311 = (struct ablocks
*) (2 + (intptr_t) ABLOCKS_BUSY (abase
));
1313 free_ablock
= free_ablock
->x
.next_free
;
1315 #ifndef GC_MALLOC_CHECK
1316 if (type
!= MEM_TYPE_NON_LISP
)
1317 mem_insert (val
, (char *) val
+ nbytes
, type
);
1320 MALLOC_UNBLOCK_INPUT
;
1322 MALLOC_PROBE (nbytes
);
1324 eassert (0 == ((uintptr_t) val
) % BLOCK_ALIGN
);
1329 lisp_align_free (void *block
)
1331 struct ablock
*ablock
= block
;
1332 struct ablocks
*abase
= ABLOCK_ABASE (ablock
);
1335 #ifndef GC_MALLOC_CHECK
1336 mem_delete (mem_find (block
));
1338 /* Put on free list. */
1339 ablock
->x
.next_free
= free_ablock
;
1340 free_ablock
= ablock
;
1341 /* Update busy count. */
1342 ABLOCKS_BUSY (abase
)
1343 = (struct ablocks
*) (-2 + (intptr_t) ABLOCKS_BUSY (abase
));
1345 if (2 > (intptr_t) ABLOCKS_BUSY (abase
))
1346 { /* All the blocks are free. */
1347 int i
= 0, aligned
= (intptr_t) ABLOCKS_BUSY (abase
);
1348 struct ablock
**tem
= &free_ablock
;
1349 struct ablock
*atop
= &abase
->blocks
[aligned
? ABLOCKS_SIZE
: ABLOCKS_SIZE
- 1];
1353 if (*tem
>= (struct ablock
*) abase
&& *tem
< atop
)
1356 *tem
= (*tem
)->x
.next_free
;
1359 tem
= &(*tem
)->x
.next_free
;
1361 eassert ((aligned
& 1) == aligned
);
1362 eassert (i
== (aligned
? ABLOCKS_SIZE
: ABLOCKS_SIZE
- 1));
1363 #ifdef USE_POSIX_MEMALIGN
1364 eassert ((uintptr_t) ABLOCKS_BASE (abase
) % BLOCK_ALIGN
== 0);
1366 free (ABLOCKS_BASE (abase
));
1368 MALLOC_UNBLOCK_INPUT
;
1372 /***********************************************************************
1374 ***********************************************************************/
1376 /* Number of intervals allocated in an interval_block structure.
1377 The 1020 is 1024 minus malloc overhead. */
1379 #define INTERVAL_BLOCK_SIZE \
1380 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1382 /* Intervals are allocated in chunks in the form of an interval_block
1385 struct interval_block
1387 /* Place `intervals' first, to preserve alignment. */
1388 struct interval intervals
[INTERVAL_BLOCK_SIZE
];
1389 struct interval_block
*next
;
1392 /* Current interval block. Its `next' pointer points to older
1395 static struct interval_block
*interval_block
;
1397 /* Index in interval_block above of the next unused interval
1400 static int interval_block_index
= INTERVAL_BLOCK_SIZE
;
1402 /* Number of free and live intervals. */
1404 static EMACS_INT total_free_intervals
, total_intervals
;
1406 /* List of free intervals. */
1408 static INTERVAL interval_free_list
;
1410 /* Return a new interval. */
1413 make_interval (void)
1419 if (interval_free_list
)
1421 val
= interval_free_list
;
1422 interval_free_list
= INTERVAL_PARENT (interval_free_list
);
1426 if (interval_block_index
== INTERVAL_BLOCK_SIZE
)
1428 struct interval_block
*newi
1429 = lisp_malloc (sizeof *newi
, MEM_TYPE_NON_LISP
);
1431 newi
->next
= interval_block
;
1432 interval_block
= newi
;
1433 interval_block_index
= 0;
1434 total_free_intervals
+= INTERVAL_BLOCK_SIZE
;
1436 val
= &interval_block
->intervals
[interval_block_index
++];
1439 MALLOC_UNBLOCK_INPUT
;
1441 consing_since_gc
+= sizeof (struct interval
);
1443 total_free_intervals
--;
1444 RESET_INTERVAL (val
);
1450 /* Mark Lisp objects in interval I. */
1453 mark_interval (register INTERVAL i
, Lisp_Object dummy
)
1455 /* Intervals should never be shared. So, if extra internal checking is
1456 enabled, GC aborts if it seems to have visited an interval twice. */
1457 eassert (!i
->gcmarkbit
);
1459 mark_object (i
->plist
);
1462 /* Mark the interval tree rooted in I. */
1464 #define MARK_INTERVAL_TREE(i) \
1466 if (i && !i->gcmarkbit) \
1467 traverse_intervals_noorder (i, mark_interval, Qnil); \
1470 /***********************************************************************
1472 ***********************************************************************/
1474 /* Lisp_Strings are allocated in string_block structures. When a new
1475 string_block is allocated, all the Lisp_Strings it contains are
1476 added to a free-list string_free_list. When a new Lisp_String is
1477 needed, it is taken from that list. During the sweep phase of GC,
1478 string_blocks that are entirely free are freed, except two which
1481 String data is allocated from sblock structures. Strings larger
1482 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1483 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1485 Sblocks consist internally of sdata structures, one for each
1486 Lisp_String. The sdata structure points to the Lisp_String it
1487 belongs to. The Lisp_String points back to the `u.data' member of
1488 its sdata structure.
1490 When a Lisp_String is freed during GC, it is put back on
1491 string_free_list, and its `data' member and its sdata's `string'
1492 pointer is set to null. The size of the string is recorded in the
1493 `n.nbytes' member of the sdata. So, sdata structures that are no
1494 longer used, can be easily recognized, and it's easy to compact the
1495 sblocks of small strings which we do in compact_small_strings. */
1497 /* Size in bytes of an sblock structure used for small strings. This
1498 is 8192 minus malloc overhead. */
1500 #define SBLOCK_SIZE 8188
1502 /* Strings larger than this are considered large strings. String data
1503 for large strings is allocated from individual sblocks. */
1505 #define LARGE_STRING_BYTES 1024
1507 /* The SDATA typedef is a struct or union describing string memory
1508 sub-allocated from an sblock. This is where the contents of Lisp
1509 strings are stored. */
1513 /* Back-pointer to the string this sdata belongs to. If null, this
1514 structure is free, and NBYTES (in this structure or in the union below)
1515 contains the string's byte size (the same value that STRING_BYTES
1516 would return if STRING were non-null). If non-null, STRING_BYTES
1517 (STRING) is the size of the data, and DATA contains the string's
1519 struct Lisp_String
*string
;
1521 #ifdef GC_CHECK_STRING_BYTES
1525 unsigned char data
[FLEXIBLE_ARRAY_MEMBER
];
1528 #ifdef GC_CHECK_STRING_BYTES
1530 typedef struct sdata sdata
;
1531 #define SDATA_NBYTES(S) (S)->nbytes
1532 #define SDATA_DATA(S) (S)->data
1538 struct Lisp_String
*string
;
1540 /* When STRING is nonnull, this union is actually of type 'struct sdata',
1541 which has a flexible array member. However, if implemented by
1542 giving this union a member of type 'struct sdata', the union
1543 could not be the last (flexible) member of 'struct sblock',
1544 because C99 prohibits a flexible array member from having a type
1545 that is itself a flexible array. So, comment this member out here,
1546 but remember that the option's there when using this union. */
1551 /* When STRING is null. */
1554 struct Lisp_String
*string
;
1559 #define SDATA_NBYTES(S) (S)->n.nbytes
1560 #define SDATA_DATA(S) ((struct sdata *) (S))->data
1562 #endif /* not GC_CHECK_STRING_BYTES */
1564 enum { SDATA_DATA_OFFSET
= offsetof (struct sdata
, data
) };
1566 /* Structure describing a block of memory which is sub-allocated to
1567 obtain string data memory for strings. Blocks for small strings
1568 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1569 as large as needed. */
1574 struct sblock
*next
;
1576 /* Pointer to the next free sdata block. This points past the end
1577 of the sblock if there isn't any space left in this block. */
1581 sdata data
[FLEXIBLE_ARRAY_MEMBER
];
1584 /* Number of Lisp strings in a string_block structure. The 1020 is
1585 1024 minus malloc overhead. */
1587 #define STRING_BLOCK_SIZE \
1588 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1590 /* Structure describing a block from which Lisp_String structures
1595 /* Place `strings' first, to preserve alignment. */
1596 struct Lisp_String strings
[STRING_BLOCK_SIZE
];
1597 struct string_block
*next
;
1600 /* Head and tail of the list of sblock structures holding Lisp string
1601 data. We always allocate from current_sblock. The NEXT pointers
1602 in the sblock structures go from oldest_sblock to current_sblock. */
1604 static struct sblock
*oldest_sblock
, *current_sblock
;
1606 /* List of sblocks for large strings. */
1608 static struct sblock
*large_sblocks
;
1610 /* List of string_block structures. */
1612 static struct string_block
*string_blocks
;
1614 /* Free-list of Lisp_Strings. */
1616 static struct Lisp_String
*string_free_list
;
1618 /* Number of live and free Lisp_Strings. */
1620 static EMACS_INT total_strings
, total_free_strings
;
1622 /* Number of bytes used by live strings. */
1624 static EMACS_INT total_string_bytes
;
1626 /* Given a pointer to a Lisp_String S which is on the free-list
1627 string_free_list, return a pointer to its successor in the
1630 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1632 /* Return a pointer to the sdata structure belonging to Lisp string S.
1633 S must be live, i.e. S->data must not be null. S->data is actually
1634 a pointer to the `u.data' member of its sdata structure; the
1635 structure starts at a constant offset in front of that. */
1637 #define SDATA_OF_STRING(S) ((sdata *) ((S)->data - SDATA_DATA_OFFSET))
1640 #ifdef GC_CHECK_STRING_OVERRUN
1642 /* We check for overrun in string data blocks by appending a small
1643 "cookie" after each allocated string data block, and check for the
1644 presence of this cookie during GC. */
1646 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1647 static char const string_overrun_cookie
[GC_STRING_OVERRUN_COOKIE_SIZE
] =
1648 { '\xde', '\xad', '\xbe', '\xef' };
1651 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1654 /* Value is the size of an sdata structure large enough to hold NBYTES
1655 bytes of string data. The value returned includes a terminating
1656 NUL byte, the size of the sdata structure, and padding. */
1658 #ifdef GC_CHECK_STRING_BYTES
1660 #define SDATA_SIZE(NBYTES) \
1661 ((SDATA_DATA_OFFSET \
1663 + sizeof (ptrdiff_t) - 1) \
1664 & ~(sizeof (ptrdiff_t) - 1))
1666 #else /* not GC_CHECK_STRING_BYTES */
1668 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1669 less than the size of that member. The 'max' is not needed when
1670 SDATA_DATA_OFFSET is a multiple of sizeof (ptrdiff_t), because then the
1671 alignment code reserves enough space. */
1673 #define SDATA_SIZE(NBYTES) \
1674 ((SDATA_DATA_OFFSET \
1675 + (SDATA_DATA_OFFSET % sizeof (ptrdiff_t) == 0 \
1677 : max (NBYTES, sizeof (ptrdiff_t) - 1)) \
1679 + sizeof (ptrdiff_t) - 1) \
1680 & ~(sizeof (ptrdiff_t) - 1))
1682 #endif /* not GC_CHECK_STRING_BYTES */
1684 /* Extra bytes to allocate for each string. */
1686 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1688 /* Exact bound on the number of bytes in a string, not counting the
1689 terminating null. A string cannot contain more bytes than
1690 STRING_BYTES_BOUND, nor can it be so long that the size_t
1691 arithmetic in allocate_string_data would overflow while it is
1692 calculating a value to be passed to malloc. */
1693 static ptrdiff_t const STRING_BYTES_MAX
=
1694 min (STRING_BYTES_BOUND
,
1695 ((SIZE_MAX
- XMALLOC_OVERRUN_CHECK_OVERHEAD
1697 - offsetof (struct sblock
, data
)
1698 - SDATA_DATA_OFFSET
)
1699 & ~(sizeof (EMACS_INT
) - 1)));
1701 /* Initialize string allocation. Called from init_alloc_once. */
1706 empty_unibyte_string
= make_pure_string ("", 0, 0, 0);
1707 empty_multibyte_string
= make_pure_string ("", 0, 0, 1);
1711 #ifdef GC_CHECK_STRING_BYTES
1713 static int check_string_bytes_count
;
1715 /* Like STRING_BYTES, but with debugging check. Can be
1716 called during GC, so pay attention to the mark bit. */
1719 string_bytes (struct Lisp_String
*s
)
1722 (s
->size_byte
< 0 ? s
->size
& ~ARRAY_MARK_FLAG
: s
->size_byte
);
1724 if (!PURE_P (s
) && s
->data
&& nbytes
!= SDATA_NBYTES (SDATA_OF_STRING (s
)))
1729 /* Check validity of Lisp strings' string_bytes member in B. */
1732 check_sblock (struct sblock
*b
)
1734 sdata
*from
, *end
, *from_end
;
1738 for (from
= b
->data
; from
< end
; from
= from_end
)
1740 /* Compute the next FROM here because copying below may
1741 overwrite data we need to compute it. */
1744 /* Check that the string size recorded in the string is the
1745 same as the one recorded in the sdata structure. */
1746 nbytes
= SDATA_SIZE (from
->string
? string_bytes (from
->string
)
1747 : SDATA_NBYTES (from
));
1748 from_end
= (sdata
*) ((char *) from
+ nbytes
+ GC_STRING_EXTRA
);
1753 /* Check validity of Lisp strings' string_bytes member. ALL_P
1754 means check all strings, otherwise check only most
1755 recently allocated strings. Used for hunting a bug. */
1758 check_string_bytes (bool all_p
)
1764 for (b
= large_sblocks
; b
; b
= b
->next
)
1766 struct Lisp_String
*s
= b
->data
[0].string
;
1771 for (b
= oldest_sblock
; b
; b
= b
->next
)
1774 else if (current_sblock
)
1775 check_sblock (current_sblock
);
1778 #else /* not GC_CHECK_STRING_BYTES */
1780 #define check_string_bytes(all) ((void) 0)
1782 #endif /* GC_CHECK_STRING_BYTES */
1784 #ifdef GC_CHECK_STRING_FREE_LIST
1786 /* Walk through the string free list looking for bogus next pointers.
1787 This may catch buffer overrun from a previous string. */
1790 check_string_free_list (void)
1792 struct Lisp_String
*s
;
1794 /* Pop a Lisp_String off the free-list. */
1795 s
= string_free_list
;
1798 if ((uintptr_t) s
< 1024)
1800 s
= NEXT_FREE_LISP_STRING (s
);
1804 #define check_string_free_list()
1807 /* Return a new Lisp_String. */
1809 static struct Lisp_String
*
1810 allocate_string (void)
1812 struct Lisp_String
*s
;
1816 /* If the free-list is empty, allocate a new string_block, and
1817 add all the Lisp_Strings in it to the free-list. */
1818 if (string_free_list
== NULL
)
1820 struct string_block
*b
= lisp_malloc (sizeof *b
, MEM_TYPE_STRING
);
1823 b
->next
= string_blocks
;
1826 for (i
= STRING_BLOCK_SIZE
- 1; i
>= 0; --i
)
1829 /* Every string on a free list should have NULL data pointer. */
1831 NEXT_FREE_LISP_STRING (s
) = string_free_list
;
1832 string_free_list
= s
;
1835 total_free_strings
+= STRING_BLOCK_SIZE
;
1838 check_string_free_list ();
1840 /* Pop a Lisp_String off the free-list. */
1841 s
= string_free_list
;
1842 string_free_list
= NEXT_FREE_LISP_STRING (s
);
1844 MALLOC_UNBLOCK_INPUT
;
1846 --total_free_strings
;
1849 consing_since_gc
+= sizeof *s
;
1851 #ifdef GC_CHECK_STRING_BYTES
1852 if (!noninteractive
)
1854 if (++check_string_bytes_count
== 200)
1856 check_string_bytes_count
= 0;
1857 check_string_bytes (1);
1860 check_string_bytes (0);
1862 #endif /* GC_CHECK_STRING_BYTES */
1868 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1869 plus a NUL byte at the end. Allocate an sdata structure for S, and
1870 set S->data to its `u.data' member. Store a NUL byte at the end of
1871 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1872 S->data if it was initially non-null. */
1875 allocate_string_data (struct Lisp_String
*s
,
1876 EMACS_INT nchars
, EMACS_INT nbytes
)
1878 sdata
*data
, *old_data
;
1880 ptrdiff_t needed
, old_nbytes
;
1882 if (STRING_BYTES_MAX
< nbytes
)
1885 /* Determine the number of bytes needed to store NBYTES bytes
1887 needed
= SDATA_SIZE (nbytes
);
1890 old_data
= SDATA_OF_STRING (s
);
1891 old_nbytes
= STRING_BYTES (s
);
1898 if (nbytes
> LARGE_STRING_BYTES
)
1900 size_t size
= offsetof (struct sblock
, data
) + needed
;
1902 #ifdef DOUG_LEA_MALLOC
1903 if (!mmap_lisp_allowed_p ())
1904 mallopt (M_MMAP_MAX
, 0);
1907 b
= lisp_malloc (size
+ GC_STRING_EXTRA
, MEM_TYPE_NON_LISP
);
1909 #ifdef DOUG_LEA_MALLOC
1910 if (!mmap_lisp_allowed_p ())
1911 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
);
1914 b
->next_free
= b
->data
;
1915 b
->data
[0].string
= NULL
;
1916 b
->next
= large_sblocks
;
1919 else if (current_sblock
== NULL
1920 || (((char *) current_sblock
+ SBLOCK_SIZE
1921 - (char *) current_sblock
->next_free
)
1922 < (needed
+ GC_STRING_EXTRA
)))
1924 /* Not enough room in the current sblock. */
1925 b
= lisp_malloc (SBLOCK_SIZE
, MEM_TYPE_NON_LISP
);
1926 b
->next_free
= b
->data
;
1927 b
->data
[0].string
= NULL
;
1931 current_sblock
->next
= b
;
1939 data
= b
->next_free
;
1940 b
->next_free
= (sdata
*) ((char *) data
+ needed
+ GC_STRING_EXTRA
);
1942 MALLOC_UNBLOCK_INPUT
;
1945 s
->data
= SDATA_DATA (data
);
1946 #ifdef GC_CHECK_STRING_BYTES
1947 SDATA_NBYTES (data
) = nbytes
;
1950 s
->size_byte
= nbytes
;
1951 s
->data
[nbytes
] = '\0';
1952 #ifdef GC_CHECK_STRING_OVERRUN
1953 memcpy ((char *) data
+ needed
, string_overrun_cookie
,
1954 GC_STRING_OVERRUN_COOKIE_SIZE
);
1957 /* Note that Faset may call to this function when S has already data
1958 assigned. In this case, mark data as free by setting it's string
1959 back-pointer to null, and record the size of the data in it. */
1962 SDATA_NBYTES (old_data
) = old_nbytes
;
1963 old_data
->string
= NULL
;
1966 consing_since_gc
+= needed
;
1970 /* Sweep and compact strings. */
1972 NO_INLINE
/* For better stack traces */
1974 sweep_strings (void)
1976 struct string_block
*b
, *next
;
1977 struct string_block
*live_blocks
= NULL
;
1979 string_free_list
= NULL
;
1980 total_strings
= total_free_strings
= 0;
1981 total_string_bytes
= 0;
1983 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1984 for (b
= string_blocks
; b
; b
= next
)
1987 struct Lisp_String
*free_list_before
= string_free_list
;
1991 for (i
= 0; i
< STRING_BLOCK_SIZE
; ++i
)
1993 struct Lisp_String
*s
= b
->strings
+ i
;
1997 /* String was not on free-list before. */
1998 if (STRING_MARKED_P (s
))
2000 /* String is live; unmark it and its intervals. */
2003 /* Do not use string_(set|get)_intervals here. */
2004 s
->intervals
= balance_intervals (s
->intervals
);
2007 total_string_bytes
+= STRING_BYTES (s
);
2011 /* String is dead. Put it on the free-list. */
2012 sdata
*data
= SDATA_OF_STRING (s
);
2014 /* Save the size of S in its sdata so that we know
2015 how large that is. Reset the sdata's string
2016 back-pointer so that we know it's free. */
2017 #ifdef GC_CHECK_STRING_BYTES
2018 if (string_bytes (s
) != SDATA_NBYTES (data
))
2021 data
->n
.nbytes
= STRING_BYTES (s
);
2023 data
->string
= NULL
;
2025 /* Reset the strings's `data' member so that we
2029 /* Put the string on the free-list. */
2030 NEXT_FREE_LISP_STRING (s
) = string_free_list
;
2031 string_free_list
= s
;
2037 /* S was on the free-list before. Put it there again. */
2038 NEXT_FREE_LISP_STRING (s
) = string_free_list
;
2039 string_free_list
= s
;
2044 /* Free blocks that contain free Lisp_Strings only, except
2045 the first two of them. */
2046 if (nfree
== STRING_BLOCK_SIZE
2047 && total_free_strings
> STRING_BLOCK_SIZE
)
2050 string_free_list
= free_list_before
;
2054 total_free_strings
+= nfree
;
2055 b
->next
= live_blocks
;
2060 check_string_free_list ();
2062 string_blocks
= live_blocks
;
2063 free_large_strings ();
2064 compact_small_strings ();
2066 check_string_free_list ();
2070 /* Free dead large strings. */
2073 free_large_strings (void)
2075 struct sblock
*b
, *next
;
2076 struct sblock
*live_blocks
= NULL
;
2078 for (b
= large_sblocks
; b
; b
= next
)
2082 if (b
->data
[0].string
== NULL
)
2086 b
->next
= live_blocks
;
2091 large_sblocks
= live_blocks
;
2095 /* Compact data of small strings. Free sblocks that don't contain
2096 data of live strings after compaction. */
2099 compact_small_strings (void)
2101 struct sblock
*b
, *tb
, *next
;
2102 sdata
*from
, *to
, *end
, *tb_end
;
2103 sdata
*to_end
, *from_end
;
2105 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2106 to, and TB_END is the end of TB. */
2108 tb_end
= (sdata
*) ((char *) tb
+ SBLOCK_SIZE
);
2111 /* Step through the blocks from the oldest to the youngest. We
2112 expect that old blocks will stabilize over time, so that less
2113 copying will happen this way. */
2114 for (b
= oldest_sblock
; b
; b
= b
->next
)
2117 eassert ((char *) end
<= (char *) b
+ SBLOCK_SIZE
);
2119 for (from
= b
->data
; from
< end
; from
= from_end
)
2121 /* Compute the next FROM here because copying below may
2122 overwrite data we need to compute it. */
2124 struct Lisp_String
*s
= from
->string
;
2126 #ifdef GC_CHECK_STRING_BYTES
2127 /* Check that the string size recorded in the string is the
2128 same as the one recorded in the sdata structure. */
2129 if (s
&& string_bytes (s
) != SDATA_NBYTES (from
))
2131 #endif /* GC_CHECK_STRING_BYTES */
2133 nbytes
= s
? STRING_BYTES (s
) : SDATA_NBYTES (from
);
2134 eassert (nbytes
<= LARGE_STRING_BYTES
);
2136 nbytes
= SDATA_SIZE (nbytes
);
2137 from_end
= (sdata
*) ((char *) from
+ nbytes
+ GC_STRING_EXTRA
);
2139 #ifdef GC_CHECK_STRING_OVERRUN
2140 if (memcmp (string_overrun_cookie
,
2141 (char *) from_end
- GC_STRING_OVERRUN_COOKIE_SIZE
,
2142 GC_STRING_OVERRUN_COOKIE_SIZE
))
2146 /* Non-NULL S means it's alive. Copy its data. */
2149 /* If TB is full, proceed with the next sblock. */
2150 to_end
= (sdata
*) ((char *) to
+ nbytes
+ GC_STRING_EXTRA
);
2151 if (to_end
> tb_end
)
2155 tb_end
= (sdata
*) ((char *) tb
+ SBLOCK_SIZE
);
2157 to_end
= (sdata
*) ((char *) to
+ nbytes
+ GC_STRING_EXTRA
);
2160 /* Copy, and update the string's `data' pointer. */
2163 eassert (tb
!= b
|| to
< from
);
2164 memmove (to
, from
, nbytes
+ GC_STRING_EXTRA
);
2165 to
->string
->data
= SDATA_DATA (to
);
2168 /* Advance past the sdata we copied to. */
2174 /* The rest of the sblocks following TB don't contain live data, so
2175 we can free them. */
2176 for (b
= tb
->next
; b
; b
= next
)
2184 current_sblock
= tb
;
2188 string_overflow (void)
2190 error ("Maximum string size exceeded");
2193 DEFUN ("make-string", Fmake_string
, Smake_string
, 2, 2, 0,
2194 doc
: /* Return a newly created string of length LENGTH, with INIT in each element.
2195 LENGTH must be an integer.
2196 INIT must be an integer that represents a character. */)
2197 (Lisp_Object length
, Lisp_Object init
)
2199 register Lisp_Object val
;
2203 CHECK_NATNUM (length
);
2204 CHECK_CHARACTER (init
);
2206 c
= XFASTINT (init
);
2207 if (ASCII_CHAR_P (c
))
2209 nbytes
= XINT (length
);
2210 val
= make_uninit_string (nbytes
);
2213 memset (SDATA (val
), c
, nbytes
);
2214 SDATA (val
)[nbytes
] = 0;
2219 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
2220 ptrdiff_t len
= CHAR_STRING (c
, str
);
2221 EMACS_INT string_len
= XINT (length
);
2222 unsigned char *p
, *beg
, *end
;
2224 if (INT_MULTIPLY_WRAPV (len
, string_len
, &nbytes
))
2226 val
= make_uninit_multibyte_string (string_len
, nbytes
);
2227 for (beg
= SDATA (val
), p
= beg
, end
= beg
+ nbytes
; p
< end
; p
+= len
)
2229 /* First time we just copy `str' to the data of `val'. */
2231 memcpy (p
, str
, len
);
2234 /* Next time we copy largest possible chunk from
2235 initialized to uninitialized part of `val'. */
2236 len
= min (p
- beg
, end
- p
);
2237 memcpy (p
, beg
, len
);
2247 /* Fill A with 1 bits if INIT is non-nil, and with 0 bits otherwise.
2251 bool_vector_fill (Lisp_Object a
, Lisp_Object init
)
2253 EMACS_INT nbits
= bool_vector_size (a
);
2256 unsigned char *data
= bool_vector_uchar_data (a
);
2257 int pattern
= NILP (init
) ? 0 : (1 << BOOL_VECTOR_BITS_PER_CHAR
) - 1;
2258 ptrdiff_t nbytes
= bool_vector_bytes (nbits
);
2259 int last_mask
= ~ (~0u << ((nbits
- 1) % BOOL_VECTOR_BITS_PER_CHAR
+ 1));
2260 memset (data
, pattern
, nbytes
- 1);
2261 data
[nbytes
- 1] = pattern
& last_mask
;
2266 /* Return a newly allocated, uninitialized bool vector of size NBITS. */
2269 make_uninit_bool_vector (EMACS_INT nbits
)
2272 EMACS_INT words
= bool_vector_words (nbits
);
2273 EMACS_INT word_bytes
= words
* sizeof (bits_word
);
2274 EMACS_INT needed_elements
= ((bool_header_size
- header_size
+ word_bytes
2277 struct Lisp_Bool_Vector
*p
2278 = (struct Lisp_Bool_Vector
*) allocate_vector (needed_elements
);
2279 XSETVECTOR (val
, p
);
2280 XSETPVECTYPESIZE (XVECTOR (val
), PVEC_BOOL_VECTOR
, 0, 0);
2283 /* Clear padding at the end. */
2285 p
->data
[words
- 1] = 0;
2290 DEFUN ("make-bool-vector", Fmake_bool_vector
, Smake_bool_vector
, 2, 2, 0,
2291 doc
: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2292 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2293 (Lisp_Object length
, Lisp_Object init
)
2297 CHECK_NATNUM (length
);
2298 val
= make_uninit_bool_vector (XFASTINT (length
));
2299 return bool_vector_fill (val
, init
);
2302 DEFUN ("bool-vector", Fbool_vector
, Sbool_vector
, 0, MANY
, 0,
2303 doc
: /* Return a new bool-vector with specified arguments as elements.
2304 Any number of arguments, even zero arguments, are allowed.
2305 usage: (bool-vector &rest OBJECTS) */)
2306 (ptrdiff_t nargs
, Lisp_Object
*args
)
2311 vector
= make_uninit_bool_vector (nargs
);
2312 for (i
= 0; i
< nargs
; i
++)
2313 bool_vector_set (vector
, i
, !NILP (args
[i
]));
2318 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2319 of characters from the contents. This string may be unibyte or
2320 multibyte, depending on the contents. */
2323 make_string (const char *contents
, ptrdiff_t nbytes
)
2325 register Lisp_Object val
;
2326 ptrdiff_t nchars
, multibyte_nbytes
;
2328 parse_str_as_multibyte ((const unsigned char *) contents
, nbytes
,
2329 &nchars
, &multibyte_nbytes
);
2330 if (nbytes
== nchars
|| nbytes
!= multibyte_nbytes
)
2331 /* CONTENTS contains no multibyte sequences or contains an invalid
2332 multibyte sequence. We must make unibyte string. */
2333 val
= make_unibyte_string (contents
, nbytes
);
2335 val
= make_multibyte_string (contents
, nchars
, nbytes
);
2339 /* Make a unibyte string from LENGTH bytes at CONTENTS. */
2342 make_unibyte_string (const char *contents
, ptrdiff_t length
)
2344 register Lisp_Object val
;
2345 val
= make_uninit_string (length
);
2346 memcpy (SDATA (val
), contents
, length
);
2351 /* Make a multibyte string from NCHARS characters occupying NBYTES
2352 bytes at CONTENTS. */
2355 make_multibyte_string (const char *contents
,
2356 ptrdiff_t nchars
, ptrdiff_t nbytes
)
2358 register Lisp_Object val
;
2359 val
= make_uninit_multibyte_string (nchars
, nbytes
);
2360 memcpy (SDATA (val
), contents
, nbytes
);
2365 /* Make a string from NCHARS characters occupying NBYTES bytes at
2366 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2369 make_string_from_bytes (const char *contents
,
2370 ptrdiff_t nchars
, ptrdiff_t nbytes
)
2372 register Lisp_Object val
;
2373 val
= make_uninit_multibyte_string (nchars
, nbytes
);
2374 memcpy (SDATA (val
), contents
, nbytes
);
2375 if (SBYTES (val
) == SCHARS (val
))
2376 STRING_SET_UNIBYTE (val
);
2381 /* Make a string from NCHARS characters occupying NBYTES bytes at
2382 CONTENTS. The argument MULTIBYTE controls whether to label the
2383 string as multibyte. If NCHARS is negative, it counts the number of
2384 characters by itself. */
2387 make_specified_string (const char *contents
,
2388 ptrdiff_t nchars
, ptrdiff_t nbytes
, bool multibyte
)
2395 nchars
= multibyte_chars_in_text ((const unsigned char *) contents
,
2400 val
= make_uninit_multibyte_string (nchars
, nbytes
);
2401 memcpy (SDATA (val
), contents
, nbytes
);
2403 STRING_SET_UNIBYTE (val
);
2408 /* Return a unibyte Lisp_String set up to hold LENGTH characters
2409 occupying LENGTH bytes. */
2412 make_uninit_string (EMACS_INT length
)
2417 return empty_unibyte_string
;
2418 val
= make_uninit_multibyte_string (length
, length
);
2419 STRING_SET_UNIBYTE (val
);
2424 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2425 which occupy NBYTES bytes. */
2428 make_uninit_multibyte_string (EMACS_INT nchars
, EMACS_INT nbytes
)
2431 struct Lisp_String
*s
;
2436 return empty_multibyte_string
;
2438 s
= allocate_string ();
2439 s
->intervals
= NULL
;
2440 allocate_string_data (s
, nchars
, nbytes
);
2441 XSETSTRING (string
, s
);
2442 string_chars_consed
+= nbytes
;
2446 /* Print arguments to BUF according to a FORMAT, then return
2447 a Lisp_String initialized with the data from BUF. */
2450 make_formatted_string (char *buf
, const char *format
, ...)
2455 va_start (ap
, format
);
2456 length
= vsprintf (buf
, format
, ap
);
2458 return make_string (buf
, length
);
2462 /***********************************************************************
2464 ***********************************************************************/
2466 /* We store float cells inside of float_blocks, allocating a new
2467 float_block with malloc whenever necessary. Float cells reclaimed
2468 by GC are put on a free list to be reallocated before allocating
2469 any new float cells from the latest float_block. */
2471 #define FLOAT_BLOCK_SIZE \
2472 (((BLOCK_BYTES - sizeof (struct float_block *) \
2473 /* The compiler might add padding at the end. */ \
2474 - (sizeof (struct Lisp_Float) - sizeof (bits_word))) * CHAR_BIT) \
2475 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2477 #define GETMARKBIT(block,n) \
2478 (((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2479 >> ((n) % BITS_PER_BITS_WORD)) \
2482 #define SETMARKBIT(block,n) \
2483 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2484 |= (bits_word) 1 << ((n) % BITS_PER_BITS_WORD))
2486 #define UNSETMARKBIT(block,n) \
2487 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2488 &= ~((bits_word) 1 << ((n) % BITS_PER_BITS_WORD)))
2490 #define FLOAT_BLOCK(fptr) \
2491 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2493 #define FLOAT_INDEX(fptr) \
2494 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2498 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2499 struct Lisp_Float floats
[FLOAT_BLOCK_SIZE
];
2500 bits_word gcmarkbits
[1 + FLOAT_BLOCK_SIZE
/ BITS_PER_BITS_WORD
];
2501 struct float_block
*next
;
2504 #define FLOAT_MARKED_P(fptr) \
2505 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2507 #define FLOAT_MARK(fptr) \
2508 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2510 #define FLOAT_UNMARK(fptr) \
2511 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2513 /* Current float_block. */
2515 static struct float_block
*float_block
;
2517 /* Index of first unused Lisp_Float in the current float_block. */
2519 static int float_block_index
= FLOAT_BLOCK_SIZE
;
2521 /* Free-list of Lisp_Floats. */
2523 static struct Lisp_Float
*float_free_list
;
2525 /* Return a new float object with value FLOAT_VALUE. */
2528 make_float (double float_value
)
2530 register Lisp_Object val
;
2534 if (float_free_list
)
2536 /* We use the data field for chaining the free list
2537 so that we won't use the same field that has the mark bit. */
2538 XSETFLOAT (val
, float_free_list
);
2539 float_free_list
= float_free_list
->u
.chain
;
2543 if (float_block_index
== FLOAT_BLOCK_SIZE
)
2545 struct float_block
*new
2546 = lisp_align_malloc (sizeof *new, MEM_TYPE_FLOAT
);
2547 new->next
= float_block
;
2548 memset (new->gcmarkbits
, 0, sizeof new->gcmarkbits
);
2550 float_block_index
= 0;
2551 total_free_floats
+= FLOAT_BLOCK_SIZE
;
2553 XSETFLOAT (val
, &float_block
->floats
[float_block_index
]);
2554 float_block_index
++;
2557 MALLOC_UNBLOCK_INPUT
;
2559 XFLOAT_INIT (val
, float_value
);
2560 eassert (!FLOAT_MARKED_P (XFLOAT (val
)));
2561 consing_since_gc
+= sizeof (struct Lisp_Float
);
2563 total_free_floats
--;
2569 /***********************************************************************
2571 ***********************************************************************/
2573 /* We store cons cells inside of cons_blocks, allocating a new
2574 cons_block with malloc whenever necessary. Cons cells reclaimed by
2575 GC are put on a free list to be reallocated before allocating
2576 any new cons cells from the latest cons_block. */
2578 #define CONS_BLOCK_SIZE \
2579 (((BLOCK_BYTES - sizeof (struct cons_block *) \
2580 /* The compiler might add padding at the end. */ \
2581 - (sizeof (struct Lisp_Cons) - sizeof (bits_word))) * CHAR_BIT) \
2582 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2584 #define CONS_BLOCK(fptr) \
2585 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2587 #define CONS_INDEX(fptr) \
2588 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2592 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2593 struct Lisp_Cons conses
[CONS_BLOCK_SIZE
];
2594 bits_word gcmarkbits
[1 + CONS_BLOCK_SIZE
/ BITS_PER_BITS_WORD
];
2595 struct cons_block
*next
;
2598 #define CONS_MARKED_P(fptr) \
2599 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2601 #define CONS_MARK(fptr) \
2602 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2604 #define CONS_UNMARK(fptr) \
2605 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2607 /* Current cons_block. */
2609 static struct cons_block
*cons_block
;
2611 /* Index of first unused Lisp_Cons in the current block. */
2613 static int cons_block_index
= CONS_BLOCK_SIZE
;
2615 /* Free-list of Lisp_Cons structures. */
2617 static struct Lisp_Cons
*cons_free_list
;
2619 /* Explicitly free a cons cell by putting it on the free-list. */
2622 free_cons (struct Lisp_Cons
*ptr
)
2624 ptr
->u
.chain
= cons_free_list
;
2626 cons_free_list
= ptr
;
2627 consing_since_gc
-= sizeof *ptr
;
2628 total_free_conses
++;
2631 DEFUN ("cons", Fcons
, Scons
, 2, 2, 0,
2632 doc
: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2633 (Lisp_Object car
, Lisp_Object cdr
)
2635 register Lisp_Object val
;
2641 /* We use the cdr for chaining the free list
2642 so that we won't use the same field that has the mark bit. */
2643 XSETCONS (val
, cons_free_list
);
2644 cons_free_list
= cons_free_list
->u
.chain
;
2648 if (cons_block_index
== CONS_BLOCK_SIZE
)
2650 struct cons_block
*new
2651 = lisp_align_malloc (sizeof *new, MEM_TYPE_CONS
);
2652 memset (new->gcmarkbits
, 0, sizeof new->gcmarkbits
);
2653 new->next
= cons_block
;
2655 cons_block_index
= 0;
2656 total_free_conses
+= CONS_BLOCK_SIZE
;
2658 XSETCONS (val
, &cons_block
->conses
[cons_block_index
]);
2662 MALLOC_UNBLOCK_INPUT
;
2666 eassert (!CONS_MARKED_P (XCONS (val
)));
2667 consing_since_gc
+= sizeof (struct Lisp_Cons
);
2668 total_free_conses
--;
2669 cons_cells_consed
++;
2673 #ifdef GC_CHECK_CONS_LIST
2674 /* Get an error now if there's any junk in the cons free list. */
2676 check_cons_list (void)
2678 struct Lisp_Cons
*tail
= cons_free_list
;
2681 tail
= tail
->u
.chain
;
2685 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2688 list1 (Lisp_Object arg1
)
2690 return Fcons (arg1
, Qnil
);
2694 list2 (Lisp_Object arg1
, Lisp_Object arg2
)
2696 return Fcons (arg1
, Fcons (arg2
, Qnil
));
2701 list3 (Lisp_Object arg1
, Lisp_Object arg2
, Lisp_Object arg3
)
2703 return Fcons (arg1
, Fcons (arg2
, Fcons (arg3
, Qnil
)));
2708 list4 (Lisp_Object arg1
, Lisp_Object arg2
, Lisp_Object arg3
, Lisp_Object arg4
)
2710 return Fcons (arg1
, Fcons (arg2
, Fcons (arg3
, Fcons (arg4
, Qnil
))));
2715 list5 (Lisp_Object arg1
, Lisp_Object arg2
, Lisp_Object arg3
, Lisp_Object arg4
, Lisp_Object arg5
)
2717 return Fcons (arg1
, Fcons (arg2
, Fcons (arg3
, Fcons (arg4
,
2718 Fcons (arg5
, Qnil
)))));
2721 /* Make a list of COUNT Lisp_Objects, where ARG is the
2722 first one. Allocate conses from pure space if TYPE
2723 is CONSTYPE_PURE, or allocate as usual if type is CONSTYPE_HEAP. */
2726 listn (enum constype type
, ptrdiff_t count
, Lisp_Object arg
, ...)
2728 Lisp_Object (*cons
) (Lisp_Object
, Lisp_Object
);
2731 case CONSTYPE_PURE
: cons
= pure_cons
; break;
2732 case CONSTYPE_HEAP
: cons
= Fcons
; break;
2733 default: emacs_abort ();
2736 eassume (0 < count
);
2737 Lisp_Object val
= cons (arg
, Qnil
);
2738 Lisp_Object tail
= val
;
2742 for (ptrdiff_t i
= 1; i
< count
; i
++)
2744 Lisp_Object elem
= cons (va_arg (ap
, Lisp_Object
), Qnil
);
2745 XSETCDR (tail
, elem
);
2753 DEFUN ("list", Flist
, Slist
, 0, MANY
, 0,
2754 doc
: /* Return a newly created list with specified arguments as elements.
2755 Any number of arguments, even zero arguments, are allowed.
2756 usage: (list &rest OBJECTS) */)
2757 (ptrdiff_t nargs
, Lisp_Object
*args
)
2759 register Lisp_Object val
;
2765 val
= Fcons (args
[nargs
], val
);
2771 DEFUN ("make-list", Fmake_list
, Smake_list
, 2, 2, 0,
2772 doc
: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2773 (register Lisp_Object length
, Lisp_Object init
)
2775 register Lisp_Object val
;
2776 register EMACS_INT size
;
2778 CHECK_NATNUM (length
);
2779 size
= XFASTINT (length
);
2784 val
= Fcons (init
, val
);
2789 val
= Fcons (init
, val
);
2794 val
= Fcons (init
, val
);
2799 val
= Fcons (init
, val
);
2804 val
= Fcons (init
, val
);
2819 /***********************************************************************
2821 ***********************************************************************/
2823 /* Sometimes a vector's contents are merely a pointer internally used
2824 in vector allocation code. On the rare platforms where a null
2825 pointer cannot be tagged, represent it with a Lisp 0.
2826 Usually you don't want to touch this. */
2828 static struct Lisp_Vector
*
2829 next_vector (struct Lisp_Vector
*v
)
2831 return XUNTAG (v
->contents
[0], Lisp_Int0
);
2835 set_next_vector (struct Lisp_Vector
*v
, struct Lisp_Vector
*p
)
2837 v
->contents
[0] = make_lisp_ptr (p
, Lisp_Int0
);
2840 /* This value is balanced well enough to avoid too much internal overhead
2841 for the most common cases; it's not required to be a power of two, but
2842 it's expected to be a mult-of-ROUNDUP_SIZE (see below). */
2844 #define VECTOR_BLOCK_SIZE 4096
2848 /* Alignment of struct Lisp_Vector objects. */
2849 vector_alignment
= COMMON_MULTIPLE (ALIGNOF_STRUCT_LISP_VECTOR
,
2852 /* Vector size requests are a multiple of this. */
2853 roundup_size
= COMMON_MULTIPLE (vector_alignment
, word_size
)
2856 /* Verify assumptions described above. */
2857 verify ((VECTOR_BLOCK_SIZE
% roundup_size
) == 0);
2858 verify (VECTOR_BLOCK_SIZE
<= (1 << PSEUDOVECTOR_SIZE_BITS
));
2860 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at compile time. */
2861 #define vroundup_ct(x) ROUNDUP (x, roundup_size)
2862 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at runtime. */
2863 #define vroundup(x) (eassume ((x) >= 0), vroundup_ct (x))
2865 /* Rounding helps to maintain alignment constraints if USE_LSB_TAG. */
2867 #define VECTOR_BLOCK_BYTES (VECTOR_BLOCK_SIZE - vroundup_ct (sizeof (void *)))
2869 /* Size of the minimal vector allocated from block. */
2871 #define VBLOCK_BYTES_MIN vroundup_ct (header_size + sizeof (Lisp_Object))
2873 /* Size of the largest vector allocated from block. */
2875 #define VBLOCK_BYTES_MAX \
2876 vroundup ((VECTOR_BLOCK_BYTES / 2) - word_size)
2878 /* We maintain one free list for each possible block-allocated
2879 vector size, and this is the number of free lists we have. */
2881 #define VECTOR_MAX_FREE_LIST_INDEX \
2882 ((VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN) / roundup_size + 1)
2884 /* Common shortcut to advance vector pointer over a block data. */
2886 #define ADVANCE(v, nbytes) ((struct Lisp_Vector *) ((char *) (v) + (nbytes)))
2888 /* Common shortcut to calculate NBYTES-vector index in VECTOR_FREE_LISTS. */
2890 #define VINDEX(nbytes) (((nbytes) - VBLOCK_BYTES_MIN) / roundup_size)
2892 /* Common shortcut to setup vector on a free list. */
2894 #define SETUP_ON_FREE_LIST(v, nbytes, tmp) \
2896 (tmp) = ((nbytes - header_size) / word_size); \
2897 XSETPVECTYPESIZE (v, PVEC_FREE, 0, (tmp)); \
2898 eassert ((nbytes) % roundup_size == 0); \
2899 (tmp) = VINDEX (nbytes); \
2900 eassert ((tmp) < VECTOR_MAX_FREE_LIST_INDEX); \
2901 set_next_vector (v, vector_free_lists[tmp]); \
2902 vector_free_lists[tmp] = (v); \
2903 total_free_vector_slots += (nbytes) / word_size; \
2906 /* This internal type is used to maintain the list of large vectors
2907 which are allocated at their own, e.g. outside of vector blocks.
2909 struct large_vector itself cannot contain a struct Lisp_Vector, as
2910 the latter contains a flexible array member and C99 does not allow
2911 such structs to be nested. Instead, each struct large_vector
2912 object LV is followed by a struct Lisp_Vector, which is at offset
2913 large_vector_offset from LV, and whose address is therefore
2914 large_vector_vec (&LV). */
2918 struct large_vector
*next
;
2923 large_vector_offset
= ROUNDUP (sizeof (struct large_vector
), vector_alignment
)
2926 static struct Lisp_Vector
*
2927 large_vector_vec (struct large_vector
*p
)
2929 return (struct Lisp_Vector
*) ((char *) p
+ large_vector_offset
);
2932 /* This internal type is used to maintain an underlying storage
2933 for small vectors. */
2937 char data
[VECTOR_BLOCK_BYTES
];
2938 struct vector_block
*next
;
2941 /* Chain of vector blocks. */
2943 static struct vector_block
*vector_blocks
;
2945 /* Vector free lists, where NTH item points to a chain of free
2946 vectors of the same NBYTES size, so NTH == VINDEX (NBYTES). */
2948 static struct Lisp_Vector
*vector_free_lists
[VECTOR_MAX_FREE_LIST_INDEX
];
2950 /* Singly-linked list of large vectors. */
2952 static struct large_vector
*large_vectors
;
2954 /* The only vector with 0 slots, allocated from pure space. */
2956 Lisp_Object zero_vector
;
2958 /* Number of live vectors. */
2960 static EMACS_INT total_vectors
;
2962 /* Total size of live and free vectors, in Lisp_Object units. */
2964 static EMACS_INT total_vector_slots
, total_free_vector_slots
;
2966 /* Get a new vector block. */
2968 static struct vector_block
*
2969 allocate_vector_block (void)
2971 struct vector_block
*block
= xmalloc (sizeof *block
);
2973 #ifndef GC_MALLOC_CHECK
2974 mem_insert (block
->data
, block
->data
+ VECTOR_BLOCK_BYTES
,
2975 MEM_TYPE_VECTOR_BLOCK
);
2978 block
->next
= vector_blocks
;
2979 vector_blocks
= block
;
2983 /* Called once to initialize vector allocation. */
2988 zero_vector
= make_pure_vector (0);
2991 /* Allocate vector from a vector block. */
2993 static struct Lisp_Vector
*
2994 allocate_vector_from_block (size_t nbytes
)
2996 struct Lisp_Vector
*vector
;
2997 struct vector_block
*block
;
2998 size_t index
, restbytes
;
3000 eassert (VBLOCK_BYTES_MIN
<= nbytes
&& nbytes
<= VBLOCK_BYTES_MAX
);
3001 eassert (nbytes
% roundup_size
== 0);
3003 /* First, try to allocate from a free list
3004 containing vectors of the requested size. */
3005 index
= VINDEX (nbytes
);
3006 if (vector_free_lists
[index
])
3008 vector
= vector_free_lists
[index
];
3009 vector_free_lists
[index
] = next_vector (vector
);
3010 total_free_vector_slots
-= nbytes
/ word_size
;
3014 /* Next, check free lists containing larger vectors. Since
3015 we will split the result, we should have remaining space
3016 large enough to use for one-slot vector at least. */
3017 for (index
= VINDEX (nbytes
+ VBLOCK_BYTES_MIN
);
3018 index
< VECTOR_MAX_FREE_LIST_INDEX
; index
++)
3019 if (vector_free_lists
[index
])
3021 /* This vector is larger than requested. */
3022 vector
= vector_free_lists
[index
];
3023 vector_free_lists
[index
] = next_vector (vector
);
3024 total_free_vector_slots
-= nbytes
/ word_size
;
3026 /* Excess bytes are used for the smaller vector,
3027 which should be set on an appropriate free list. */
3028 restbytes
= index
* roundup_size
+ VBLOCK_BYTES_MIN
- nbytes
;
3029 eassert (restbytes
% roundup_size
== 0);
3030 SETUP_ON_FREE_LIST (ADVANCE (vector
, nbytes
), restbytes
, index
);
3034 /* Finally, need a new vector block. */
3035 block
= allocate_vector_block ();
3037 /* New vector will be at the beginning of this block. */
3038 vector
= (struct Lisp_Vector
*) block
->data
;
3040 /* If the rest of space from this block is large enough
3041 for one-slot vector at least, set up it on a free list. */
3042 restbytes
= VECTOR_BLOCK_BYTES
- nbytes
;
3043 if (restbytes
>= VBLOCK_BYTES_MIN
)
3045 eassert (restbytes
% roundup_size
== 0);
3046 SETUP_ON_FREE_LIST (ADVANCE (vector
, nbytes
), restbytes
, index
);
3051 /* Nonzero if VECTOR pointer is valid pointer inside BLOCK. */
3053 #define VECTOR_IN_BLOCK(vector, block) \
3054 ((char *) (vector) <= (block)->data \
3055 + VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN)
3057 /* Return the memory footprint of V in bytes. */
3060 vector_nbytes (struct Lisp_Vector
*v
)
3062 ptrdiff_t size
= v
->header
.size
& ~ARRAY_MARK_FLAG
;
3065 if (size
& PSEUDOVECTOR_FLAG
)
3067 if (PSEUDOVECTOR_TYPEP (&v
->header
, PVEC_BOOL_VECTOR
))
3069 struct Lisp_Bool_Vector
*bv
= (struct Lisp_Bool_Vector
*) v
;
3070 ptrdiff_t word_bytes
= (bool_vector_words (bv
->size
)
3071 * sizeof (bits_word
));
3072 ptrdiff_t boolvec_bytes
= bool_header_size
+ word_bytes
;
3073 verify (header_size
<= bool_header_size
);
3074 nwords
= (boolvec_bytes
- header_size
+ word_size
- 1) / word_size
;
3077 nwords
= ((size
& PSEUDOVECTOR_SIZE_MASK
)
3078 + ((size
& PSEUDOVECTOR_REST_MASK
)
3079 >> PSEUDOVECTOR_SIZE_BITS
));
3083 return vroundup (header_size
+ word_size
* nwords
);
3086 /* Release extra resources still in use by VECTOR, which may be any
3087 vector-like object. For now, this is used just to free data in
3091 cleanup_vector (struct Lisp_Vector
*vector
)
3093 detect_suspicious_free (vector
);
3094 if (PSEUDOVECTOR_TYPEP (&vector
->header
, PVEC_FONT
)
3095 && ((vector
->header
.size
& PSEUDOVECTOR_SIZE_MASK
)
3096 == FONT_OBJECT_MAX
))
3098 struct font_driver
*drv
= ((struct font
*) vector
)->driver
;
3100 /* The font driver might sometimes be NULL, e.g. if Emacs was
3101 interrupted before it had time to set it up. */
3104 /* Attempt to catch subtle bugs like Bug#16140. */
3105 eassert (valid_font_driver (drv
));
3106 drv
->close ((struct font
*) vector
);
3111 /* Reclaim space used by unmarked vectors. */
3113 NO_INLINE
/* For better stack traces */
3115 sweep_vectors (void)
3117 struct vector_block
*block
, **bprev
= &vector_blocks
;
3118 struct large_vector
*lv
, **lvprev
= &large_vectors
;
3119 struct Lisp_Vector
*vector
, *next
;
3121 total_vectors
= total_vector_slots
= total_free_vector_slots
= 0;
3122 memset (vector_free_lists
, 0, sizeof (vector_free_lists
));
3124 /* Looking through vector blocks. */
3126 for (block
= vector_blocks
; block
; block
= *bprev
)
3128 bool free_this_block
= 0;
3131 for (vector
= (struct Lisp_Vector
*) block
->data
;
3132 VECTOR_IN_BLOCK (vector
, block
); vector
= next
)
3134 if (VECTOR_MARKED_P (vector
))
3136 VECTOR_UNMARK (vector
);
3138 nbytes
= vector_nbytes (vector
);
3139 total_vector_slots
+= nbytes
/ word_size
;
3140 next
= ADVANCE (vector
, nbytes
);
3144 ptrdiff_t total_bytes
;
3146 cleanup_vector (vector
);
3147 nbytes
= vector_nbytes (vector
);
3148 total_bytes
= nbytes
;
3149 next
= ADVANCE (vector
, nbytes
);
3151 /* While NEXT is not marked, try to coalesce with VECTOR,
3152 thus making VECTOR of the largest possible size. */
3154 while (VECTOR_IN_BLOCK (next
, block
))
3156 if (VECTOR_MARKED_P (next
))
3158 cleanup_vector (next
);
3159 nbytes
= vector_nbytes (next
);
3160 total_bytes
+= nbytes
;
3161 next
= ADVANCE (next
, nbytes
);
3164 eassert (total_bytes
% roundup_size
== 0);
3166 if (vector
== (struct Lisp_Vector
*) block
->data
3167 && !VECTOR_IN_BLOCK (next
, block
))
3168 /* This block should be freed because all of its
3169 space was coalesced into the only free vector. */
3170 free_this_block
= 1;
3174 SETUP_ON_FREE_LIST (vector
, total_bytes
, tmp
);
3179 if (free_this_block
)
3181 *bprev
= block
->next
;
3182 #ifndef GC_MALLOC_CHECK
3183 mem_delete (mem_find (block
->data
));
3188 bprev
= &block
->next
;
3191 /* Sweep large vectors. */
3193 for (lv
= large_vectors
; lv
; lv
= *lvprev
)
3195 vector
= large_vector_vec (lv
);
3196 if (VECTOR_MARKED_P (vector
))
3198 VECTOR_UNMARK (vector
);
3200 if (vector
->header
.size
& PSEUDOVECTOR_FLAG
)
3202 /* All non-bool pseudovectors are small enough to be allocated
3203 from vector blocks. This code should be redesigned if some
3204 pseudovector type grows beyond VBLOCK_BYTES_MAX. */
3205 eassert (PSEUDOVECTOR_TYPEP (&vector
->header
, PVEC_BOOL_VECTOR
));
3206 total_vector_slots
+= vector_nbytes (vector
) / word_size
;
3210 += header_size
/ word_size
+ vector
->header
.size
;
3221 /* Value is a pointer to a newly allocated Lisp_Vector structure
3222 with room for LEN Lisp_Objects. */
3224 static struct Lisp_Vector
*
3225 allocate_vectorlike (ptrdiff_t len
)
3227 struct Lisp_Vector
*p
;
3232 p
= XVECTOR (zero_vector
);
3235 size_t nbytes
= header_size
+ len
* word_size
;
3237 #ifdef DOUG_LEA_MALLOC
3238 if (!mmap_lisp_allowed_p ())
3239 mallopt (M_MMAP_MAX
, 0);
3242 if (nbytes
<= VBLOCK_BYTES_MAX
)
3243 p
= allocate_vector_from_block (vroundup (nbytes
));
3246 struct large_vector
*lv
3247 = lisp_malloc ((large_vector_offset
+ header_size
3249 MEM_TYPE_VECTORLIKE
);
3250 lv
->next
= large_vectors
;
3252 p
= large_vector_vec (lv
);
3255 #ifdef DOUG_LEA_MALLOC
3256 if (!mmap_lisp_allowed_p ())
3257 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
);
3260 if (find_suspicious_object_in_range (p
, (char *) p
+ nbytes
))
3263 consing_since_gc
+= nbytes
;
3264 vector_cells_consed
+= len
;
3267 MALLOC_UNBLOCK_INPUT
;
3273 /* Allocate a vector with LEN slots. */
3275 struct Lisp_Vector
*
3276 allocate_vector (EMACS_INT len
)
3278 struct Lisp_Vector
*v
;
3279 ptrdiff_t nbytes_max
= min (PTRDIFF_MAX
, SIZE_MAX
);
3281 if (min ((nbytes_max
- header_size
) / word_size
, MOST_POSITIVE_FIXNUM
) < len
)
3282 memory_full (SIZE_MAX
);
3283 v
= allocate_vectorlike (len
);
3285 v
->header
.size
= len
;
3290 /* Allocate other vector-like structures. */
3292 struct Lisp_Vector
*
3293 allocate_pseudovector (int memlen
, int lisplen
,
3294 int zerolen
, enum pvec_type tag
)
3296 struct Lisp_Vector
*v
= allocate_vectorlike (memlen
);
3298 /* Catch bogus values. */
3299 eassert (0 <= tag
&& tag
<= PVEC_FONT
);
3300 eassert (0 <= lisplen
&& lisplen
<= zerolen
&& zerolen
<= memlen
);
3301 eassert (memlen
- lisplen
<= (1 << PSEUDOVECTOR_REST_BITS
) - 1);
3302 eassert (lisplen
<= (1 << PSEUDOVECTOR_SIZE_BITS
) - 1);
3304 /* Only the first LISPLEN slots will be traced normally by the GC. */
3305 memclear (v
->contents
, zerolen
* word_size
);
3306 XSETPVECTYPESIZE (v
, tag
, lisplen
, memlen
- lisplen
);
3311 allocate_buffer (void)
3313 struct buffer
*b
= lisp_malloc (sizeof *b
, MEM_TYPE_BUFFER
);
3315 BUFFER_PVEC_INIT (b
);
3316 /* Put B on the chain of all buffers including killed ones. */
3317 b
->next
= all_buffers
;
3319 /* Note that the rest fields of B are not initialized. */
3323 DEFUN ("make-vector", Fmake_vector
, Smake_vector
, 2, 2, 0,
3324 doc
: /* Return a newly created vector of length LENGTH, with each element being INIT.
3325 See also the function `vector'. */)
3326 (register Lisp_Object length
, Lisp_Object init
)
3329 register ptrdiff_t sizei
;
3330 register ptrdiff_t i
;
3331 register struct Lisp_Vector
*p
;
3333 CHECK_NATNUM (length
);
3335 p
= allocate_vector (XFASTINT (length
));
3336 sizei
= XFASTINT (length
);
3337 for (i
= 0; i
< sizei
; i
++)
3338 p
->contents
[i
] = init
;
3340 XSETVECTOR (vector
, p
);
3344 DEFUN ("vector", Fvector
, Svector
, 0, MANY
, 0,
3345 doc
: /* Return a newly created vector with specified arguments as elements.
3346 Any number of arguments, even zero arguments, are allowed.
3347 usage: (vector &rest OBJECTS) */)
3348 (ptrdiff_t nargs
, Lisp_Object
*args
)
3351 register Lisp_Object val
= make_uninit_vector (nargs
);
3352 register struct Lisp_Vector
*p
= XVECTOR (val
);
3354 for (i
= 0; i
< nargs
; i
++)
3355 p
->contents
[i
] = args
[i
];
3360 make_byte_code (struct Lisp_Vector
*v
)
3362 /* Don't allow the global zero_vector to become a byte code object. */
3363 eassert (0 < v
->header
.size
);
3365 if (v
->header
.size
> 1 && STRINGP (v
->contents
[1])
3366 && STRING_MULTIBYTE (v
->contents
[1]))
3367 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3368 earlier because they produced a raw 8-bit string for byte-code
3369 and now such a byte-code string is loaded as multibyte while
3370 raw 8-bit characters converted to multibyte form. Thus, now we
3371 must convert them back to the original unibyte form. */
3372 v
->contents
[1] = Fstring_as_unibyte (v
->contents
[1]);
3373 XSETPVECTYPE (v
, PVEC_COMPILED
);
3376 DEFUN ("make-byte-code", Fmake_byte_code
, Smake_byte_code
, 4, MANY
, 0,
3377 doc
: /* Create a byte-code object with specified arguments as elements.
3378 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3379 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3380 and (optional) INTERACTIVE-SPEC.
3381 The first four arguments are required; at most six have any
3383 The ARGLIST can be either like the one of `lambda', in which case the arguments
3384 will be dynamically bound before executing the byte code, or it can be an
3385 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3386 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3387 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3388 argument to catch the left-over arguments. If such an integer is used, the
3389 arguments will not be dynamically bound but will be instead pushed on the
3390 stack before executing the byte-code.
3391 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3392 (ptrdiff_t nargs
, Lisp_Object
*args
)
3395 register Lisp_Object val
= make_uninit_vector (nargs
);
3396 register struct Lisp_Vector
*p
= XVECTOR (val
);
3398 /* We used to purecopy everything here, if purify-flag was set. This worked
3399 OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
3400 dangerous, since make-byte-code is used during execution to build
3401 closures, so any closure built during the preload phase would end up
3402 copied into pure space, including its free variables, which is sometimes
3403 just wasteful and other times plainly wrong (e.g. those free vars may want
3406 for (i
= 0; i
< nargs
; i
++)
3407 p
->contents
[i
] = args
[i
];
3409 XSETCOMPILED (val
, p
);
3415 /***********************************************************************
3417 ***********************************************************************/
3419 /* Like struct Lisp_Symbol, but padded so that the size is a multiple
3420 of the required alignment. */
3422 union aligned_Lisp_Symbol
3424 struct Lisp_Symbol s
;
3425 unsigned char c
[(sizeof (struct Lisp_Symbol
) + GCALIGNMENT
- 1)
3429 /* Each symbol_block is just under 1020 bytes long, since malloc
3430 really allocates in units of powers of two and uses 4 bytes for its
3433 #define SYMBOL_BLOCK_SIZE \
3434 ((1020 - sizeof (struct symbol_block *)) / sizeof (union aligned_Lisp_Symbol))
3438 /* Place `symbols' first, to preserve alignment. */
3439 union aligned_Lisp_Symbol symbols
[SYMBOL_BLOCK_SIZE
];
3440 struct symbol_block
*next
;
3443 /* Current symbol block and index of first unused Lisp_Symbol
3446 static struct symbol_block
*symbol_block
;
3447 static int symbol_block_index
= SYMBOL_BLOCK_SIZE
;
3448 /* Pointer to the first symbol_block that contains pinned symbols.
3449 Tests for 24.4 showed that at dump-time, Emacs contains about 15K symbols,
3450 10K of which are pinned (and all but 250 of them are interned in obarray),
3451 whereas a "typical session" has in the order of 30K symbols.
3452 `symbol_block_pinned' lets mark_pinned_symbols scan only 15K symbols rather
3453 than 30K to find the 10K symbols we need to mark. */
3454 static struct symbol_block
*symbol_block_pinned
;
3456 /* List of free symbols. */
3458 static struct Lisp_Symbol
*symbol_free_list
;
3461 set_symbol_name (Lisp_Object sym
, Lisp_Object name
)
3463 XSYMBOL (sym
)->name
= name
;
3467 init_symbol (Lisp_Object val
, Lisp_Object name
)
3469 struct Lisp_Symbol
*p
= XSYMBOL (val
);
3470 set_symbol_name (val
, name
);
3471 set_symbol_plist (val
, Qnil
);
3472 p
->redirect
= SYMBOL_PLAINVAL
;
3473 SET_SYMBOL_VAL (p
, Qunbound
);
3474 set_symbol_function (val
, Qnil
);
3475 set_symbol_next (val
, NULL
);
3476 p
->gcmarkbit
= false;
3477 p
->interned
= SYMBOL_UNINTERNED
;
3479 p
->declared_special
= false;
3483 DEFUN ("make-symbol", Fmake_symbol
, Smake_symbol
, 1, 1, 0,
3484 doc
: /* Return a newly allocated uninterned symbol whose name is NAME.
3485 Its value is void, and its function definition and property list are nil. */)
3490 CHECK_STRING (name
);
3494 if (symbol_free_list
)
3496 XSETSYMBOL (val
, symbol_free_list
);
3497 symbol_free_list
= symbol_free_list
->next
;
3501 if (symbol_block_index
== SYMBOL_BLOCK_SIZE
)
3503 struct symbol_block
*new
3504 = lisp_malloc (sizeof *new, MEM_TYPE_SYMBOL
);
3505 new->next
= symbol_block
;
3507 symbol_block_index
= 0;
3508 total_free_symbols
+= SYMBOL_BLOCK_SIZE
;
3510 XSETSYMBOL (val
, &symbol_block
->symbols
[symbol_block_index
].s
);
3511 symbol_block_index
++;
3514 MALLOC_UNBLOCK_INPUT
;
3516 init_symbol (val
, name
);
3517 consing_since_gc
+= sizeof (struct Lisp_Symbol
);
3519 total_free_symbols
--;
3525 /***********************************************************************
3526 Marker (Misc) Allocation
3527 ***********************************************************************/
3529 /* Like union Lisp_Misc, but padded so that its size is a multiple of
3530 the required alignment. */
3532 union aligned_Lisp_Misc
3535 unsigned char c
[(sizeof (union Lisp_Misc
) + GCALIGNMENT
- 1)
3539 /* Allocation of markers and other objects that share that structure.
3540 Works like allocation of conses. */
3542 #define MARKER_BLOCK_SIZE \
3543 ((1020 - sizeof (struct marker_block *)) / sizeof (union aligned_Lisp_Misc))
3547 /* Place `markers' first, to preserve alignment. */
3548 union aligned_Lisp_Misc markers
[MARKER_BLOCK_SIZE
];
3549 struct marker_block
*next
;
3552 static struct marker_block
*marker_block
;
3553 static int marker_block_index
= MARKER_BLOCK_SIZE
;
3555 static union Lisp_Misc
*marker_free_list
;
3557 /* Return a newly allocated Lisp_Misc object of specified TYPE. */
3560 allocate_misc (enum Lisp_Misc_Type type
)
3566 if (marker_free_list
)
3568 XSETMISC (val
, marker_free_list
);
3569 marker_free_list
= marker_free_list
->u_free
.chain
;
3573 if (marker_block_index
== MARKER_BLOCK_SIZE
)
3575 struct marker_block
*new = lisp_malloc (sizeof *new, MEM_TYPE_MISC
);
3576 new->next
= marker_block
;
3578 marker_block_index
= 0;
3579 total_free_markers
+= MARKER_BLOCK_SIZE
;
3581 XSETMISC (val
, &marker_block
->markers
[marker_block_index
].m
);
3582 marker_block_index
++;
3585 MALLOC_UNBLOCK_INPUT
;
3587 --total_free_markers
;
3588 consing_since_gc
+= sizeof (union Lisp_Misc
);
3589 misc_objects_consed
++;
3590 XMISCANY (val
)->type
= type
;
3591 XMISCANY (val
)->gcmarkbit
= 0;
3595 /* Free a Lisp_Misc object. */
3598 free_misc (Lisp_Object misc
)
3600 XMISCANY (misc
)->type
= Lisp_Misc_Free
;
3601 XMISC (misc
)->u_free
.chain
= marker_free_list
;
3602 marker_free_list
= XMISC (misc
);
3603 consing_since_gc
-= sizeof (union Lisp_Misc
);
3604 total_free_markers
++;
3607 /* Verify properties of Lisp_Save_Value's representation
3608 that are assumed here and elsewhere. */
3610 verify (SAVE_UNUSED
== 0);
3611 verify (((SAVE_INTEGER
| SAVE_POINTER
| SAVE_FUNCPOINTER
| SAVE_OBJECT
)
3615 /* Return Lisp_Save_Value objects for the various combinations
3616 that callers need. */
3619 make_save_int_int_int (ptrdiff_t a
, ptrdiff_t b
, ptrdiff_t c
)
3621 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3622 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3623 p
->save_type
= SAVE_TYPE_INT_INT_INT
;
3624 p
->data
[0].integer
= a
;
3625 p
->data
[1].integer
= b
;
3626 p
->data
[2].integer
= c
;
3631 make_save_obj_obj_obj_obj (Lisp_Object a
, Lisp_Object b
, Lisp_Object c
,
3634 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3635 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3636 p
->save_type
= SAVE_TYPE_OBJ_OBJ_OBJ_OBJ
;
3637 p
->data
[0].object
= a
;
3638 p
->data
[1].object
= b
;
3639 p
->data
[2].object
= c
;
3640 p
->data
[3].object
= d
;
3645 make_save_ptr (void *a
)
3647 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3648 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3649 p
->save_type
= SAVE_POINTER
;
3650 p
->data
[0].pointer
= a
;
3655 make_save_ptr_int (void *a
, ptrdiff_t b
)
3657 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3658 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3659 p
->save_type
= SAVE_TYPE_PTR_INT
;
3660 p
->data
[0].pointer
= a
;
3661 p
->data
[1].integer
= b
;
3665 #if ! (defined USE_X_TOOLKIT || defined USE_GTK)
3667 make_save_ptr_ptr (void *a
, void *b
)
3669 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3670 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3671 p
->save_type
= SAVE_TYPE_PTR_PTR
;
3672 p
->data
[0].pointer
= a
;
3673 p
->data
[1].pointer
= b
;
3679 make_save_funcptr_ptr_obj (void (*a
) (void), void *b
, Lisp_Object c
)
3681 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3682 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3683 p
->save_type
= SAVE_TYPE_FUNCPTR_PTR_OBJ
;
3684 p
->data
[0].funcpointer
= a
;
3685 p
->data
[1].pointer
= b
;
3686 p
->data
[2].object
= c
;
3690 /* Return a Lisp_Save_Value object that represents an array A
3691 of N Lisp objects. */
3694 make_save_memory (Lisp_Object
*a
, ptrdiff_t n
)
3696 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3697 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3698 p
->save_type
= SAVE_TYPE_MEMORY
;
3699 p
->data
[0].pointer
= a
;
3700 p
->data
[1].integer
= n
;
3704 /* Free a Lisp_Save_Value object. Do not use this function
3705 if SAVE contains pointer other than returned by xmalloc. */
3708 free_save_value (Lisp_Object save
)
3710 xfree (XSAVE_POINTER (save
, 0));
3714 /* Return a Lisp_Misc_Overlay object with specified START, END and PLIST. */
3717 build_overlay (Lisp_Object start
, Lisp_Object end
, Lisp_Object plist
)
3719 register Lisp_Object overlay
;
3721 overlay
= allocate_misc (Lisp_Misc_Overlay
);
3722 OVERLAY_START (overlay
) = start
;
3723 OVERLAY_END (overlay
) = end
;
3724 set_overlay_plist (overlay
, plist
);
3725 XOVERLAY (overlay
)->next
= NULL
;
3729 DEFUN ("make-marker", Fmake_marker
, Smake_marker
, 0, 0, 0,
3730 doc
: /* Return a newly allocated marker which does not point at any place. */)
3733 register Lisp_Object val
;
3734 register struct Lisp_Marker
*p
;
3736 val
= allocate_misc (Lisp_Misc_Marker
);
3742 p
->insertion_type
= 0;
3743 p
->need_adjustment
= 0;
3747 /* Return a newly allocated marker which points into BUF
3748 at character position CHARPOS and byte position BYTEPOS. */
3751 build_marker (struct buffer
*buf
, ptrdiff_t charpos
, ptrdiff_t bytepos
)
3754 struct Lisp_Marker
*m
;
3756 /* No dead buffers here. */
3757 eassert (BUFFER_LIVE_P (buf
));
3759 /* Every character is at least one byte. */
3760 eassert (charpos
<= bytepos
);
3762 obj
= allocate_misc (Lisp_Misc_Marker
);
3765 m
->charpos
= charpos
;
3766 m
->bytepos
= bytepos
;
3767 m
->insertion_type
= 0;
3768 m
->need_adjustment
= 0;
3769 m
->next
= BUF_MARKERS (buf
);
3770 BUF_MARKERS (buf
) = m
;
3774 /* Put MARKER back on the free list after using it temporarily. */
3777 free_marker (Lisp_Object marker
)
3779 unchain_marker (XMARKER (marker
));
3784 /* Return a newly created vector or string with specified arguments as
3785 elements. If all the arguments are characters that can fit
3786 in a string of events, make a string; otherwise, make a vector.
3788 Any number of arguments, even zero arguments, are allowed. */
3791 make_event_array (ptrdiff_t nargs
, Lisp_Object
*args
)
3795 for (i
= 0; i
< nargs
; i
++)
3796 /* The things that fit in a string
3797 are characters that are in 0...127,
3798 after discarding the meta bit and all the bits above it. */
3799 if (!INTEGERP (args
[i
])
3800 || (XINT (args
[i
]) & ~(-CHAR_META
)) >= 0200)
3801 return Fvector (nargs
, args
);
3803 /* Since the loop exited, we know that all the things in it are
3804 characters, so we can make a string. */
3808 result
= Fmake_string (make_number (nargs
), make_number (0));
3809 for (i
= 0; i
< nargs
; i
++)
3811 SSET (result
, i
, XINT (args
[i
]));
3812 /* Move the meta bit to the right place for a string char. */
3813 if (XINT (args
[i
]) & CHAR_META
)
3814 SSET (result
, i
, SREF (result
, i
) | 0x80);
3822 /* Create a new module user ptr object. */
3824 make_user_ptr (void (*finalizer
) (void *), void *p
)
3827 struct Lisp_User_Ptr
*uptr
;
3829 obj
= allocate_misc (Lisp_Misc_User_Ptr
);
3830 uptr
= XUSER_PTR (obj
);
3831 uptr
->finalizer
= finalizer
;
3839 init_finalizer_list (struct Lisp_Finalizer
*head
)
3841 head
->prev
= head
->next
= head
;
3844 /* Insert FINALIZER before ELEMENT. */
3847 finalizer_insert (struct Lisp_Finalizer
*element
,
3848 struct Lisp_Finalizer
*finalizer
)
3850 eassert (finalizer
->prev
== NULL
);
3851 eassert (finalizer
->next
== NULL
);
3852 finalizer
->next
= element
;
3853 finalizer
->prev
= element
->prev
;
3854 finalizer
->prev
->next
= finalizer
;
3855 element
->prev
= finalizer
;
3859 unchain_finalizer (struct Lisp_Finalizer
*finalizer
)
3861 if (finalizer
->prev
!= NULL
)
3863 eassert (finalizer
->next
!= NULL
);
3864 finalizer
->prev
->next
= finalizer
->next
;
3865 finalizer
->next
->prev
= finalizer
->prev
;
3866 finalizer
->prev
= finalizer
->next
= NULL
;
3871 mark_finalizer_list (struct Lisp_Finalizer
*head
)
3873 for (struct Lisp_Finalizer
*finalizer
= head
->next
;
3875 finalizer
= finalizer
->next
)
3877 finalizer
->base
.gcmarkbit
= true;
3878 mark_object (finalizer
->function
);
3882 /* Move doomed finalizers to list DEST from list SRC. A doomed
3883 finalizer is one that is not GC-reachable and whose
3884 finalizer->function is non-nil. */
3887 queue_doomed_finalizers (struct Lisp_Finalizer
*dest
,
3888 struct Lisp_Finalizer
*src
)
3890 struct Lisp_Finalizer
*finalizer
= src
->next
;
3891 while (finalizer
!= src
)
3893 struct Lisp_Finalizer
*next
= finalizer
->next
;
3894 if (!finalizer
->base
.gcmarkbit
&& !NILP (finalizer
->function
))
3896 unchain_finalizer (finalizer
);
3897 finalizer_insert (dest
, finalizer
);
3905 run_finalizer_handler (Lisp_Object args
)
3907 add_to_log ("finalizer failed: %S", args
);
3912 run_finalizer_function (Lisp_Object function
)
3914 ptrdiff_t count
= SPECPDL_INDEX ();
3916 specbind (Qinhibit_quit
, Qt
);
3917 internal_condition_case_1 (call0
, function
, Qt
, run_finalizer_handler
);
3918 unbind_to (count
, Qnil
);
3922 run_finalizers (struct Lisp_Finalizer
*finalizers
)
3924 struct Lisp_Finalizer
*finalizer
;
3925 Lisp_Object function
;
3927 while (finalizers
->next
!= finalizers
)
3929 finalizer
= finalizers
->next
;
3930 eassert (finalizer
->base
.type
== Lisp_Misc_Finalizer
);
3931 unchain_finalizer (finalizer
);
3932 function
= finalizer
->function
;
3933 if (!NILP (function
))
3935 finalizer
->function
= Qnil
;
3936 run_finalizer_function (function
);
3941 DEFUN ("make-finalizer", Fmake_finalizer
, Smake_finalizer
, 1, 1, 0,
3942 doc
: /* Make a finalizer that will run FUNCTION.
3943 FUNCTION will be called after garbage collection when the returned
3944 finalizer object becomes unreachable. If the finalizer object is
3945 reachable only through references from finalizer objects, it does not
3946 count as reachable for the purpose of deciding whether to run
3947 FUNCTION. FUNCTION will be run once per finalizer object. */)
3948 (Lisp_Object function
)
3950 Lisp_Object val
= allocate_misc (Lisp_Misc_Finalizer
);
3951 struct Lisp_Finalizer
*finalizer
= XFINALIZER (val
);
3952 finalizer
->function
= function
;
3953 finalizer
->prev
= finalizer
->next
= NULL
;
3954 finalizer_insert (&finalizers
, finalizer
);
3959 /************************************************************************
3960 Memory Full Handling
3961 ************************************************************************/
3964 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
3965 there may have been size_t overflow so that malloc was never
3966 called, or perhaps malloc was invoked successfully but the
3967 resulting pointer had problems fitting into a tagged EMACS_INT. In
3968 either case this counts as memory being full even though malloc did
3972 memory_full (size_t nbytes
)
3974 /* Do not go into hysterics merely because a large request failed. */
3975 bool enough_free_memory
= 0;
3976 if (SPARE_MEMORY
< nbytes
)
3981 p
= malloc (SPARE_MEMORY
);
3985 enough_free_memory
= 1;
3987 MALLOC_UNBLOCK_INPUT
;
3990 if (! enough_free_memory
)
3996 memory_full_cons_threshold
= sizeof (struct cons_block
);
3998 /* The first time we get here, free the spare memory. */
3999 for (i
= 0; i
< ARRAYELTS (spare_memory
); i
++)
4000 if (spare_memory
[i
])
4003 free (spare_memory
[i
]);
4004 else if (i
>= 1 && i
<= 4)
4005 lisp_align_free (spare_memory
[i
]);
4007 lisp_free (spare_memory
[i
]);
4008 spare_memory
[i
] = 0;
4012 /* This used to call error, but if we've run out of memory, we could
4013 get infinite recursion trying to build the string. */
4014 xsignal (Qnil
, Vmemory_signal_data
);
4017 /* If we released our reserve (due to running out of memory),
4018 and we have a fair amount free once again,
4019 try to set aside another reserve in case we run out once more.
4021 This is called when a relocatable block is freed in ralloc.c,
4022 and also directly from this file, in case we're not using ralloc.c. */
4025 refill_memory_reserve (void)
4027 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
4028 if (spare_memory
[0] == 0)
4029 spare_memory
[0] = malloc (SPARE_MEMORY
);
4030 if (spare_memory
[1] == 0)
4031 spare_memory
[1] = lisp_align_malloc (sizeof (struct cons_block
),
4033 if (spare_memory
[2] == 0)
4034 spare_memory
[2] = lisp_align_malloc (sizeof (struct cons_block
),
4036 if (spare_memory
[3] == 0)
4037 spare_memory
[3] = lisp_align_malloc (sizeof (struct cons_block
),
4039 if (spare_memory
[4] == 0)
4040 spare_memory
[4] = lisp_align_malloc (sizeof (struct cons_block
),
4042 if (spare_memory
[5] == 0)
4043 spare_memory
[5] = lisp_malloc (sizeof (struct string_block
),
4045 if (spare_memory
[6] == 0)
4046 spare_memory
[6] = lisp_malloc (sizeof (struct string_block
),
4048 if (spare_memory
[0] && spare_memory
[1] && spare_memory
[5])
4049 Vmemory_full
= Qnil
;
4053 /************************************************************************
4055 ************************************************************************/
4057 /* Conservative C stack marking requires a method to identify possibly
4058 live Lisp objects given a pointer value. We do this by keeping
4059 track of blocks of Lisp data that are allocated in a red-black tree
4060 (see also the comment of mem_node which is the type of nodes in
4061 that tree). Function lisp_malloc adds information for an allocated
4062 block to the red-black tree with calls to mem_insert, and function
4063 lisp_free removes it with mem_delete. Functions live_string_p etc
4064 call mem_find to lookup information about a given pointer in the
4065 tree, and use that to determine if the pointer points to a Lisp
4068 /* Initialize this part of alloc.c. */
4073 mem_z
.left
= mem_z
.right
= MEM_NIL
;
4074 mem_z
.parent
= NULL
;
4075 mem_z
.color
= MEM_BLACK
;
4076 mem_z
.start
= mem_z
.end
= NULL
;
4081 /* Value is a pointer to the mem_node containing START. Value is
4082 MEM_NIL if there is no node in the tree containing START. */
4084 static struct mem_node
*
4085 mem_find (void *start
)
4089 if (start
< min_heap_address
|| start
> max_heap_address
)
4092 /* Make the search always successful to speed up the loop below. */
4093 mem_z
.start
= start
;
4094 mem_z
.end
= (char *) start
+ 1;
4097 while (start
< p
->start
|| start
>= p
->end
)
4098 p
= start
< p
->start
? p
->left
: p
->right
;
4103 /* Insert a new node into the tree for a block of memory with start
4104 address START, end address END, and type TYPE. Value is a
4105 pointer to the node that was inserted. */
4107 static struct mem_node
*
4108 mem_insert (void *start
, void *end
, enum mem_type type
)
4110 struct mem_node
*c
, *parent
, *x
;
4112 if (min_heap_address
== NULL
|| start
< min_heap_address
)
4113 min_heap_address
= start
;
4114 if (max_heap_address
== NULL
|| end
> max_heap_address
)
4115 max_heap_address
= end
;
4117 /* See where in the tree a node for START belongs. In this
4118 particular application, it shouldn't happen that a node is already
4119 present. For debugging purposes, let's check that. */
4123 while (c
!= MEM_NIL
)
4126 c
= start
< c
->start
? c
->left
: c
->right
;
4129 /* Create a new node. */
4130 #ifdef GC_MALLOC_CHECK
4131 x
= malloc (sizeof *x
);
4135 x
= xmalloc (sizeof *x
);
4141 x
->left
= x
->right
= MEM_NIL
;
4144 /* Insert it as child of PARENT or install it as root. */
4147 if (start
< parent
->start
)
4155 /* Re-establish red-black tree properties. */
4156 mem_insert_fixup (x
);
4162 /* Re-establish the red-black properties of the tree, and thereby
4163 balance the tree, after node X has been inserted; X is always red. */
4166 mem_insert_fixup (struct mem_node
*x
)
4168 while (x
!= mem_root
&& x
->parent
->color
== MEM_RED
)
4170 /* X is red and its parent is red. This is a violation of
4171 red-black tree property #3. */
4173 if (x
->parent
== x
->parent
->parent
->left
)
4175 /* We're on the left side of our grandparent, and Y is our
4177 struct mem_node
*y
= x
->parent
->parent
->right
;
4179 if (y
->color
== MEM_RED
)
4181 /* Uncle and parent are red but should be black because
4182 X is red. Change the colors accordingly and proceed
4183 with the grandparent. */
4184 x
->parent
->color
= MEM_BLACK
;
4185 y
->color
= MEM_BLACK
;
4186 x
->parent
->parent
->color
= MEM_RED
;
4187 x
= x
->parent
->parent
;
4191 /* Parent and uncle have different colors; parent is
4192 red, uncle is black. */
4193 if (x
== x
->parent
->right
)
4196 mem_rotate_left (x
);
4199 x
->parent
->color
= MEM_BLACK
;
4200 x
->parent
->parent
->color
= MEM_RED
;
4201 mem_rotate_right (x
->parent
->parent
);
4206 /* This is the symmetrical case of above. */
4207 struct mem_node
*y
= x
->parent
->parent
->left
;
4209 if (y
->color
== MEM_RED
)
4211 x
->parent
->color
= MEM_BLACK
;
4212 y
->color
= MEM_BLACK
;
4213 x
->parent
->parent
->color
= MEM_RED
;
4214 x
= x
->parent
->parent
;
4218 if (x
== x
->parent
->left
)
4221 mem_rotate_right (x
);
4224 x
->parent
->color
= MEM_BLACK
;
4225 x
->parent
->parent
->color
= MEM_RED
;
4226 mem_rotate_left (x
->parent
->parent
);
4231 /* The root may have been changed to red due to the algorithm. Set
4232 it to black so that property #5 is satisfied. */
4233 mem_root
->color
= MEM_BLACK
;
4244 mem_rotate_left (struct mem_node
*x
)
4248 /* Turn y's left sub-tree into x's right sub-tree. */
4251 if (y
->left
!= MEM_NIL
)
4252 y
->left
->parent
= x
;
4254 /* Y's parent was x's parent. */
4256 y
->parent
= x
->parent
;
4258 /* Get the parent to point to y instead of x. */
4261 if (x
== x
->parent
->left
)
4262 x
->parent
->left
= y
;
4264 x
->parent
->right
= y
;
4269 /* Put x on y's left. */
4283 mem_rotate_right (struct mem_node
*x
)
4285 struct mem_node
*y
= x
->left
;
4288 if (y
->right
!= MEM_NIL
)
4289 y
->right
->parent
= x
;
4292 y
->parent
= x
->parent
;
4295 if (x
== x
->parent
->right
)
4296 x
->parent
->right
= y
;
4298 x
->parent
->left
= y
;
4309 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
4312 mem_delete (struct mem_node
*z
)
4314 struct mem_node
*x
, *y
;
4316 if (!z
|| z
== MEM_NIL
)
4319 if (z
->left
== MEM_NIL
|| z
->right
== MEM_NIL
)
4324 while (y
->left
!= MEM_NIL
)
4328 if (y
->left
!= MEM_NIL
)
4333 x
->parent
= y
->parent
;
4336 if (y
== y
->parent
->left
)
4337 y
->parent
->left
= x
;
4339 y
->parent
->right
= x
;
4346 z
->start
= y
->start
;
4351 if (y
->color
== MEM_BLACK
)
4352 mem_delete_fixup (x
);
4354 #ifdef GC_MALLOC_CHECK
4362 /* Re-establish the red-black properties of the tree, after a
4366 mem_delete_fixup (struct mem_node
*x
)
4368 while (x
!= mem_root
&& x
->color
== MEM_BLACK
)
4370 if (x
== x
->parent
->left
)
4372 struct mem_node
*w
= x
->parent
->right
;
4374 if (w
->color
== MEM_RED
)
4376 w
->color
= MEM_BLACK
;
4377 x
->parent
->color
= MEM_RED
;
4378 mem_rotate_left (x
->parent
);
4379 w
= x
->parent
->right
;
4382 if (w
->left
->color
== MEM_BLACK
&& w
->right
->color
== MEM_BLACK
)
4389 if (w
->right
->color
== MEM_BLACK
)
4391 w
->left
->color
= MEM_BLACK
;
4393 mem_rotate_right (w
);
4394 w
= x
->parent
->right
;
4396 w
->color
= x
->parent
->color
;
4397 x
->parent
->color
= MEM_BLACK
;
4398 w
->right
->color
= MEM_BLACK
;
4399 mem_rotate_left (x
->parent
);
4405 struct mem_node
*w
= x
->parent
->left
;
4407 if (w
->color
== MEM_RED
)
4409 w
->color
= MEM_BLACK
;
4410 x
->parent
->color
= MEM_RED
;
4411 mem_rotate_right (x
->parent
);
4412 w
= x
->parent
->left
;
4415 if (w
->right
->color
== MEM_BLACK
&& w
->left
->color
== MEM_BLACK
)
4422 if (w
->left
->color
== MEM_BLACK
)
4424 w
->right
->color
= MEM_BLACK
;
4426 mem_rotate_left (w
);
4427 w
= x
->parent
->left
;
4430 w
->color
= x
->parent
->color
;
4431 x
->parent
->color
= MEM_BLACK
;
4432 w
->left
->color
= MEM_BLACK
;
4433 mem_rotate_right (x
->parent
);
4439 x
->color
= MEM_BLACK
;
4443 /* Value is non-zero if P is a pointer to a live Lisp string on
4444 the heap. M is a pointer to the mem_block for P. */
4447 live_string_p (struct mem_node
*m
, void *p
)
4449 if (m
->type
== MEM_TYPE_STRING
)
4451 struct string_block
*b
= m
->start
;
4452 ptrdiff_t offset
= (char *) p
- (char *) &b
->strings
[0];
4454 /* P must point to the start of a Lisp_String structure, and it
4455 must not be on the free-list. */
4457 && offset
% sizeof b
->strings
[0] == 0
4458 && offset
< (STRING_BLOCK_SIZE
* sizeof b
->strings
[0])
4459 && ((struct Lisp_String
*) p
)->data
!= NULL
);
4466 /* Value is non-zero if P is a pointer to a live Lisp cons on
4467 the heap. M is a pointer to the mem_block for P. */
4470 live_cons_p (struct mem_node
*m
, void *p
)
4472 if (m
->type
== MEM_TYPE_CONS
)
4474 struct cons_block
*b
= m
->start
;
4475 ptrdiff_t offset
= (char *) p
- (char *) &b
->conses
[0];
4477 /* P must point to the start of a Lisp_Cons, not be
4478 one of the unused cells in the current cons block,
4479 and not be on the free-list. */
4481 && offset
% sizeof b
->conses
[0] == 0
4482 && offset
< (CONS_BLOCK_SIZE
* sizeof b
->conses
[0])
4484 || offset
/ sizeof b
->conses
[0] < cons_block_index
)
4485 && !EQ (((struct Lisp_Cons
*) p
)->car
, Vdead
));
4492 /* Value is non-zero if P is a pointer to a live Lisp symbol on
4493 the heap. M is a pointer to the mem_block for P. */
4496 live_symbol_p (struct mem_node
*m
, void *p
)
4498 if (m
->type
== MEM_TYPE_SYMBOL
)
4500 struct symbol_block
*b
= m
->start
;
4501 ptrdiff_t offset
= (char *) p
- (char *) &b
->symbols
[0];
4503 /* P must point to the start of a Lisp_Symbol, not be
4504 one of the unused cells in the current symbol block,
4505 and not be on the free-list. */
4507 && offset
% sizeof b
->symbols
[0] == 0
4508 && offset
< (SYMBOL_BLOCK_SIZE
* sizeof b
->symbols
[0])
4509 && (b
!= symbol_block
4510 || offset
/ sizeof b
->symbols
[0] < symbol_block_index
)
4511 && !EQ (((struct Lisp_Symbol
*)p
)->function
, Vdead
));
4518 /* Value is non-zero if P is a pointer to a live Lisp float on
4519 the heap. M is a pointer to the mem_block for P. */
4522 live_float_p (struct mem_node
*m
, void *p
)
4524 if (m
->type
== MEM_TYPE_FLOAT
)
4526 struct float_block
*b
= m
->start
;
4527 ptrdiff_t offset
= (char *) p
- (char *) &b
->floats
[0];
4529 /* P must point to the start of a Lisp_Float and not be
4530 one of the unused cells in the current float block. */
4532 && offset
% sizeof b
->floats
[0] == 0
4533 && offset
< (FLOAT_BLOCK_SIZE
* sizeof b
->floats
[0])
4534 && (b
!= float_block
4535 || offset
/ sizeof b
->floats
[0] < float_block_index
));
4542 /* Value is non-zero if P is a pointer to a live Lisp Misc on
4543 the heap. M is a pointer to the mem_block for P. */
4546 live_misc_p (struct mem_node
*m
, void *p
)
4548 if (m
->type
== MEM_TYPE_MISC
)
4550 struct marker_block
*b
= m
->start
;
4551 ptrdiff_t offset
= (char *) p
- (char *) &b
->markers
[0];
4553 /* P must point to the start of a Lisp_Misc, not be
4554 one of the unused cells in the current misc block,
4555 and not be on the free-list. */
4557 && offset
% sizeof b
->markers
[0] == 0
4558 && offset
< (MARKER_BLOCK_SIZE
* sizeof b
->markers
[0])
4559 && (b
!= marker_block
4560 || offset
/ sizeof b
->markers
[0] < marker_block_index
)
4561 && ((union Lisp_Misc
*) p
)->u_any
.type
!= Lisp_Misc_Free
);
4568 /* Value is non-zero if P is a pointer to a live vector-like object.
4569 M is a pointer to the mem_block for P. */
4572 live_vector_p (struct mem_node
*m
, void *p
)
4574 if (m
->type
== MEM_TYPE_VECTOR_BLOCK
)
4576 /* This memory node corresponds to a vector block. */
4577 struct vector_block
*block
= m
->start
;
4578 struct Lisp_Vector
*vector
= (struct Lisp_Vector
*) block
->data
;
4580 /* P is in the block's allocation range. Scan the block
4581 up to P and see whether P points to the start of some
4582 vector which is not on a free list. FIXME: check whether
4583 some allocation patterns (probably a lot of short vectors)
4584 may cause a substantial overhead of this loop. */
4585 while (VECTOR_IN_BLOCK (vector
, block
)
4586 && vector
<= (struct Lisp_Vector
*) p
)
4588 if (!PSEUDOVECTOR_TYPEP (&vector
->header
, PVEC_FREE
) && vector
== p
)
4591 vector
= ADVANCE (vector
, vector_nbytes (vector
));
4594 else if (m
->type
== MEM_TYPE_VECTORLIKE
&& p
== large_vector_vec (m
->start
))
4595 /* This memory node corresponds to a large vector. */
4601 /* Value is non-zero if P is a pointer to a live buffer. M is a
4602 pointer to the mem_block for P. */
4605 live_buffer_p (struct mem_node
*m
, void *p
)
4607 /* P must point to the start of the block, and the buffer
4608 must not have been killed. */
4609 return (m
->type
== MEM_TYPE_BUFFER
4611 && !NILP (((struct buffer
*) p
)->name_
));
4614 /* Mark OBJ if we can prove it's a Lisp_Object. */
4617 mark_maybe_object (Lisp_Object obj
)
4621 VALGRIND_MAKE_MEM_DEFINED (&obj
, sizeof (obj
));
4627 void *po
= XPNTR (obj
);
4628 struct mem_node
*m
= mem_find (po
);
4632 bool mark_p
= false;
4634 switch (XTYPE (obj
))
4637 mark_p
= (live_string_p (m
, po
)
4638 && !STRING_MARKED_P ((struct Lisp_String
*) po
));
4642 mark_p
= (live_cons_p (m
, po
) && !CONS_MARKED_P (XCONS (obj
)));
4646 mark_p
= (live_symbol_p (m
, po
) && !XSYMBOL (obj
)->gcmarkbit
);
4650 mark_p
= (live_float_p (m
, po
) && !FLOAT_MARKED_P (XFLOAT (obj
)));
4653 case Lisp_Vectorlike
:
4654 /* Note: can't check BUFFERP before we know it's a
4655 buffer because checking that dereferences the pointer
4656 PO which might point anywhere. */
4657 if (live_vector_p (m
, po
))
4658 mark_p
= !SUBRP (obj
) && !VECTOR_MARKED_P (XVECTOR (obj
));
4659 else if (live_buffer_p (m
, po
))
4660 mark_p
= BUFFERP (obj
) && !VECTOR_MARKED_P (XBUFFER (obj
));
4664 mark_p
= (live_misc_p (m
, po
) && !XMISCANY (obj
)->gcmarkbit
);
4676 /* Return true if P can point to Lisp data, and false otherwise.
4677 Symbols are implemented via offsets not pointers, but the offsets
4678 are also multiples of GCALIGNMENT. */
4681 maybe_lisp_pointer (void *p
)
4683 return (uintptr_t) p
% GCALIGNMENT
== 0;
4686 #ifndef HAVE_MODULES
4687 enum { HAVE_MODULES
= false };
4690 /* If P points to Lisp data, mark that as live if it isn't already
4694 mark_maybe_pointer (void *p
)
4700 VALGRIND_MAKE_MEM_DEFINED (&p
, sizeof (p
));
4703 if (sizeof (Lisp_Object
) == sizeof (void *) || !HAVE_MODULES
)
4705 if (!maybe_lisp_pointer (p
))
4710 /* For the wide-int case, also mark emacs_value tagged pointers,
4711 which can be generated by emacs-module.c's value_to_lisp. */
4712 p
= (void *) ((uintptr_t) p
& ~(GCALIGNMENT
- 1));
4718 Lisp_Object obj
= Qnil
;
4722 case MEM_TYPE_NON_LISP
:
4723 case MEM_TYPE_SPARE
:
4724 /* Nothing to do; not a pointer to Lisp memory. */
4727 case MEM_TYPE_BUFFER
:
4728 if (live_buffer_p (m
, p
) && !VECTOR_MARKED_P ((struct buffer
*)p
))
4729 XSETVECTOR (obj
, p
);
4733 if (live_cons_p (m
, p
) && !CONS_MARKED_P ((struct Lisp_Cons
*) p
))
4737 case MEM_TYPE_STRING
:
4738 if (live_string_p (m
, p
)
4739 && !STRING_MARKED_P ((struct Lisp_String
*) p
))
4740 XSETSTRING (obj
, p
);
4744 if (live_misc_p (m
, p
) && !((struct Lisp_Free
*) p
)->gcmarkbit
)
4748 case MEM_TYPE_SYMBOL
:
4749 if (live_symbol_p (m
, p
) && !((struct Lisp_Symbol
*) p
)->gcmarkbit
)
4750 XSETSYMBOL (obj
, p
);
4753 case MEM_TYPE_FLOAT
:
4754 if (live_float_p (m
, p
) && !FLOAT_MARKED_P (p
))
4758 case MEM_TYPE_VECTORLIKE
:
4759 case MEM_TYPE_VECTOR_BLOCK
:
4760 if (live_vector_p (m
, p
))
4763 XSETVECTOR (tem
, p
);
4764 if (!SUBRP (tem
) && !VECTOR_MARKED_P (XVECTOR (tem
)))
4779 /* Alignment of pointer values. Use alignof, as it sometimes returns
4780 a smaller alignment than GCC's __alignof__ and mark_memory might
4781 miss objects if __alignof__ were used. */
4782 #define GC_POINTER_ALIGNMENT alignof (void *)
4784 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4785 or END+OFFSET..START. */
4787 static void ATTRIBUTE_NO_SANITIZE_ADDRESS
4788 mark_memory (void *start
, void *end
)
4792 /* Make START the pointer to the start of the memory region,
4793 if it isn't already. */
4801 eassert (((uintptr_t) start
) % GC_POINTER_ALIGNMENT
== 0);
4803 /* Mark Lisp data pointed to. This is necessary because, in some
4804 situations, the C compiler optimizes Lisp objects away, so that
4805 only a pointer to them remains. Example:
4807 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4810 Lisp_Object obj = build_string ("test");
4811 struct Lisp_String *s = XSTRING (obj);
4812 Fgarbage_collect ();
4813 fprintf (stderr, "test '%s'\n", s->data);
4817 Here, `obj' isn't really used, and the compiler optimizes it
4818 away. The only reference to the life string is through the
4821 for (pp
= start
; (void *) pp
< end
; pp
+= GC_POINTER_ALIGNMENT
)
4823 mark_maybe_pointer (*(void **) pp
);
4824 mark_maybe_object (*(Lisp_Object
*) pp
);
4828 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4830 static bool setjmp_tested_p
;
4831 static int longjmps_done
;
4833 #define SETJMP_WILL_LIKELY_WORK "\
4835 Emacs garbage collector has been changed to use conservative stack\n\
4836 marking. Emacs has determined that the method it uses to do the\n\
4837 marking will likely work on your system, but this isn't sure.\n\
4839 If you are a system-programmer, or can get the help of a local wizard\n\
4840 who is, please take a look at the function mark_stack in alloc.c, and\n\
4841 verify that the methods used are appropriate for your system.\n\
4843 Please mail the result to <emacs-devel@gnu.org>.\n\
4846 #define SETJMP_WILL_NOT_WORK "\
4848 Emacs garbage collector has been changed to use conservative stack\n\
4849 marking. Emacs has determined that the default method it uses to do the\n\
4850 marking will not work on your system. We will need a system-dependent\n\
4851 solution for your system.\n\
4853 Please take a look at the function mark_stack in alloc.c, and\n\
4854 try to find a way to make it work on your system.\n\
4856 Note that you may get false negatives, depending on the compiler.\n\
4857 In particular, you need to use -O with GCC for this test.\n\
4859 Please mail the result to <emacs-devel@gnu.org>.\n\
4863 /* Perform a quick check if it looks like setjmp saves registers in a
4864 jmp_buf. Print a message to stderr saying so. When this test
4865 succeeds, this is _not_ a proof that setjmp is sufficient for
4866 conservative stack marking. Only the sources or a disassembly
4876 /* Arrange for X to be put in a register. */
4882 if (longjmps_done
== 1)
4884 /* Came here after the longjmp at the end of the function.
4886 If x == 1, the longjmp has restored the register to its
4887 value before the setjmp, and we can hope that setjmp
4888 saves all such registers in the jmp_buf, although that
4891 For other values of X, either something really strange is
4892 taking place, or the setjmp just didn't save the register. */
4895 fprintf (stderr
, SETJMP_WILL_LIKELY_WORK
);
4898 fprintf (stderr
, SETJMP_WILL_NOT_WORK
);
4905 if (longjmps_done
== 1)
4906 sys_longjmp (jbuf
, 1);
4909 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4912 /* Mark live Lisp objects on the C stack.
4914 There are several system-dependent problems to consider when
4915 porting this to new architectures:
4919 We have to mark Lisp objects in CPU registers that can hold local
4920 variables or are used to pass parameters.
4922 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4923 something that either saves relevant registers on the stack, or
4924 calls mark_maybe_object passing it each register's contents.
4926 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4927 implementation assumes that calling setjmp saves registers we need
4928 to see in a jmp_buf which itself lies on the stack. This doesn't
4929 have to be true! It must be verified for each system, possibly
4930 by taking a look at the source code of setjmp.
4932 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4933 can use it as a machine independent method to store all registers
4934 to the stack. In this case the macros described in the previous
4935 two paragraphs are not used.
4939 Architectures differ in the way their processor stack is organized.
4940 For example, the stack might look like this
4943 | Lisp_Object | size = 4
4945 | something else | size = 2
4947 | Lisp_Object | size = 4
4951 In such a case, not every Lisp_Object will be aligned equally. To
4952 find all Lisp_Object on the stack it won't be sufficient to walk
4953 the stack in steps of 4 bytes. Instead, two passes will be
4954 necessary, one starting at the start of the stack, and a second
4955 pass starting at the start of the stack + 2. Likewise, if the
4956 minimal alignment of Lisp_Objects on the stack is 1, four passes
4957 would be necessary, each one starting with one byte more offset
4958 from the stack start. */
4961 mark_stack (void *end
)
4964 /* This assumes that the stack is a contiguous region in memory. If
4965 that's not the case, something has to be done here to iterate
4966 over the stack segments. */
4967 mark_memory (stack_base
, end
);
4969 /* Allow for marking a secondary stack, like the register stack on the
4971 #ifdef GC_MARK_SECONDARY_STACK
4972 GC_MARK_SECONDARY_STACK ();
4977 c_symbol_p (struct Lisp_Symbol
*sym
)
4979 char *lispsym_ptr
= (char *) lispsym
;
4980 char *sym_ptr
= (char *) sym
;
4981 ptrdiff_t lispsym_offset
= sym_ptr
- lispsym_ptr
;
4982 return 0 <= lispsym_offset
&& lispsym_offset
< sizeof lispsym
;
4985 /* Determine whether it is safe to access memory at address P. */
4987 valid_pointer_p (void *p
)
4990 return w32_valid_pointer_p (p
, 16);
4993 if (ADDRESS_SANITIZER
)
4998 /* Obviously, we cannot just access it (we would SEGV trying), so we
4999 trick the o/s to tell us whether p is a valid pointer.
5000 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
5001 not validate p in that case. */
5003 if (emacs_pipe (fd
) == 0)
5005 bool valid
= emacs_write (fd
[1], p
, 16) == 16;
5006 emacs_close (fd
[1]);
5007 emacs_close (fd
[0]);
5015 /* Return 2 if OBJ is a killed or special buffer object, 1 if OBJ is a
5016 valid lisp object, 0 if OBJ is NOT a valid lisp object, or -1 if we
5017 cannot validate OBJ. This function can be quite slow, so its primary
5018 use is the manual debugging. The only exception is print_object, where
5019 we use it to check whether the memory referenced by the pointer of
5020 Lisp_Save_Value object contains valid objects. */
5023 valid_lisp_object_p (Lisp_Object obj
)
5028 void *p
= XPNTR (obj
);
5032 if (SYMBOLP (obj
) && c_symbol_p (p
))
5033 return ((char *) p
- (char *) lispsym
) % sizeof lispsym
[0] == 0;
5035 if (p
== &buffer_defaults
|| p
== &buffer_local_symbols
)
5038 struct mem_node
*m
= mem_find (p
);
5042 int valid
= valid_pointer_p (p
);
5054 case MEM_TYPE_NON_LISP
:
5055 case MEM_TYPE_SPARE
:
5058 case MEM_TYPE_BUFFER
:
5059 return live_buffer_p (m
, p
) ? 1 : 2;
5062 return live_cons_p (m
, p
);
5064 case MEM_TYPE_STRING
:
5065 return live_string_p (m
, p
);
5068 return live_misc_p (m
, p
);
5070 case MEM_TYPE_SYMBOL
:
5071 return live_symbol_p (m
, p
);
5073 case MEM_TYPE_FLOAT
:
5074 return live_float_p (m
, p
);
5076 case MEM_TYPE_VECTORLIKE
:
5077 case MEM_TYPE_VECTOR_BLOCK
:
5078 return live_vector_p (m
, p
);
5087 /***********************************************************************
5088 Pure Storage Management
5089 ***********************************************************************/
5091 /* Allocate room for SIZE bytes from pure Lisp storage and return a
5092 pointer to it. TYPE is the Lisp type for which the memory is
5093 allocated. TYPE < 0 means it's not used for a Lisp object. */
5096 pure_alloc (size_t size
, int type
)
5103 /* Allocate space for a Lisp object from the beginning of the free
5104 space with taking account of alignment. */
5105 result
= ALIGN (purebeg
+ pure_bytes_used_lisp
, GCALIGNMENT
);
5106 pure_bytes_used_lisp
= ((char *)result
- (char *)purebeg
) + size
;
5110 /* Allocate space for a non-Lisp object from the end of the free
5112 pure_bytes_used_non_lisp
+= size
;
5113 result
= purebeg
+ pure_size
- pure_bytes_used_non_lisp
;
5115 pure_bytes_used
= pure_bytes_used_lisp
+ pure_bytes_used_non_lisp
;
5117 if (pure_bytes_used
<= pure_size
)
5120 /* Don't allocate a large amount here,
5121 because it might get mmap'd and then its address
5122 might not be usable. */
5123 purebeg
= xmalloc (10000);
5125 pure_bytes_used_before_overflow
+= pure_bytes_used
- size
;
5126 pure_bytes_used
= 0;
5127 pure_bytes_used_lisp
= pure_bytes_used_non_lisp
= 0;
5132 /* Print a warning if PURESIZE is too small. */
5135 check_pure_size (void)
5137 if (pure_bytes_used_before_overflow
)
5138 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI
"d"
5140 pure_bytes_used
+ pure_bytes_used_before_overflow
);
5144 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
5145 the non-Lisp data pool of the pure storage, and return its start
5146 address. Return NULL if not found. */
5149 find_string_data_in_pure (const char *data
, ptrdiff_t nbytes
)
5152 ptrdiff_t skip
, bm_skip
[256], last_char_skip
, infinity
, start
, start_max
;
5153 const unsigned char *p
;
5156 if (pure_bytes_used_non_lisp
<= nbytes
)
5159 /* Set up the Boyer-Moore table. */
5161 for (i
= 0; i
< 256; i
++)
5164 p
= (const unsigned char *) data
;
5166 bm_skip
[*p
++] = skip
;
5168 last_char_skip
= bm_skip
['\0'];
5170 non_lisp_beg
= purebeg
+ pure_size
- pure_bytes_used_non_lisp
;
5171 start_max
= pure_bytes_used_non_lisp
- (nbytes
+ 1);
5173 /* See the comments in the function `boyer_moore' (search.c) for the
5174 use of `infinity'. */
5175 infinity
= pure_bytes_used_non_lisp
+ 1;
5176 bm_skip
['\0'] = infinity
;
5178 p
= (const unsigned char *) non_lisp_beg
+ nbytes
;
5182 /* Check the last character (== '\0'). */
5185 start
+= bm_skip
[*(p
+ start
)];
5187 while (start
<= start_max
);
5189 if (start
< infinity
)
5190 /* Couldn't find the last character. */
5193 /* No less than `infinity' means we could find the last
5194 character at `p[start - infinity]'. */
5197 /* Check the remaining characters. */
5198 if (memcmp (data
, non_lisp_beg
+ start
, nbytes
) == 0)
5200 return non_lisp_beg
+ start
;
5202 start
+= last_char_skip
;
5204 while (start
<= start_max
);
5210 /* Return a string allocated in pure space. DATA is a buffer holding
5211 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
5212 means make the result string multibyte.
5214 Must get an error if pure storage is full, since if it cannot hold
5215 a large string it may be able to hold conses that point to that
5216 string; then the string is not protected from gc. */
5219 make_pure_string (const char *data
,
5220 ptrdiff_t nchars
, ptrdiff_t nbytes
, bool multibyte
)
5223 struct Lisp_String
*s
= pure_alloc (sizeof *s
, Lisp_String
);
5224 s
->data
= (unsigned char *) find_string_data_in_pure (data
, nbytes
);
5225 if (s
->data
== NULL
)
5227 s
->data
= pure_alloc (nbytes
+ 1, -1);
5228 memcpy (s
->data
, data
, nbytes
);
5229 s
->data
[nbytes
] = '\0';
5232 s
->size_byte
= multibyte
? nbytes
: -1;
5233 s
->intervals
= NULL
;
5234 XSETSTRING (string
, s
);
5238 /* Return a string allocated in pure space. Do not
5239 allocate the string data, just point to DATA. */
5242 make_pure_c_string (const char *data
, ptrdiff_t nchars
)
5245 struct Lisp_String
*s
= pure_alloc (sizeof *s
, Lisp_String
);
5248 s
->data
= (unsigned char *) data
;
5249 s
->intervals
= NULL
;
5250 XSETSTRING (string
, s
);
5254 static Lisp_Object
purecopy (Lisp_Object obj
);
5256 /* Return a cons allocated from pure space. Give it pure copies
5257 of CAR as car and CDR as cdr. */
5260 pure_cons (Lisp_Object car
, Lisp_Object cdr
)
5263 struct Lisp_Cons
*p
= pure_alloc (sizeof *p
, Lisp_Cons
);
5265 XSETCAR (new, purecopy (car
));
5266 XSETCDR (new, purecopy (cdr
));
5271 /* Value is a float object with value NUM allocated from pure space. */
5274 make_pure_float (double num
)
5277 struct Lisp_Float
*p
= pure_alloc (sizeof *p
, Lisp_Float
);
5279 XFLOAT_INIT (new, num
);
5284 /* Return a vector with room for LEN Lisp_Objects allocated from
5288 make_pure_vector (ptrdiff_t len
)
5291 size_t size
= header_size
+ len
* word_size
;
5292 struct Lisp_Vector
*p
= pure_alloc (size
, Lisp_Vectorlike
);
5293 XSETVECTOR (new, p
);
5294 XVECTOR (new)->header
.size
= len
;
5298 DEFUN ("purecopy", Fpurecopy
, Spurecopy
, 1, 1, 0,
5299 doc
: /* Make a copy of object OBJ in pure storage.
5300 Recursively copies contents of vectors and cons cells.
5301 Does not copy symbols. Copies strings without text properties. */)
5302 (register Lisp_Object obj
)
5304 if (NILP (Vpurify_flag
))
5306 else if (MARKERP (obj
) || OVERLAYP (obj
)
5307 || HASH_TABLE_P (obj
) || SYMBOLP (obj
))
5308 /* Can't purify those. */
5311 return purecopy (obj
);
5315 purecopy (Lisp_Object obj
)
5318 || (! SYMBOLP (obj
) && PURE_P (XPNTR_OR_SYMBOL_OFFSET (obj
)))
5320 return obj
; /* Already pure. */
5322 if (STRINGP (obj
) && XSTRING (obj
)->intervals
)
5323 message_with_string ("Dropping text-properties while making string `%s' pure",
5326 if (HASH_TABLE_P (Vpurify_flag
)) /* Hash consing. */
5328 Lisp_Object tmp
= Fgethash (obj
, Vpurify_flag
, Qnil
);
5334 obj
= pure_cons (XCAR (obj
), XCDR (obj
));
5335 else if (FLOATP (obj
))
5336 obj
= make_pure_float (XFLOAT_DATA (obj
));
5337 else if (STRINGP (obj
))
5338 obj
= make_pure_string (SSDATA (obj
), SCHARS (obj
),
5340 STRING_MULTIBYTE (obj
));
5341 else if (COMPILEDP (obj
) || VECTORP (obj
) || HASH_TABLE_P (obj
))
5343 struct Lisp_Vector
*objp
= XVECTOR (obj
);
5344 ptrdiff_t nbytes
= vector_nbytes (objp
);
5345 struct Lisp_Vector
*vec
= pure_alloc (nbytes
, Lisp_Vectorlike
);
5346 register ptrdiff_t i
;
5347 ptrdiff_t size
= ASIZE (obj
);
5348 if (size
& PSEUDOVECTOR_FLAG
)
5349 size
&= PSEUDOVECTOR_SIZE_MASK
;
5350 memcpy (vec
, objp
, nbytes
);
5351 for (i
= 0; i
< size
; i
++)
5352 vec
->contents
[i
] = purecopy (vec
->contents
[i
]);
5353 XSETVECTOR (obj
, vec
);
5355 else if (SYMBOLP (obj
))
5357 if (!XSYMBOL (obj
)->pinned
&& !c_symbol_p (XSYMBOL (obj
)))
5358 { /* We can't purify them, but they appear in many pure objects.
5359 Mark them as `pinned' so we know to mark them at every GC cycle. */
5360 XSYMBOL (obj
)->pinned
= true;
5361 symbol_block_pinned
= symbol_block
;
5363 /* Don't hash-cons it. */
5368 Lisp_Object fmt
= build_pure_c_string ("Don't know how to purify: %S");
5369 Fsignal (Qerror
, list1 (CALLN (Fformat
, fmt
, obj
)));
5372 if (HASH_TABLE_P (Vpurify_flag
)) /* Hash consing. */
5373 Fputhash (obj
, obj
, Vpurify_flag
);
5380 /***********************************************************************
5382 ***********************************************************************/
5384 /* Put an entry in staticvec, pointing at the variable with address
5388 staticpro (Lisp_Object
*varaddress
)
5390 if (staticidx
>= NSTATICS
)
5391 fatal ("NSTATICS too small; try increasing and recompiling Emacs.");
5392 staticvec
[staticidx
++] = varaddress
;
5396 /***********************************************************************
5398 ***********************************************************************/
5400 /* Temporarily prevent garbage collection. */
5403 inhibit_garbage_collection (void)
5405 ptrdiff_t count
= SPECPDL_INDEX ();
5407 specbind (Qgc_cons_threshold
, make_number (MOST_POSITIVE_FIXNUM
));
5411 /* Used to avoid possible overflows when
5412 converting from C to Lisp integers. */
5415 bounded_number (EMACS_INT number
)
5417 return make_number (min (MOST_POSITIVE_FIXNUM
, number
));
5420 /* Calculate total bytes of live objects. */
5423 total_bytes_of_live_objects (void)
5426 tot
+= total_conses
* sizeof (struct Lisp_Cons
);
5427 tot
+= total_symbols
* sizeof (struct Lisp_Symbol
);
5428 tot
+= total_markers
* sizeof (union Lisp_Misc
);
5429 tot
+= total_string_bytes
;
5430 tot
+= total_vector_slots
* word_size
;
5431 tot
+= total_floats
* sizeof (struct Lisp_Float
);
5432 tot
+= total_intervals
* sizeof (struct interval
);
5433 tot
+= total_strings
* sizeof (struct Lisp_String
);
5437 #ifdef HAVE_WINDOW_SYSTEM
5439 /* Remove unmarked font-spec and font-entity objects from ENTRY, which is
5440 (DRIVER-TYPE NUM-FRAMES FONT-CACHE-DATA ...), and return changed entry. */
5443 compact_font_cache_entry (Lisp_Object entry
)
5445 Lisp_Object tail
, *prev
= &entry
;
5447 for (tail
= entry
; CONSP (tail
); tail
= XCDR (tail
))
5450 Lisp_Object obj
= XCAR (tail
);
5452 /* Consider OBJ if it is (font-spec . [font-entity font-entity ...]). */
5453 if (CONSP (obj
) && GC_FONT_SPEC_P (XCAR (obj
))
5454 && !VECTOR_MARKED_P (GC_XFONT_SPEC (XCAR (obj
)))
5455 /* Don't use VECTORP here, as that calls ASIZE, which could
5456 hit assertion violation during GC. */
5457 && (VECTORLIKEP (XCDR (obj
))
5458 && ! (gc_asize (XCDR (obj
)) & PSEUDOVECTOR_FLAG
)))
5460 ptrdiff_t i
, size
= gc_asize (XCDR (obj
));
5461 Lisp_Object obj_cdr
= XCDR (obj
);
5463 /* If font-spec is not marked, most likely all font-entities
5464 are not marked too. But we must be sure that nothing is
5465 marked within OBJ before we really drop it. */
5466 for (i
= 0; i
< size
; i
++)
5468 Lisp_Object objlist
;
5470 if (VECTOR_MARKED_P (GC_XFONT_ENTITY (AREF (obj_cdr
, i
))))
5473 objlist
= AREF (AREF (obj_cdr
, i
), FONT_OBJLIST_INDEX
);
5474 for (; CONSP (objlist
); objlist
= XCDR (objlist
))
5476 Lisp_Object val
= XCAR (objlist
);
5477 struct font
*font
= GC_XFONT_OBJECT (val
);
5479 if (!NILP (AREF (val
, FONT_TYPE_INDEX
))
5480 && VECTOR_MARKED_P(font
))
5483 if (CONSP (objlist
))
5485 /* Found a marked font, bail out. */
5492 /* No marked fonts were found, so this entire font
5493 entity can be dropped. */
5498 *prev
= XCDR (tail
);
5500 prev
= xcdr_addr (tail
);
5505 /* Compact font caches on all terminals and mark
5506 everything which is still here after compaction. */
5509 compact_font_caches (void)
5513 for (t
= terminal_list
; t
; t
= t
->next_terminal
)
5515 Lisp_Object cache
= TERMINAL_FONT_CACHE (t
);
5520 for (entry
= XCDR (cache
); CONSP (entry
); entry
= XCDR (entry
))
5521 XSETCAR (entry
, compact_font_cache_entry (XCAR (entry
)));
5523 mark_object (cache
);
5527 #else /* not HAVE_WINDOW_SYSTEM */
5529 #define compact_font_caches() (void)(0)
5531 #endif /* HAVE_WINDOW_SYSTEM */
5533 /* Remove (MARKER . DATA) entries with unmarked MARKER
5534 from buffer undo LIST and return changed list. */
5537 compact_undo_list (Lisp_Object list
)
5539 Lisp_Object tail
, *prev
= &list
;
5541 for (tail
= list
; CONSP (tail
); tail
= XCDR (tail
))
5543 if (CONSP (XCAR (tail
))
5544 && MARKERP (XCAR (XCAR (tail
)))
5545 && !XMARKER (XCAR (XCAR (tail
)))->gcmarkbit
)
5546 *prev
= XCDR (tail
);
5548 prev
= xcdr_addr (tail
);
5554 mark_pinned_symbols (void)
5556 struct symbol_block
*sblk
;
5557 int lim
= (symbol_block_pinned
== symbol_block
5558 ? symbol_block_index
: SYMBOL_BLOCK_SIZE
);
5560 for (sblk
= symbol_block_pinned
; sblk
; sblk
= sblk
->next
)
5562 union aligned_Lisp_Symbol
*sym
= sblk
->symbols
, *end
= sym
+ lim
;
5563 for (; sym
< end
; ++sym
)
5565 mark_object (make_lisp_symbol (&sym
->s
));
5567 lim
= SYMBOL_BLOCK_SIZE
;
5571 /* Subroutine of Fgarbage_collect that does most of the work. It is a
5572 separate function so that we could limit mark_stack in searching
5573 the stack frames below this function, thus avoiding the rare cases
5574 where mark_stack finds values that look like live Lisp objects on
5575 portions of stack that couldn't possibly contain such live objects.
5576 For more details of this, see the discussion at
5577 http://lists.gnu.org/archive/html/emacs-devel/2014-05/msg00270.html. */
5579 garbage_collect_1 (void *end
)
5581 struct buffer
*nextb
;
5582 char stack_top_variable
;
5585 ptrdiff_t count
= SPECPDL_INDEX ();
5586 struct timespec start
;
5587 Lisp_Object retval
= Qnil
;
5588 size_t tot_before
= 0;
5593 /* Can't GC if pure storage overflowed because we can't determine
5594 if something is a pure object or not. */
5595 if (pure_bytes_used_before_overflow
)
5598 /* Record this function, so it appears on the profiler's backtraces. */
5599 record_in_backtrace (Qautomatic_gc
, 0, 0);
5603 /* Don't keep undo information around forever.
5604 Do this early on, so it is no problem if the user quits. */
5605 FOR_EACH_BUFFER (nextb
)
5606 compact_buffer (nextb
);
5608 if (profiler_memory_running
)
5609 tot_before
= total_bytes_of_live_objects ();
5611 start
= current_timespec ();
5613 /* In case user calls debug_print during GC,
5614 don't let that cause a recursive GC. */
5615 consing_since_gc
= 0;
5617 /* Save what's currently displayed in the echo area. Don't do that
5618 if we are GC'ing because we've run out of memory, since
5619 push_message will cons, and we might have no memory for that. */
5620 if (NILP (Vmemory_full
))
5622 message_p
= push_message ();
5623 record_unwind_protect_void (pop_message_unwind
);
5628 /* Save a copy of the contents of the stack, for debugging. */
5629 #if MAX_SAVE_STACK > 0
5630 if (NILP (Vpurify_flag
))
5633 ptrdiff_t stack_size
;
5634 if (&stack_top_variable
< stack_bottom
)
5636 stack
= &stack_top_variable
;
5637 stack_size
= stack_bottom
- &stack_top_variable
;
5641 stack
= stack_bottom
;
5642 stack_size
= &stack_top_variable
- stack_bottom
;
5644 if (stack_size
<= MAX_SAVE_STACK
)
5646 if (stack_copy_size
< stack_size
)
5648 stack_copy
= xrealloc (stack_copy
, stack_size
);
5649 stack_copy_size
= stack_size
;
5651 no_sanitize_memcpy (stack_copy
, stack
, stack_size
);
5654 #endif /* MAX_SAVE_STACK > 0 */
5656 if (garbage_collection_messages
)
5657 message1_nolog ("Garbage collecting...");
5661 shrink_regexp_cache ();
5665 /* Mark all the special slots that serve as the roots of accessibility. */
5667 mark_buffer (&buffer_defaults
);
5668 mark_buffer (&buffer_local_symbols
);
5670 for (i
= 0; i
< ARRAYELTS (lispsym
); i
++)
5671 mark_object (builtin_lisp_symbol (i
));
5673 for (i
= 0; i
< staticidx
; i
++)
5674 mark_object (*staticvec
[i
]);
5676 mark_pinned_symbols ();
5688 struct handler
*handler
;
5689 for (handler
= handlerlist
; handler
; handler
= handler
->next
)
5691 mark_object (handler
->tag_or_ch
);
5692 mark_object (handler
->val
);
5695 #ifdef HAVE_WINDOW_SYSTEM
5696 mark_fringe_data ();
5699 /* Everything is now marked, except for the data in font caches,
5700 undo lists, and finalizers. The first two are compacted by
5701 removing an items which aren't reachable otherwise. */
5703 compact_font_caches ();
5705 FOR_EACH_BUFFER (nextb
)
5707 if (!EQ (BVAR (nextb
, undo_list
), Qt
))
5708 bset_undo_list (nextb
, compact_undo_list (BVAR (nextb
, undo_list
)));
5709 /* Now that we have stripped the elements that need not be
5710 in the undo_list any more, we can finally mark the list. */
5711 mark_object (BVAR (nextb
, undo_list
));
5714 /* Now pre-sweep finalizers. Here, we add any unmarked finalizers
5715 to doomed_finalizers so we can run their associated functions
5716 after GC. It's important to scan finalizers at this stage so
5717 that we can be sure that unmarked finalizers are really
5718 unreachable except for references from their associated functions
5719 and from other finalizers. */
5721 queue_doomed_finalizers (&doomed_finalizers
, &finalizers
);
5722 mark_finalizer_list (&doomed_finalizers
);
5726 relocate_byte_stack ();
5728 /* Clear the mark bits that we set in certain root slots. */
5729 VECTOR_UNMARK (&buffer_defaults
);
5730 VECTOR_UNMARK (&buffer_local_symbols
);
5738 consing_since_gc
= 0;
5739 if (gc_cons_threshold
< GC_DEFAULT_THRESHOLD
/ 10)
5740 gc_cons_threshold
= GC_DEFAULT_THRESHOLD
/ 10;
5742 gc_relative_threshold
= 0;
5743 if (FLOATP (Vgc_cons_percentage
))
5744 { /* Set gc_cons_combined_threshold. */
5745 double tot
= total_bytes_of_live_objects ();
5747 tot
*= XFLOAT_DATA (Vgc_cons_percentage
);
5750 if (tot
< TYPE_MAXIMUM (EMACS_INT
))
5751 gc_relative_threshold
= tot
;
5753 gc_relative_threshold
= TYPE_MAXIMUM (EMACS_INT
);
5757 if (garbage_collection_messages
&& NILP (Vmemory_full
))
5759 if (message_p
|| minibuf_level
> 0)
5762 message1_nolog ("Garbage collecting...done");
5765 unbind_to (count
, Qnil
);
5767 Lisp_Object total
[] = {
5768 list4 (Qconses
, make_number (sizeof (struct Lisp_Cons
)),
5769 bounded_number (total_conses
),
5770 bounded_number (total_free_conses
)),
5771 list4 (Qsymbols
, make_number (sizeof (struct Lisp_Symbol
)),
5772 bounded_number (total_symbols
),
5773 bounded_number (total_free_symbols
)),
5774 list4 (Qmiscs
, make_number (sizeof (union Lisp_Misc
)),
5775 bounded_number (total_markers
),
5776 bounded_number (total_free_markers
)),
5777 list4 (Qstrings
, make_number (sizeof (struct Lisp_String
)),
5778 bounded_number (total_strings
),
5779 bounded_number (total_free_strings
)),
5780 list3 (Qstring_bytes
, make_number (1),
5781 bounded_number (total_string_bytes
)),
5783 make_number (header_size
+ sizeof (Lisp_Object
)),
5784 bounded_number (total_vectors
)),
5785 list4 (Qvector_slots
, make_number (word_size
),
5786 bounded_number (total_vector_slots
),
5787 bounded_number (total_free_vector_slots
)),
5788 list4 (Qfloats
, make_number (sizeof (struct Lisp_Float
)),
5789 bounded_number (total_floats
),
5790 bounded_number (total_free_floats
)),
5791 list4 (Qintervals
, make_number (sizeof (struct interval
)),
5792 bounded_number (total_intervals
),
5793 bounded_number (total_free_intervals
)),
5794 list3 (Qbuffers
, make_number (sizeof (struct buffer
)),
5795 bounded_number (total_buffers
)),
5797 #ifdef DOUG_LEA_MALLOC
5798 list4 (Qheap
, make_number (1024),
5799 bounded_number ((mallinfo ().uordblks
+ 1023) >> 10),
5800 bounded_number ((mallinfo ().fordblks
+ 1023) >> 10)),
5803 retval
= CALLMANY (Flist
, total
);
5805 /* GC is complete: now we can run our finalizer callbacks. */
5806 run_finalizers (&doomed_finalizers
);
5808 if (!NILP (Vpost_gc_hook
))
5810 ptrdiff_t gc_count
= inhibit_garbage_collection ();
5811 safe_run_hooks (Qpost_gc_hook
);
5812 unbind_to (gc_count
, Qnil
);
5815 /* Accumulate statistics. */
5816 if (FLOATP (Vgc_elapsed
))
5818 struct timespec since_start
= timespec_sub (current_timespec (), start
);
5819 Vgc_elapsed
= make_float (XFLOAT_DATA (Vgc_elapsed
)
5820 + timespectod (since_start
));
5825 /* Collect profiling data. */
5826 if (profiler_memory_running
)
5829 size_t tot_after
= total_bytes_of_live_objects ();
5830 if (tot_before
> tot_after
)
5831 swept
= tot_before
- tot_after
;
5832 malloc_probe (swept
);
5838 DEFUN ("garbage-collect", Fgarbage_collect
, Sgarbage_collect
, 0, 0, "",
5839 doc
: /* Reclaim storage for Lisp objects no longer needed.
5840 Garbage collection happens automatically if you cons more than
5841 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5842 `garbage-collect' normally returns a list with info on amount of space in use,
5843 where each entry has the form (NAME SIZE USED FREE), where:
5844 - NAME is a symbol describing the kind of objects this entry represents,
5845 - SIZE is the number of bytes used by each one,
5846 - USED is the number of those objects that were found live in the heap,
5847 - FREE is the number of those objects that are not live but that Emacs
5848 keeps around for future allocations (maybe because it does not know how
5849 to return them to the OS).
5850 However, if there was overflow in pure space, `garbage-collect'
5851 returns nil, because real GC can't be done.
5852 See Info node `(elisp)Garbage Collection'. */)
5857 #ifdef HAVE___BUILTIN_UNWIND_INIT
5858 /* Force callee-saved registers and register windows onto the stack.
5859 This is the preferred method if available, obviating the need for
5860 machine dependent methods. */
5861 __builtin_unwind_init ();
5863 #else /* not HAVE___BUILTIN_UNWIND_INIT */
5864 #ifndef GC_SAVE_REGISTERS_ON_STACK
5865 /* jmp_buf may not be aligned enough on darwin-ppc64 */
5866 union aligned_jmpbuf
{
5870 volatile bool stack_grows_down_p
= (char *) &j
> (char *) stack_base
;
5872 /* This trick flushes the register windows so that all the state of
5873 the process is contained in the stack. */
5874 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
5875 needed on ia64 too. See mach_dep.c, where it also says inline
5876 assembler doesn't work with relevant proprietary compilers. */
5878 #if defined (__sparc64__) && defined (__FreeBSD__)
5879 /* FreeBSD does not have a ta 3 handler. */
5886 /* Save registers that we need to see on the stack. We need to see
5887 registers used to hold register variables and registers used to
5889 #ifdef GC_SAVE_REGISTERS_ON_STACK
5890 GC_SAVE_REGISTERS_ON_STACK (end
);
5891 #else /* not GC_SAVE_REGISTERS_ON_STACK */
5893 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
5894 setjmp will definitely work, test it
5895 and print a message with the result
5897 if (!setjmp_tested_p
)
5899 setjmp_tested_p
= 1;
5902 #endif /* GC_SETJMP_WORKS */
5905 end
= stack_grows_down_p
? (char *) &j
+ sizeof j
: (char *) &j
;
5906 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
5907 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
5908 return garbage_collect_1 (end
);
5911 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5912 only interesting objects referenced from glyphs are strings. */
5915 mark_glyph_matrix (struct glyph_matrix
*matrix
)
5917 struct glyph_row
*row
= matrix
->rows
;
5918 struct glyph_row
*end
= row
+ matrix
->nrows
;
5920 for (; row
< end
; ++row
)
5924 for (area
= LEFT_MARGIN_AREA
; area
< LAST_AREA
; ++area
)
5926 struct glyph
*glyph
= row
->glyphs
[area
];
5927 struct glyph
*end_glyph
= glyph
+ row
->used
[area
];
5929 for (; glyph
< end_glyph
; ++glyph
)
5930 if (STRINGP (glyph
->object
)
5931 && !STRING_MARKED_P (XSTRING (glyph
->object
)))
5932 mark_object (glyph
->object
);
5937 /* Mark reference to a Lisp_Object.
5938 If the object referred to has not been seen yet, recursively mark
5939 all the references contained in it. */
5941 #define LAST_MARKED_SIZE 500
5942 static Lisp_Object last_marked
[LAST_MARKED_SIZE
];
5943 static int last_marked_index
;
5945 /* For debugging--call abort when we cdr down this many
5946 links of a list, in mark_object. In debugging,
5947 the call to abort will hit a breakpoint.
5948 Normally this is zero and the check never goes off. */
5949 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE
;
5952 mark_vectorlike (struct Lisp_Vector
*ptr
)
5954 ptrdiff_t size
= ptr
->header
.size
;
5957 eassert (!VECTOR_MARKED_P (ptr
));
5958 VECTOR_MARK (ptr
); /* Else mark it. */
5959 if (size
& PSEUDOVECTOR_FLAG
)
5960 size
&= PSEUDOVECTOR_SIZE_MASK
;
5962 /* Note that this size is not the memory-footprint size, but only
5963 the number of Lisp_Object fields that we should trace.
5964 The distinction is used e.g. by Lisp_Process which places extra
5965 non-Lisp_Object fields at the end of the structure... */
5966 for (i
= 0; i
< size
; i
++) /* ...and then mark its elements. */
5967 mark_object (ptr
->contents
[i
]);
5970 /* Like mark_vectorlike but optimized for char-tables (and
5971 sub-char-tables) assuming that the contents are mostly integers or
5975 mark_char_table (struct Lisp_Vector
*ptr
, enum pvec_type pvectype
)
5977 int size
= ptr
->header
.size
& PSEUDOVECTOR_SIZE_MASK
;
5978 /* Consult the Lisp_Sub_Char_Table layout before changing this. */
5979 int i
, idx
= (pvectype
== PVEC_SUB_CHAR_TABLE
? SUB_CHAR_TABLE_OFFSET
: 0);
5981 eassert (!VECTOR_MARKED_P (ptr
));
5983 for (i
= idx
; i
< size
; i
++)
5985 Lisp_Object val
= ptr
->contents
[i
];
5987 if (INTEGERP (val
) || (SYMBOLP (val
) && XSYMBOL (val
)->gcmarkbit
))
5989 if (SUB_CHAR_TABLE_P (val
))
5991 if (! VECTOR_MARKED_P (XVECTOR (val
)))
5992 mark_char_table (XVECTOR (val
), PVEC_SUB_CHAR_TABLE
);
5999 NO_INLINE
/* To reduce stack depth in mark_object. */
6001 mark_compiled (struct Lisp_Vector
*ptr
)
6003 int i
, size
= ptr
->header
.size
& PSEUDOVECTOR_SIZE_MASK
;
6006 for (i
= 0; i
< size
; i
++)
6007 if (i
!= COMPILED_CONSTANTS
)
6008 mark_object (ptr
->contents
[i
]);
6009 return size
> COMPILED_CONSTANTS
? ptr
->contents
[COMPILED_CONSTANTS
] : Qnil
;
6012 /* Mark the chain of overlays starting at PTR. */
6015 mark_overlay (struct Lisp_Overlay
*ptr
)
6017 for (; ptr
&& !ptr
->gcmarkbit
; ptr
= ptr
->next
)
6020 /* These two are always markers and can be marked fast. */
6021 XMARKER (ptr
->start
)->gcmarkbit
= 1;
6022 XMARKER (ptr
->end
)->gcmarkbit
= 1;
6023 mark_object (ptr
->plist
);
6027 /* Mark Lisp_Objects and special pointers in BUFFER. */
6030 mark_buffer (struct buffer
*buffer
)
6032 /* This is handled much like other pseudovectors... */
6033 mark_vectorlike ((struct Lisp_Vector
*) buffer
);
6035 /* ...but there are some buffer-specific things. */
6037 MARK_INTERVAL_TREE (buffer_intervals (buffer
));
6039 /* For now, we just don't mark the undo_list. It's done later in
6040 a special way just before the sweep phase, and after stripping
6041 some of its elements that are not needed any more. */
6043 mark_overlay (buffer
->overlays_before
);
6044 mark_overlay (buffer
->overlays_after
);
6046 /* If this is an indirect buffer, mark its base buffer. */
6047 if (buffer
->base_buffer
&& !VECTOR_MARKED_P (buffer
->base_buffer
))
6048 mark_buffer (buffer
->base_buffer
);
6051 /* Mark Lisp faces in the face cache C. */
6053 NO_INLINE
/* To reduce stack depth in mark_object. */
6055 mark_face_cache (struct face_cache
*c
)
6060 for (i
= 0; i
< c
->used
; ++i
)
6062 struct face
*face
= FACE_FROM_ID (c
->f
, i
);
6066 if (face
->font
&& !VECTOR_MARKED_P (face
->font
))
6067 mark_vectorlike ((struct Lisp_Vector
*) face
->font
);
6069 for (j
= 0; j
< LFACE_VECTOR_SIZE
; ++j
)
6070 mark_object (face
->lface
[j
]);
6076 NO_INLINE
/* To reduce stack depth in mark_object. */
6078 mark_localized_symbol (struct Lisp_Symbol
*ptr
)
6080 struct Lisp_Buffer_Local_Value
*blv
= SYMBOL_BLV (ptr
);
6081 Lisp_Object where
= blv
->where
;
6082 /* If the value is set up for a killed buffer or deleted
6083 frame, restore its global binding. If the value is
6084 forwarded to a C variable, either it's not a Lisp_Object
6085 var, or it's staticpro'd already. */
6086 if ((BUFFERP (where
) && !BUFFER_LIVE_P (XBUFFER (where
)))
6087 || (FRAMEP (where
) && !FRAME_LIVE_P (XFRAME (where
))))
6088 swap_in_global_binding (ptr
);
6089 mark_object (blv
->where
);
6090 mark_object (blv
->valcell
);
6091 mark_object (blv
->defcell
);
6094 NO_INLINE
/* To reduce stack depth in mark_object. */
6096 mark_save_value (struct Lisp_Save_Value
*ptr
)
6098 /* If `save_type' is zero, `data[0].pointer' is the address
6099 of a memory area containing `data[1].integer' potential
6101 if (ptr
->save_type
== SAVE_TYPE_MEMORY
)
6103 Lisp_Object
*p
= ptr
->data
[0].pointer
;
6105 for (nelt
= ptr
->data
[1].integer
; nelt
> 0; nelt
--, p
++)
6106 mark_maybe_object (*p
);
6110 /* Find Lisp_Objects in `data[N]' slots and mark them. */
6112 for (i
= 0; i
< SAVE_VALUE_SLOTS
; i
++)
6113 if (save_type (ptr
, i
) == SAVE_OBJECT
)
6114 mark_object (ptr
->data
[i
].object
);
6118 /* Remove killed buffers or items whose car is a killed buffer from
6119 LIST, and mark other items. Return changed LIST, which is marked. */
6122 mark_discard_killed_buffers (Lisp_Object list
)
6124 Lisp_Object tail
, *prev
= &list
;
6126 for (tail
= list
; CONSP (tail
) && !CONS_MARKED_P (XCONS (tail
));
6129 Lisp_Object tem
= XCAR (tail
);
6132 if (BUFFERP (tem
) && !BUFFER_LIVE_P (XBUFFER (tem
)))
6133 *prev
= XCDR (tail
);
6136 CONS_MARK (XCONS (tail
));
6137 mark_object (XCAR (tail
));
6138 prev
= xcdr_addr (tail
);
6145 /* Determine type of generic Lisp_Object and mark it accordingly.
6147 This function implements a straightforward depth-first marking
6148 algorithm and so the recursion depth may be very high (a few
6149 tens of thousands is not uncommon). To minimize stack usage,
6150 a few cold paths are moved out to NO_INLINE functions above.
6151 In general, inlining them doesn't help you to gain more speed. */
6154 mark_object (Lisp_Object arg
)
6156 register Lisp_Object obj
;
6158 #ifdef GC_CHECK_MARKED_OBJECTS
6161 ptrdiff_t cdr_count
= 0;
6170 last_marked
[last_marked_index
++] = obj
;
6171 if (last_marked_index
== LAST_MARKED_SIZE
)
6172 last_marked_index
= 0;
6174 /* Perform some sanity checks on the objects marked here. Abort if
6175 we encounter an object we know is bogus. This increases GC time
6177 #ifdef GC_CHECK_MARKED_OBJECTS
6179 /* Check that the object pointed to by PO is known to be a Lisp
6180 structure allocated from the heap. */
6181 #define CHECK_ALLOCATED() \
6183 m = mem_find (po); \
6188 /* Check that the object pointed to by PO is live, using predicate
6190 #define CHECK_LIVE(LIVEP) \
6192 if (!LIVEP (m, po)) \
6196 /* Check both of the above conditions, for non-symbols. */
6197 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
6199 CHECK_ALLOCATED (); \
6200 CHECK_LIVE (LIVEP); \
6203 /* Check both of the above conditions, for symbols. */
6204 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() \
6206 if (!c_symbol_p (ptr)) \
6208 CHECK_ALLOCATED (); \
6209 CHECK_LIVE (live_symbol_p); \
6213 #else /* not GC_CHECK_MARKED_OBJECTS */
6215 #define CHECK_LIVE(LIVEP) ((void) 0)
6216 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) ((void) 0)
6217 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() ((void) 0)
6219 #endif /* not GC_CHECK_MARKED_OBJECTS */
6221 switch (XTYPE (obj
))
6225 register struct Lisp_String
*ptr
= XSTRING (obj
);
6226 if (STRING_MARKED_P (ptr
))
6228 CHECK_ALLOCATED_AND_LIVE (live_string_p
);
6230 MARK_INTERVAL_TREE (ptr
->intervals
);
6231 #ifdef GC_CHECK_STRING_BYTES
6232 /* Check that the string size recorded in the string is the
6233 same as the one recorded in the sdata structure. */
6235 #endif /* GC_CHECK_STRING_BYTES */
6239 case Lisp_Vectorlike
:
6241 register struct Lisp_Vector
*ptr
= XVECTOR (obj
);
6242 register ptrdiff_t pvectype
;
6244 if (VECTOR_MARKED_P (ptr
))
6247 #ifdef GC_CHECK_MARKED_OBJECTS
6249 if (m
== MEM_NIL
&& !SUBRP (obj
))
6251 #endif /* GC_CHECK_MARKED_OBJECTS */
6253 if (ptr
->header
.size
& PSEUDOVECTOR_FLAG
)
6254 pvectype
= ((ptr
->header
.size
& PVEC_TYPE_MASK
)
6255 >> PSEUDOVECTOR_AREA_BITS
);
6257 pvectype
= PVEC_NORMAL_VECTOR
;
6259 if (pvectype
!= PVEC_SUBR
&& pvectype
!= PVEC_BUFFER
)
6260 CHECK_LIVE (live_vector_p
);
6265 #ifdef GC_CHECK_MARKED_OBJECTS
6274 #endif /* GC_CHECK_MARKED_OBJECTS */
6275 mark_buffer ((struct buffer
*) ptr
);
6279 /* Although we could treat this just like a vector, mark_compiled
6280 returns the COMPILED_CONSTANTS element, which is marked at the
6281 next iteration of goto-loop here. This is done to avoid a few
6282 recursive calls to mark_object. */
6283 obj
= mark_compiled (ptr
);
6290 struct frame
*f
= (struct frame
*) ptr
;
6292 mark_vectorlike (ptr
);
6293 mark_face_cache (f
->face_cache
);
6294 #ifdef HAVE_WINDOW_SYSTEM
6295 if (FRAME_WINDOW_P (f
) && FRAME_X_OUTPUT (f
))
6297 struct font
*font
= FRAME_FONT (f
);
6299 if (font
&& !VECTOR_MARKED_P (font
))
6300 mark_vectorlike ((struct Lisp_Vector
*) font
);
6308 struct window
*w
= (struct window
*) ptr
;
6310 mark_vectorlike (ptr
);
6312 /* Mark glyph matrices, if any. Marking window
6313 matrices is sufficient because frame matrices
6314 use the same glyph memory. */
6315 if (w
->current_matrix
)
6317 mark_glyph_matrix (w
->current_matrix
);
6318 mark_glyph_matrix (w
->desired_matrix
);
6321 /* Filter out killed buffers from both buffer lists
6322 in attempt to help GC to reclaim killed buffers faster.
6323 We can do it elsewhere for live windows, but this is the
6324 best place to do it for dead windows. */
6326 (w
, mark_discard_killed_buffers (w
->prev_buffers
));
6328 (w
, mark_discard_killed_buffers (w
->next_buffers
));
6332 case PVEC_HASH_TABLE
:
6334 struct Lisp_Hash_Table
*h
= (struct Lisp_Hash_Table
*) ptr
;
6336 mark_vectorlike (ptr
);
6337 mark_object (h
->test
.name
);
6338 mark_object (h
->test
.user_hash_function
);
6339 mark_object (h
->test
.user_cmp_function
);
6340 /* If hash table is not weak, mark all keys and values.
6341 For weak tables, mark only the vector. */
6343 mark_object (h
->key_and_value
);
6345 VECTOR_MARK (XVECTOR (h
->key_and_value
));
6349 case PVEC_CHAR_TABLE
:
6350 case PVEC_SUB_CHAR_TABLE
:
6351 mark_char_table (ptr
, (enum pvec_type
) pvectype
);
6354 case PVEC_BOOL_VECTOR
:
6355 /* No Lisp_Objects to mark in a bool vector. */
6366 mark_vectorlike (ptr
);
6373 register struct Lisp_Symbol
*ptr
= XSYMBOL (obj
);
6377 CHECK_ALLOCATED_AND_LIVE_SYMBOL ();
6379 /* Attempt to catch bogus objects. */
6380 eassert (valid_lisp_object_p (ptr
->function
));
6381 mark_object (ptr
->function
);
6382 mark_object (ptr
->plist
);
6383 switch (ptr
->redirect
)
6385 case SYMBOL_PLAINVAL
: mark_object (SYMBOL_VAL (ptr
)); break;
6386 case SYMBOL_VARALIAS
:
6389 XSETSYMBOL (tem
, SYMBOL_ALIAS (ptr
));
6393 case SYMBOL_LOCALIZED
:
6394 mark_localized_symbol (ptr
);
6396 case SYMBOL_FORWARDED
:
6397 /* If the value is forwarded to a buffer or keyboard field,
6398 these are marked when we see the corresponding object.
6399 And if it's forwarded to a C variable, either it's not
6400 a Lisp_Object var, or it's staticpro'd already. */
6402 default: emacs_abort ();
6404 if (!PURE_P (XSTRING (ptr
->name
)))
6405 MARK_STRING (XSTRING (ptr
->name
));
6406 MARK_INTERVAL_TREE (string_intervals (ptr
->name
));
6407 /* Inner loop to mark next symbol in this bucket, if any. */
6408 po
= ptr
= ptr
->next
;
6415 CHECK_ALLOCATED_AND_LIVE (live_misc_p
);
6417 if (XMISCANY (obj
)->gcmarkbit
)
6420 switch (XMISCTYPE (obj
))
6422 case Lisp_Misc_Marker
:
6423 /* DO NOT mark thru the marker's chain.
6424 The buffer's markers chain does not preserve markers from gc;
6425 instead, markers are removed from the chain when freed by gc. */
6426 XMISCANY (obj
)->gcmarkbit
= 1;
6429 case Lisp_Misc_Save_Value
:
6430 XMISCANY (obj
)->gcmarkbit
= 1;
6431 mark_save_value (XSAVE_VALUE (obj
));
6434 case Lisp_Misc_Overlay
:
6435 mark_overlay (XOVERLAY (obj
));
6438 case Lisp_Misc_Finalizer
:
6439 XMISCANY (obj
)->gcmarkbit
= true;
6440 mark_object (XFINALIZER (obj
)->function
);
6444 case Lisp_Misc_User_Ptr
:
6445 XMISCANY (obj
)->gcmarkbit
= true;
6456 register struct Lisp_Cons
*ptr
= XCONS (obj
);
6457 if (CONS_MARKED_P (ptr
))
6459 CHECK_ALLOCATED_AND_LIVE (live_cons_p
);
6461 /* If the cdr is nil, avoid recursion for the car. */
6462 if (EQ (ptr
->u
.cdr
, Qnil
))
6468 mark_object (ptr
->car
);
6471 if (cdr_count
== mark_object_loop_halt
)
6477 CHECK_ALLOCATED_AND_LIVE (live_float_p
);
6478 FLOAT_MARK (XFLOAT (obj
));
6489 #undef CHECK_ALLOCATED
6490 #undef CHECK_ALLOCATED_AND_LIVE
6492 /* Mark the Lisp pointers in the terminal objects.
6493 Called by Fgarbage_collect. */
6496 mark_terminals (void)
6499 for (t
= terminal_list
; t
; t
= t
->next_terminal
)
6501 eassert (t
->name
!= NULL
);
6502 #ifdef HAVE_WINDOW_SYSTEM
6503 /* If a terminal object is reachable from a stacpro'ed object,
6504 it might have been marked already. Make sure the image cache
6506 mark_image_cache (t
->image_cache
);
6507 #endif /* HAVE_WINDOW_SYSTEM */
6508 if (!VECTOR_MARKED_P (t
))
6509 mark_vectorlike ((struct Lisp_Vector
*)t
);
6515 /* Value is non-zero if OBJ will survive the current GC because it's
6516 either marked or does not need to be marked to survive. */
6519 survives_gc_p (Lisp_Object obj
)
6523 switch (XTYPE (obj
))
6530 survives_p
= XSYMBOL (obj
)->gcmarkbit
;
6534 survives_p
= XMISCANY (obj
)->gcmarkbit
;
6538 survives_p
= STRING_MARKED_P (XSTRING (obj
));
6541 case Lisp_Vectorlike
:
6542 survives_p
= SUBRP (obj
) || VECTOR_MARKED_P (XVECTOR (obj
));
6546 survives_p
= CONS_MARKED_P (XCONS (obj
));
6550 survives_p
= FLOAT_MARKED_P (XFLOAT (obj
));
6557 return survives_p
|| PURE_P (XPNTR (obj
));
6563 NO_INLINE
/* For better stack traces */
6567 struct cons_block
*cblk
;
6568 struct cons_block
**cprev
= &cons_block
;
6569 int lim
= cons_block_index
;
6570 EMACS_INT num_free
= 0, num_used
= 0;
6574 for (cblk
= cons_block
; cblk
; cblk
= *cprev
)
6578 int ilim
= (lim
+ BITS_PER_BITS_WORD
- 1) / BITS_PER_BITS_WORD
;
6580 /* Scan the mark bits an int at a time. */
6581 for (i
= 0; i
< ilim
; i
++)
6583 if (cblk
->gcmarkbits
[i
] == BITS_WORD_MAX
)
6585 /* Fast path - all cons cells for this int are marked. */
6586 cblk
->gcmarkbits
[i
] = 0;
6587 num_used
+= BITS_PER_BITS_WORD
;
6591 /* Some cons cells for this int are not marked.
6592 Find which ones, and free them. */
6593 int start
, pos
, stop
;
6595 start
= i
* BITS_PER_BITS_WORD
;
6597 if (stop
> BITS_PER_BITS_WORD
)
6598 stop
= BITS_PER_BITS_WORD
;
6601 for (pos
= start
; pos
< stop
; pos
++)
6603 if (!CONS_MARKED_P (&cblk
->conses
[pos
]))
6606 cblk
->conses
[pos
].u
.chain
= cons_free_list
;
6607 cons_free_list
= &cblk
->conses
[pos
];
6608 cons_free_list
->car
= Vdead
;
6613 CONS_UNMARK (&cblk
->conses
[pos
]);
6619 lim
= CONS_BLOCK_SIZE
;
6620 /* If this block contains only free conses and we have already
6621 seen more than two blocks worth of free conses then deallocate
6623 if (this_free
== CONS_BLOCK_SIZE
&& num_free
> CONS_BLOCK_SIZE
)
6625 *cprev
= cblk
->next
;
6626 /* Unhook from the free list. */
6627 cons_free_list
= cblk
->conses
[0].u
.chain
;
6628 lisp_align_free (cblk
);
6632 num_free
+= this_free
;
6633 cprev
= &cblk
->next
;
6636 total_conses
= num_used
;
6637 total_free_conses
= num_free
;
6640 NO_INLINE
/* For better stack traces */
6644 register struct float_block
*fblk
;
6645 struct float_block
**fprev
= &float_block
;
6646 register int lim
= float_block_index
;
6647 EMACS_INT num_free
= 0, num_used
= 0;
6649 float_free_list
= 0;
6651 for (fblk
= float_block
; fblk
; fblk
= *fprev
)
6655 for (i
= 0; i
< lim
; i
++)
6656 if (!FLOAT_MARKED_P (&fblk
->floats
[i
]))
6659 fblk
->floats
[i
].u
.chain
= float_free_list
;
6660 float_free_list
= &fblk
->floats
[i
];
6665 FLOAT_UNMARK (&fblk
->floats
[i
]);
6667 lim
= FLOAT_BLOCK_SIZE
;
6668 /* If this block contains only free floats and we have already
6669 seen more than two blocks worth of free floats then deallocate
6671 if (this_free
== FLOAT_BLOCK_SIZE
&& num_free
> FLOAT_BLOCK_SIZE
)
6673 *fprev
= fblk
->next
;
6674 /* Unhook from the free list. */
6675 float_free_list
= fblk
->floats
[0].u
.chain
;
6676 lisp_align_free (fblk
);
6680 num_free
+= this_free
;
6681 fprev
= &fblk
->next
;
6684 total_floats
= num_used
;
6685 total_free_floats
= num_free
;
6688 NO_INLINE
/* For better stack traces */
6690 sweep_intervals (void)
6692 register struct interval_block
*iblk
;
6693 struct interval_block
**iprev
= &interval_block
;
6694 register int lim
= interval_block_index
;
6695 EMACS_INT num_free
= 0, num_used
= 0;
6697 interval_free_list
= 0;
6699 for (iblk
= interval_block
; iblk
; iblk
= *iprev
)
6704 for (i
= 0; i
< lim
; i
++)
6706 if (!iblk
->intervals
[i
].gcmarkbit
)
6708 set_interval_parent (&iblk
->intervals
[i
], interval_free_list
);
6709 interval_free_list
= &iblk
->intervals
[i
];
6715 iblk
->intervals
[i
].gcmarkbit
= 0;
6718 lim
= INTERVAL_BLOCK_SIZE
;
6719 /* If this block contains only free intervals and we have already
6720 seen more than two blocks worth of free intervals then
6721 deallocate this block. */
6722 if (this_free
== INTERVAL_BLOCK_SIZE
&& num_free
> INTERVAL_BLOCK_SIZE
)
6724 *iprev
= iblk
->next
;
6725 /* Unhook from the free list. */
6726 interval_free_list
= INTERVAL_PARENT (&iblk
->intervals
[0]);
6731 num_free
+= this_free
;
6732 iprev
= &iblk
->next
;
6735 total_intervals
= num_used
;
6736 total_free_intervals
= num_free
;
6739 NO_INLINE
/* For better stack traces */
6741 sweep_symbols (void)
6743 struct symbol_block
*sblk
;
6744 struct symbol_block
**sprev
= &symbol_block
;
6745 int lim
= symbol_block_index
;
6746 EMACS_INT num_free
= 0, num_used
= ARRAYELTS (lispsym
);
6748 symbol_free_list
= NULL
;
6750 for (int i
= 0; i
< ARRAYELTS (lispsym
); i
++)
6751 lispsym
[i
].gcmarkbit
= 0;
6753 for (sblk
= symbol_block
; sblk
; sblk
= *sprev
)
6756 union aligned_Lisp_Symbol
*sym
= sblk
->symbols
;
6757 union aligned_Lisp_Symbol
*end
= sym
+ lim
;
6759 for (; sym
< end
; ++sym
)
6761 if (!sym
->s
.gcmarkbit
)
6763 if (sym
->s
.redirect
== SYMBOL_LOCALIZED
)
6764 xfree (SYMBOL_BLV (&sym
->s
));
6765 sym
->s
.next
= symbol_free_list
;
6766 symbol_free_list
= &sym
->s
;
6767 symbol_free_list
->function
= Vdead
;
6773 sym
->s
.gcmarkbit
= 0;
6774 /* Attempt to catch bogus objects. */
6775 eassert (valid_lisp_object_p (sym
->s
.function
));
6779 lim
= SYMBOL_BLOCK_SIZE
;
6780 /* If this block contains only free symbols and we have already
6781 seen more than two blocks worth of free symbols then deallocate
6783 if (this_free
== SYMBOL_BLOCK_SIZE
&& num_free
> SYMBOL_BLOCK_SIZE
)
6785 *sprev
= sblk
->next
;
6786 /* Unhook from the free list. */
6787 symbol_free_list
= sblk
->symbols
[0].s
.next
;
6792 num_free
+= this_free
;
6793 sprev
= &sblk
->next
;
6796 total_symbols
= num_used
;
6797 total_free_symbols
= num_free
;
6800 NO_INLINE
/* For better stack traces. */
6804 register struct marker_block
*mblk
;
6805 struct marker_block
**mprev
= &marker_block
;
6806 register int lim
= marker_block_index
;
6807 EMACS_INT num_free
= 0, num_used
= 0;
6809 /* Put all unmarked misc's on free list. For a marker, first
6810 unchain it from the buffer it points into. */
6812 marker_free_list
= 0;
6814 for (mblk
= marker_block
; mblk
; mblk
= *mprev
)
6819 for (i
= 0; i
< lim
; i
++)
6821 if (!mblk
->markers
[i
].m
.u_any
.gcmarkbit
)
6823 if (mblk
->markers
[i
].m
.u_any
.type
== Lisp_Misc_Marker
)
6824 unchain_marker (&mblk
->markers
[i
].m
.u_marker
);
6825 else if (mblk
->markers
[i
].m
.u_any
.type
== Lisp_Misc_Finalizer
)
6826 unchain_finalizer (&mblk
->markers
[i
].m
.u_finalizer
);
6828 else if (mblk
->markers
[i
].m
.u_any
.type
== Lisp_Misc_User_Ptr
)
6830 struct Lisp_User_Ptr
*uptr
= &mblk
->markers
[i
].m
.u_user_ptr
;
6831 uptr
->finalizer (uptr
->p
);
6834 /* Set the type of the freed object to Lisp_Misc_Free.
6835 We could leave the type alone, since nobody checks it,
6836 but this might catch bugs faster. */
6837 mblk
->markers
[i
].m
.u_marker
.type
= Lisp_Misc_Free
;
6838 mblk
->markers
[i
].m
.u_free
.chain
= marker_free_list
;
6839 marker_free_list
= &mblk
->markers
[i
].m
;
6845 mblk
->markers
[i
].m
.u_any
.gcmarkbit
= 0;
6848 lim
= MARKER_BLOCK_SIZE
;
6849 /* If this block contains only free markers and we have already
6850 seen more than two blocks worth of free markers then deallocate
6852 if (this_free
== MARKER_BLOCK_SIZE
&& num_free
> MARKER_BLOCK_SIZE
)
6854 *mprev
= mblk
->next
;
6855 /* Unhook from the free list. */
6856 marker_free_list
= mblk
->markers
[0].m
.u_free
.chain
;
6861 num_free
+= this_free
;
6862 mprev
= &mblk
->next
;
6866 total_markers
= num_used
;
6867 total_free_markers
= num_free
;
6870 NO_INLINE
/* For better stack traces */
6872 sweep_buffers (void)
6874 register struct buffer
*buffer
, **bprev
= &all_buffers
;
6877 for (buffer
= all_buffers
; buffer
; buffer
= *bprev
)
6878 if (!VECTOR_MARKED_P (buffer
))
6880 *bprev
= buffer
->next
;
6885 VECTOR_UNMARK (buffer
);
6886 /* Do not use buffer_(set|get)_intervals here. */
6887 buffer
->text
->intervals
= balance_intervals (buffer
->text
->intervals
);
6889 bprev
= &buffer
->next
;
6893 /* Sweep: find all structures not marked, and free them. */
6897 /* Remove or mark entries in weak hash tables.
6898 This must be done before any object is unmarked. */
6899 sweep_weak_hash_tables ();
6902 check_string_bytes (!noninteractive
);
6910 check_string_bytes (!noninteractive
);
6913 DEFUN ("memory-info", Fmemory_info
, Smemory_info
, 0, 0, 0,
6914 doc
: /* Return a list of (TOTAL-RAM FREE-RAM TOTAL-SWAP FREE-SWAP).
6915 All values are in Kbytes. If there is no swap space,
6916 last two values are zero. If the system is not supported
6917 or memory information can't be obtained, return nil. */)
6920 #if defined HAVE_LINUX_SYSINFO
6926 #ifdef LINUX_SYSINFO_UNIT
6927 units
= si
.mem_unit
;
6931 return list4i ((uintmax_t) si
.totalram
* units
/ 1024,
6932 (uintmax_t) si
.freeram
* units
/ 1024,
6933 (uintmax_t) si
.totalswap
* units
/ 1024,
6934 (uintmax_t) si
.freeswap
* units
/ 1024);
6935 #elif defined WINDOWSNT
6936 unsigned long long totalram
, freeram
, totalswap
, freeswap
;
6938 if (w32_memory_info (&totalram
, &freeram
, &totalswap
, &freeswap
) == 0)
6939 return list4i ((uintmax_t) totalram
/ 1024,
6940 (uintmax_t) freeram
/ 1024,
6941 (uintmax_t) totalswap
/ 1024,
6942 (uintmax_t) freeswap
/ 1024);
6946 unsigned long totalram
, freeram
, totalswap
, freeswap
;
6948 if (dos_memory_info (&totalram
, &freeram
, &totalswap
, &freeswap
) == 0)
6949 return list4i ((uintmax_t) totalram
/ 1024,
6950 (uintmax_t) freeram
/ 1024,
6951 (uintmax_t) totalswap
/ 1024,
6952 (uintmax_t) freeswap
/ 1024);
6955 #else /* not HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
6956 /* FIXME: add more systems. */
6958 #endif /* HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
6961 /* Debugging aids. */
6963 DEFUN ("memory-limit", Fmemory_limit
, Smemory_limit
, 0, 0, 0,
6964 doc
: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6965 This may be helpful in debugging Emacs's memory usage.
6966 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6972 /* Avoid warning. sbrk has no relation to memory allocated anyway. */
6975 XSETINT (end
, (intptr_t) (char *) sbrk (0) / 1024);
6981 DEFUN ("memory-use-counts", Fmemory_use_counts
, Smemory_use_counts
, 0, 0, 0,
6982 doc
: /* Return a list of counters that measure how much consing there has been.
6983 Each of these counters increments for a certain kind of object.
6984 The counters wrap around from the largest positive integer to zero.
6985 Garbage collection does not decrease them.
6986 The elements of the value are as follows:
6987 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6988 All are in units of 1 = one object consed
6989 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6991 MISCS include overlays, markers, and some internal types.
6992 Frames, windows, buffers, and subprocesses count as vectors
6993 (but the contents of a buffer's text do not count here). */)
6996 return listn (CONSTYPE_HEAP
, 8,
6997 bounded_number (cons_cells_consed
),
6998 bounded_number (floats_consed
),
6999 bounded_number (vector_cells_consed
),
7000 bounded_number (symbols_consed
),
7001 bounded_number (string_chars_consed
),
7002 bounded_number (misc_objects_consed
),
7003 bounded_number (intervals_consed
),
7004 bounded_number (strings_consed
));
7008 symbol_uses_obj (Lisp_Object symbol
, Lisp_Object obj
)
7010 struct Lisp_Symbol
*sym
= XSYMBOL (symbol
);
7011 Lisp_Object val
= find_symbol_value (symbol
);
7012 return (EQ (val
, obj
)
7013 || EQ (sym
->function
, obj
)
7014 || (!NILP (sym
->function
)
7015 && COMPILEDP (sym
->function
)
7016 && EQ (AREF (sym
->function
, COMPILED_BYTECODE
), obj
))
7019 && EQ (AREF (val
, COMPILED_BYTECODE
), obj
)));
7022 /* Find at most FIND_MAX symbols which have OBJ as their value or
7023 function. This is used in gdbinit's `xwhichsymbols' command. */
7026 which_symbols (Lisp_Object obj
, EMACS_INT find_max
)
7028 struct symbol_block
*sblk
;
7029 ptrdiff_t gc_count
= inhibit_garbage_collection ();
7030 Lisp_Object found
= Qnil
;
7034 for (int i
= 0; i
< ARRAYELTS (lispsym
); i
++)
7036 Lisp_Object sym
= builtin_lisp_symbol (i
);
7037 if (symbol_uses_obj (sym
, obj
))
7039 found
= Fcons (sym
, found
);
7040 if (--find_max
== 0)
7045 for (sblk
= symbol_block
; sblk
; sblk
= sblk
->next
)
7047 union aligned_Lisp_Symbol
*aligned_sym
= sblk
->symbols
;
7050 for (bn
= 0; bn
< SYMBOL_BLOCK_SIZE
; bn
++, aligned_sym
++)
7052 if (sblk
== symbol_block
&& bn
>= symbol_block_index
)
7055 Lisp_Object sym
= make_lisp_symbol (&aligned_sym
->s
);
7056 if (symbol_uses_obj (sym
, obj
))
7058 found
= Fcons (sym
, found
);
7059 if (--find_max
== 0)
7067 unbind_to (gc_count
, Qnil
);
7071 #ifdef SUSPICIOUS_OBJECT_CHECKING
7074 find_suspicious_object_in_range (void *begin
, void *end
)
7076 char *begin_a
= begin
;
7080 for (i
= 0; i
< ARRAYELTS (suspicious_objects
); ++i
)
7082 char *suspicious_object
= suspicious_objects
[i
];
7083 if (begin_a
<= suspicious_object
&& suspicious_object
< end_a
)
7084 return suspicious_object
;
7091 note_suspicious_free (void* ptr
)
7093 struct suspicious_free_record
* rec
;
7095 rec
= &suspicious_free_history
[suspicious_free_history_index
++];
7096 if (suspicious_free_history_index
==
7097 ARRAYELTS (suspicious_free_history
))
7099 suspicious_free_history_index
= 0;
7102 memset (rec
, 0, sizeof (*rec
));
7103 rec
->suspicious_object
= ptr
;
7104 backtrace (&rec
->backtrace
[0], ARRAYELTS (rec
->backtrace
));
7108 detect_suspicious_free (void* ptr
)
7112 eassert (ptr
!= NULL
);
7114 for (i
= 0; i
< ARRAYELTS (suspicious_objects
); ++i
)
7115 if (suspicious_objects
[i
] == ptr
)
7117 note_suspicious_free (ptr
);
7118 suspicious_objects
[i
] = NULL
;
7122 #endif /* SUSPICIOUS_OBJECT_CHECKING */
7124 DEFUN ("suspicious-object", Fsuspicious_object
, Ssuspicious_object
, 1, 1, 0,
7125 doc
: /* Return OBJ, maybe marking it for extra scrutiny.
7126 If Emacs is compiled with suspicious object checking, capture
7127 a stack trace when OBJ is freed in order to help track down
7128 garbage collection bugs. Otherwise, do nothing and return OBJ. */)
7131 #ifdef SUSPICIOUS_OBJECT_CHECKING
7132 /* Right now, we care only about vectors. */
7133 if (VECTORLIKEP (obj
))
7135 suspicious_objects
[suspicious_object_index
++] = XVECTOR (obj
);
7136 if (suspicious_object_index
== ARRAYELTS (suspicious_objects
))
7137 suspicious_object_index
= 0;
7143 #ifdef ENABLE_CHECKING
7145 bool suppress_checking
;
7148 die (const char *msg
, const char *file
, int line
)
7150 fprintf (stderr
, "\r\n%s:%d: Emacs fatal error: assertion failed: %s\r\n",
7152 terminate_due_to_signal (SIGABRT
, INT_MAX
);
7155 #endif /* ENABLE_CHECKING */
7157 #if defined (ENABLE_CHECKING) && USE_STACK_LISP_OBJECTS
7159 /* Debugging check whether STR is ASCII-only. */
7162 verify_ascii (const char *str
)
7164 const unsigned char *ptr
= (unsigned char *) str
, *end
= ptr
+ strlen (str
);
7167 int c
= STRING_CHAR_ADVANCE (ptr
);
7168 if (!ASCII_CHAR_P (c
))
7174 /* Stress alloca with inconveniently sized requests and check
7175 whether all allocated areas may be used for Lisp_Object. */
7177 NO_INLINE
static void
7178 verify_alloca (void)
7181 enum { ALLOCA_CHECK_MAX
= 256 };
7182 /* Start from size of the smallest Lisp object. */
7183 for (i
= sizeof (struct Lisp_Cons
); i
<= ALLOCA_CHECK_MAX
; i
++)
7185 void *ptr
= alloca (i
);
7186 make_lisp_ptr (ptr
, Lisp_Cons
);
7190 #else /* not ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7192 #define verify_alloca() ((void) 0)
7194 #endif /* ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7196 /* Initialization. */
7199 init_alloc_once (void)
7201 /* Even though Qt's contents are not set up, its address is known. */
7205 pure_size
= PURESIZE
;
7208 init_finalizer_list (&finalizers
);
7209 init_finalizer_list (&doomed_finalizers
);
7212 Vdead
= make_pure_string ("DEAD", 4, 4, 0);
7214 #ifdef DOUG_LEA_MALLOC
7215 mallopt (M_TRIM_THRESHOLD
, 128 * 1024); /* Trim threshold. */
7216 mallopt (M_MMAP_THRESHOLD
, 64 * 1024); /* Mmap threshold. */
7217 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
); /* Max. number of mmap'ed areas. */
7222 refill_memory_reserve ();
7223 gc_cons_threshold
= GC_DEFAULT_THRESHOLD
;
7229 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
7230 setjmp_tested_p
= longjmps_done
= 0;
7232 Vgc_elapsed
= make_float (0.0);
7236 valgrind_p
= RUNNING_ON_VALGRIND
!= 0;
7241 syms_of_alloc (void)
7243 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold
,
7244 doc
: /* Number of bytes of consing between garbage collections.
7245 Garbage collection can happen automatically once this many bytes have been
7246 allocated since the last garbage collection. All data types count.
7248 Garbage collection happens automatically only when `eval' is called.
7250 By binding this temporarily to a large number, you can effectively
7251 prevent garbage collection during a part of the program.
7252 See also `gc-cons-percentage'. */);
7254 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage
,
7255 doc
: /* Portion of the heap used for allocation.
7256 Garbage collection can happen automatically once this portion of the heap
7257 has been allocated since the last garbage collection.
7258 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
7259 Vgc_cons_percentage
= make_float (0.1);
7261 DEFVAR_INT ("pure-bytes-used", pure_bytes_used
,
7262 doc
: /* Number of bytes of shareable Lisp data allocated so far. */);
7264 DEFVAR_INT ("cons-cells-consed", cons_cells_consed
,
7265 doc
: /* Number of cons cells that have been consed so far. */);
7267 DEFVAR_INT ("floats-consed", floats_consed
,
7268 doc
: /* Number of floats that have been consed so far. */);
7270 DEFVAR_INT ("vector-cells-consed", vector_cells_consed
,
7271 doc
: /* Number of vector cells that have been consed so far. */);
7273 DEFVAR_INT ("symbols-consed", symbols_consed
,
7274 doc
: /* Number of symbols that have been consed so far. */);
7275 symbols_consed
+= ARRAYELTS (lispsym
);
7277 DEFVAR_INT ("string-chars-consed", string_chars_consed
,
7278 doc
: /* Number of string characters that have been consed so far. */);
7280 DEFVAR_INT ("misc-objects-consed", misc_objects_consed
,
7281 doc
: /* Number of miscellaneous objects that have been consed so far.
7282 These include markers and overlays, plus certain objects not visible
7285 DEFVAR_INT ("intervals-consed", intervals_consed
,
7286 doc
: /* Number of intervals that have been consed so far. */);
7288 DEFVAR_INT ("strings-consed", strings_consed
,
7289 doc
: /* Number of strings that have been consed so far. */);
7291 DEFVAR_LISP ("purify-flag", Vpurify_flag
,
7292 doc
: /* Non-nil means loading Lisp code in order to dump an executable.
7293 This means that certain objects should be allocated in shared (pure) space.
7294 It can also be set to a hash-table, in which case this table is used to
7295 do hash-consing of the objects allocated to pure space. */);
7297 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages
,
7298 doc
: /* Non-nil means display messages at start and end of garbage collection. */);
7299 garbage_collection_messages
= 0;
7301 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook
,
7302 doc
: /* Hook run after garbage collection has finished. */);
7303 Vpost_gc_hook
= Qnil
;
7304 DEFSYM (Qpost_gc_hook
, "post-gc-hook");
7306 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data
,
7307 doc
: /* Precomputed `signal' argument for memory-full error. */);
7308 /* We build this in advance because if we wait until we need it, we might
7309 not be able to allocate the memory to hold it. */
7311 = listn (CONSTYPE_PURE
, 2, Qerror
,
7312 build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
7314 DEFVAR_LISP ("memory-full", Vmemory_full
,
7315 doc
: /* Non-nil means Emacs cannot get much more Lisp memory. */);
7316 Vmemory_full
= Qnil
;
7318 DEFSYM (Qconses
, "conses");
7319 DEFSYM (Qsymbols
, "symbols");
7320 DEFSYM (Qmiscs
, "miscs");
7321 DEFSYM (Qstrings
, "strings");
7322 DEFSYM (Qvectors
, "vectors");
7323 DEFSYM (Qfloats
, "floats");
7324 DEFSYM (Qintervals
, "intervals");
7325 DEFSYM (Qbuffers
, "buffers");
7326 DEFSYM (Qstring_bytes
, "string-bytes");
7327 DEFSYM (Qvector_slots
, "vector-slots");
7328 DEFSYM (Qheap
, "heap");
7329 DEFSYM (Qautomatic_gc
, "Automatic GC");
7331 DEFSYM (Qgc_cons_threshold
, "gc-cons-threshold");
7332 DEFSYM (Qchar_table_extra_slots
, "char-table-extra-slots");
7334 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed
,
7335 doc
: /* Accumulated time elapsed in garbage collections.
7336 The time is in seconds as a floating point value. */);
7337 DEFVAR_INT ("gcs-done", gcs_done
,
7338 doc
: /* Accumulated number of garbage collections done. */);
7343 defsubr (&Sbool_vector
);
7344 defsubr (&Smake_byte_code
);
7345 defsubr (&Smake_list
);
7346 defsubr (&Smake_vector
);
7347 defsubr (&Smake_string
);
7348 defsubr (&Smake_bool_vector
);
7349 defsubr (&Smake_symbol
);
7350 defsubr (&Smake_marker
);
7351 defsubr (&Smake_finalizer
);
7352 defsubr (&Spurecopy
);
7353 defsubr (&Sgarbage_collect
);
7354 defsubr (&Smemory_limit
);
7355 defsubr (&Smemory_info
);
7356 defsubr (&Smemory_use_counts
);
7357 defsubr (&Ssuspicious_object
);
7360 /* When compiled with GCC, GDB might say "No enum type named
7361 pvec_type" if we don't have at least one symbol with that type, and
7362 then xbacktrace could fail. Similarly for the other enums and
7363 their values. Some non-GCC compilers don't like these constructs. */
7367 enum CHARTAB_SIZE_BITS CHARTAB_SIZE_BITS
;
7368 enum char_table_specials char_table_specials
;
7369 enum char_bits char_bits
;
7370 enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE
;
7371 enum DEFAULT_HASH_SIZE DEFAULT_HASH_SIZE
;
7372 enum Lisp_Bits Lisp_Bits
;
7373 enum Lisp_Compiled Lisp_Compiled
;
7374 enum maxargs maxargs
;
7375 enum MAX_ALLOCA MAX_ALLOCA
;
7376 enum More_Lisp_Bits More_Lisp_Bits
;
7377 enum pvec_type pvec_type
;
7378 } const EXTERNALLY_VISIBLE gdb_make_enums_visible
= {0};
7379 #endif /* __GNUC__ */