Fix last commit in w32term.c.
[emacs.git] / src / alloc.c
bloba8ad44491fad7f3ba8318a5ed8597d04a1a18288
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2014 Free Software
4 Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
23 #include <stdio.h>
24 #include <limits.h> /* For CHAR_BIT. */
26 #ifdef ENABLE_CHECKING
27 #include <signal.h> /* For SIGABRT. */
28 #endif
30 #ifdef HAVE_PTHREAD
31 #include <pthread.h>
32 #endif
34 #include "lisp.h"
35 #include "process.h"
36 #include "intervals.h"
37 #include "puresize.h"
38 #include "character.h"
39 #include "buffer.h"
40 #include "window.h"
41 #include "keyboard.h"
42 #include "frame.h"
43 #include "blockinput.h"
44 #include "termhooks.h" /* For struct terminal. */
45 #ifdef HAVE_WINDOW_SYSTEM
46 #include TERM_HEADER
47 #endif /* HAVE_WINDOW_SYSTEM */
49 #include <verify.h>
50 #include <execinfo.h> /* For backtrace. */
52 #ifdef HAVE_LINUX_SYSINFO
53 #include <sys/sysinfo.h>
54 #endif
56 #ifdef MSDOS
57 #include "dosfns.h" /* For dos_memory_info. */
58 #endif
60 #if (defined ENABLE_CHECKING \
61 && defined HAVE_VALGRIND_VALGRIND_H \
62 && !defined USE_VALGRIND)
63 # define USE_VALGRIND 1
64 #endif
66 #if USE_VALGRIND
67 #include <valgrind/valgrind.h>
68 #include <valgrind/memcheck.h>
69 static bool valgrind_p;
70 #endif
72 /* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects.
73 Doable only if GC_MARK_STACK. */
74 #if ! GC_MARK_STACK
75 # undef GC_CHECK_MARKED_OBJECTS
76 #endif
78 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
79 memory. Can do this only if using gmalloc.c and if not checking
80 marked objects. */
82 #if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
83 || defined GC_CHECK_MARKED_OBJECTS)
84 #undef GC_MALLOC_CHECK
85 #endif
87 #include <unistd.h>
88 #include <fcntl.h>
90 #ifdef USE_GTK
91 # include "gtkutil.h"
92 #endif
93 #ifdef WINDOWSNT
94 #include "w32.h"
95 #include "w32heap.h" /* for sbrk */
96 #endif
98 #ifdef DOUG_LEA_MALLOC
100 #include <malloc.h>
102 /* Specify maximum number of areas to mmap. It would be nice to use a
103 value that explicitly means "no limit". */
105 #define MMAP_MAX_AREAS 100000000
107 #endif /* not DOUG_LEA_MALLOC */
109 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
110 to a struct Lisp_String. */
112 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
113 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
114 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
116 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
117 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
118 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
120 /* Default value of gc_cons_threshold (see below). */
122 #define GC_DEFAULT_THRESHOLD (100000 * word_size)
124 /* Global variables. */
125 struct emacs_globals globals;
127 /* Number of bytes of consing done since the last gc. */
129 EMACS_INT consing_since_gc;
131 /* Similar minimum, computed from Vgc_cons_percentage. */
133 EMACS_INT gc_relative_threshold;
135 /* Minimum number of bytes of consing since GC before next GC,
136 when memory is full. */
138 EMACS_INT memory_full_cons_threshold;
140 /* True during GC. */
142 bool gc_in_progress;
144 /* True means abort if try to GC.
145 This is for code which is written on the assumption that
146 no GC will happen, so as to verify that assumption. */
148 bool abort_on_gc;
150 /* Number of live and free conses etc. */
152 static EMACS_INT total_conses, total_markers, total_symbols, total_buffers;
153 static EMACS_INT total_free_conses, total_free_markers, total_free_symbols;
154 static EMACS_INT total_free_floats, total_floats;
156 /* Points to memory space allocated as "spare", to be freed if we run
157 out of memory. We keep one large block, four cons-blocks, and
158 two string blocks. */
160 static char *spare_memory[7];
162 /* Amount of spare memory to keep in large reserve block, or to see
163 whether this much is available when malloc fails on a larger request. */
165 #define SPARE_MEMORY (1 << 14)
167 /* Initialize it to a nonzero value to force it into data space
168 (rather than bss space). That way unexec will remap it into text
169 space (pure), on some systems. We have not implemented the
170 remapping on more recent systems because this is less important
171 nowadays than in the days of small memories and timesharing. */
173 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
174 #define PUREBEG (char *) pure
176 /* Pointer to the pure area, and its size. */
178 static char *purebeg;
179 static ptrdiff_t pure_size;
181 /* Number of bytes of pure storage used before pure storage overflowed.
182 If this is non-zero, this implies that an overflow occurred. */
184 static ptrdiff_t pure_bytes_used_before_overflow;
186 /* True if P points into pure space. */
188 #define PURE_POINTER_P(P) \
189 ((uintptr_t) (P) - (uintptr_t) purebeg <= pure_size)
191 /* Index in pure at which next pure Lisp object will be allocated.. */
193 static ptrdiff_t pure_bytes_used_lisp;
195 /* Number of bytes allocated for non-Lisp objects in pure storage. */
197 static ptrdiff_t pure_bytes_used_non_lisp;
199 /* If nonzero, this is a warning delivered by malloc and not yet
200 displayed. */
202 const char *pending_malloc_warning;
204 #if 0 /* Normally, pointer sanity only on request... */
205 #ifdef ENABLE_CHECKING
206 #define SUSPICIOUS_OBJECT_CHECKING 1
207 #endif
208 #endif
210 /* ... but unconditionally use SUSPICIOUS_OBJECT_CHECKING while the GC
211 bug is unresolved. */
212 #define SUSPICIOUS_OBJECT_CHECKING 1
214 #ifdef SUSPICIOUS_OBJECT_CHECKING
215 struct suspicious_free_record
217 void *suspicious_object;
218 void *backtrace[128];
220 static void *suspicious_objects[32];
221 static int suspicious_object_index;
222 struct suspicious_free_record suspicious_free_history[64] EXTERNALLY_VISIBLE;
223 static int suspicious_free_history_index;
224 /* Find the first currently-monitored suspicious pointer in range
225 [begin,end) or NULL if no such pointer exists. */
226 static void *find_suspicious_object_in_range (void *begin, void *end);
227 static void detect_suspicious_free (void *ptr);
228 #else
229 # define find_suspicious_object_in_range(begin, end) NULL
230 # define detect_suspicious_free(ptr) (void)
231 #endif
233 /* Maximum amount of C stack to save when a GC happens. */
235 #ifndef MAX_SAVE_STACK
236 #define MAX_SAVE_STACK 16000
237 #endif
239 /* Buffer in which we save a copy of the C stack at each GC. */
241 #if MAX_SAVE_STACK > 0
242 static char *stack_copy;
243 static ptrdiff_t stack_copy_size;
245 /* Copy to DEST a block of memory from SRC of size SIZE bytes,
246 avoiding any address sanitization. */
248 static void * ATTRIBUTE_NO_SANITIZE_ADDRESS
249 no_sanitize_memcpy (void *dest, void const *src, size_t size)
251 if (! ADDRESS_SANITIZER)
252 return memcpy (dest, src, size);
253 else
255 size_t i;
256 char *d = dest;
257 char const *s = src;
258 for (i = 0; i < size; i++)
259 d[i] = s[i];
260 return dest;
264 #endif /* MAX_SAVE_STACK > 0 */
266 static Lisp_Object Qconses;
267 static Lisp_Object Qsymbols;
268 static Lisp_Object Qmiscs;
269 static Lisp_Object Qstrings;
270 static Lisp_Object Qvectors;
271 static Lisp_Object Qfloats;
272 static Lisp_Object Qintervals;
273 static Lisp_Object Qbuffers;
274 static Lisp_Object Qstring_bytes, Qvector_slots, Qheap;
275 static Lisp_Object Qgc_cons_threshold;
276 Lisp_Object Qautomatic_gc;
277 Lisp_Object Qchar_table_extra_slots;
279 /* Hook run after GC has finished. */
281 static Lisp_Object Qpost_gc_hook;
283 static void mark_terminals (void);
284 static void gc_sweep (void);
285 static Lisp_Object make_pure_vector (ptrdiff_t);
286 static void mark_buffer (struct buffer *);
288 #if !defined REL_ALLOC || defined SYSTEM_MALLOC
289 static void refill_memory_reserve (void);
290 #endif
291 static void compact_small_strings (void);
292 static void free_large_strings (void);
293 extern Lisp_Object which_symbols (Lisp_Object, EMACS_INT) EXTERNALLY_VISIBLE;
295 /* When scanning the C stack for live Lisp objects, Emacs keeps track of
296 what memory allocated via lisp_malloc and lisp_align_malloc is intended
297 for what purpose. This enumeration specifies the type of memory. */
299 enum mem_type
301 MEM_TYPE_NON_LISP,
302 MEM_TYPE_BUFFER,
303 MEM_TYPE_CONS,
304 MEM_TYPE_STRING,
305 MEM_TYPE_MISC,
306 MEM_TYPE_SYMBOL,
307 MEM_TYPE_FLOAT,
308 /* Since all non-bool pseudovectors are small enough to be
309 allocated from vector blocks, this memory type denotes
310 large regular vectors and large bool pseudovectors. */
311 MEM_TYPE_VECTORLIKE,
312 /* Special type to denote vector blocks. */
313 MEM_TYPE_VECTOR_BLOCK,
314 /* Special type to denote reserved memory. */
315 MEM_TYPE_SPARE
318 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
320 /* A unique object in pure space used to make some Lisp objects
321 on free lists recognizable in O(1). */
323 static Lisp_Object Vdead;
324 #define DEADP(x) EQ (x, Vdead)
326 #ifdef GC_MALLOC_CHECK
328 enum mem_type allocated_mem_type;
330 #endif /* GC_MALLOC_CHECK */
332 /* A node in the red-black tree describing allocated memory containing
333 Lisp data. Each such block is recorded with its start and end
334 address when it is allocated, and removed from the tree when it
335 is freed.
337 A red-black tree is a balanced binary tree with the following
338 properties:
340 1. Every node is either red or black.
341 2. Every leaf is black.
342 3. If a node is red, then both of its children are black.
343 4. Every simple path from a node to a descendant leaf contains
344 the same number of black nodes.
345 5. The root is always black.
347 When nodes are inserted into the tree, or deleted from the tree,
348 the tree is "fixed" so that these properties are always true.
350 A red-black tree with N internal nodes has height at most 2
351 log(N+1). Searches, insertions and deletions are done in O(log N).
352 Please see a text book about data structures for a detailed
353 description of red-black trees. Any book worth its salt should
354 describe them. */
356 struct mem_node
358 /* Children of this node. These pointers are never NULL. When there
359 is no child, the value is MEM_NIL, which points to a dummy node. */
360 struct mem_node *left, *right;
362 /* The parent of this node. In the root node, this is NULL. */
363 struct mem_node *parent;
365 /* Start and end of allocated region. */
366 void *start, *end;
368 /* Node color. */
369 enum {MEM_BLACK, MEM_RED} color;
371 /* Memory type. */
372 enum mem_type type;
375 /* Base address of stack. Set in main. */
377 Lisp_Object *stack_base;
379 /* Root of the tree describing allocated Lisp memory. */
381 static struct mem_node *mem_root;
383 /* Lowest and highest known address in the heap. */
385 static void *min_heap_address, *max_heap_address;
387 /* Sentinel node of the tree. */
389 static struct mem_node mem_z;
390 #define MEM_NIL &mem_z
392 static struct mem_node *mem_insert (void *, void *, enum mem_type);
393 static void mem_insert_fixup (struct mem_node *);
394 static void mem_rotate_left (struct mem_node *);
395 static void mem_rotate_right (struct mem_node *);
396 static void mem_delete (struct mem_node *);
397 static void mem_delete_fixup (struct mem_node *);
398 static struct mem_node *mem_find (void *);
400 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
402 #ifndef DEADP
403 # define DEADP(x) 0
404 #endif
406 /* Recording what needs to be marked for gc. */
408 struct gcpro *gcprolist;
410 /* Addresses of staticpro'd variables. Initialize it to a nonzero
411 value; otherwise some compilers put it into BSS. */
413 enum { NSTATICS = 2048 };
414 static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
416 /* Index of next unused slot in staticvec. */
418 static int staticidx;
420 static void *pure_alloc (size_t, int);
422 /* Return X rounded to the next multiple of Y. Arguments should not
423 have side effects, as they are evaluated more than once. Assume X
424 + Y - 1 does not overflow. Tune for Y being a power of 2. */
426 #define ROUNDUP(x, y) ((y) & ((y) - 1) \
427 ? ((x) + (y) - 1) - ((x) + (y) - 1) % (y) \
428 : ((x) + (y) - 1) & ~ ((y) - 1))
430 /* Return PTR rounded up to the next multiple of ALIGNMENT. */
432 static void *
433 ALIGN (void *ptr, int alignment)
435 return (void *) ROUNDUP ((uintptr_t) ptr, alignment);
438 static void
439 XFLOAT_INIT (Lisp_Object f, double n)
441 XFLOAT (f)->u.data = n;
444 static bool
445 pointers_fit_in_lispobj_p (void)
447 return (UINTPTR_MAX <= VAL_MAX) || USE_LSB_TAG;
450 static bool
451 mmap_lisp_allowed_p (void)
453 /* If we can't store all memory addresses in our lisp objects, it's
454 risky to let the heap use mmap and give us addresses from all
455 over our address space. We also can't use mmap for lisp objects
456 if we might dump: unexec doesn't preserve the contents of mmaped
457 regions. */
458 return pointers_fit_in_lispobj_p () && !might_dump;
462 /************************************************************************
463 Malloc
464 ************************************************************************/
466 /* Function malloc calls this if it finds we are near exhausting storage. */
468 void
469 malloc_warning (const char *str)
471 pending_malloc_warning = str;
475 /* Display an already-pending malloc warning. */
477 void
478 display_malloc_warning (void)
480 call3 (intern ("display-warning"),
481 intern ("alloc"),
482 build_string (pending_malloc_warning),
483 intern ("emergency"));
484 pending_malloc_warning = 0;
487 /* Called if we can't allocate relocatable space for a buffer. */
489 void
490 buffer_memory_full (ptrdiff_t nbytes)
492 /* If buffers use the relocating allocator, no need to free
493 spare_memory, because we may have plenty of malloc space left
494 that we could get, and if we don't, the malloc that fails will
495 itself cause spare_memory to be freed. If buffers don't use the
496 relocating allocator, treat this like any other failing
497 malloc. */
499 #ifndef REL_ALLOC
500 memory_full (nbytes);
501 #else
502 /* This used to call error, but if we've run out of memory, we could
503 get infinite recursion trying to build the string. */
504 xsignal (Qnil, Vmemory_signal_data);
505 #endif
508 /* A common multiple of the positive integers A and B. Ideally this
509 would be the least common multiple, but there's no way to do that
510 as a constant expression in C, so do the best that we can easily do. */
511 #define COMMON_MULTIPLE(a, b) \
512 ((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
514 #ifndef XMALLOC_OVERRUN_CHECK
515 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
516 #else
518 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
519 around each block.
521 The header consists of XMALLOC_OVERRUN_CHECK_SIZE fixed bytes
522 followed by XMALLOC_OVERRUN_SIZE_SIZE bytes containing the original
523 block size in little-endian order. The trailer consists of
524 XMALLOC_OVERRUN_CHECK_SIZE fixed bytes.
526 The header is used to detect whether this block has been allocated
527 through these functions, as some low-level libc functions may
528 bypass the malloc hooks. */
530 #define XMALLOC_OVERRUN_CHECK_SIZE 16
531 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
532 (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)
534 /* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
535 hold a size_t value and (2) the header size is a multiple of the
536 alignment that Emacs needs for C types and for USE_LSB_TAG. */
537 #define XMALLOC_BASE_ALIGNMENT \
538 alignof (union { long double d; intmax_t i; void *p; })
540 #if USE_LSB_TAG
541 # define XMALLOC_HEADER_ALIGNMENT \
542 COMMON_MULTIPLE (GCALIGNMENT, XMALLOC_BASE_ALIGNMENT)
543 #else
544 # define XMALLOC_HEADER_ALIGNMENT XMALLOC_BASE_ALIGNMENT
545 #endif
546 #define XMALLOC_OVERRUN_SIZE_SIZE \
547 (((XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t) \
548 + XMALLOC_HEADER_ALIGNMENT - 1) \
549 / XMALLOC_HEADER_ALIGNMENT * XMALLOC_HEADER_ALIGNMENT) \
550 - XMALLOC_OVERRUN_CHECK_SIZE)
552 static char const xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE] =
553 { '\x9a', '\x9b', '\xae', '\xaf',
554 '\xbf', '\xbe', '\xce', '\xcf',
555 '\xea', '\xeb', '\xec', '\xed',
556 '\xdf', '\xde', '\x9c', '\x9d' };
558 static char const xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
559 { '\xaa', '\xab', '\xac', '\xad',
560 '\xba', '\xbb', '\xbc', '\xbd',
561 '\xca', '\xcb', '\xcc', '\xcd',
562 '\xda', '\xdb', '\xdc', '\xdd' };
564 /* Insert and extract the block size in the header. */
566 static void
567 xmalloc_put_size (unsigned char *ptr, size_t size)
569 int i;
570 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
572 *--ptr = size & ((1 << CHAR_BIT) - 1);
573 size >>= CHAR_BIT;
577 static size_t
578 xmalloc_get_size (unsigned char *ptr)
580 size_t size = 0;
581 int i;
582 ptr -= XMALLOC_OVERRUN_SIZE_SIZE;
583 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
585 size <<= CHAR_BIT;
586 size += *ptr++;
588 return size;
592 /* Like malloc, but wraps allocated block with header and trailer. */
594 static void *
595 overrun_check_malloc (size_t size)
597 register unsigned char *val;
598 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
599 emacs_abort ();
601 val = malloc (size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
602 if (val)
604 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
605 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
606 xmalloc_put_size (val, size);
607 memcpy (val + size, xmalloc_overrun_check_trailer,
608 XMALLOC_OVERRUN_CHECK_SIZE);
610 return val;
614 /* Like realloc, but checks old block for overrun, and wraps new block
615 with header and trailer. */
617 static void *
618 overrun_check_realloc (void *block, size_t size)
620 register unsigned char *val = (unsigned char *) block;
621 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
622 emacs_abort ();
624 if (val
625 && memcmp (xmalloc_overrun_check_header,
626 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
627 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
629 size_t osize = xmalloc_get_size (val);
630 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
631 XMALLOC_OVERRUN_CHECK_SIZE))
632 emacs_abort ();
633 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
634 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
635 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
638 val = realloc (val, size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
640 if (val)
642 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
643 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
644 xmalloc_put_size (val, size);
645 memcpy (val + size, xmalloc_overrun_check_trailer,
646 XMALLOC_OVERRUN_CHECK_SIZE);
648 return val;
651 /* Like free, but checks block for overrun. */
653 static void
654 overrun_check_free (void *block)
656 unsigned char *val = (unsigned char *) block;
658 if (val
659 && memcmp (xmalloc_overrun_check_header,
660 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
661 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
663 size_t osize = xmalloc_get_size (val);
664 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
665 XMALLOC_OVERRUN_CHECK_SIZE))
666 emacs_abort ();
667 #ifdef XMALLOC_CLEAR_FREE_MEMORY
668 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
669 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_OVERHEAD);
670 #else
671 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
672 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
673 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
674 #endif
677 free (val);
680 #undef malloc
681 #undef realloc
682 #undef free
683 #define malloc overrun_check_malloc
684 #define realloc overrun_check_realloc
685 #define free overrun_check_free
686 #endif
688 /* If compiled with XMALLOC_BLOCK_INPUT_CHECK, define a symbol
689 BLOCK_INPUT_IN_MEMORY_ALLOCATORS that is visible to the debugger.
690 If that variable is set, block input while in one of Emacs's memory
691 allocation functions. There should be no need for this debugging
692 option, since signal handlers do not allocate memory, but Emacs
693 formerly allocated memory in signal handlers and this compile-time
694 option remains as a way to help debug the issue should it rear its
695 ugly head again. */
696 #ifdef XMALLOC_BLOCK_INPUT_CHECK
697 bool block_input_in_memory_allocators EXTERNALLY_VISIBLE;
698 static void
699 malloc_block_input (void)
701 if (block_input_in_memory_allocators)
702 block_input ();
704 static void
705 malloc_unblock_input (void)
707 if (block_input_in_memory_allocators)
708 unblock_input ();
710 # define MALLOC_BLOCK_INPUT malloc_block_input ()
711 # define MALLOC_UNBLOCK_INPUT malloc_unblock_input ()
712 #else
713 # define MALLOC_BLOCK_INPUT ((void) 0)
714 # define MALLOC_UNBLOCK_INPUT ((void) 0)
715 #endif
717 #define MALLOC_PROBE(size) \
718 do { \
719 if (profiler_memory_running) \
720 malloc_probe (size); \
721 } while (0)
724 /* Like malloc but check for no memory and block interrupt input.. */
726 void *
727 xmalloc (size_t size)
729 void *val;
731 MALLOC_BLOCK_INPUT;
732 val = malloc (size);
733 MALLOC_UNBLOCK_INPUT;
735 if (!val && size)
736 memory_full (size);
737 MALLOC_PROBE (size);
738 return val;
741 /* Like the above, but zeroes out the memory just allocated. */
743 void *
744 xzalloc (size_t size)
746 void *val;
748 MALLOC_BLOCK_INPUT;
749 val = malloc (size);
750 MALLOC_UNBLOCK_INPUT;
752 if (!val && size)
753 memory_full (size);
754 memset (val, 0, size);
755 MALLOC_PROBE (size);
756 return val;
759 /* Like realloc but check for no memory and block interrupt input.. */
761 void *
762 xrealloc (void *block, size_t size)
764 void *val;
766 MALLOC_BLOCK_INPUT;
767 /* We must call malloc explicitly when BLOCK is 0, since some
768 reallocs don't do this. */
769 if (! block)
770 val = malloc (size);
771 else
772 val = realloc (block, size);
773 MALLOC_UNBLOCK_INPUT;
775 if (!val && size)
776 memory_full (size);
777 MALLOC_PROBE (size);
778 return val;
782 /* Like free but block interrupt input. */
784 void
785 xfree (void *block)
787 if (!block)
788 return;
789 MALLOC_BLOCK_INPUT;
790 free (block);
791 MALLOC_UNBLOCK_INPUT;
792 /* We don't call refill_memory_reserve here
793 because in practice the call in r_alloc_free seems to suffice. */
797 /* Other parts of Emacs pass large int values to allocator functions
798 expecting ptrdiff_t. This is portable in practice, but check it to
799 be safe. */
800 verify (INT_MAX <= PTRDIFF_MAX);
803 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
804 Signal an error on memory exhaustion, and block interrupt input. */
806 void *
807 xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
809 eassert (0 <= nitems && 0 < item_size);
810 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
811 memory_full (SIZE_MAX);
812 return xmalloc (nitems * item_size);
816 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
817 Signal an error on memory exhaustion, and block interrupt input. */
819 void *
820 xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
822 eassert (0 <= nitems && 0 < item_size);
823 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
824 memory_full (SIZE_MAX);
825 return xrealloc (pa, nitems * item_size);
829 /* Grow PA, which points to an array of *NITEMS items, and return the
830 location of the reallocated array, updating *NITEMS to reflect its
831 new size. The new array will contain at least NITEMS_INCR_MIN more
832 items, but will not contain more than NITEMS_MAX items total.
833 ITEM_SIZE is the size of each item, in bytes.
835 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
836 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
837 infinity.
839 If PA is null, then allocate a new array instead of reallocating
840 the old one.
842 Block interrupt input as needed. If memory exhaustion occurs, set
843 *NITEMS to zero if PA is null, and signal an error (i.e., do not
844 return).
846 Thus, to grow an array A without saving its old contents, do
847 { xfree (A); A = NULL; A = xpalloc (NULL, &AITEMS, ...); }.
848 The A = NULL avoids a dangling pointer if xpalloc exhausts memory
849 and signals an error, and later this code is reexecuted and
850 attempts to free A. */
852 void *
853 xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
854 ptrdiff_t nitems_max, ptrdiff_t item_size)
856 /* The approximate size to use for initial small allocation
857 requests. This is the largest "small" request for the GNU C
858 library malloc. */
859 enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
861 /* If the array is tiny, grow it to about (but no greater than)
862 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%. */
863 ptrdiff_t n = *nitems;
864 ptrdiff_t tiny_max = DEFAULT_MXFAST / item_size - n;
865 ptrdiff_t half_again = n >> 1;
866 ptrdiff_t incr_estimate = max (tiny_max, half_again);
868 /* Adjust the increment according to three constraints: NITEMS_INCR_MIN,
869 NITEMS_MAX, and what the C language can represent safely. */
870 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / item_size;
871 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
872 ? nitems_max : C_language_max);
873 ptrdiff_t nitems_incr_max = n_max - n;
874 ptrdiff_t incr = max (nitems_incr_min, min (incr_estimate, nitems_incr_max));
876 eassert (0 < item_size && 0 < nitems_incr_min && 0 <= n && -1 <= nitems_max);
877 if (! pa)
878 *nitems = 0;
879 if (nitems_incr_max < incr)
880 memory_full (SIZE_MAX);
881 n += incr;
882 pa = xrealloc (pa, n * item_size);
883 *nitems = n;
884 return pa;
888 /* Like strdup, but uses xmalloc. */
890 char *
891 xstrdup (const char *s)
893 ptrdiff_t size;
894 eassert (s);
895 size = strlen (s) + 1;
896 return memcpy (xmalloc (size), s, size);
899 /* Like above, but duplicates Lisp string to C string. */
901 char *
902 xlispstrdup (Lisp_Object string)
904 ptrdiff_t size = SBYTES (string) + 1;
905 return memcpy (xmalloc (size), SSDATA (string), size);
908 /* Assign to *PTR a copy of STRING, freeing any storage *PTR formerly
909 pointed to. If STRING is null, assign it without copying anything.
910 Allocate before freeing, to avoid a dangling pointer if allocation
911 fails. */
913 void
914 dupstring (char **ptr, char const *string)
916 char *old = *ptr;
917 *ptr = string ? xstrdup (string) : 0;
918 xfree (old);
922 /* Like putenv, but (1) use the equivalent of xmalloc and (2) the
923 argument is a const pointer. */
925 void
926 xputenv (char const *string)
928 if (putenv ((char *) string) != 0)
929 memory_full (0);
932 /* Return a newly allocated memory block of SIZE bytes, remembering
933 to free it when unwinding. */
934 void *
935 record_xmalloc (size_t size)
937 void *p = xmalloc (size);
938 record_unwind_protect_ptr (xfree, p);
939 return p;
943 /* Like malloc but used for allocating Lisp data. NBYTES is the
944 number of bytes to allocate, TYPE describes the intended use of the
945 allocated memory block (for strings, for conses, ...). */
947 #if ! USE_LSB_TAG
948 void *lisp_malloc_loser EXTERNALLY_VISIBLE;
949 #endif
951 static void *
952 lisp_malloc (size_t nbytes, enum mem_type type)
954 register void *val;
956 MALLOC_BLOCK_INPUT;
958 #ifdef GC_MALLOC_CHECK
959 allocated_mem_type = type;
960 #endif
962 val = malloc (nbytes);
964 #if ! USE_LSB_TAG
965 /* If the memory just allocated cannot be addressed thru a Lisp
966 object's pointer, and it needs to be,
967 that's equivalent to running out of memory. */
968 if (val && type != MEM_TYPE_NON_LISP)
970 Lisp_Object tem;
971 XSETCONS (tem, (char *) val + nbytes - 1);
972 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
974 lisp_malloc_loser = val;
975 free (val);
976 val = 0;
979 #endif
981 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
982 if (val && type != MEM_TYPE_NON_LISP)
983 mem_insert (val, (char *) val + nbytes, type);
984 #endif
986 MALLOC_UNBLOCK_INPUT;
987 if (!val && nbytes)
988 memory_full (nbytes);
989 MALLOC_PROBE (nbytes);
990 return val;
993 /* Free BLOCK. This must be called to free memory allocated with a
994 call to lisp_malloc. */
996 static void
997 lisp_free (void *block)
999 MALLOC_BLOCK_INPUT;
1000 free (block);
1001 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1002 mem_delete (mem_find (block));
1003 #endif
1004 MALLOC_UNBLOCK_INPUT;
1007 /***** Allocation of aligned blocks of memory to store Lisp data. *****/
1009 /* The entry point is lisp_align_malloc which returns blocks of at most
1010 BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
1012 /* Use aligned_alloc if it or a simple substitute is available.
1013 Address sanitization breaks aligned allocation, as of gcc 4.8.2 and
1014 clang 3.3 anyway. */
1016 #if ! ADDRESS_SANITIZER
1017 # if !defined SYSTEM_MALLOC && !defined DOUG_LEA_MALLOC
1018 # define USE_ALIGNED_ALLOC 1
1019 /* Defined in gmalloc.c. */
1020 void *aligned_alloc (size_t, size_t);
1021 # elif defined HAVE_ALIGNED_ALLOC
1022 # define USE_ALIGNED_ALLOC 1
1023 # elif defined HAVE_POSIX_MEMALIGN
1024 # define USE_ALIGNED_ALLOC 1
1025 static void *
1026 aligned_alloc (size_t alignment, size_t size)
1028 void *p;
1029 return posix_memalign (&p, alignment, size) == 0 ? p : 0;
1031 # endif
1032 #endif
1034 /* BLOCK_ALIGN has to be a power of 2. */
1035 #define BLOCK_ALIGN (1 << 10)
1037 /* Padding to leave at the end of a malloc'd block. This is to give
1038 malloc a chance to minimize the amount of memory wasted to alignment.
1039 It should be tuned to the particular malloc library used.
1040 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
1041 aligned_alloc on the other hand would ideally prefer a value of 4
1042 because otherwise, there's 1020 bytes wasted between each ablocks.
1043 In Emacs, testing shows that those 1020 can most of the time be
1044 efficiently used by malloc to place other objects, so a value of 0 can
1045 still preferable unless you have a lot of aligned blocks and virtually
1046 nothing else. */
1047 #define BLOCK_PADDING 0
1048 #define BLOCK_BYTES \
1049 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
1051 /* Internal data structures and constants. */
1053 #define ABLOCKS_SIZE 16
1055 /* An aligned block of memory. */
1056 struct ablock
1058 union
1060 char payload[BLOCK_BYTES];
1061 struct ablock *next_free;
1062 } x;
1063 /* `abase' is the aligned base of the ablocks. */
1064 /* It is overloaded to hold the virtual `busy' field that counts
1065 the number of used ablock in the parent ablocks.
1066 The first ablock has the `busy' field, the others have the `abase'
1067 field. To tell the difference, we assume that pointers will have
1068 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
1069 is used to tell whether the real base of the parent ablocks is `abase'
1070 (if not, the word before the first ablock holds a pointer to the
1071 real base). */
1072 struct ablocks *abase;
1073 /* The padding of all but the last ablock is unused. The padding of
1074 the last ablock in an ablocks is not allocated. */
1075 #if BLOCK_PADDING
1076 char padding[BLOCK_PADDING];
1077 #endif
1080 /* A bunch of consecutive aligned blocks. */
1081 struct ablocks
1083 struct ablock blocks[ABLOCKS_SIZE];
1086 /* Size of the block requested from malloc or aligned_alloc. */
1087 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
1089 #define ABLOCK_ABASE(block) \
1090 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
1091 ? (struct ablocks *)(block) \
1092 : (block)->abase)
1094 /* Virtual `busy' field. */
1095 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
1097 /* Pointer to the (not necessarily aligned) malloc block. */
1098 #ifdef USE_ALIGNED_ALLOC
1099 #define ABLOCKS_BASE(abase) (abase)
1100 #else
1101 #define ABLOCKS_BASE(abase) \
1102 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void **)abase)[-1])
1103 #endif
1105 /* The list of free ablock. */
1106 static struct ablock *free_ablock;
1108 /* Allocate an aligned block of nbytes.
1109 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
1110 smaller or equal to BLOCK_BYTES. */
1111 static void *
1112 lisp_align_malloc (size_t nbytes, enum mem_type type)
1114 void *base, *val;
1115 struct ablocks *abase;
1117 eassert (nbytes <= BLOCK_BYTES);
1119 MALLOC_BLOCK_INPUT;
1121 #ifdef GC_MALLOC_CHECK
1122 allocated_mem_type = type;
1123 #endif
1125 if (!free_ablock)
1127 int i;
1128 intptr_t aligned; /* int gets warning casting to 64-bit pointer. */
1130 #ifdef DOUG_LEA_MALLOC
1131 if (!mmap_lisp_allowed_p ())
1132 mallopt (M_MMAP_MAX, 0);
1133 #endif
1135 #ifdef USE_ALIGNED_ALLOC
1136 abase = base = aligned_alloc (BLOCK_ALIGN, ABLOCKS_BYTES);
1137 #else
1138 base = malloc (ABLOCKS_BYTES);
1139 abase = ALIGN (base, BLOCK_ALIGN);
1140 #endif
1142 if (base == 0)
1144 MALLOC_UNBLOCK_INPUT;
1145 memory_full (ABLOCKS_BYTES);
1148 aligned = (base == abase);
1149 if (!aligned)
1150 ((void **) abase)[-1] = base;
1152 #ifdef DOUG_LEA_MALLOC
1153 if (!mmap_lisp_allowed_p ())
1154 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1155 #endif
1157 #if ! USE_LSB_TAG
1158 /* If the memory just allocated cannot be addressed thru a Lisp
1159 object's pointer, and it needs to be, that's equivalent to
1160 running out of memory. */
1161 if (type != MEM_TYPE_NON_LISP)
1163 Lisp_Object tem;
1164 char *end = (char *) base + ABLOCKS_BYTES - 1;
1165 XSETCONS (tem, end);
1166 if ((char *) XCONS (tem) != end)
1168 lisp_malloc_loser = base;
1169 free (base);
1170 MALLOC_UNBLOCK_INPUT;
1171 memory_full (SIZE_MAX);
1174 #endif
1176 /* Initialize the blocks and put them on the free list.
1177 If `base' was not properly aligned, we can't use the last block. */
1178 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1180 abase->blocks[i].abase = abase;
1181 abase->blocks[i].x.next_free = free_ablock;
1182 free_ablock = &abase->blocks[i];
1184 ABLOCKS_BUSY (abase) = (struct ablocks *) aligned;
1186 eassert (0 == ((uintptr_t) abase) % BLOCK_ALIGN);
1187 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1188 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1189 eassert (ABLOCKS_BASE (abase) == base);
1190 eassert (aligned == (intptr_t) ABLOCKS_BUSY (abase));
1193 abase = ABLOCK_ABASE (free_ablock);
1194 ABLOCKS_BUSY (abase)
1195 = (struct ablocks *) (2 + (intptr_t) ABLOCKS_BUSY (abase));
1196 val = free_ablock;
1197 free_ablock = free_ablock->x.next_free;
1199 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1200 if (type != MEM_TYPE_NON_LISP)
1201 mem_insert (val, (char *) val + nbytes, type);
1202 #endif
1204 MALLOC_UNBLOCK_INPUT;
1206 MALLOC_PROBE (nbytes);
1208 eassert (0 == ((uintptr_t) val) % BLOCK_ALIGN);
1209 return val;
1212 static void
1213 lisp_align_free (void *block)
1215 struct ablock *ablock = block;
1216 struct ablocks *abase = ABLOCK_ABASE (ablock);
1218 MALLOC_BLOCK_INPUT;
1219 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1220 mem_delete (mem_find (block));
1221 #endif
1222 /* Put on free list. */
1223 ablock->x.next_free = free_ablock;
1224 free_ablock = ablock;
1225 /* Update busy count. */
1226 ABLOCKS_BUSY (abase)
1227 = (struct ablocks *) (-2 + (intptr_t) ABLOCKS_BUSY (abase));
1229 if (2 > (intptr_t) ABLOCKS_BUSY (abase))
1230 { /* All the blocks are free. */
1231 int i = 0, aligned = (intptr_t) ABLOCKS_BUSY (abase);
1232 struct ablock **tem = &free_ablock;
1233 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1235 while (*tem)
1237 if (*tem >= (struct ablock *) abase && *tem < atop)
1239 i++;
1240 *tem = (*tem)->x.next_free;
1242 else
1243 tem = &(*tem)->x.next_free;
1245 eassert ((aligned & 1) == aligned);
1246 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1247 #ifdef USE_POSIX_MEMALIGN
1248 eassert ((uintptr_t) ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1249 #endif
1250 free (ABLOCKS_BASE (abase));
1252 MALLOC_UNBLOCK_INPUT;
1256 /***********************************************************************
1257 Interval Allocation
1258 ***********************************************************************/
1260 /* Number of intervals allocated in an interval_block structure.
1261 The 1020 is 1024 minus malloc overhead. */
1263 #define INTERVAL_BLOCK_SIZE \
1264 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1266 /* Intervals are allocated in chunks in the form of an interval_block
1267 structure. */
1269 struct interval_block
1271 /* Place `intervals' first, to preserve alignment. */
1272 struct interval intervals[INTERVAL_BLOCK_SIZE];
1273 struct interval_block *next;
1276 /* Current interval block. Its `next' pointer points to older
1277 blocks. */
1279 static struct interval_block *interval_block;
1281 /* Index in interval_block above of the next unused interval
1282 structure. */
1284 static int interval_block_index = INTERVAL_BLOCK_SIZE;
1286 /* Number of free and live intervals. */
1288 static EMACS_INT total_free_intervals, total_intervals;
1290 /* List of free intervals. */
1292 static INTERVAL interval_free_list;
1294 /* Return a new interval. */
1296 INTERVAL
1297 make_interval (void)
1299 INTERVAL val;
1301 MALLOC_BLOCK_INPUT;
1303 if (interval_free_list)
1305 val = interval_free_list;
1306 interval_free_list = INTERVAL_PARENT (interval_free_list);
1308 else
1310 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1312 struct interval_block *newi
1313 = lisp_malloc (sizeof *newi, MEM_TYPE_NON_LISP);
1315 newi->next = interval_block;
1316 interval_block = newi;
1317 interval_block_index = 0;
1318 total_free_intervals += INTERVAL_BLOCK_SIZE;
1320 val = &interval_block->intervals[interval_block_index++];
1323 MALLOC_UNBLOCK_INPUT;
1325 consing_since_gc += sizeof (struct interval);
1326 intervals_consed++;
1327 total_free_intervals--;
1328 RESET_INTERVAL (val);
1329 val->gcmarkbit = 0;
1330 return val;
1334 /* Mark Lisp objects in interval I. */
1336 static void
1337 mark_interval (register INTERVAL i, Lisp_Object dummy)
1339 /* Intervals should never be shared. So, if extra internal checking is
1340 enabled, GC aborts if it seems to have visited an interval twice. */
1341 eassert (!i->gcmarkbit);
1342 i->gcmarkbit = 1;
1343 mark_object (i->plist);
1346 /* Mark the interval tree rooted in I. */
1348 #define MARK_INTERVAL_TREE(i) \
1349 do { \
1350 if (i && !i->gcmarkbit) \
1351 traverse_intervals_noorder (i, mark_interval, Qnil); \
1352 } while (0)
1354 /***********************************************************************
1355 String Allocation
1356 ***********************************************************************/
1358 /* Lisp_Strings are allocated in string_block structures. When a new
1359 string_block is allocated, all the Lisp_Strings it contains are
1360 added to a free-list string_free_list. When a new Lisp_String is
1361 needed, it is taken from that list. During the sweep phase of GC,
1362 string_blocks that are entirely free are freed, except two which
1363 we keep.
1365 String data is allocated from sblock structures. Strings larger
1366 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1367 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1369 Sblocks consist internally of sdata structures, one for each
1370 Lisp_String. The sdata structure points to the Lisp_String it
1371 belongs to. The Lisp_String points back to the `u.data' member of
1372 its sdata structure.
1374 When a Lisp_String is freed during GC, it is put back on
1375 string_free_list, and its `data' member and its sdata's `string'
1376 pointer is set to null. The size of the string is recorded in the
1377 `n.nbytes' member of the sdata. So, sdata structures that are no
1378 longer used, can be easily recognized, and it's easy to compact the
1379 sblocks of small strings which we do in compact_small_strings. */
1381 /* Size in bytes of an sblock structure used for small strings. This
1382 is 8192 minus malloc overhead. */
1384 #define SBLOCK_SIZE 8188
1386 /* Strings larger than this are considered large strings. String data
1387 for large strings is allocated from individual sblocks. */
1389 #define LARGE_STRING_BYTES 1024
1391 /* The SDATA typedef is a struct or union describing string memory
1392 sub-allocated from an sblock. This is where the contents of Lisp
1393 strings are stored. */
1395 struct sdata
1397 /* Back-pointer to the string this sdata belongs to. If null, this
1398 structure is free, and NBYTES (in this structure or in the union below)
1399 contains the string's byte size (the same value that STRING_BYTES
1400 would return if STRING were non-null). If non-null, STRING_BYTES
1401 (STRING) is the size of the data, and DATA contains the string's
1402 contents. */
1403 struct Lisp_String *string;
1405 #ifdef GC_CHECK_STRING_BYTES
1406 ptrdiff_t nbytes;
1407 #endif
1409 unsigned char data[FLEXIBLE_ARRAY_MEMBER];
1412 #ifdef GC_CHECK_STRING_BYTES
1414 typedef struct sdata sdata;
1415 #define SDATA_NBYTES(S) (S)->nbytes
1416 #define SDATA_DATA(S) (S)->data
1418 #else
1420 typedef union
1422 struct Lisp_String *string;
1424 /* When STRING is nonnull, this union is actually of type 'struct sdata',
1425 which has a flexible array member. However, if implemented by
1426 giving this union a member of type 'struct sdata', the union
1427 could not be the last (flexible) member of 'struct sblock',
1428 because C99 prohibits a flexible array member from having a type
1429 that is itself a flexible array. So, comment this member out here,
1430 but remember that the option's there when using this union. */
1431 #if 0
1432 struct sdata u;
1433 #endif
1435 /* When STRING is null. */
1436 struct
1438 struct Lisp_String *string;
1439 ptrdiff_t nbytes;
1440 } n;
1441 } sdata;
1443 #define SDATA_NBYTES(S) (S)->n.nbytes
1444 #define SDATA_DATA(S) ((struct sdata *) (S))->data
1446 #endif /* not GC_CHECK_STRING_BYTES */
1448 enum { SDATA_DATA_OFFSET = offsetof (struct sdata, data) };
1450 /* Structure describing a block of memory which is sub-allocated to
1451 obtain string data memory for strings. Blocks for small strings
1452 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1453 as large as needed. */
1455 struct sblock
1457 /* Next in list. */
1458 struct sblock *next;
1460 /* Pointer to the next free sdata block. This points past the end
1461 of the sblock if there isn't any space left in this block. */
1462 sdata *next_free;
1464 /* String data. */
1465 sdata data[FLEXIBLE_ARRAY_MEMBER];
1468 /* Number of Lisp strings in a string_block structure. The 1020 is
1469 1024 minus malloc overhead. */
1471 #define STRING_BLOCK_SIZE \
1472 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1474 /* Structure describing a block from which Lisp_String structures
1475 are allocated. */
1477 struct string_block
1479 /* Place `strings' first, to preserve alignment. */
1480 struct Lisp_String strings[STRING_BLOCK_SIZE];
1481 struct string_block *next;
1484 /* Head and tail of the list of sblock structures holding Lisp string
1485 data. We always allocate from current_sblock. The NEXT pointers
1486 in the sblock structures go from oldest_sblock to current_sblock. */
1488 static struct sblock *oldest_sblock, *current_sblock;
1490 /* List of sblocks for large strings. */
1492 static struct sblock *large_sblocks;
1494 /* List of string_block structures. */
1496 static struct string_block *string_blocks;
1498 /* Free-list of Lisp_Strings. */
1500 static struct Lisp_String *string_free_list;
1502 /* Number of live and free Lisp_Strings. */
1504 static EMACS_INT total_strings, total_free_strings;
1506 /* Number of bytes used by live strings. */
1508 static EMACS_INT total_string_bytes;
1510 /* Given a pointer to a Lisp_String S which is on the free-list
1511 string_free_list, return a pointer to its successor in the
1512 free-list. */
1514 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1516 /* Return a pointer to the sdata structure belonging to Lisp string S.
1517 S must be live, i.e. S->data must not be null. S->data is actually
1518 a pointer to the `u.data' member of its sdata structure; the
1519 structure starts at a constant offset in front of that. */
1521 #define SDATA_OF_STRING(S) ((sdata *) ((S)->data - SDATA_DATA_OFFSET))
1524 #ifdef GC_CHECK_STRING_OVERRUN
1526 /* We check for overrun in string data blocks by appending a small
1527 "cookie" after each allocated string data block, and check for the
1528 presence of this cookie during GC. */
1530 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1531 static char const string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1532 { '\xde', '\xad', '\xbe', '\xef' };
1534 #else
1535 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1536 #endif
1538 /* Value is the size of an sdata structure large enough to hold NBYTES
1539 bytes of string data. The value returned includes a terminating
1540 NUL byte, the size of the sdata structure, and padding. */
1542 #ifdef GC_CHECK_STRING_BYTES
1544 #define SDATA_SIZE(NBYTES) \
1545 ((SDATA_DATA_OFFSET \
1546 + (NBYTES) + 1 \
1547 + sizeof (ptrdiff_t) - 1) \
1548 & ~(sizeof (ptrdiff_t) - 1))
1550 #else /* not GC_CHECK_STRING_BYTES */
1552 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1553 less than the size of that member. The 'max' is not needed when
1554 SDATA_DATA_OFFSET is a multiple of sizeof (ptrdiff_t), because then the
1555 alignment code reserves enough space. */
1557 #define SDATA_SIZE(NBYTES) \
1558 ((SDATA_DATA_OFFSET \
1559 + (SDATA_DATA_OFFSET % sizeof (ptrdiff_t) == 0 \
1560 ? NBYTES \
1561 : max (NBYTES, sizeof (ptrdiff_t) - 1)) \
1562 + 1 \
1563 + sizeof (ptrdiff_t) - 1) \
1564 & ~(sizeof (ptrdiff_t) - 1))
1566 #endif /* not GC_CHECK_STRING_BYTES */
1568 /* Extra bytes to allocate for each string. */
1570 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1572 /* Exact bound on the number of bytes in a string, not counting the
1573 terminating null. A string cannot contain more bytes than
1574 STRING_BYTES_BOUND, nor can it be so long that the size_t
1575 arithmetic in allocate_string_data would overflow while it is
1576 calculating a value to be passed to malloc. */
1577 static ptrdiff_t const STRING_BYTES_MAX =
1578 min (STRING_BYTES_BOUND,
1579 ((SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD
1580 - GC_STRING_EXTRA
1581 - offsetof (struct sblock, data)
1582 - SDATA_DATA_OFFSET)
1583 & ~(sizeof (EMACS_INT) - 1)));
1585 /* Initialize string allocation. Called from init_alloc_once. */
1587 static void
1588 init_strings (void)
1590 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1591 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1595 #ifdef GC_CHECK_STRING_BYTES
1597 static int check_string_bytes_count;
1599 /* Like STRING_BYTES, but with debugging check. Can be
1600 called during GC, so pay attention to the mark bit. */
1602 ptrdiff_t
1603 string_bytes (struct Lisp_String *s)
1605 ptrdiff_t nbytes =
1606 (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1608 if (!PURE_POINTER_P (s)
1609 && s->data
1610 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1611 emacs_abort ();
1612 return nbytes;
1615 /* Check validity of Lisp strings' string_bytes member in B. */
1617 static void
1618 check_sblock (struct sblock *b)
1620 sdata *from, *end, *from_end;
1622 end = b->next_free;
1624 for (from = b->data; from < end; from = from_end)
1626 /* Compute the next FROM here because copying below may
1627 overwrite data we need to compute it. */
1628 ptrdiff_t nbytes;
1630 /* Check that the string size recorded in the string is the
1631 same as the one recorded in the sdata structure. */
1632 nbytes = SDATA_SIZE (from->string ? string_bytes (from->string)
1633 : SDATA_NBYTES (from));
1634 from_end = (sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1639 /* Check validity of Lisp strings' string_bytes member. ALL_P
1640 means check all strings, otherwise check only most
1641 recently allocated strings. Used for hunting a bug. */
1643 static void
1644 check_string_bytes (bool all_p)
1646 if (all_p)
1648 struct sblock *b;
1650 for (b = large_sblocks; b; b = b->next)
1652 struct Lisp_String *s = b->data[0].string;
1653 if (s)
1654 string_bytes (s);
1657 for (b = oldest_sblock; b; b = b->next)
1658 check_sblock (b);
1660 else if (current_sblock)
1661 check_sblock (current_sblock);
1664 #else /* not GC_CHECK_STRING_BYTES */
1666 #define check_string_bytes(all) ((void) 0)
1668 #endif /* GC_CHECK_STRING_BYTES */
1670 #ifdef GC_CHECK_STRING_FREE_LIST
1672 /* Walk through the string free list looking for bogus next pointers.
1673 This may catch buffer overrun from a previous string. */
1675 static void
1676 check_string_free_list (void)
1678 struct Lisp_String *s;
1680 /* Pop a Lisp_String off the free-list. */
1681 s = string_free_list;
1682 while (s != NULL)
1684 if ((uintptr_t) s < 1024)
1685 emacs_abort ();
1686 s = NEXT_FREE_LISP_STRING (s);
1689 #else
1690 #define check_string_free_list()
1691 #endif
1693 /* Return a new Lisp_String. */
1695 static struct Lisp_String *
1696 allocate_string (void)
1698 struct Lisp_String *s;
1700 MALLOC_BLOCK_INPUT;
1702 /* If the free-list is empty, allocate a new string_block, and
1703 add all the Lisp_Strings in it to the free-list. */
1704 if (string_free_list == NULL)
1706 struct string_block *b = lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1707 int i;
1709 b->next = string_blocks;
1710 string_blocks = b;
1712 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1714 s = b->strings + i;
1715 /* Every string on a free list should have NULL data pointer. */
1716 s->data = NULL;
1717 NEXT_FREE_LISP_STRING (s) = string_free_list;
1718 string_free_list = s;
1721 total_free_strings += STRING_BLOCK_SIZE;
1724 check_string_free_list ();
1726 /* Pop a Lisp_String off the free-list. */
1727 s = string_free_list;
1728 string_free_list = NEXT_FREE_LISP_STRING (s);
1730 MALLOC_UNBLOCK_INPUT;
1732 --total_free_strings;
1733 ++total_strings;
1734 ++strings_consed;
1735 consing_since_gc += sizeof *s;
1737 #ifdef GC_CHECK_STRING_BYTES
1738 if (!noninteractive)
1740 if (++check_string_bytes_count == 200)
1742 check_string_bytes_count = 0;
1743 check_string_bytes (1);
1745 else
1746 check_string_bytes (0);
1748 #endif /* GC_CHECK_STRING_BYTES */
1750 return s;
1754 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1755 plus a NUL byte at the end. Allocate an sdata structure for S, and
1756 set S->data to its `u.data' member. Store a NUL byte at the end of
1757 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1758 S->data if it was initially non-null. */
1760 void
1761 allocate_string_data (struct Lisp_String *s,
1762 EMACS_INT nchars, EMACS_INT nbytes)
1764 sdata *data, *old_data;
1765 struct sblock *b;
1766 ptrdiff_t needed, old_nbytes;
1768 if (STRING_BYTES_MAX < nbytes)
1769 string_overflow ();
1771 /* Determine the number of bytes needed to store NBYTES bytes
1772 of string data. */
1773 needed = SDATA_SIZE (nbytes);
1774 if (s->data)
1776 old_data = SDATA_OF_STRING (s);
1777 old_nbytes = STRING_BYTES (s);
1779 else
1780 old_data = NULL;
1782 MALLOC_BLOCK_INPUT;
1784 if (nbytes > LARGE_STRING_BYTES)
1786 size_t size = offsetof (struct sblock, data) + needed;
1788 #ifdef DOUG_LEA_MALLOC
1789 if (!mmap_lisp_allowed_p ())
1790 mallopt (M_MMAP_MAX, 0);
1791 #endif
1793 b = lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
1795 #ifdef DOUG_LEA_MALLOC
1796 if (!mmap_lisp_allowed_p ())
1797 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1798 #endif
1800 b->next_free = b->data;
1801 b->data[0].string = NULL;
1802 b->next = large_sblocks;
1803 large_sblocks = b;
1805 else if (current_sblock == NULL
1806 || (((char *) current_sblock + SBLOCK_SIZE
1807 - (char *) current_sblock->next_free)
1808 < (needed + GC_STRING_EXTRA)))
1810 /* Not enough room in the current sblock. */
1811 b = lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1812 b->next_free = b->data;
1813 b->data[0].string = NULL;
1814 b->next = NULL;
1816 if (current_sblock)
1817 current_sblock->next = b;
1818 else
1819 oldest_sblock = b;
1820 current_sblock = b;
1822 else
1823 b = current_sblock;
1825 data = b->next_free;
1826 b->next_free = (sdata *) ((char *) data + needed + GC_STRING_EXTRA);
1828 MALLOC_UNBLOCK_INPUT;
1830 data->string = s;
1831 s->data = SDATA_DATA (data);
1832 #ifdef GC_CHECK_STRING_BYTES
1833 SDATA_NBYTES (data) = nbytes;
1834 #endif
1835 s->size = nchars;
1836 s->size_byte = nbytes;
1837 s->data[nbytes] = '\0';
1838 #ifdef GC_CHECK_STRING_OVERRUN
1839 memcpy ((char *) data + needed, string_overrun_cookie,
1840 GC_STRING_OVERRUN_COOKIE_SIZE);
1841 #endif
1843 /* Note that Faset may call to this function when S has already data
1844 assigned. In this case, mark data as free by setting it's string
1845 back-pointer to null, and record the size of the data in it. */
1846 if (old_data)
1848 SDATA_NBYTES (old_data) = old_nbytes;
1849 old_data->string = NULL;
1852 consing_since_gc += needed;
1856 /* Sweep and compact strings. */
1858 NO_INLINE /* For better stack traces */
1859 static void
1860 sweep_strings (void)
1862 struct string_block *b, *next;
1863 struct string_block *live_blocks = NULL;
1865 string_free_list = NULL;
1866 total_strings = total_free_strings = 0;
1867 total_string_bytes = 0;
1869 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1870 for (b = string_blocks; b; b = next)
1872 int i, nfree = 0;
1873 struct Lisp_String *free_list_before = string_free_list;
1875 next = b->next;
1877 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
1879 struct Lisp_String *s = b->strings + i;
1881 if (s->data)
1883 /* String was not on free-list before. */
1884 if (STRING_MARKED_P (s))
1886 /* String is live; unmark it and its intervals. */
1887 UNMARK_STRING (s);
1889 /* Do not use string_(set|get)_intervals here. */
1890 s->intervals = balance_intervals (s->intervals);
1892 ++total_strings;
1893 total_string_bytes += STRING_BYTES (s);
1895 else
1897 /* String is dead. Put it on the free-list. */
1898 sdata *data = SDATA_OF_STRING (s);
1900 /* Save the size of S in its sdata so that we know
1901 how large that is. Reset the sdata's string
1902 back-pointer so that we know it's free. */
1903 #ifdef GC_CHECK_STRING_BYTES
1904 if (string_bytes (s) != SDATA_NBYTES (data))
1905 emacs_abort ();
1906 #else
1907 data->n.nbytes = STRING_BYTES (s);
1908 #endif
1909 data->string = NULL;
1911 /* Reset the strings's `data' member so that we
1912 know it's free. */
1913 s->data = NULL;
1915 /* Put the string on the free-list. */
1916 NEXT_FREE_LISP_STRING (s) = string_free_list;
1917 string_free_list = s;
1918 ++nfree;
1921 else
1923 /* S was on the free-list before. Put it there again. */
1924 NEXT_FREE_LISP_STRING (s) = string_free_list;
1925 string_free_list = s;
1926 ++nfree;
1930 /* Free blocks that contain free Lisp_Strings only, except
1931 the first two of them. */
1932 if (nfree == STRING_BLOCK_SIZE
1933 && total_free_strings > STRING_BLOCK_SIZE)
1935 lisp_free (b);
1936 string_free_list = free_list_before;
1938 else
1940 total_free_strings += nfree;
1941 b->next = live_blocks;
1942 live_blocks = b;
1946 check_string_free_list ();
1948 string_blocks = live_blocks;
1949 free_large_strings ();
1950 compact_small_strings ();
1952 check_string_free_list ();
1956 /* Free dead large strings. */
1958 static void
1959 free_large_strings (void)
1961 struct sblock *b, *next;
1962 struct sblock *live_blocks = NULL;
1964 for (b = large_sblocks; b; b = next)
1966 next = b->next;
1968 if (b->data[0].string == NULL)
1969 lisp_free (b);
1970 else
1972 b->next = live_blocks;
1973 live_blocks = b;
1977 large_sblocks = live_blocks;
1981 /* Compact data of small strings. Free sblocks that don't contain
1982 data of live strings after compaction. */
1984 static void
1985 compact_small_strings (void)
1987 struct sblock *b, *tb, *next;
1988 sdata *from, *to, *end, *tb_end;
1989 sdata *to_end, *from_end;
1991 /* TB is the sblock we copy to, TO is the sdata within TB we copy
1992 to, and TB_END is the end of TB. */
1993 tb = oldest_sblock;
1994 tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
1995 to = tb->data;
1997 /* Step through the blocks from the oldest to the youngest. We
1998 expect that old blocks will stabilize over time, so that less
1999 copying will happen this way. */
2000 for (b = oldest_sblock; b; b = b->next)
2002 end = b->next_free;
2003 eassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2005 for (from = b->data; from < end; from = from_end)
2007 /* Compute the next FROM here because copying below may
2008 overwrite data we need to compute it. */
2009 ptrdiff_t nbytes;
2010 struct Lisp_String *s = from->string;
2012 #ifdef GC_CHECK_STRING_BYTES
2013 /* Check that the string size recorded in the string is the
2014 same as the one recorded in the sdata structure. */
2015 if (s && string_bytes (s) != SDATA_NBYTES (from))
2016 emacs_abort ();
2017 #endif /* GC_CHECK_STRING_BYTES */
2019 nbytes = s ? STRING_BYTES (s) : SDATA_NBYTES (from);
2020 eassert (nbytes <= LARGE_STRING_BYTES);
2022 nbytes = SDATA_SIZE (nbytes);
2023 from_end = (sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
2025 #ifdef GC_CHECK_STRING_OVERRUN
2026 if (memcmp (string_overrun_cookie,
2027 (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
2028 GC_STRING_OVERRUN_COOKIE_SIZE))
2029 emacs_abort ();
2030 #endif
2032 /* Non-NULL S means it's alive. Copy its data. */
2033 if (s)
2035 /* If TB is full, proceed with the next sblock. */
2036 to_end = (sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2037 if (to_end > tb_end)
2039 tb->next_free = to;
2040 tb = tb->next;
2041 tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
2042 to = tb->data;
2043 to_end = (sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2046 /* Copy, and update the string's `data' pointer. */
2047 if (from != to)
2049 eassert (tb != b || to < from);
2050 memmove (to, from, nbytes + GC_STRING_EXTRA);
2051 to->string->data = SDATA_DATA (to);
2054 /* Advance past the sdata we copied to. */
2055 to = to_end;
2060 /* The rest of the sblocks following TB don't contain live data, so
2061 we can free them. */
2062 for (b = tb->next; b; b = next)
2064 next = b->next;
2065 lisp_free (b);
2068 tb->next_free = to;
2069 tb->next = NULL;
2070 current_sblock = tb;
2073 void
2074 string_overflow (void)
2076 error ("Maximum string size exceeded");
2079 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2080 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2081 LENGTH must be an integer.
2082 INIT must be an integer that represents a character. */)
2083 (Lisp_Object length, Lisp_Object init)
2085 register Lisp_Object val;
2086 int c;
2087 EMACS_INT nbytes;
2089 CHECK_NATNUM (length);
2090 CHECK_CHARACTER (init);
2092 c = XFASTINT (init);
2093 if (ASCII_CHAR_P (c))
2095 nbytes = XINT (length);
2096 val = make_uninit_string (nbytes);
2097 memset (SDATA (val), c, nbytes);
2098 SDATA (val)[nbytes] = 0;
2100 else
2102 unsigned char str[MAX_MULTIBYTE_LENGTH];
2103 ptrdiff_t len = CHAR_STRING (c, str);
2104 EMACS_INT string_len = XINT (length);
2105 unsigned char *p, *beg, *end;
2107 if (string_len > STRING_BYTES_MAX / len)
2108 string_overflow ();
2109 nbytes = len * string_len;
2110 val = make_uninit_multibyte_string (string_len, nbytes);
2111 for (beg = SDATA (val), p = beg, end = beg + nbytes; p < end; p += len)
2113 /* First time we just copy `str' to the data of `val'. */
2114 if (p == beg)
2115 memcpy (p, str, len);
2116 else
2118 /* Next time we copy largest possible chunk from
2119 initialized to uninitialized part of `val'. */
2120 len = min (p - beg, end - p);
2121 memcpy (p, beg, len);
2124 *p = 0;
2127 return val;
2130 /* Fill A with 1 bits if INIT is non-nil, and with 0 bits otherwise.
2131 Return A. */
2133 Lisp_Object
2134 bool_vector_fill (Lisp_Object a, Lisp_Object init)
2136 EMACS_INT nbits = bool_vector_size (a);
2137 if (0 < nbits)
2139 unsigned char *data = bool_vector_uchar_data (a);
2140 int pattern = NILP (init) ? 0 : (1 << BOOL_VECTOR_BITS_PER_CHAR) - 1;
2141 ptrdiff_t nbytes = bool_vector_bytes (nbits);
2142 int last_mask = ~ (~0u << ((nbits - 1) % BOOL_VECTOR_BITS_PER_CHAR + 1));
2143 memset (data, pattern, nbytes - 1);
2144 data[nbytes - 1] = pattern & last_mask;
2146 return a;
2149 /* Return a newly allocated, uninitialized bool vector of size NBITS. */
2151 Lisp_Object
2152 make_uninit_bool_vector (EMACS_INT nbits)
2154 Lisp_Object val;
2155 EMACS_INT words = bool_vector_words (nbits);
2156 EMACS_INT word_bytes = words * sizeof (bits_word);
2157 EMACS_INT needed_elements = ((bool_header_size - header_size + word_bytes
2158 + word_size - 1)
2159 / word_size);
2160 struct Lisp_Bool_Vector *p
2161 = (struct Lisp_Bool_Vector *) allocate_vector (needed_elements);
2162 XSETVECTOR (val, p);
2163 XSETPVECTYPESIZE (XVECTOR (val), PVEC_BOOL_VECTOR, 0, 0);
2164 p->size = nbits;
2166 /* Clear padding at the end. */
2167 if (words)
2168 p->data[words - 1] = 0;
2170 return val;
2173 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2174 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2175 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2176 (Lisp_Object length, Lisp_Object init)
2178 Lisp_Object val;
2180 CHECK_NATNUM (length);
2181 val = make_uninit_bool_vector (XFASTINT (length));
2182 return bool_vector_fill (val, init);
2185 DEFUN ("bool-vector", Fbool_vector, Sbool_vector, 0, MANY, 0,
2186 doc: /* Return a new bool-vector with specified arguments as elements.
2187 Any number of arguments, even zero arguments, are allowed.
2188 usage: (bool-vector &rest OBJECTS) */)
2189 (ptrdiff_t nargs, Lisp_Object *args)
2191 ptrdiff_t i;
2192 Lisp_Object vector;
2194 vector = make_uninit_bool_vector (nargs);
2195 for (i = 0; i < nargs; i++)
2196 bool_vector_set (vector, i, !NILP (args[i]));
2198 return vector;
2201 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2202 of characters from the contents. This string may be unibyte or
2203 multibyte, depending on the contents. */
2205 Lisp_Object
2206 make_string (const char *contents, ptrdiff_t nbytes)
2208 register Lisp_Object val;
2209 ptrdiff_t nchars, multibyte_nbytes;
2211 parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
2212 &nchars, &multibyte_nbytes);
2213 if (nbytes == nchars || nbytes != multibyte_nbytes)
2214 /* CONTENTS contains no multibyte sequences or contains an invalid
2215 multibyte sequence. We must make unibyte string. */
2216 val = make_unibyte_string (contents, nbytes);
2217 else
2218 val = make_multibyte_string (contents, nchars, nbytes);
2219 return val;
2223 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
2225 Lisp_Object
2226 make_unibyte_string (const char *contents, ptrdiff_t length)
2228 register Lisp_Object val;
2229 val = make_uninit_string (length);
2230 memcpy (SDATA (val), contents, length);
2231 return val;
2235 /* Make a multibyte string from NCHARS characters occupying NBYTES
2236 bytes at CONTENTS. */
2238 Lisp_Object
2239 make_multibyte_string (const char *contents,
2240 ptrdiff_t nchars, ptrdiff_t nbytes)
2242 register Lisp_Object val;
2243 val = make_uninit_multibyte_string (nchars, nbytes);
2244 memcpy (SDATA (val), contents, nbytes);
2245 return val;
2249 /* Make a string from NCHARS characters occupying NBYTES bytes at
2250 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2252 Lisp_Object
2253 make_string_from_bytes (const char *contents,
2254 ptrdiff_t nchars, ptrdiff_t nbytes)
2256 register Lisp_Object val;
2257 val = make_uninit_multibyte_string (nchars, nbytes);
2258 memcpy (SDATA (val), contents, nbytes);
2259 if (SBYTES (val) == SCHARS (val))
2260 STRING_SET_UNIBYTE (val);
2261 return val;
2265 /* Make a string from NCHARS characters occupying NBYTES bytes at
2266 CONTENTS. The argument MULTIBYTE controls whether to label the
2267 string as multibyte. If NCHARS is negative, it counts the number of
2268 characters by itself. */
2270 Lisp_Object
2271 make_specified_string (const char *contents,
2272 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
2274 Lisp_Object val;
2276 if (nchars < 0)
2278 if (multibyte)
2279 nchars = multibyte_chars_in_text ((const unsigned char *) contents,
2280 nbytes);
2281 else
2282 nchars = nbytes;
2284 val = make_uninit_multibyte_string (nchars, nbytes);
2285 memcpy (SDATA (val), contents, nbytes);
2286 if (!multibyte)
2287 STRING_SET_UNIBYTE (val);
2288 return val;
2292 /* Return an unibyte Lisp_String set up to hold LENGTH characters
2293 occupying LENGTH bytes. */
2295 Lisp_Object
2296 make_uninit_string (EMACS_INT length)
2298 Lisp_Object val;
2300 if (!length)
2301 return empty_unibyte_string;
2302 val = make_uninit_multibyte_string (length, length);
2303 STRING_SET_UNIBYTE (val);
2304 return val;
2308 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2309 which occupy NBYTES bytes. */
2311 Lisp_Object
2312 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2314 Lisp_Object string;
2315 struct Lisp_String *s;
2317 if (nchars < 0)
2318 emacs_abort ();
2319 if (!nbytes)
2320 return empty_multibyte_string;
2322 s = allocate_string ();
2323 s->intervals = NULL;
2324 allocate_string_data (s, nchars, nbytes);
2325 XSETSTRING (string, s);
2326 string_chars_consed += nbytes;
2327 return string;
2330 /* Print arguments to BUF according to a FORMAT, then return
2331 a Lisp_String initialized with the data from BUF. */
2333 Lisp_Object
2334 make_formatted_string (char *buf, const char *format, ...)
2336 va_list ap;
2337 int length;
2339 va_start (ap, format);
2340 length = vsprintf (buf, format, ap);
2341 va_end (ap);
2342 return make_string (buf, length);
2346 /***********************************************************************
2347 Float Allocation
2348 ***********************************************************************/
2350 /* We store float cells inside of float_blocks, allocating a new
2351 float_block with malloc whenever necessary. Float cells reclaimed
2352 by GC are put on a free list to be reallocated before allocating
2353 any new float cells from the latest float_block. */
2355 #define FLOAT_BLOCK_SIZE \
2356 (((BLOCK_BYTES - sizeof (struct float_block *) \
2357 /* The compiler might add padding at the end. */ \
2358 - (sizeof (struct Lisp_Float) - sizeof (bits_word))) * CHAR_BIT) \
2359 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2361 #define GETMARKBIT(block,n) \
2362 (((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2363 >> ((n) % BITS_PER_BITS_WORD)) \
2364 & 1)
2366 #define SETMARKBIT(block,n) \
2367 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2368 |= (bits_word) 1 << ((n) % BITS_PER_BITS_WORD))
2370 #define UNSETMARKBIT(block,n) \
2371 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2372 &= ~((bits_word) 1 << ((n) % BITS_PER_BITS_WORD)))
2374 #define FLOAT_BLOCK(fptr) \
2375 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2377 #define FLOAT_INDEX(fptr) \
2378 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2380 struct float_block
2382 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2383 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2384 bits_word gcmarkbits[1 + FLOAT_BLOCK_SIZE / BITS_PER_BITS_WORD];
2385 struct float_block *next;
2388 #define FLOAT_MARKED_P(fptr) \
2389 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2391 #define FLOAT_MARK(fptr) \
2392 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2394 #define FLOAT_UNMARK(fptr) \
2395 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2397 /* Current float_block. */
2399 static struct float_block *float_block;
2401 /* Index of first unused Lisp_Float in the current float_block. */
2403 static int float_block_index = FLOAT_BLOCK_SIZE;
2405 /* Free-list of Lisp_Floats. */
2407 static struct Lisp_Float *float_free_list;
2409 /* Return a new float object with value FLOAT_VALUE. */
2411 Lisp_Object
2412 make_float (double float_value)
2414 register Lisp_Object val;
2416 MALLOC_BLOCK_INPUT;
2418 if (float_free_list)
2420 /* We use the data field for chaining the free list
2421 so that we won't use the same field that has the mark bit. */
2422 XSETFLOAT (val, float_free_list);
2423 float_free_list = float_free_list->u.chain;
2425 else
2427 if (float_block_index == FLOAT_BLOCK_SIZE)
2429 struct float_block *new
2430 = lisp_align_malloc (sizeof *new, MEM_TYPE_FLOAT);
2431 new->next = float_block;
2432 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2433 float_block = new;
2434 float_block_index = 0;
2435 total_free_floats += FLOAT_BLOCK_SIZE;
2437 XSETFLOAT (val, &float_block->floats[float_block_index]);
2438 float_block_index++;
2441 MALLOC_UNBLOCK_INPUT;
2443 XFLOAT_INIT (val, float_value);
2444 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2445 consing_since_gc += sizeof (struct Lisp_Float);
2446 floats_consed++;
2447 total_free_floats--;
2448 return val;
2453 /***********************************************************************
2454 Cons Allocation
2455 ***********************************************************************/
2457 /* We store cons cells inside of cons_blocks, allocating a new
2458 cons_block with malloc whenever necessary. Cons cells reclaimed by
2459 GC are put on a free list to be reallocated before allocating
2460 any new cons cells from the latest cons_block. */
2462 #define CONS_BLOCK_SIZE \
2463 (((BLOCK_BYTES - sizeof (struct cons_block *) \
2464 /* The compiler might add padding at the end. */ \
2465 - (sizeof (struct Lisp_Cons) - sizeof (bits_word))) * CHAR_BIT) \
2466 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2468 #define CONS_BLOCK(fptr) \
2469 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2471 #define CONS_INDEX(fptr) \
2472 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2474 struct cons_block
2476 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2477 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2478 bits_word gcmarkbits[1 + CONS_BLOCK_SIZE / BITS_PER_BITS_WORD];
2479 struct cons_block *next;
2482 #define CONS_MARKED_P(fptr) \
2483 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2485 #define CONS_MARK(fptr) \
2486 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2488 #define CONS_UNMARK(fptr) \
2489 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2491 /* Current cons_block. */
2493 static struct cons_block *cons_block;
2495 /* Index of first unused Lisp_Cons in the current block. */
2497 static int cons_block_index = CONS_BLOCK_SIZE;
2499 /* Free-list of Lisp_Cons structures. */
2501 static struct Lisp_Cons *cons_free_list;
2503 /* Explicitly free a cons cell by putting it on the free-list. */
2505 void
2506 free_cons (struct Lisp_Cons *ptr)
2508 ptr->u.chain = cons_free_list;
2509 #if GC_MARK_STACK
2510 ptr->car = Vdead;
2511 #endif
2512 cons_free_list = ptr;
2513 consing_since_gc -= sizeof *ptr;
2514 total_free_conses++;
2517 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2518 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2519 (Lisp_Object car, Lisp_Object cdr)
2521 register Lisp_Object val;
2523 MALLOC_BLOCK_INPUT;
2525 if (cons_free_list)
2527 /* We use the cdr for chaining the free list
2528 so that we won't use the same field that has the mark bit. */
2529 XSETCONS (val, cons_free_list);
2530 cons_free_list = cons_free_list->u.chain;
2532 else
2534 if (cons_block_index == CONS_BLOCK_SIZE)
2536 struct cons_block *new
2537 = lisp_align_malloc (sizeof *new, MEM_TYPE_CONS);
2538 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2539 new->next = cons_block;
2540 cons_block = new;
2541 cons_block_index = 0;
2542 total_free_conses += CONS_BLOCK_SIZE;
2544 XSETCONS (val, &cons_block->conses[cons_block_index]);
2545 cons_block_index++;
2548 MALLOC_UNBLOCK_INPUT;
2550 XSETCAR (val, car);
2551 XSETCDR (val, cdr);
2552 eassert (!CONS_MARKED_P (XCONS (val)));
2553 consing_since_gc += sizeof (struct Lisp_Cons);
2554 total_free_conses--;
2555 cons_cells_consed++;
2556 return val;
2559 #ifdef GC_CHECK_CONS_LIST
2560 /* Get an error now if there's any junk in the cons free list. */
2561 void
2562 check_cons_list (void)
2564 struct Lisp_Cons *tail = cons_free_list;
2566 while (tail)
2567 tail = tail->u.chain;
2569 #endif
2571 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2573 Lisp_Object
2574 list1 (Lisp_Object arg1)
2576 return Fcons (arg1, Qnil);
2579 Lisp_Object
2580 list2 (Lisp_Object arg1, Lisp_Object arg2)
2582 return Fcons (arg1, Fcons (arg2, Qnil));
2586 Lisp_Object
2587 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2589 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2593 Lisp_Object
2594 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2596 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2600 Lisp_Object
2601 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2603 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2604 Fcons (arg5, Qnil)))));
2607 /* Make a list of COUNT Lisp_Objects, where ARG is the
2608 first one. Allocate conses from pure space if TYPE
2609 is CONSTYPE_PURE, or allocate as usual if type is CONSTYPE_HEAP. */
2611 Lisp_Object
2612 listn (enum constype type, ptrdiff_t count, Lisp_Object arg, ...)
2614 va_list ap;
2615 ptrdiff_t i;
2616 Lisp_Object val, *objp;
2618 /* Change to SAFE_ALLOCA if you hit this eassert. */
2619 eassert (count <= MAX_ALLOCA / word_size);
2621 objp = alloca (count * word_size);
2622 objp[0] = arg;
2623 va_start (ap, arg);
2624 for (i = 1; i < count; i++)
2625 objp[i] = va_arg (ap, Lisp_Object);
2626 va_end (ap);
2628 for (val = Qnil, i = count - 1; i >= 0; i--)
2630 if (type == CONSTYPE_PURE)
2631 val = pure_cons (objp[i], val);
2632 else if (type == CONSTYPE_HEAP)
2633 val = Fcons (objp[i], val);
2634 else
2635 emacs_abort ();
2637 return val;
2640 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2641 doc: /* Return a newly created list with specified arguments as elements.
2642 Any number of arguments, even zero arguments, are allowed.
2643 usage: (list &rest OBJECTS) */)
2644 (ptrdiff_t nargs, Lisp_Object *args)
2646 register Lisp_Object val;
2647 val = Qnil;
2649 while (nargs > 0)
2651 nargs--;
2652 val = Fcons (args[nargs], val);
2654 return val;
2658 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2659 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2660 (register Lisp_Object length, Lisp_Object init)
2662 register Lisp_Object val;
2663 register EMACS_INT size;
2665 CHECK_NATNUM (length);
2666 size = XFASTINT (length);
2668 val = Qnil;
2669 while (size > 0)
2671 val = Fcons (init, val);
2672 --size;
2674 if (size > 0)
2676 val = Fcons (init, val);
2677 --size;
2679 if (size > 0)
2681 val = Fcons (init, val);
2682 --size;
2684 if (size > 0)
2686 val = Fcons (init, val);
2687 --size;
2689 if (size > 0)
2691 val = Fcons (init, val);
2692 --size;
2698 QUIT;
2701 return val;
2706 /***********************************************************************
2707 Vector Allocation
2708 ***********************************************************************/
2710 /* Sometimes a vector's contents are merely a pointer internally used
2711 in vector allocation code. On the rare platforms where a null
2712 pointer cannot be tagged, represent it with a Lisp 0.
2713 Usually you don't want to touch this. */
2715 static struct Lisp_Vector *
2716 next_vector (struct Lisp_Vector *v)
2718 return XUNTAG (v->contents[0], 0);
2721 static void
2722 set_next_vector (struct Lisp_Vector *v, struct Lisp_Vector *p)
2724 v->contents[0] = make_lisp_ptr (p, 0);
2727 /* This value is balanced well enough to avoid too much internal overhead
2728 for the most common cases; it's not required to be a power of two, but
2729 it's expected to be a mult-of-ROUNDUP_SIZE (see below). */
2731 #define VECTOR_BLOCK_SIZE 4096
2733 enum
2735 /* Alignment of struct Lisp_Vector objects. */
2736 vector_alignment = COMMON_MULTIPLE (ALIGNOF_STRUCT_LISP_VECTOR,
2737 USE_LSB_TAG ? GCALIGNMENT : 1),
2739 /* Vector size requests are a multiple of this. */
2740 roundup_size = COMMON_MULTIPLE (vector_alignment, word_size)
2743 /* Verify assumptions described above. */
2744 verify ((VECTOR_BLOCK_SIZE % roundup_size) == 0);
2745 verify (VECTOR_BLOCK_SIZE <= (1 << PSEUDOVECTOR_SIZE_BITS));
2747 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at compile time. */
2748 #define vroundup_ct(x) ROUNDUP (x, roundup_size)
2749 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at runtime. */
2750 #define vroundup(x) (eassume ((x) >= 0), vroundup_ct (x))
2752 /* Rounding helps to maintain alignment constraints if USE_LSB_TAG. */
2754 #define VECTOR_BLOCK_BYTES (VECTOR_BLOCK_SIZE - vroundup_ct (sizeof (void *)))
2756 /* Size of the minimal vector allocated from block. */
2758 #define VBLOCK_BYTES_MIN vroundup_ct (header_size + sizeof (Lisp_Object))
2760 /* Size of the largest vector allocated from block. */
2762 #define VBLOCK_BYTES_MAX \
2763 vroundup ((VECTOR_BLOCK_BYTES / 2) - word_size)
2765 /* We maintain one free list for each possible block-allocated
2766 vector size, and this is the number of free lists we have. */
2768 #define VECTOR_MAX_FREE_LIST_INDEX \
2769 ((VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN) / roundup_size + 1)
2771 /* Common shortcut to advance vector pointer over a block data. */
2773 #define ADVANCE(v, nbytes) ((struct Lisp_Vector *) ((char *) (v) + (nbytes)))
2775 /* Common shortcut to calculate NBYTES-vector index in VECTOR_FREE_LISTS. */
2777 #define VINDEX(nbytes) (((nbytes) - VBLOCK_BYTES_MIN) / roundup_size)
2779 /* Common shortcut to setup vector on a free list. */
2781 #define SETUP_ON_FREE_LIST(v, nbytes, tmp) \
2782 do { \
2783 (tmp) = ((nbytes - header_size) / word_size); \
2784 XSETPVECTYPESIZE (v, PVEC_FREE, 0, (tmp)); \
2785 eassert ((nbytes) % roundup_size == 0); \
2786 (tmp) = VINDEX (nbytes); \
2787 eassert ((tmp) < VECTOR_MAX_FREE_LIST_INDEX); \
2788 set_next_vector (v, vector_free_lists[tmp]); \
2789 vector_free_lists[tmp] = (v); \
2790 total_free_vector_slots += (nbytes) / word_size; \
2791 } while (0)
2793 /* This internal type is used to maintain the list of large vectors
2794 which are allocated at their own, e.g. outside of vector blocks.
2796 struct large_vector itself cannot contain a struct Lisp_Vector, as
2797 the latter contains a flexible array member and C99 does not allow
2798 such structs to be nested. Instead, each struct large_vector
2799 object LV is followed by a struct Lisp_Vector, which is at offset
2800 large_vector_offset from LV, and whose address is therefore
2801 large_vector_vec (&LV). */
2803 struct large_vector
2805 struct large_vector *next;
2808 enum
2810 large_vector_offset = ROUNDUP (sizeof (struct large_vector), vector_alignment)
2813 static struct Lisp_Vector *
2814 large_vector_vec (struct large_vector *p)
2816 return (struct Lisp_Vector *) ((char *) p + large_vector_offset);
2819 /* This internal type is used to maintain an underlying storage
2820 for small vectors. */
2822 struct vector_block
2824 char data[VECTOR_BLOCK_BYTES];
2825 struct vector_block *next;
2828 /* Chain of vector blocks. */
2830 static struct vector_block *vector_blocks;
2832 /* Vector free lists, where NTH item points to a chain of free
2833 vectors of the same NBYTES size, so NTH == VINDEX (NBYTES). */
2835 static struct Lisp_Vector *vector_free_lists[VECTOR_MAX_FREE_LIST_INDEX];
2837 /* Singly-linked list of large vectors. */
2839 static struct large_vector *large_vectors;
2841 /* The only vector with 0 slots, allocated from pure space. */
2843 Lisp_Object zero_vector;
2845 /* Number of live vectors. */
2847 static EMACS_INT total_vectors;
2849 /* Total size of live and free vectors, in Lisp_Object units. */
2851 static EMACS_INT total_vector_slots, total_free_vector_slots;
2853 /* Get a new vector block. */
2855 static struct vector_block *
2856 allocate_vector_block (void)
2858 struct vector_block *block = xmalloc (sizeof *block);
2860 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
2861 mem_insert (block->data, block->data + VECTOR_BLOCK_BYTES,
2862 MEM_TYPE_VECTOR_BLOCK);
2863 #endif
2865 block->next = vector_blocks;
2866 vector_blocks = block;
2867 return block;
2870 /* Called once to initialize vector allocation. */
2872 static void
2873 init_vectors (void)
2875 zero_vector = make_pure_vector (0);
2878 /* Allocate vector from a vector block. */
2880 static struct Lisp_Vector *
2881 allocate_vector_from_block (size_t nbytes)
2883 struct Lisp_Vector *vector;
2884 struct vector_block *block;
2885 size_t index, restbytes;
2887 eassert (VBLOCK_BYTES_MIN <= nbytes && nbytes <= VBLOCK_BYTES_MAX);
2888 eassert (nbytes % roundup_size == 0);
2890 /* First, try to allocate from a free list
2891 containing vectors of the requested size. */
2892 index = VINDEX (nbytes);
2893 if (vector_free_lists[index])
2895 vector = vector_free_lists[index];
2896 vector_free_lists[index] = next_vector (vector);
2897 total_free_vector_slots -= nbytes / word_size;
2898 return vector;
2901 /* Next, check free lists containing larger vectors. Since
2902 we will split the result, we should have remaining space
2903 large enough to use for one-slot vector at least. */
2904 for (index = VINDEX (nbytes + VBLOCK_BYTES_MIN);
2905 index < VECTOR_MAX_FREE_LIST_INDEX; index++)
2906 if (vector_free_lists[index])
2908 /* This vector is larger than requested. */
2909 vector = vector_free_lists[index];
2910 vector_free_lists[index] = next_vector (vector);
2911 total_free_vector_slots -= nbytes / word_size;
2913 /* Excess bytes are used for the smaller vector,
2914 which should be set on an appropriate free list. */
2915 restbytes = index * roundup_size + VBLOCK_BYTES_MIN - nbytes;
2916 eassert (restbytes % roundup_size == 0);
2917 SETUP_ON_FREE_LIST (ADVANCE (vector, nbytes), restbytes, index);
2918 return vector;
2921 /* Finally, need a new vector block. */
2922 block = allocate_vector_block ();
2924 /* New vector will be at the beginning of this block. */
2925 vector = (struct Lisp_Vector *) block->data;
2927 /* If the rest of space from this block is large enough
2928 for one-slot vector at least, set up it on a free list. */
2929 restbytes = VECTOR_BLOCK_BYTES - nbytes;
2930 if (restbytes >= VBLOCK_BYTES_MIN)
2932 eassert (restbytes % roundup_size == 0);
2933 SETUP_ON_FREE_LIST (ADVANCE (vector, nbytes), restbytes, index);
2935 return vector;
2938 /* Nonzero if VECTOR pointer is valid pointer inside BLOCK. */
2940 #define VECTOR_IN_BLOCK(vector, block) \
2941 ((char *) (vector) <= (block)->data \
2942 + VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN)
2944 /* Return the memory footprint of V in bytes. */
2946 static ptrdiff_t
2947 vector_nbytes (struct Lisp_Vector *v)
2949 ptrdiff_t size = v->header.size & ~ARRAY_MARK_FLAG;
2950 ptrdiff_t nwords;
2952 if (size & PSEUDOVECTOR_FLAG)
2954 if (PSEUDOVECTOR_TYPEP (&v->header, PVEC_BOOL_VECTOR))
2956 struct Lisp_Bool_Vector *bv = (struct Lisp_Bool_Vector *) v;
2957 ptrdiff_t word_bytes = (bool_vector_words (bv->size)
2958 * sizeof (bits_word));
2959 ptrdiff_t boolvec_bytes = bool_header_size + word_bytes;
2960 verify (header_size <= bool_header_size);
2961 nwords = (boolvec_bytes - header_size + word_size - 1) / word_size;
2963 else
2964 nwords = ((size & PSEUDOVECTOR_SIZE_MASK)
2965 + ((size & PSEUDOVECTOR_REST_MASK)
2966 >> PSEUDOVECTOR_SIZE_BITS));
2968 else
2969 nwords = size;
2970 return vroundup (header_size + word_size * nwords);
2973 /* Release extra resources still in use by VECTOR, which may be any
2974 vector-like object. For now, this is used just to free data in
2975 font objects. */
2977 static void
2978 cleanup_vector (struct Lisp_Vector *vector)
2980 detect_suspicious_free (vector);
2981 if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FONT)
2982 && ((vector->header.size & PSEUDOVECTOR_SIZE_MASK)
2983 == FONT_OBJECT_MAX))
2985 struct font_driver *drv = ((struct font *) vector)->driver;
2987 /* The font driver might sometimes be NULL, e.g. if Emacs was
2988 interrupted before it had time to set it up. */
2989 if (drv)
2991 /* Attempt to catch subtle bugs like Bug#16140. */
2992 eassert (valid_font_driver (drv));
2993 drv->close ((struct font *) vector);
2998 /* Reclaim space used by unmarked vectors. */
3000 NO_INLINE /* For better stack traces */
3001 static void
3002 sweep_vectors (void)
3004 struct vector_block *block, **bprev = &vector_blocks;
3005 struct large_vector *lv, **lvprev = &large_vectors;
3006 struct Lisp_Vector *vector, *next;
3008 total_vectors = total_vector_slots = total_free_vector_slots = 0;
3009 memset (vector_free_lists, 0, sizeof (vector_free_lists));
3011 /* Looking through vector blocks. */
3013 for (block = vector_blocks; block; block = *bprev)
3015 bool free_this_block = 0;
3016 ptrdiff_t nbytes;
3018 for (vector = (struct Lisp_Vector *) block->data;
3019 VECTOR_IN_BLOCK (vector, block); vector = next)
3021 if (VECTOR_MARKED_P (vector))
3023 VECTOR_UNMARK (vector);
3024 total_vectors++;
3025 nbytes = vector_nbytes (vector);
3026 total_vector_slots += nbytes / word_size;
3027 next = ADVANCE (vector, nbytes);
3029 else
3031 ptrdiff_t total_bytes;
3033 cleanup_vector (vector);
3034 nbytes = vector_nbytes (vector);
3035 total_bytes = nbytes;
3036 next = ADVANCE (vector, nbytes);
3038 /* While NEXT is not marked, try to coalesce with VECTOR,
3039 thus making VECTOR of the largest possible size. */
3041 while (VECTOR_IN_BLOCK (next, block))
3043 if (VECTOR_MARKED_P (next))
3044 break;
3045 cleanup_vector (next);
3046 nbytes = vector_nbytes (next);
3047 total_bytes += nbytes;
3048 next = ADVANCE (next, nbytes);
3051 eassert (total_bytes % roundup_size == 0);
3053 if (vector == (struct Lisp_Vector *) block->data
3054 && !VECTOR_IN_BLOCK (next, block))
3055 /* This block should be freed because all of its
3056 space was coalesced into the only free vector. */
3057 free_this_block = 1;
3058 else
3060 size_t tmp;
3061 SETUP_ON_FREE_LIST (vector, total_bytes, tmp);
3066 if (free_this_block)
3068 *bprev = block->next;
3069 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
3070 mem_delete (mem_find (block->data));
3071 #endif
3072 xfree (block);
3074 else
3075 bprev = &block->next;
3078 /* Sweep large vectors. */
3080 for (lv = large_vectors; lv; lv = *lvprev)
3082 vector = large_vector_vec (lv);
3083 if (VECTOR_MARKED_P (vector))
3085 VECTOR_UNMARK (vector);
3086 total_vectors++;
3087 if (vector->header.size & PSEUDOVECTOR_FLAG)
3089 /* All non-bool pseudovectors are small enough to be allocated
3090 from vector blocks. This code should be redesigned if some
3091 pseudovector type grows beyond VBLOCK_BYTES_MAX. */
3092 eassert (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_BOOL_VECTOR));
3093 total_vector_slots += vector_nbytes (vector) / word_size;
3095 else
3096 total_vector_slots
3097 += header_size / word_size + vector->header.size;
3098 lvprev = &lv->next;
3100 else
3102 *lvprev = lv->next;
3103 lisp_free (lv);
3108 /* Value is a pointer to a newly allocated Lisp_Vector structure
3109 with room for LEN Lisp_Objects. */
3111 static struct Lisp_Vector *
3112 allocate_vectorlike (ptrdiff_t len)
3114 struct Lisp_Vector *p;
3116 MALLOC_BLOCK_INPUT;
3118 if (len == 0)
3119 p = XVECTOR (zero_vector);
3120 else
3122 size_t nbytes = header_size + len * word_size;
3124 #ifdef DOUG_LEA_MALLOC
3125 if (!mmap_lisp_allowed_p ())
3126 mallopt (M_MMAP_MAX, 0);
3127 #endif
3129 if (nbytes <= VBLOCK_BYTES_MAX)
3130 p = allocate_vector_from_block (vroundup (nbytes));
3131 else
3133 struct large_vector *lv
3134 = lisp_malloc ((large_vector_offset + header_size
3135 + len * word_size),
3136 MEM_TYPE_VECTORLIKE);
3137 lv->next = large_vectors;
3138 large_vectors = lv;
3139 p = large_vector_vec (lv);
3142 #ifdef DOUG_LEA_MALLOC
3143 if (!mmap_lisp_allowed_p ())
3144 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
3145 #endif
3147 if (find_suspicious_object_in_range (p, (char *) p + nbytes))
3148 emacs_abort ();
3150 consing_since_gc += nbytes;
3151 vector_cells_consed += len;
3154 MALLOC_UNBLOCK_INPUT;
3156 return p;
3160 /* Allocate a vector with LEN slots. */
3162 struct Lisp_Vector *
3163 allocate_vector (EMACS_INT len)
3165 struct Lisp_Vector *v;
3166 ptrdiff_t nbytes_max = min (PTRDIFF_MAX, SIZE_MAX);
3168 if (min ((nbytes_max - header_size) / word_size, MOST_POSITIVE_FIXNUM) < len)
3169 memory_full (SIZE_MAX);
3170 v = allocate_vectorlike (len);
3171 v->header.size = len;
3172 return v;
3176 /* Allocate other vector-like structures. */
3178 struct Lisp_Vector *
3179 allocate_pseudovector (int memlen, int lisplen, enum pvec_type tag)
3181 struct Lisp_Vector *v = allocate_vectorlike (memlen);
3182 int i;
3184 /* Catch bogus values. */
3185 eassert (tag <= PVEC_FONT);
3186 eassert (memlen - lisplen <= (1 << PSEUDOVECTOR_REST_BITS) - 1);
3187 eassert (lisplen <= (1 << PSEUDOVECTOR_SIZE_BITS) - 1);
3189 /* Only the first lisplen slots will be traced normally by the GC. */
3190 for (i = 0; i < lisplen; ++i)
3191 v->contents[i] = Qnil;
3193 XSETPVECTYPESIZE (v, tag, lisplen, memlen - lisplen);
3194 return v;
3197 struct buffer *
3198 allocate_buffer (void)
3200 struct buffer *b = lisp_malloc (sizeof *b, MEM_TYPE_BUFFER);
3202 BUFFER_PVEC_INIT (b);
3203 /* Put B on the chain of all buffers including killed ones. */
3204 b->next = all_buffers;
3205 all_buffers = b;
3206 /* Note that the rest fields of B are not initialized. */
3207 return b;
3210 struct Lisp_Hash_Table *
3211 allocate_hash_table (void)
3213 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table, count, PVEC_HASH_TABLE);
3216 struct window *
3217 allocate_window (void)
3219 struct window *w;
3221 w = ALLOCATE_PSEUDOVECTOR (struct window, current_matrix, PVEC_WINDOW);
3222 /* Users assumes that non-Lisp data is zeroed. */
3223 memset (&w->current_matrix, 0,
3224 sizeof (*w) - offsetof (struct window, current_matrix));
3225 return w;
3228 struct terminal *
3229 allocate_terminal (void)
3231 struct terminal *t;
3233 t = ALLOCATE_PSEUDOVECTOR (struct terminal, next_terminal, PVEC_TERMINAL);
3234 /* Users assumes that non-Lisp data is zeroed. */
3235 memset (&t->next_terminal, 0,
3236 sizeof (*t) - offsetof (struct terminal, next_terminal));
3237 return t;
3240 struct frame *
3241 allocate_frame (void)
3243 struct frame *f;
3245 f = ALLOCATE_PSEUDOVECTOR (struct frame, face_cache, PVEC_FRAME);
3246 /* Users assumes that non-Lisp data is zeroed. */
3247 memset (&f->face_cache, 0,
3248 sizeof (*f) - offsetof (struct frame, face_cache));
3249 return f;
3252 struct Lisp_Process *
3253 allocate_process (void)
3255 struct Lisp_Process *p;
3257 p = ALLOCATE_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
3258 /* Users assumes that non-Lisp data is zeroed. */
3259 memset (&p->pid, 0,
3260 sizeof (*p) - offsetof (struct Lisp_Process, pid));
3261 return p;
3264 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
3265 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
3266 See also the function `vector'. */)
3267 (register Lisp_Object length, Lisp_Object init)
3269 Lisp_Object vector;
3270 register ptrdiff_t sizei;
3271 register ptrdiff_t i;
3272 register struct Lisp_Vector *p;
3274 CHECK_NATNUM (length);
3276 p = allocate_vector (XFASTINT (length));
3277 sizei = XFASTINT (length);
3278 for (i = 0; i < sizei; i++)
3279 p->contents[i] = init;
3281 XSETVECTOR (vector, p);
3282 return vector;
3286 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3287 doc: /* Return a newly created vector with specified arguments as elements.
3288 Any number of arguments, even zero arguments, are allowed.
3289 usage: (vector &rest OBJECTS) */)
3290 (ptrdiff_t nargs, Lisp_Object *args)
3292 ptrdiff_t i;
3293 register Lisp_Object val = make_uninit_vector (nargs);
3294 register struct Lisp_Vector *p = XVECTOR (val);
3296 for (i = 0; i < nargs; i++)
3297 p->contents[i] = args[i];
3298 return val;
3301 void
3302 make_byte_code (struct Lisp_Vector *v)
3304 /* Don't allow the global zero_vector to become a byte code object. */
3305 eassert (0 < v->header.size);
3307 if (v->header.size > 1 && STRINGP (v->contents[1])
3308 && STRING_MULTIBYTE (v->contents[1]))
3309 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3310 earlier because they produced a raw 8-bit string for byte-code
3311 and now such a byte-code string is loaded as multibyte while
3312 raw 8-bit characters converted to multibyte form. Thus, now we
3313 must convert them back to the original unibyte form. */
3314 v->contents[1] = Fstring_as_unibyte (v->contents[1]);
3315 XSETPVECTYPE (v, PVEC_COMPILED);
3318 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3319 doc: /* Create a byte-code object with specified arguments as elements.
3320 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3321 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3322 and (optional) INTERACTIVE-SPEC.
3323 The first four arguments are required; at most six have any
3324 significance.
3325 The ARGLIST can be either like the one of `lambda', in which case the arguments
3326 will be dynamically bound before executing the byte code, or it can be an
3327 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3328 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3329 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3330 argument to catch the left-over arguments. If such an integer is used, the
3331 arguments will not be dynamically bound but will be instead pushed on the
3332 stack before executing the byte-code.
3333 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3334 (ptrdiff_t nargs, Lisp_Object *args)
3336 ptrdiff_t i;
3337 register Lisp_Object val = make_uninit_vector (nargs);
3338 register struct Lisp_Vector *p = XVECTOR (val);
3340 /* We used to purecopy everything here, if purify-flag was set. This worked
3341 OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
3342 dangerous, since make-byte-code is used during execution to build
3343 closures, so any closure built during the preload phase would end up
3344 copied into pure space, including its free variables, which is sometimes
3345 just wasteful and other times plainly wrong (e.g. those free vars may want
3346 to be setcar'd). */
3348 for (i = 0; i < nargs; i++)
3349 p->contents[i] = args[i];
3350 make_byte_code (p);
3351 XSETCOMPILED (val, p);
3352 return val;
3357 /***********************************************************************
3358 Symbol Allocation
3359 ***********************************************************************/
3361 /* Like struct Lisp_Symbol, but padded so that the size is a multiple
3362 of the required alignment if LSB tags are used. */
3364 union aligned_Lisp_Symbol
3366 struct Lisp_Symbol s;
3367 #if USE_LSB_TAG
3368 unsigned char c[(sizeof (struct Lisp_Symbol) + GCALIGNMENT - 1)
3369 & -GCALIGNMENT];
3370 #endif
3373 /* Each symbol_block is just under 1020 bytes long, since malloc
3374 really allocates in units of powers of two and uses 4 bytes for its
3375 own overhead. */
3377 #define SYMBOL_BLOCK_SIZE \
3378 ((1020 - sizeof (struct symbol_block *)) / sizeof (union aligned_Lisp_Symbol))
3380 struct symbol_block
3382 /* Place `symbols' first, to preserve alignment. */
3383 union aligned_Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3384 struct symbol_block *next;
3387 /* Current symbol block and index of first unused Lisp_Symbol
3388 structure in it. */
3390 static struct symbol_block *symbol_block;
3391 static int symbol_block_index = SYMBOL_BLOCK_SIZE;
3392 /* Pointer to the first symbol_block that contains pinned symbols.
3393 Tests for 24.4 showed that at dump-time, Emacs contains about 15K symbols,
3394 10K of which are pinned (and all but 250 of them are interned in obarray),
3395 whereas a "typical session" has in the order of 30K symbols.
3396 `symbol_block_pinned' lets mark_pinned_symbols scan only 15K symbols rather
3397 than 30K to find the 10K symbols we need to mark. */
3398 static struct symbol_block *symbol_block_pinned;
3400 /* List of free symbols. */
3402 static struct Lisp_Symbol *symbol_free_list;
3404 static void
3405 set_symbol_name (Lisp_Object sym, Lisp_Object name)
3407 XSYMBOL (sym)->name = name;
3410 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3411 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3412 Its value is void, and its function definition and property list are nil. */)
3413 (Lisp_Object name)
3415 register Lisp_Object val;
3416 register struct Lisp_Symbol *p;
3418 CHECK_STRING (name);
3420 MALLOC_BLOCK_INPUT;
3422 if (symbol_free_list)
3424 XSETSYMBOL (val, symbol_free_list);
3425 symbol_free_list = symbol_free_list->next;
3427 else
3429 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3431 struct symbol_block *new
3432 = lisp_malloc (sizeof *new, MEM_TYPE_SYMBOL);
3433 new->next = symbol_block;
3434 symbol_block = new;
3435 symbol_block_index = 0;
3436 total_free_symbols += SYMBOL_BLOCK_SIZE;
3438 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index].s);
3439 symbol_block_index++;
3442 MALLOC_UNBLOCK_INPUT;
3444 p = XSYMBOL (val);
3445 set_symbol_name (val, name);
3446 set_symbol_plist (val, Qnil);
3447 p->redirect = SYMBOL_PLAINVAL;
3448 SET_SYMBOL_VAL (p, Qunbound);
3449 set_symbol_function (val, Qnil);
3450 set_symbol_next (val, NULL);
3451 p->gcmarkbit = false;
3452 p->interned = SYMBOL_UNINTERNED;
3453 p->constant = 0;
3454 p->declared_special = false;
3455 p->pinned = false;
3456 consing_since_gc += sizeof (struct Lisp_Symbol);
3457 symbols_consed++;
3458 total_free_symbols--;
3459 return val;
3464 /***********************************************************************
3465 Marker (Misc) Allocation
3466 ***********************************************************************/
3468 /* Like union Lisp_Misc, but padded so that its size is a multiple of
3469 the required alignment when LSB tags are used. */
3471 union aligned_Lisp_Misc
3473 union Lisp_Misc m;
3474 #if USE_LSB_TAG
3475 unsigned char c[(sizeof (union Lisp_Misc) + GCALIGNMENT - 1)
3476 & -GCALIGNMENT];
3477 #endif
3480 /* Allocation of markers and other objects that share that structure.
3481 Works like allocation of conses. */
3483 #define MARKER_BLOCK_SIZE \
3484 ((1020 - sizeof (struct marker_block *)) / sizeof (union aligned_Lisp_Misc))
3486 struct marker_block
3488 /* Place `markers' first, to preserve alignment. */
3489 union aligned_Lisp_Misc markers[MARKER_BLOCK_SIZE];
3490 struct marker_block *next;
3493 static struct marker_block *marker_block;
3494 static int marker_block_index = MARKER_BLOCK_SIZE;
3496 static union Lisp_Misc *marker_free_list;
3498 /* Return a newly allocated Lisp_Misc object of specified TYPE. */
3500 static Lisp_Object
3501 allocate_misc (enum Lisp_Misc_Type type)
3503 Lisp_Object val;
3505 MALLOC_BLOCK_INPUT;
3507 if (marker_free_list)
3509 XSETMISC (val, marker_free_list);
3510 marker_free_list = marker_free_list->u_free.chain;
3512 else
3514 if (marker_block_index == MARKER_BLOCK_SIZE)
3516 struct marker_block *new = lisp_malloc (sizeof *new, MEM_TYPE_MISC);
3517 new->next = marker_block;
3518 marker_block = new;
3519 marker_block_index = 0;
3520 total_free_markers += MARKER_BLOCK_SIZE;
3522 XSETMISC (val, &marker_block->markers[marker_block_index].m);
3523 marker_block_index++;
3526 MALLOC_UNBLOCK_INPUT;
3528 --total_free_markers;
3529 consing_since_gc += sizeof (union Lisp_Misc);
3530 misc_objects_consed++;
3531 XMISCANY (val)->type = type;
3532 XMISCANY (val)->gcmarkbit = 0;
3533 return val;
3536 /* Free a Lisp_Misc object. */
3538 void
3539 free_misc (Lisp_Object misc)
3541 XMISCANY (misc)->type = Lisp_Misc_Free;
3542 XMISC (misc)->u_free.chain = marker_free_list;
3543 marker_free_list = XMISC (misc);
3544 consing_since_gc -= sizeof (union Lisp_Misc);
3545 total_free_markers++;
3548 /* Verify properties of Lisp_Save_Value's representation
3549 that are assumed here and elsewhere. */
3551 verify (SAVE_UNUSED == 0);
3552 verify (((SAVE_INTEGER | SAVE_POINTER | SAVE_FUNCPOINTER | SAVE_OBJECT)
3553 >> SAVE_SLOT_BITS)
3554 == 0);
3556 /* Return Lisp_Save_Value objects for the various combinations
3557 that callers need. */
3559 Lisp_Object
3560 make_save_int_int_int (ptrdiff_t a, ptrdiff_t b, ptrdiff_t c)
3562 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3563 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3564 p->save_type = SAVE_TYPE_INT_INT_INT;
3565 p->data[0].integer = a;
3566 p->data[1].integer = b;
3567 p->data[2].integer = c;
3568 return val;
3571 Lisp_Object
3572 make_save_obj_obj_obj_obj (Lisp_Object a, Lisp_Object b, Lisp_Object c,
3573 Lisp_Object d)
3575 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3576 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3577 p->save_type = SAVE_TYPE_OBJ_OBJ_OBJ_OBJ;
3578 p->data[0].object = a;
3579 p->data[1].object = b;
3580 p->data[2].object = c;
3581 p->data[3].object = d;
3582 return val;
3585 Lisp_Object
3586 make_save_ptr (void *a)
3588 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3589 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3590 p->save_type = SAVE_POINTER;
3591 p->data[0].pointer = a;
3592 return val;
3595 Lisp_Object
3596 make_save_ptr_int (void *a, ptrdiff_t b)
3598 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3599 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3600 p->save_type = SAVE_TYPE_PTR_INT;
3601 p->data[0].pointer = a;
3602 p->data[1].integer = b;
3603 return val;
3606 #if ! (defined USE_X_TOOLKIT || defined USE_GTK)
3607 Lisp_Object
3608 make_save_ptr_ptr (void *a, void *b)
3610 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3611 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3612 p->save_type = SAVE_TYPE_PTR_PTR;
3613 p->data[0].pointer = a;
3614 p->data[1].pointer = b;
3615 return val;
3617 #endif
3619 Lisp_Object
3620 make_save_funcptr_ptr_obj (void (*a) (void), void *b, Lisp_Object c)
3622 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3623 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3624 p->save_type = SAVE_TYPE_FUNCPTR_PTR_OBJ;
3625 p->data[0].funcpointer = a;
3626 p->data[1].pointer = b;
3627 p->data[2].object = c;
3628 return val;
3631 /* Return a Lisp_Save_Value object that represents an array A
3632 of N Lisp objects. */
3634 Lisp_Object
3635 make_save_memory (Lisp_Object *a, ptrdiff_t n)
3637 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3638 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3639 p->save_type = SAVE_TYPE_MEMORY;
3640 p->data[0].pointer = a;
3641 p->data[1].integer = n;
3642 return val;
3645 /* Free a Lisp_Save_Value object. Do not use this function
3646 if SAVE contains pointer other than returned by xmalloc. */
3648 void
3649 free_save_value (Lisp_Object save)
3651 xfree (XSAVE_POINTER (save, 0));
3652 free_misc (save);
3655 /* Return a Lisp_Misc_Overlay object with specified START, END and PLIST. */
3657 Lisp_Object
3658 build_overlay (Lisp_Object start, Lisp_Object end, Lisp_Object plist)
3660 register Lisp_Object overlay;
3662 overlay = allocate_misc (Lisp_Misc_Overlay);
3663 OVERLAY_START (overlay) = start;
3664 OVERLAY_END (overlay) = end;
3665 set_overlay_plist (overlay, plist);
3666 XOVERLAY (overlay)->next = NULL;
3667 return overlay;
3670 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3671 doc: /* Return a newly allocated marker which does not point at any place. */)
3672 (void)
3674 register Lisp_Object val;
3675 register struct Lisp_Marker *p;
3677 val = allocate_misc (Lisp_Misc_Marker);
3678 p = XMARKER (val);
3679 p->buffer = 0;
3680 p->bytepos = 0;
3681 p->charpos = 0;
3682 p->next = NULL;
3683 p->insertion_type = 0;
3684 p->need_adjustment = 0;
3685 return val;
3688 /* Return a newly allocated marker which points into BUF
3689 at character position CHARPOS and byte position BYTEPOS. */
3691 Lisp_Object
3692 build_marker (struct buffer *buf, ptrdiff_t charpos, ptrdiff_t bytepos)
3694 Lisp_Object obj;
3695 struct Lisp_Marker *m;
3697 /* No dead buffers here. */
3698 eassert (BUFFER_LIVE_P (buf));
3700 /* Every character is at least one byte. */
3701 eassert (charpos <= bytepos);
3703 obj = allocate_misc (Lisp_Misc_Marker);
3704 m = XMARKER (obj);
3705 m->buffer = buf;
3706 m->charpos = charpos;
3707 m->bytepos = bytepos;
3708 m->insertion_type = 0;
3709 m->need_adjustment = 0;
3710 m->next = BUF_MARKERS (buf);
3711 BUF_MARKERS (buf) = m;
3712 return obj;
3715 /* Put MARKER back on the free list after using it temporarily. */
3717 void
3718 free_marker (Lisp_Object marker)
3720 unchain_marker (XMARKER (marker));
3721 free_misc (marker);
3725 /* Return a newly created vector or string with specified arguments as
3726 elements. If all the arguments are characters that can fit
3727 in a string of events, make a string; otherwise, make a vector.
3729 Any number of arguments, even zero arguments, are allowed. */
3731 Lisp_Object
3732 make_event_array (ptrdiff_t nargs, Lisp_Object *args)
3734 ptrdiff_t i;
3736 for (i = 0; i < nargs; i++)
3737 /* The things that fit in a string
3738 are characters that are in 0...127,
3739 after discarding the meta bit and all the bits above it. */
3740 if (!INTEGERP (args[i])
3741 || (XINT (args[i]) & ~(-CHAR_META)) >= 0200)
3742 return Fvector (nargs, args);
3744 /* Since the loop exited, we know that all the things in it are
3745 characters, so we can make a string. */
3747 Lisp_Object result;
3749 result = Fmake_string (make_number (nargs), make_number (0));
3750 for (i = 0; i < nargs; i++)
3752 SSET (result, i, XINT (args[i]));
3753 /* Move the meta bit to the right place for a string char. */
3754 if (XINT (args[i]) & CHAR_META)
3755 SSET (result, i, SREF (result, i) | 0x80);
3758 return result;
3764 /************************************************************************
3765 Memory Full Handling
3766 ************************************************************************/
3769 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
3770 there may have been size_t overflow so that malloc was never
3771 called, or perhaps malloc was invoked successfully but the
3772 resulting pointer had problems fitting into a tagged EMACS_INT. In
3773 either case this counts as memory being full even though malloc did
3774 not fail. */
3776 void
3777 memory_full (size_t nbytes)
3779 /* Do not go into hysterics merely because a large request failed. */
3780 bool enough_free_memory = 0;
3781 if (SPARE_MEMORY < nbytes)
3783 void *p;
3785 MALLOC_BLOCK_INPUT;
3786 p = malloc (SPARE_MEMORY);
3787 if (p)
3789 free (p);
3790 enough_free_memory = 1;
3792 MALLOC_UNBLOCK_INPUT;
3795 if (! enough_free_memory)
3797 int i;
3799 Vmemory_full = Qt;
3801 memory_full_cons_threshold = sizeof (struct cons_block);
3803 /* The first time we get here, free the spare memory. */
3804 for (i = 0; i < ARRAYELTS (spare_memory); i++)
3805 if (spare_memory[i])
3807 if (i == 0)
3808 free (spare_memory[i]);
3809 else if (i >= 1 && i <= 4)
3810 lisp_align_free (spare_memory[i]);
3811 else
3812 lisp_free (spare_memory[i]);
3813 spare_memory[i] = 0;
3817 /* This used to call error, but if we've run out of memory, we could
3818 get infinite recursion trying to build the string. */
3819 xsignal (Qnil, Vmemory_signal_data);
3822 /* If we released our reserve (due to running out of memory),
3823 and we have a fair amount free once again,
3824 try to set aside another reserve in case we run out once more.
3826 This is called when a relocatable block is freed in ralloc.c,
3827 and also directly from this file, in case we're not using ralloc.c. */
3829 void
3830 refill_memory_reserve (void)
3832 #ifndef SYSTEM_MALLOC
3833 if (spare_memory[0] == 0)
3834 spare_memory[0] = malloc (SPARE_MEMORY);
3835 if (spare_memory[1] == 0)
3836 spare_memory[1] = lisp_align_malloc (sizeof (struct cons_block),
3837 MEM_TYPE_SPARE);
3838 if (spare_memory[2] == 0)
3839 spare_memory[2] = lisp_align_malloc (sizeof (struct cons_block),
3840 MEM_TYPE_SPARE);
3841 if (spare_memory[3] == 0)
3842 spare_memory[3] = lisp_align_malloc (sizeof (struct cons_block),
3843 MEM_TYPE_SPARE);
3844 if (spare_memory[4] == 0)
3845 spare_memory[4] = lisp_align_malloc (sizeof (struct cons_block),
3846 MEM_TYPE_SPARE);
3847 if (spare_memory[5] == 0)
3848 spare_memory[5] = lisp_malloc (sizeof (struct string_block),
3849 MEM_TYPE_SPARE);
3850 if (spare_memory[6] == 0)
3851 spare_memory[6] = lisp_malloc (sizeof (struct string_block),
3852 MEM_TYPE_SPARE);
3853 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
3854 Vmemory_full = Qnil;
3855 #endif
3858 /************************************************************************
3859 C Stack Marking
3860 ************************************************************************/
3862 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
3864 /* Conservative C stack marking requires a method to identify possibly
3865 live Lisp objects given a pointer value. We do this by keeping
3866 track of blocks of Lisp data that are allocated in a red-black tree
3867 (see also the comment of mem_node which is the type of nodes in
3868 that tree). Function lisp_malloc adds information for an allocated
3869 block to the red-black tree with calls to mem_insert, and function
3870 lisp_free removes it with mem_delete. Functions live_string_p etc
3871 call mem_find to lookup information about a given pointer in the
3872 tree, and use that to determine if the pointer points to a Lisp
3873 object or not. */
3875 /* Initialize this part of alloc.c. */
3877 static void
3878 mem_init (void)
3880 mem_z.left = mem_z.right = MEM_NIL;
3881 mem_z.parent = NULL;
3882 mem_z.color = MEM_BLACK;
3883 mem_z.start = mem_z.end = NULL;
3884 mem_root = MEM_NIL;
3888 /* Value is a pointer to the mem_node containing START. Value is
3889 MEM_NIL if there is no node in the tree containing START. */
3891 static struct mem_node *
3892 mem_find (void *start)
3894 struct mem_node *p;
3896 if (start < min_heap_address || start > max_heap_address)
3897 return MEM_NIL;
3899 /* Make the search always successful to speed up the loop below. */
3900 mem_z.start = start;
3901 mem_z.end = (char *) start + 1;
3903 p = mem_root;
3904 while (start < p->start || start >= p->end)
3905 p = start < p->start ? p->left : p->right;
3906 return p;
3910 /* Insert a new node into the tree for a block of memory with start
3911 address START, end address END, and type TYPE. Value is a
3912 pointer to the node that was inserted. */
3914 static struct mem_node *
3915 mem_insert (void *start, void *end, enum mem_type type)
3917 struct mem_node *c, *parent, *x;
3919 if (min_heap_address == NULL || start < min_heap_address)
3920 min_heap_address = start;
3921 if (max_heap_address == NULL || end > max_heap_address)
3922 max_heap_address = end;
3924 /* See where in the tree a node for START belongs. In this
3925 particular application, it shouldn't happen that a node is already
3926 present. For debugging purposes, let's check that. */
3927 c = mem_root;
3928 parent = NULL;
3930 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
3932 while (c != MEM_NIL)
3934 if (start >= c->start && start < c->end)
3935 emacs_abort ();
3936 parent = c;
3937 c = start < c->start ? c->left : c->right;
3940 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3942 while (c != MEM_NIL)
3944 parent = c;
3945 c = start < c->start ? c->left : c->right;
3948 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3950 /* Create a new node. */
3951 #ifdef GC_MALLOC_CHECK
3952 x = malloc (sizeof *x);
3953 if (x == NULL)
3954 emacs_abort ();
3955 #else
3956 x = xmalloc (sizeof *x);
3957 #endif
3958 x->start = start;
3959 x->end = end;
3960 x->type = type;
3961 x->parent = parent;
3962 x->left = x->right = MEM_NIL;
3963 x->color = MEM_RED;
3965 /* Insert it as child of PARENT or install it as root. */
3966 if (parent)
3968 if (start < parent->start)
3969 parent->left = x;
3970 else
3971 parent->right = x;
3973 else
3974 mem_root = x;
3976 /* Re-establish red-black tree properties. */
3977 mem_insert_fixup (x);
3979 return x;
3983 /* Re-establish the red-black properties of the tree, and thereby
3984 balance the tree, after node X has been inserted; X is always red. */
3986 static void
3987 mem_insert_fixup (struct mem_node *x)
3989 while (x != mem_root && x->parent->color == MEM_RED)
3991 /* X is red and its parent is red. This is a violation of
3992 red-black tree property #3. */
3994 if (x->parent == x->parent->parent->left)
3996 /* We're on the left side of our grandparent, and Y is our
3997 "uncle". */
3998 struct mem_node *y = x->parent->parent->right;
4000 if (y->color == MEM_RED)
4002 /* Uncle and parent are red but should be black because
4003 X is red. Change the colors accordingly and proceed
4004 with the grandparent. */
4005 x->parent->color = MEM_BLACK;
4006 y->color = MEM_BLACK;
4007 x->parent->parent->color = MEM_RED;
4008 x = x->parent->parent;
4010 else
4012 /* Parent and uncle have different colors; parent is
4013 red, uncle is black. */
4014 if (x == x->parent->right)
4016 x = x->parent;
4017 mem_rotate_left (x);
4020 x->parent->color = MEM_BLACK;
4021 x->parent->parent->color = MEM_RED;
4022 mem_rotate_right (x->parent->parent);
4025 else
4027 /* This is the symmetrical case of above. */
4028 struct mem_node *y = x->parent->parent->left;
4030 if (y->color == MEM_RED)
4032 x->parent->color = MEM_BLACK;
4033 y->color = MEM_BLACK;
4034 x->parent->parent->color = MEM_RED;
4035 x = x->parent->parent;
4037 else
4039 if (x == x->parent->left)
4041 x = x->parent;
4042 mem_rotate_right (x);
4045 x->parent->color = MEM_BLACK;
4046 x->parent->parent->color = MEM_RED;
4047 mem_rotate_left (x->parent->parent);
4052 /* The root may have been changed to red due to the algorithm. Set
4053 it to black so that property #5 is satisfied. */
4054 mem_root->color = MEM_BLACK;
4058 /* (x) (y)
4059 / \ / \
4060 a (y) ===> (x) c
4061 / \ / \
4062 b c a b */
4064 static void
4065 mem_rotate_left (struct mem_node *x)
4067 struct mem_node *y;
4069 /* Turn y's left sub-tree into x's right sub-tree. */
4070 y = x->right;
4071 x->right = y->left;
4072 if (y->left != MEM_NIL)
4073 y->left->parent = x;
4075 /* Y's parent was x's parent. */
4076 if (y != MEM_NIL)
4077 y->parent = x->parent;
4079 /* Get the parent to point to y instead of x. */
4080 if (x->parent)
4082 if (x == x->parent->left)
4083 x->parent->left = y;
4084 else
4085 x->parent->right = y;
4087 else
4088 mem_root = y;
4090 /* Put x on y's left. */
4091 y->left = x;
4092 if (x != MEM_NIL)
4093 x->parent = y;
4097 /* (x) (Y)
4098 / \ / \
4099 (y) c ===> a (x)
4100 / \ / \
4101 a b b c */
4103 static void
4104 mem_rotate_right (struct mem_node *x)
4106 struct mem_node *y = x->left;
4108 x->left = y->right;
4109 if (y->right != MEM_NIL)
4110 y->right->parent = x;
4112 if (y != MEM_NIL)
4113 y->parent = x->parent;
4114 if (x->parent)
4116 if (x == x->parent->right)
4117 x->parent->right = y;
4118 else
4119 x->parent->left = y;
4121 else
4122 mem_root = y;
4124 y->right = x;
4125 if (x != MEM_NIL)
4126 x->parent = y;
4130 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
4132 static void
4133 mem_delete (struct mem_node *z)
4135 struct mem_node *x, *y;
4137 if (!z || z == MEM_NIL)
4138 return;
4140 if (z->left == MEM_NIL || z->right == MEM_NIL)
4141 y = z;
4142 else
4144 y = z->right;
4145 while (y->left != MEM_NIL)
4146 y = y->left;
4149 if (y->left != MEM_NIL)
4150 x = y->left;
4151 else
4152 x = y->right;
4154 x->parent = y->parent;
4155 if (y->parent)
4157 if (y == y->parent->left)
4158 y->parent->left = x;
4159 else
4160 y->parent->right = x;
4162 else
4163 mem_root = x;
4165 if (y != z)
4167 z->start = y->start;
4168 z->end = y->end;
4169 z->type = y->type;
4172 if (y->color == MEM_BLACK)
4173 mem_delete_fixup (x);
4175 #ifdef GC_MALLOC_CHECK
4176 free (y);
4177 #else
4178 xfree (y);
4179 #endif
4183 /* Re-establish the red-black properties of the tree, after a
4184 deletion. */
4186 static void
4187 mem_delete_fixup (struct mem_node *x)
4189 while (x != mem_root && x->color == MEM_BLACK)
4191 if (x == x->parent->left)
4193 struct mem_node *w = x->parent->right;
4195 if (w->color == MEM_RED)
4197 w->color = MEM_BLACK;
4198 x->parent->color = MEM_RED;
4199 mem_rotate_left (x->parent);
4200 w = x->parent->right;
4203 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
4205 w->color = MEM_RED;
4206 x = x->parent;
4208 else
4210 if (w->right->color == MEM_BLACK)
4212 w->left->color = MEM_BLACK;
4213 w->color = MEM_RED;
4214 mem_rotate_right (w);
4215 w = x->parent->right;
4217 w->color = x->parent->color;
4218 x->parent->color = MEM_BLACK;
4219 w->right->color = MEM_BLACK;
4220 mem_rotate_left (x->parent);
4221 x = mem_root;
4224 else
4226 struct mem_node *w = x->parent->left;
4228 if (w->color == MEM_RED)
4230 w->color = MEM_BLACK;
4231 x->parent->color = MEM_RED;
4232 mem_rotate_right (x->parent);
4233 w = x->parent->left;
4236 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
4238 w->color = MEM_RED;
4239 x = x->parent;
4241 else
4243 if (w->left->color == MEM_BLACK)
4245 w->right->color = MEM_BLACK;
4246 w->color = MEM_RED;
4247 mem_rotate_left (w);
4248 w = x->parent->left;
4251 w->color = x->parent->color;
4252 x->parent->color = MEM_BLACK;
4253 w->left->color = MEM_BLACK;
4254 mem_rotate_right (x->parent);
4255 x = mem_root;
4260 x->color = MEM_BLACK;
4264 /* Value is non-zero if P is a pointer to a live Lisp string on
4265 the heap. M is a pointer to the mem_block for P. */
4267 static bool
4268 live_string_p (struct mem_node *m, void *p)
4270 if (m->type == MEM_TYPE_STRING)
4272 struct string_block *b = m->start;
4273 ptrdiff_t offset = (char *) p - (char *) &b->strings[0];
4275 /* P must point to the start of a Lisp_String structure, and it
4276 must not be on the free-list. */
4277 return (offset >= 0
4278 && offset % sizeof b->strings[0] == 0
4279 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
4280 && ((struct Lisp_String *) p)->data != NULL);
4282 else
4283 return 0;
4287 /* Value is non-zero if P is a pointer to a live Lisp cons on
4288 the heap. M is a pointer to the mem_block for P. */
4290 static bool
4291 live_cons_p (struct mem_node *m, void *p)
4293 if (m->type == MEM_TYPE_CONS)
4295 struct cons_block *b = m->start;
4296 ptrdiff_t offset = (char *) p - (char *) &b->conses[0];
4298 /* P must point to the start of a Lisp_Cons, not be
4299 one of the unused cells in the current cons block,
4300 and not be on the free-list. */
4301 return (offset >= 0
4302 && offset % sizeof b->conses[0] == 0
4303 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
4304 && (b != cons_block
4305 || offset / sizeof b->conses[0] < cons_block_index)
4306 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
4308 else
4309 return 0;
4313 /* Value is non-zero if P is a pointer to a live Lisp symbol on
4314 the heap. M is a pointer to the mem_block for P. */
4316 static bool
4317 live_symbol_p (struct mem_node *m, void *p)
4319 if (m->type == MEM_TYPE_SYMBOL)
4321 struct symbol_block *b = m->start;
4322 ptrdiff_t offset = (char *) p - (char *) &b->symbols[0];
4324 /* P must point to the start of a Lisp_Symbol, not be
4325 one of the unused cells in the current symbol block,
4326 and not be on the free-list. */
4327 return (offset >= 0
4328 && offset % sizeof b->symbols[0] == 0
4329 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
4330 && (b != symbol_block
4331 || offset / sizeof b->symbols[0] < symbol_block_index)
4332 && !EQ (((struct Lisp_Symbol *)p)->function, Vdead));
4334 else
4335 return 0;
4339 /* Value is non-zero if P is a pointer to a live Lisp float on
4340 the heap. M is a pointer to the mem_block for P. */
4342 static bool
4343 live_float_p (struct mem_node *m, void *p)
4345 if (m->type == MEM_TYPE_FLOAT)
4347 struct float_block *b = m->start;
4348 ptrdiff_t offset = (char *) p - (char *) &b->floats[0];
4350 /* P must point to the start of a Lisp_Float and not be
4351 one of the unused cells in the current float block. */
4352 return (offset >= 0
4353 && offset % sizeof b->floats[0] == 0
4354 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
4355 && (b != float_block
4356 || offset / sizeof b->floats[0] < float_block_index));
4358 else
4359 return 0;
4363 /* Value is non-zero if P is a pointer to a live Lisp Misc on
4364 the heap. M is a pointer to the mem_block for P. */
4366 static bool
4367 live_misc_p (struct mem_node *m, void *p)
4369 if (m->type == MEM_TYPE_MISC)
4371 struct marker_block *b = m->start;
4372 ptrdiff_t offset = (char *) p - (char *) &b->markers[0];
4374 /* P must point to the start of a Lisp_Misc, not be
4375 one of the unused cells in the current misc block,
4376 and not be on the free-list. */
4377 return (offset >= 0
4378 && offset % sizeof b->markers[0] == 0
4379 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
4380 && (b != marker_block
4381 || offset / sizeof b->markers[0] < marker_block_index)
4382 && ((union Lisp_Misc *) p)->u_any.type != Lisp_Misc_Free);
4384 else
4385 return 0;
4389 /* Value is non-zero if P is a pointer to a live vector-like object.
4390 M is a pointer to the mem_block for P. */
4392 static bool
4393 live_vector_p (struct mem_node *m, void *p)
4395 if (m->type == MEM_TYPE_VECTOR_BLOCK)
4397 /* This memory node corresponds to a vector block. */
4398 struct vector_block *block = m->start;
4399 struct Lisp_Vector *vector = (struct Lisp_Vector *) block->data;
4401 /* P is in the block's allocation range. Scan the block
4402 up to P and see whether P points to the start of some
4403 vector which is not on a free list. FIXME: check whether
4404 some allocation patterns (probably a lot of short vectors)
4405 may cause a substantial overhead of this loop. */
4406 while (VECTOR_IN_BLOCK (vector, block)
4407 && vector <= (struct Lisp_Vector *) p)
4409 if (!PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FREE) && vector == p)
4410 return 1;
4411 else
4412 vector = ADVANCE (vector, vector_nbytes (vector));
4415 else if (m->type == MEM_TYPE_VECTORLIKE && p == large_vector_vec (m->start))
4416 /* This memory node corresponds to a large vector. */
4417 return 1;
4418 return 0;
4422 /* Value is non-zero if P is a pointer to a live buffer. M is a
4423 pointer to the mem_block for P. */
4425 static bool
4426 live_buffer_p (struct mem_node *m, void *p)
4428 /* P must point to the start of the block, and the buffer
4429 must not have been killed. */
4430 return (m->type == MEM_TYPE_BUFFER
4431 && p == m->start
4432 && !NILP (((struct buffer *) p)->INTERNAL_FIELD (name)));
4435 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
4437 #if GC_MARK_STACK
4439 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4441 /* Currently not used, but may be called from gdb. */
4443 void dump_zombies (void) EXTERNALLY_VISIBLE;
4445 /* Array of objects that are kept alive because the C stack contains
4446 a pattern that looks like a reference to them. */
4448 #define MAX_ZOMBIES 10
4449 static Lisp_Object zombies[MAX_ZOMBIES];
4451 /* Number of zombie objects. */
4453 static EMACS_INT nzombies;
4455 /* Number of garbage collections. */
4457 static EMACS_INT ngcs;
4459 /* Average percentage of zombies per collection. */
4461 static double avg_zombies;
4463 /* Max. number of live and zombie objects. */
4465 static EMACS_INT max_live, max_zombies;
4467 /* Average number of live objects per GC. */
4469 static double avg_live;
4471 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
4472 doc: /* Show information about live and zombie objects. */)
4473 (void)
4475 Lisp_Object args[8], zombie_list = Qnil;
4476 EMACS_INT i;
4477 for (i = 0; i < min (MAX_ZOMBIES, nzombies); i++)
4478 zombie_list = Fcons (zombies[i], zombie_list);
4479 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
4480 args[1] = make_number (ngcs);
4481 args[2] = make_float (avg_live);
4482 args[3] = make_float (avg_zombies);
4483 args[4] = make_float (avg_zombies / avg_live / 100);
4484 args[5] = make_number (max_live);
4485 args[6] = make_number (max_zombies);
4486 args[7] = zombie_list;
4487 return Fmessage (8, args);
4490 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4493 /* Mark OBJ if we can prove it's a Lisp_Object. */
4495 static void
4496 mark_maybe_object (Lisp_Object obj)
4498 void *po;
4499 struct mem_node *m;
4501 #if USE_VALGRIND
4502 if (valgrind_p)
4503 VALGRIND_MAKE_MEM_DEFINED (&obj, sizeof (obj));
4504 #endif
4506 if (INTEGERP (obj))
4507 return;
4509 po = (void *) XPNTR (obj);
4510 m = mem_find (po);
4512 if (m != MEM_NIL)
4514 bool mark_p = 0;
4516 switch (XTYPE (obj))
4518 case Lisp_String:
4519 mark_p = (live_string_p (m, po)
4520 && !STRING_MARKED_P ((struct Lisp_String *) po));
4521 break;
4523 case Lisp_Cons:
4524 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4525 break;
4527 case Lisp_Symbol:
4528 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4529 break;
4531 case Lisp_Float:
4532 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4533 break;
4535 case Lisp_Vectorlike:
4536 /* Note: can't check BUFFERP before we know it's a
4537 buffer because checking that dereferences the pointer
4538 PO which might point anywhere. */
4539 if (live_vector_p (m, po))
4540 mark_p = !SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4541 else if (live_buffer_p (m, po))
4542 mark_p = BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4543 break;
4545 case Lisp_Misc:
4546 mark_p = (live_misc_p (m, po) && !XMISCANY (obj)->gcmarkbit);
4547 break;
4549 default:
4550 break;
4553 if (mark_p)
4555 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4556 if (nzombies < MAX_ZOMBIES)
4557 zombies[nzombies] = obj;
4558 ++nzombies;
4559 #endif
4560 mark_object (obj);
4565 /* Return true if P can point to Lisp data, and false otherwise.
4566 USE_LSB_TAG needs Lisp data to be aligned on multiples of GCALIGNMENT.
4567 Otherwise, assume that Lisp data is aligned on even addresses. */
4569 static bool
4570 maybe_lisp_pointer (void *p)
4572 return !((intptr_t) p % (USE_LSB_TAG ? GCALIGNMENT : 2));
4575 /* If P points to Lisp data, mark that as live if it isn't already
4576 marked. */
4578 static void
4579 mark_maybe_pointer (void *p)
4581 struct mem_node *m;
4583 #if USE_VALGRIND
4584 if (valgrind_p)
4585 VALGRIND_MAKE_MEM_DEFINED (&p, sizeof (p));
4586 #endif
4588 if (!maybe_lisp_pointer (p))
4589 return;
4591 m = mem_find (p);
4592 if (m != MEM_NIL)
4594 Lisp_Object obj = Qnil;
4596 switch (m->type)
4598 case MEM_TYPE_NON_LISP:
4599 case MEM_TYPE_SPARE:
4600 /* Nothing to do; not a pointer to Lisp memory. */
4601 break;
4603 case MEM_TYPE_BUFFER:
4604 if (live_buffer_p (m, p) && !VECTOR_MARKED_P ((struct buffer *)p))
4605 XSETVECTOR (obj, p);
4606 break;
4608 case MEM_TYPE_CONS:
4609 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4610 XSETCONS (obj, p);
4611 break;
4613 case MEM_TYPE_STRING:
4614 if (live_string_p (m, p)
4615 && !STRING_MARKED_P ((struct Lisp_String *) p))
4616 XSETSTRING (obj, p);
4617 break;
4619 case MEM_TYPE_MISC:
4620 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4621 XSETMISC (obj, p);
4622 break;
4624 case MEM_TYPE_SYMBOL:
4625 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4626 XSETSYMBOL (obj, p);
4627 break;
4629 case MEM_TYPE_FLOAT:
4630 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4631 XSETFLOAT (obj, p);
4632 break;
4634 case MEM_TYPE_VECTORLIKE:
4635 case MEM_TYPE_VECTOR_BLOCK:
4636 if (live_vector_p (m, p))
4638 Lisp_Object tem;
4639 XSETVECTOR (tem, p);
4640 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4641 obj = tem;
4643 break;
4645 default:
4646 emacs_abort ();
4649 if (!NILP (obj))
4650 mark_object (obj);
4655 /* Alignment of pointer values. Use alignof, as it sometimes returns
4656 a smaller alignment than GCC's __alignof__ and mark_memory might
4657 miss objects if __alignof__ were used. */
4658 #define GC_POINTER_ALIGNMENT alignof (void *)
4660 /* Define POINTERS_MIGHT_HIDE_IN_OBJECTS to 1 if marking via C pointers does
4661 not suffice, which is the typical case. A host where a Lisp_Object is
4662 wider than a pointer might allocate a Lisp_Object in non-adjacent halves.
4663 If USE_LSB_TAG, the bottom half is not a valid pointer, but it should
4664 suffice to widen it to to a Lisp_Object and check it that way. */
4665 #if USE_LSB_TAG || VAL_MAX < UINTPTR_MAX
4666 # if !USE_LSB_TAG && VAL_MAX < UINTPTR_MAX >> GCTYPEBITS
4667 /* If tag bits straddle pointer-word boundaries, neither mark_maybe_pointer
4668 nor mark_maybe_object can follow the pointers. This should not occur on
4669 any practical porting target. */
4670 # error "MSB type bits straddle pointer-word boundaries"
4671 # endif
4672 /* Marking via C pointers does not suffice, because Lisp_Objects contain
4673 pointer words that hold pointers ORed with type bits. */
4674 # define POINTERS_MIGHT_HIDE_IN_OBJECTS 1
4675 #else
4676 /* Marking via C pointers suffices, because Lisp_Objects contain pointer
4677 words that hold unmodified pointers. */
4678 # define POINTERS_MIGHT_HIDE_IN_OBJECTS 0
4679 #endif
4681 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4682 or END+OFFSET..START. */
4684 static void ATTRIBUTE_NO_SANITIZE_ADDRESS
4685 mark_memory (void *start, void *end)
4687 void **pp;
4688 int i;
4690 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4691 nzombies = 0;
4692 #endif
4694 /* Make START the pointer to the start of the memory region,
4695 if it isn't already. */
4696 if (end < start)
4698 void *tem = start;
4699 start = end;
4700 end = tem;
4703 /* Mark Lisp data pointed to. This is necessary because, in some
4704 situations, the C compiler optimizes Lisp objects away, so that
4705 only a pointer to them remains. Example:
4707 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4710 Lisp_Object obj = build_string ("test");
4711 struct Lisp_String *s = XSTRING (obj);
4712 Fgarbage_collect ();
4713 fprintf (stderr, "test `%s'\n", s->data);
4714 return Qnil;
4717 Here, `obj' isn't really used, and the compiler optimizes it
4718 away. The only reference to the life string is through the
4719 pointer `s'. */
4721 for (pp = start; (void *) pp < end; pp++)
4722 for (i = 0; i < sizeof *pp; i += GC_POINTER_ALIGNMENT)
4724 void *p = *(void **) ((char *) pp + i);
4725 mark_maybe_pointer (p);
4726 if (POINTERS_MIGHT_HIDE_IN_OBJECTS)
4727 mark_maybe_object (XIL ((intptr_t) p));
4731 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4733 static bool setjmp_tested_p;
4734 static int longjmps_done;
4736 #define SETJMP_WILL_LIKELY_WORK "\
4738 Emacs garbage collector has been changed to use conservative stack\n\
4739 marking. Emacs has determined that the method it uses to do the\n\
4740 marking will likely work on your system, but this isn't sure.\n\
4742 If you are a system-programmer, or can get the help of a local wizard\n\
4743 who is, please take a look at the function mark_stack in alloc.c, and\n\
4744 verify that the methods used are appropriate for your system.\n\
4746 Please mail the result to <emacs-devel@gnu.org>.\n\
4749 #define SETJMP_WILL_NOT_WORK "\
4751 Emacs garbage collector has been changed to use conservative stack\n\
4752 marking. Emacs has determined that the default method it uses to do the\n\
4753 marking will not work on your system. We will need a system-dependent\n\
4754 solution for your system.\n\
4756 Please take a look at the function mark_stack in alloc.c, and\n\
4757 try to find a way to make it work on your system.\n\
4759 Note that you may get false negatives, depending on the compiler.\n\
4760 In particular, you need to use -O with GCC for this test.\n\
4762 Please mail the result to <emacs-devel@gnu.org>.\n\
4766 /* Perform a quick check if it looks like setjmp saves registers in a
4767 jmp_buf. Print a message to stderr saying so. When this test
4768 succeeds, this is _not_ a proof that setjmp is sufficient for
4769 conservative stack marking. Only the sources or a disassembly
4770 can prove that. */
4772 static void
4773 test_setjmp (void)
4775 char buf[10];
4776 register int x;
4777 sys_jmp_buf jbuf;
4779 /* Arrange for X to be put in a register. */
4780 sprintf (buf, "1");
4781 x = strlen (buf);
4782 x = 2 * x - 1;
4784 sys_setjmp (jbuf);
4785 if (longjmps_done == 1)
4787 /* Came here after the longjmp at the end of the function.
4789 If x == 1, the longjmp has restored the register to its
4790 value before the setjmp, and we can hope that setjmp
4791 saves all such registers in the jmp_buf, although that
4792 isn't sure.
4794 For other values of X, either something really strange is
4795 taking place, or the setjmp just didn't save the register. */
4797 if (x == 1)
4798 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4799 else
4801 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4802 exit (1);
4806 ++longjmps_done;
4807 x = 2;
4808 if (longjmps_done == 1)
4809 sys_longjmp (jbuf, 1);
4812 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4815 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4817 /* Abort if anything GCPRO'd doesn't survive the GC. */
4819 static void
4820 check_gcpros (void)
4822 struct gcpro *p;
4823 ptrdiff_t i;
4825 for (p = gcprolist; p; p = p->next)
4826 for (i = 0; i < p->nvars; ++i)
4827 if (!survives_gc_p (p->var[i]))
4828 /* FIXME: It's not necessarily a bug. It might just be that the
4829 GCPRO is unnecessary or should release the object sooner. */
4830 emacs_abort ();
4833 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4835 void
4836 dump_zombies (void)
4838 int i;
4840 fprintf (stderr, "\nZombies kept alive = %"pI"d:\n", nzombies);
4841 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
4843 fprintf (stderr, " %d = ", i);
4844 debug_print (zombies[i]);
4848 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4851 /* Mark live Lisp objects on the C stack.
4853 There are several system-dependent problems to consider when
4854 porting this to new architectures:
4856 Processor Registers
4858 We have to mark Lisp objects in CPU registers that can hold local
4859 variables or are used to pass parameters.
4861 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4862 something that either saves relevant registers on the stack, or
4863 calls mark_maybe_object passing it each register's contents.
4865 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4866 implementation assumes that calling setjmp saves registers we need
4867 to see in a jmp_buf which itself lies on the stack. This doesn't
4868 have to be true! It must be verified for each system, possibly
4869 by taking a look at the source code of setjmp.
4871 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4872 can use it as a machine independent method to store all registers
4873 to the stack. In this case the macros described in the previous
4874 two paragraphs are not used.
4876 Stack Layout
4878 Architectures differ in the way their processor stack is organized.
4879 For example, the stack might look like this
4881 +----------------+
4882 | Lisp_Object | size = 4
4883 +----------------+
4884 | something else | size = 2
4885 +----------------+
4886 | Lisp_Object | size = 4
4887 +----------------+
4888 | ... |
4890 In such a case, not every Lisp_Object will be aligned equally. To
4891 find all Lisp_Object on the stack it won't be sufficient to walk
4892 the stack in steps of 4 bytes. Instead, two passes will be
4893 necessary, one starting at the start of the stack, and a second
4894 pass starting at the start of the stack + 2. Likewise, if the
4895 minimal alignment of Lisp_Objects on the stack is 1, four passes
4896 would be necessary, each one starting with one byte more offset
4897 from the stack start. */
4899 static void
4900 mark_stack (void *end)
4903 /* This assumes that the stack is a contiguous region in memory. If
4904 that's not the case, something has to be done here to iterate
4905 over the stack segments. */
4906 mark_memory (stack_base, end);
4908 /* Allow for marking a secondary stack, like the register stack on the
4909 ia64. */
4910 #ifdef GC_MARK_SECONDARY_STACK
4911 GC_MARK_SECONDARY_STACK ();
4912 #endif
4914 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4915 check_gcpros ();
4916 #endif
4919 #else /* GC_MARK_STACK == 0 */
4921 #define mark_maybe_object(obj) emacs_abort ()
4923 #endif /* GC_MARK_STACK != 0 */
4926 /* Determine whether it is safe to access memory at address P. */
4927 static int
4928 valid_pointer_p (void *p)
4930 #ifdef WINDOWSNT
4931 return w32_valid_pointer_p (p, 16);
4932 #else
4933 int fd[2];
4935 /* Obviously, we cannot just access it (we would SEGV trying), so we
4936 trick the o/s to tell us whether p is a valid pointer.
4937 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4938 not validate p in that case. */
4940 if (emacs_pipe (fd) == 0)
4942 bool valid = emacs_write (fd[1], p, 16) == 16;
4943 emacs_close (fd[1]);
4944 emacs_close (fd[0]);
4945 return valid;
4948 return -1;
4949 #endif
4952 /* Return 2 if OBJ is a killed or special buffer object, 1 if OBJ is a
4953 valid lisp object, 0 if OBJ is NOT a valid lisp object, or -1 if we
4954 cannot validate OBJ. This function can be quite slow, so its primary
4955 use is the manual debugging. The only exception is print_object, where
4956 we use it to check whether the memory referenced by the pointer of
4957 Lisp_Save_Value object contains valid objects. */
4960 valid_lisp_object_p (Lisp_Object obj)
4962 void *p;
4963 #if GC_MARK_STACK
4964 struct mem_node *m;
4965 #endif
4967 if (INTEGERP (obj))
4968 return 1;
4970 p = (void *) XPNTR (obj);
4971 if (PURE_POINTER_P (p))
4972 return 1;
4974 if (p == &buffer_defaults || p == &buffer_local_symbols)
4975 return 2;
4977 #if !GC_MARK_STACK
4978 return valid_pointer_p (p);
4979 #else
4981 m = mem_find (p);
4983 if (m == MEM_NIL)
4985 int valid = valid_pointer_p (p);
4986 if (valid <= 0)
4987 return valid;
4989 if (SUBRP (obj))
4990 return 1;
4992 return 0;
4995 switch (m->type)
4997 case MEM_TYPE_NON_LISP:
4998 case MEM_TYPE_SPARE:
4999 return 0;
5001 case MEM_TYPE_BUFFER:
5002 return live_buffer_p (m, p) ? 1 : 2;
5004 case MEM_TYPE_CONS:
5005 return live_cons_p (m, p);
5007 case MEM_TYPE_STRING:
5008 return live_string_p (m, p);
5010 case MEM_TYPE_MISC:
5011 return live_misc_p (m, p);
5013 case MEM_TYPE_SYMBOL:
5014 return live_symbol_p (m, p);
5016 case MEM_TYPE_FLOAT:
5017 return live_float_p (m, p);
5019 case MEM_TYPE_VECTORLIKE:
5020 case MEM_TYPE_VECTOR_BLOCK:
5021 return live_vector_p (m, p);
5023 default:
5024 break;
5027 return 0;
5028 #endif
5031 /* If GC_MARK_STACK, return 1 if STR is a relocatable data of Lisp_String
5032 (i.e. there is a non-pure Lisp_Object X so that SDATA (X) == STR) and 0
5033 if not. Otherwise we can't rely on valid_lisp_object_p and return -1.
5034 This function is slow and should be used for debugging purposes. */
5037 relocatable_string_data_p (const char *str)
5039 if (PURE_POINTER_P (str))
5040 return 0;
5041 #if GC_MARK_STACK
5042 if (str)
5044 struct sdata *sdata
5045 = (struct sdata *) (str - offsetof (struct sdata, data));
5047 if (valid_pointer_p (sdata)
5048 && valid_pointer_p (sdata->string)
5049 && maybe_lisp_pointer (sdata->string))
5050 return (valid_lisp_object_p
5051 (make_lisp_ptr (sdata->string, Lisp_String))
5052 && (const char *) sdata->string->data == str);
5054 return 0;
5055 #endif /* GC_MARK_STACK */
5056 return -1;
5059 /***********************************************************************
5060 Pure Storage Management
5061 ***********************************************************************/
5063 /* Allocate room for SIZE bytes from pure Lisp storage and return a
5064 pointer to it. TYPE is the Lisp type for which the memory is
5065 allocated. TYPE < 0 means it's not used for a Lisp object. */
5067 static void *
5068 pure_alloc (size_t size, int type)
5070 void *result;
5071 #if USE_LSB_TAG
5072 size_t alignment = GCALIGNMENT;
5073 #else
5074 size_t alignment = alignof (EMACS_INT);
5076 /* Give Lisp_Floats an extra alignment. */
5077 if (type == Lisp_Float)
5078 alignment = alignof (struct Lisp_Float);
5079 #endif
5081 again:
5082 if (type >= 0)
5084 /* Allocate space for a Lisp object from the beginning of the free
5085 space with taking account of alignment. */
5086 result = ALIGN (purebeg + pure_bytes_used_lisp, alignment);
5087 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
5089 else
5091 /* Allocate space for a non-Lisp object from the end of the free
5092 space. */
5093 pure_bytes_used_non_lisp += size;
5094 result = purebeg + pure_size - pure_bytes_used_non_lisp;
5096 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
5098 if (pure_bytes_used <= pure_size)
5099 return result;
5101 /* Don't allocate a large amount here,
5102 because it might get mmap'd and then its address
5103 might not be usable. */
5104 purebeg = xmalloc (10000);
5105 pure_size = 10000;
5106 pure_bytes_used_before_overflow += pure_bytes_used - size;
5107 pure_bytes_used = 0;
5108 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
5109 goto again;
5113 /* Print a warning if PURESIZE is too small. */
5115 void
5116 check_pure_size (void)
5118 if (pure_bytes_used_before_overflow)
5119 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI"d"
5120 " bytes needed)"),
5121 pure_bytes_used + pure_bytes_used_before_overflow);
5125 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
5126 the non-Lisp data pool of the pure storage, and return its start
5127 address. Return NULL if not found. */
5129 static char *
5130 find_string_data_in_pure (const char *data, ptrdiff_t nbytes)
5132 int i;
5133 ptrdiff_t skip, bm_skip[256], last_char_skip, infinity, start, start_max;
5134 const unsigned char *p;
5135 char *non_lisp_beg;
5137 if (pure_bytes_used_non_lisp <= nbytes)
5138 return NULL;
5140 /* Set up the Boyer-Moore table. */
5141 skip = nbytes + 1;
5142 for (i = 0; i < 256; i++)
5143 bm_skip[i] = skip;
5145 p = (const unsigned char *) data;
5146 while (--skip > 0)
5147 bm_skip[*p++] = skip;
5149 last_char_skip = bm_skip['\0'];
5151 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
5152 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
5154 /* See the comments in the function `boyer_moore' (search.c) for the
5155 use of `infinity'. */
5156 infinity = pure_bytes_used_non_lisp + 1;
5157 bm_skip['\0'] = infinity;
5159 p = (const unsigned char *) non_lisp_beg + nbytes;
5160 start = 0;
5163 /* Check the last character (== '\0'). */
5166 start += bm_skip[*(p + start)];
5168 while (start <= start_max);
5170 if (start < infinity)
5171 /* Couldn't find the last character. */
5172 return NULL;
5174 /* No less than `infinity' means we could find the last
5175 character at `p[start - infinity]'. */
5176 start -= infinity;
5178 /* Check the remaining characters. */
5179 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
5180 /* Found. */
5181 return non_lisp_beg + start;
5183 start += last_char_skip;
5185 while (start <= start_max);
5187 return NULL;
5191 /* Return a string allocated in pure space. DATA is a buffer holding
5192 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
5193 means make the result string multibyte.
5195 Must get an error if pure storage is full, since if it cannot hold
5196 a large string it may be able to hold conses that point to that
5197 string; then the string is not protected from gc. */
5199 Lisp_Object
5200 make_pure_string (const char *data,
5201 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
5203 Lisp_Object string;
5204 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5205 s->data = (unsigned char *) find_string_data_in_pure (data, nbytes);
5206 if (s->data == NULL)
5208 s->data = pure_alloc (nbytes + 1, -1);
5209 memcpy (s->data, data, nbytes);
5210 s->data[nbytes] = '\0';
5212 s->size = nchars;
5213 s->size_byte = multibyte ? nbytes : -1;
5214 s->intervals = NULL;
5215 XSETSTRING (string, s);
5216 return string;
5219 /* Return a string allocated in pure space. Do not
5220 allocate the string data, just point to DATA. */
5222 Lisp_Object
5223 make_pure_c_string (const char *data, ptrdiff_t nchars)
5225 Lisp_Object string;
5226 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5227 s->size = nchars;
5228 s->size_byte = -1;
5229 s->data = (unsigned char *) data;
5230 s->intervals = NULL;
5231 XSETSTRING (string, s);
5232 return string;
5235 static Lisp_Object purecopy (Lisp_Object obj);
5237 /* Return a cons allocated from pure space. Give it pure copies
5238 of CAR as car and CDR as cdr. */
5240 Lisp_Object
5241 pure_cons (Lisp_Object car, Lisp_Object cdr)
5243 Lisp_Object new;
5244 struct Lisp_Cons *p = pure_alloc (sizeof *p, Lisp_Cons);
5245 XSETCONS (new, p);
5246 XSETCAR (new, purecopy (car));
5247 XSETCDR (new, purecopy (cdr));
5248 return new;
5252 /* Value is a float object with value NUM allocated from pure space. */
5254 static Lisp_Object
5255 make_pure_float (double num)
5257 Lisp_Object new;
5258 struct Lisp_Float *p = pure_alloc (sizeof *p, Lisp_Float);
5259 XSETFLOAT (new, p);
5260 XFLOAT_INIT (new, num);
5261 return new;
5265 /* Return a vector with room for LEN Lisp_Objects allocated from
5266 pure space. */
5268 static Lisp_Object
5269 make_pure_vector (ptrdiff_t len)
5271 Lisp_Object new;
5272 size_t size = header_size + len * word_size;
5273 struct Lisp_Vector *p = pure_alloc (size, Lisp_Vectorlike);
5274 XSETVECTOR (new, p);
5275 XVECTOR (new)->header.size = len;
5276 return new;
5280 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
5281 doc: /* Make a copy of object OBJ in pure storage.
5282 Recursively copies contents of vectors and cons cells.
5283 Does not copy symbols. Copies strings without text properties. */)
5284 (register Lisp_Object obj)
5286 if (NILP (Vpurify_flag))
5287 return obj;
5288 else if (MARKERP (obj) || OVERLAYP (obj)
5289 || HASH_TABLE_P (obj) || SYMBOLP (obj))
5290 /* Can't purify those. */
5291 return obj;
5292 else
5293 return purecopy (obj);
5296 static Lisp_Object
5297 purecopy (Lisp_Object obj)
5299 if (PURE_POINTER_P (XPNTR (obj)) || INTEGERP (obj) || SUBRP (obj))
5300 return obj; /* Already pure. */
5302 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5304 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
5305 if (!NILP (tmp))
5306 return tmp;
5309 if (CONSP (obj))
5310 obj = pure_cons (XCAR (obj), XCDR (obj));
5311 else if (FLOATP (obj))
5312 obj = make_pure_float (XFLOAT_DATA (obj));
5313 else if (STRINGP (obj))
5314 obj = make_pure_string (SSDATA (obj), SCHARS (obj),
5315 SBYTES (obj),
5316 STRING_MULTIBYTE (obj));
5317 else if (COMPILEDP (obj) || VECTORP (obj))
5319 register struct Lisp_Vector *vec;
5320 register ptrdiff_t i;
5321 ptrdiff_t size;
5323 size = ASIZE (obj);
5324 if (size & PSEUDOVECTOR_FLAG)
5325 size &= PSEUDOVECTOR_SIZE_MASK;
5326 vec = XVECTOR (make_pure_vector (size));
5327 for (i = 0; i < size; i++)
5328 vec->contents[i] = purecopy (AREF (obj, i));
5329 if (COMPILEDP (obj))
5331 XSETPVECTYPE (vec, PVEC_COMPILED);
5332 XSETCOMPILED (obj, vec);
5334 else
5335 XSETVECTOR (obj, vec);
5337 else if (SYMBOLP (obj))
5339 if (!XSYMBOL (obj)->pinned)
5340 { /* We can't purify them, but they appear in many pure objects.
5341 Mark them as `pinned' so we know to mark them at every GC cycle. */
5342 XSYMBOL (obj)->pinned = true;
5343 symbol_block_pinned = symbol_block;
5345 return obj;
5347 else
5349 Lisp_Object args[2];
5350 args[0] = build_pure_c_string ("Don't know how to purify: %S");
5351 args[1] = obj;
5352 Fsignal (Qerror, (Fcons (Fformat (2, args), Qnil)));
5355 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5356 Fputhash (obj, obj, Vpurify_flag);
5358 return obj;
5363 /***********************************************************************
5364 Protection from GC
5365 ***********************************************************************/
5367 /* Put an entry in staticvec, pointing at the variable with address
5368 VARADDRESS. */
5370 void
5371 staticpro (Lisp_Object *varaddress)
5373 if (staticidx >= NSTATICS)
5374 fatal ("NSTATICS too small; try increasing and recompiling Emacs.");
5375 staticvec[staticidx++] = varaddress;
5379 /***********************************************************************
5380 Protection from GC
5381 ***********************************************************************/
5383 /* Temporarily prevent garbage collection. */
5385 ptrdiff_t
5386 inhibit_garbage_collection (void)
5388 ptrdiff_t count = SPECPDL_INDEX ();
5390 specbind (Qgc_cons_threshold, make_number (MOST_POSITIVE_FIXNUM));
5391 return count;
5394 /* Used to avoid possible overflows when
5395 converting from C to Lisp integers. */
5397 static Lisp_Object
5398 bounded_number (EMACS_INT number)
5400 return make_number (min (MOST_POSITIVE_FIXNUM, number));
5403 /* Calculate total bytes of live objects. */
5405 static size_t
5406 total_bytes_of_live_objects (void)
5408 size_t tot = 0;
5409 tot += total_conses * sizeof (struct Lisp_Cons);
5410 tot += total_symbols * sizeof (struct Lisp_Symbol);
5411 tot += total_markers * sizeof (union Lisp_Misc);
5412 tot += total_string_bytes;
5413 tot += total_vector_slots * word_size;
5414 tot += total_floats * sizeof (struct Lisp_Float);
5415 tot += total_intervals * sizeof (struct interval);
5416 tot += total_strings * sizeof (struct Lisp_String);
5417 return tot;
5420 #ifdef HAVE_WINDOW_SYSTEM
5422 /* This code has a few issues on MS-Windows, see Bug#15876 and Bug#16140. */
5424 #if !defined (HAVE_NTGUI)
5426 /* Remove unmarked font-spec and font-entity objects from ENTRY, which is
5427 (DRIVER-TYPE NUM-FRAMES FONT-CACHE-DATA ...), and return changed entry. */
5429 static Lisp_Object
5430 compact_font_cache_entry (Lisp_Object entry)
5432 Lisp_Object tail, *prev = &entry;
5434 for (tail = entry; CONSP (tail); tail = XCDR (tail))
5436 bool drop = 0;
5437 Lisp_Object obj = XCAR (tail);
5439 /* Consider OBJ if it is (font-spec . [font-entity font-entity ...]). */
5440 if (CONSP (obj) && FONT_SPEC_P (XCAR (obj))
5441 && !VECTOR_MARKED_P (XFONT_SPEC (XCAR (obj)))
5442 && VECTORP (XCDR (obj)))
5444 ptrdiff_t i, size = ASIZE (XCDR (obj)) & ~ARRAY_MARK_FLAG;
5446 /* If font-spec is not marked, most likely all font-entities
5447 are not marked too. But we must be sure that nothing is
5448 marked within OBJ before we really drop it. */
5449 for (i = 0; i < size; i++)
5450 if (VECTOR_MARKED_P (XFONT_ENTITY (AREF (XCDR (obj), i))))
5451 break;
5453 if (i == size)
5454 drop = 1;
5456 if (drop)
5457 *prev = XCDR (tail);
5458 else
5459 prev = xcdr_addr (tail);
5461 return entry;
5464 #endif /* not HAVE_NTGUI */
5466 /* Compact font caches on all terminals and mark
5467 everything which is still here after compaction. */
5469 static void
5470 compact_font_caches (void)
5472 struct terminal *t;
5474 for (t = terminal_list; t; t = t->next_terminal)
5476 Lisp_Object cache = TERMINAL_FONT_CACHE (t);
5477 #if !defined (HAVE_NTGUI)
5478 if (CONSP (cache))
5480 Lisp_Object entry;
5482 for (entry = XCDR (cache); CONSP (entry); entry = XCDR (entry))
5483 XSETCAR (entry, compact_font_cache_entry (XCAR (entry)));
5485 #endif /* not HAVE_NTGUI */
5486 mark_object (cache);
5490 #else /* not HAVE_WINDOW_SYSTEM */
5492 #define compact_font_caches() (void)(0)
5494 #endif /* HAVE_WINDOW_SYSTEM */
5496 /* Remove (MARKER . DATA) entries with unmarked MARKER
5497 from buffer undo LIST and return changed list. */
5499 static Lisp_Object
5500 compact_undo_list (Lisp_Object list)
5502 Lisp_Object tail, *prev = &list;
5504 for (tail = list; CONSP (tail); tail = XCDR (tail))
5506 if (CONSP (XCAR (tail))
5507 && MARKERP (XCAR (XCAR (tail)))
5508 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5509 *prev = XCDR (tail);
5510 else
5511 prev = xcdr_addr (tail);
5513 return list;
5516 static void
5517 mark_pinned_symbols (void)
5519 struct symbol_block *sblk;
5520 int lim = (symbol_block_pinned == symbol_block
5521 ? symbol_block_index : SYMBOL_BLOCK_SIZE);
5523 for (sblk = symbol_block_pinned; sblk; sblk = sblk->next)
5525 union aligned_Lisp_Symbol *sym = sblk->symbols, *end = sym + lim;
5526 for (; sym < end; ++sym)
5527 if (sym->s.pinned)
5528 mark_object (make_lisp_ptr (&sym->s, Lisp_Symbol));
5530 lim = SYMBOL_BLOCK_SIZE;
5534 /* Subroutine of Fgarbage_collect that does most of the work. It is a
5535 separate function so that we could limit mark_stack in searching
5536 the stack frames below this function, thus avoiding the rare cases
5537 where mark_stack finds values that look like live Lisp objects on
5538 portions of stack that couldn't possibly contain such live objects.
5539 For more details of this, see the discussion at
5540 http://lists.gnu.org/archive/html/emacs-devel/2014-05/msg00270.html. */
5541 static Lisp_Object
5542 garbage_collect_1 (void *end)
5544 struct buffer *nextb;
5545 char stack_top_variable;
5546 ptrdiff_t i;
5547 bool message_p;
5548 ptrdiff_t count = SPECPDL_INDEX ();
5549 struct timespec start;
5550 Lisp_Object retval = Qnil;
5551 size_t tot_before = 0;
5553 if (abort_on_gc)
5554 emacs_abort ();
5556 /* Can't GC if pure storage overflowed because we can't determine
5557 if something is a pure object or not. */
5558 if (pure_bytes_used_before_overflow)
5559 return Qnil;
5561 /* Record this function, so it appears on the profiler's backtraces. */
5562 record_in_backtrace (Qautomatic_gc, &Qnil, 0);
5564 check_cons_list ();
5566 /* Don't keep undo information around forever.
5567 Do this early on, so it is no problem if the user quits. */
5568 FOR_EACH_BUFFER (nextb)
5569 compact_buffer (nextb);
5571 if (profiler_memory_running)
5572 tot_before = total_bytes_of_live_objects ();
5574 start = current_timespec ();
5576 /* In case user calls debug_print during GC,
5577 don't let that cause a recursive GC. */
5578 consing_since_gc = 0;
5580 /* Save what's currently displayed in the echo area. */
5581 message_p = push_message ();
5582 record_unwind_protect_void (pop_message_unwind);
5584 /* Save a copy of the contents of the stack, for debugging. */
5585 #if MAX_SAVE_STACK > 0
5586 if (NILP (Vpurify_flag))
5588 char *stack;
5589 ptrdiff_t stack_size;
5590 if (&stack_top_variable < stack_bottom)
5592 stack = &stack_top_variable;
5593 stack_size = stack_bottom - &stack_top_variable;
5595 else
5597 stack = stack_bottom;
5598 stack_size = &stack_top_variable - stack_bottom;
5600 if (stack_size <= MAX_SAVE_STACK)
5602 if (stack_copy_size < stack_size)
5604 stack_copy = xrealloc (stack_copy, stack_size);
5605 stack_copy_size = stack_size;
5607 no_sanitize_memcpy (stack_copy, stack, stack_size);
5610 #endif /* MAX_SAVE_STACK > 0 */
5612 if (garbage_collection_messages)
5613 message1_nolog ("Garbage collecting...");
5615 block_input ();
5617 shrink_regexp_cache ();
5619 gc_in_progress = 1;
5621 /* Mark all the special slots that serve as the roots of accessibility. */
5623 mark_buffer (&buffer_defaults);
5624 mark_buffer (&buffer_local_symbols);
5626 for (i = 0; i < staticidx; i++)
5627 mark_object (*staticvec[i]);
5629 mark_pinned_symbols ();
5630 mark_specpdl ();
5631 mark_terminals ();
5632 mark_kboards ();
5634 #ifdef USE_GTK
5635 xg_mark_data ();
5636 #endif
5638 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
5639 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
5640 mark_stack (end);
5641 #else
5643 register struct gcpro *tail;
5644 for (tail = gcprolist; tail; tail = tail->next)
5645 for (i = 0; i < tail->nvars; i++)
5646 mark_object (tail->var[i]);
5648 mark_byte_stack ();
5649 #endif
5651 struct handler *handler;
5652 for (handler = handlerlist; handler; handler = handler->next)
5654 mark_object (handler->tag_or_ch);
5655 mark_object (handler->val);
5658 #ifdef HAVE_WINDOW_SYSTEM
5659 mark_fringe_data ();
5660 #endif
5662 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5663 mark_stack (end);
5664 #endif
5666 /* Everything is now marked, except for the data in font caches
5667 and undo lists. They're compacted by removing an items which
5668 aren't reachable otherwise. */
5670 compact_font_caches ();
5672 FOR_EACH_BUFFER (nextb)
5674 if (!EQ (BVAR (nextb, undo_list), Qt))
5675 bset_undo_list (nextb, compact_undo_list (BVAR (nextb, undo_list)));
5676 /* Now that we have stripped the elements that need not be
5677 in the undo_list any more, we can finally mark the list. */
5678 mark_object (BVAR (nextb, undo_list));
5681 gc_sweep ();
5683 /* Clear the mark bits that we set in certain root slots. */
5685 unmark_byte_stack ();
5686 VECTOR_UNMARK (&buffer_defaults);
5687 VECTOR_UNMARK (&buffer_local_symbols);
5689 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
5690 dump_zombies ();
5691 #endif
5693 check_cons_list ();
5695 gc_in_progress = 0;
5697 unblock_input ();
5699 consing_since_gc = 0;
5700 if (gc_cons_threshold < GC_DEFAULT_THRESHOLD / 10)
5701 gc_cons_threshold = GC_DEFAULT_THRESHOLD / 10;
5703 gc_relative_threshold = 0;
5704 if (FLOATP (Vgc_cons_percentage))
5705 { /* Set gc_cons_combined_threshold. */
5706 double tot = total_bytes_of_live_objects ();
5708 tot *= XFLOAT_DATA (Vgc_cons_percentage);
5709 if (0 < tot)
5711 if (tot < TYPE_MAXIMUM (EMACS_INT))
5712 gc_relative_threshold = tot;
5713 else
5714 gc_relative_threshold = TYPE_MAXIMUM (EMACS_INT);
5718 if (garbage_collection_messages)
5720 if (message_p || minibuf_level > 0)
5721 restore_message ();
5722 else
5723 message1_nolog ("Garbage collecting...done");
5726 unbind_to (count, Qnil);
5728 Lisp_Object total[11];
5729 int total_size = 10;
5731 total[0] = list4 (Qconses, make_number (sizeof (struct Lisp_Cons)),
5732 bounded_number (total_conses),
5733 bounded_number (total_free_conses));
5735 total[1] = list4 (Qsymbols, make_number (sizeof (struct Lisp_Symbol)),
5736 bounded_number (total_symbols),
5737 bounded_number (total_free_symbols));
5739 total[2] = list4 (Qmiscs, make_number (sizeof (union Lisp_Misc)),
5740 bounded_number (total_markers),
5741 bounded_number (total_free_markers));
5743 total[3] = list4 (Qstrings, make_number (sizeof (struct Lisp_String)),
5744 bounded_number (total_strings),
5745 bounded_number (total_free_strings));
5747 total[4] = list3 (Qstring_bytes, make_number (1),
5748 bounded_number (total_string_bytes));
5750 total[5] = list3 (Qvectors,
5751 make_number (header_size + sizeof (Lisp_Object)),
5752 bounded_number (total_vectors));
5754 total[6] = list4 (Qvector_slots, make_number (word_size),
5755 bounded_number (total_vector_slots),
5756 bounded_number (total_free_vector_slots));
5758 total[7] = list4 (Qfloats, make_number (sizeof (struct Lisp_Float)),
5759 bounded_number (total_floats),
5760 bounded_number (total_free_floats));
5762 total[8] = list4 (Qintervals, make_number (sizeof (struct interval)),
5763 bounded_number (total_intervals),
5764 bounded_number (total_free_intervals));
5766 total[9] = list3 (Qbuffers, make_number (sizeof (struct buffer)),
5767 bounded_number (total_buffers));
5769 #ifdef DOUG_LEA_MALLOC
5770 total_size++;
5771 total[10] = list4 (Qheap, make_number (1024),
5772 bounded_number ((mallinfo ().uordblks + 1023) >> 10),
5773 bounded_number ((mallinfo ().fordblks + 1023) >> 10));
5774 #endif
5775 retval = Flist (total_size, total);
5778 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5780 /* Compute average percentage of zombies. */
5781 double nlive
5782 = (total_conses + total_symbols + total_markers + total_strings
5783 + total_vectors + total_floats + total_intervals + total_buffers);
5785 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
5786 max_live = max (nlive, max_live);
5787 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
5788 max_zombies = max (nzombies, max_zombies);
5789 ++ngcs;
5791 #endif
5793 if (!NILP (Vpost_gc_hook))
5795 ptrdiff_t gc_count = inhibit_garbage_collection ();
5796 safe_run_hooks (Qpost_gc_hook);
5797 unbind_to (gc_count, Qnil);
5800 /* Accumulate statistics. */
5801 if (FLOATP (Vgc_elapsed))
5803 struct timespec since_start = timespec_sub (current_timespec (), start);
5804 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed)
5805 + timespectod (since_start));
5808 gcs_done++;
5810 /* Collect profiling data. */
5811 if (profiler_memory_running)
5813 size_t swept = 0;
5814 size_t tot_after = total_bytes_of_live_objects ();
5815 if (tot_before > tot_after)
5816 swept = tot_before - tot_after;
5817 malloc_probe (swept);
5820 return retval;
5823 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
5824 doc: /* Reclaim storage for Lisp objects no longer needed.
5825 Garbage collection happens automatically if you cons more than
5826 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5827 `garbage-collect' normally returns a list with info on amount of space in use,
5828 where each entry has the form (NAME SIZE USED FREE), where:
5829 - NAME is a symbol describing the kind of objects this entry represents,
5830 - SIZE is the number of bytes used by each one,
5831 - USED is the number of those objects that were found live in the heap,
5832 - FREE is the number of those objects that are not live but that Emacs
5833 keeps around for future allocations (maybe because it does not know how
5834 to return them to the OS).
5835 However, if there was overflow in pure space, `garbage-collect'
5836 returns nil, because real GC can't be done.
5837 See Info node `(elisp)Garbage Collection'. */)
5838 (void)
5840 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
5841 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS \
5842 || GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES)
5843 void *end;
5845 #ifdef HAVE___BUILTIN_UNWIND_INIT
5846 /* Force callee-saved registers and register windows onto the stack.
5847 This is the preferred method if available, obviating the need for
5848 machine dependent methods. */
5849 __builtin_unwind_init ();
5850 end = &end;
5851 #else /* not HAVE___BUILTIN_UNWIND_INIT */
5852 #ifndef GC_SAVE_REGISTERS_ON_STACK
5853 /* jmp_buf may not be aligned enough on darwin-ppc64 */
5854 union aligned_jmpbuf {
5855 Lisp_Object o;
5856 sys_jmp_buf j;
5857 } j;
5858 volatile bool stack_grows_down_p = (char *) &j > (char *) stack_base;
5859 #endif
5860 /* This trick flushes the register windows so that all the state of
5861 the process is contained in the stack. */
5862 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
5863 needed on ia64 too. See mach_dep.c, where it also says inline
5864 assembler doesn't work with relevant proprietary compilers. */
5865 #ifdef __sparc__
5866 #if defined (__sparc64__) && defined (__FreeBSD__)
5867 /* FreeBSD does not have a ta 3 handler. */
5868 asm ("flushw");
5869 #else
5870 asm ("ta 3");
5871 #endif
5872 #endif
5874 /* Save registers that we need to see on the stack. We need to see
5875 registers used to hold register variables and registers used to
5876 pass parameters. */
5877 #ifdef GC_SAVE_REGISTERS_ON_STACK
5878 GC_SAVE_REGISTERS_ON_STACK (end);
5879 #else /* not GC_SAVE_REGISTERS_ON_STACK */
5881 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
5882 setjmp will definitely work, test it
5883 and print a message with the result
5884 of the test. */
5885 if (!setjmp_tested_p)
5887 setjmp_tested_p = 1;
5888 test_setjmp ();
5890 #endif /* GC_SETJMP_WORKS */
5892 sys_setjmp (j.j);
5893 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
5894 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
5895 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
5896 return garbage_collect_1 (end);
5897 #elif (GC_MARK_STACK == GC_USE_GCPROS_AS_BEFORE)
5898 /* Old GCPROs-based method without stack marking. */
5899 return garbage_collect_1 (NULL);
5900 #else
5901 emacs_abort ();
5902 #endif /* GC_MARK_STACK */
5905 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5906 only interesting objects referenced from glyphs are strings. */
5908 static void
5909 mark_glyph_matrix (struct glyph_matrix *matrix)
5911 struct glyph_row *row = matrix->rows;
5912 struct glyph_row *end = row + matrix->nrows;
5914 for (; row < end; ++row)
5915 if (row->enabled_p)
5917 int area;
5918 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
5920 struct glyph *glyph = row->glyphs[area];
5921 struct glyph *end_glyph = glyph + row->used[area];
5923 for (; glyph < end_glyph; ++glyph)
5924 if (STRINGP (glyph->object)
5925 && !STRING_MARKED_P (XSTRING (glyph->object)))
5926 mark_object (glyph->object);
5931 /* Mark reference to a Lisp_Object.
5932 If the object referred to has not been seen yet, recursively mark
5933 all the references contained in it. */
5935 #define LAST_MARKED_SIZE 500
5936 static Lisp_Object last_marked[LAST_MARKED_SIZE];
5937 static int last_marked_index;
5939 /* For debugging--call abort when we cdr down this many
5940 links of a list, in mark_object. In debugging,
5941 the call to abort will hit a breakpoint.
5942 Normally this is zero and the check never goes off. */
5943 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE;
5945 static void
5946 mark_vectorlike (struct Lisp_Vector *ptr)
5948 ptrdiff_t size = ptr->header.size;
5949 ptrdiff_t i;
5951 eassert (!VECTOR_MARKED_P (ptr));
5952 VECTOR_MARK (ptr); /* Else mark it. */
5953 if (size & PSEUDOVECTOR_FLAG)
5954 size &= PSEUDOVECTOR_SIZE_MASK;
5956 /* Note that this size is not the memory-footprint size, but only
5957 the number of Lisp_Object fields that we should trace.
5958 The distinction is used e.g. by Lisp_Process which places extra
5959 non-Lisp_Object fields at the end of the structure... */
5960 for (i = 0; i < size; i++) /* ...and then mark its elements. */
5961 mark_object (ptr->contents[i]);
5964 /* Like mark_vectorlike but optimized for char-tables (and
5965 sub-char-tables) assuming that the contents are mostly integers or
5966 symbols. */
5968 static void
5969 mark_char_table (struct Lisp_Vector *ptr, enum pvec_type pvectype)
5971 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5972 /* Consult the Lisp_Sub_Char_Table layout before changing this. */
5973 int i, idx = (pvectype == PVEC_SUB_CHAR_TABLE ? SUB_CHAR_TABLE_OFFSET : 0);
5975 eassert (!VECTOR_MARKED_P (ptr));
5976 VECTOR_MARK (ptr);
5977 for (i = idx; i < size; i++)
5979 Lisp_Object val = ptr->contents[i];
5981 if (INTEGERP (val) || (SYMBOLP (val) && XSYMBOL (val)->gcmarkbit))
5982 continue;
5983 if (SUB_CHAR_TABLE_P (val))
5985 if (! VECTOR_MARKED_P (XVECTOR (val)))
5986 mark_char_table (XVECTOR (val), PVEC_SUB_CHAR_TABLE);
5988 else
5989 mark_object (val);
5993 NO_INLINE /* To reduce stack depth in mark_object. */
5994 static Lisp_Object
5995 mark_compiled (struct Lisp_Vector *ptr)
5997 int i, size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5999 VECTOR_MARK (ptr);
6000 for (i = 0; i < size; i++)
6001 if (i != COMPILED_CONSTANTS)
6002 mark_object (ptr->contents[i]);
6003 return size > COMPILED_CONSTANTS ? ptr->contents[COMPILED_CONSTANTS] : Qnil;
6006 /* Mark the chain of overlays starting at PTR. */
6008 static void
6009 mark_overlay (struct Lisp_Overlay *ptr)
6011 for (; ptr && !ptr->gcmarkbit; ptr = ptr->next)
6013 ptr->gcmarkbit = 1;
6014 mark_object (ptr->start);
6015 mark_object (ptr->end);
6016 mark_object (ptr->plist);
6020 /* Mark Lisp_Objects and special pointers in BUFFER. */
6022 static void
6023 mark_buffer (struct buffer *buffer)
6025 /* This is handled much like other pseudovectors... */
6026 mark_vectorlike ((struct Lisp_Vector *) buffer);
6028 /* ...but there are some buffer-specific things. */
6030 MARK_INTERVAL_TREE (buffer_intervals (buffer));
6032 /* For now, we just don't mark the undo_list. It's done later in
6033 a special way just before the sweep phase, and after stripping
6034 some of its elements that are not needed any more. */
6036 mark_overlay (buffer->overlays_before);
6037 mark_overlay (buffer->overlays_after);
6039 /* If this is an indirect buffer, mark its base buffer. */
6040 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
6041 mark_buffer (buffer->base_buffer);
6044 /* Mark Lisp faces in the face cache C. */
6046 NO_INLINE /* To reduce stack depth in mark_object. */
6047 static void
6048 mark_face_cache (struct face_cache *c)
6050 if (c)
6052 int i, j;
6053 for (i = 0; i < c->used; ++i)
6055 struct face *face = FACE_FROM_ID (c->f, i);
6057 if (face)
6059 if (face->font && !VECTOR_MARKED_P (face->font))
6060 mark_vectorlike ((struct Lisp_Vector *) face->font);
6062 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
6063 mark_object (face->lface[j]);
6069 NO_INLINE /* To reduce stack depth in mark_object. */
6070 static void
6071 mark_localized_symbol (struct Lisp_Symbol *ptr)
6073 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
6074 Lisp_Object where = blv->where;
6075 /* If the value is set up for a killed buffer or deleted
6076 frame, restore its global binding. If the value is
6077 forwarded to a C variable, either it's not a Lisp_Object
6078 var, or it's staticpro'd already. */
6079 if ((BUFFERP (where) && !BUFFER_LIVE_P (XBUFFER (where)))
6080 || (FRAMEP (where) && !FRAME_LIVE_P (XFRAME (where))))
6081 swap_in_global_binding (ptr);
6082 mark_object (blv->where);
6083 mark_object (blv->valcell);
6084 mark_object (blv->defcell);
6087 NO_INLINE /* To reduce stack depth in mark_object. */
6088 static void
6089 mark_save_value (struct Lisp_Save_Value *ptr)
6091 /* If `save_type' is zero, `data[0].pointer' is the address
6092 of a memory area containing `data[1].integer' potential
6093 Lisp_Objects. */
6094 if (GC_MARK_STACK && ptr->save_type == SAVE_TYPE_MEMORY)
6096 Lisp_Object *p = ptr->data[0].pointer;
6097 ptrdiff_t nelt;
6098 for (nelt = ptr->data[1].integer; nelt > 0; nelt--, p++)
6099 mark_maybe_object (*p);
6101 else
6103 /* Find Lisp_Objects in `data[N]' slots and mark them. */
6104 int i;
6105 for (i = 0; i < SAVE_VALUE_SLOTS; i++)
6106 if (save_type (ptr, i) == SAVE_OBJECT)
6107 mark_object (ptr->data[i].object);
6111 /* Remove killed buffers or items whose car is a killed buffer from
6112 LIST, and mark other items. Return changed LIST, which is marked. */
6114 static Lisp_Object
6115 mark_discard_killed_buffers (Lisp_Object list)
6117 Lisp_Object tail, *prev = &list;
6119 for (tail = list; CONSP (tail) && !CONS_MARKED_P (XCONS (tail));
6120 tail = XCDR (tail))
6122 Lisp_Object tem = XCAR (tail);
6123 if (CONSP (tem))
6124 tem = XCAR (tem);
6125 if (BUFFERP (tem) && !BUFFER_LIVE_P (XBUFFER (tem)))
6126 *prev = XCDR (tail);
6127 else
6129 CONS_MARK (XCONS (tail));
6130 mark_object (XCAR (tail));
6131 prev = xcdr_addr (tail);
6134 mark_object (tail);
6135 return list;
6138 /* Determine type of generic Lisp_Object and mark it accordingly.
6140 This function implements a straightforward depth-first marking
6141 algorithm and so the recursion depth may be very high (a few
6142 tens of thousands is not uncommon). To minimize stack usage,
6143 a few cold paths are moved out to NO_INLINE functions above.
6144 In general, inlining them doesn't help you to gain more speed. */
6146 void
6147 mark_object (Lisp_Object arg)
6149 register Lisp_Object obj = arg;
6150 #ifdef GC_CHECK_MARKED_OBJECTS
6151 void *po;
6152 struct mem_node *m;
6153 #endif
6154 ptrdiff_t cdr_count = 0;
6156 loop:
6158 if (PURE_POINTER_P (XPNTR (obj)))
6159 return;
6161 last_marked[last_marked_index++] = obj;
6162 if (last_marked_index == LAST_MARKED_SIZE)
6163 last_marked_index = 0;
6165 /* Perform some sanity checks on the objects marked here. Abort if
6166 we encounter an object we know is bogus. This increases GC time
6167 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
6168 #ifdef GC_CHECK_MARKED_OBJECTS
6170 po = (void *) XPNTR (obj);
6172 /* Check that the object pointed to by PO is known to be a Lisp
6173 structure allocated from the heap. */
6174 #define CHECK_ALLOCATED() \
6175 do { \
6176 m = mem_find (po); \
6177 if (m == MEM_NIL) \
6178 emacs_abort (); \
6179 } while (0)
6181 /* Check that the object pointed to by PO is live, using predicate
6182 function LIVEP. */
6183 #define CHECK_LIVE(LIVEP) \
6184 do { \
6185 if (!LIVEP (m, po)) \
6186 emacs_abort (); \
6187 } while (0)
6189 /* Check both of the above conditions. */
6190 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
6191 do { \
6192 CHECK_ALLOCATED (); \
6193 CHECK_LIVE (LIVEP); \
6194 } while (0) \
6196 #else /* not GC_CHECK_MARKED_OBJECTS */
6198 #define CHECK_LIVE(LIVEP) (void) 0
6199 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
6201 #endif /* not GC_CHECK_MARKED_OBJECTS */
6203 switch (XTYPE (obj))
6205 case Lisp_String:
6207 register struct Lisp_String *ptr = XSTRING (obj);
6208 if (STRING_MARKED_P (ptr))
6209 break;
6210 CHECK_ALLOCATED_AND_LIVE (live_string_p);
6211 MARK_STRING (ptr);
6212 MARK_INTERVAL_TREE (ptr->intervals);
6213 #ifdef GC_CHECK_STRING_BYTES
6214 /* Check that the string size recorded in the string is the
6215 same as the one recorded in the sdata structure. */
6216 string_bytes (ptr);
6217 #endif /* GC_CHECK_STRING_BYTES */
6219 break;
6221 case Lisp_Vectorlike:
6223 register struct Lisp_Vector *ptr = XVECTOR (obj);
6224 register ptrdiff_t pvectype;
6226 if (VECTOR_MARKED_P (ptr))
6227 break;
6229 #ifdef GC_CHECK_MARKED_OBJECTS
6230 m = mem_find (po);
6231 if (m == MEM_NIL && !SUBRP (obj))
6232 emacs_abort ();
6233 #endif /* GC_CHECK_MARKED_OBJECTS */
6235 if (ptr->header.size & PSEUDOVECTOR_FLAG)
6236 pvectype = ((ptr->header.size & PVEC_TYPE_MASK)
6237 >> PSEUDOVECTOR_AREA_BITS);
6238 else
6239 pvectype = PVEC_NORMAL_VECTOR;
6241 if (pvectype != PVEC_SUBR && pvectype != PVEC_BUFFER)
6242 CHECK_LIVE (live_vector_p);
6244 switch (pvectype)
6246 case PVEC_BUFFER:
6247 #ifdef GC_CHECK_MARKED_OBJECTS
6249 struct buffer *b;
6250 FOR_EACH_BUFFER (b)
6251 if (b == po)
6252 break;
6253 if (b == NULL)
6254 emacs_abort ();
6256 #endif /* GC_CHECK_MARKED_OBJECTS */
6257 mark_buffer ((struct buffer *) ptr);
6258 break;
6260 case PVEC_COMPILED:
6261 /* Although we could treat this just like a vector, mark_compiled
6262 returns the COMPILED_CONSTANTS element, which is marked at the
6263 next iteration of goto-loop here. This is done to avoid a few
6264 recursive calls to mark_object. */
6265 obj = mark_compiled (ptr);
6266 if (!NILP (obj))
6267 goto loop;
6268 break;
6270 case PVEC_FRAME:
6272 struct frame *f = (struct frame *) ptr;
6274 mark_vectorlike (ptr);
6275 mark_face_cache (f->face_cache);
6276 #ifdef HAVE_WINDOW_SYSTEM
6277 if (FRAME_WINDOW_P (f) && FRAME_X_OUTPUT (f))
6279 struct font *font = FRAME_FONT (f);
6281 if (font && !VECTOR_MARKED_P (font))
6282 mark_vectorlike ((struct Lisp_Vector *) font);
6284 #endif
6286 break;
6288 case PVEC_WINDOW:
6290 struct window *w = (struct window *) ptr;
6292 mark_vectorlike (ptr);
6294 /* Mark glyph matrices, if any. Marking window
6295 matrices is sufficient because frame matrices
6296 use the same glyph memory. */
6297 if (w->current_matrix)
6299 mark_glyph_matrix (w->current_matrix);
6300 mark_glyph_matrix (w->desired_matrix);
6303 /* Filter out killed buffers from both buffer lists
6304 in attempt to help GC to reclaim killed buffers faster.
6305 We can do it elsewhere for live windows, but this is the
6306 best place to do it for dead windows. */
6307 wset_prev_buffers
6308 (w, mark_discard_killed_buffers (w->prev_buffers));
6309 wset_next_buffers
6310 (w, mark_discard_killed_buffers (w->next_buffers));
6312 break;
6314 case PVEC_HASH_TABLE:
6316 struct Lisp_Hash_Table *h = (struct Lisp_Hash_Table *) ptr;
6318 mark_vectorlike (ptr);
6319 mark_object (h->test.name);
6320 mark_object (h->test.user_hash_function);
6321 mark_object (h->test.user_cmp_function);
6322 /* If hash table is not weak, mark all keys and values.
6323 For weak tables, mark only the vector. */
6324 if (NILP (h->weak))
6325 mark_object (h->key_and_value);
6326 else
6327 VECTOR_MARK (XVECTOR (h->key_and_value));
6329 break;
6331 case PVEC_CHAR_TABLE:
6332 case PVEC_SUB_CHAR_TABLE:
6333 mark_char_table (ptr, (enum pvec_type) pvectype);
6334 break;
6336 case PVEC_BOOL_VECTOR:
6337 /* No Lisp_Objects to mark in a bool vector. */
6338 VECTOR_MARK (ptr);
6339 break;
6341 case PVEC_SUBR:
6342 break;
6344 case PVEC_FREE:
6345 emacs_abort ();
6347 default:
6348 mark_vectorlike (ptr);
6351 break;
6353 case Lisp_Symbol:
6355 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
6356 nextsym:
6357 if (ptr->gcmarkbit)
6358 break;
6359 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
6360 ptr->gcmarkbit = 1;
6361 /* Attempt to catch bogus objects. */
6362 eassert (valid_lisp_object_p (ptr->function) >= 1);
6363 mark_object (ptr->function);
6364 mark_object (ptr->plist);
6365 switch (ptr->redirect)
6367 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
6368 case SYMBOL_VARALIAS:
6370 Lisp_Object tem;
6371 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
6372 mark_object (tem);
6373 break;
6375 case SYMBOL_LOCALIZED:
6376 mark_localized_symbol (ptr);
6377 break;
6378 case SYMBOL_FORWARDED:
6379 /* If the value is forwarded to a buffer or keyboard field,
6380 these are marked when we see the corresponding object.
6381 And if it's forwarded to a C variable, either it's not
6382 a Lisp_Object var, or it's staticpro'd already. */
6383 break;
6384 default: emacs_abort ();
6386 if (!PURE_POINTER_P (XSTRING (ptr->name)))
6387 MARK_STRING (XSTRING (ptr->name));
6388 MARK_INTERVAL_TREE (string_intervals (ptr->name));
6389 /* Inner loop to mark next symbol in this bucket, if any. */
6390 ptr = ptr->next;
6391 if (ptr)
6392 goto nextsym;
6394 break;
6396 case Lisp_Misc:
6397 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
6399 if (XMISCANY (obj)->gcmarkbit)
6400 break;
6402 switch (XMISCTYPE (obj))
6404 case Lisp_Misc_Marker:
6405 /* DO NOT mark thru the marker's chain.
6406 The buffer's markers chain does not preserve markers from gc;
6407 instead, markers are removed from the chain when freed by gc. */
6408 XMISCANY (obj)->gcmarkbit = 1;
6409 break;
6411 case Lisp_Misc_Save_Value:
6412 XMISCANY (obj)->gcmarkbit = 1;
6413 mark_save_value (XSAVE_VALUE (obj));
6414 break;
6416 case Lisp_Misc_Overlay:
6417 mark_overlay (XOVERLAY (obj));
6418 break;
6420 default:
6421 emacs_abort ();
6423 break;
6425 case Lisp_Cons:
6427 register struct Lisp_Cons *ptr = XCONS (obj);
6428 if (CONS_MARKED_P (ptr))
6429 break;
6430 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
6431 CONS_MARK (ptr);
6432 /* If the cdr is nil, avoid recursion for the car. */
6433 if (EQ (ptr->u.cdr, Qnil))
6435 obj = ptr->car;
6436 cdr_count = 0;
6437 goto loop;
6439 mark_object (ptr->car);
6440 obj = ptr->u.cdr;
6441 cdr_count++;
6442 if (cdr_count == mark_object_loop_halt)
6443 emacs_abort ();
6444 goto loop;
6447 case Lisp_Float:
6448 CHECK_ALLOCATED_AND_LIVE (live_float_p);
6449 FLOAT_MARK (XFLOAT (obj));
6450 break;
6452 case_Lisp_Int:
6453 break;
6455 default:
6456 emacs_abort ();
6459 #undef CHECK_LIVE
6460 #undef CHECK_ALLOCATED
6461 #undef CHECK_ALLOCATED_AND_LIVE
6463 /* Mark the Lisp pointers in the terminal objects.
6464 Called by Fgarbage_collect. */
6466 static void
6467 mark_terminals (void)
6469 struct terminal *t;
6470 for (t = terminal_list; t; t = t->next_terminal)
6472 eassert (t->name != NULL);
6473 #ifdef HAVE_WINDOW_SYSTEM
6474 /* If a terminal object is reachable from a stacpro'ed object,
6475 it might have been marked already. Make sure the image cache
6476 gets marked. */
6477 mark_image_cache (t->image_cache);
6478 #endif /* HAVE_WINDOW_SYSTEM */
6479 if (!VECTOR_MARKED_P (t))
6480 mark_vectorlike ((struct Lisp_Vector *)t);
6486 /* Value is non-zero if OBJ will survive the current GC because it's
6487 either marked or does not need to be marked to survive. */
6489 bool
6490 survives_gc_p (Lisp_Object obj)
6492 bool survives_p;
6494 switch (XTYPE (obj))
6496 case_Lisp_Int:
6497 survives_p = 1;
6498 break;
6500 case Lisp_Symbol:
6501 survives_p = XSYMBOL (obj)->gcmarkbit;
6502 break;
6504 case Lisp_Misc:
6505 survives_p = XMISCANY (obj)->gcmarkbit;
6506 break;
6508 case Lisp_String:
6509 survives_p = STRING_MARKED_P (XSTRING (obj));
6510 break;
6512 case Lisp_Vectorlike:
6513 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
6514 break;
6516 case Lisp_Cons:
6517 survives_p = CONS_MARKED_P (XCONS (obj));
6518 break;
6520 case Lisp_Float:
6521 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
6522 break;
6524 default:
6525 emacs_abort ();
6528 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
6534 NO_INLINE /* For better stack traces */
6535 static void
6536 sweep_conses (void)
6538 struct cons_block *cblk;
6539 struct cons_block **cprev = &cons_block;
6540 int lim = cons_block_index;
6541 EMACS_INT num_free = 0, num_used = 0;
6543 cons_free_list = 0;
6545 for (cblk = cons_block; cblk; cblk = *cprev)
6547 int i = 0;
6548 int this_free = 0;
6549 int ilim = (lim + BITS_PER_BITS_WORD - 1) / BITS_PER_BITS_WORD;
6551 /* Scan the mark bits an int at a time. */
6552 for (i = 0; i < ilim; i++)
6554 if (cblk->gcmarkbits[i] == BITS_WORD_MAX)
6556 /* Fast path - all cons cells for this int are marked. */
6557 cblk->gcmarkbits[i] = 0;
6558 num_used += BITS_PER_BITS_WORD;
6560 else
6562 /* Some cons cells for this int are not marked.
6563 Find which ones, and free them. */
6564 int start, pos, stop;
6566 start = i * BITS_PER_BITS_WORD;
6567 stop = lim - start;
6568 if (stop > BITS_PER_BITS_WORD)
6569 stop = BITS_PER_BITS_WORD;
6570 stop += start;
6572 for (pos = start; pos < stop; pos++)
6574 if (!CONS_MARKED_P (&cblk->conses[pos]))
6576 this_free++;
6577 cblk->conses[pos].u.chain = cons_free_list;
6578 cons_free_list = &cblk->conses[pos];
6579 #if GC_MARK_STACK
6580 cons_free_list->car = Vdead;
6581 #endif
6583 else
6585 num_used++;
6586 CONS_UNMARK (&cblk->conses[pos]);
6592 lim = CONS_BLOCK_SIZE;
6593 /* If this block contains only free conses and we have already
6594 seen more than two blocks worth of free conses then deallocate
6595 this block. */
6596 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
6598 *cprev = cblk->next;
6599 /* Unhook from the free list. */
6600 cons_free_list = cblk->conses[0].u.chain;
6601 lisp_align_free (cblk);
6603 else
6605 num_free += this_free;
6606 cprev = &cblk->next;
6609 total_conses = num_used;
6610 total_free_conses = num_free;
6613 NO_INLINE /* For better stack traces */
6614 static void
6615 sweep_floats (void)
6617 register struct float_block *fblk;
6618 struct float_block **fprev = &float_block;
6619 register int lim = float_block_index;
6620 EMACS_INT num_free = 0, num_used = 0;
6622 float_free_list = 0;
6624 for (fblk = float_block; fblk; fblk = *fprev)
6626 register int i;
6627 int this_free = 0;
6628 for (i = 0; i < lim; i++)
6629 if (!FLOAT_MARKED_P (&fblk->floats[i]))
6631 this_free++;
6632 fblk->floats[i].u.chain = float_free_list;
6633 float_free_list = &fblk->floats[i];
6635 else
6637 num_used++;
6638 FLOAT_UNMARK (&fblk->floats[i]);
6640 lim = FLOAT_BLOCK_SIZE;
6641 /* If this block contains only free floats and we have already
6642 seen more than two blocks worth of free floats then deallocate
6643 this block. */
6644 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6646 *fprev = fblk->next;
6647 /* Unhook from the free list. */
6648 float_free_list = fblk->floats[0].u.chain;
6649 lisp_align_free (fblk);
6651 else
6653 num_free += this_free;
6654 fprev = &fblk->next;
6657 total_floats = num_used;
6658 total_free_floats = num_free;
6661 NO_INLINE /* For better stack traces */
6662 static void
6663 sweep_intervals (void)
6665 register struct interval_block *iblk;
6666 struct interval_block **iprev = &interval_block;
6667 register int lim = interval_block_index;
6668 EMACS_INT num_free = 0, num_used = 0;
6670 interval_free_list = 0;
6672 for (iblk = interval_block; iblk; iblk = *iprev)
6674 register int i;
6675 int this_free = 0;
6677 for (i = 0; i < lim; i++)
6679 if (!iblk->intervals[i].gcmarkbit)
6681 set_interval_parent (&iblk->intervals[i], interval_free_list);
6682 interval_free_list = &iblk->intervals[i];
6683 this_free++;
6685 else
6687 num_used++;
6688 iblk->intervals[i].gcmarkbit = 0;
6691 lim = INTERVAL_BLOCK_SIZE;
6692 /* If this block contains only free intervals and we have already
6693 seen more than two blocks worth of free intervals then
6694 deallocate this block. */
6695 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6697 *iprev = iblk->next;
6698 /* Unhook from the free list. */
6699 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
6700 lisp_free (iblk);
6702 else
6704 num_free += this_free;
6705 iprev = &iblk->next;
6708 total_intervals = num_used;
6709 total_free_intervals = num_free;
6712 NO_INLINE /* For better stack traces */
6713 static void
6714 sweep_symbols (void)
6716 register struct symbol_block *sblk;
6717 struct symbol_block **sprev = &symbol_block;
6718 register int lim = symbol_block_index;
6719 EMACS_INT num_free = 0, num_used = 0;
6721 symbol_free_list = NULL;
6723 for (sblk = symbol_block; sblk; sblk = *sprev)
6725 int this_free = 0;
6726 union aligned_Lisp_Symbol *sym = sblk->symbols;
6727 union aligned_Lisp_Symbol *end = sym + lim;
6729 for (; sym < end; ++sym)
6731 if (!sym->s.gcmarkbit)
6733 if (sym->s.redirect == SYMBOL_LOCALIZED)
6734 xfree (SYMBOL_BLV (&sym->s));
6735 sym->s.next = symbol_free_list;
6736 symbol_free_list = &sym->s;
6737 #if GC_MARK_STACK
6738 symbol_free_list->function = Vdead;
6739 #endif
6740 ++this_free;
6742 else
6744 ++num_used;
6745 sym->s.gcmarkbit = 0;
6746 /* Attempt to catch bogus objects. */
6747 eassert (valid_lisp_object_p (sym->s.function) >= 1);
6751 lim = SYMBOL_BLOCK_SIZE;
6752 /* If this block contains only free symbols and we have already
6753 seen more than two blocks worth of free symbols then deallocate
6754 this block. */
6755 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6757 *sprev = sblk->next;
6758 /* Unhook from the free list. */
6759 symbol_free_list = sblk->symbols[0].s.next;
6760 lisp_free (sblk);
6762 else
6764 num_free += this_free;
6765 sprev = &sblk->next;
6768 total_symbols = num_used;
6769 total_free_symbols = num_free;
6772 NO_INLINE /* For better stack traces */
6773 static void
6774 sweep_misc (void)
6776 register struct marker_block *mblk;
6777 struct marker_block **mprev = &marker_block;
6778 register int lim = marker_block_index;
6779 EMACS_INT num_free = 0, num_used = 0;
6781 /* Put all unmarked misc's on free list. For a marker, first
6782 unchain it from the buffer it points into. */
6784 marker_free_list = 0;
6786 for (mblk = marker_block; mblk; mblk = *mprev)
6788 register int i;
6789 int this_free = 0;
6791 for (i = 0; i < lim; i++)
6793 if (!mblk->markers[i].m.u_any.gcmarkbit)
6795 if (mblk->markers[i].m.u_any.type == Lisp_Misc_Marker)
6796 unchain_marker (&mblk->markers[i].m.u_marker);
6797 /* Set the type of the freed object to Lisp_Misc_Free.
6798 We could leave the type alone, since nobody checks it,
6799 but this might catch bugs faster. */
6800 mblk->markers[i].m.u_marker.type = Lisp_Misc_Free;
6801 mblk->markers[i].m.u_free.chain = marker_free_list;
6802 marker_free_list = &mblk->markers[i].m;
6803 this_free++;
6805 else
6807 num_used++;
6808 mblk->markers[i].m.u_any.gcmarkbit = 0;
6811 lim = MARKER_BLOCK_SIZE;
6812 /* If this block contains only free markers and we have already
6813 seen more than two blocks worth of free markers then deallocate
6814 this block. */
6815 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6817 *mprev = mblk->next;
6818 /* Unhook from the free list. */
6819 marker_free_list = mblk->markers[0].m.u_free.chain;
6820 lisp_free (mblk);
6822 else
6824 num_free += this_free;
6825 mprev = &mblk->next;
6829 total_markers = num_used;
6830 total_free_markers = num_free;
6833 NO_INLINE /* For better stack traces */
6834 static void
6835 sweep_buffers (void)
6837 register struct buffer *buffer, **bprev = &all_buffers;
6839 total_buffers = 0;
6840 for (buffer = all_buffers; buffer; buffer = *bprev)
6841 if (!VECTOR_MARKED_P (buffer))
6843 *bprev = buffer->next;
6844 lisp_free (buffer);
6846 else
6848 VECTOR_UNMARK (buffer);
6849 /* Do not use buffer_(set|get)_intervals here. */
6850 buffer->text->intervals = balance_intervals (buffer->text->intervals);
6851 total_buffers++;
6852 bprev = &buffer->next;
6856 /* Sweep: find all structures not marked, and free them. */
6857 static void
6858 gc_sweep (void)
6860 /* Remove or mark entries in weak hash tables.
6861 This must be done before any object is unmarked. */
6862 sweep_weak_hash_tables ();
6864 sweep_strings ();
6865 check_string_bytes (!noninteractive);
6866 sweep_conses ();
6867 sweep_floats ();
6868 sweep_intervals ();
6869 sweep_symbols ();
6870 sweep_misc ();
6871 sweep_buffers ();
6872 sweep_vectors ();
6873 check_string_bytes (!noninteractive);
6876 DEFUN ("memory-info", Fmemory_info, Smemory_info, 0, 0, 0,
6877 doc: /* Return a list of (TOTAL-RAM FREE-RAM TOTAL-SWAP FREE-SWAP).
6878 All values are in Kbytes. If there is no swap space,
6879 last two values are zero. If the system is not supported
6880 or memory information can't be obtained, return nil. */)
6881 (void)
6883 #if defined HAVE_LINUX_SYSINFO
6884 struct sysinfo si;
6885 uintmax_t units;
6887 if (sysinfo (&si))
6888 return Qnil;
6889 #ifdef LINUX_SYSINFO_UNIT
6890 units = si.mem_unit;
6891 #else
6892 units = 1;
6893 #endif
6894 return list4i ((uintmax_t) si.totalram * units / 1024,
6895 (uintmax_t) si.freeram * units / 1024,
6896 (uintmax_t) si.totalswap * units / 1024,
6897 (uintmax_t) si.freeswap * units / 1024);
6898 #elif defined WINDOWSNT
6899 unsigned long long totalram, freeram, totalswap, freeswap;
6901 if (w32_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
6902 return list4i ((uintmax_t) totalram / 1024,
6903 (uintmax_t) freeram / 1024,
6904 (uintmax_t) totalswap / 1024,
6905 (uintmax_t) freeswap / 1024);
6906 else
6907 return Qnil;
6908 #elif defined MSDOS
6909 unsigned long totalram, freeram, totalswap, freeswap;
6911 if (dos_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
6912 return list4i ((uintmax_t) totalram / 1024,
6913 (uintmax_t) freeram / 1024,
6914 (uintmax_t) totalswap / 1024,
6915 (uintmax_t) freeswap / 1024);
6916 else
6917 return Qnil;
6919 #else /* not HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
6920 /* FIXME: add more systems. */
6921 return Qnil;
6922 #endif /* HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
6925 /* Debugging aids. */
6927 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
6928 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6929 This may be helpful in debugging Emacs's memory usage.
6930 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6931 (void)
6933 Lisp_Object end;
6935 #ifdef HAVE_NS
6936 /* Avoid warning. sbrk has no relation to memory allocated anyway. */
6937 XSETINT (end, 0);
6938 #else
6939 XSETINT (end, (intptr_t) (char *) sbrk (0) / 1024);
6940 #endif
6942 return end;
6945 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
6946 doc: /* Return a list of counters that measure how much consing there has been.
6947 Each of these counters increments for a certain kind of object.
6948 The counters wrap around from the largest positive integer to zero.
6949 Garbage collection does not decrease them.
6950 The elements of the value are as follows:
6951 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6952 All are in units of 1 = one object consed
6953 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6954 objects consed.
6955 MISCS include overlays, markers, and some internal types.
6956 Frames, windows, buffers, and subprocesses count as vectors
6957 (but the contents of a buffer's text do not count here). */)
6958 (void)
6960 return listn (CONSTYPE_HEAP, 8,
6961 bounded_number (cons_cells_consed),
6962 bounded_number (floats_consed),
6963 bounded_number (vector_cells_consed),
6964 bounded_number (symbols_consed),
6965 bounded_number (string_chars_consed),
6966 bounded_number (misc_objects_consed),
6967 bounded_number (intervals_consed),
6968 bounded_number (strings_consed));
6971 /* Find at most FIND_MAX symbols which have OBJ as their value or
6972 function. This is used in gdbinit's `xwhichsymbols' command. */
6974 Lisp_Object
6975 which_symbols (Lisp_Object obj, EMACS_INT find_max)
6977 struct symbol_block *sblk;
6978 ptrdiff_t gc_count = inhibit_garbage_collection ();
6979 Lisp_Object found = Qnil;
6981 if (! DEADP (obj))
6983 for (sblk = symbol_block; sblk; sblk = sblk->next)
6985 union aligned_Lisp_Symbol *aligned_sym = sblk->symbols;
6986 int bn;
6988 for (bn = 0; bn < SYMBOL_BLOCK_SIZE; bn++, aligned_sym++)
6990 struct Lisp_Symbol *sym = &aligned_sym->s;
6991 Lisp_Object val;
6992 Lisp_Object tem;
6994 if (sblk == symbol_block && bn >= symbol_block_index)
6995 break;
6997 XSETSYMBOL (tem, sym);
6998 val = find_symbol_value (tem);
6999 if (EQ (val, obj)
7000 || EQ (sym->function, obj)
7001 || (!NILP (sym->function)
7002 && COMPILEDP (sym->function)
7003 && EQ (AREF (sym->function, COMPILED_BYTECODE), obj))
7004 || (!NILP (val)
7005 && COMPILEDP (val)
7006 && EQ (AREF (val, COMPILED_BYTECODE), obj)))
7008 found = Fcons (tem, found);
7009 if (--find_max == 0)
7010 goto out;
7016 out:
7017 unbind_to (gc_count, Qnil);
7018 return found;
7021 #ifdef SUSPICIOUS_OBJECT_CHECKING
7023 static void *
7024 find_suspicious_object_in_range (void *begin, void *end)
7026 char *begin_a = begin;
7027 char *end_a = end;
7028 int i;
7030 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
7032 char *suspicious_object = suspicious_objects[i];
7033 if (begin_a <= suspicious_object && suspicious_object < end_a)
7034 return suspicious_object;
7037 return NULL;
7040 static void
7041 note_suspicious_free (void* ptr)
7043 struct suspicious_free_record* rec;
7045 rec = &suspicious_free_history[suspicious_free_history_index++];
7046 if (suspicious_free_history_index ==
7047 ARRAYELTS (suspicious_free_history))
7049 suspicious_free_history_index = 0;
7052 memset (rec, 0, sizeof (*rec));
7053 rec->suspicious_object = ptr;
7054 backtrace (&rec->backtrace[0], ARRAYELTS (rec->backtrace));
7057 static void
7058 detect_suspicious_free (void* ptr)
7060 int i;
7062 eassert (ptr != NULL);
7064 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
7065 if (suspicious_objects[i] == ptr)
7067 note_suspicious_free (ptr);
7068 suspicious_objects[i] = NULL;
7072 #endif /* SUSPICIOUS_OBJECT_CHECKING */
7074 DEFUN ("suspicious-object", Fsuspicious_object, Ssuspicious_object, 1, 1, 0,
7075 doc: /* Return OBJ, maybe marking it for extra scrutiny.
7076 If Emacs is compiled with suspicous object checking, capture
7077 a stack trace when OBJ is freed in order to help track down
7078 garbage collection bugs. Otherwise, do nothing and return OBJ. */)
7079 (Lisp_Object obj)
7081 #ifdef SUSPICIOUS_OBJECT_CHECKING
7082 /* Right now, we care only about vectors. */
7083 if (VECTORLIKEP (obj))
7085 suspicious_objects[suspicious_object_index++] = XVECTOR (obj);
7086 if (suspicious_object_index == ARRAYELTS (suspicious_objects))
7087 suspicious_object_index = 0;
7089 #endif
7090 return obj;
7093 #ifdef ENABLE_CHECKING
7095 bool suppress_checking;
7097 void
7098 die (const char *msg, const char *file, int line)
7100 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: assertion failed: %s\r\n",
7101 file, line, msg);
7102 terminate_due_to_signal (SIGABRT, INT_MAX);
7104 #endif
7106 /* Initialization. */
7108 void
7109 init_alloc_once (void)
7111 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
7112 purebeg = PUREBEG;
7113 pure_size = PURESIZE;
7115 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
7116 mem_init ();
7117 Vdead = make_pure_string ("DEAD", 4, 4, 0);
7118 #endif
7120 #ifdef DOUG_LEA_MALLOC
7121 mallopt (M_TRIM_THRESHOLD, 128 * 1024); /* Trim threshold. */
7122 mallopt (M_MMAP_THRESHOLD, 64 * 1024); /* Mmap threshold. */
7123 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* Max. number of mmap'ed areas. */
7124 #endif
7125 init_strings ();
7126 init_vectors ();
7128 refill_memory_reserve ();
7129 gc_cons_threshold = GC_DEFAULT_THRESHOLD;
7132 void
7133 init_alloc (void)
7135 gcprolist = 0;
7136 byte_stack_list = 0;
7137 #if GC_MARK_STACK
7138 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
7139 setjmp_tested_p = longjmps_done = 0;
7140 #endif
7141 #endif
7142 Vgc_elapsed = make_float (0.0);
7143 gcs_done = 0;
7145 #if USE_VALGRIND
7146 valgrind_p = RUNNING_ON_VALGRIND != 0;
7147 #endif
7150 void
7151 syms_of_alloc (void)
7153 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
7154 doc: /* Number of bytes of consing between garbage collections.
7155 Garbage collection can happen automatically once this many bytes have been
7156 allocated since the last garbage collection. All data types count.
7158 Garbage collection happens automatically only when `eval' is called.
7160 By binding this temporarily to a large number, you can effectively
7161 prevent garbage collection during a part of the program.
7162 See also `gc-cons-percentage'. */);
7164 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
7165 doc: /* Portion of the heap used for allocation.
7166 Garbage collection can happen automatically once this portion of the heap
7167 has been allocated since the last garbage collection.
7168 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
7169 Vgc_cons_percentage = make_float (0.1);
7171 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
7172 doc: /* Number of bytes of shareable Lisp data allocated so far. */);
7174 DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
7175 doc: /* Number of cons cells that have been consed so far. */);
7177 DEFVAR_INT ("floats-consed", floats_consed,
7178 doc: /* Number of floats that have been consed so far. */);
7180 DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
7181 doc: /* Number of vector cells that have been consed so far. */);
7183 DEFVAR_INT ("symbols-consed", symbols_consed,
7184 doc: /* Number of symbols that have been consed so far. */);
7186 DEFVAR_INT ("string-chars-consed", string_chars_consed,
7187 doc: /* Number of string characters that have been consed so far. */);
7189 DEFVAR_INT ("misc-objects-consed", misc_objects_consed,
7190 doc: /* Number of miscellaneous objects that have been consed so far.
7191 These include markers and overlays, plus certain objects not visible
7192 to users. */);
7194 DEFVAR_INT ("intervals-consed", intervals_consed,
7195 doc: /* Number of intervals that have been consed so far. */);
7197 DEFVAR_INT ("strings-consed", strings_consed,
7198 doc: /* Number of strings that have been consed so far. */);
7200 DEFVAR_LISP ("purify-flag", Vpurify_flag,
7201 doc: /* Non-nil means loading Lisp code in order to dump an executable.
7202 This means that certain objects should be allocated in shared (pure) space.
7203 It can also be set to a hash-table, in which case this table is used to
7204 do hash-consing of the objects allocated to pure space. */);
7206 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
7207 doc: /* Non-nil means display messages at start and end of garbage collection. */);
7208 garbage_collection_messages = 0;
7210 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
7211 doc: /* Hook run after garbage collection has finished. */);
7212 Vpost_gc_hook = Qnil;
7213 DEFSYM (Qpost_gc_hook, "post-gc-hook");
7215 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
7216 doc: /* Precomputed `signal' argument for memory-full error. */);
7217 /* We build this in advance because if we wait until we need it, we might
7218 not be able to allocate the memory to hold it. */
7219 Vmemory_signal_data
7220 = listn (CONSTYPE_PURE, 2, Qerror,
7221 build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
7223 DEFVAR_LISP ("memory-full", Vmemory_full,
7224 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
7225 Vmemory_full = Qnil;
7227 DEFSYM (Qconses, "conses");
7228 DEFSYM (Qsymbols, "symbols");
7229 DEFSYM (Qmiscs, "miscs");
7230 DEFSYM (Qstrings, "strings");
7231 DEFSYM (Qvectors, "vectors");
7232 DEFSYM (Qfloats, "floats");
7233 DEFSYM (Qintervals, "intervals");
7234 DEFSYM (Qbuffers, "buffers");
7235 DEFSYM (Qstring_bytes, "string-bytes");
7236 DEFSYM (Qvector_slots, "vector-slots");
7237 DEFSYM (Qheap, "heap");
7238 DEFSYM (Qautomatic_gc, "Automatic GC");
7240 DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
7241 DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
7243 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
7244 doc: /* Accumulated time elapsed in garbage collections.
7245 The time is in seconds as a floating point value. */);
7246 DEFVAR_INT ("gcs-done", gcs_done,
7247 doc: /* Accumulated number of garbage collections done. */);
7249 defsubr (&Scons);
7250 defsubr (&Slist);
7251 defsubr (&Svector);
7252 defsubr (&Sbool_vector);
7253 defsubr (&Smake_byte_code);
7254 defsubr (&Smake_list);
7255 defsubr (&Smake_vector);
7256 defsubr (&Smake_string);
7257 defsubr (&Smake_bool_vector);
7258 defsubr (&Smake_symbol);
7259 defsubr (&Smake_marker);
7260 defsubr (&Spurecopy);
7261 defsubr (&Sgarbage_collect);
7262 defsubr (&Smemory_limit);
7263 defsubr (&Smemory_info);
7264 defsubr (&Smemory_use_counts);
7265 defsubr (&Ssuspicious_object);
7267 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
7268 defsubr (&Sgc_status);
7269 #endif
7272 /* When compiled with GCC, GDB might say "No enum type named
7273 pvec_type" if we don't have at least one symbol with that type, and
7274 then xbacktrace could fail. Similarly for the other enums and
7275 their values. Some non-GCC compilers don't like these constructs. */
7276 #ifdef __GNUC__
7277 union
7279 enum CHARTAB_SIZE_BITS CHARTAB_SIZE_BITS;
7280 enum char_table_specials char_table_specials;
7281 enum char_bits char_bits;
7282 enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE;
7283 enum DEFAULT_HASH_SIZE DEFAULT_HASH_SIZE;
7284 enum Lisp_Bits Lisp_Bits;
7285 enum Lisp_Compiled Lisp_Compiled;
7286 enum maxargs maxargs;
7287 enum MAX_ALLOCA MAX_ALLOCA;
7288 enum More_Lisp_Bits More_Lisp_Bits;
7289 enum pvec_type pvec_type;
7290 } const EXTERNALLY_VISIBLE gdb_make_enums_visible = {0};
7291 #endif /* __GNUC__ */