1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2017 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 (at
11 your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
26 #include <limits.h> /* For CHAR_BIT. */
27 #include <signal.h> /* For SIGABRT, SIGDANGER. */
34 #include "dispextern.h"
35 #include "intervals.h"
36 #include "ptr-bounds.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 */
51 #include <flexmember.h>
53 #include <execinfo.h> /* For backtrace. */
55 #ifdef HAVE_LINUX_SYSINFO
56 #include <sys/sysinfo.h>
60 #include "dosfns.h" /* For dos_memory_info. */
67 #if (defined ENABLE_CHECKING \
68 && defined HAVE_VALGRIND_VALGRIND_H \
69 && !defined USE_VALGRIND)
70 # define USE_VALGRIND 1
74 #include <valgrind/valgrind.h>
75 #include <valgrind/memcheck.h>
76 static bool valgrind_p
;
79 /* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects.
80 We turn that on by default when ENABLE_CHECKING is defined;
81 define GC_CHECK_MARKED_OBJECTS to zero to disable. */
83 #if defined ENABLE_CHECKING && !defined GC_CHECK_MARKED_OBJECTS
84 # define GC_CHECK_MARKED_OBJECTS 1
87 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
88 memory. Can do this only if using gmalloc.c and if not checking
91 #if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
92 || defined HYBRID_MALLOC || GC_CHECK_MARKED_OBJECTS)
93 #undef GC_MALLOC_CHECK
100 # include "gtkutil.h"
104 #include "w32heap.h" /* for sbrk */
108 /* The address where the heap starts. */
119 #ifdef DOUG_LEA_MALLOC
121 /* Specify maximum number of areas to mmap. It would be nice to use a
122 value that explicitly means "no limit". */
124 #define MMAP_MAX_AREAS 100000000
126 /* A pointer to the memory allocated that copies that static data
127 inside glibc's malloc. */
128 static void *malloc_state_ptr
;
130 /* Restore the dumped malloc state. Because malloc can be invoked
131 even before main (e.g. by the dynamic linker), the dumped malloc
132 state must be restored as early as possible using this special hook. */
134 malloc_initialize_hook (void)
136 static bool malloc_using_checking
;
143 malloc_using_checking
= getenv ("MALLOC_CHECK_") != NULL
;
147 if (!malloc_using_checking
)
149 /* Work around a bug in glibc's malloc. MALLOC_CHECK_ must be
150 ignored if the heap to be restored was constructed without
151 malloc checking. Can't use unsetenv, since that calls malloc. */
155 if (strncmp (*p
, "MALLOC_CHECK_=", 14) == 0)
165 if (malloc_set_state (malloc_state_ptr
) != 0)
167 # ifndef XMALLOC_OVERRUN_CHECK
168 alloc_unexec_post ();
173 /* Declare the malloc initialization hook, which runs before 'main' starts.
174 EXTERNALLY_VISIBLE works around Bug#22522. */
175 # ifndef __MALLOC_HOOK_VOLATILE
176 # define __MALLOC_HOOK_VOLATILE
178 voidfuncptr __MALLOC_HOOK_VOLATILE __malloc_initialize_hook EXTERNALLY_VISIBLE
179 = malloc_initialize_hook
;
183 #if defined DOUG_LEA_MALLOC || !defined CANNOT_DUMP
185 /* Allocator-related actions to do just before and after unexec. */
188 alloc_unexec_pre (void)
190 # ifdef DOUG_LEA_MALLOC
191 malloc_state_ptr
= malloc_get_state ();
192 if (!malloc_state_ptr
)
193 fatal ("malloc_get_state: %s", strerror (errno
));
195 # ifdef HYBRID_MALLOC
196 bss_sbrk_did_unexec
= true;
201 alloc_unexec_post (void)
203 # ifdef DOUG_LEA_MALLOC
204 free (malloc_state_ptr
);
206 # ifdef HYBRID_MALLOC
207 bss_sbrk_did_unexec
= false;
212 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
213 to a struct Lisp_String. */
215 #define MARK_STRING(S) ((S)->u.s.size |= ARRAY_MARK_FLAG)
216 #define UNMARK_STRING(S) ((S)->u.s.size &= ~ARRAY_MARK_FLAG)
217 #define STRING_MARKED_P(S) (((S)->u.s.size & ARRAY_MARK_FLAG) != 0)
219 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
220 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
221 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
223 /* Default value of gc_cons_threshold (see below). */
225 #define GC_DEFAULT_THRESHOLD (100000 * word_size)
227 /* Global variables. */
228 struct emacs_globals globals
;
230 /* Number of bytes of consing done since the last gc. */
232 EMACS_INT consing_since_gc
;
234 /* Similar minimum, computed from Vgc_cons_percentage. */
236 EMACS_INT gc_relative_threshold
;
238 /* Minimum number of bytes of consing since GC before next GC,
239 when memory is full. */
241 EMACS_INT memory_full_cons_threshold
;
243 /* True during GC. */
247 /* Number of live and free conses etc. */
249 static EMACS_INT total_conses
, total_markers
, total_symbols
, total_buffers
;
250 static EMACS_INT total_free_conses
, total_free_markers
, total_free_symbols
;
251 static EMACS_INT total_free_floats
, total_floats
;
253 /* Points to memory space allocated as "spare", to be freed if we run
254 out of memory. We keep one large block, four cons-blocks, and
255 two string blocks. */
257 static char *spare_memory
[7];
259 /* Amount of spare memory to keep in large reserve block, or to see
260 whether this much is available when malloc fails on a larger request. */
262 #define SPARE_MEMORY (1 << 14)
264 /* Initialize it to a nonzero value to force it into data space
265 (rather than bss space). That way unexec will remap it into text
266 space (pure), on some systems. We have not implemented the
267 remapping on more recent systems because this is less important
268 nowadays than in the days of small memories and timesharing. */
270 EMACS_INT pure
[(PURESIZE
+ sizeof (EMACS_INT
) - 1) / sizeof (EMACS_INT
)] = {1,};
271 #define PUREBEG (char *) pure
273 /* Pointer to the pure area, and its size. */
275 static char *purebeg
;
276 static ptrdiff_t pure_size
;
278 /* Number of bytes of pure storage used before pure storage overflowed.
279 If this is non-zero, this implies that an overflow occurred. */
281 static ptrdiff_t pure_bytes_used_before_overflow
;
283 /* Index in pure at which next pure Lisp object will be allocated.. */
285 static ptrdiff_t pure_bytes_used_lisp
;
287 /* Number of bytes allocated for non-Lisp objects in pure storage. */
289 static ptrdiff_t pure_bytes_used_non_lisp
;
291 /* If nonzero, this is a warning delivered by malloc and not yet
294 const char *pending_malloc_warning
;
296 #if 0 /* Normally, pointer sanity only on request... */
297 #ifdef ENABLE_CHECKING
298 #define SUSPICIOUS_OBJECT_CHECKING 1
302 /* ... but unconditionally use SUSPICIOUS_OBJECT_CHECKING while the GC
303 bug is unresolved. */
304 #define SUSPICIOUS_OBJECT_CHECKING 1
306 #ifdef SUSPICIOUS_OBJECT_CHECKING
307 struct suspicious_free_record
309 void *suspicious_object
;
310 void *backtrace
[128];
312 static void *suspicious_objects
[32];
313 static int suspicious_object_index
;
314 struct suspicious_free_record suspicious_free_history
[64] EXTERNALLY_VISIBLE
;
315 static int suspicious_free_history_index
;
316 /* Find the first currently-monitored suspicious pointer in range
317 [begin,end) or NULL if no such pointer exists. */
318 static void *find_suspicious_object_in_range (void *begin
, void *end
);
319 static void detect_suspicious_free (void *ptr
);
321 # define find_suspicious_object_in_range(begin, end) NULL
322 # define detect_suspicious_free(ptr) (void)
325 /* Maximum amount of C stack to save when a GC happens. */
327 #ifndef MAX_SAVE_STACK
328 #define MAX_SAVE_STACK 16000
331 /* Buffer in which we save a copy of the C stack at each GC. */
333 #if MAX_SAVE_STACK > 0
334 static char *stack_copy
;
335 static ptrdiff_t stack_copy_size
;
337 /* Copy to DEST a block of memory from SRC of size SIZE bytes,
338 avoiding any address sanitization. */
340 static void * ATTRIBUTE_NO_SANITIZE_ADDRESS
341 no_sanitize_memcpy (void *dest
, void const *src
, size_t size
)
343 if (! ADDRESS_SANITIZER
)
344 return memcpy (dest
, src
, size
);
350 for (i
= 0; i
< size
; i
++)
356 #endif /* MAX_SAVE_STACK > 0 */
358 static void mark_terminals (void);
359 static void gc_sweep (void);
360 static Lisp_Object
make_pure_vector (ptrdiff_t);
361 static void mark_buffer (struct buffer
*);
363 #if !defined REL_ALLOC || defined SYSTEM_MALLOC || defined HYBRID_MALLOC
364 static void refill_memory_reserve (void);
366 static void compact_small_strings (void);
367 static void free_large_strings (void);
368 extern Lisp_Object
which_symbols (Lisp_Object
, EMACS_INT
) EXTERNALLY_VISIBLE
;
370 /* When scanning the C stack for live Lisp objects, Emacs keeps track of
371 what memory allocated via lisp_malloc and lisp_align_malloc is intended
372 for what purpose. This enumeration specifies the type of memory. */
383 /* Since all non-bool pseudovectors are small enough to be
384 allocated from vector blocks, this memory type denotes
385 large regular vectors and large bool pseudovectors. */
387 /* Special type to denote vector blocks. */
388 MEM_TYPE_VECTOR_BLOCK
,
389 /* Special type to denote reserved memory. */
393 /* A unique object in pure space used to make some Lisp objects
394 on free lists recognizable in O(1). */
396 static Lisp_Object Vdead
;
397 #define DEADP(x) EQ (x, Vdead)
399 #ifdef GC_MALLOC_CHECK
401 enum mem_type allocated_mem_type
;
403 #endif /* GC_MALLOC_CHECK */
405 /* A node in the red-black tree describing allocated memory containing
406 Lisp data. Each such block is recorded with its start and end
407 address when it is allocated, and removed from the tree when it
410 A red-black tree is a balanced binary tree with the following
413 1. Every node is either red or black.
414 2. Every leaf is black.
415 3. If a node is red, then both of its children are black.
416 4. Every simple path from a node to a descendant leaf contains
417 the same number of black nodes.
418 5. The root is always black.
420 When nodes are inserted into the tree, or deleted from the tree,
421 the tree is "fixed" so that these properties are always true.
423 A red-black tree with N internal nodes has height at most 2
424 log(N+1). Searches, insertions and deletions are done in O(log N).
425 Please see a text book about data structures for a detailed
426 description of red-black trees. Any book worth its salt should
431 /* Children of this node. These pointers are never NULL. When there
432 is no child, the value is MEM_NIL, which points to a dummy node. */
433 struct mem_node
*left
, *right
;
435 /* The parent of this node. In the root node, this is NULL. */
436 struct mem_node
*parent
;
438 /* Start and end of allocated region. */
442 enum {MEM_BLACK
, MEM_RED
} color
;
448 /* Root of the tree describing allocated Lisp memory. */
450 static struct mem_node
*mem_root
;
452 /* Lowest and highest known address in the heap. */
454 static void *min_heap_address
, *max_heap_address
;
456 /* Sentinel node of the tree. */
458 static struct mem_node mem_z
;
459 #define MEM_NIL &mem_z
461 static struct mem_node
*mem_insert (void *, void *, enum mem_type
);
462 static void mem_insert_fixup (struct mem_node
*);
463 static void mem_rotate_left (struct mem_node
*);
464 static void mem_rotate_right (struct mem_node
*);
465 static void mem_delete (struct mem_node
*);
466 static void mem_delete_fixup (struct mem_node
*);
467 static struct mem_node
*mem_find (void *);
473 /* Addresses of staticpro'd variables. Initialize it to a nonzero
474 value; otherwise some compilers put it into BSS. */
476 enum { NSTATICS
= 2048 };
477 static Lisp_Object
*staticvec
[NSTATICS
] = {&Vpurify_flag
};
479 /* Index of next unused slot in staticvec. */
481 static int staticidx
;
483 static void *pure_alloc (size_t, int);
485 /* True if N is a power of 2. N should be positive. */
487 #define POWER_OF_2(n) (((n) & ((n) - 1)) == 0)
489 /* Return X rounded to the next multiple of Y. Y should be positive,
490 and Y - 1 + X should not overflow. Arguments should not have side
491 effects, as they are evaluated more than once. Tune for Y being a
494 #define ROUNDUP(x, y) (POWER_OF_2 (y) \
495 ? ((y) - 1 + (x)) & ~ ((y) - 1) \
496 : ((y) - 1 + (x)) - ((y) - 1 + (x)) % (y))
498 /* Return PTR rounded up to the next multiple of ALIGNMENT. */
501 pointer_align (void *ptr
, int alignment
)
503 return (void *) ROUNDUP ((uintptr_t) ptr
, alignment
);
506 /* Extract the pointer hidden within O. Define this as a function, as
507 functions are cleaner and can be used in debuggers. Also, define
508 it as a macro if being compiled with GCC without optimization, for
509 performance in that case. macro_XPNTR is private to this section
512 #define macro_XPNTR(o) \
515 ? ((char *) lispsym \
516 - ((EMACS_UINT) Lisp_Symbol << (USE_LSB_TAG ? 0 : VALBITS)) \
518 : (char *) XLP (o) - (XLI (o) & ~VALMASK)))
520 static ATTRIBUTE_UNUSED
void *
521 XPNTR (Lisp_Object a
)
523 return macro_XPNTR (a
);
526 #if DEFINE_KEY_OPS_AS_MACROS
527 # define XPNTR(a) macro_XPNTR (a)
531 XFLOAT_INIT (Lisp_Object f
, double n
)
533 XFLOAT (f
)->u
.data
= n
;
536 #ifdef DOUG_LEA_MALLOC
538 pointers_fit_in_lispobj_p (void)
540 return (UINTPTR_MAX
<= VAL_MAX
) || USE_LSB_TAG
;
544 mmap_lisp_allowed_p (void)
546 /* If we can't store all memory addresses in our lisp objects, it's
547 risky to let the heap use mmap and give us addresses from all
548 over our address space. We also can't use mmap for lisp objects
549 if we might dump: unexec doesn't preserve the contents of mmapped
551 return pointers_fit_in_lispobj_p () && !might_dump
;
555 /* Head of a circularly-linked list of extant finalizers. */
556 static struct Lisp_Finalizer finalizers
;
558 /* Head of a circularly-linked list of finalizers that must be invoked
559 because we deemed them unreachable. This list must be global, and
560 not a local inside garbage_collect_1, in case we GC again while
561 running finalizers. */
562 static struct Lisp_Finalizer doomed_finalizers
;
565 /************************************************************************
567 ************************************************************************/
569 #if defined SIGDANGER || (!defined SYSTEM_MALLOC && !defined HYBRID_MALLOC)
571 /* Function malloc calls this if it finds we are near exhausting storage. */
574 malloc_warning (const char *str
)
576 pending_malloc_warning
= str
;
581 /* Display an already-pending malloc warning. */
584 display_malloc_warning (void)
586 call3 (intern ("display-warning"),
588 build_string (pending_malloc_warning
),
589 intern ("emergency"));
590 pending_malloc_warning
= 0;
593 /* Called if we can't allocate relocatable space for a buffer. */
596 buffer_memory_full (ptrdiff_t nbytes
)
598 /* If buffers use the relocating allocator, no need to free
599 spare_memory, because we may have plenty of malloc space left
600 that we could get, and if we don't, the malloc that fails will
601 itself cause spare_memory to be freed. If buffers don't use the
602 relocating allocator, treat this like any other failing
606 memory_full (nbytes
);
608 /* This used to call error, but if we've run out of memory, we could
609 get infinite recursion trying to build the string. */
610 xsignal (Qnil
, Vmemory_signal_data
);
614 /* A common multiple of the positive integers A and B. Ideally this
615 would be the least common multiple, but there's no way to do that
616 as a constant expression in C, so do the best that we can easily do. */
617 #define COMMON_MULTIPLE(a, b) \
618 ((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
620 #ifndef XMALLOC_OVERRUN_CHECK
621 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
624 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
627 The header consists of XMALLOC_OVERRUN_CHECK_SIZE fixed bytes
628 followed by XMALLOC_OVERRUN_SIZE_SIZE bytes containing the original
629 block size in little-endian order. The trailer consists of
630 XMALLOC_OVERRUN_CHECK_SIZE fixed bytes.
632 The header is used to detect whether this block has been allocated
633 through these functions, as some low-level libc functions may
634 bypass the malloc hooks. */
636 #define XMALLOC_OVERRUN_CHECK_SIZE 16
637 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
638 (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)
640 #define XMALLOC_BASE_ALIGNMENT alignof (max_align_t)
642 #define XMALLOC_HEADER_ALIGNMENT \
643 COMMON_MULTIPLE (GCALIGNMENT, XMALLOC_BASE_ALIGNMENT)
645 /* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
646 hold a size_t value and (2) the header size is a multiple of the
647 alignment that Emacs needs for C types and for USE_LSB_TAG. */
648 #define XMALLOC_OVERRUN_SIZE_SIZE \
649 (((XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t) \
650 + XMALLOC_HEADER_ALIGNMENT - 1) \
651 / XMALLOC_HEADER_ALIGNMENT * XMALLOC_HEADER_ALIGNMENT) \
652 - XMALLOC_OVERRUN_CHECK_SIZE)
654 static char const xmalloc_overrun_check_header
[XMALLOC_OVERRUN_CHECK_SIZE
] =
655 { '\x9a', '\x9b', '\xae', '\xaf',
656 '\xbf', '\xbe', '\xce', '\xcf',
657 '\xea', '\xeb', '\xec', '\xed',
658 '\xdf', '\xde', '\x9c', '\x9d' };
660 static char const xmalloc_overrun_check_trailer
[XMALLOC_OVERRUN_CHECK_SIZE
] =
661 { '\xaa', '\xab', '\xac', '\xad',
662 '\xba', '\xbb', '\xbc', '\xbd',
663 '\xca', '\xcb', '\xcc', '\xcd',
664 '\xda', '\xdb', '\xdc', '\xdd' };
666 /* Insert and extract the block size in the header. */
669 xmalloc_put_size (unsigned char *ptr
, size_t size
)
672 for (i
= 0; i
< XMALLOC_OVERRUN_SIZE_SIZE
; i
++)
674 *--ptr
= size
& ((1 << CHAR_BIT
) - 1);
680 xmalloc_get_size (unsigned char *ptr
)
684 ptr
-= XMALLOC_OVERRUN_SIZE_SIZE
;
685 for (i
= 0; i
< XMALLOC_OVERRUN_SIZE_SIZE
; i
++)
694 /* Like malloc, but wraps allocated block with header and trailer. */
697 overrun_check_malloc (size_t size
)
699 register unsigned char *val
;
700 if (SIZE_MAX
- XMALLOC_OVERRUN_CHECK_OVERHEAD
< size
)
703 val
= malloc (size
+ XMALLOC_OVERRUN_CHECK_OVERHEAD
);
706 memcpy (val
, xmalloc_overrun_check_header
, XMALLOC_OVERRUN_CHECK_SIZE
);
707 val
+= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
708 xmalloc_put_size (val
, size
);
709 memcpy (val
+ size
, xmalloc_overrun_check_trailer
,
710 XMALLOC_OVERRUN_CHECK_SIZE
);
716 /* Like realloc, but checks old block for overrun, and wraps new block
717 with header and trailer. */
720 overrun_check_realloc (void *block
, size_t size
)
722 register unsigned char *val
= (unsigned char *) block
;
723 if (SIZE_MAX
- XMALLOC_OVERRUN_CHECK_OVERHEAD
< size
)
727 && memcmp (xmalloc_overrun_check_header
,
728 val
- XMALLOC_OVERRUN_CHECK_SIZE
- XMALLOC_OVERRUN_SIZE_SIZE
,
729 XMALLOC_OVERRUN_CHECK_SIZE
) == 0)
731 size_t osize
= xmalloc_get_size (val
);
732 if (memcmp (xmalloc_overrun_check_trailer
, val
+ osize
,
733 XMALLOC_OVERRUN_CHECK_SIZE
))
735 memset (val
+ osize
, 0, XMALLOC_OVERRUN_CHECK_SIZE
);
736 val
-= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
737 memset (val
, 0, XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
);
740 val
= realloc (val
, size
+ XMALLOC_OVERRUN_CHECK_OVERHEAD
);
744 memcpy (val
, xmalloc_overrun_check_header
, XMALLOC_OVERRUN_CHECK_SIZE
);
745 val
+= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
746 xmalloc_put_size (val
, size
);
747 memcpy (val
+ size
, xmalloc_overrun_check_trailer
,
748 XMALLOC_OVERRUN_CHECK_SIZE
);
753 /* Like free, but checks block for overrun. */
756 overrun_check_free (void *block
)
758 unsigned char *val
= (unsigned char *) block
;
761 && memcmp (xmalloc_overrun_check_header
,
762 val
- XMALLOC_OVERRUN_CHECK_SIZE
- XMALLOC_OVERRUN_SIZE_SIZE
,
763 XMALLOC_OVERRUN_CHECK_SIZE
) == 0)
765 size_t osize
= xmalloc_get_size (val
);
766 if (memcmp (xmalloc_overrun_check_trailer
, val
+ osize
,
767 XMALLOC_OVERRUN_CHECK_SIZE
))
769 #ifdef XMALLOC_CLEAR_FREE_MEMORY
770 val
-= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
771 memset (val
, 0xff, osize
+ XMALLOC_OVERRUN_CHECK_OVERHEAD
);
773 memset (val
+ osize
, 0, XMALLOC_OVERRUN_CHECK_SIZE
);
774 val
-= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
775 memset (val
, 0, XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
);
785 #define malloc overrun_check_malloc
786 #define realloc overrun_check_realloc
787 #define free overrun_check_free
790 /* If compiled with XMALLOC_BLOCK_INPUT_CHECK, define a symbol
791 BLOCK_INPUT_IN_MEMORY_ALLOCATORS that is visible to the debugger.
792 If that variable is set, block input while in one of Emacs's memory
793 allocation functions. There should be no need for this debugging
794 option, since signal handlers do not allocate memory, but Emacs
795 formerly allocated memory in signal handlers and this compile-time
796 option remains as a way to help debug the issue should it rear its
798 #ifdef XMALLOC_BLOCK_INPUT_CHECK
799 bool block_input_in_memory_allocators EXTERNALLY_VISIBLE
;
801 malloc_block_input (void)
803 if (block_input_in_memory_allocators
)
807 malloc_unblock_input (void)
809 if (block_input_in_memory_allocators
)
812 # define MALLOC_BLOCK_INPUT malloc_block_input ()
813 # define MALLOC_UNBLOCK_INPUT malloc_unblock_input ()
815 # define MALLOC_BLOCK_INPUT ((void) 0)
816 # define MALLOC_UNBLOCK_INPUT ((void) 0)
819 #define MALLOC_PROBE(size) \
821 if (profiler_memory_running) \
822 malloc_probe (size); \
825 static void *lmalloc (size_t) ATTRIBUTE_MALLOC_SIZE ((1));
826 static void *lrealloc (void *, size_t);
828 /* Like malloc but check for no memory and block interrupt input. */
831 xmalloc (size_t size
)
836 val
= lmalloc (size
);
837 MALLOC_UNBLOCK_INPUT
;
845 /* Like the above, but zeroes out the memory just allocated. */
848 xzalloc (size_t size
)
853 val
= lmalloc (size
);
854 MALLOC_UNBLOCK_INPUT
;
858 memset (val
, 0, size
);
863 /* Like realloc but check for no memory and block interrupt input.. */
866 xrealloc (void *block
, size_t size
)
871 /* We must call malloc explicitly when BLOCK is 0, since some
872 reallocs don't do this. */
874 val
= lmalloc (size
);
876 val
= lrealloc (block
, size
);
877 MALLOC_UNBLOCK_INPUT
;
886 /* Like free but block interrupt input. */
895 MALLOC_UNBLOCK_INPUT
;
896 /* We don't call refill_memory_reserve here
897 because in practice the call in r_alloc_free seems to suffice. */
901 /* Other parts of Emacs pass large int values to allocator functions
902 expecting ptrdiff_t. This is portable in practice, but check it to
904 verify (INT_MAX
<= PTRDIFF_MAX
);
907 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
908 Signal an error on memory exhaustion, and block interrupt input. */
911 xnmalloc (ptrdiff_t nitems
, ptrdiff_t item_size
)
913 eassert (0 <= nitems
&& 0 < item_size
);
915 if (INT_MULTIPLY_WRAPV (nitems
, item_size
, &nbytes
) || SIZE_MAX
< nbytes
)
916 memory_full (SIZE_MAX
);
917 return xmalloc (nbytes
);
921 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
922 Signal an error on memory exhaustion, and block interrupt input. */
925 xnrealloc (void *pa
, ptrdiff_t nitems
, ptrdiff_t item_size
)
927 eassert (0 <= nitems
&& 0 < item_size
);
929 if (INT_MULTIPLY_WRAPV (nitems
, item_size
, &nbytes
) || SIZE_MAX
< nbytes
)
930 memory_full (SIZE_MAX
);
931 return xrealloc (pa
, nbytes
);
935 /* Grow PA, which points to an array of *NITEMS items, and return the
936 location of the reallocated array, updating *NITEMS to reflect its
937 new size. The new array will contain at least NITEMS_INCR_MIN more
938 items, but will not contain more than NITEMS_MAX items total.
939 ITEM_SIZE is the size of each item, in bytes.
941 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
942 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
945 If PA is null, then allocate a new array instead of reallocating
948 Block interrupt input as needed. If memory exhaustion occurs, set
949 *NITEMS to zero if PA is null, and signal an error (i.e., do not
952 Thus, to grow an array A without saving its old contents, do
953 { xfree (A); A = NULL; A = xpalloc (NULL, &AITEMS, ...); }.
954 The A = NULL avoids a dangling pointer if xpalloc exhausts memory
955 and signals an error, and later this code is reexecuted and
956 attempts to free A. */
959 xpalloc (void *pa
, ptrdiff_t *nitems
, ptrdiff_t nitems_incr_min
,
960 ptrdiff_t nitems_max
, ptrdiff_t item_size
)
962 ptrdiff_t n0
= *nitems
;
963 eassume (0 < item_size
&& 0 < nitems_incr_min
&& 0 <= n0
&& -1 <= nitems_max
);
965 /* The approximate size to use for initial small allocation
966 requests. This is the largest "small" request for the GNU C
968 enum { DEFAULT_MXFAST
= 64 * sizeof (size_t) / 4 };
970 /* If the array is tiny, grow it to about (but no greater than)
971 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%.
972 Adjust the growth according to three constraints: NITEMS_INCR_MIN,
973 NITEMS_MAX, and what the C language can represent safely. */
976 if (INT_ADD_WRAPV (n0
, n0
>> 1, &n
))
978 if (0 <= nitems_max
&& nitems_max
< n
)
981 ptrdiff_t adjusted_nbytes
982 = ((INT_MULTIPLY_WRAPV (n
, item_size
, &nbytes
) || SIZE_MAX
< nbytes
)
983 ? min (PTRDIFF_MAX
, SIZE_MAX
)
984 : nbytes
< DEFAULT_MXFAST
? DEFAULT_MXFAST
: 0);
987 n
= adjusted_nbytes
/ item_size
;
988 nbytes
= adjusted_nbytes
- adjusted_nbytes
% item_size
;
993 if (n
- n0
< nitems_incr_min
994 && (INT_ADD_WRAPV (n0
, nitems_incr_min
, &n
)
995 || (0 <= nitems_max
&& nitems_max
< n
)
996 || INT_MULTIPLY_WRAPV (n
, item_size
, &nbytes
)))
997 memory_full (SIZE_MAX
);
998 pa
= xrealloc (pa
, nbytes
);
1004 /* Like strdup, but uses xmalloc. */
1007 xstrdup (const char *s
)
1011 size
= strlen (s
) + 1;
1012 return memcpy (xmalloc (size
), s
, size
);
1015 /* Like above, but duplicates Lisp string to C string. */
1018 xlispstrdup (Lisp_Object string
)
1020 ptrdiff_t size
= SBYTES (string
) + 1;
1021 return memcpy (xmalloc (size
), SSDATA (string
), size
);
1024 /* Assign to *PTR a copy of STRING, freeing any storage *PTR formerly
1025 pointed to. If STRING is null, assign it without copying anything.
1026 Allocate before freeing, to avoid a dangling pointer if allocation
1030 dupstring (char **ptr
, char const *string
)
1033 *ptr
= string
? xstrdup (string
) : 0;
1038 /* Like putenv, but (1) use the equivalent of xmalloc and (2) the
1039 argument is a const pointer. */
1042 xputenv (char const *string
)
1044 if (putenv ((char *) string
) != 0)
1048 /* Return a newly allocated memory block of SIZE bytes, remembering
1049 to free it when unwinding. */
1051 record_xmalloc (size_t size
)
1053 void *p
= xmalloc (size
);
1054 record_unwind_protect_ptr (xfree
, p
);
1059 /* Like malloc but used for allocating Lisp data. NBYTES is the
1060 number of bytes to allocate, TYPE describes the intended use of the
1061 allocated memory block (for strings, for conses, ...). */
1064 void *lisp_malloc_loser EXTERNALLY_VISIBLE
;
1068 lisp_malloc (size_t nbytes
, enum mem_type type
)
1074 #ifdef GC_MALLOC_CHECK
1075 allocated_mem_type
= type
;
1078 val
= lmalloc (nbytes
);
1081 /* If the memory just allocated cannot be addressed thru a Lisp
1082 object's pointer, and it needs to be,
1083 that's equivalent to running out of memory. */
1084 if (val
&& type
!= MEM_TYPE_NON_LISP
)
1087 XSETCONS (tem
, (char *) val
+ nbytes
- 1);
1088 if ((char *) XCONS (tem
) != (char *) val
+ nbytes
- 1)
1090 lisp_malloc_loser
= val
;
1097 #ifndef GC_MALLOC_CHECK
1098 if (val
&& type
!= MEM_TYPE_NON_LISP
)
1099 mem_insert (val
, (char *) val
+ nbytes
, type
);
1102 MALLOC_UNBLOCK_INPUT
;
1104 memory_full (nbytes
);
1105 MALLOC_PROBE (nbytes
);
1109 /* Free BLOCK. This must be called to free memory allocated with a
1110 call to lisp_malloc. */
1113 lisp_free (void *block
)
1117 #ifndef GC_MALLOC_CHECK
1118 mem_delete (mem_find (block
));
1120 MALLOC_UNBLOCK_INPUT
;
1123 /***** Allocation of aligned blocks of memory to store Lisp data. *****/
1125 /* The entry point is lisp_align_malloc which returns blocks of at most
1126 BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
1128 /* Byte alignment of storage blocks. */
1129 #define BLOCK_ALIGN (1 << 10)
1130 verify (POWER_OF_2 (BLOCK_ALIGN
));
1132 /* Use aligned_alloc if it or a simple substitute is available.
1133 Address sanitization breaks aligned allocation, as of gcc 4.8.2 and
1134 clang 3.3 anyway. Aligned allocation is incompatible with
1135 unexmacosx.c, so don't use it on Darwin. */
1137 #if ! ADDRESS_SANITIZER && !defined DARWIN_OS
1138 # if (defined HAVE_ALIGNED_ALLOC \
1139 || (defined HYBRID_MALLOC \
1140 ? defined HAVE_POSIX_MEMALIGN \
1141 : !defined SYSTEM_MALLOC && !defined DOUG_LEA_MALLOC))
1142 # define USE_ALIGNED_ALLOC 1
1143 # elif !defined HYBRID_MALLOC && defined HAVE_POSIX_MEMALIGN
1144 # define USE_ALIGNED_ALLOC 1
1145 # define aligned_alloc my_aligned_alloc /* Avoid collision with lisp.h. */
1147 aligned_alloc (size_t alignment
, size_t size
)
1149 /* POSIX says the alignment must be a power-of-2 multiple of sizeof (void *).
1150 Verify this for all arguments this function is given. */
1151 verify (BLOCK_ALIGN
% sizeof (void *) == 0
1152 && POWER_OF_2 (BLOCK_ALIGN
/ sizeof (void *)));
1153 verify (GCALIGNMENT
% sizeof (void *) == 0
1154 && POWER_OF_2 (GCALIGNMENT
/ sizeof (void *)));
1155 eassert (alignment
== BLOCK_ALIGN
|| alignment
== GCALIGNMENT
);
1158 return posix_memalign (&p
, alignment
, size
) == 0 ? p
: 0;
1163 /* Padding to leave at the end of a malloc'd block. This is to give
1164 malloc a chance to minimize the amount of memory wasted to alignment.
1165 It should be tuned to the particular malloc library used.
1166 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
1167 aligned_alloc on the other hand would ideally prefer a value of 4
1168 because otherwise, there's 1020 bytes wasted between each ablocks.
1169 In Emacs, testing shows that those 1020 can most of the time be
1170 efficiently used by malloc to place other objects, so a value of 0 can
1171 still preferable unless you have a lot of aligned blocks and virtually
1173 #define BLOCK_PADDING 0
1174 #define BLOCK_BYTES \
1175 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
1177 /* Internal data structures and constants. */
1179 #define ABLOCKS_SIZE 16
1181 /* An aligned block of memory. */
1186 char payload
[BLOCK_BYTES
];
1187 struct ablock
*next_free
;
1190 /* ABASE is the aligned base of the ablocks. It is overloaded to
1191 hold a virtual "busy" field that counts twice the number of used
1192 ablock values in the parent ablocks, plus one if the real base of
1193 the parent ablocks is ABASE (if the "busy" field is even, the
1194 word before the first ablock holds a pointer to the real base).
1195 The first ablock has a "busy" ABASE, and the others have an
1196 ordinary pointer ABASE. To tell the difference, the code assumes
1197 that pointers, when cast to uintptr_t, are at least 2 *
1198 ABLOCKS_SIZE + 1. */
1199 struct ablocks
*abase
;
1201 /* The padding of all but the last ablock is unused. The padding of
1202 the last ablock in an ablocks is not allocated. */
1204 char padding
[BLOCK_PADDING
];
1208 /* A bunch of consecutive aligned blocks. */
1211 struct ablock blocks
[ABLOCKS_SIZE
];
1214 /* Size of the block requested from malloc or aligned_alloc. */
1215 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
1217 #define ABLOCK_ABASE(block) \
1218 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
1219 ? (struct ablocks *) (block) \
1222 /* Virtual `busy' field. */
1223 #define ABLOCKS_BUSY(a_base) ((a_base)->blocks[0].abase)
1225 /* Pointer to the (not necessarily aligned) malloc block. */
1226 #ifdef USE_ALIGNED_ALLOC
1227 #define ABLOCKS_BASE(abase) (abase)
1229 #define ABLOCKS_BASE(abase) \
1230 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void **) (abase))[-1])
1233 /* The list of free ablock. */
1234 static struct ablock
*free_ablock
;
1236 /* Allocate an aligned block of nbytes.
1237 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
1238 smaller or equal to BLOCK_BYTES. */
1240 lisp_align_malloc (size_t nbytes
, enum mem_type type
)
1243 struct ablocks
*abase
;
1245 eassert (nbytes
<= BLOCK_BYTES
);
1249 #ifdef GC_MALLOC_CHECK
1250 allocated_mem_type
= type
;
1258 #ifdef DOUG_LEA_MALLOC
1259 if (!mmap_lisp_allowed_p ())
1260 mallopt (M_MMAP_MAX
, 0);
1263 #ifdef USE_ALIGNED_ALLOC
1264 verify (ABLOCKS_BYTES
% BLOCK_ALIGN
== 0);
1265 abase
= base
= aligned_alloc (BLOCK_ALIGN
, ABLOCKS_BYTES
);
1267 base
= malloc (ABLOCKS_BYTES
);
1268 abase
= pointer_align (base
, BLOCK_ALIGN
);
1273 MALLOC_UNBLOCK_INPUT
;
1274 memory_full (ABLOCKS_BYTES
);
1277 aligned
= (base
== abase
);
1279 ((void **) abase
)[-1] = base
;
1281 #ifdef DOUG_LEA_MALLOC
1282 if (!mmap_lisp_allowed_p ())
1283 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
);
1287 /* If the memory just allocated cannot be addressed thru a Lisp
1288 object's pointer, and it needs to be, that's equivalent to
1289 running out of memory. */
1290 if (type
!= MEM_TYPE_NON_LISP
)
1293 char *end
= (char *) base
+ ABLOCKS_BYTES
- 1;
1294 XSETCONS (tem
, end
);
1295 if ((char *) XCONS (tem
) != end
)
1297 lisp_malloc_loser
= base
;
1299 MALLOC_UNBLOCK_INPUT
;
1300 memory_full (SIZE_MAX
);
1305 /* Initialize the blocks and put them on the free list.
1306 If `base' was not properly aligned, we can't use the last block. */
1307 for (i
= 0; i
< (aligned
? ABLOCKS_SIZE
: ABLOCKS_SIZE
- 1); i
++)
1309 abase
->blocks
[i
].abase
= abase
;
1310 abase
->blocks
[i
].x
.next_free
= free_ablock
;
1311 free_ablock
= &abase
->blocks
[i
];
1313 intptr_t ialigned
= aligned
;
1314 ABLOCKS_BUSY (abase
) = (struct ablocks
*) ialigned
;
1316 eassert ((uintptr_t) abase
% BLOCK_ALIGN
== 0);
1317 eassert (ABLOCK_ABASE (&abase
->blocks
[3]) == abase
); /* 3 is arbitrary */
1318 eassert (ABLOCK_ABASE (&abase
->blocks
[0]) == abase
);
1319 eassert (ABLOCKS_BASE (abase
) == base
);
1320 eassert ((intptr_t) ABLOCKS_BUSY (abase
) == aligned
);
1323 abase
= ABLOCK_ABASE (free_ablock
);
1324 ABLOCKS_BUSY (abase
)
1325 = (struct ablocks
*) (2 + (intptr_t) ABLOCKS_BUSY (abase
));
1327 free_ablock
= free_ablock
->x
.next_free
;
1329 #ifndef GC_MALLOC_CHECK
1330 if (type
!= MEM_TYPE_NON_LISP
)
1331 mem_insert (val
, (char *) val
+ nbytes
, type
);
1334 MALLOC_UNBLOCK_INPUT
;
1336 MALLOC_PROBE (nbytes
);
1338 eassert (0 == ((uintptr_t) val
) % BLOCK_ALIGN
);
1343 lisp_align_free (void *block
)
1345 struct ablock
*ablock
= block
;
1346 struct ablocks
*abase
= ABLOCK_ABASE (ablock
);
1349 #ifndef GC_MALLOC_CHECK
1350 mem_delete (mem_find (block
));
1352 /* Put on free list. */
1353 ablock
->x
.next_free
= free_ablock
;
1354 free_ablock
= ablock
;
1355 /* Update busy count. */
1356 intptr_t busy
= (intptr_t) ABLOCKS_BUSY (abase
) - 2;
1357 eassume (0 <= busy
&& busy
<= 2 * ABLOCKS_SIZE
- 1);
1358 ABLOCKS_BUSY (abase
) = (struct ablocks
*) busy
;
1361 { /* All the blocks are free. */
1363 bool aligned
= busy
;
1364 struct ablock
**tem
= &free_ablock
;
1365 struct ablock
*atop
= &abase
->blocks
[aligned
? ABLOCKS_SIZE
: ABLOCKS_SIZE
- 1];
1369 if (*tem
>= (struct ablock
*) abase
&& *tem
< atop
)
1372 *tem
= (*tem
)->x
.next_free
;
1375 tem
= &(*tem
)->x
.next_free
;
1377 eassert ((aligned
& 1) == aligned
);
1378 eassert (i
== (aligned
? ABLOCKS_SIZE
: ABLOCKS_SIZE
- 1));
1379 #ifdef USE_POSIX_MEMALIGN
1380 eassert ((uintptr_t) ABLOCKS_BASE (abase
) % BLOCK_ALIGN
== 0);
1382 free (ABLOCKS_BASE (abase
));
1384 MALLOC_UNBLOCK_INPUT
;
1387 #if !defined __GNUC__ && !defined __alignof__
1388 # define __alignof__(type) alignof (type)
1391 /* True if malloc (N) is known to return a multiple of GCALIGNMENT
1392 whenever N is also a multiple. In practice this is true if
1393 __alignof__ (max_align_t) is a multiple as well, assuming
1394 GCALIGNMENT is 8; other values of GCALIGNMENT have not been looked
1395 into. Use __alignof__ if available, as otherwise
1396 MALLOC_IS_GC_ALIGNED would be false on GCC x86 even though the
1397 alignment is OK there.
1399 This is a macro, not an enum constant, for portability to HP-UX
1400 10.20 cc and AIX 3.2.5 xlc. */
1401 #define MALLOC_IS_GC_ALIGNED \
1402 (GCALIGNMENT == 8 && __alignof__ (max_align_t) % GCALIGNMENT == 0)
1404 /* True if a malloc-returned pointer P is suitably aligned for SIZE,
1405 where Lisp alignment may be needed if SIZE is Lisp-aligned. */
1408 laligned (void *p
, size_t size
)
1410 return (MALLOC_IS_GC_ALIGNED
|| (intptr_t) p
% GCALIGNMENT
== 0
1411 || size
% GCALIGNMENT
!= 0);
1414 /* Like malloc and realloc except that if SIZE is Lisp-aligned, make
1415 sure the result is too, if necessary by reallocating (typically
1416 with larger and larger sizes) until the allocator returns a
1417 Lisp-aligned pointer. Code that needs to allocate C heap memory
1418 for a Lisp object should use one of these functions to obtain a
1419 pointer P; that way, if T is an enum Lisp_Type value and L ==
1420 make_lisp_ptr (P, T), then XPNTR (L) == P and XTYPE (L) == T.
1422 On typical modern platforms these functions' loops do not iterate.
1423 On now-rare (and perhaps nonexistent) platforms, the loops in
1424 theory could repeat forever. If an infinite loop is possible on a
1425 platform, a build would surely loop and the builder can then send
1426 us a bug report. Adding a counter to try to detect any such loop
1427 would complicate the code (and possibly introduce bugs, in code
1428 that's never really exercised) for little benefit. */
1431 lmalloc (size_t size
)
1433 #if USE_ALIGNED_ALLOC
1434 if (! MALLOC_IS_GC_ALIGNED
&& size
% GCALIGNMENT
== 0)
1435 return aligned_alloc (GCALIGNMENT
, size
);
1440 void *p
= malloc (size
);
1441 if (laligned (p
, size
))
1444 size_t bigger
= size
+ GCALIGNMENT
;
1451 lrealloc (void *p
, size_t size
)
1455 p
= realloc (p
, size
);
1456 if (laligned (p
, size
))
1458 size_t bigger
= size
+ GCALIGNMENT
;
1465 /***********************************************************************
1467 ***********************************************************************/
1469 /* Number of intervals allocated in an interval_block structure.
1470 The 1020 is 1024 minus malloc overhead. */
1472 #define INTERVAL_BLOCK_SIZE \
1473 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1475 /* Intervals are allocated in chunks in the form of an interval_block
1478 struct interval_block
1480 /* Place `intervals' first, to preserve alignment. */
1481 struct interval intervals
[INTERVAL_BLOCK_SIZE
];
1482 struct interval_block
*next
;
1485 /* Current interval block. Its `next' pointer points to older
1488 static struct interval_block
*interval_block
;
1490 /* Index in interval_block above of the next unused interval
1493 static int interval_block_index
= INTERVAL_BLOCK_SIZE
;
1495 /* Number of free and live intervals. */
1497 static EMACS_INT total_free_intervals
, total_intervals
;
1499 /* List of free intervals. */
1501 static INTERVAL interval_free_list
;
1503 /* Return a new interval. */
1506 make_interval (void)
1512 if (interval_free_list
)
1514 val
= interval_free_list
;
1515 interval_free_list
= INTERVAL_PARENT (interval_free_list
);
1519 if (interval_block_index
== INTERVAL_BLOCK_SIZE
)
1521 struct interval_block
*newi
1522 = lisp_malloc (sizeof *newi
, MEM_TYPE_NON_LISP
);
1524 newi
->next
= interval_block
;
1525 interval_block
= newi
;
1526 interval_block_index
= 0;
1527 total_free_intervals
+= INTERVAL_BLOCK_SIZE
;
1529 val
= &interval_block
->intervals
[interval_block_index
++];
1532 MALLOC_UNBLOCK_INPUT
;
1534 consing_since_gc
+= sizeof (struct interval
);
1536 total_free_intervals
--;
1537 RESET_INTERVAL (val
);
1543 /* Mark Lisp objects in interval I. */
1546 mark_interval (INTERVAL i
, void *dummy
)
1548 /* Intervals should never be shared. So, if extra internal checking is
1549 enabled, GC aborts if it seems to have visited an interval twice. */
1550 eassert (!i
->gcmarkbit
);
1552 mark_object (i
->plist
);
1555 /* Mark the interval tree rooted in I. */
1557 #define MARK_INTERVAL_TREE(i) \
1559 if (i && !i->gcmarkbit) \
1560 traverse_intervals_noorder (i, mark_interval, NULL); \
1563 /***********************************************************************
1565 ***********************************************************************/
1567 /* Lisp_Strings are allocated in string_block structures. When a new
1568 string_block is allocated, all the Lisp_Strings it contains are
1569 added to a free-list string_free_list. When a new Lisp_String is
1570 needed, it is taken from that list. During the sweep phase of GC,
1571 string_blocks that are entirely free are freed, except two which
1574 String data is allocated from sblock structures. Strings larger
1575 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1576 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1578 Sblocks consist internally of sdata structures, one for each
1579 Lisp_String. The sdata structure points to the Lisp_String it
1580 belongs to. The Lisp_String points back to the `u.data' member of
1581 its sdata structure.
1583 When a Lisp_String is freed during GC, it is put back on
1584 string_free_list, and its `data' member and its sdata's `string'
1585 pointer is set to null. The size of the string is recorded in the
1586 `n.nbytes' member of the sdata. So, sdata structures that are no
1587 longer used, can be easily recognized, and it's easy to compact the
1588 sblocks of small strings which we do in compact_small_strings. */
1590 /* Size in bytes of an sblock structure used for small strings. This
1591 is 8192 minus malloc overhead. */
1593 #define SBLOCK_SIZE 8188
1595 /* Strings larger than this are considered large strings. String data
1596 for large strings is allocated from individual sblocks. */
1598 #define LARGE_STRING_BYTES 1024
1600 /* The SDATA typedef is a struct or union describing string memory
1601 sub-allocated from an sblock. This is where the contents of Lisp
1602 strings are stored. */
1606 /* Back-pointer to the string this sdata belongs to. If null, this
1607 structure is free, and NBYTES (in this structure or in the union below)
1608 contains the string's byte size (the same value that STRING_BYTES
1609 would return if STRING were non-null). If non-null, STRING_BYTES
1610 (STRING) is the size of the data, and DATA contains the string's
1612 struct Lisp_String
*string
;
1614 #ifdef GC_CHECK_STRING_BYTES
1618 unsigned char data
[FLEXIBLE_ARRAY_MEMBER
];
1621 #ifdef GC_CHECK_STRING_BYTES
1623 typedef struct sdata sdata
;
1624 #define SDATA_NBYTES(S) (S)->nbytes
1625 #define SDATA_DATA(S) (S)->data
1631 struct Lisp_String
*string
;
1633 /* When STRING is nonnull, this union is actually of type 'struct sdata',
1634 which has a flexible array member. However, if implemented by
1635 giving this union a member of type 'struct sdata', the union
1636 could not be the last (flexible) member of 'struct sblock',
1637 because C99 prohibits a flexible array member from having a type
1638 that is itself a flexible array. So, comment this member out here,
1639 but remember that the option's there when using this union. */
1644 /* When STRING is null. */
1647 struct Lisp_String
*string
;
1652 #define SDATA_NBYTES(S) (S)->n.nbytes
1653 #define SDATA_DATA(S) ((struct sdata *) (S))->data
1655 #endif /* not GC_CHECK_STRING_BYTES */
1657 enum { SDATA_DATA_OFFSET
= offsetof (struct sdata
, data
) };
1659 /* Structure describing a block of memory which is sub-allocated to
1660 obtain string data memory for strings. Blocks for small strings
1661 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1662 as large as needed. */
1667 struct sblock
*next
;
1669 /* Pointer to the next free sdata block. This points past the end
1670 of the sblock if there isn't any space left in this block. */
1674 sdata data
[FLEXIBLE_ARRAY_MEMBER
];
1677 /* Number of Lisp strings in a string_block structure. The 1020 is
1678 1024 minus malloc overhead. */
1680 #define STRING_BLOCK_SIZE \
1681 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1683 /* Structure describing a block from which Lisp_String structures
1688 /* Place `strings' first, to preserve alignment. */
1689 struct Lisp_String strings
[STRING_BLOCK_SIZE
];
1690 struct string_block
*next
;
1693 /* Head and tail of the list of sblock structures holding Lisp string
1694 data. We always allocate from current_sblock. The NEXT pointers
1695 in the sblock structures go from oldest_sblock to current_sblock. */
1697 static struct sblock
*oldest_sblock
, *current_sblock
;
1699 /* List of sblocks for large strings. */
1701 static struct sblock
*large_sblocks
;
1703 /* List of string_block structures. */
1705 static struct string_block
*string_blocks
;
1707 /* Free-list of Lisp_Strings. */
1709 static struct Lisp_String
*string_free_list
;
1711 /* Number of live and free Lisp_Strings. */
1713 static EMACS_INT total_strings
, total_free_strings
;
1715 /* Number of bytes used by live strings. */
1717 static EMACS_INT total_string_bytes
;
1719 /* Given a pointer to a Lisp_String S which is on the free-list
1720 string_free_list, return a pointer to its successor in the
1723 #define NEXT_FREE_LISP_STRING(S) ((S)->u.next)
1725 /* Return a pointer to the sdata structure belonging to Lisp string S.
1726 S must be live, i.e. S->data must not be null. S->data is actually
1727 a pointer to the `u.data' member of its sdata structure; the
1728 structure starts at a constant offset in front of that. */
1730 #define SDATA_OF_STRING(S) ((sdata *) ptr_bounds_init ((S)->u.s.data \
1731 - SDATA_DATA_OFFSET))
1734 #ifdef GC_CHECK_STRING_OVERRUN
1736 /* We check for overrun in string data blocks by appending a small
1737 "cookie" after each allocated string data block, and check for the
1738 presence of this cookie during GC. */
1740 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1741 static char const string_overrun_cookie
[GC_STRING_OVERRUN_COOKIE_SIZE
] =
1742 { '\xde', '\xad', '\xbe', '\xef' };
1745 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1748 /* Value is the size of an sdata structure large enough to hold NBYTES
1749 bytes of string data. The value returned includes a terminating
1750 NUL byte, the size of the sdata structure, and padding. */
1752 #ifdef GC_CHECK_STRING_BYTES
1754 #define SDATA_SIZE(NBYTES) FLEXSIZEOF (struct sdata, data, (NBYTES) + 1)
1756 #else /* not GC_CHECK_STRING_BYTES */
1758 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1759 less than the size of that member. The 'max' is not needed when
1760 SDATA_DATA_OFFSET is a multiple of FLEXALIGNOF (struct sdata),
1761 because then the alignment code reserves enough space. */
1763 #define SDATA_SIZE(NBYTES) \
1764 ((SDATA_DATA_OFFSET \
1765 + (SDATA_DATA_OFFSET % FLEXALIGNOF (struct sdata) == 0 \
1767 : max (NBYTES, FLEXALIGNOF (struct sdata) - 1)) \
1769 + FLEXALIGNOF (struct sdata) - 1) \
1770 & ~(FLEXALIGNOF (struct sdata) - 1))
1772 #endif /* not GC_CHECK_STRING_BYTES */
1774 /* Extra bytes to allocate for each string. */
1776 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1778 /* Exact bound on the number of bytes in a string, not counting the
1779 terminating null. A string cannot contain more bytes than
1780 STRING_BYTES_BOUND, nor can it be so long that the size_t
1781 arithmetic in allocate_string_data would overflow while it is
1782 calculating a value to be passed to malloc. */
1783 static ptrdiff_t const STRING_BYTES_MAX
=
1784 min (STRING_BYTES_BOUND
,
1785 ((SIZE_MAX
- XMALLOC_OVERRUN_CHECK_OVERHEAD
1787 - offsetof (struct sblock
, data
)
1788 - SDATA_DATA_OFFSET
)
1789 & ~(sizeof (EMACS_INT
) - 1)));
1791 /* Initialize string allocation. Called from init_alloc_once. */
1796 empty_unibyte_string
= make_pure_string ("", 0, 0, 0);
1797 empty_multibyte_string
= make_pure_string ("", 0, 0, 1);
1801 #ifdef GC_CHECK_STRING_BYTES
1803 static int check_string_bytes_count
;
1805 /* Like STRING_BYTES, but with debugging check. Can be
1806 called during GC, so pay attention to the mark bit. */
1809 string_bytes (struct Lisp_String
*s
)
1812 (s
->u
.s
.size_byte
< 0 ? s
->u
.s
.size
& ~ARRAY_MARK_FLAG
: s
->u
.s
.size_byte
);
1814 if (!PURE_P (s
) && s
->u
.s
.data
1815 && nbytes
!= SDATA_NBYTES (SDATA_OF_STRING (s
)))
1820 /* Check validity of Lisp strings' string_bytes member in B. */
1823 check_sblock (struct sblock
*b
)
1825 sdata
*from
, *end
, *from_end
;
1829 for (from
= b
->data
; from
< end
; from
= from_end
)
1831 /* Compute the next FROM here because copying below may
1832 overwrite data we need to compute it. */
1835 /* Check that the string size recorded in the string is the
1836 same as the one recorded in the sdata structure. */
1837 nbytes
= SDATA_SIZE (from
->string
? string_bytes (from
->string
)
1838 : SDATA_NBYTES (from
));
1839 from_end
= (sdata
*) ((char *) from
+ nbytes
+ GC_STRING_EXTRA
);
1844 /* Check validity of Lisp strings' string_bytes member. ALL_P
1845 means check all strings, otherwise check only most
1846 recently allocated strings. Used for hunting a bug. */
1849 check_string_bytes (bool all_p
)
1855 for (b
= large_sblocks
; b
; b
= b
->next
)
1857 struct Lisp_String
*s
= b
->data
[0].string
;
1862 for (b
= oldest_sblock
; b
; b
= b
->next
)
1865 else if (current_sblock
)
1866 check_sblock (current_sblock
);
1869 #else /* not GC_CHECK_STRING_BYTES */
1871 #define check_string_bytes(all) ((void) 0)
1873 #endif /* GC_CHECK_STRING_BYTES */
1875 #ifdef GC_CHECK_STRING_FREE_LIST
1877 /* Walk through the string free list looking for bogus next pointers.
1878 This may catch buffer overrun from a previous string. */
1881 check_string_free_list (void)
1883 struct Lisp_String
*s
;
1885 /* Pop a Lisp_String off the free-list. */
1886 s
= string_free_list
;
1889 if ((uintptr_t) s
< 1024)
1891 s
= NEXT_FREE_LISP_STRING (s
);
1895 #define check_string_free_list()
1898 /* Return a new Lisp_String. */
1900 static struct Lisp_String
*
1901 allocate_string (void)
1903 struct Lisp_String
*s
;
1907 /* If the free-list is empty, allocate a new string_block, and
1908 add all the Lisp_Strings in it to the free-list. */
1909 if (string_free_list
== NULL
)
1911 struct string_block
*b
= lisp_malloc (sizeof *b
, MEM_TYPE_STRING
);
1914 b
->next
= string_blocks
;
1917 for (i
= STRING_BLOCK_SIZE
- 1; i
>= 0; --i
)
1920 /* Every string on a free list should have NULL data pointer. */
1922 NEXT_FREE_LISP_STRING (s
) = string_free_list
;
1923 string_free_list
= ptr_bounds_clip (s
, sizeof *s
);
1926 total_free_strings
+= STRING_BLOCK_SIZE
;
1929 check_string_free_list ();
1931 /* Pop a Lisp_String off the free-list. */
1932 s
= string_free_list
;
1933 string_free_list
= NEXT_FREE_LISP_STRING (s
);
1935 MALLOC_UNBLOCK_INPUT
;
1937 --total_free_strings
;
1940 consing_since_gc
+= sizeof *s
;
1942 #ifdef GC_CHECK_STRING_BYTES
1943 if (!noninteractive
)
1945 if (++check_string_bytes_count
== 200)
1947 check_string_bytes_count
= 0;
1948 check_string_bytes (1);
1951 check_string_bytes (0);
1953 #endif /* GC_CHECK_STRING_BYTES */
1959 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1960 plus a NUL byte at the end. Allocate an sdata structure DATA for
1961 S, and set S->u.s.data to SDATA->u.data. Store a NUL byte at the
1962 end of S->u.s.data. Set S->u.s.size to NCHARS and S->u.s.size_byte
1963 to NBYTES. Free S->u.s.data if it was initially non-null. */
1966 allocate_string_data (struct Lisp_String
*s
,
1967 EMACS_INT nchars
, EMACS_INT nbytes
)
1969 sdata
*data
, *old_data
;
1971 ptrdiff_t needed
, old_nbytes
;
1973 if (STRING_BYTES_MAX
< nbytes
)
1976 /* Determine the number of bytes needed to store NBYTES bytes
1978 needed
= SDATA_SIZE (nbytes
);
1981 old_data
= SDATA_OF_STRING (s
);
1982 old_nbytes
= STRING_BYTES (s
);
1989 if (nbytes
> LARGE_STRING_BYTES
)
1991 size_t size
= FLEXSIZEOF (struct sblock
, data
, needed
);
1993 #ifdef DOUG_LEA_MALLOC
1994 if (!mmap_lisp_allowed_p ())
1995 mallopt (M_MMAP_MAX
, 0);
1998 b
= lisp_malloc (size
+ GC_STRING_EXTRA
, MEM_TYPE_NON_LISP
);
2000 #ifdef DOUG_LEA_MALLOC
2001 if (!mmap_lisp_allowed_p ())
2002 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
);
2006 b
->next
= large_sblocks
;
2007 b
->next_free
= data
;
2010 else if (current_sblock
== NULL
2011 || (((char *) current_sblock
+ SBLOCK_SIZE
2012 - (char *) current_sblock
->next_free
)
2013 < (needed
+ GC_STRING_EXTRA
)))
2015 /* Not enough room in the current sblock. */
2016 b
= lisp_malloc (SBLOCK_SIZE
, MEM_TYPE_NON_LISP
);
2019 b
->next_free
= data
;
2022 current_sblock
->next
= b
;
2030 data
= b
->next_free
;
2034 b
->next_free
= (sdata
*) ((char *) data
+ needed
+ GC_STRING_EXTRA
);
2036 MALLOC_UNBLOCK_INPUT
;
2038 s
->u
.s
.data
= ptr_bounds_clip (SDATA_DATA (data
), nbytes
+ 1);
2039 #ifdef GC_CHECK_STRING_BYTES
2040 SDATA_NBYTES (data
) = nbytes
;
2042 s
->u
.s
.size
= nchars
;
2043 s
->u
.s
.size_byte
= nbytes
;
2044 s
->u
.s
.data
[nbytes
] = '\0';
2045 #ifdef GC_CHECK_STRING_OVERRUN
2046 memcpy ((char *) data
+ needed
, string_overrun_cookie
,
2047 GC_STRING_OVERRUN_COOKIE_SIZE
);
2050 /* Note that Faset may call to this function when S has already data
2051 assigned. In this case, mark data as free by setting it's string
2052 back-pointer to null, and record the size of the data in it. */
2055 SDATA_NBYTES (old_data
) = old_nbytes
;
2056 old_data
->string
= NULL
;
2059 consing_since_gc
+= needed
;
2063 /* Sweep and compact strings. */
2065 NO_INLINE
/* For better stack traces */
2067 sweep_strings (void)
2069 struct string_block
*b
, *next
;
2070 struct string_block
*live_blocks
= NULL
;
2072 string_free_list
= NULL
;
2073 total_strings
= total_free_strings
= 0;
2074 total_string_bytes
= 0;
2076 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
2077 for (b
= string_blocks
; b
; b
= next
)
2080 struct Lisp_String
*free_list_before
= string_free_list
;
2084 for (i
= 0; i
< STRING_BLOCK_SIZE
; ++i
)
2086 struct Lisp_String
*s
= b
->strings
+ i
;
2090 /* String was not on free-list before. */
2091 if (STRING_MARKED_P (s
))
2093 /* String is live; unmark it and its intervals. */
2096 /* Do not use string_(set|get)_intervals here. */
2097 s
->u
.s
.intervals
= balance_intervals (s
->u
.s
.intervals
);
2100 total_string_bytes
+= STRING_BYTES (s
);
2104 /* String is dead. Put it on the free-list. */
2105 sdata
*data
= SDATA_OF_STRING (s
);
2107 /* Save the size of S in its sdata so that we know
2108 how large that is. Reset the sdata's string
2109 back-pointer so that we know it's free. */
2110 #ifdef GC_CHECK_STRING_BYTES
2111 if (string_bytes (s
) != SDATA_NBYTES (data
))
2114 data
->n
.nbytes
= STRING_BYTES (s
);
2116 data
->string
= NULL
;
2118 /* Reset the strings's `data' member so that we
2122 /* Put the string on the free-list. */
2123 NEXT_FREE_LISP_STRING (s
) = string_free_list
;
2124 string_free_list
= ptr_bounds_clip (s
, sizeof *s
);
2130 /* S was on the free-list before. Put it there again. */
2131 NEXT_FREE_LISP_STRING (s
) = string_free_list
;
2132 string_free_list
= ptr_bounds_clip (s
, sizeof *s
);
2137 /* Free blocks that contain free Lisp_Strings only, except
2138 the first two of them. */
2139 if (nfree
== STRING_BLOCK_SIZE
2140 && total_free_strings
> STRING_BLOCK_SIZE
)
2143 string_free_list
= free_list_before
;
2147 total_free_strings
+= nfree
;
2148 b
->next
= live_blocks
;
2153 check_string_free_list ();
2155 string_blocks
= live_blocks
;
2156 free_large_strings ();
2157 compact_small_strings ();
2159 check_string_free_list ();
2163 /* Free dead large strings. */
2166 free_large_strings (void)
2168 struct sblock
*b
, *next
;
2169 struct sblock
*live_blocks
= NULL
;
2171 for (b
= large_sblocks
; b
; b
= next
)
2175 if (b
->data
[0].string
== NULL
)
2179 b
->next
= live_blocks
;
2184 large_sblocks
= live_blocks
;
2188 /* Compact data of small strings. Free sblocks that don't contain
2189 data of live strings after compaction. */
2192 compact_small_strings (void)
2194 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2195 to, and TB_END is the end of TB. */
2196 struct sblock
*tb
= oldest_sblock
;
2199 sdata
*tb_end
= (sdata
*) ((char *) tb
+ SBLOCK_SIZE
);
2200 sdata
*to
= tb
->data
;
2202 /* Step through the blocks from the oldest to the youngest. We
2203 expect that old blocks will stabilize over time, so that less
2204 copying will happen this way. */
2205 struct sblock
*b
= tb
;
2208 sdata
*end
= b
->next_free
;
2209 eassert ((char *) end
<= (char *) b
+ SBLOCK_SIZE
);
2211 for (sdata
*from
= b
->data
; from
< end
; )
2213 /* Compute the next FROM here because copying below may
2214 overwrite data we need to compute it. */
2216 struct Lisp_String
*s
= from
->string
;
2218 #ifdef GC_CHECK_STRING_BYTES
2219 /* Check that the string size recorded in the string is the
2220 same as the one recorded in the sdata structure. */
2221 if (s
&& string_bytes (s
) != SDATA_NBYTES (from
))
2223 #endif /* GC_CHECK_STRING_BYTES */
2225 nbytes
= s
? STRING_BYTES (s
) : SDATA_NBYTES (from
);
2226 eassert (nbytes
<= LARGE_STRING_BYTES
);
2228 ptrdiff_t size
= SDATA_SIZE (nbytes
);
2229 sdata
*from_end
= (sdata
*) ((char *) from
2230 + size
+ GC_STRING_EXTRA
);
2232 #ifdef GC_CHECK_STRING_OVERRUN
2233 if (memcmp (string_overrun_cookie
,
2234 (char *) from_end
- GC_STRING_OVERRUN_COOKIE_SIZE
,
2235 GC_STRING_OVERRUN_COOKIE_SIZE
))
2239 /* Non-NULL S means it's alive. Copy its data. */
2242 /* If TB is full, proceed with the next sblock. */
2243 sdata
*to_end
= (sdata
*) ((char *) to
2244 + size
+ GC_STRING_EXTRA
);
2245 if (to_end
> tb_end
)
2249 tb_end
= (sdata
*) ((char *) tb
+ SBLOCK_SIZE
);
2251 to_end
= (sdata
*) ((char *) to
+ size
+ GC_STRING_EXTRA
);
2254 /* Copy, and update the string's `data' pointer. */
2257 eassert (tb
!= b
|| to
< from
);
2258 memmove (to
, from
, size
+ GC_STRING_EXTRA
);
2259 to
->string
->u
.s
.data
2260 = ptr_bounds_clip (SDATA_DATA (to
), nbytes
+ 1);
2263 /* Advance past the sdata we copied to. */
2272 /* The rest of the sblocks following TB don't contain live data, so
2273 we can free them. */
2274 for (b
= tb
->next
; b
; )
2276 struct sblock
*next
= b
->next
;
2285 current_sblock
= tb
;
2289 string_overflow (void)
2291 error ("Maximum string size exceeded");
2294 DEFUN ("make-string", Fmake_string
, Smake_string
, 2, 3, 0,
2295 doc
: /* Return a newly created string of length LENGTH, with INIT in each element.
2296 LENGTH must be an integer.
2297 INIT must be an integer that represents a character.
2298 If optional argument MULTIBYTE is non-nil, the result will be
2299 a multibyte string even if INIT is an ASCII character. */)
2300 (Lisp_Object length
, Lisp_Object init
, Lisp_Object multibyte
)
2302 register Lisp_Object val
;
2306 CHECK_NATNUM (length
);
2307 CHECK_CHARACTER (init
);
2309 c
= XFASTINT (init
);
2310 if (ASCII_CHAR_P (c
) && NILP (multibyte
))
2312 nbytes
= XINT (length
);
2313 val
= make_uninit_string (nbytes
);
2316 memset (SDATA (val
), c
, nbytes
);
2317 SDATA (val
)[nbytes
] = 0;
2322 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
2323 ptrdiff_t len
= CHAR_STRING (c
, str
);
2324 EMACS_INT string_len
= XINT (length
);
2325 unsigned char *p
, *beg
, *end
;
2327 if (INT_MULTIPLY_WRAPV (len
, string_len
, &nbytes
))
2329 val
= make_uninit_multibyte_string (string_len
, nbytes
);
2330 for (beg
= SDATA (val
), p
= beg
, end
= beg
+ nbytes
; p
< end
; p
+= len
)
2332 /* First time we just copy `str' to the data of `val'. */
2334 memcpy (p
, str
, len
);
2337 /* Next time we copy largest possible chunk from
2338 initialized to uninitialized part of `val'. */
2339 len
= min (p
- beg
, end
- p
);
2340 memcpy (p
, beg
, len
);
2350 /* Fill A with 1 bits if INIT is non-nil, and with 0 bits otherwise.
2354 bool_vector_fill (Lisp_Object a
, Lisp_Object init
)
2356 EMACS_INT nbits
= bool_vector_size (a
);
2359 unsigned char *data
= bool_vector_uchar_data (a
);
2360 int pattern
= NILP (init
) ? 0 : (1 << BOOL_VECTOR_BITS_PER_CHAR
) - 1;
2361 ptrdiff_t nbytes
= bool_vector_bytes (nbits
);
2362 int last_mask
= ~ (~0u << ((nbits
- 1) % BOOL_VECTOR_BITS_PER_CHAR
+ 1));
2363 memset (data
, pattern
, nbytes
- 1);
2364 data
[nbytes
- 1] = pattern
& last_mask
;
2369 /* Return a newly allocated, uninitialized bool vector of size NBITS. */
2372 make_uninit_bool_vector (EMACS_INT nbits
)
2375 EMACS_INT words
= bool_vector_words (nbits
);
2376 EMACS_INT word_bytes
= words
* sizeof (bits_word
);
2377 EMACS_INT needed_elements
= ((bool_header_size
- header_size
+ word_bytes
2380 struct Lisp_Bool_Vector
*p
2381 = (struct Lisp_Bool_Vector
*) allocate_vector (needed_elements
);
2382 XSETVECTOR (val
, p
);
2383 XSETPVECTYPESIZE (XVECTOR (val
), PVEC_BOOL_VECTOR
, 0, 0);
2386 /* Clear padding at the end. */
2388 p
->data
[words
- 1] = 0;
2393 DEFUN ("make-bool-vector", Fmake_bool_vector
, Smake_bool_vector
, 2, 2, 0,
2394 doc
: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2395 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2396 (Lisp_Object length
, Lisp_Object init
)
2400 CHECK_NATNUM (length
);
2401 val
= make_uninit_bool_vector (XFASTINT (length
));
2402 return bool_vector_fill (val
, init
);
2405 DEFUN ("bool-vector", Fbool_vector
, Sbool_vector
, 0, MANY
, 0,
2406 doc
: /* Return a new bool-vector with specified arguments as elements.
2407 Any number of arguments, even zero arguments, are allowed.
2408 usage: (bool-vector &rest OBJECTS) */)
2409 (ptrdiff_t nargs
, Lisp_Object
*args
)
2414 vector
= make_uninit_bool_vector (nargs
);
2415 for (i
= 0; i
< nargs
; i
++)
2416 bool_vector_set (vector
, i
, !NILP (args
[i
]));
2421 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2422 of characters from the contents. This string may be unibyte or
2423 multibyte, depending on the contents. */
2426 make_string (const char *contents
, ptrdiff_t nbytes
)
2428 register Lisp_Object val
;
2429 ptrdiff_t nchars
, multibyte_nbytes
;
2431 parse_str_as_multibyte ((const unsigned char *) contents
, nbytes
,
2432 &nchars
, &multibyte_nbytes
);
2433 if (nbytes
== nchars
|| nbytes
!= multibyte_nbytes
)
2434 /* CONTENTS contains no multibyte sequences or contains an invalid
2435 multibyte sequence. We must make unibyte string. */
2436 val
= make_unibyte_string (contents
, nbytes
);
2438 val
= make_multibyte_string (contents
, nchars
, nbytes
);
2442 /* Make a unibyte string from LENGTH bytes at CONTENTS. */
2445 make_unibyte_string (const char *contents
, ptrdiff_t length
)
2447 register Lisp_Object val
;
2448 val
= make_uninit_string (length
);
2449 memcpy (SDATA (val
), contents
, length
);
2454 /* Make a multibyte string from NCHARS characters occupying NBYTES
2455 bytes at CONTENTS. */
2458 make_multibyte_string (const char *contents
,
2459 ptrdiff_t nchars
, ptrdiff_t nbytes
)
2461 register Lisp_Object val
;
2462 val
= make_uninit_multibyte_string (nchars
, nbytes
);
2463 memcpy (SDATA (val
), contents
, nbytes
);
2468 /* Make a string from NCHARS characters occupying NBYTES bytes at
2469 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2472 make_string_from_bytes (const char *contents
,
2473 ptrdiff_t nchars
, ptrdiff_t nbytes
)
2475 register Lisp_Object val
;
2476 val
= make_uninit_multibyte_string (nchars
, nbytes
);
2477 memcpy (SDATA (val
), contents
, nbytes
);
2478 if (SBYTES (val
) == SCHARS (val
))
2479 STRING_SET_UNIBYTE (val
);
2484 /* Make a string from NCHARS characters occupying NBYTES bytes at
2485 CONTENTS. The argument MULTIBYTE controls whether to label the
2486 string as multibyte. If NCHARS is negative, it counts the number of
2487 characters by itself. */
2490 make_specified_string (const char *contents
,
2491 ptrdiff_t nchars
, ptrdiff_t nbytes
, bool multibyte
)
2498 nchars
= multibyte_chars_in_text ((const unsigned char *) contents
,
2503 val
= make_uninit_multibyte_string (nchars
, nbytes
);
2504 memcpy (SDATA (val
), contents
, nbytes
);
2506 STRING_SET_UNIBYTE (val
);
2511 /* Return a unibyte Lisp_String set up to hold LENGTH characters
2512 occupying LENGTH bytes. */
2515 make_uninit_string (EMACS_INT length
)
2520 return empty_unibyte_string
;
2521 val
= make_uninit_multibyte_string (length
, length
);
2522 STRING_SET_UNIBYTE (val
);
2527 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2528 which occupy NBYTES bytes. */
2531 make_uninit_multibyte_string (EMACS_INT nchars
, EMACS_INT nbytes
)
2534 struct Lisp_String
*s
;
2539 return empty_multibyte_string
;
2541 s
= allocate_string ();
2542 s
->u
.s
.intervals
= NULL
;
2543 allocate_string_data (s
, nchars
, nbytes
);
2544 XSETSTRING (string
, s
);
2545 string_chars_consed
+= nbytes
;
2549 /* Print arguments to BUF according to a FORMAT, then return
2550 a Lisp_String initialized with the data from BUF. */
2553 make_formatted_string (char *buf
, const char *format
, ...)
2558 va_start (ap
, format
);
2559 length
= vsprintf (buf
, format
, ap
);
2561 return make_string (buf
, length
);
2565 /***********************************************************************
2567 ***********************************************************************/
2569 /* We store float cells inside of float_blocks, allocating a new
2570 float_block with malloc whenever necessary. Float cells reclaimed
2571 by GC are put on a free list to be reallocated before allocating
2572 any new float cells from the latest float_block. */
2574 #define FLOAT_BLOCK_SIZE \
2575 (((BLOCK_BYTES - sizeof (struct float_block *) \
2576 /* The compiler might add padding at the end. */ \
2577 - (sizeof (struct Lisp_Float) - sizeof (bits_word))) * CHAR_BIT) \
2578 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2580 #define GETMARKBIT(block,n) \
2581 (((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2582 >> ((n) % BITS_PER_BITS_WORD)) \
2585 #define SETMARKBIT(block,n) \
2586 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2587 |= (bits_word) 1 << ((n) % BITS_PER_BITS_WORD))
2589 #define UNSETMARKBIT(block,n) \
2590 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2591 &= ~((bits_word) 1 << ((n) % BITS_PER_BITS_WORD)))
2593 #define FLOAT_BLOCK(fptr) \
2594 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2596 #define FLOAT_INDEX(fptr) \
2597 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2601 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2602 struct Lisp_Float floats
[FLOAT_BLOCK_SIZE
];
2603 bits_word gcmarkbits
[1 + FLOAT_BLOCK_SIZE
/ BITS_PER_BITS_WORD
];
2604 struct float_block
*next
;
2607 #define FLOAT_MARKED_P(fptr) \
2608 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2610 #define FLOAT_MARK(fptr) \
2611 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2613 #define FLOAT_UNMARK(fptr) \
2614 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2616 /* Current float_block. */
2618 static struct float_block
*float_block
;
2620 /* Index of first unused Lisp_Float in the current float_block. */
2622 static int float_block_index
= FLOAT_BLOCK_SIZE
;
2624 /* Free-list of Lisp_Floats. */
2626 static struct Lisp_Float
*float_free_list
;
2628 /* Return a new float object with value FLOAT_VALUE. */
2631 make_float (double float_value
)
2633 register Lisp_Object val
;
2637 if (float_free_list
)
2639 /* We use the data field for chaining the free list
2640 so that we won't use the same field that has the mark bit. */
2641 XSETFLOAT (val
, float_free_list
);
2642 float_free_list
= float_free_list
->u
.chain
;
2646 if (float_block_index
== FLOAT_BLOCK_SIZE
)
2648 struct float_block
*new
2649 = lisp_align_malloc (sizeof *new, MEM_TYPE_FLOAT
);
2650 new->next
= float_block
;
2651 memset (new->gcmarkbits
, 0, sizeof new->gcmarkbits
);
2653 float_block_index
= 0;
2654 total_free_floats
+= FLOAT_BLOCK_SIZE
;
2656 XSETFLOAT (val
, &float_block
->floats
[float_block_index
]);
2657 float_block_index
++;
2660 MALLOC_UNBLOCK_INPUT
;
2662 XFLOAT_INIT (val
, float_value
);
2663 eassert (!FLOAT_MARKED_P (XFLOAT (val
)));
2664 consing_since_gc
+= sizeof (struct Lisp_Float
);
2666 total_free_floats
--;
2672 /***********************************************************************
2674 ***********************************************************************/
2676 /* We store cons cells inside of cons_blocks, allocating a new
2677 cons_block with malloc whenever necessary. Cons cells reclaimed by
2678 GC are put on a free list to be reallocated before allocating
2679 any new cons cells from the latest cons_block. */
2681 #define CONS_BLOCK_SIZE \
2682 (((BLOCK_BYTES - sizeof (struct cons_block *) \
2683 /* The compiler might add padding at the end. */ \
2684 - (sizeof (struct Lisp_Cons) - sizeof (bits_word))) * CHAR_BIT) \
2685 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2687 #define CONS_BLOCK(fptr) \
2688 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2690 #define CONS_INDEX(fptr) \
2691 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2695 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2696 struct Lisp_Cons conses
[CONS_BLOCK_SIZE
];
2697 bits_word gcmarkbits
[1 + CONS_BLOCK_SIZE
/ BITS_PER_BITS_WORD
];
2698 struct cons_block
*next
;
2701 #define CONS_MARKED_P(fptr) \
2702 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2704 #define CONS_MARK(fptr) \
2705 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2707 #define CONS_UNMARK(fptr) \
2708 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2710 /* Current cons_block. */
2712 static struct cons_block
*cons_block
;
2714 /* Index of first unused Lisp_Cons in the current block. */
2716 static int cons_block_index
= CONS_BLOCK_SIZE
;
2718 /* Free-list of Lisp_Cons structures. */
2720 static struct Lisp_Cons
*cons_free_list
;
2722 /* Explicitly free a cons cell by putting it on the free-list. */
2725 free_cons (struct Lisp_Cons
*ptr
)
2727 ptr
->u
.s
.u
.chain
= cons_free_list
;
2728 ptr
->u
.s
.car
= Vdead
;
2729 cons_free_list
= ptr
;
2730 consing_since_gc
-= sizeof *ptr
;
2731 total_free_conses
++;
2734 DEFUN ("cons", Fcons
, Scons
, 2, 2, 0,
2735 doc
: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2736 (Lisp_Object car
, Lisp_Object cdr
)
2738 register Lisp_Object val
;
2744 /* We use the cdr for chaining the free list
2745 so that we won't use the same field that has the mark bit. */
2746 XSETCONS (val
, cons_free_list
);
2747 cons_free_list
= cons_free_list
->u
.s
.u
.chain
;
2751 if (cons_block_index
== CONS_BLOCK_SIZE
)
2753 struct cons_block
*new
2754 = lisp_align_malloc (sizeof *new, MEM_TYPE_CONS
);
2755 memset (new->gcmarkbits
, 0, sizeof new->gcmarkbits
);
2756 new->next
= cons_block
;
2758 cons_block_index
= 0;
2759 total_free_conses
+= CONS_BLOCK_SIZE
;
2761 XSETCONS (val
, &cons_block
->conses
[cons_block_index
]);
2765 MALLOC_UNBLOCK_INPUT
;
2769 eassert (!CONS_MARKED_P (XCONS (val
)));
2770 consing_since_gc
+= sizeof (struct Lisp_Cons
);
2771 total_free_conses
--;
2772 cons_cells_consed
++;
2776 #ifdef GC_CHECK_CONS_LIST
2777 /* Get an error now if there's any junk in the cons free list. */
2779 check_cons_list (void)
2781 struct Lisp_Cons
*tail
= cons_free_list
;
2784 tail
= tail
->u
.s
.u
.chain
;
2788 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2791 list1 (Lisp_Object arg1
)
2793 return Fcons (arg1
, Qnil
);
2797 list2 (Lisp_Object arg1
, Lisp_Object arg2
)
2799 return Fcons (arg1
, Fcons (arg2
, Qnil
));
2804 list3 (Lisp_Object arg1
, Lisp_Object arg2
, Lisp_Object arg3
)
2806 return Fcons (arg1
, Fcons (arg2
, Fcons (arg3
, Qnil
)));
2811 list4 (Lisp_Object arg1
, Lisp_Object arg2
, Lisp_Object arg3
, Lisp_Object arg4
)
2813 return Fcons (arg1
, Fcons (arg2
, Fcons (arg3
, Fcons (arg4
, Qnil
))));
2818 list5 (Lisp_Object arg1
, Lisp_Object arg2
, Lisp_Object arg3
, Lisp_Object arg4
, Lisp_Object arg5
)
2820 return Fcons (arg1
, Fcons (arg2
, Fcons (arg3
, Fcons (arg4
,
2821 Fcons (arg5
, Qnil
)))));
2824 /* Make a list of COUNT Lisp_Objects, where ARG is the
2825 first one. Allocate conses from pure space if TYPE
2826 is CONSTYPE_PURE, or allocate as usual if type is CONSTYPE_HEAP. */
2829 listn (enum constype type
, ptrdiff_t count
, Lisp_Object arg
, ...)
2831 Lisp_Object (*cons
) (Lisp_Object
, Lisp_Object
);
2834 case CONSTYPE_PURE
: cons
= pure_cons
; break;
2835 case CONSTYPE_HEAP
: cons
= Fcons
; break;
2836 default: emacs_abort ();
2839 eassume (0 < count
);
2840 Lisp_Object val
= cons (arg
, Qnil
);
2841 Lisp_Object tail
= val
;
2845 for (ptrdiff_t i
= 1; i
< count
; i
++)
2847 Lisp_Object elem
= cons (va_arg (ap
, Lisp_Object
), Qnil
);
2848 XSETCDR (tail
, elem
);
2856 DEFUN ("list", Flist
, Slist
, 0, MANY
, 0,
2857 doc
: /* Return a newly created list with specified arguments as elements.
2858 Any number of arguments, even zero arguments, are allowed.
2859 usage: (list &rest OBJECTS) */)
2860 (ptrdiff_t nargs
, Lisp_Object
*args
)
2862 register Lisp_Object val
;
2868 val
= Fcons (args
[nargs
], val
);
2874 DEFUN ("make-list", Fmake_list
, Smake_list
, 2, 2, 0,
2875 doc
: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2876 (Lisp_Object length
, Lisp_Object init
)
2878 Lisp_Object val
= Qnil
;
2879 CHECK_NATNUM (length
);
2881 for (EMACS_INT size
= XFASTINT (length
); 0 < size
; size
--)
2883 val
= Fcons (init
, val
);
2892 /***********************************************************************
2894 ***********************************************************************/
2896 /* Sometimes a vector's contents are merely a pointer internally used
2897 in vector allocation code. On the rare platforms where a null
2898 pointer cannot be tagged, represent it with a Lisp 0.
2899 Usually you don't want to touch this. */
2901 static struct Lisp_Vector
*
2902 next_vector (struct Lisp_Vector
*v
)
2904 return XUNTAG (v
->contents
[0], Lisp_Int0
);
2908 set_next_vector (struct Lisp_Vector
*v
, struct Lisp_Vector
*p
)
2910 v
->contents
[0] = make_lisp_ptr (p
, Lisp_Int0
);
2913 /* This value is balanced well enough to avoid too much internal overhead
2914 for the most common cases; it's not required to be a power of two, but
2915 it's expected to be a mult-of-ROUNDUP_SIZE (see below). */
2917 #define VECTOR_BLOCK_SIZE 4096
2919 /* Alignment of struct Lisp_Vector objects. Because pseudovectors
2920 can contain any C type, align at least as strictly as
2921 max_align_t. On x86 and x86-64 this can waste up to 8 bytes
2922 for typical vectors, since alignof (max_align_t) is 16 but
2923 typical vectors need only an alignment of 8. However, it is
2924 not worth the hassle to avoid wasting those bytes. */
2925 enum {vector_alignment
= COMMON_MULTIPLE (alignof (max_align_t
), GCALIGNMENT
)};
2927 /* Vector size requests are a multiple of this. */
2928 enum { roundup_size
= COMMON_MULTIPLE (vector_alignment
, word_size
) };
2930 /* Verify assumptions described above. */
2931 verify (VECTOR_BLOCK_SIZE
% roundup_size
== 0);
2932 verify (VECTOR_BLOCK_SIZE
<= (1 << PSEUDOVECTOR_SIZE_BITS
));
2934 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at compile time. */
2935 #define vroundup_ct(x) ROUNDUP (x, roundup_size)
2936 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at runtime. */
2937 #define vroundup(x) (eassume ((x) >= 0), vroundup_ct (x))
2939 /* Rounding helps to maintain alignment constraints if USE_LSB_TAG. */
2941 #define VECTOR_BLOCK_BYTES (VECTOR_BLOCK_SIZE - vroundup_ct (sizeof (void *)))
2943 /* Size of the minimal vector allocated from block. */
2945 #define VBLOCK_BYTES_MIN vroundup_ct (header_size + sizeof (Lisp_Object))
2947 /* Size of the largest vector allocated from block. */
2949 #define VBLOCK_BYTES_MAX \
2950 vroundup ((VECTOR_BLOCK_BYTES / 2) - word_size)
2952 /* We maintain one free list for each possible block-allocated
2953 vector size, and this is the number of free lists we have. */
2955 #define VECTOR_MAX_FREE_LIST_INDEX \
2956 ((VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN) / roundup_size + 1)
2958 /* Common shortcut to advance vector pointer over a block data. */
2960 static struct Lisp_Vector
*
2961 ADVANCE (struct Lisp_Vector
*v
, ptrdiff_t nbytes
)
2965 void *p
= cv
+ nbytes
;
2969 /* Common shortcut to calculate NBYTES-vector index in VECTOR_FREE_LISTS. */
2972 VINDEX (ptrdiff_t nbytes
)
2974 eassume (VBLOCK_BYTES_MIN
<= nbytes
);
2975 return (nbytes
- VBLOCK_BYTES_MIN
) / roundup_size
;
2978 /* This internal type is used to maintain the list of large vectors
2979 which are allocated at their own, e.g. outside of vector blocks.
2981 struct large_vector itself cannot contain a struct Lisp_Vector, as
2982 the latter contains a flexible array member and C99 does not allow
2983 such structs to be nested. Instead, each struct large_vector
2984 object LV is followed by a struct Lisp_Vector, which is at offset
2985 large_vector_offset from LV, and whose address is therefore
2986 large_vector_vec (&LV). */
2990 struct large_vector
*next
;
2995 large_vector_offset
= ROUNDUP (sizeof (struct large_vector
), vector_alignment
)
2998 static struct Lisp_Vector
*
2999 large_vector_vec (struct large_vector
*p
)
3001 return (struct Lisp_Vector
*) ((char *) p
+ large_vector_offset
);
3004 /* This internal type is used to maintain an underlying storage
3005 for small vectors. */
3009 char data
[VECTOR_BLOCK_BYTES
];
3010 struct vector_block
*next
;
3013 /* Chain of vector blocks. */
3015 static struct vector_block
*vector_blocks
;
3017 /* Vector free lists, where NTH item points to a chain of free
3018 vectors of the same NBYTES size, so NTH == VINDEX (NBYTES). */
3020 static struct Lisp_Vector
*vector_free_lists
[VECTOR_MAX_FREE_LIST_INDEX
];
3022 /* Singly-linked list of large vectors. */
3024 static struct large_vector
*large_vectors
;
3026 /* The only vector with 0 slots, allocated from pure space. */
3028 Lisp_Object zero_vector
;
3030 /* Number of live vectors. */
3032 static EMACS_INT total_vectors
;
3034 /* Total size of live and free vectors, in Lisp_Object units. */
3036 static EMACS_INT total_vector_slots
, total_free_vector_slots
;
3038 /* Common shortcut to setup vector on a free list. */
3041 setup_on_free_list (struct Lisp_Vector
*v
, ptrdiff_t nbytes
)
3043 v
= ptr_bounds_clip (v
, nbytes
);
3044 eassume (header_size
<= nbytes
);
3045 ptrdiff_t nwords
= (nbytes
- header_size
) / word_size
;
3046 XSETPVECTYPESIZE (v
, PVEC_FREE
, 0, nwords
);
3047 eassert (nbytes
% roundup_size
== 0);
3048 ptrdiff_t vindex
= VINDEX (nbytes
);
3049 eassert (vindex
< VECTOR_MAX_FREE_LIST_INDEX
);
3050 set_next_vector (v
, vector_free_lists
[vindex
]);
3051 vector_free_lists
[vindex
] = v
;
3052 total_free_vector_slots
+= nbytes
/ word_size
;
3055 /* Get a new vector block. */
3057 static struct vector_block
*
3058 allocate_vector_block (void)
3060 struct vector_block
*block
= xmalloc (sizeof *block
);
3062 #ifndef GC_MALLOC_CHECK
3063 mem_insert (block
->data
, block
->data
+ VECTOR_BLOCK_BYTES
,
3064 MEM_TYPE_VECTOR_BLOCK
);
3067 block
->next
= vector_blocks
;
3068 vector_blocks
= block
;
3072 /* Called once to initialize vector allocation. */
3077 zero_vector
= make_pure_vector (0);
3080 /* Allocate vector from a vector block. */
3082 static struct Lisp_Vector
*
3083 allocate_vector_from_block (size_t nbytes
)
3085 struct Lisp_Vector
*vector
;
3086 struct vector_block
*block
;
3087 size_t index
, restbytes
;
3089 eassert (VBLOCK_BYTES_MIN
<= nbytes
&& nbytes
<= VBLOCK_BYTES_MAX
);
3090 eassert (nbytes
% roundup_size
== 0);
3092 /* First, try to allocate from a free list
3093 containing vectors of the requested size. */
3094 index
= VINDEX (nbytes
);
3095 if (vector_free_lists
[index
])
3097 vector
= vector_free_lists
[index
];
3098 vector_free_lists
[index
] = next_vector (vector
);
3099 total_free_vector_slots
-= nbytes
/ word_size
;
3103 /* Next, check free lists containing larger vectors. Since
3104 we will split the result, we should have remaining space
3105 large enough to use for one-slot vector at least. */
3106 for (index
= VINDEX (nbytes
+ VBLOCK_BYTES_MIN
);
3107 index
< VECTOR_MAX_FREE_LIST_INDEX
; index
++)
3108 if (vector_free_lists
[index
])
3110 /* This vector is larger than requested. */
3111 vector
= vector_free_lists
[index
];
3112 vector_free_lists
[index
] = next_vector (vector
);
3113 total_free_vector_slots
-= nbytes
/ word_size
;
3115 /* Excess bytes are used for the smaller vector,
3116 which should be set on an appropriate free list. */
3117 restbytes
= index
* roundup_size
+ VBLOCK_BYTES_MIN
- nbytes
;
3118 eassert (restbytes
% roundup_size
== 0);
3119 setup_on_free_list (ADVANCE (vector
, nbytes
), restbytes
);
3123 /* Finally, need a new vector block. */
3124 block
= allocate_vector_block ();
3126 /* New vector will be at the beginning of this block. */
3127 vector
= (struct Lisp_Vector
*) block
->data
;
3129 /* If the rest of space from this block is large enough
3130 for one-slot vector at least, set up it on a free list. */
3131 restbytes
= VECTOR_BLOCK_BYTES
- nbytes
;
3132 if (restbytes
>= VBLOCK_BYTES_MIN
)
3134 eassert (restbytes
% roundup_size
== 0);
3135 setup_on_free_list (ADVANCE (vector
, nbytes
), restbytes
);
3140 /* Nonzero if VECTOR pointer is valid pointer inside BLOCK. */
3142 #define VECTOR_IN_BLOCK(vector, block) \
3143 ((char *) (vector) <= (block)->data \
3144 + VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN)
3146 /* Return the memory footprint of V in bytes. */
3149 vector_nbytes (struct Lisp_Vector
*v
)
3151 ptrdiff_t size
= v
->header
.size
& ~ARRAY_MARK_FLAG
;
3154 if (size
& PSEUDOVECTOR_FLAG
)
3156 if (PSEUDOVECTOR_TYPEP (&v
->header
, PVEC_BOOL_VECTOR
))
3158 struct Lisp_Bool_Vector
*bv
= (struct Lisp_Bool_Vector
*) v
;
3159 ptrdiff_t word_bytes
= (bool_vector_words (bv
->size
)
3160 * sizeof (bits_word
));
3161 ptrdiff_t boolvec_bytes
= bool_header_size
+ word_bytes
;
3162 verify (header_size
<= bool_header_size
);
3163 nwords
= (boolvec_bytes
- header_size
+ word_size
- 1) / word_size
;
3166 nwords
= ((size
& PSEUDOVECTOR_SIZE_MASK
)
3167 + ((size
& PSEUDOVECTOR_REST_MASK
)
3168 >> PSEUDOVECTOR_SIZE_BITS
));
3172 return vroundup (header_size
+ word_size
* nwords
);
3175 /* Release extra resources still in use by VECTOR, which may be any
3176 vector-like object. */
3179 cleanup_vector (struct Lisp_Vector
*vector
)
3181 detect_suspicious_free (vector
);
3182 if (PSEUDOVECTOR_TYPEP (&vector
->header
, PVEC_FONT
)
3183 && ((vector
->header
.size
& PSEUDOVECTOR_SIZE_MASK
)
3184 == FONT_OBJECT_MAX
))
3186 struct font_driver
const *drv
= ((struct font
*) vector
)->driver
;
3188 /* The font driver might sometimes be NULL, e.g. if Emacs was
3189 interrupted before it had time to set it up. */
3192 /* Attempt to catch subtle bugs like Bug#16140. */
3193 eassert (valid_font_driver (drv
));
3194 drv
->close ((struct font
*) vector
);
3198 if (PSEUDOVECTOR_TYPEP (&vector
->header
, PVEC_THREAD
))
3199 finalize_one_thread ((struct thread_state
*) vector
);
3200 else if (PSEUDOVECTOR_TYPEP (&vector
->header
, PVEC_MUTEX
))
3201 finalize_one_mutex ((struct Lisp_Mutex
*) vector
);
3202 else if (PSEUDOVECTOR_TYPEP (&vector
->header
, PVEC_CONDVAR
))
3203 finalize_one_condvar ((struct Lisp_CondVar
*) vector
);
3206 /* Reclaim space used by unmarked vectors. */
3208 NO_INLINE
/* For better stack traces */
3210 sweep_vectors (void)
3212 struct vector_block
*block
, **bprev
= &vector_blocks
;
3213 struct large_vector
*lv
, **lvprev
= &large_vectors
;
3214 struct Lisp_Vector
*vector
, *next
;
3216 total_vectors
= total_vector_slots
= total_free_vector_slots
= 0;
3217 memset (vector_free_lists
, 0, sizeof (vector_free_lists
));
3219 /* Looking through vector blocks. */
3221 for (block
= vector_blocks
; block
; block
= *bprev
)
3223 bool free_this_block
= 0;
3226 for (vector
= (struct Lisp_Vector
*) block
->data
;
3227 VECTOR_IN_BLOCK (vector
, block
); vector
= next
)
3229 if (VECTOR_MARKED_P (vector
))
3231 VECTOR_UNMARK (vector
);
3233 nbytes
= vector_nbytes (vector
);
3234 total_vector_slots
+= nbytes
/ word_size
;
3235 next
= ADVANCE (vector
, nbytes
);
3239 ptrdiff_t total_bytes
;
3241 cleanup_vector (vector
);
3242 nbytes
= vector_nbytes (vector
);
3243 total_bytes
= nbytes
;
3244 next
= ADVANCE (vector
, nbytes
);
3246 /* While NEXT is not marked, try to coalesce with VECTOR,
3247 thus making VECTOR of the largest possible size. */
3249 while (VECTOR_IN_BLOCK (next
, block
))
3251 if (VECTOR_MARKED_P (next
))
3253 cleanup_vector (next
);
3254 nbytes
= vector_nbytes (next
);
3255 total_bytes
+= nbytes
;
3256 next
= ADVANCE (next
, nbytes
);
3259 eassert (total_bytes
% roundup_size
== 0);
3261 if (vector
== (struct Lisp_Vector
*) block
->data
3262 && !VECTOR_IN_BLOCK (next
, block
))
3263 /* This block should be freed because all of its
3264 space was coalesced into the only free vector. */
3265 free_this_block
= 1;
3267 setup_on_free_list (vector
, total_bytes
);
3271 if (free_this_block
)
3273 *bprev
= block
->next
;
3274 #ifndef GC_MALLOC_CHECK
3275 mem_delete (mem_find (block
->data
));
3280 bprev
= &block
->next
;
3283 /* Sweep large vectors. */
3285 for (lv
= large_vectors
; lv
; lv
= *lvprev
)
3287 vector
= large_vector_vec (lv
);
3288 if (VECTOR_MARKED_P (vector
))
3290 VECTOR_UNMARK (vector
);
3292 if (vector
->header
.size
& PSEUDOVECTOR_FLAG
)
3293 total_vector_slots
+= vector_nbytes (vector
) / word_size
;
3296 += header_size
/ word_size
+ vector
->header
.size
;
3307 /* Value is a pointer to a newly allocated Lisp_Vector structure
3308 with room for LEN Lisp_Objects. */
3310 static struct Lisp_Vector
*
3311 allocate_vectorlike (ptrdiff_t len
)
3314 return XVECTOR (zero_vector
);
3317 size_t nbytes
= header_size
+ len
* word_size
;
3318 struct Lisp_Vector
*p
;
3322 #ifdef DOUG_LEA_MALLOC
3323 if (!mmap_lisp_allowed_p ())
3324 mallopt (M_MMAP_MAX
, 0);
3327 if (nbytes
<= VBLOCK_BYTES_MAX
)
3328 p
= allocate_vector_from_block (vroundup (nbytes
));
3331 struct large_vector
*lv
3332 = lisp_malloc ((large_vector_offset
+ header_size
3334 MEM_TYPE_VECTORLIKE
);
3335 lv
->next
= large_vectors
;
3337 p
= large_vector_vec (lv
);
3340 #ifdef DOUG_LEA_MALLOC
3341 if (!mmap_lisp_allowed_p ())
3342 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
);
3345 if (find_suspicious_object_in_range (p
, (char *) p
+ nbytes
))
3348 consing_since_gc
+= nbytes
;
3349 vector_cells_consed
+= len
;
3351 MALLOC_UNBLOCK_INPUT
;
3353 return ptr_bounds_clip (p
, nbytes
);
3358 /* Allocate a vector with LEN slots. */
3360 struct Lisp_Vector
*
3361 allocate_vector (EMACS_INT len
)
3363 struct Lisp_Vector
*v
;
3364 ptrdiff_t nbytes_max
= min (PTRDIFF_MAX
, SIZE_MAX
);
3366 if (min ((nbytes_max
- header_size
) / word_size
, MOST_POSITIVE_FIXNUM
) < len
)
3367 memory_full (SIZE_MAX
);
3368 v
= allocate_vectorlike (len
);
3370 v
->header
.size
= len
;
3375 /* Allocate other vector-like structures. */
3377 struct Lisp_Vector
*
3378 allocate_pseudovector (int memlen
, int lisplen
,
3379 int zerolen
, enum pvec_type tag
)
3381 struct Lisp_Vector
*v
= allocate_vectorlike (memlen
);
3383 /* Catch bogus values. */
3384 eassert (0 <= tag
&& tag
<= PVEC_FONT
);
3385 eassert (0 <= lisplen
&& lisplen
<= zerolen
&& zerolen
<= memlen
);
3386 eassert (memlen
- lisplen
<= (1 << PSEUDOVECTOR_REST_BITS
) - 1);
3387 eassert (lisplen
<= PSEUDOVECTOR_SIZE_MASK
);
3389 /* Only the first LISPLEN slots will be traced normally by the GC. */
3390 memclear (v
->contents
, zerolen
* word_size
);
3391 XSETPVECTYPESIZE (v
, tag
, lisplen
, memlen
- lisplen
);
3396 allocate_buffer (void)
3398 struct buffer
*b
= lisp_malloc (sizeof *b
, MEM_TYPE_BUFFER
);
3400 BUFFER_PVEC_INIT (b
);
3401 /* Put B on the chain of all buffers including killed ones. */
3402 b
->next
= all_buffers
;
3404 /* Note that the rest fields of B are not initialized. */
3409 /* Allocate a record with COUNT slots. COUNT must be positive, and
3410 includes the type slot. */
3412 static struct Lisp_Vector
*
3413 allocate_record (EMACS_INT count
)
3415 if (count
> PSEUDOVECTOR_SIZE_MASK
)
3416 error ("Attempt to allocate a record of %"pI
"d slots; max is %d",
3417 count
, PSEUDOVECTOR_SIZE_MASK
);
3418 struct Lisp_Vector
*p
= allocate_vectorlike (count
);
3419 p
->header
.size
= count
;
3420 XSETPVECTYPE (p
, PVEC_RECORD
);
3425 DEFUN ("make-record", Fmake_record
, Smake_record
, 3, 3, 0,
3426 doc
: /* Create a new record.
3427 TYPE is its type as returned by `type-of'; it should be either a
3428 symbol or a type descriptor. SLOTS is the number of non-type slots,
3429 each initialized to INIT. */)
3430 (Lisp_Object type
, Lisp_Object slots
, Lisp_Object init
)
3432 CHECK_NATNUM (slots
);
3433 EMACS_INT size
= XFASTINT (slots
) + 1;
3434 struct Lisp_Vector
*p
= allocate_record (size
);
3435 p
->contents
[0] = type
;
3436 for (ptrdiff_t i
= 1; i
< size
; i
++)
3437 p
->contents
[i
] = init
;
3438 return make_lisp_ptr (p
, Lisp_Vectorlike
);
3442 DEFUN ("record", Frecord
, Srecord
, 1, MANY
, 0,
3443 doc
: /* Create a new record.
3444 TYPE is its type as returned by `type-of'; it should be either a
3445 symbol or a type descriptor. SLOTS is used to initialize the record
3446 slots with shallow copies of the arguments.
3447 usage: (record TYPE &rest SLOTS) */)
3448 (ptrdiff_t nargs
, Lisp_Object
*args
)
3450 struct Lisp_Vector
*p
= allocate_record (nargs
);
3451 memcpy (p
->contents
, args
, nargs
* sizeof *args
);
3452 return make_lisp_ptr (p
, Lisp_Vectorlike
);
3456 DEFUN ("make-vector", Fmake_vector
, Smake_vector
, 2, 2, 0,
3457 doc
: /* Return a newly created vector of length LENGTH, with each element being INIT.
3458 See also the function `vector'. */)
3459 (Lisp_Object length
, Lisp_Object init
)
3461 CHECK_NATNUM (length
);
3462 struct Lisp_Vector
*p
= allocate_vector (XFASTINT (length
));
3463 for (ptrdiff_t i
= 0; i
< XFASTINT (length
); i
++)
3464 p
->contents
[i
] = init
;
3465 return make_lisp_ptr (p
, Lisp_Vectorlike
);
3468 DEFUN ("vector", Fvector
, Svector
, 0, MANY
, 0,
3469 doc
: /* Return a newly created vector with specified arguments as elements.
3470 Any number of arguments, even zero arguments, are allowed.
3471 usage: (vector &rest OBJECTS) */)
3472 (ptrdiff_t nargs
, Lisp_Object
*args
)
3474 Lisp_Object val
= make_uninit_vector (nargs
);
3475 struct Lisp_Vector
*p
= XVECTOR (val
);
3476 memcpy (p
->contents
, args
, nargs
* sizeof *args
);
3481 make_byte_code (struct Lisp_Vector
*v
)
3483 /* Don't allow the global zero_vector to become a byte code object. */
3484 eassert (0 < v
->header
.size
);
3486 if (v
->header
.size
> 1 && STRINGP (v
->contents
[1])
3487 && STRING_MULTIBYTE (v
->contents
[1]))
3488 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3489 earlier because they produced a raw 8-bit string for byte-code
3490 and now such a byte-code string is loaded as multibyte while
3491 raw 8-bit characters converted to multibyte form. Thus, now we
3492 must convert them back to the original unibyte form. */
3493 v
->contents
[1] = Fstring_as_unibyte (v
->contents
[1]);
3494 XSETPVECTYPE (v
, PVEC_COMPILED
);
3497 DEFUN ("make-byte-code", Fmake_byte_code
, Smake_byte_code
, 4, MANY
, 0,
3498 doc
: /* Create a byte-code object with specified arguments as elements.
3499 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3500 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3501 and (optional) INTERACTIVE-SPEC.
3502 The first four arguments are required; at most six have any
3504 The ARGLIST can be either like the one of `lambda', in which case the arguments
3505 will be dynamically bound before executing the byte code, or it can be an
3506 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3507 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3508 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3509 argument to catch the left-over arguments. If such an integer is used, the
3510 arguments will not be dynamically bound but will be instead pushed on the
3511 stack before executing the byte-code.
3512 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3513 (ptrdiff_t nargs
, Lisp_Object
*args
)
3515 Lisp_Object val
= make_uninit_vector (nargs
);
3516 struct Lisp_Vector
*p
= XVECTOR (val
);
3518 /* We used to purecopy everything here, if purify-flag was set. This worked
3519 OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
3520 dangerous, since make-byte-code is used during execution to build
3521 closures, so any closure built during the preload phase would end up
3522 copied into pure space, including its free variables, which is sometimes
3523 just wasteful and other times plainly wrong (e.g. those free vars may want
3526 memcpy (p
->contents
, args
, nargs
* sizeof *args
);
3528 XSETCOMPILED (val
, p
);
3534 /***********************************************************************
3536 ***********************************************************************/
3538 /* Each symbol_block is just under 1020 bytes long, since malloc
3539 really allocates in units of powers of two and uses 4 bytes for its
3542 #define SYMBOL_BLOCK_SIZE \
3543 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
3547 /* Place `symbols' first, to preserve alignment. */
3548 struct Lisp_Symbol symbols
[SYMBOL_BLOCK_SIZE
];
3549 struct symbol_block
*next
;
3552 /* Current symbol block and index of first unused Lisp_Symbol
3555 static struct symbol_block
*symbol_block
;
3556 static int symbol_block_index
= SYMBOL_BLOCK_SIZE
;
3557 /* Pointer to the first symbol_block that contains pinned symbols.
3558 Tests for 24.4 showed that at dump-time, Emacs contains about 15K symbols,
3559 10K of which are pinned (and all but 250 of them are interned in obarray),
3560 whereas a "typical session" has in the order of 30K symbols.
3561 `symbol_block_pinned' lets mark_pinned_symbols scan only 15K symbols rather
3562 than 30K to find the 10K symbols we need to mark. */
3563 static struct symbol_block
*symbol_block_pinned
;
3565 /* List of free symbols. */
3567 static struct Lisp_Symbol
*symbol_free_list
;
3570 set_symbol_name (Lisp_Object sym
, Lisp_Object name
)
3572 XSYMBOL (sym
)->u
.s
.name
= name
;
3576 init_symbol (Lisp_Object val
, Lisp_Object name
)
3578 struct Lisp_Symbol
*p
= XSYMBOL (val
);
3579 set_symbol_name (val
, name
);
3580 set_symbol_plist (val
, Qnil
);
3581 p
->u
.s
.redirect
= SYMBOL_PLAINVAL
;
3582 SET_SYMBOL_VAL (p
, Qunbound
);
3583 set_symbol_function (val
, Qnil
);
3584 set_symbol_next (val
, NULL
);
3585 p
->u
.s
.gcmarkbit
= false;
3586 p
->u
.s
.interned
= SYMBOL_UNINTERNED
;
3587 p
->u
.s
.trapped_write
= SYMBOL_UNTRAPPED_WRITE
;
3588 p
->u
.s
.declared_special
= false;
3589 p
->u
.s
.pinned
= false;
3592 DEFUN ("make-symbol", Fmake_symbol
, Smake_symbol
, 1, 1, 0,
3593 doc
: /* Return a newly allocated uninterned symbol whose name is NAME.
3594 Its value is void, and its function definition and property list are nil. */)
3599 CHECK_STRING (name
);
3603 if (symbol_free_list
)
3605 XSETSYMBOL (val
, symbol_free_list
);
3606 symbol_free_list
= symbol_free_list
->u
.s
.next
;
3610 if (symbol_block_index
== SYMBOL_BLOCK_SIZE
)
3612 struct symbol_block
*new
3613 = lisp_malloc (sizeof *new, MEM_TYPE_SYMBOL
);
3614 new->next
= symbol_block
;
3616 symbol_block_index
= 0;
3617 total_free_symbols
+= SYMBOL_BLOCK_SIZE
;
3619 XSETSYMBOL (val
, &symbol_block
->symbols
[symbol_block_index
]);
3620 symbol_block_index
++;
3623 MALLOC_UNBLOCK_INPUT
;
3625 init_symbol (val
, name
);
3626 consing_since_gc
+= sizeof (struct Lisp_Symbol
);
3628 total_free_symbols
--;
3634 /***********************************************************************
3635 Marker (Misc) Allocation
3636 ***********************************************************************/
3638 /* Like union Lisp_Misc, but padded so that its size is a multiple of
3639 the required alignment. */
3641 union aligned_Lisp_Misc
3644 unsigned char c
[(sizeof (union Lisp_Misc
) + GCALIGNMENT
- 1)
3648 /* Allocation of markers and other objects that share that structure.
3649 Works like allocation of conses. */
3651 #define MARKER_BLOCK_SIZE \
3652 ((1020 - sizeof (struct marker_block *)) / sizeof (union aligned_Lisp_Misc))
3656 /* Place `markers' first, to preserve alignment. */
3657 union aligned_Lisp_Misc markers
[MARKER_BLOCK_SIZE
];
3658 struct marker_block
*next
;
3661 static struct marker_block
*marker_block
;
3662 static int marker_block_index
= MARKER_BLOCK_SIZE
;
3664 static union Lisp_Misc
*marker_free_list
;
3666 /* Return a newly allocated Lisp_Misc object of specified TYPE. */
3669 allocate_misc (enum Lisp_Misc_Type type
)
3675 if (marker_free_list
)
3677 XSETMISC (val
, marker_free_list
);
3678 marker_free_list
= marker_free_list
->u_free
.chain
;
3682 if (marker_block_index
== MARKER_BLOCK_SIZE
)
3684 struct marker_block
*new = lisp_malloc (sizeof *new, MEM_TYPE_MISC
);
3685 new->next
= marker_block
;
3687 marker_block_index
= 0;
3688 total_free_markers
+= MARKER_BLOCK_SIZE
;
3690 XSETMISC (val
, &marker_block
->markers
[marker_block_index
].m
);
3691 marker_block_index
++;
3694 MALLOC_UNBLOCK_INPUT
;
3696 --total_free_markers
;
3697 consing_since_gc
+= sizeof (union Lisp_Misc
);
3698 misc_objects_consed
++;
3699 XMISCANY (val
)->type
= type
;
3700 XMISCANY (val
)->gcmarkbit
= 0;
3704 /* Free a Lisp_Misc object. */
3707 free_misc (Lisp_Object misc
)
3709 XMISCANY (misc
)->type
= Lisp_Misc_Free
;
3710 XMISC (misc
)->u_free
.chain
= marker_free_list
;
3711 marker_free_list
= XMISC (misc
);
3712 consing_since_gc
-= sizeof (union Lisp_Misc
);
3713 total_free_markers
++;
3716 /* Verify properties of Lisp_Save_Value's representation
3717 that are assumed here and elsewhere. */
3719 verify (SAVE_UNUSED
== 0);
3720 verify (((SAVE_INTEGER
| SAVE_POINTER
| SAVE_FUNCPOINTER
| SAVE_OBJECT
)
3724 /* Return Lisp_Save_Value objects for the various combinations
3725 that callers need. */
3728 make_save_int_int_int (ptrdiff_t a
, ptrdiff_t b
, ptrdiff_t c
)
3730 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3731 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3732 p
->save_type
= SAVE_TYPE_INT_INT_INT
;
3733 p
->data
[0].integer
= a
;
3734 p
->data
[1].integer
= b
;
3735 p
->data
[2].integer
= c
;
3740 make_save_obj_obj_obj_obj (Lisp_Object a
, Lisp_Object b
, Lisp_Object c
,
3743 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3744 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3745 p
->save_type
= SAVE_TYPE_OBJ_OBJ_OBJ_OBJ
;
3746 p
->data
[0].object
= a
;
3747 p
->data
[1].object
= b
;
3748 p
->data
[2].object
= c
;
3749 p
->data
[3].object
= d
;
3754 make_save_ptr (void *a
)
3756 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3757 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3758 p
->save_type
= SAVE_POINTER
;
3759 p
->data
[0].pointer
= a
;
3764 make_save_ptr_int (void *a
, ptrdiff_t b
)
3766 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3767 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3768 p
->save_type
= SAVE_TYPE_PTR_INT
;
3769 p
->data
[0].pointer
= a
;
3770 p
->data
[1].integer
= b
;
3775 make_save_ptr_ptr (void *a
, void *b
)
3777 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3778 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3779 p
->save_type
= SAVE_TYPE_PTR_PTR
;
3780 p
->data
[0].pointer
= a
;
3781 p
->data
[1].pointer
= b
;
3786 make_save_funcptr_ptr_obj (void (*a
) (void), void *b
, Lisp_Object c
)
3788 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3789 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3790 p
->save_type
= SAVE_TYPE_FUNCPTR_PTR_OBJ
;
3791 p
->data
[0].funcpointer
= a
;
3792 p
->data
[1].pointer
= b
;
3793 p
->data
[2].object
= c
;
3797 /* Return a Lisp_Save_Value object that represents an array A
3798 of N Lisp objects. */
3801 make_save_memory (Lisp_Object
*a
, ptrdiff_t n
)
3803 Lisp_Object val
= allocate_misc (Lisp_Misc_Save_Value
);
3804 struct Lisp_Save_Value
*p
= XSAVE_VALUE (val
);
3805 p
->save_type
= SAVE_TYPE_MEMORY
;
3806 p
->data
[0].pointer
= a
;
3807 p
->data
[1].integer
= n
;
3811 /* Free a Lisp_Save_Value object. Do not use this function
3812 if SAVE contains pointer other than returned by xmalloc. */
3815 free_save_value (Lisp_Object save
)
3817 xfree (XSAVE_POINTER (save
, 0));
3821 /* Return a Lisp_Misc_Overlay object with specified START, END and PLIST. */
3824 build_overlay (Lisp_Object start
, Lisp_Object end
, Lisp_Object plist
)
3826 register Lisp_Object overlay
;
3828 overlay
= allocate_misc (Lisp_Misc_Overlay
);
3829 OVERLAY_START (overlay
) = start
;
3830 OVERLAY_END (overlay
) = end
;
3831 set_overlay_plist (overlay
, plist
);
3832 XOVERLAY (overlay
)->next
= NULL
;
3836 DEFUN ("make-marker", Fmake_marker
, Smake_marker
, 0, 0, 0,
3837 doc
: /* Return a newly allocated marker which does not point at any place. */)
3840 register Lisp_Object val
;
3841 register struct Lisp_Marker
*p
;
3843 val
= allocate_misc (Lisp_Misc_Marker
);
3849 p
->insertion_type
= 0;
3850 p
->need_adjustment
= 0;
3854 /* Return a newly allocated marker which points into BUF
3855 at character position CHARPOS and byte position BYTEPOS. */
3858 build_marker (struct buffer
*buf
, ptrdiff_t charpos
, ptrdiff_t bytepos
)
3861 struct Lisp_Marker
*m
;
3863 /* No dead buffers here. */
3864 eassert (BUFFER_LIVE_P (buf
));
3866 /* Every character is at least one byte. */
3867 eassert (charpos
<= bytepos
);
3869 obj
= allocate_misc (Lisp_Misc_Marker
);
3872 m
->charpos
= charpos
;
3873 m
->bytepos
= bytepos
;
3874 m
->insertion_type
= 0;
3875 m
->need_adjustment
= 0;
3876 m
->next
= BUF_MARKERS (buf
);
3877 BUF_MARKERS (buf
) = m
;
3881 /* Put MARKER back on the free list after using it temporarily. */
3884 free_marker (Lisp_Object marker
)
3886 unchain_marker (XMARKER (marker
));
3891 /* Return a newly created vector or string with specified arguments as
3892 elements. If all the arguments are characters that can fit
3893 in a string of events, make a string; otherwise, make a vector.
3895 Any number of arguments, even zero arguments, are allowed. */
3898 make_event_array (ptrdiff_t nargs
, Lisp_Object
*args
)
3902 for (i
= 0; i
< nargs
; i
++)
3903 /* The things that fit in a string
3904 are characters that are in 0...127,
3905 after discarding the meta bit and all the bits above it. */
3906 if (!INTEGERP (args
[i
])
3907 || (XINT (args
[i
]) & ~(-CHAR_META
)) >= 0200)
3908 return Fvector (nargs
, args
);
3910 /* Since the loop exited, we know that all the things in it are
3911 characters, so we can make a string. */
3915 result
= Fmake_string (make_number (nargs
), make_number (0), Qnil
);
3916 for (i
= 0; i
< nargs
; i
++)
3918 SSET (result
, i
, XINT (args
[i
]));
3919 /* Move the meta bit to the right place for a string char. */
3920 if (XINT (args
[i
]) & CHAR_META
)
3921 SSET (result
, i
, SREF (result
, i
) | 0x80);
3929 /* Create a new module user ptr object. */
3931 make_user_ptr (void (*finalizer
) (void *), void *p
)
3934 struct Lisp_User_Ptr
*uptr
;
3936 obj
= allocate_misc (Lisp_Misc_User_Ptr
);
3937 uptr
= XUSER_PTR (obj
);
3938 uptr
->finalizer
= finalizer
;
3945 init_finalizer_list (struct Lisp_Finalizer
*head
)
3947 head
->prev
= head
->next
= head
;
3950 /* Insert FINALIZER before ELEMENT. */
3953 finalizer_insert (struct Lisp_Finalizer
*element
,
3954 struct Lisp_Finalizer
*finalizer
)
3956 eassert (finalizer
->prev
== NULL
);
3957 eassert (finalizer
->next
== NULL
);
3958 finalizer
->next
= element
;
3959 finalizer
->prev
= element
->prev
;
3960 finalizer
->prev
->next
= finalizer
;
3961 element
->prev
= finalizer
;
3965 unchain_finalizer (struct Lisp_Finalizer
*finalizer
)
3967 if (finalizer
->prev
!= NULL
)
3969 eassert (finalizer
->next
!= NULL
);
3970 finalizer
->prev
->next
= finalizer
->next
;
3971 finalizer
->next
->prev
= finalizer
->prev
;
3972 finalizer
->prev
= finalizer
->next
= NULL
;
3977 mark_finalizer_list (struct Lisp_Finalizer
*head
)
3979 for (struct Lisp_Finalizer
*finalizer
= head
->next
;
3981 finalizer
= finalizer
->next
)
3983 finalizer
->base
.gcmarkbit
= true;
3984 mark_object (finalizer
->function
);
3988 /* Move doomed finalizers to list DEST from list SRC. A doomed
3989 finalizer is one that is not GC-reachable and whose
3990 finalizer->function is non-nil. */
3993 queue_doomed_finalizers (struct Lisp_Finalizer
*dest
,
3994 struct Lisp_Finalizer
*src
)
3996 struct Lisp_Finalizer
*finalizer
= src
->next
;
3997 while (finalizer
!= src
)
3999 struct Lisp_Finalizer
*next
= finalizer
->next
;
4000 if (!finalizer
->base
.gcmarkbit
&& !NILP (finalizer
->function
))
4002 unchain_finalizer (finalizer
);
4003 finalizer_insert (dest
, finalizer
);
4011 run_finalizer_handler (Lisp_Object args
)
4013 add_to_log ("finalizer failed: %S", args
);
4018 run_finalizer_function (Lisp_Object function
)
4020 ptrdiff_t count
= SPECPDL_INDEX ();
4022 specbind (Qinhibit_quit
, Qt
);
4023 internal_condition_case_1 (call0
, function
, Qt
, run_finalizer_handler
);
4024 unbind_to (count
, Qnil
);
4028 run_finalizers (struct Lisp_Finalizer
*finalizers
)
4030 struct Lisp_Finalizer
*finalizer
;
4031 Lisp_Object function
;
4033 while (finalizers
->next
!= finalizers
)
4035 finalizer
= finalizers
->next
;
4036 eassert (finalizer
->base
.type
== Lisp_Misc_Finalizer
);
4037 unchain_finalizer (finalizer
);
4038 function
= finalizer
->function
;
4039 if (!NILP (function
))
4041 finalizer
->function
= Qnil
;
4042 run_finalizer_function (function
);
4047 DEFUN ("make-finalizer", Fmake_finalizer
, Smake_finalizer
, 1, 1, 0,
4048 doc
: /* Make a finalizer that will run FUNCTION.
4049 FUNCTION will be called after garbage collection when the returned
4050 finalizer object becomes unreachable. If the finalizer object is
4051 reachable only through references from finalizer objects, it does not
4052 count as reachable for the purpose of deciding whether to run
4053 FUNCTION. FUNCTION will be run once per finalizer object. */)
4054 (Lisp_Object function
)
4056 Lisp_Object val
= allocate_misc (Lisp_Misc_Finalizer
);
4057 struct Lisp_Finalizer
*finalizer
= XFINALIZER (val
);
4058 finalizer
->function
= function
;
4059 finalizer
->prev
= finalizer
->next
= NULL
;
4060 finalizer_insert (&finalizers
, finalizer
);
4065 /************************************************************************
4066 Memory Full Handling
4067 ************************************************************************/
4070 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
4071 there may have been size_t overflow so that malloc was never
4072 called, or perhaps malloc was invoked successfully but the
4073 resulting pointer had problems fitting into a tagged EMACS_INT. In
4074 either case this counts as memory being full even though malloc did
4078 memory_full (size_t nbytes
)
4080 /* Do not go into hysterics merely because a large request failed. */
4081 bool enough_free_memory
= 0;
4082 if (SPARE_MEMORY
< nbytes
)
4087 p
= malloc (SPARE_MEMORY
);
4091 enough_free_memory
= 1;
4093 MALLOC_UNBLOCK_INPUT
;
4096 if (! enough_free_memory
)
4102 memory_full_cons_threshold
= sizeof (struct cons_block
);
4104 /* The first time we get here, free the spare memory. */
4105 for (i
= 0; i
< ARRAYELTS (spare_memory
); i
++)
4106 if (spare_memory
[i
])
4109 free (spare_memory
[i
]);
4110 else if (i
>= 1 && i
<= 4)
4111 lisp_align_free (spare_memory
[i
]);
4113 lisp_free (spare_memory
[i
]);
4114 spare_memory
[i
] = 0;
4118 /* This used to call error, but if we've run out of memory, we could
4119 get infinite recursion trying to build the string. */
4120 xsignal (Qnil
, Vmemory_signal_data
);
4123 /* If we released our reserve (due to running out of memory),
4124 and we have a fair amount free once again,
4125 try to set aside another reserve in case we run out once more.
4127 This is called when a relocatable block is freed in ralloc.c,
4128 and also directly from this file, in case we're not using ralloc.c. */
4131 refill_memory_reserve (void)
4133 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
4134 if (spare_memory
[0] == 0)
4135 spare_memory
[0] = malloc (SPARE_MEMORY
);
4136 if (spare_memory
[1] == 0)
4137 spare_memory
[1] = lisp_align_malloc (sizeof (struct cons_block
),
4139 if (spare_memory
[2] == 0)
4140 spare_memory
[2] = lisp_align_malloc (sizeof (struct cons_block
),
4142 if (spare_memory
[3] == 0)
4143 spare_memory
[3] = lisp_align_malloc (sizeof (struct cons_block
),
4145 if (spare_memory
[4] == 0)
4146 spare_memory
[4] = lisp_align_malloc (sizeof (struct cons_block
),
4148 if (spare_memory
[5] == 0)
4149 spare_memory
[5] = lisp_malloc (sizeof (struct string_block
),
4151 if (spare_memory
[6] == 0)
4152 spare_memory
[6] = lisp_malloc (sizeof (struct string_block
),
4154 if (spare_memory
[0] && spare_memory
[1] && spare_memory
[5])
4155 Vmemory_full
= Qnil
;
4159 /************************************************************************
4161 ************************************************************************/
4163 /* Conservative C stack marking requires a method to identify possibly
4164 live Lisp objects given a pointer value. We do this by keeping
4165 track of blocks of Lisp data that are allocated in a red-black tree
4166 (see also the comment of mem_node which is the type of nodes in
4167 that tree). Function lisp_malloc adds information for an allocated
4168 block to the red-black tree with calls to mem_insert, and function
4169 lisp_free removes it with mem_delete. Functions live_string_p etc
4170 call mem_find to lookup information about a given pointer in the
4171 tree, and use that to determine if the pointer points into a Lisp
4174 /* Initialize this part of alloc.c. */
4179 mem_z
.left
= mem_z
.right
= MEM_NIL
;
4180 mem_z
.parent
= NULL
;
4181 mem_z
.color
= MEM_BLACK
;
4182 mem_z
.start
= mem_z
.end
= NULL
;
4187 /* Value is a pointer to the mem_node containing START. Value is
4188 MEM_NIL if there is no node in the tree containing START. */
4190 static struct mem_node
*
4191 mem_find (void *start
)
4195 if (start
< min_heap_address
|| start
> max_heap_address
)
4198 /* Make the search always successful to speed up the loop below. */
4199 mem_z
.start
= start
;
4200 mem_z
.end
= (char *) start
+ 1;
4203 while (start
< p
->start
|| start
>= p
->end
)
4204 p
= start
< p
->start
? p
->left
: p
->right
;
4209 /* Insert a new node into the tree for a block of memory with start
4210 address START, end address END, and type TYPE. Value is a
4211 pointer to the node that was inserted. */
4213 static struct mem_node
*
4214 mem_insert (void *start
, void *end
, enum mem_type type
)
4216 struct mem_node
*c
, *parent
, *x
;
4218 if (min_heap_address
== NULL
|| start
< min_heap_address
)
4219 min_heap_address
= start
;
4220 if (max_heap_address
== NULL
|| end
> max_heap_address
)
4221 max_heap_address
= end
;
4223 /* See where in the tree a node for START belongs. In this
4224 particular application, it shouldn't happen that a node is already
4225 present. For debugging purposes, let's check that. */
4229 while (c
!= MEM_NIL
)
4232 c
= start
< c
->start
? c
->left
: c
->right
;
4235 /* Create a new node. */
4236 #ifdef GC_MALLOC_CHECK
4237 x
= malloc (sizeof *x
);
4241 x
= xmalloc (sizeof *x
);
4247 x
->left
= x
->right
= MEM_NIL
;
4250 /* Insert it as child of PARENT or install it as root. */
4253 if (start
< parent
->start
)
4261 /* Re-establish red-black tree properties. */
4262 mem_insert_fixup (x
);
4268 /* Re-establish the red-black properties of the tree, and thereby
4269 balance the tree, after node X has been inserted; X is always red. */
4272 mem_insert_fixup (struct mem_node
*x
)
4274 while (x
!= mem_root
&& x
->parent
->color
== MEM_RED
)
4276 /* X is red and its parent is red. This is a violation of
4277 red-black tree property #3. */
4279 if (x
->parent
== x
->parent
->parent
->left
)
4281 /* We're on the left side of our grandparent, and Y is our
4283 struct mem_node
*y
= x
->parent
->parent
->right
;
4285 if (y
->color
== MEM_RED
)
4287 /* Uncle and parent are red but should be black because
4288 X is red. Change the colors accordingly and proceed
4289 with the grandparent. */
4290 x
->parent
->color
= MEM_BLACK
;
4291 y
->color
= MEM_BLACK
;
4292 x
->parent
->parent
->color
= MEM_RED
;
4293 x
= x
->parent
->parent
;
4297 /* Parent and uncle have different colors; parent is
4298 red, uncle is black. */
4299 if (x
== x
->parent
->right
)
4302 mem_rotate_left (x
);
4305 x
->parent
->color
= MEM_BLACK
;
4306 x
->parent
->parent
->color
= MEM_RED
;
4307 mem_rotate_right (x
->parent
->parent
);
4312 /* This is the symmetrical case of above. */
4313 struct mem_node
*y
= x
->parent
->parent
->left
;
4315 if (y
->color
== MEM_RED
)
4317 x
->parent
->color
= MEM_BLACK
;
4318 y
->color
= MEM_BLACK
;
4319 x
->parent
->parent
->color
= MEM_RED
;
4320 x
= x
->parent
->parent
;
4324 if (x
== x
->parent
->left
)
4327 mem_rotate_right (x
);
4330 x
->parent
->color
= MEM_BLACK
;
4331 x
->parent
->parent
->color
= MEM_RED
;
4332 mem_rotate_left (x
->parent
->parent
);
4337 /* The root may have been changed to red due to the algorithm. Set
4338 it to black so that property #5 is satisfied. */
4339 mem_root
->color
= MEM_BLACK
;
4350 mem_rotate_left (struct mem_node
*x
)
4354 /* Turn y's left sub-tree into x's right sub-tree. */
4357 if (y
->left
!= MEM_NIL
)
4358 y
->left
->parent
= x
;
4360 /* Y's parent was x's parent. */
4362 y
->parent
= x
->parent
;
4364 /* Get the parent to point to y instead of x. */
4367 if (x
== x
->parent
->left
)
4368 x
->parent
->left
= y
;
4370 x
->parent
->right
= y
;
4375 /* Put x on y's left. */
4389 mem_rotate_right (struct mem_node
*x
)
4391 struct mem_node
*y
= x
->left
;
4394 if (y
->right
!= MEM_NIL
)
4395 y
->right
->parent
= x
;
4398 y
->parent
= x
->parent
;
4401 if (x
== x
->parent
->right
)
4402 x
->parent
->right
= y
;
4404 x
->parent
->left
= y
;
4415 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
4418 mem_delete (struct mem_node
*z
)
4420 struct mem_node
*x
, *y
;
4422 if (!z
|| z
== MEM_NIL
)
4425 if (z
->left
== MEM_NIL
|| z
->right
== MEM_NIL
)
4430 while (y
->left
!= MEM_NIL
)
4434 if (y
->left
!= MEM_NIL
)
4439 x
->parent
= y
->parent
;
4442 if (y
== y
->parent
->left
)
4443 y
->parent
->left
= x
;
4445 y
->parent
->right
= x
;
4452 z
->start
= y
->start
;
4457 if (y
->color
== MEM_BLACK
)
4458 mem_delete_fixup (x
);
4460 #ifdef GC_MALLOC_CHECK
4468 /* Re-establish the red-black properties of the tree, after a
4472 mem_delete_fixup (struct mem_node
*x
)
4474 while (x
!= mem_root
&& x
->color
== MEM_BLACK
)
4476 if (x
== x
->parent
->left
)
4478 struct mem_node
*w
= x
->parent
->right
;
4480 if (w
->color
== MEM_RED
)
4482 w
->color
= MEM_BLACK
;
4483 x
->parent
->color
= MEM_RED
;
4484 mem_rotate_left (x
->parent
);
4485 w
= x
->parent
->right
;
4488 if (w
->left
->color
== MEM_BLACK
&& w
->right
->color
== MEM_BLACK
)
4495 if (w
->right
->color
== MEM_BLACK
)
4497 w
->left
->color
= MEM_BLACK
;
4499 mem_rotate_right (w
);
4500 w
= x
->parent
->right
;
4502 w
->color
= x
->parent
->color
;
4503 x
->parent
->color
= MEM_BLACK
;
4504 w
->right
->color
= MEM_BLACK
;
4505 mem_rotate_left (x
->parent
);
4511 struct mem_node
*w
= x
->parent
->left
;
4513 if (w
->color
== MEM_RED
)
4515 w
->color
= MEM_BLACK
;
4516 x
->parent
->color
= MEM_RED
;
4517 mem_rotate_right (x
->parent
);
4518 w
= x
->parent
->left
;
4521 if (w
->right
->color
== MEM_BLACK
&& w
->left
->color
== MEM_BLACK
)
4528 if (w
->left
->color
== MEM_BLACK
)
4530 w
->right
->color
= MEM_BLACK
;
4532 mem_rotate_left (w
);
4533 w
= x
->parent
->left
;
4536 w
->color
= x
->parent
->color
;
4537 x
->parent
->color
= MEM_BLACK
;
4538 w
->left
->color
= MEM_BLACK
;
4539 mem_rotate_right (x
->parent
);
4545 x
->color
= MEM_BLACK
;
4549 /* If P is a pointer into a live Lisp string object on the heap,
4550 return the object. Otherwise, return nil. M is a pointer to the
4553 This and other *_holding functions look for a pointer anywhere into
4554 the object, not merely for a pointer to the start of the object,
4555 because some compilers sometimes optimize away the latter. See
4559 live_string_holding (struct mem_node
*m
, void *p
)
4561 if (m
->type
== MEM_TYPE_STRING
)
4563 struct string_block
*b
= m
->start
;
4565 ptrdiff_t offset
= cp
- (char *) &b
->strings
[0];
4567 /* P must point into a Lisp_String structure, and it
4568 must not be on the free-list. */
4569 if (0 <= offset
&& offset
< STRING_BLOCK_SIZE
* sizeof b
->strings
[0])
4571 cp
= ptr_bounds_copy (cp
, b
);
4572 struct Lisp_String
*s
= p
= cp
-= offset
% sizeof b
->strings
[0];
4574 return make_lisp_ptr (s
, Lisp_String
);
4581 live_string_p (struct mem_node
*m
, void *p
)
4583 return !NILP (live_string_holding (m
, p
));
4586 /* If P is a pointer into a live Lisp cons object on the heap, return
4587 the object. Otherwise, return nil. M is a pointer to the
4591 live_cons_holding (struct mem_node
*m
, void *p
)
4593 if (m
->type
== MEM_TYPE_CONS
)
4595 struct cons_block
*b
= m
->start
;
4597 ptrdiff_t offset
= cp
- (char *) &b
->conses
[0];
4599 /* P must point into a Lisp_Cons, not be
4600 one of the unused cells in the current cons block,
4601 and not be on the free-list. */
4602 if (0 <= offset
&& offset
< CONS_BLOCK_SIZE
* sizeof b
->conses
[0]
4604 || offset
/ sizeof b
->conses
[0] < cons_block_index
))
4606 cp
= ptr_bounds_copy (cp
, b
);
4607 struct Lisp_Cons
*s
= p
= cp
-= offset
% sizeof b
->conses
[0];
4608 if (!EQ (s
->u
.s
.car
, Vdead
))
4609 return make_lisp_ptr (s
, Lisp_Cons
);
4616 live_cons_p (struct mem_node
*m
, void *p
)
4618 return !NILP (live_cons_holding (m
, p
));
4622 /* If P is a pointer into a live Lisp symbol object on the heap,
4623 return the object. Otherwise, return nil. M is a pointer to the
4627 live_symbol_holding (struct mem_node
*m
, void *p
)
4629 if (m
->type
== MEM_TYPE_SYMBOL
)
4631 struct symbol_block
*b
= m
->start
;
4633 ptrdiff_t offset
= cp
- (char *) &b
->symbols
[0];
4635 /* P must point into the Lisp_Symbol, not be
4636 one of the unused cells in the current symbol block,
4637 and not be on the free-list. */
4638 if (0 <= offset
&& offset
< SYMBOL_BLOCK_SIZE
* sizeof b
->symbols
[0]
4639 && (b
!= symbol_block
4640 || offset
/ sizeof b
->symbols
[0] < symbol_block_index
))
4642 cp
= ptr_bounds_copy (cp
, b
);
4643 struct Lisp_Symbol
*s
= p
= cp
-= offset
% sizeof b
->symbols
[0];
4644 if (!EQ (s
->u
.s
.function
, Vdead
))
4645 return make_lisp_symbol (s
);
4652 live_symbol_p (struct mem_node
*m
, void *p
)
4654 return !NILP (live_symbol_holding (m
, p
));
4658 /* Return true if P is a pointer to a live Lisp float on
4659 the heap. M is a pointer to the mem_block for P. */
4662 live_float_p (struct mem_node
*m
, void *p
)
4664 if (m
->type
== MEM_TYPE_FLOAT
)
4666 struct float_block
*b
= m
->start
;
4668 ptrdiff_t offset
= cp
- (char *) &b
->floats
[0];
4670 /* P must point to the start of a Lisp_Float and not be
4671 one of the unused cells in the current float block. */
4673 && offset
% sizeof b
->floats
[0] == 0
4674 && offset
< (FLOAT_BLOCK_SIZE
* sizeof b
->floats
[0])
4675 && (b
!= float_block
4676 || offset
/ sizeof b
->floats
[0] < float_block_index
));
4683 /* If P is a pointer to a live Lisp Misc on the heap, return the object.
4684 Otherwise, return nil. M is a pointer to the mem_block for P. */
4687 live_misc_holding (struct mem_node
*m
, void *p
)
4689 if (m
->type
== MEM_TYPE_MISC
)
4691 struct marker_block
*b
= m
->start
;
4693 ptrdiff_t offset
= cp
- (char *) &b
->markers
[0];
4695 /* P must point into a Lisp_Misc, not be
4696 one of the unused cells in the current misc block,
4697 and not be on the free-list. */
4698 if (0 <= offset
&& offset
< MARKER_BLOCK_SIZE
* sizeof b
->markers
[0]
4699 && (b
!= marker_block
4700 || offset
/ sizeof b
->markers
[0] < marker_block_index
))
4702 cp
= ptr_bounds_copy (cp
, b
);
4703 union Lisp_Misc
*s
= p
= cp
-= offset
% sizeof b
->markers
[0];
4704 if (s
->u_any
.type
!= Lisp_Misc_Free
)
4705 return make_lisp_ptr (s
, Lisp_Misc
);
4712 live_misc_p (struct mem_node
*m
, void *p
)
4714 return !NILP (live_misc_holding (m
, p
));
4717 /* If P is a pointer to a live vector-like object, return the object.
4718 Otherwise, return nil.
4719 M is a pointer to the mem_block for P. */
4722 live_vector_holding (struct mem_node
*m
, void *p
)
4724 struct Lisp_Vector
*vp
= p
;
4726 if (m
->type
== MEM_TYPE_VECTOR_BLOCK
)
4728 /* This memory node corresponds to a vector block. */
4729 struct vector_block
*block
= m
->start
;
4730 struct Lisp_Vector
*vector
= (struct Lisp_Vector
*) block
->data
;
4732 /* P is in the block's allocation range. Scan the block
4733 up to P and see whether P points to the start of some
4734 vector which is not on a free list. FIXME: check whether
4735 some allocation patterns (probably a lot of short vectors)
4736 may cause a substantial overhead of this loop. */
4737 while (VECTOR_IN_BLOCK (vector
, block
) && vector
<= vp
)
4739 struct Lisp_Vector
*next
= ADVANCE (vector
, vector_nbytes (vector
));
4740 if (vp
< next
&& !PSEUDOVECTOR_TYPEP (&vector
->header
, PVEC_FREE
))
4741 return make_lisp_ptr (vector
, Lisp_Vectorlike
);
4745 else if (m
->type
== MEM_TYPE_VECTORLIKE
)
4747 /* This memory node corresponds to a large vector. */
4748 struct Lisp_Vector
*vector
= large_vector_vec (m
->start
);
4749 struct Lisp_Vector
*next
= ADVANCE (vector
, vector_nbytes (vector
));
4750 if (vector
<= vp
&& vp
< next
)
4751 return make_lisp_ptr (vector
, Lisp_Vectorlike
);
4757 live_vector_p (struct mem_node
*m
, void *p
)
4759 return !NILP (live_vector_holding (m
, p
));
4762 /* If P is a pointer into a live buffer, return the buffer.
4763 Otherwise, return nil. M is a pointer to the mem_block for P. */
4766 live_buffer_holding (struct mem_node
*m
, void *p
)
4768 /* P must point into the block, and the buffer
4769 must not have been killed. */
4770 if (m
->type
== MEM_TYPE_BUFFER
)
4772 struct buffer
*b
= m
->start
;
4773 char *cb
= m
->start
;
4775 ptrdiff_t offset
= cp
- cb
;
4776 if (0 <= offset
&& offset
< sizeof *b
&& !NILP (b
->name_
))
4779 XSETBUFFER (obj
, b
);
4787 live_buffer_p (struct mem_node
*m
, void *p
)
4789 return !NILP (live_buffer_holding (m
, p
));
4792 /* Mark OBJ if we can prove it's a Lisp_Object. */
4795 mark_maybe_object (Lisp_Object obj
)
4799 VALGRIND_MAKE_MEM_DEFINED (&obj
, sizeof (obj
));
4805 void *po
= XPNTR (obj
);
4806 struct mem_node
*m
= mem_find (po
);
4810 bool mark_p
= false;
4812 switch (XTYPE (obj
))
4815 mark_p
= EQ (obj
, live_string_holding (m
, po
));
4819 mark_p
= EQ (obj
, live_cons_holding (m
, po
));
4823 mark_p
= EQ (obj
, live_symbol_holding (m
, po
));
4827 mark_p
= live_float_p (m
, po
);
4830 case Lisp_Vectorlike
:
4831 mark_p
= (EQ (obj
, live_vector_holding (m
, po
))
4832 || EQ (obj
, live_buffer_holding (m
, po
)));
4836 mark_p
= EQ (obj
, live_misc_holding (m
, po
));
4848 /* Return true if P can point to Lisp data, and false otherwise.
4849 Symbols are implemented via offsets not pointers, but the offsets
4850 are also multiples of GCALIGNMENT. */
4853 maybe_lisp_pointer (void *p
)
4855 return (uintptr_t) p
% GCALIGNMENT
== 0;
4858 #ifndef HAVE_MODULES
4859 enum { HAVE_MODULES
= false };
4862 /* If P points to Lisp data, mark that as live if it isn't already
4866 mark_maybe_pointer (void *p
)
4872 VALGRIND_MAKE_MEM_DEFINED (&p
, sizeof (p
));
4875 if (sizeof (Lisp_Object
) == sizeof (void *) || !HAVE_MODULES
)
4877 if (!maybe_lisp_pointer (p
))
4882 /* For the wide-int case, also mark emacs_value tagged pointers,
4883 which can be generated by emacs-module.c's value_to_lisp. */
4884 p
= (void *) ((uintptr_t) p
& ~(GCALIGNMENT
- 1));
4890 Lisp_Object obj
= Qnil
;
4894 case MEM_TYPE_NON_LISP
:
4895 case MEM_TYPE_SPARE
:
4896 /* Nothing to do; not a pointer to Lisp memory. */
4899 case MEM_TYPE_BUFFER
:
4900 obj
= live_buffer_holding (m
, p
);
4904 obj
= live_cons_holding (m
, p
);
4907 case MEM_TYPE_STRING
:
4908 obj
= live_string_holding (m
, p
);
4912 obj
= live_misc_holding (m
, p
);
4915 case MEM_TYPE_SYMBOL
:
4916 obj
= live_symbol_holding (m
, p
);
4919 case MEM_TYPE_FLOAT
:
4920 if (live_float_p (m
, p
))
4921 obj
= make_lisp_ptr (p
, Lisp_Float
);
4924 case MEM_TYPE_VECTORLIKE
:
4925 case MEM_TYPE_VECTOR_BLOCK
:
4926 obj
= live_vector_holding (m
, p
);
4939 /* Alignment of pointer values. Use alignof, as it sometimes returns
4940 a smaller alignment than GCC's __alignof__ and mark_memory might
4941 miss objects if __alignof__ were used. */
4942 #define GC_POINTER_ALIGNMENT alignof (void *)
4944 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4945 or END+OFFSET..START. */
4947 static void ATTRIBUTE_NO_SANITIZE_ADDRESS
4948 mark_memory (void *start
, void *end
)
4952 /* Make START the pointer to the start of the memory region,
4953 if it isn't already. */
4961 eassert (((uintptr_t) start
) % GC_POINTER_ALIGNMENT
== 0);
4963 /* Mark Lisp data pointed to. This is necessary because, in some
4964 situations, the C compiler optimizes Lisp objects away, so that
4965 only a pointer to them remains. Example:
4967 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4970 Lisp_Object obj = build_string ("test");
4971 struct Lisp_String *s = XSTRING (obj);
4972 Fgarbage_collect ();
4973 fprintf (stderr, "test '%s'\n", s->u.s.data);
4977 Here, `obj' isn't really used, and the compiler optimizes it
4978 away. The only reference to the life string is through the
4981 for (pp
= start
; (void *) pp
< end
; pp
+= GC_POINTER_ALIGNMENT
)
4983 mark_maybe_pointer (*(void **) pp
);
4984 mark_maybe_object (*(Lisp_Object
*) pp
);
4988 #ifndef HAVE___BUILTIN_UNWIND_INIT
4990 # ifdef GC_SETJMP_WORKS
4997 static bool setjmp_tested_p
;
4998 static int longjmps_done
;
5000 # define SETJMP_WILL_LIKELY_WORK "\
5002 Emacs garbage collector has been changed to use conservative stack\n\
5003 marking. Emacs has determined that the method it uses to do the\n\
5004 marking will likely work on your system, but this isn't sure.\n\
5006 If you are a system-programmer, or can get the help of a local wizard\n\
5007 who is, please take a look at the function mark_stack in alloc.c, and\n\
5008 verify that the methods used are appropriate for your system.\n\
5010 Please mail the result to <emacs-devel@gnu.org>.\n\
5013 # define SETJMP_WILL_NOT_WORK "\
5015 Emacs garbage collector has been changed to use conservative stack\n\
5016 marking. Emacs has determined that the default method it uses to do the\n\
5017 marking will not work on your system. We will need a system-dependent\n\
5018 solution for your system.\n\
5020 Please take a look at the function mark_stack in alloc.c, and\n\
5021 try to find a way to make it work on your system.\n\
5023 Note that you may get false negatives, depending on the compiler.\n\
5024 In particular, you need to use -O with GCC for this test.\n\
5026 Please mail the result to <emacs-devel@gnu.org>.\n\
5030 /* Perform a quick check if it looks like setjmp saves registers in a
5031 jmp_buf. Print a message to stderr saying so. When this test
5032 succeeds, this is _not_ a proof that setjmp is sufficient for
5033 conservative stack marking. Only the sources or a disassembly
5039 if (setjmp_tested_p
)
5041 setjmp_tested_p
= true;
5046 /* Arrange for X to be put in a register. */
5052 if (longjmps_done
== 1)
5054 /* Came here after the longjmp at the end of the function.
5056 If x == 1, the longjmp has restored the register to its
5057 value before the setjmp, and we can hope that setjmp
5058 saves all such registers in the jmp_buf, although that
5061 For other values of X, either something really strange is
5062 taking place, or the setjmp just didn't save the register. */
5065 fprintf (stderr
, SETJMP_WILL_LIKELY_WORK
);
5068 fprintf (stderr
, SETJMP_WILL_NOT_WORK
);
5075 if (longjmps_done
== 1)
5076 sys_longjmp (jbuf
, 1);
5078 # endif /* ! GC_SETJMP_WORKS */
5079 #endif /* ! HAVE___BUILTIN_UNWIND_INIT */
5081 /* The type of an object near the stack top, whose address can be used
5082 as a stack scan limit. */
5085 /* Align the stack top properly. Even if !HAVE___BUILTIN_UNWIND_INIT,
5086 jmp_buf may not be aligned enough on darwin-ppc64. */
5088 #ifndef HAVE___BUILTIN_UNWIND_INIT
5094 /* Force callee-saved registers and register windows onto the stack.
5095 Use the platform-defined __builtin_unwind_init if available,
5096 obviating the need for machine dependent methods. */
5097 #ifndef HAVE___BUILTIN_UNWIND_INIT
5099 /* This trick flushes the register windows so that all the state of
5100 the process is contained in the stack.
5101 FreeBSD does not have a ta 3 handler, so handle it specially.
5102 FIXME: Code in the Boehm GC suggests flushing (with 'flushrs') is
5103 needed on ia64 too. See mach_dep.c, where it also says inline
5104 assembler doesn't work with relevant proprietary compilers. */
5105 # if defined __sparc64__ && defined __FreeBSD__
5106 # define __builtin_unwind_init() asm ("flushw")
5108 # define __builtin_unwind_init() asm ("ta 3")
5111 # define __builtin_unwind_init() ((void) 0)
5115 /* Yield an address close enough to the top of the stack that the
5116 garbage collector need not scan above it. Callers should be
5117 declared NO_INLINE. */
5118 #ifdef HAVE___BUILTIN_FRAME_ADDRESS
5119 # define NEAR_STACK_TOP(addr) ((void) (addr), __builtin_frame_address (0))
5121 # define NEAR_STACK_TOP(addr) (addr)
5124 /* Set *P to the address of the top of the stack. This must be a
5125 macro, not a function, so that it is executed in the caller’s
5126 environment. It is not inside a do-while so that its storage
5127 survives the macro. Callers should be declared NO_INLINE. */
5128 #ifdef HAVE___BUILTIN_UNWIND_INIT
5129 # define SET_STACK_TOP_ADDRESS(p) \
5130 stacktop_sentry sentry; \
5131 __builtin_unwind_init (); \
5132 *(p) = NEAR_STACK_TOP (&sentry)
5134 # define SET_STACK_TOP_ADDRESS(p) \
5135 stacktop_sentry sentry; \
5136 __builtin_unwind_init (); \
5138 sys_setjmp (sentry.j); \
5139 *(p) = NEAR_STACK_TOP (&sentry + (stack_bottom < &sentry.c))
5142 /* Mark live Lisp objects on the C stack.
5144 There are several system-dependent problems to consider when
5145 porting this to new architectures:
5149 We have to mark Lisp objects in CPU registers that can hold local
5150 variables or are used to pass parameters.
5152 This code assumes that calling setjmp saves registers we need
5153 to see in a jmp_buf which itself lies on the stack. This doesn't
5154 have to be true! It must be verified for each system, possibly
5155 by taking a look at the source code of setjmp.
5157 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
5158 can use it as a machine independent method to store all registers
5159 to the stack. In this case the macros described in the previous
5160 two paragraphs are not used.
5164 Architectures differ in the way their processor stack is organized.
5165 For example, the stack might look like this
5168 | Lisp_Object | size = 4
5170 | something else | size = 2
5172 | Lisp_Object | size = 4
5176 In such a case, not every Lisp_Object will be aligned equally. To
5177 find all Lisp_Object on the stack it won't be sufficient to walk
5178 the stack in steps of 4 bytes. Instead, two passes will be
5179 necessary, one starting at the start of the stack, and a second
5180 pass starting at the start of the stack + 2. Likewise, if the
5181 minimal alignment of Lisp_Objects on the stack is 1, four passes
5182 would be necessary, each one starting with one byte more offset
5183 from the stack start. */
5186 mark_stack (char *bottom
, char *end
)
5188 /* This assumes that the stack is a contiguous region in memory. If
5189 that's not the case, something has to be done here to iterate
5190 over the stack segments. */
5191 mark_memory (bottom
, end
);
5193 /* Allow for marking a secondary stack, like the register stack on the
5195 #ifdef GC_MARK_SECONDARY_STACK
5196 GC_MARK_SECONDARY_STACK ();
5200 /* This is a trampoline function that flushes registers to the stack,
5201 and then calls FUNC. ARG is passed through to FUNC verbatim.
5203 This function must be called whenever Emacs is about to release the
5204 global interpreter lock. This lets the garbage collector easily
5205 find roots in registers on threads that are not actively running
5208 It is invalid to run any Lisp code or to allocate any GC memory
5212 flush_stack_call_func (void (*func
) (void *arg
), void *arg
)
5215 struct thread_state
*self
= current_thread
;
5216 SET_STACK_TOP_ADDRESS (&end
);
5217 self
->stack_top
= end
;
5219 eassert (current_thread
== self
);
5223 c_symbol_p (struct Lisp_Symbol
*sym
)
5225 char *lispsym_ptr
= (char *) lispsym
;
5226 char *sym_ptr
= (char *) sym
;
5227 ptrdiff_t lispsym_offset
= sym_ptr
- lispsym_ptr
;
5228 return 0 <= lispsym_offset
&& lispsym_offset
< sizeof lispsym
;
5231 /* Determine whether it is safe to access memory at address P. */
5233 valid_pointer_p (void *p
)
5236 return w32_valid_pointer_p (p
, 16);
5239 if (ADDRESS_SANITIZER
)
5244 /* Obviously, we cannot just access it (we would SEGV trying), so we
5245 trick the o/s to tell us whether p is a valid pointer.
5246 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
5247 not validate p in that case. */
5249 if (emacs_pipe (fd
) == 0)
5251 bool valid
= emacs_write (fd
[1], p
, 16) == 16;
5252 emacs_close (fd
[1]);
5253 emacs_close (fd
[0]);
5261 /* Return 2 if OBJ is a killed or special buffer object, 1 if OBJ is a
5262 valid lisp object, 0 if OBJ is NOT a valid lisp object, or -1 if we
5263 cannot validate OBJ. This function can be quite slow, so its primary
5264 use is the manual debugging. The only exception is print_object, where
5265 we use it to check whether the memory referenced by the pointer of
5266 Lisp_Save_Value object contains valid objects. */
5269 valid_lisp_object_p (Lisp_Object obj
)
5274 void *p
= XPNTR (obj
);
5278 if (SYMBOLP (obj
) && c_symbol_p (p
))
5279 return ((char *) p
- (char *) lispsym
) % sizeof lispsym
[0] == 0;
5281 if (p
== &buffer_defaults
|| p
== &buffer_local_symbols
)
5284 struct mem_node
*m
= mem_find (p
);
5288 int valid
= valid_pointer_p (p
);
5300 case MEM_TYPE_NON_LISP
:
5301 case MEM_TYPE_SPARE
:
5304 case MEM_TYPE_BUFFER
:
5305 return live_buffer_p (m
, p
) ? 1 : 2;
5308 return live_cons_p (m
, p
);
5310 case MEM_TYPE_STRING
:
5311 return live_string_p (m
, p
);
5314 return live_misc_p (m
, p
);
5316 case MEM_TYPE_SYMBOL
:
5317 return live_symbol_p (m
, p
);
5319 case MEM_TYPE_FLOAT
:
5320 return live_float_p (m
, p
);
5322 case MEM_TYPE_VECTORLIKE
:
5323 case MEM_TYPE_VECTOR_BLOCK
:
5324 return live_vector_p (m
, p
);
5333 /***********************************************************************
5334 Pure Storage Management
5335 ***********************************************************************/
5337 /* Allocate room for SIZE bytes from pure Lisp storage and return a
5338 pointer to it. TYPE is the Lisp type for which the memory is
5339 allocated. TYPE < 0 means it's not used for a Lisp object. */
5342 pure_alloc (size_t size
, int type
)
5349 /* Allocate space for a Lisp object from the beginning of the free
5350 space with taking account of alignment. */
5351 result
= pointer_align (purebeg
+ pure_bytes_used_lisp
, GCALIGNMENT
);
5352 pure_bytes_used_lisp
= ((char *)result
- (char *)purebeg
) + size
;
5356 /* Allocate space for a non-Lisp object from the end of the free
5358 pure_bytes_used_non_lisp
+= size
;
5359 result
= purebeg
+ pure_size
- pure_bytes_used_non_lisp
;
5361 pure_bytes_used
= pure_bytes_used_lisp
+ pure_bytes_used_non_lisp
;
5363 if (pure_bytes_used
<= pure_size
)
5364 return ptr_bounds_clip (result
, size
);
5366 /* Don't allocate a large amount here,
5367 because it might get mmap'd and then its address
5368 might not be usable. */
5369 purebeg
= xmalloc (10000);
5371 pure_bytes_used_before_overflow
+= pure_bytes_used
- size
;
5372 pure_bytes_used
= 0;
5373 pure_bytes_used_lisp
= pure_bytes_used_non_lisp
= 0;
5380 /* Print a warning if PURESIZE is too small. */
5383 check_pure_size (void)
5385 if (pure_bytes_used_before_overflow
)
5386 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI
"d"
5388 pure_bytes_used
+ pure_bytes_used_before_overflow
);
5393 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
5394 the non-Lisp data pool of the pure storage, and return its start
5395 address. Return NULL if not found. */
5398 find_string_data_in_pure (const char *data
, ptrdiff_t nbytes
)
5401 ptrdiff_t skip
, bm_skip
[256], last_char_skip
, infinity
, start
, start_max
;
5402 const unsigned char *p
;
5405 if (pure_bytes_used_non_lisp
<= nbytes
)
5408 /* Set up the Boyer-Moore table. */
5410 for (i
= 0; i
< 256; i
++)
5413 p
= (const unsigned char *) data
;
5415 bm_skip
[*p
++] = skip
;
5417 last_char_skip
= bm_skip
['\0'];
5419 non_lisp_beg
= purebeg
+ pure_size
- pure_bytes_used_non_lisp
;
5420 start_max
= pure_bytes_used_non_lisp
- (nbytes
+ 1);
5422 /* See the comments in the function `boyer_moore' (search.c) for the
5423 use of `infinity'. */
5424 infinity
= pure_bytes_used_non_lisp
+ 1;
5425 bm_skip
['\0'] = infinity
;
5427 p
= (const unsigned char *) non_lisp_beg
+ nbytes
;
5431 /* Check the last character (== '\0'). */
5434 start
+= bm_skip
[*(p
+ start
)];
5436 while (start
<= start_max
);
5438 if (start
< infinity
)
5439 /* Couldn't find the last character. */
5442 /* No less than `infinity' means we could find the last
5443 character at `p[start - infinity]'. */
5446 /* Check the remaining characters. */
5447 if (memcmp (data
, non_lisp_beg
+ start
, nbytes
) == 0)
5449 return ptr_bounds_clip (non_lisp_beg
+ start
, nbytes
+ 1);
5451 start
+= last_char_skip
;
5453 while (start
<= start_max
);
5459 /* Return a string allocated in pure space. DATA is a buffer holding
5460 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
5461 means make the result string multibyte.
5463 Must get an error if pure storage is full, since if it cannot hold
5464 a large string it may be able to hold conses that point to that
5465 string; then the string is not protected from gc. */
5468 make_pure_string (const char *data
,
5469 ptrdiff_t nchars
, ptrdiff_t nbytes
, bool multibyte
)
5472 struct Lisp_String
*s
= pure_alloc (sizeof *s
, Lisp_String
);
5473 s
->u
.s
.data
= (unsigned char *) find_string_data_in_pure (data
, nbytes
);
5474 if (s
->u
.s
.data
== NULL
)
5476 s
->u
.s
.data
= pure_alloc (nbytes
+ 1, -1);
5477 memcpy (s
->u
.s
.data
, data
, nbytes
);
5478 s
->u
.s
.data
[nbytes
] = '\0';
5480 s
->u
.s
.size
= nchars
;
5481 s
->u
.s
.size_byte
= multibyte
? nbytes
: -1;
5482 s
->u
.s
.intervals
= NULL
;
5483 XSETSTRING (string
, s
);
5487 /* Return a string allocated in pure space. Do not
5488 allocate the string data, just point to DATA. */
5491 make_pure_c_string (const char *data
, ptrdiff_t nchars
)
5494 struct Lisp_String
*s
= pure_alloc (sizeof *s
, Lisp_String
);
5495 s
->u
.s
.size
= nchars
;
5496 s
->u
.s
.size_byte
= -1;
5497 s
->u
.s
.data
= (unsigned char *) data
;
5498 s
->u
.s
.intervals
= NULL
;
5499 XSETSTRING (string
, s
);
5503 static Lisp_Object
purecopy (Lisp_Object obj
);
5505 /* Return a cons allocated from pure space. Give it pure copies
5506 of CAR as car and CDR as cdr. */
5509 pure_cons (Lisp_Object car
, Lisp_Object cdr
)
5512 struct Lisp_Cons
*p
= pure_alloc (sizeof *p
, Lisp_Cons
);
5514 XSETCAR (new, purecopy (car
));
5515 XSETCDR (new, purecopy (cdr
));
5520 /* Value is a float object with value NUM allocated from pure space. */
5523 make_pure_float (double num
)
5526 struct Lisp_Float
*p
= pure_alloc (sizeof *p
, Lisp_Float
);
5528 XFLOAT_INIT (new, num
);
5533 /* Return a vector with room for LEN Lisp_Objects allocated from
5537 make_pure_vector (ptrdiff_t len
)
5540 size_t size
= header_size
+ len
* word_size
;
5541 struct Lisp_Vector
*p
= pure_alloc (size
, Lisp_Vectorlike
);
5542 XSETVECTOR (new, p
);
5543 XVECTOR (new)->header
.size
= len
;
5547 /* Copy all contents and parameters of TABLE to a new table allocated
5548 from pure space, return the purified table. */
5549 static struct Lisp_Hash_Table
*
5550 purecopy_hash_table (struct Lisp_Hash_Table
*table
)
5552 eassert (NILP (table
->weak
));
5553 eassert (table
->pure
);
5555 struct Lisp_Hash_Table
*pure
= pure_alloc (sizeof *pure
, Lisp_Vectorlike
);
5556 struct hash_table_test pure_test
= table
->test
;
5558 /* Purecopy the hash table test. */
5559 pure_test
.name
= purecopy (table
->test
.name
);
5560 pure_test
.user_hash_function
= purecopy (table
->test
.user_hash_function
);
5561 pure_test
.user_cmp_function
= purecopy (table
->test
.user_cmp_function
);
5563 pure
->header
= table
->header
;
5564 pure
->weak
= purecopy (Qnil
);
5565 pure
->hash
= purecopy (table
->hash
);
5566 pure
->next
= purecopy (table
->next
);
5567 pure
->index
= purecopy (table
->index
);
5568 pure
->count
= table
->count
;
5569 pure
->next_free
= table
->next_free
;
5570 pure
->pure
= table
->pure
;
5571 pure
->rehash_threshold
= table
->rehash_threshold
;
5572 pure
->rehash_size
= table
->rehash_size
;
5573 pure
->key_and_value
= purecopy (table
->key_and_value
);
5574 pure
->test
= pure_test
;
5579 DEFUN ("purecopy", Fpurecopy
, Spurecopy
, 1, 1, 0,
5580 doc
: /* Make a copy of object OBJ in pure storage.
5581 Recursively copies contents of vectors and cons cells.
5582 Does not copy symbols. Copies strings without text properties. */)
5583 (register Lisp_Object obj
)
5585 if (NILP (Vpurify_flag
))
5587 else if (MARKERP (obj
) || OVERLAYP (obj
) || SYMBOLP (obj
))
5588 /* Can't purify those. */
5591 return purecopy (obj
);
5594 /* Pinned objects are marked before every GC cycle. */
5595 static struct pinned_object
5598 struct pinned_object
*next
;
5602 purecopy (Lisp_Object obj
)
5605 || (! SYMBOLP (obj
) && PURE_P (XPNTR (obj
)))
5607 return obj
; /* Already pure. */
5609 if (STRINGP (obj
) && XSTRING (obj
)->u
.s
.intervals
)
5610 message_with_string ("Dropping text-properties while making string `%s' pure",
5613 if (HASH_TABLE_P (Vpurify_flag
)) /* Hash consing. */
5615 Lisp_Object tmp
= Fgethash (obj
, Vpurify_flag
, Qnil
);
5621 obj
= pure_cons (XCAR (obj
), XCDR (obj
));
5622 else if (FLOATP (obj
))
5623 obj
= make_pure_float (XFLOAT_DATA (obj
));
5624 else if (STRINGP (obj
))
5625 obj
= make_pure_string (SSDATA (obj
), SCHARS (obj
),
5627 STRING_MULTIBYTE (obj
));
5628 else if (HASH_TABLE_P (obj
))
5630 struct Lisp_Hash_Table
*table
= XHASH_TABLE (obj
);
5631 /* Do not purify hash tables which haven't been defined with
5632 :purecopy as non-nil or are weak - they aren't guaranteed to
5634 if (!NILP (table
->weak
) || !table
->pure
)
5636 /* Instead, add the hash table to the list of pinned objects,
5637 so that it will be marked during GC. */
5638 struct pinned_object
*o
= xmalloc (sizeof *o
);
5640 o
->next
= pinned_objects
;
5642 return obj
; /* Don't hash cons it. */
5645 struct Lisp_Hash_Table
*h
= purecopy_hash_table (table
);
5646 XSET_HASH_TABLE (obj
, h
);
5648 else if (COMPILEDP (obj
) || VECTORP (obj
) || RECORDP (obj
))
5650 struct Lisp_Vector
*objp
= XVECTOR (obj
);
5651 ptrdiff_t nbytes
= vector_nbytes (objp
);
5652 struct Lisp_Vector
*vec
= pure_alloc (nbytes
, Lisp_Vectorlike
);
5653 register ptrdiff_t i
;
5654 ptrdiff_t size
= ASIZE (obj
);
5655 if (size
& PSEUDOVECTOR_FLAG
)
5656 size
&= PSEUDOVECTOR_SIZE_MASK
;
5657 memcpy (vec
, objp
, nbytes
);
5658 for (i
= 0; i
< size
; i
++)
5659 vec
->contents
[i
] = purecopy (vec
->contents
[i
]);
5660 XSETVECTOR (obj
, vec
);
5662 else if (SYMBOLP (obj
))
5664 if (!XSYMBOL (obj
)->u
.s
.pinned
&& !c_symbol_p (XSYMBOL (obj
)))
5665 { /* We can't purify them, but they appear in many pure objects.
5666 Mark them as `pinned' so we know to mark them at every GC cycle. */
5667 XSYMBOL (obj
)->u
.s
.pinned
= true;
5668 symbol_block_pinned
= symbol_block
;
5670 /* Don't hash-cons it. */
5675 AUTO_STRING (fmt
, "Don't know how to purify: %S");
5676 Fsignal (Qerror
, list1 (CALLN (Fformat
, fmt
, obj
)));
5679 if (HASH_TABLE_P (Vpurify_flag
)) /* Hash consing. */
5680 Fputhash (obj
, obj
, Vpurify_flag
);
5687 /***********************************************************************
5689 ***********************************************************************/
5691 /* Put an entry in staticvec, pointing at the variable with address
5695 staticpro (Lisp_Object
*varaddress
)
5697 if (staticidx
>= NSTATICS
)
5698 fatal ("NSTATICS too small; try increasing and recompiling Emacs.");
5699 staticvec
[staticidx
++] = varaddress
;
5703 /***********************************************************************
5705 ***********************************************************************/
5707 /* Temporarily prevent garbage collection. */
5710 inhibit_garbage_collection (void)
5712 ptrdiff_t count
= SPECPDL_INDEX ();
5714 specbind (Qgc_cons_threshold
, make_number (MOST_POSITIVE_FIXNUM
));
5718 /* Used to avoid possible overflows when
5719 converting from C to Lisp integers. */
5722 bounded_number (EMACS_INT number
)
5724 return make_number (min (MOST_POSITIVE_FIXNUM
, number
));
5727 /* Calculate total bytes of live objects. */
5730 total_bytes_of_live_objects (void)
5733 tot
+= total_conses
* sizeof (struct Lisp_Cons
);
5734 tot
+= total_symbols
* sizeof (struct Lisp_Symbol
);
5735 tot
+= total_markers
* sizeof (union Lisp_Misc
);
5736 tot
+= total_string_bytes
;
5737 tot
+= total_vector_slots
* word_size
;
5738 tot
+= total_floats
* sizeof (struct Lisp_Float
);
5739 tot
+= total_intervals
* sizeof (struct interval
);
5740 tot
+= total_strings
* sizeof (struct Lisp_String
);
5744 #ifdef HAVE_WINDOW_SYSTEM
5746 /* Remove unmarked font-spec and font-entity objects from ENTRY, which is
5747 (DRIVER-TYPE NUM-FRAMES FONT-CACHE-DATA ...), and return changed entry. */
5750 compact_font_cache_entry (Lisp_Object entry
)
5752 Lisp_Object tail
, *prev
= &entry
;
5754 for (tail
= entry
; CONSP (tail
); tail
= XCDR (tail
))
5757 Lisp_Object obj
= XCAR (tail
);
5759 /* Consider OBJ if it is (font-spec . [font-entity font-entity ...]). */
5760 if (CONSP (obj
) && GC_FONT_SPEC_P (XCAR (obj
))
5761 && !VECTOR_MARKED_P (GC_XFONT_SPEC (XCAR (obj
)))
5762 /* Don't use VECTORP here, as that calls ASIZE, which could
5763 hit assertion violation during GC. */
5764 && (VECTORLIKEP (XCDR (obj
))
5765 && ! (gc_asize (XCDR (obj
)) & PSEUDOVECTOR_FLAG
)))
5767 ptrdiff_t i
, size
= gc_asize (XCDR (obj
));
5768 Lisp_Object obj_cdr
= XCDR (obj
);
5770 /* If font-spec is not marked, most likely all font-entities
5771 are not marked too. But we must be sure that nothing is
5772 marked within OBJ before we really drop it. */
5773 for (i
= 0; i
< size
; i
++)
5775 Lisp_Object objlist
;
5777 if (VECTOR_MARKED_P (GC_XFONT_ENTITY (AREF (obj_cdr
, i
))))
5780 objlist
= AREF (AREF (obj_cdr
, i
), FONT_OBJLIST_INDEX
);
5781 for (; CONSP (objlist
); objlist
= XCDR (objlist
))
5783 Lisp_Object val
= XCAR (objlist
);
5784 struct font
*font
= GC_XFONT_OBJECT (val
);
5786 if (!NILP (AREF (val
, FONT_TYPE_INDEX
))
5787 && VECTOR_MARKED_P(font
))
5790 if (CONSP (objlist
))
5792 /* Found a marked font, bail out. */
5799 /* No marked fonts were found, so this entire font
5800 entity can be dropped. */
5805 *prev
= XCDR (tail
);
5807 prev
= xcdr_addr (tail
);
5812 /* Compact font caches on all terminals and mark
5813 everything which is still here after compaction. */
5816 compact_font_caches (void)
5820 for (t
= terminal_list
; t
; t
= t
->next_terminal
)
5822 Lisp_Object cache
= TERMINAL_FONT_CACHE (t
);
5823 /* Inhibit compacting the caches if the user so wishes. Some of
5824 the users don't mind a larger memory footprint, but do mind
5825 slower redisplay. */
5826 if (!inhibit_compacting_font_caches
5831 for (entry
= XCDR (cache
); CONSP (entry
); entry
= XCDR (entry
))
5832 XSETCAR (entry
, compact_font_cache_entry (XCAR (entry
)));
5834 mark_object (cache
);
5838 #else /* not HAVE_WINDOW_SYSTEM */
5840 #define compact_font_caches() (void)(0)
5842 #endif /* HAVE_WINDOW_SYSTEM */
5844 /* Remove (MARKER . DATA) entries with unmarked MARKER
5845 from buffer undo LIST and return changed list. */
5848 compact_undo_list (Lisp_Object list
)
5850 Lisp_Object tail
, *prev
= &list
;
5852 for (tail
= list
; CONSP (tail
); tail
= XCDR (tail
))
5854 if (CONSP (XCAR (tail
))
5855 && MARKERP (XCAR (XCAR (tail
)))
5856 && !XMARKER (XCAR (XCAR (tail
)))->gcmarkbit
)
5857 *prev
= XCDR (tail
);
5859 prev
= xcdr_addr (tail
);
5865 mark_pinned_objects (void)
5867 for (struct pinned_object
*pobj
= pinned_objects
; pobj
; pobj
= pobj
->next
)
5868 mark_object (pobj
->object
);
5872 mark_pinned_symbols (void)
5874 struct symbol_block
*sblk
;
5875 int lim
= (symbol_block_pinned
== symbol_block
5876 ? symbol_block_index
: SYMBOL_BLOCK_SIZE
);
5878 for (sblk
= symbol_block_pinned
; sblk
; sblk
= sblk
->next
)
5880 struct Lisp_Symbol
*sym
= sblk
->symbols
, *end
= sym
+ lim
;
5881 for (; sym
< end
; ++sym
)
5882 if (sym
->u
.s
.pinned
)
5883 mark_object (make_lisp_symbol (sym
));
5885 lim
= SYMBOL_BLOCK_SIZE
;
5889 /* Subroutine of Fgarbage_collect that does most of the work. It is a
5890 separate function so that we could limit mark_stack in searching
5891 the stack frames below this function, thus avoiding the rare cases
5892 where mark_stack finds values that look like live Lisp objects on
5893 portions of stack that couldn't possibly contain such live objects.
5894 For more details of this, see the discussion at
5895 https://lists.gnu.org/r/emacs-devel/2014-05/msg00270.html. */
5897 garbage_collect_1 (void *end
)
5899 struct buffer
*nextb
;
5900 char stack_top_variable
;
5903 ptrdiff_t count
= SPECPDL_INDEX ();
5904 struct timespec start
;
5905 Lisp_Object retval
= Qnil
;
5906 size_t tot_before
= 0;
5908 /* Can't GC if pure storage overflowed because we can't determine
5909 if something is a pure object or not. */
5910 if (pure_bytes_used_before_overflow
)
5913 /* Record this function, so it appears on the profiler's backtraces. */
5914 record_in_backtrace (QAutomatic_GC
, 0, 0);
5918 /* Don't keep undo information around forever.
5919 Do this early on, so it is no problem if the user quits. */
5920 FOR_EACH_BUFFER (nextb
)
5921 compact_buffer (nextb
);
5923 if (profiler_memory_running
)
5924 tot_before
= total_bytes_of_live_objects ();
5926 start
= current_timespec ();
5928 /* In case user calls debug_print during GC,
5929 don't let that cause a recursive GC. */
5930 consing_since_gc
= 0;
5932 /* Save what's currently displayed in the echo area. Don't do that
5933 if we are GC'ing because we've run out of memory, since
5934 push_message will cons, and we might have no memory for that. */
5935 if (NILP (Vmemory_full
))
5937 message_p
= push_message ();
5938 record_unwind_protect_void (pop_message_unwind
);
5943 /* Save a copy of the contents of the stack, for debugging. */
5944 #if MAX_SAVE_STACK > 0
5945 if (NILP (Vpurify_flag
))
5948 ptrdiff_t stack_size
;
5949 if (&stack_top_variable
< stack_bottom
)
5951 stack
= &stack_top_variable
;
5952 stack_size
= stack_bottom
- &stack_top_variable
;
5956 stack
= stack_bottom
;
5957 stack_size
= &stack_top_variable
- stack_bottom
;
5959 if (stack_size
<= MAX_SAVE_STACK
)
5961 if (stack_copy_size
< stack_size
)
5963 stack_copy
= xrealloc (stack_copy
, stack_size
);
5964 stack_copy_size
= stack_size
;
5966 stack
= ptr_bounds_set (stack
, stack_size
);
5967 no_sanitize_memcpy (stack_copy
, stack
, stack_size
);
5970 #endif /* MAX_SAVE_STACK > 0 */
5972 if (garbage_collection_messages
)
5973 message1_nolog ("Garbage collecting...");
5977 shrink_regexp_cache ();
5981 /* Mark all the special slots that serve as the roots of accessibility. */
5983 mark_buffer (&buffer_defaults
);
5984 mark_buffer (&buffer_local_symbols
);
5986 for (i
= 0; i
< ARRAYELTS (lispsym
); i
++)
5987 mark_object (builtin_lisp_symbol (i
));
5989 for (i
= 0; i
< staticidx
; i
++)
5990 mark_object (*staticvec
[i
]);
5992 mark_pinned_objects ();
5993 mark_pinned_symbols ();
6002 #ifdef HAVE_WINDOW_SYSTEM
6003 mark_fringe_data ();
6010 /* Everything is now marked, except for the data in font caches,
6011 undo lists, and finalizers. The first two are compacted by
6012 removing an items which aren't reachable otherwise. */
6014 compact_font_caches ();
6016 FOR_EACH_BUFFER (nextb
)
6018 if (!EQ (BVAR (nextb
, undo_list
), Qt
))
6019 bset_undo_list (nextb
, compact_undo_list (BVAR (nextb
, undo_list
)));
6020 /* Now that we have stripped the elements that need not be
6021 in the undo_list any more, we can finally mark the list. */
6022 mark_object (BVAR (nextb
, undo_list
));
6025 /* Now pre-sweep finalizers. Here, we add any unmarked finalizers
6026 to doomed_finalizers so we can run their associated functions
6027 after GC. It's important to scan finalizers at this stage so
6028 that we can be sure that unmarked finalizers are really
6029 unreachable except for references from their associated functions
6030 and from other finalizers. */
6032 queue_doomed_finalizers (&doomed_finalizers
, &finalizers
);
6033 mark_finalizer_list (&doomed_finalizers
);
6037 /* Clear the mark bits that we set in certain root slots. */
6038 VECTOR_UNMARK (&buffer_defaults
);
6039 VECTOR_UNMARK (&buffer_local_symbols
);
6047 consing_since_gc
= 0;
6048 if (gc_cons_threshold
< GC_DEFAULT_THRESHOLD
/ 10)
6049 gc_cons_threshold
= GC_DEFAULT_THRESHOLD
/ 10;
6051 gc_relative_threshold
= 0;
6052 if (FLOATP (Vgc_cons_percentage
))
6053 { /* Set gc_cons_combined_threshold. */
6054 double tot
= total_bytes_of_live_objects ();
6056 tot
*= XFLOAT_DATA (Vgc_cons_percentage
);
6059 if (tot
< TYPE_MAXIMUM (EMACS_INT
))
6060 gc_relative_threshold
= tot
;
6062 gc_relative_threshold
= TYPE_MAXIMUM (EMACS_INT
);
6066 if (garbage_collection_messages
&& NILP (Vmemory_full
))
6068 if (message_p
|| minibuf_level
> 0)
6071 message1_nolog ("Garbage collecting...done");
6074 unbind_to (count
, Qnil
);
6076 Lisp_Object total
[] = {
6077 list4 (Qconses
, make_number (sizeof (struct Lisp_Cons
)),
6078 bounded_number (total_conses
),
6079 bounded_number (total_free_conses
)),
6080 list4 (Qsymbols
, make_number (sizeof (struct Lisp_Symbol
)),
6081 bounded_number (total_symbols
),
6082 bounded_number (total_free_symbols
)),
6083 list4 (Qmiscs
, make_number (sizeof (union Lisp_Misc
)),
6084 bounded_number (total_markers
),
6085 bounded_number (total_free_markers
)),
6086 list4 (Qstrings
, make_number (sizeof (struct Lisp_String
)),
6087 bounded_number (total_strings
),
6088 bounded_number (total_free_strings
)),
6089 list3 (Qstring_bytes
, make_number (1),
6090 bounded_number (total_string_bytes
)),
6092 make_number (header_size
+ sizeof (Lisp_Object
)),
6093 bounded_number (total_vectors
)),
6094 list4 (Qvector_slots
, make_number (word_size
),
6095 bounded_number (total_vector_slots
),
6096 bounded_number (total_free_vector_slots
)),
6097 list4 (Qfloats
, make_number (sizeof (struct Lisp_Float
)),
6098 bounded_number (total_floats
),
6099 bounded_number (total_free_floats
)),
6100 list4 (Qintervals
, make_number (sizeof (struct interval
)),
6101 bounded_number (total_intervals
),
6102 bounded_number (total_free_intervals
)),
6103 list3 (Qbuffers
, make_number (sizeof (struct buffer
)),
6104 bounded_number (total_buffers
)),
6106 #ifdef DOUG_LEA_MALLOC
6107 list4 (Qheap
, make_number (1024),
6108 bounded_number ((mallinfo ().uordblks
+ 1023) >> 10),
6109 bounded_number ((mallinfo ().fordblks
+ 1023) >> 10)),
6112 retval
= CALLMANY (Flist
, total
);
6114 /* GC is complete: now we can run our finalizer callbacks. */
6115 run_finalizers (&doomed_finalizers
);
6117 if (!NILP (Vpost_gc_hook
))
6119 ptrdiff_t gc_count
= inhibit_garbage_collection ();
6120 safe_run_hooks (Qpost_gc_hook
);
6121 unbind_to (gc_count
, Qnil
);
6124 /* Accumulate statistics. */
6125 if (FLOATP (Vgc_elapsed
))
6127 struct timespec since_start
= timespec_sub (current_timespec (), start
);
6128 Vgc_elapsed
= make_float (XFLOAT_DATA (Vgc_elapsed
)
6129 + timespectod (since_start
));
6134 /* Collect profiling data. */
6135 if (profiler_memory_running
)
6138 size_t tot_after
= total_bytes_of_live_objects ();
6139 if (tot_before
> tot_after
)
6140 swept
= tot_before
- tot_after
;
6141 malloc_probe (swept
);
6147 DEFUN ("garbage-collect", Fgarbage_collect
, Sgarbage_collect
, 0, 0, "",
6148 doc
: /* Reclaim storage for Lisp objects no longer needed.
6149 Garbage collection happens automatically if you cons more than
6150 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
6151 `garbage-collect' normally returns a list with info on amount of space in use,
6152 where each entry has the form (NAME SIZE USED FREE), where:
6153 - NAME is a symbol describing the kind of objects this entry represents,
6154 - SIZE is the number of bytes used by each one,
6155 - USED is the number of those objects that were found live in the heap,
6156 - FREE is the number of those objects that are not live but that Emacs
6157 keeps around for future allocations (maybe because it does not know how
6158 to return them to the OS).
6159 However, if there was overflow in pure space, `garbage-collect'
6160 returns nil, because real GC can't be done.
6161 See Info node `(elisp)Garbage Collection'. */
6162 attributes
: noinline
)
6166 SET_STACK_TOP_ADDRESS (&end
);
6167 return garbage_collect_1 (end
);
6170 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
6171 only interesting objects referenced from glyphs are strings. */
6174 mark_glyph_matrix (struct glyph_matrix
*matrix
)
6176 struct glyph_row
*row
= matrix
->rows
;
6177 struct glyph_row
*end
= row
+ matrix
->nrows
;
6179 for (; row
< end
; ++row
)
6183 for (area
= LEFT_MARGIN_AREA
; area
< LAST_AREA
; ++area
)
6185 struct glyph
*glyph
= row
->glyphs
[area
];
6186 struct glyph
*end_glyph
= glyph
+ row
->used
[area
];
6188 for (; glyph
< end_glyph
; ++glyph
)
6189 if (STRINGP (glyph
->object
)
6190 && !STRING_MARKED_P (XSTRING (glyph
->object
)))
6191 mark_object (glyph
->object
);
6196 /* Mark reference to a Lisp_Object.
6197 If the object referred to has not been seen yet, recursively mark
6198 all the references contained in it. */
6200 #define LAST_MARKED_SIZE 500
6201 Lisp_Object last_marked
[LAST_MARKED_SIZE
] EXTERNALLY_VISIBLE
;
6202 static int last_marked_index
;
6204 /* For debugging--call abort when we cdr down this many
6205 links of a list, in mark_object. In debugging,
6206 the call to abort will hit a breakpoint.
6207 Normally this is zero and the check never goes off. */
6208 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE
;
6211 mark_vectorlike (struct Lisp_Vector
*ptr
)
6213 ptrdiff_t size
= ptr
->header
.size
;
6216 eassert (!VECTOR_MARKED_P (ptr
));
6217 VECTOR_MARK (ptr
); /* Else mark it. */
6218 if (size
& PSEUDOVECTOR_FLAG
)
6219 size
&= PSEUDOVECTOR_SIZE_MASK
;
6221 /* Note that this size is not the memory-footprint size, but only
6222 the number of Lisp_Object fields that we should trace.
6223 The distinction is used e.g. by Lisp_Process which places extra
6224 non-Lisp_Object fields at the end of the structure... */
6225 for (i
= 0; i
< size
; i
++) /* ...and then mark its elements. */
6226 mark_object (ptr
->contents
[i
]);
6229 /* Like mark_vectorlike but optimized for char-tables (and
6230 sub-char-tables) assuming that the contents are mostly integers or
6234 mark_char_table (struct Lisp_Vector
*ptr
, enum pvec_type pvectype
)
6236 int size
= ptr
->header
.size
& PSEUDOVECTOR_SIZE_MASK
;
6237 /* Consult the Lisp_Sub_Char_Table layout before changing this. */
6238 int i
, idx
= (pvectype
== PVEC_SUB_CHAR_TABLE
? SUB_CHAR_TABLE_OFFSET
: 0);
6240 eassert (!VECTOR_MARKED_P (ptr
));
6242 for (i
= idx
; i
< size
; i
++)
6244 Lisp_Object val
= ptr
->contents
[i
];
6246 if (INTEGERP (val
) || (SYMBOLP (val
) && XSYMBOL (val
)->u
.s
.gcmarkbit
))
6248 if (SUB_CHAR_TABLE_P (val
))
6250 if (! VECTOR_MARKED_P (XVECTOR (val
)))
6251 mark_char_table (XVECTOR (val
), PVEC_SUB_CHAR_TABLE
);
6258 NO_INLINE
/* To reduce stack depth in mark_object. */
6260 mark_compiled (struct Lisp_Vector
*ptr
)
6262 int i
, size
= ptr
->header
.size
& PSEUDOVECTOR_SIZE_MASK
;
6265 for (i
= 0; i
< size
; i
++)
6266 if (i
!= COMPILED_CONSTANTS
)
6267 mark_object (ptr
->contents
[i
]);
6268 return size
> COMPILED_CONSTANTS
? ptr
->contents
[COMPILED_CONSTANTS
] : Qnil
;
6271 /* Mark the chain of overlays starting at PTR. */
6274 mark_overlay (struct Lisp_Overlay
*ptr
)
6276 for (; ptr
&& !ptr
->gcmarkbit
; ptr
= ptr
->next
)
6279 /* These two are always markers and can be marked fast. */
6280 XMARKER (ptr
->start
)->gcmarkbit
= 1;
6281 XMARKER (ptr
->end
)->gcmarkbit
= 1;
6282 mark_object (ptr
->plist
);
6286 /* Mark Lisp_Objects and special pointers in BUFFER. */
6289 mark_buffer (struct buffer
*buffer
)
6291 /* This is handled much like other pseudovectors... */
6292 mark_vectorlike ((struct Lisp_Vector
*) buffer
);
6294 /* ...but there are some buffer-specific things. */
6296 MARK_INTERVAL_TREE (buffer_intervals (buffer
));
6298 /* For now, we just don't mark the undo_list. It's done later in
6299 a special way just before the sweep phase, and after stripping
6300 some of its elements that are not needed any more. */
6302 mark_overlay (buffer
->overlays_before
);
6303 mark_overlay (buffer
->overlays_after
);
6305 /* If this is an indirect buffer, mark its base buffer. */
6306 if (buffer
->base_buffer
&& !VECTOR_MARKED_P (buffer
->base_buffer
))
6307 mark_buffer (buffer
->base_buffer
);
6310 /* Mark Lisp faces in the face cache C. */
6312 NO_INLINE
/* To reduce stack depth in mark_object. */
6314 mark_face_cache (struct face_cache
*c
)
6319 for (i
= 0; i
< c
->used
; ++i
)
6321 struct face
*face
= FACE_FROM_ID_OR_NULL (c
->f
, i
);
6325 if (face
->font
&& !VECTOR_MARKED_P (face
->font
))
6326 mark_vectorlike ((struct Lisp_Vector
*) face
->font
);
6328 for (j
= 0; j
< LFACE_VECTOR_SIZE
; ++j
)
6329 mark_object (face
->lface
[j
]);
6335 NO_INLINE
/* To reduce stack depth in mark_object. */
6337 mark_localized_symbol (struct Lisp_Symbol
*ptr
)
6339 struct Lisp_Buffer_Local_Value
*blv
= SYMBOL_BLV (ptr
);
6340 Lisp_Object where
= blv
->where
;
6341 /* If the value is set up for a killed buffer or deleted
6342 frame, restore its global binding. If the value is
6343 forwarded to a C variable, either it's not a Lisp_Object
6344 var, or it's staticpro'd already. */
6345 if ((BUFFERP (where
) && !BUFFER_LIVE_P (XBUFFER (where
)))
6346 || (FRAMEP (where
) && !FRAME_LIVE_P (XFRAME (where
))))
6347 swap_in_global_binding (ptr
);
6348 mark_object (blv
->where
);
6349 mark_object (blv
->valcell
);
6350 mark_object (blv
->defcell
);
6353 NO_INLINE
/* To reduce stack depth in mark_object. */
6355 mark_save_value (struct Lisp_Save_Value
*ptr
)
6357 /* If `save_type' is zero, `data[0].pointer' is the address
6358 of a memory area containing `data[1].integer' potential
6360 if (ptr
->save_type
== SAVE_TYPE_MEMORY
)
6362 Lisp_Object
*p
= ptr
->data
[0].pointer
;
6364 for (nelt
= ptr
->data
[1].integer
; nelt
> 0; nelt
--, p
++)
6365 mark_maybe_object (*p
);
6369 /* Find Lisp_Objects in `data[N]' slots and mark them. */
6371 for (i
= 0; i
< SAVE_VALUE_SLOTS
; i
++)
6372 if (save_type (ptr
, i
) == SAVE_OBJECT
)
6373 mark_object (ptr
->data
[i
].object
);
6377 /* Remove killed buffers or items whose car is a killed buffer from
6378 LIST, and mark other items. Return changed LIST, which is marked. */
6381 mark_discard_killed_buffers (Lisp_Object list
)
6383 Lisp_Object tail
, *prev
= &list
;
6385 for (tail
= list
; CONSP (tail
) && !CONS_MARKED_P (XCONS (tail
));
6388 Lisp_Object tem
= XCAR (tail
);
6391 if (BUFFERP (tem
) && !BUFFER_LIVE_P (XBUFFER (tem
)))
6392 *prev
= XCDR (tail
);
6395 CONS_MARK (XCONS (tail
));
6396 mark_object (XCAR (tail
));
6397 prev
= xcdr_addr (tail
);
6404 /* Determine type of generic Lisp_Object and mark it accordingly.
6406 This function implements a straightforward depth-first marking
6407 algorithm and so the recursion depth may be very high (a few
6408 tens of thousands is not uncommon). To minimize stack usage,
6409 a few cold paths are moved out to NO_INLINE functions above.
6410 In general, inlining them doesn't help you to gain more speed. */
6413 mark_object (Lisp_Object arg
)
6415 register Lisp_Object obj
;
6417 #if GC_CHECK_MARKED_OBJECTS
6420 ptrdiff_t cdr_count
= 0;
6429 last_marked
[last_marked_index
++] = obj
;
6430 if (last_marked_index
== LAST_MARKED_SIZE
)
6431 last_marked_index
= 0;
6433 /* Perform some sanity checks on the objects marked here. Abort if
6434 we encounter an object we know is bogus. This increases GC time
6436 #if GC_CHECK_MARKED_OBJECTS
6438 /* Check that the object pointed to by PO is known to be a Lisp
6439 structure allocated from the heap. */
6440 #define CHECK_ALLOCATED() \
6442 m = mem_find (po); \
6447 /* Check that the object pointed to by PO is live, using predicate
6449 #define CHECK_LIVE(LIVEP) \
6451 if (!LIVEP (m, po)) \
6455 /* Check both of the above conditions, for non-symbols. */
6456 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
6458 CHECK_ALLOCATED (); \
6459 CHECK_LIVE (LIVEP); \
6462 /* Check both of the above conditions, for symbols. */
6463 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() \
6465 if (!c_symbol_p (ptr)) \
6467 CHECK_ALLOCATED (); \
6468 CHECK_LIVE (live_symbol_p); \
6472 #else /* not GC_CHECK_MARKED_OBJECTS */
6474 #define CHECK_LIVE(LIVEP) ((void) 0)
6475 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) ((void) 0)
6476 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() ((void) 0)
6478 #endif /* not GC_CHECK_MARKED_OBJECTS */
6480 switch (XTYPE (obj
))
6484 register struct Lisp_String
*ptr
= XSTRING (obj
);
6485 if (STRING_MARKED_P (ptr
))
6487 CHECK_ALLOCATED_AND_LIVE (live_string_p
);
6489 MARK_INTERVAL_TREE (ptr
->u
.s
.intervals
);
6490 #ifdef GC_CHECK_STRING_BYTES
6491 /* Check that the string size recorded in the string is the
6492 same as the one recorded in the sdata structure. */
6494 #endif /* GC_CHECK_STRING_BYTES */
6498 case Lisp_Vectorlike
:
6500 register struct Lisp_Vector
*ptr
= XVECTOR (obj
);
6502 if (VECTOR_MARKED_P (ptr
))
6505 #if GC_CHECK_MARKED_OBJECTS
6507 if (m
== MEM_NIL
&& !SUBRP (obj
) && !main_thread_p (po
))
6509 #endif /* GC_CHECK_MARKED_OBJECTS */
6511 enum pvec_type pvectype
6512 = PSEUDOVECTOR_TYPE (ptr
);
6514 if (pvectype
!= PVEC_SUBR
6515 && pvectype
!= PVEC_BUFFER
6516 && !main_thread_p (po
))
6517 CHECK_LIVE (live_vector_p
);
6522 #if GC_CHECK_MARKED_OBJECTS
6531 #endif /* GC_CHECK_MARKED_OBJECTS */
6532 mark_buffer ((struct buffer
*) ptr
);
6536 /* Although we could treat this just like a vector, mark_compiled
6537 returns the COMPILED_CONSTANTS element, which is marked at the
6538 next iteration of goto-loop here. This is done to avoid a few
6539 recursive calls to mark_object. */
6540 obj
= mark_compiled (ptr
);
6547 struct frame
*f
= (struct frame
*) ptr
;
6549 mark_vectorlike (ptr
);
6550 mark_face_cache (f
->face_cache
);
6551 #ifdef HAVE_WINDOW_SYSTEM
6552 if (FRAME_WINDOW_P (f
) && FRAME_X_OUTPUT (f
))
6554 struct font
*font
= FRAME_FONT (f
);
6556 if (font
&& !VECTOR_MARKED_P (font
))
6557 mark_vectorlike ((struct Lisp_Vector
*) font
);
6565 struct window
*w
= (struct window
*) ptr
;
6567 mark_vectorlike (ptr
);
6569 /* Mark glyph matrices, if any. Marking window
6570 matrices is sufficient because frame matrices
6571 use the same glyph memory. */
6572 if (w
->current_matrix
)
6574 mark_glyph_matrix (w
->current_matrix
);
6575 mark_glyph_matrix (w
->desired_matrix
);
6578 /* Filter out killed buffers from both buffer lists
6579 in attempt to help GC to reclaim killed buffers faster.
6580 We can do it elsewhere for live windows, but this is the
6581 best place to do it for dead windows. */
6583 (w
, mark_discard_killed_buffers (w
->prev_buffers
));
6585 (w
, mark_discard_killed_buffers (w
->next_buffers
));
6589 case PVEC_HASH_TABLE
:
6591 struct Lisp_Hash_Table
*h
= (struct Lisp_Hash_Table
*) ptr
;
6593 mark_vectorlike (ptr
);
6594 mark_object (h
->test
.name
);
6595 mark_object (h
->test
.user_hash_function
);
6596 mark_object (h
->test
.user_cmp_function
);
6597 /* If hash table is not weak, mark all keys and values.
6598 For weak tables, mark only the vector. */
6600 mark_object (h
->key_and_value
);
6602 VECTOR_MARK (XVECTOR (h
->key_and_value
));
6606 case PVEC_CHAR_TABLE
:
6607 case PVEC_SUB_CHAR_TABLE
:
6608 mark_char_table (ptr
, (enum pvec_type
) pvectype
);
6611 case PVEC_BOOL_VECTOR
:
6612 /* No Lisp_Objects to mark in a bool vector. */
6623 mark_vectorlike (ptr
);
6630 struct Lisp_Symbol
*ptr
= XSYMBOL (obj
);
6632 if (ptr
->u
.s
.gcmarkbit
)
6634 CHECK_ALLOCATED_AND_LIVE_SYMBOL ();
6635 ptr
->u
.s
.gcmarkbit
= 1;
6636 /* Attempt to catch bogus objects. */
6637 eassert (valid_lisp_object_p (ptr
->u
.s
.function
));
6638 mark_object (ptr
->u
.s
.function
);
6639 mark_object (ptr
->u
.s
.plist
);
6640 switch (ptr
->u
.s
.redirect
)
6642 case SYMBOL_PLAINVAL
: mark_object (SYMBOL_VAL (ptr
)); break;
6643 case SYMBOL_VARALIAS
:
6646 XSETSYMBOL (tem
, SYMBOL_ALIAS (ptr
));
6650 case SYMBOL_LOCALIZED
:
6651 mark_localized_symbol (ptr
);
6653 case SYMBOL_FORWARDED
:
6654 /* If the value is forwarded to a buffer or keyboard field,
6655 these are marked when we see the corresponding object.
6656 And if it's forwarded to a C variable, either it's not
6657 a Lisp_Object var, or it's staticpro'd already. */
6659 default: emacs_abort ();
6661 if (!PURE_P (XSTRING (ptr
->u
.s
.name
)))
6662 MARK_STRING (XSTRING (ptr
->u
.s
.name
));
6663 MARK_INTERVAL_TREE (string_intervals (ptr
->u
.s
.name
));
6664 /* Inner loop to mark next symbol in this bucket, if any. */
6665 po
= ptr
= ptr
->u
.s
.next
;
6672 CHECK_ALLOCATED_AND_LIVE (live_misc_p
);
6674 if (XMISCANY (obj
)->gcmarkbit
)
6677 switch (XMISCTYPE (obj
))
6679 case Lisp_Misc_Marker
:
6680 /* DO NOT mark thru the marker's chain.
6681 The buffer's markers chain does not preserve markers from gc;
6682 instead, markers are removed from the chain when freed by gc. */
6683 XMISCANY (obj
)->gcmarkbit
= 1;
6686 case Lisp_Misc_Save_Value
:
6687 XMISCANY (obj
)->gcmarkbit
= 1;
6688 mark_save_value (XSAVE_VALUE (obj
));
6691 case Lisp_Misc_Overlay
:
6692 mark_overlay (XOVERLAY (obj
));
6695 case Lisp_Misc_Finalizer
:
6696 XMISCANY (obj
)->gcmarkbit
= true;
6697 mark_object (XFINALIZER (obj
)->function
);
6701 case Lisp_Misc_User_Ptr
:
6702 XMISCANY (obj
)->gcmarkbit
= true;
6713 register struct Lisp_Cons
*ptr
= XCONS (obj
);
6714 if (CONS_MARKED_P (ptr
))
6716 CHECK_ALLOCATED_AND_LIVE (live_cons_p
);
6718 /* If the cdr is nil, avoid recursion for the car. */
6719 if (EQ (ptr
->u
.s
.u
.cdr
, Qnil
))
6725 mark_object (ptr
->u
.s
.car
);
6726 obj
= ptr
->u
.s
.u
.cdr
;
6728 if (cdr_count
== mark_object_loop_halt
)
6734 CHECK_ALLOCATED_AND_LIVE (live_float_p
);
6735 FLOAT_MARK (XFLOAT (obj
));
6746 #undef CHECK_ALLOCATED
6747 #undef CHECK_ALLOCATED_AND_LIVE
6749 /* Mark the Lisp pointers in the terminal objects.
6750 Called by Fgarbage_collect. */
6753 mark_terminals (void)
6756 for (t
= terminal_list
; t
; t
= t
->next_terminal
)
6758 eassert (t
->name
!= NULL
);
6759 #ifdef HAVE_WINDOW_SYSTEM
6760 /* If a terminal object is reachable from a stacpro'ed object,
6761 it might have been marked already. Make sure the image cache
6763 mark_image_cache (t
->image_cache
);
6764 #endif /* HAVE_WINDOW_SYSTEM */
6765 if (!VECTOR_MARKED_P (t
))
6766 mark_vectorlike ((struct Lisp_Vector
*)t
);
6772 /* Value is non-zero if OBJ will survive the current GC because it's
6773 either marked or does not need to be marked to survive. */
6776 survives_gc_p (Lisp_Object obj
)
6780 switch (XTYPE (obj
))
6787 survives_p
= XSYMBOL (obj
)->u
.s
.gcmarkbit
;
6791 survives_p
= XMISCANY (obj
)->gcmarkbit
;
6795 survives_p
= STRING_MARKED_P (XSTRING (obj
));
6798 case Lisp_Vectorlike
:
6799 survives_p
= SUBRP (obj
) || VECTOR_MARKED_P (XVECTOR (obj
));
6803 survives_p
= CONS_MARKED_P (XCONS (obj
));
6807 survives_p
= FLOAT_MARKED_P (XFLOAT (obj
));
6814 return survives_p
|| PURE_P (XPNTR (obj
));
6820 NO_INLINE
/* For better stack traces */
6824 struct cons_block
*cblk
;
6825 struct cons_block
**cprev
= &cons_block
;
6826 int lim
= cons_block_index
;
6827 EMACS_INT num_free
= 0, num_used
= 0;
6831 for (cblk
= cons_block
; cblk
; cblk
= *cprev
)
6835 int ilim
= (lim
+ BITS_PER_BITS_WORD
- 1) / BITS_PER_BITS_WORD
;
6837 /* Scan the mark bits an int at a time. */
6838 for (i
= 0; i
< ilim
; i
++)
6840 if (cblk
->gcmarkbits
[i
] == BITS_WORD_MAX
)
6842 /* Fast path - all cons cells for this int are marked. */
6843 cblk
->gcmarkbits
[i
] = 0;
6844 num_used
+= BITS_PER_BITS_WORD
;
6848 /* Some cons cells for this int are not marked.
6849 Find which ones, and free them. */
6850 int start
, pos
, stop
;
6852 start
= i
* BITS_PER_BITS_WORD
;
6854 if (stop
> BITS_PER_BITS_WORD
)
6855 stop
= BITS_PER_BITS_WORD
;
6858 for (pos
= start
; pos
< stop
; pos
++)
6860 struct Lisp_Cons
*acons
6861 = ptr_bounds_copy (&cblk
->conses
[pos
], cblk
);
6862 if (!CONS_MARKED_P (acons
))
6865 cblk
->conses
[pos
].u
.s
.u
.chain
= cons_free_list
;
6866 cons_free_list
= &cblk
->conses
[pos
];
6867 cons_free_list
->u
.s
.car
= Vdead
;
6872 CONS_UNMARK (acons
);
6878 lim
= CONS_BLOCK_SIZE
;
6879 /* If this block contains only free conses and we have already
6880 seen more than two blocks worth of free conses then deallocate
6882 if (this_free
== CONS_BLOCK_SIZE
&& num_free
> CONS_BLOCK_SIZE
)
6884 *cprev
= cblk
->next
;
6885 /* Unhook from the free list. */
6886 cons_free_list
= cblk
->conses
[0].u
.s
.u
.chain
;
6887 lisp_align_free (cblk
);
6891 num_free
+= this_free
;
6892 cprev
= &cblk
->next
;
6895 total_conses
= num_used
;
6896 total_free_conses
= num_free
;
6899 NO_INLINE
/* For better stack traces */
6903 register struct float_block
*fblk
;
6904 struct float_block
**fprev
= &float_block
;
6905 register int lim
= float_block_index
;
6906 EMACS_INT num_free
= 0, num_used
= 0;
6908 float_free_list
= 0;
6910 for (fblk
= float_block
; fblk
; fblk
= *fprev
)
6914 for (i
= 0; i
< lim
; i
++)
6916 struct Lisp_Float
*afloat
= ptr_bounds_copy (&fblk
->floats
[i
], fblk
);
6917 if (!FLOAT_MARKED_P (afloat
))
6920 fblk
->floats
[i
].u
.chain
= float_free_list
;
6921 float_free_list
= &fblk
->floats
[i
];
6926 FLOAT_UNMARK (afloat
);
6929 lim
= FLOAT_BLOCK_SIZE
;
6930 /* If this block contains only free floats and we have already
6931 seen more than two blocks worth of free floats then deallocate
6933 if (this_free
== FLOAT_BLOCK_SIZE
&& num_free
> FLOAT_BLOCK_SIZE
)
6935 *fprev
= fblk
->next
;
6936 /* Unhook from the free list. */
6937 float_free_list
= fblk
->floats
[0].u
.chain
;
6938 lisp_align_free (fblk
);
6942 num_free
+= this_free
;
6943 fprev
= &fblk
->next
;
6946 total_floats
= num_used
;
6947 total_free_floats
= num_free
;
6950 NO_INLINE
/* For better stack traces */
6952 sweep_intervals (void)
6954 register struct interval_block
*iblk
;
6955 struct interval_block
**iprev
= &interval_block
;
6956 register int lim
= interval_block_index
;
6957 EMACS_INT num_free
= 0, num_used
= 0;
6959 interval_free_list
= 0;
6961 for (iblk
= interval_block
; iblk
; iblk
= *iprev
)
6966 for (i
= 0; i
< lim
; i
++)
6968 if (!iblk
->intervals
[i
].gcmarkbit
)
6970 set_interval_parent (&iblk
->intervals
[i
], interval_free_list
);
6971 interval_free_list
= &iblk
->intervals
[i
];
6977 iblk
->intervals
[i
].gcmarkbit
= 0;
6980 lim
= INTERVAL_BLOCK_SIZE
;
6981 /* If this block contains only free intervals and we have already
6982 seen more than two blocks worth of free intervals then
6983 deallocate this block. */
6984 if (this_free
== INTERVAL_BLOCK_SIZE
&& num_free
> INTERVAL_BLOCK_SIZE
)
6986 *iprev
= iblk
->next
;
6987 /* Unhook from the free list. */
6988 interval_free_list
= INTERVAL_PARENT (&iblk
->intervals
[0]);
6993 num_free
+= this_free
;
6994 iprev
= &iblk
->next
;
6997 total_intervals
= num_used
;
6998 total_free_intervals
= num_free
;
7001 NO_INLINE
/* For better stack traces */
7003 sweep_symbols (void)
7005 struct symbol_block
*sblk
;
7006 struct symbol_block
**sprev
= &symbol_block
;
7007 int lim
= symbol_block_index
;
7008 EMACS_INT num_free
= 0, num_used
= ARRAYELTS (lispsym
);
7010 symbol_free_list
= NULL
;
7012 for (int i
= 0; i
< ARRAYELTS (lispsym
); i
++)
7013 lispsym
[i
].u
.s
.gcmarkbit
= 0;
7015 for (sblk
= symbol_block
; sblk
; sblk
= *sprev
)
7018 struct Lisp_Symbol
*sym
= sblk
->symbols
;
7019 struct Lisp_Symbol
*end
= sym
+ lim
;
7021 for (; sym
< end
; ++sym
)
7023 if (!sym
->u
.s
.gcmarkbit
)
7025 if (sym
->u
.s
.redirect
== SYMBOL_LOCALIZED
)
7027 xfree (SYMBOL_BLV (sym
));
7028 /* At every GC we sweep all symbol_blocks and rebuild the
7029 symbol_free_list, so those symbols which stayed unused
7030 between the two will be re-swept.
7031 So we have to make sure we don't re-free this blv next
7032 time we sweep this symbol_block (bug#29066). */
7033 sym
->u
.s
.redirect
= SYMBOL_PLAINVAL
;
7035 sym
->u
.s
.next
= symbol_free_list
;
7036 symbol_free_list
= sym
;
7037 symbol_free_list
->u
.s
.function
= Vdead
;
7043 sym
->u
.s
.gcmarkbit
= 0;
7044 /* Attempt to catch bogus objects. */
7045 eassert (valid_lisp_object_p (sym
->u
.s
.function
));
7049 lim
= SYMBOL_BLOCK_SIZE
;
7050 /* If this block contains only free symbols and we have already
7051 seen more than two blocks worth of free symbols then deallocate
7053 if (this_free
== SYMBOL_BLOCK_SIZE
&& num_free
> SYMBOL_BLOCK_SIZE
)
7055 *sprev
= sblk
->next
;
7056 /* Unhook from the free list. */
7057 symbol_free_list
= sblk
->symbols
[0].u
.s
.next
;
7062 num_free
+= this_free
;
7063 sprev
= &sblk
->next
;
7066 total_symbols
= num_used
;
7067 total_free_symbols
= num_free
;
7070 NO_INLINE
/* For better stack traces. */
7074 register struct marker_block
*mblk
;
7075 struct marker_block
**mprev
= &marker_block
;
7076 register int lim
= marker_block_index
;
7077 EMACS_INT num_free
= 0, num_used
= 0;
7079 /* Put all unmarked misc's on free list. For a marker, first
7080 unchain it from the buffer it points into. */
7082 marker_free_list
= 0;
7084 for (mblk
= marker_block
; mblk
; mblk
= *mprev
)
7089 for (i
= 0; i
< lim
; i
++)
7091 if (!mblk
->markers
[i
].m
.u_any
.gcmarkbit
)
7093 if (mblk
->markers
[i
].m
.u_any
.type
== Lisp_Misc_Marker
)
7094 unchain_marker (&mblk
->markers
[i
].m
.u_marker
);
7095 else if (mblk
->markers
[i
].m
.u_any
.type
== Lisp_Misc_Finalizer
)
7096 unchain_finalizer (&mblk
->markers
[i
].m
.u_finalizer
);
7098 else if (mblk
->markers
[i
].m
.u_any
.type
== Lisp_Misc_User_Ptr
)
7100 struct Lisp_User_Ptr
*uptr
= &mblk
->markers
[i
].m
.u_user_ptr
;
7101 if (uptr
->finalizer
)
7102 uptr
->finalizer (uptr
->p
);
7105 /* Set the type of the freed object to Lisp_Misc_Free.
7106 We could leave the type alone, since nobody checks it,
7107 but this might catch bugs faster. */
7108 mblk
->markers
[i
].m
.u_marker
.type
= Lisp_Misc_Free
;
7109 mblk
->markers
[i
].m
.u_free
.chain
= marker_free_list
;
7110 marker_free_list
= &mblk
->markers
[i
].m
;
7116 mblk
->markers
[i
].m
.u_any
.gcmarkbit
= 0;
7119 lim
= MARKER_BLOCK_SIZE
;
7120 /* If this block contains only free markers and we have already
7121 seen more than two blocks worth of free markers then deallocate
7123 if (this_free
== MARKER_BLOCK_SIZE
&& num_free
> MARKER_BLOCK_SIZE
)
7125 *mprev
= mblk
->next
;
7126 /* Unhook from the free list. */
7127 marker_free_list
= mblk
->markers
[0].m
.u_free
.chain
;
7132 num_free
+= this_free
;
7133 mprev
= &mblk
->next
;
7137 total_markers
= num_used
;
7138 total_free_markers
= num_free
;
7141 NO_INLINE
/* For better stack traces */
7143 sweep_buffers (void)
7145 register struct buffer
*buffer
, **bprev
= &all_buffers
;
7148 for (buffer
= all_buffers
; buffer
; buffer
= *bprev
)
7149 if (!VECTOR_MARKED_P (buffer
))
7151 *bprev
= buffer
->next
;
7156 VECTOR_UNMARK (buffer
);
7157 /* Do not use buffer_(set|get)_intervals here. */
7158 buffer
->text
->intervals
= balance_intervals (buffer
->text
->intervals
);
7160 bprev
= &buffer
->next
;
7164 /* Sweep: find all structures not marked, and free them. */
7168 /* Remove or mark entries in weak hash tables.
7169 This must be done before any object is unmarked. */
7170 sweep_weak_hash_tables ();
7173 check_string_bytes (!noninteractive
);
7181 check_string_bytes (!noninteractive
);
7184 DEFUN ("memory-info", Fmemory_info
, Smemory_info
, 0, 0, 0,
7185 doc
: /* Return a list of (TOTAL-RAM FREE-RAM TOTAL-SWAP FREE-SWAP).
7186 All values are in Kbytes. If there is no swap space,
7187 last two values are zero. If the system is not supported
7188 or memory information can't be obtained, return nil. */)
7191 #if defined HAVE_LINUX_SYSINFO
7197 #ifdef LINUX_SYSINFO_UNIT
7198 units
= si
.mem_unit
;
7202 return list4i ((uintmax_t) si
.totalram
* units
/ 1024,
7203 (uintmax_t) si
.freeram
* units
/ 1024,
7204 (uintmax_t) si
.totalswap
* units
/ 1024,
7205 (uintmax_t) si
.freeswap
* units
/ 1024);
7206 #elif defined WINDOWSNT
7207 unsigned long long totalram
, freeram
, totalswap
, freeswap
;
7209 if (w32_memory_info (&totalram
, &freeram
, &totalswap
, &freeswap
) == 0)
7210 return list4i ((uintmax_t) totalram
/ 1024,
7211 (uintmax_t) freeram
/ 1024,
7212 (uintmax_t) totalswap
/ 1024,
7213 (uintmax_t) freeswap
/ 1024);
7217 unsigned long totalram
, freeram
, totalswap
, freeswap
;
7219 if (dos_memory_info (&totalram
, &freeram
, &totalswap
, &freeswap
) == 0)
7220 return list4i ((uintmax_t) totalram
/ 1024,
7221 (uintmax_t) freeram
/ 1024,
7222 (uintmax_t) totalswap
/ 1024,
7223 (uintmax_t) freeswap
/ 1024);
7226 #else /* not HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
7227 /* FIXME: add more systems. */
7229 #endif /* HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
7232 /* Debugging aids. */
7234 DEFUN ("memory-limit", Fmemory_limit
, Smemory_limit
, 0, 0, 0,
7235 doc
: /* Return the address of the last byte Emacs has allocated, divided by 1024.
7236 This may be helpful in debugging Emacs's memory usage.
7237 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
7242 #if defined HAVE_NS || defined __APPLE__ || !HAVE_SBRK
7243 /* Avoid warning. sbrk has no relation to memory allocated anyway. */
7246 XSETINT (end
, (intptr_t) (char *) sbrk (0) / 1024);
7252 DEFUN ("memory-use-counts", Fmemory_use_counts
, Smemory_use_counts
, 0, 0, 0,
7253 doc
: /* Return a list of counters that measure how much consing there has been.
7254 Each of these counters increments for a certain kind of object.
7255 The counters wrap around from the largest positive integer to zero.
7256 Garbage collection does not decrease them.
7257 The elements of the value are as follows:
7258 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
7259 All are in units of 1 = one object consed
7260 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
7262 MISCS include overlays, markers, and some internal types.
7263 Frames, windows, buffers, and subprocesses count as vectors
7264 (but the contents of a buffer's text do not count here). */)
7267 return listn (CONSTYPE_HEAP
, 8,
7268 bounded_number (cons_cells_consed
),
7269 bounded_number (floats_consed
),
7270 bounded_number (vector_cells_consed
),
7271 bounded_number (symbols_consed
),
7272 bounded_number (string_chars_consed
),
7273 bounded_number (misc_objects_consed
),
7274 bounded_number (intervals_consed
),
7275 bounded_number (strings_consed
));
7279 symbol_uses_obj (Lisp_Object symbol
, Lisp_Object obj
)
7281 struct Lisp_Symbol
*sym
= XSYMBOL (symbol
);
7282 Lisp_Object val
= find_symbol_value (symbol
);
7283 return (EQ (val
, obj
)
7284 || EQ (sym
->u
.s
.function
, obj
)
7285 || (!NILP (sym
->u
.s
.function
)
7286 && COMPILEDP (sym
->u
.s
.function
)
7287 && EQ (AREF (sym
->u
.s
.function
, COMPILED_BYTECODE
), obj
))
7290 && EQ (AREF (val
, COMPILED_BYTECODE
), obj
)));
7293 /* Find at most FIND_MAX symbols which have OBJ as their value or
7294 function. This is used in gdbinit's `xwhichsymbols' command. */
7297 which_symbols (Lisp_Object obj
, EMACS_INT find_max
)
7299 struct symbol_block
*sblk
;
7300 ptrdiff_t gc_count
= inhibit_garbage_collection ();
7301 Lisp_Object found
= Qnil
;
7305 for (int i
= 0; i
< ARRAYELTS (lispsym
); i
++)
7307 Lisp_Object sym
= builtin_lisp_symbol (i
);
7308 if (symbol_uses_obj (sym
, obj
))
7310 found
= Fcons (sym
, found
);
7311 if (--find_max
== 0)
7316 for (sblk
= symbol_block
; sblk
; sblk
= sblk
->next
)
7318 struct Lisp_Symbol
*asym
= sblk
->symbols
;
7321 for (bn
= 0; bn
< SYMBOL_BLOCK_SIZE
; bn
++, asym
++)
7323 if (sblk
== symbol_block
&& bn
>= symbol_block_index
)
7326 Lisp_Object sym
= make_lisp_symbol (asym
);
7327 if (symbol_uses_obj (sym
, obj
))
7329 found
= Fcons (sym
, found
);
7330 if (--find_max
== 0)
7338 unbind_to (gc_count
, Qnil
);
7342 #ifdef SUSPICIOUS_OBJECT_CHECKING
7345 find_suspicious_object_in_range (void *begin
, void *end
)
7347 char *begin_a
= begin
;
7351 for (i
= 0; i
< ARRAYELTS (suspicious_objects
); ++i
)
7353 char *suspicious_object
= suspicious_objects
[i
];
7354 if (begin_a
<= suspicious_object
&& suspicious_object
< end_a
)
7355 return suspicious_object
;
7362 note_suspicious_free (void *ptr
)
7364 struct suspicious_free_record
*rec
;
7366 rec
= &suspicious_free_history
[suspicious_free_history_index
++];
7367 if (suspicious_free_history_index
==
7368 ARRAYELTS (suspicious_free_history
))
7370 suspicious_free_history_index
= 0;
7373 memset (rec
, 0, sizeof (*rec
));
7374 rec
->suspicious_object
= ptr
;
7375 backtrace (&rec
->backtrace
[0], ARRAYELTS (rec
->backtrace
));
7379 detect_suspicious_free (void *ptr
)
7383 eassert (ptr
!= NULL
);
7385 for (i
= 0; i
< ARRAYELTS (suspicious_objects
); ++i
)
7386 if (suspicious_objects
[i
] == ptr
)
7388 note_suspicious_free (ptr
);
7389 suspicious_objects
[i
] = NULL
;
7393 #endif /* SUSPICIOUS_OBJECT_CHECKING */
7395 DEFUN ("suspicious-object", Fsuspicious_object
, Ssuspicious_object
, 1, 1, 0,
7396 doc
: /* Return OBJ, maybe marking it for extra scrutiny.
7397 If Emacs is compiled with suspicious object checking, capture
7398 a stack trace when OBJ is freed in order to help track down
7399 garbage collection bugs. Otherwise, do nothing and return OBJ. */)
7402 #ifdef SUSPICIOUS_OBJECT_CHECKING
7403 /* Right now, we care only about vectors. */
7404 if (VECTORLIKEP (obj
))
7406 suspicious_objects
[suspicious_object_index
++] = XVECTOR (obj
);
7407 if (suspicious_object_index
== ARRAYELTS (suspicious_objects
))
7408 suspicious_object_index
= 0;
7414 #ifdef ENABLE_CHECKING
7416 bool suppress_checking
;
7419 die (const char *msg
, const char *file
, int line
)
7421 fprintf (stderr
, "\r\n%s:%d: Emacs fatal error: assertion failed: %s\r\n",
7423 terminate_due_to_signal (SIGABRT
, INT_MAX
);
7426 #endif /* ENABLE_CHECKING */
7428 #if defined (ENABLE_CHECKING) && USE_STACK_LISP_OBJECTS
7430 /* Stress alloca with inconveniently sized requests and check
7431 whether all allocated areas may be used for Lisp_Object. */
7433 NO_INLINE
static void
7434 verify_alloca (void)
7437 enum { ALLOCA_CHECK_MAX
= 256 };
7438 /* Start from size of the smallest Lisp object. */
7439 for (i
= sizeof (struct Lisp_Cons
); i
<= ALLOCA_CHECK_MAX
; i
++)
7441 void *ptr
= alloca (i
);
7442 make_lisp_ptr (ptr
, Lisp_Cons
);
7446 #else /* not ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7448 #define verify_alloca() ((void) 0)
7450 #endif /* ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7452 /* Initialization. */
7455 init_alloc_once (void)
7457 /* Even though Qt's contents are not set up, its address is known. */
7461 pure_size
= PURESIZE
;
7464 init_finalizer_list (&finalizers
);
7465 init_finalizer_list (&doomed_finalizers
);
7468 Vdead
= make_pure_string ("DEAD", 4, 4, 0);
7470 #ifdef DOUG_LEA_MALLOC
7471 mallopt (M_TRIM_THRESHOLD
, 128 * 1024); /* Trim threshold. */
7472 mallopt (M_MMAP_THRESHOLD
, 64 * 1024); /* Mmap threshold. */
7473 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
); /* Max. number of mmap'ed areas. */
7478 refill_memory_reserve ();
7479 gc_cons_threshold
= GC_DEFAULT_THRESHOLD
;
7485 Vgc_elapsed
= make_float (0.0);
7489 valgrind_p
= RUNNING_ON_VALGRIND
!= 0;
7494 syms_of_alloc (void)
7496 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold
,
7497 doc
: /* Number of bytes of consing between garbage collections.
7498 Garbage collection can happen automatically once this many bytes have been
7499 allocated since the last garbage collection. All data types count.
7501 Garbage collection happens automatically only when `eval' is called.
7503 By binding this temporarily to a large number, you can effectively
7504 prevent garbage collection during a part of the program.
7505 See also `gc-cons-percentage'. */);
7507 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage
,
7508 doc
: /* Portion of the heap used for allocation.
7509 Garbage collection can happen automatically once this portion of the heap
7510 has been allocated since the last garbage collection.
7511 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
7512 Vgc_cons_percentage
= make_float (0.1);
7514 DEFVAR_INT ("pure-bytes-used", pure_bytes_used
,
7515 doc
: /* Number of bytes of shareable Lisp data allocated so far. */);
7517 DEFVAR_INT ("cons-cells-consed", cons_cells_consed
,
7518 doc
: /* Number of cons cells that have been consed so far. */);
7520 DEFVAR_INT ("floats-consed", floats_consed
,
7521 doc
: /* Number of floats that have been consed so far. */);
7523 DEFVAR_INT ("vector-cells-consed", vector_cells_consed
,
7524 doc
: /* Number of vector cells that have been consed so far. */);
7526 DEFVAR_INT ("symbols-consed", symbols_consed
,
7527 doc
: /* Number of symbols that have been consed so far. */);
7528 symbols_consed
+= ARRAYELTS (lispsym
);
7530 DEFVAR_INT ("string-chars-consed", string_chars_consed
,
7531 doc
: /* Number of string characters that have been consed so far. */);
7533 DEFVAR_INT ("misc-objects-consed", misc_objects_consed
,
7534 doc
: /* Number of miscellaneous objects that have been consed so far.
7535 These include markers and overlays, plus certain objects not visible
7538 DEFVAR_INT ("intervals-consed", intervals_consed
,
7539 doc
: /* Number of intervals that have been consed so far. */);
7541 DEFVAR_INT ("strings-consed", strings_consed
,
7542 doc
: /* Number of strings that have been consed so far. */);
7544 DEFVAR_LISP ("purify-flag", Vpurify_flag
,
7545 doc
: /* Non-nil means loading Lisp code in order to dump an executable.
7546 This means that certain objects should be allocated in shared (pure) space.
7547 It can also be set to a hash-table, in which case this table is used to
7548 do hash-consing of the objects allocated to pure space. */);
7550 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages
,
7551 doc
: /* Non-nil means display messages at start and end of garbage collection. */);
7552 garbage_collection_messages
= 0;
7554 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook
,
7555 doc
: /* Hook run after garbage collection has finished. */);
7556 Vpost_gc_hook
= Qnil
;
7557 DEFSYM (Qpost_gc_hook
, "post-gc-hook");
7559 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data
,
7560 doc
: /* Precomputed `signal' argument for memory-full error. */);
7561 /* We build this in advance because if we wait until we need it, we might
7562 not be able to allocate the memory to hold it. */
7564 = listn (CONSTYPE_PURE
, 2, Qerror
,
7565 build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
7567 DEFVAR_LISP ("memory-full", Vmemory_full
,
7568 doc
: /* Non-nil means Emacs cannot get much more Lisp memory. */);
7569 Vmemory_full
= Qnil
;
7571 DEFSYM (Qconses
, "conses");
7572 DEFSYM (Qsymbols
, "symbols");
7573 DEFSYM (Qmiscs
, "miscs");
7574 DEFSYM (Qstrings
, "strings");
7575 DEFSYM (Qvectors
, "vectors");
7576 DEFSYM (Qfloats
, "floats");
7577 DEFSYM (Qintervals
, "intervals");
7578 DEFSYM (Qbuffers
, "buffers");
7579 DEFSYM (Qstring_bytes
, "string-bytes");
7580 DEFSYM (Qvector_slots
, "vector-slots");
7581 DEFSYM (Qheap
, "heap");
7582 DEFSYM (QAutomatic_GC
, "Automatic GC");
7584 DEFSYM (Qgc_cons_threshold
, "gc-cons-threshold");
7585 DEFSYM (Qchar_table_extra_slots
, "char-table-extra-slots");
7587 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed
,
7588 doc
: /* Accumulated time elapsed in garbage collections.
7589 The time is in seconds as a floating point value. */);
7590 DEFVAR_INT ("gcs-done", gcs_done
,
7591 doc
: /* Accumulated number of garbage collections done. */);
7597 defsubr (&Sbool_vector
);
7598 defsubr (&Smake_byte_code
);
7599 defsubr (&Smake_list
);
7600 defsubr (&Smake_vector
);
7601 defsubr (&Smake_record
);
7602 defsubr (&Smake_string
);
7603 defsubr (&Smake_bool_vector
);
7604 defsubr (&Smake_symbol
);
7605 defsubr (&Smake_marker
);
7606 defsubr (&Smake_finalizer
);
7607 defsubr (&Spurecopy
);
7608 defsubr (&Sgarbage_collect
);
7609 defsubr (&Smemory_limit
);
7610 defsubr (&Smemory_info
);
7611 defsubr (&Smemory_use_counts
);
7612 defsubr (&Ssuspicious_object
);
7615 /* When compiled with GCC, GDB might say "No enum type named
7616 pvec_type" if we don't have at least one symbol with that type, and
7617 then xbacktrace could fail. Similarly for the other enums and
7618 their values. Some non-GCC compilers don't like these constructs. */
7622 enum CHARTAB_SIZE_BITS CHARTAB_SIZE_BITS
;
7623 enum char_table_specials char_table_specials
;
7624 enum char_bits char_bits
;
7625 enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE
;
7626 enum DEFAULT_HASH_SIZE DEFAULT_HASH_SIZE
;
7627 enum Lisp_Bits Lisp_Bits
;
7628 enum Lisp_Compiled Lisp_Compiled
;
7629 enum maxargs maxargs
;
7630 enum MAX_ALLOCA MAX_ALLOCA
;
7631 enum More_Lisp_Bits More_Lisp_Bits
;
7632 enum pvec_type pvec_type
;
7633 } const EXTERNALLY_VISIBLE gdb_make_enums_visible
= {0};
7634 #endif /* __GNUC__ */