Frame icon optimization
[emacs.git] / src / alloc.c
blob884de3e03e7803d190fbe886975142f1ec3a4431
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>
51 #if (defined ENABLE_CHECKING \
52 && defined HAVE_VALGRIND_VALGRIND_H \
53 && !defined USE_VALGRIND)
54 # define USE_VALGRIND 1
55 #endif
57 #if USE_VALGRIND
58 #include <valgrind/valgrind.h>
59 #include <valgrind/memcheck.h>
60 static bool valgrind_p;
61 #endif
63 /* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects.
64 Doable only if GC_MARK_STACK. */
65 #if ! GC_MARK_STACK
66 # undef GC_CHECK_MARKED_OBJECTS
67 #endif
69 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
70 memory. Can do this only if using gmalloc.c and if not checking
71 marked objects. */
73 #if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
74 || defined GC_CHECK_MARKED_OBJECTS)
75 #undef GC_MALLOC_CHECK
76 #endif
78 #include <unistd.h>
79 #include <fcntl.h>
81 #ifdef USE_GTK
82 # include "gtkutil.h"
83 #endif
84 #ifdef WINDOWSNT
85 #include "w32.h"
86 #include "w32heap.h" /* for sbrk */
87 #endif
89 #ifdef DOUG_LEA_MALLOC
91 #include <malloc.h>
93 /* Specify maximum number of areas to mmap. It would be nice to use a
94 value that explicitly means "no limit". */
96 #define MMAP_MAX_AREAS 100000000
98 #endif /* not DOUG_LEA_MALLOC */
100 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
101 to a struct Lisp_String. */
103 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
104 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
105 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
107 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
108 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
109 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
111 /* Default value of gc_cons_threshold (see below). */
113 #define GC_DEFAULT_THRESHOLD (100000 * word_size)
115 /* Global variables. */
116 struct emacs_globals globals;
118 /* Number of bytes of consing done since the last gc. */
120 EMACS_INT consing_since_gc;
122 /* Similar minimum, computed from Vgc_cons_percentage. */
124 EMACS_INT gc_relative_threshold;
126 /* Minimum number of bytes of consing since GC before next GC,
127 when memory is full. */
129 EMACS_INT memory_full_cons_threshold;
131 /* True during GC. */
133 bool gc_in_progress;
135 /* True means abort if try to GC.
136 This is for code which is written on the assumption that
137 no GC will happen, so as to verify that assumption. */
139 bool abort_on_gc;
141 /* Number of live and free conses etc. */
143 static EMACS_INT total_conses, total_markers, total_symbols, total_buffers;
144 static EMACS_INT total_free_conses, total_free_markers, total_free_symbols;
145 static EMACS_INT total_free_floats, total_floats;
147 /* Points to memory space allocated as "spare", to be freed if we run
148 out of memory. We keep one large block, four cons-blocks, and
149 two string blocks. */
151 static char *spare_memory[7];
153 /* Amount of spare memory to keep in large reserve block, or to see
154 whether this much is available when malloc fails on a larger request. */
156 #define SPARE_MEMORY (1 << 14)
158 /* Initialize it to a nonzero value to force it into data space
159 (rather than bss space). That way unexec will remap it into text
160 space (pure), on some systems. We have not implemented the
161 remapping on more recent systems because this is less important
162 nowadays than in the days of small memories and timesharing. */
164 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
165 #define PUREBEG (char *) pure
167 /* Pointer to the pure area, and its size. */
169 static char *purebeg;
170 static ptrdiff_t pure_size;
172 /* Number of bytes of pure storage used before pure storage overflowed.
173 If this is non-zero, this implies that an overflow occurred. */
175 static ptrdiff_t pure_bytes_used_before_overflow;
177 /* True if P points into pure space. */
179 #define PURE_POINTER_P(P) \
180 ((uintptr_t) (P) - (uintptr_t) purebeg <= pure_size)
182 /* Index in pure at which next pure Lisp object will be allocated.. */
184 static ptrdiff_t pure_bytes_used_lisp;
186 /* Number of bytes allocated for non-Lisp objects in pure storage. */
188 static ptrdiff_t pure_bytes_used_non_lisp;
190 /* If nonzero, this is a warning delivered by malloc and not yet
191 displayed. */
193 const char *pending_malloc_warning;
195 /* Maximum amount of C stack to save when a GC happens. */
197 #ifndef MAX_SAVE_STACK
198 #define MAX_SAVE_STACK 16000
199 #endif
201 /* Buffer in which we save a copy of the C stack at each GC. */
203 #if MAX_SAVE_STACK > 0
204 static char *stack_copy;
205 static ptrdiff_t stack_copy_size;
207 /* Copy to DEST a block of memory from SRC of size SIZE bytes,
208 avoiding any address sanitization. */
210 static void * ATTRIBUTE_NO_SANITIZE_ADDRESS
211 no_sanitize_memcpy (void *dest, void const *src, size_t size)
213 if (! ADDRESS_SANITIZER)
214 return memcpy (dest, src, size);
215 else
217 size_t i;
218 char *d = dest;
219 char const *s = src;
220 for (i = 0; i < size; i++)
221 d[i] = s[i];
222 return dest;
226 #endif /* MAX_SAVE_STACK > 0 */
228 static Lisp_Object Qconses;
229 static Lisp_Object Qsymbols;
230 static Lisp_Object Qmiscs;
231 static Lisp_Object Qstrings;
232 static Lisp_Object Qvectors;
233 static Lisp_Object Qfloats;
234 static Lisp_Object Qintervals;
235 static Lisp_Object Qbuffers;
236 static Lisp_Object Qstring_bytes, Qvector_slots, Qheap;
237 static Lisp_Object Qgc_cons_threshold;
238 Lisp_Object Qautomatic_gc;
239 Lisp_Object Qchar_table_extra_slots;
241 /* Hook run after GC has finished. */
243 static Lisp_Object Qpost_gc_hook;
245 static void mark_terminals (void);
246 static void gc_sweep (void);
247 static Lisp_Object make_pure_vector (ptrdiff_t);
248 static void mark_buffer (struct buffer *);
250 #if !defined REL_ALLOC || defined SYSTEM_MALLOC
251 static void refill_memory_reserve (void);
252 #endif
253 static void compact_small_strings (void);
254 static void free_large_strings (void);
255 extern Lisp_Object which_symbols (Lisp_Object, EMACS_INT) EXTERNALLY_VISIBLE;
257 /* When scanning the C stack for live Lisp objects, Emacs keeps track of
258 what memory allocated via lisp_malloc and lisp_align_malloc is intended
259 for what purpose. This enumeration specifies the type of memory. */
261 enum mem_type
263 MEM_TYPE_NON_LISP,
264 MEM_TYPE_BUFFER,
265 MEM_TYPE_CONS,
266 MEM_TYPE_STRING,
267 MEM_TYPE_MISC,
268 MEM_TYPE_SYMBOL,
269 MEM_TYPE_FLOAT,
270 /* Since all non-bool pseudovectors are small enough to be
271 allocated from vector blocks, this memory type denotes
272 large regular vectors and large bool pseudovectors. */
273 MEM_TYPE_VECTORLIKE,
274 /* Special type to denote vector blocks. */
275 MEM_TYPE_VECTOR_BLOCK,
276 /* Special type to denote reserved memory. */
277 MEM_TYPE_SPARE
280 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
282 /* A unique object in pure space used to make some Lisp objects
283 on free lists recognizable in O(1). */
285 static Lisp_Object Vdead;
286 #define DEADP(x) EQ (x, Vdead)
288 #ifdef GC_MALLOC_CHECK
290 enum mem_type allocated_mem_type;
292 #endif /* GC_MALLOC_CHECK */
294 /* A node in the red-black tree describing allocated memory containing
295 Lisp data. Each such block is recorded with its start and end
296 address when it is allocated, and removed from the tree when it
297 is freed.
299 A red-black tree is a balanced binary tree with the following
300 properties:
302 1. Every node is either red or black.
303 2. Every leaf is black.
304 3. If a node is red, then both of its children are black.
305 4. Every simple path from a node to a descendant leaf contains
306 the same number of black nodes.
307 5. The root is always black.
309 When nodes are inserted into the tree, or deleted from the tree,
310 the tree is "fixed" so that these properties are always true.
312 A red-black tree with N internal nodes has height at most 2
313 log(N+1). Searches, insertions and deletions are done in O(log N).
314 Please see a text book about data structures for a detailed
315 description of red-black trees. Any book worth its salt should
316 describe them. */
318 struct mem_node
320 /* Children of this node. These pointers are never NULL. When there
321 is no child, the value is MEM_NIL, which points to a dummy node. */
322 struct mem_node *left, *right;
324 /* The parent of this node. In the root node, this is NULL. */
325 struct mem_node *parent;
327 /* Start and end of allocated region. */
328 void *start, *end;
330 /* Node color. */
331 enum {MEM_BLACK, MEM_RED} color;
333 /* Memory type. */
334 enum mem_type type;
337 /* Base address of stack. Set in main. */
339 Lisp_Object *stack_base;
341 /* Root of the tree describing allocated Lisp memory. */
343 static struct mem_node *mem_root;
345 /* Lowest and highest known address in the heap. */
347 static void *min_heap_address, *max_heap_address;
349 /* Sentinel node of the tree. */
351 static struct mem_node mem_z;
352 #define MEM_NIL &mem_z
354 static struct mem_node *mem_insert (void *, void *, enum mem_type);
355 static void mem_insert_fixup (struct mem_node *);
356 static void mem_rotate_left (struct mem_node *);
357 static void mem_rotate_right (struct mem_node *);
358 static void mem_delete (struct mem_node *);
359 static void mem_delete_fixup (struct mem_node *);
360 static struct mem_node *mem_find (void *);
362 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
364 #ifndef DEADP
365 # define DEADP(x) 0
366 #endif
368 /* Recording what needs to be marked for gc. */
370 struct gcpro *gcprolist;
372 /* Addresses of staticpro'd variables. Initialize it to a nonzero
373 value; otherwise some compilers put it into BSS. */
375 enum { NSTATICS = 2048 };
376 static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
378 /* Index of next unused slot in staticvec. */
380 static int staticidx;
382 static void *pure_alloc (size_t, int);
384 /* Return X rounded to the next multiple of Y. Arguments should not
385 have side effects, as they are evaluated more than once. Assume X
386 + Y - 1 does not overflow. Tune for Y being a power of 2. */
388 #define ROUNDUP(x, y) ((y) & ((y) - 1) \
389 ? ((x) + (y) - 1) - ((x) + (y) - 1) % (y) \
390 : ((x) + (y) - 1) & ~ ((y) - 1))
392 /* Return PTR rounded up to the next multiple of ALIGNMENT. */
394 static void *
395 ALIGN (void *ptr, int alignment)
397 return (void *) ROUNDUP ((uintptr_t) ptr, alignment);
400 static void
401 XFLOAT_INIT (Lisp_Object f, double n)
403 XFLOAT (f)->u.data = n;
406 static bool
407 pointers_fit_in_lispobj_p (void)
409 return (UINTPTR_MAX <= VAL_MAX) || USE_LSB_TAG;
412 static bool
413 mmap_lisp_allowed_p (void)
415 /* If we can't store all memory addresses in our lisp objects, it's
416 risky to let the heap use mmap and give us addresses from all
417 over our address space. We also can't use mmap for lisp objects
418 if we might dump: unexec doesn't preserve the contents of mmaped
419 regions. */
420 return pointers_fit_in_lispobj_p () && !might_dump;
424 /************************************************************************
425 Malloc
426 ************************************************************************/
428 /* Function malloc calls this if it finds we are near exhausting storage. */
430 void
431 malloc_warning (const char *str)
433 pending_malloc_warning = str;
437 /* Display an already-pending malloc warning. */
439 void
440 display_malloc_warning (void)
442 call3 (intern ("display-warning"),
443 intern ("alloc"),
444 build_string (pending_malloc_warning),
445 intern ("emergency"));
446 pending_malloc_warning = 0;
449 /* Called if we can't allocate relocatable space for a buffer. */
451 void
452 buffer_memory_full (ptrdiff_t nbytes)
454 /* If buffers use the relocating allocator, no need to free
455 spare_memory, because we may have plenty of malloc space left
456 that we could get, and if we don't, the malloc that fails will
457 itself cause spare_memory to be freed. If buffers don't use the
458 relocating allocator, treat this like any other failing
459 malloc. */
461 #ifndef REL_ALLOC
462 memory_full (nbytes);
463 #else
464 /* This used to call error, but if we've run out of memory, we could
465 get infinite recursion trying to build the string. */
466 xsignal (Qnil, Vmemory_signal_data);
467 #endif
470 /* A common multiple of the positive integers A and B. Ideally this
471 would be the least common multiple, but there's no way to do that
472 as a constant expression in C, so do the best that we can easily do. */
473 #define COMMON_MULTIPLE(a, b) \
474 ((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
476 #ifndef XMALLOC_OVERRUN_CHECK
477 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
478 #else
480 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
481 around each block.
483 The header consists of XMALLOC_OVERRUN_CHECK_SIZE fixed bytes
484 followed by XMALLOC_OVERRUN_SIZE_SIZE bytes containing the original
485 block size in little-endian order. The trailer consists of
486 XMALLOC_OVERRUN_CHECK_SIZE fixed bytes.
488 The header is used to detect whether this block has been allocated
489 through these functions, as some low-level libc functions may
490 bypass the malloc hooks. */
492 #define XMALLOC_OVERRUN_CHECK_SIZE 16
493 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
494 (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)
496 /* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
497 hold a size_t value and (2) the header size is a multiple of the
498 alignment that Emacs needs for C types and for USE_LSB_TAG. */
499 #define XMALLOC_BASE_ALIGNMENT \
500 alignof (union { long double d; intmax_t i; void *p; })
502 #if USE_LSB_TAG
503 # define XMALLOC_HEADER_ALIGNMENT \
504 COMMON_MULTIPLE (GCALIGNMENT, XMALLOC_BASE_ALIGNMENT)
505 #else
506 # define XMALLOC_HEADER_ALIGNMENT XMALLOC_BASE_ALIGNMENT
507 #endif
508 #define XMALLOC_OVERRUN_SIZE_SIZE \
509 (((XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t) \
510 + XMALLOC_HEADER_ALIGNMENT - 1) \
511 / XMALLOC_HEADER_ALIGNMENT * XMALLOC_HEADER_ALIGNMENT) \
512 - XMALLOC_OVERRUN_CHECK_SIZE)
514 static char const xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE] =
515 { '\x9a', '\x9b', '\xae', '\xaf',
516 '\xbf', '\xbe', '\xce', '\xcf',
517 '\xea', '\xeb', '\xec', '\xed',
518 '\xdf', '\xde', '\x9c', '\x9d' };
520 static char const xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
521 { '\xaa', '\xab', '\xac', '\xad',
522 '\xba', '\xbb', '\xbc', '\xbd',
523 '\xca', '\xcb', '\xcc', '\xcd',
524 '\xda', '\xdb', '\xdc', '\xdd' };
526 /* Insert and extract the block size in the header. */
528 static void
529 xmalloc_put_size (unsigned char *ptr, size_t size)
531 int i;
532 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
534 *--ptr = size & ((1 << CHAR_BIT) - 1);
535 size >>= CHAR_BIT;
539 static size_t
540 xmalloc_get_size (unsigned char *ptr)
542 size_t size = 0;
543 int i;
544 ptr -= XMALLOC_OVERRUN_SIZE_SIZE;
545 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
547 size <<= CHAR_BIT;
548 size += *ptr++;
550 return size;
554 /* Like malloc, but wraps allocated block with header and trailer. */
556 static void *
557 overrun_check_malloc (size_t size)
559 register unsigned char *val;
560 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
561 emacs_abort ();
563 val = malloc (size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
564 if (val)
566 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
567 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
568 xmalloc_put_size (val, size);
569 memcpy (val + size, xmalloc_overrun_check_trailer,
570 XMALLOC_OVERRUN_CHECK_SIZE);
572 return val;
576 /* Like realloc, but checks old block for overrun, and wraps new block
577 with header and trailer. */
579 static void *
580 overrun_check_realloc (void *block, size_t size)
582 register unsigned char *val = (unsigned char *) block;
583 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
584 emacs_abort ();
586 if (val
587 && memcmp (xmalloc_overrun_check_header,
588 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
589 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
591 size_t osize = xmalloc_get_size (val);
592 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
593 XMALLOC_OVERRUN_CHECK_SIZE))
594 emacs_abort ();
595 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
596 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
597 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
600 val = realloc (val, 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;
613 /* Like free, but checks block for overrun. */
615 static void
616 overrun_check_free (void *block)
618 unsigned char *val = (unsigned char *) block;
620 if (val
621 && memcmp (xmalloc_overrun_check_header,
622 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
623 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
625 size_t osize = xmalloc_get_size (val);
626 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
627 XMALLOC_OVERRUN_CHECK_SIZE))
628 emacs_abort ();
629 #ifdef XMALLOC_CLEAR_FREE_MEMORY
630 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
631 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_OVERHEAD);
632 #else
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);
636 #endif
639 free (val);
642 #undef malloc
643 #undef realloc
644 #undef free
645 #define malloc overrun_check_malloc
646 #define realloc overrun_check_realloc
647 #define free overrun_check_free
648 #endif
650 /* If compiled with XMALLOC_BLOCK_INPUT_CHECK, define a symbol
651 BLOCK_INPUT_IN_MEMORY_ALLOCATORS that is visible to the debugger.
652 If that variable is set, block input while in one of Emacs's memory
653 allocation functions. There should be no need for this debugging
654 option, since signal handlers do not allocate memory, but Emacs
655 formerly allocated memory in signal handlers and this compile-time
656 option remains as a way to help debug the issue should it rear its
657 ugly head again. */
658 #ifdef XMALLOC_BLOCK_INPUT_CHECK
659 bool block_input_in_memory_allocators EXTERNALLY_VISIBLE;
660 static void
661 malloc_block_input (void)
663 if (block_input_in_memory_allocators)
664 block_input ();
666 static void
667 malloc_unblock_input (void)
669 if (block_input_in_memory_allocators)
670 unblock_input ();
672 # define MALLOC_BLOCK_INPUT malloc_block_input ()
673 # define MALLOC_UNBLOCK_INPUT malloc_unblock_input ()
674 #else
675 # define MALLOC_BLOCK_INPUT ((void) 0)
676 # define MALLOC_UNBLOCK_INPUT ((void) 0)
677 #endif
679 #define MALLOC_PROBE(size) \
680 do { \
681 if (profiler_memory_running) \
682 malloc_probe (size); \
683 } while (0)
686 /* Like malloc but check for no memory and block interrupt input.. */
688 void *
689 xmalloc (size_t size)
691 void *val;
693 MALLOC_BLOCK_INPUT;
694 val = malloc (size);
695 MALLOC_UNBLOCK_INPUT;
697 if (!val && size)
698 memory_full (size);
699 MALLOC_PROBE (size);
700 return val;
703 /* Like the above, but zeroes out the memory just allocated. */
705 void *
706 xzalloc (size_t size)
708 void *val;
710 MALLOC_BLOCK_INPUT;
711 val = malloc (size);
712 MALLOC_UNBLOCK_INPUT;
714 if (!val && size)
715 memory_full (size);
716 memset (val, 0, size);
717 MALLOC_PROBE (size);
718 return val;
721 /* Like realloc but check for no memory and block interrupt input.. */
723 void *
724 xrealloc (void *block, size_t size)
726 void *val;
728 MALLOC_BLOCK_INPUT;
729 /* We must call malloc explicitly when BLOCK is 0, since some
730 reallocs don't do this. */
731 if (! block)
732 val = malloc (size);
733 else
734 val = realloc (block, size);
735 MALLOC_UNBLOCK_INPUT;
737 if (!val && size)
738 memory_full (size);
739 MALLOC_PROBE (size);
740 return val;
744 /* Like free but block interrupt input. */
746 void
747 xfree (void *block)
749 if (!block)
750 return;
751 MALLOC_BLOCK_INPUT;
752 free (block);
753 MALLOC_UNBLOCK_INPUT;
754 /* We don't call refill_memory_reserve here
755 because in practice the call in r_alloc_free seems to suffice. */
759 /* Other parts of Emacs pass large int values to allocator functions
760 expecting ptrdiff_t. This is portable in practice, but check it to
761 be safe. */
762 verify (INT_MAX <= PTRDIFF_MAX);
765 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
766 Signal an error on memory exhaustion, and block interrupt input. */
768 void *
769 xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
771 eassert (0 <= nitems && 0 < item_size);
772 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
773 memory_full (SIZE_MAX);
774 return xmalloc (nitems * item_size);
778 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
779 Signal an error on memory exhaustion, and block interrupt input. */
781 void *
782 xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
784 eassert (0 <= nitems && 0 < item_size);
785 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
786 memory_full (SIZE_MAX);
787 return xrealloc (pa, nitems * item_size);
791 /* Grow PA, which points to an array of *NITEMS items, and return the
792 location of the reallocated array, updating *NITEMS to reflect its
793 new size. The new array will contain at least NITEMS_INCR_MIN more
794 items, but will not contain more than NITEMS_MAX items total.
795 ITEM_SIZE is the size of each item, in bytes.
797 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
798 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
799 infinity.
801 If PA is null, then allocate a new array instead of reallocating
802 the old one.
804 Block interrupt input as needed. If memory exhaustion occurs, set
805 *NITEMS to zero if PA is null, and signal an error (i.e., do not
806 return).
808 Thus, to grow an array A without saving its old contents, do
809 { xfree (A); A = NULL; A = xpalloc (NULL, &AITEMS, ...); }.
810 The A = NULL avoids a dangling pointer if xpalloc exhausts memory
811 and signals an error, and later this code is reexecuted and
812 attempts to free A. */
814 void *
815 xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
816 ptrdiff_t nitems_max, ptrdiff_t item_size)
818 /* The approximate size to use for initial small allocation
819 requests. This is the largest "small" request for the GNU C
820 library malloc. */
821 enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
823 /* If the array is tiny, grow it to about (but no greater than)
824 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%. */
825 ptrdiff_t n = *nitems;
826 ptrdiff_t tiny_max = DEFAULT_MXFAST / item_size - n;
827 ptrdiff_t half_again = n >> 1;
828 ptrdiff_t incr_estimate = max (tiny_max, half_again);
830 /* Adjust the increment according to three constraints: NITEMS_INCR_MIN,
831 NITEMS_MAX, and what the C language can represent safely. */
832 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / item_size;
833 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
834 ? nitems_max : C_language_max);
835 ptrdiff_t nitems_incr_max = n_max - n;
836 ptrdiff_t incr = max (nitems_incr_min, min (incr_estimate, nitems_incr_max));
838 eassert (0 < item_size && 0 < nitems_incr_min && 0 <= n && -1 <= nitems_max);
839 if (! pa)
840 *nitems = 0;
841 if (nitems_incr_max < incr)
842 memory_full (SIZE_MAX);
843 n += incr;
844 pa = xrealloc (pa, n * item_size);
845 *nitems = n;
846 return pa;
850 /* Like strdup, but uses xmalloc. */
852 char *
853 xstrdup (const char *s)
855 ptrdiff_t size;
856 eassert (s);
857 size = strlen (s) + 1;
858 return memcpy (xmalloc (size), s, size);
861 /* Like above, but duplicates Lisp string to C string. */
863 char *
864 xlispstrdup (Lisp_Object string)
866 ptrdiff_t size = SBYTES (string) + 1;
867 return memcpy (xmalloc (size), SSDATA (string), size);
870 /* Assign to *PTR a copy of STRING, freeing any storage *PTR formerly
871 pointed to. If STRING is null, assign it without copying anything.
872 Allocate before freeing, to avoid a dangling pointer if allocation
873 fails. */
875 void
876 dupstring (char **ptr, char const *string)
878 char *old = *ptr;
879 *ptr = string ? xstrdup (string) : 0;
880 xfree (old);
884 /* Like putenv, but (1) use the equivalent of xmalloc and (2) the
885 argument is a const pointer. */
887 void
888 xputenv (char const *string)
890 if (putenv ((char *) string) != 0)
891 memory_full (0);
894 /* Return a newly allocated memory block of SIZE bytes, remembering
895 to free it when unwinding. */
896 void *
897 record_xmalloc (size_t size)
899 void *p = xmalloc (size);
900 record_unwind_protect_ptr (xfree, p);
901 return p;
905 /* Like malloc but used for allocating Lisp data. NBYTES is the
906 number of bytes to allocate, TYPE describes the intended use of the
907 allocated memory block (for strings, for conses, ...). */
909 #if ! USE_LSB_TAG
910 void *lisp_malloc_loser EXTERNALLY_VISIBLE;
911 #endif
913 static void *
914 lisp_malloc (size_t nbytes, enum mem_type type)
916 register void *val;
918 MALLOC_BLOCK_INPUT;
920 #ifdef GC_MALLOC_CHECK
921 allocated_mem_type = type;
922 #endif
924 val = malloc (nbytes);
926 #if ! USE_LSB_TAG
927 /* If the memory just allocated cannot be addressed thru a Lisp
928 object's pointer, and it needs to be,
929 that's equivalent to running out of memory. */
930 if (val && type != MEM_TYPE_NON_LISP)
932 Lisp_Object tem;
933 XSETCONS (tem, (char *) val + nbytes - 1);
934 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
936 lisp_malloc_loser = val;
937 free (val);
938 val = 0;
941 #endif
943 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
944 if (val && type != MEM_TYPE_NON_LISP)
945 mem_insert (val, (char *) val + nbytes, type);
946 #endif
948 MALLOC_UNBLOCK_INPUT;
949 if (!val && nbytes)
950 memory_full (nbytes);
951 MALLOC_PROBE (nbytes);
952 return val;
955 /* Free BLOCK. This must be called to free memory allocated with a
956 call to lisp_malloc. */
958 static void
959 lisp_free (void *block)
961 MALLOC_BLOCK_INPUT;
962 free (block);
963 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
964 mem_delete (mem_find (block));
965 #endif
966 MALLOC_UNBLOCK_INPUT;
969 /***** Allocation of aligned blocks of memory to store Lisp data. *****/
971 /* The entry point is lisp_align_malloc which returns blocks of at most
972 BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
974 /* Use aligned_alloc if it or a simple substitute is available.
975 Address sanitization breaks aligned allocation, as of gcc 4.8.2 and
976 clang 3.3 anyway. */
978 #if ! ADDRESS_SANITIZER
979 # if !defined SYSTEM_MALLOC && !defined DOUG_LEA_MALLOC
980 # define USE_ALIGNED_ALLOC 1
981 /* Defined in gmalloc.c. */
982 void *aligned_alloc (size_t, size_t);
983 # elif defined HAVE_ALIGNED_ALLOC
984 # define USE_ALIGNED_ALLOC 1
985 # elif defined HAVE_POSIX_MEMALIGN
986 # define USE_ALIGNED_ALLOC 1
987 static void *
988 aligned_alloc (size_t alignment, size_t size)
990 void *p;
991 return posix_memalign (&p, alignment, size) == 0 ? p : 0;
993 # endif
994 #endif
996 /* BLOCK_ALIGN has to be a power of 2. */
997 #define BLOCK_ALIGN (1 << 10)
999 /* Padding to leave at the end of a malloc'd block. This is to give
1000 malloc a chance to minimize the amount of memory wasted to alignment.
1001 It should be tuned to the particular malloc library used.
1002 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
1003 aligned_alloc on the other hand would ideally prefer a value of 4
1004 because otherwise, there's 1020 bytes wasted between each ablocks.
1005 In Emacs, testing shows that those 1020 can most of the time be
1006 efficiently used by malloc to place other objects, so a value of 0 can
1007 still preferable unless you have a lot of aligned blocks and virtually
1008 nothing else. */
1009 #define BLOCK_PADDING 0
1010 #define BLOCK_BYTES \
1011 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
1013 /* Internal data structures and constants. */
1015 #define ABLOCKS_SIZE 16
1017 /* An aligned block of memory. */
1018 struct ablock
1020 union
1022 char payload[BLOCK_BYTES];
1023 struct ablock *next_free;
1024 } x;
1025 /* `abase' is the aligned base of the ablocks. */
1026 /* It is overloaded to hold the virtual `busy' field that counts
1027 the number of used ablock in the parent ablocks.
1028 The first ablock has the `busy' field, the others have the `abase'
1029 field. To tell the difference, we assume that pointers will have
1030 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
1031 is used to tell whether the real base of the parent ablocks is `abase'
1032 (if not, the word before the first ablock holds a pointer to the
1033 real base). */
1034 struct ablocks *abase;
1035 /* The padding of all but the last ablock is unused. The padding of
1036 the last ablock in an ablocks is not allocated. */
1037 #if BLOCK_PADDING
1038 char padding[BLOCK_PADDING];
1039 #endif
1042 /* A bunch of consecutive aligned blocks. */
1043 struct ablocks
1045 struct ablock blocks[ABLOCKS_SIZE];
1048 /* Size of the block requested from malloc or aligned_alloc. */
1049 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
1051 #define ABLOCK_ABASE(block) \
1052 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
1053 ? (struct ablocks *)(block) \
1054 : (block)->abase)
1056 /* Virtual `busy' field. */
1057 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
1059 /* Pointer to the (not necessarily aligned) malloc block. */
1060 #ifdef USE_ALIGNED_ALLOC
1061 #define ABLOCKS_BASE(abase) (abase)
1062 #else
1063 #define ABLOCKS_BASE(abase) \
1064 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void **)abase)[-1])
1065 #endif
1067 /* The list of free ablock. */
1068 static struct ablock *free_ablock;
1070 /* Allocate an aligned block of nbytes.
1071 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
1072 smaller or equal to BLOCK_BYTES. */
1073 static void *
1074 lisp_align_malloc (size_t nbytes, enum mem_type type)
1076 void *base, *val;
1077 struct ablocks *abase;
1079 eassert (nbytes <= BLOCK_BYTES);
1081 MALLOC_BLOCK_INPUT;
1083 #ifdef GC_MALLOC_CHECK
1084 allocated_mem_type = type;
1085 #endif
1087 if (!free_ablock)
1089 int i;
1090 intptr_t aligned; /* int gets warning casting to 64-bit pointer. */
1092 #ifdef DOUG_LEA_MALLOC
1093 if (!mmap_lisp_allowed_p ())
1094 mallopt (M_MMAP_MAX, 0);
1095 #endif
1097 #ifdef USE_ALIGNED_ALLOC
1098 abase = base = aligned_alloc (BLOCK_ALIGN, ABLOCKS_BYTES);
1099 #else
1100 base = malloc (ABLOCKS_BYTES);
1101 abase = ALIGN (base, BLOCK_ALIGN);
1102 #endif
1104 if (base == 0)
1106 MALLOC_UNBLOCK_INPUT;
1107 memory_full (ABLOCKS_BYTES);
1110 aligned = (base == abase);
1111 if (!aligned)
1112 ((void **) abase)[-1] = base;
1114 #ifdef DOUG_LEA_MALLOC
1115 if (!mmap_lisp_allowed_p ())
1116 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1117 #endif
1119 #if ! USE_LSB_TAG
1120 /* If the memory just allocated cannot be addressed thru a Lisp
1121 object's pointer, and it needs to be, that's equivalent to
1122 running out of memory. */
1123 if (type != MEM_TYPE_NON_LISP)
1125 Lisp_Object tem;
1126 char *end = (char *) base + ABLOCKS_BYTES - 1;
1127 XSETCONS (tem, end);
1128 if ((char *) XCONS (tem) != end)
1130 lisp_malloc_loser = base;
1131 free (base);
1132 MALLOC_UNBLOCK_INPUT;
1133 memory_full (SIZE_MAX);
1136 #endif
1138 /* Initialize the blocks and put them on the free list.
1139 If `base' was not properly aligned, we can't use the last block. */
1140 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1142 abase->blocks[i].abase = abase;
1143 abase->blocks[i].x.next_free = free_ablock;
1144 free_ablock = &abase->blocks[i];
1146 ABLOCKS_BUSY (abase) = (struct ablocks *) aligned;
1148 eassert (0 == ((uintptr_t) abase) % BLOCK_ALIGN);
1149 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1150 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1151 eassert (ABLOCKS_BASE (abase) == base);
1152 eassert (aligned == (intptr_t) ABLOCKS_BUSY (abase));
1155 abase = ABLOCK_ABASE (free_ablock);
1156 ABLOCKS_BUSY (abase)
1157 = (struct ablocks *) (2 + (intptr_t) ABLOCKS_BUSY (abase));
1158 val = free_ablock;
1159 free_ablock = free_ablock->x.next_free;
1161 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1162 if (type != MEM_TYPE_NON_LISP)
1163 mem_insert (val, (char *) val + nbytes, type);
1164 #endif
1166 MALLOC_UNBLOCK_INPUT;
1168 MALLOC_PROBE (nbytes);
1170 eassert (0 == ((uintptr_t) val) % BLOCK_ALIGN);
1171 return val;
1174 static void
1175 lisp_align_free (void *block)
1177 struct ablock *ablock = block;
1178 struct ablocks *abase = ABLOCK_ABASE (ablock);
1180 MALLOC_BLOCK_INPUT;
1181 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1182 mem_delete (mem_find (block));
1183 #endif
1184 /* Put on free list. */
1185 ablock->x.next_free = free_ablock;
1186 free_ablock = ablock;
1187 /* Update busy count. */
1188 ABLOCKS_BUSY (abase)
1189 = (struct ablocks *) (-2 + (intptr_t) ABLOCKS_BUSY (abase));
1191 if (2 > (intptr_t) ABLOCKS_BUSY (abase))
1192 { /* All the blocks are free. */
1193 int i = 0, aligned = (intptr_t) ABLOCKS_BUSY (abase);
1194 struct ablock **tem = &free_ablock;
1195 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1197 while (*tem)
1199 if (*tem >= (struct ablock *) abase && *tem < atop)
1201 i++;
1202 *tem = (*tem)->x.next_free;
1204 else
1205 tem = &(*tem)->x.next_free;
1207 eassert ((aligned & 1) == aligned);
1208 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1209 #ifdef USE_POSIX_MEMALIGN
1210 eassert ((uintptr_t) ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1211 #endif
1212 free (ABLOCKS_BASE (abase));
1214 MALLOC_UNBLOCK_INPUT;
1218 /***********************************************************************
1219 Interval Allocation
1220 ***********************************************************************/
1222 /* Number of intervals allocated in an interval_block structure.
1223 The 1020 is 1024 minus malloc overhead. */
1225 #define INTERVAL_BLOCK_SIZE \
1226 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1228 /* Intervals are allocated in chunks in the form of an interval_block
1229 structure. */
1231 struct interval_block
1233 /* Place `intervals' first, to preserve alignment. */
1234 struct interval intervals[INTERVAL_BLOCK_SIZE];
1235 struct interval_block *next;
1238 /* Current interval block. Its `next' pointer points to older
1239 blocks. */
1241 static struct interval_block *interval_block;
1243 /* Index in interval_block above of the next unused interval
1244 structure. */
1246 static int interval_block_index = INTERVAL_BLOCK_SIZE;
1248 /* Number of free and live intervals. */
1250 static EMACS_INT total_free_intervals, total_intervals;
1252 /* List of free intervals. */
1254 static INTERVAL interval_free_list;
1256 /* Return a new interval. */
1258 INTERVAL
1259 make_interval (void)
1261 INTERVAL val;
1263 MALLOC_BLOCK_INPUT;
1265 if (interval_free_list)
1267 val = interval_free_list;
1268 interval_free_list = INTERVAL_PARENT (interval_free_list);
1270 else
1272 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1274 struct interval_block *newi
1275 = lisp_malloc (sizeof *newi, MEM_TYPE_NON_LISP);
1277 newi->next = interval_block;
1278 interval_block = newi;
1279 interval_block_index = 0;
1280 total_free_intervals += INTERVAL_BLOCK_SIZE;
1282 val = &interval_block->intervals[interval_block_index++];
1285 MALLOC_UNBLOCK_INPUT;
1287 consing_since_gc += sizeof (struct interval);
1288 intervals_consed++;
1289 total_free_intervals--;
1290 RESET_INTERVAL (val);
1291 val->gcmarkbit = 0;
1292 return val;
1296 /* Mark Lisp objects in interval I. */
1298 static void
1299 mark_interval (register INTERVAL i, Lisp_Object dummy)
1301 /* Intervals should never be shared. So, if extra internal checking is
1302 enabled, GC aborts if it seems to have visited an interval twice. */
1303 eassert (!i->gcmarkbit);
1304 i->gcmarkbit = 1;
1305 mark_object (i->plist);
1308 /* Mark the interval tree rooted in I. */
1310 #define MARK_INTERVAL_TREE(i) \
1311 do { \
1312 if (i && !i->gcmarkbit) \
1313 traverse_intervals_noorder (i, mark_interval, Qnil); \
1314 } while (0)
1316 /***********************************************************************
1317 String Allocation
1318 ***********************************************************************/
1320 /* Lisp_Strings are allocated in string_block structures. When a new
1321 string_block is allocated, all the Lisp_Strings it contains are
1322 added to a free-list string_free_list. When a new Lisp_String is
1323 needed, it is taken from that list. During the sweep phase of GC,
1324 string_blocks that are entirely free are freed, except two which
1325 we keep.
1327 String data is allocated from sblock structures. Strings larger
1328 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1329 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1331 Sblocks consist internally of sdata structures, one for each
1332 Lisp_String. The sdata structure points to the Lisp_String it
1333 belongs to. The Lisp_String points back to the `u.data' member of
1334 its sdata structure.
1336 When a Lisp_String is freed during GC, it is put back on
1337 string_free_list, and its `data' member and its sdata's `string'
1338 pointer is set to null. The size of the string is recorded in the
1339 `n.nbytes' member of the sdata. So, sdata structures that are no
1340 longer used, can be easily recognized, and it's easy to compact the
1341 sblocks of small strings which we do in compact_small_strings. */
1343 /* Size in bytes of an sblock structure used for small strings. This
1344 is 8192 minus malloc overhead. */
1346 #define SBLOCK_SIZE 8188
1348 /* Strings larger than this are considered large strings. String data
1349 for large strings is allocated from individual sblocks. */
1351 #define LARGE_STRING_BYTES 1024
1353 /* The SDATA typedef is a struct or union describing string memory
1354 sub-allocated from an sblock. This is where the contents of Lisp
1355 strings are stored. */
1357 struct sdata
1359 /* Back-pointer to the string this sdata belongs to. If null, this
1360 structure is free, and NBYTES (in this structure or in the union below)
1361 contains the string's byte size (the same value that STRING_BYTES
1362 would return if STRING were non-null). If non-null, STRING_BYTES
1363 (STRING) is the size of the data, and DATA contains the string's
1364 contents. */
1365 struct Lisp_String *string;
1367 #ifdef GC_CHECK_STRING_BYTES
1368 ptrdiff_t nbytes;
1369 #endif
1371 unsigned char data[FLEXIBLE_ARRAY_MEMBER];
1374 #ifdef GC_CHECK_STRING_BYTES
1376 typedef struct sdata sdata;
1377 #define SDATA_NBYTES(S) (S)->nbytes
1378 #define SDATA_DATA(S) (S)->data
1380 #else
1382 typedef union
1384 struct Lisp_String *string;
1386 /* When STRING is nonnull, this union is actually of type 'struct sdata',
1387 which has a flexible array member. However, if implemented by
1388 giving this union a member of type 'struct sdata', the union
1389 could not be the last (flexible) member of 'struct sblock',
1390 because C99 prohibits a flexible array member from having a type
1391 that is itself a flexible array. So, comment this member out here,
1392 but remember that the option's there when using this union. */
1393 #if 0
1394 struct sdata u;
1395 #endif
1397 /* When STRING is null. */
1398 struct
1400 struct Lisp_String *string;
1401 ptrdiff_t nbytes;
1402 } n;
1403 } sdata;
1405 #define SDATA_NBYTES(S) (S)->n.nbytes
1406 #define SDATA_DATA(S) ((struct sdata *) (S))->data
1408 #endif /* not GC_CHECK_STRING_BYTES */
1410 enum { SDATA_DATA_OFFSET = offsetof (struct sdata, data) };
1412 /* Structure describing a block of memory which is sub-allocated to
1413 obtain string data memory for strings. Blocks for small strings
1414 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1415 as large as needed. */
1417 struct sblock
1419 /* Next in list. */
1420 struct sblock *next;
1422 /* Pointer to the next free sdata block. This points past the end
1423 of the sblock if there isn't any space left in this block. */
1424 sdata *next_free;
1426 /* String data. */
1427 sdata data[FLEXIBLE_ARRAY_MEMBER];
1430 /* Number of Lisp strings in a string_block structure. The 1020 is
1431 1024 minus malloc overhead. */
1433 #define STRING_BLOCK_SIZE \
1434 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1436 /* Structure describing a block from which Lisp_String structures
1437 are allocated. */
1439 struct string_block
1441 /* Place `strings' first, to preserve alignment. */
1442 struct Lisp_String strings[STRING_BLOCK_SIZE];
1443 struct string_block *next;
1446 /* Head and tail of the list of sblock structures holding Lisp string
1447 data. We always allocate from current_sblock. The NEXT pointers
1448 in the sblock structures go from oldest_sblock to current_sblock. */
1450 static struct sblock *oldest_sblock, *current_sblock;
1452 /* List of sblocks for large strings. */
1454 static struct sblock *large_sblocks;
1456 /* List of string_block structures. */
1458 static struct string_block *string_blocks;
1460 /* Free-list of Lisp_Strings. */
1462 static struct Lisp_String *string_free_list;
1464 /* Number of live and free Lisp_Strings. */
1466 static EMACS_INT total_strings, total_free_strings;
1468 /* Number of bytes used by live strings. */
1470 static EMACS_INT total_string_bytes;
1472 /* Given a pointer to a Lisp_String S which is on the free-list
1473 string_free_list, return a pointer to its successor in the
1474 free-list. */
1476 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1478 /* Return a pointer to the sdata structure belonging to Lisp string S.
1479 S must be live, i.e. S->data must not be null. S->data is actually
1480 a pointer to the `u.data' member of its sdata structure; the
1481 structure starts at a constant offset in front of that. */
1483 #define SDATA_OF_STRING(S) ((sdata *) ((S)->data - SDATA_DATA_OFFSET))
1486 #ifdef GC_CHECK_STRING_OVERRUN
1488 /* We check for overrun in string data blocks by appending a small
1489 "cookie" after each allocated string data block, and check for the
1490 presence of this cookie during GC. */
1492 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1493 static char const string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1494 { '\xde', '\xad', '\xbe', '\xef' };
1496 #else
1497 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1498 #endif
1500 /* Value is the size of an sdata structure large enough to hold NBYTES
1501 bytes of string data. The value returned includes a terminating
1502 NUL byte, the size of the sdata structure, and padding. */
1504 #ifdef GC_CHECK_STRING_BYTES
1506 #define SDATA_SIZE(NBYTES) \
1507 ((SDATA_DATA_OFFSET \
1508 + (NBYTES) + 1 \
1509 + sizeof (ptrdiff_t) - 1) \
1510 & ~(sizeof (ptrdiff_t) - 1))
1512 #else /* not GC_CHECK_STRING_BYTES */
1514 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1515 less than the size of that member. The 'max' is not needed when
1516 SDATA_DATA_OFFSET is a multiple of sizeof (ptrdiff_t), because then the
1517 alignment code reserves enough space. */
1519 #define SDATA_SIZE(NBYTES) \
1520 ((SDATA_DATA_OFFSET \
1521 + (SDATA_DATA_OFFSET % sizeof (ptrdiff_t) == 0 \
1522 ? NBYTES \
1523 : max (NBYTES, sizeof (ptrdiff_t) - 1)) \
1524 + 1 \
1525 + sizeof (ptrdiff_t) - 1) \
1526 & ~(sizeof (ptrdiff_t) - 1))
1528 #endif /* not GC_CHECK_STRING_BYTES */
1530 /* Extra bytes to allocate for each string. */
1532 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1534 /* Exact bound on the number of bytes in a string, not counting the
1535 terminating null. A string cannot contain more bytes than
1536 STRING_BYTES_BOUND, nor can it be so long that the size_t
1537 arithmetic in allocate_string_data would overflow while it is
1538 calculating a value to be passed to malloc. */
1539 static ptrdiff_t const STRING_BYTES_MAX =
1540 min (STRING_BYTES_BOUND,
1541 ((SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD
1542 - GC_STRING_EXTRA
1543 - offsetof (struct sblock, data)
1544 - SDATA_DATA_OFFSET)
1545 & ~(sizeof (EMACS_INT) - 1)));
1547 /* Initialize string allocation. Called from init_alloc_once. */
1549 static void
1550 init_strings (void)
1552 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1553 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1557 #ifdef GC_CHECK_STRING_BYTES
1559 static int check_string_bytes_count;
1561 /* Like STRING_BYTES, but with debugging check. Can be
1562 called during GC, so pay attention to the mark bit. */
1564 ptrdiff_t
1565 string_bytes (struct Lisp_String *s)
1567 ptrdiff_t nbytes =
1568 (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1570 if (!PURE_POINTER_P (s)
1571 && s->data
1572 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1573 emacs_abort ();
1574 return nbytes;
1577 /* Check validity of Lisp strings' string_bytes member in B. */
1579 static void
1580 check_sblock (struct sblock *b)
1582 sdata *from, *end, *from_end;
1584 end = b->next_free;
1586 for (from = b->data; from < end; from = from_end)
1588 /* Compute the next FROM here because copying below may
1589 overwrite data we need to compute it. */
1590 ptrdiff_t nbytes;
1592 /* Check that the string size recorded in the string is the
1593 same as the one recorded in the sdata structure. */
1594 nbytes = SDATA_SIZE (from->string ? string_bytes (from->string)
1595 : SDATA_NBYTES (from));
1596 from_end = (sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1601 /* Check validity of Lisp strings' string_bytes member. ALL_P
1602 means check all strings, otherwise check only most
1603 recently allocated strings. Used for hunting a bug. */
1605 static void
1606 check_string_bytes (bool all_p)
1608 if (all_p)
1610 struct sblock *b;
1612 for (b = large_sblocks; b; b = b->next)
1614 struct Lisp_String *s = b->data[0].string;
1615 if (s)
1616 string_bytes (s);
1619 for (b = oldest_sblock; b; b = b->next)
1620 check_sblock (b);
1622 else if (current_sblock)
1623 check_sblock (current_sblock);
1626 #else /* not GC_CHECK_STRING_BYTES */
1628 #define check_string_bytes(all) ((void) 0)
1630 #endif /* GC_CHECK_STRING_BYTES */
1632 #ifdef GC_CHECK_STRING_FREE_LIST
1634 /* Walk through the string free list looking for bogus next pointers.
1635 This may catch buffer overrun from a previous string. */
1637 static void
1638 check_string_free_list (void)
1640 struct Lisp_String *s;
1642 /* Pop a Lisp_String off the free-list. */
1643 s = string_free_list;
1644 while (s != NULL)
1646 if ((uintptr_t) s < 1024)
1647 emacs_abort ();
1648 s = NEXT_FREE_LISP_STRING (s);
1651 #else
1652 #define check_string_free_list()
1653 #endif
1655 /* Return a new Lisp_String. */
1657 static struct Lisp_String *
1658 allocate_string (void)
1660 struct Lisp_String *s;
1662 MALLOC_BLOCK_INPUT;
1664 /* If the free-list is empty, allocate a new string_block, and
1665 add all the Lisp_Strings in it to the free-list. */
1666 if (string_free_list == NULL)
1668 struct string_block *b = lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1669 int i;
1671 b->next = string_blocks;
1672 string_blocks = b;
1674 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1676 s = b->strings + i;
1677 /* Every string on a free list should have NULL data pointer. */
1678 s->data = NULL;
1679 NEXT_FREE_LISP_STRING (s) = string_free_list;
1680 string_free_list = s;
1683 total_free_strings += STRING_BLOCK_SIZE;
1686 check_string_free_list ();
1688 /* Pop a Lisp_String off the free-list. */
1689 s = string_free_list;
1690 string_free_list = NEXT_FREE_LISP_STRING (s);
1692 MALLOC_UNBLOCK_INPUT;
1694 --total_free_strings;
1695 ++total_strings;
1696 ++strings_consed;
1697 consing_since_gc += sizeof *s;
1699 #ifdef GC_CHECK_STRING_BYTES
1700 if (!noninteractive)
1702 if (++check_string_bytes_count == 200)
1704 check_string_bytes_count = 0;
1705 check_string_bytes (1);
1707 else
1708 check_string_bytes (0);
1710 #endif /* GC_CHECK_STRING_BYTES */
1712 return s;
1716 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1717 plus a NUL byte at the end. Allocate an sdata structure for S, and
1718 set S->data to its `u.data' member. Store a NUL byte at the end of
1719 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1720 S->data if it was initially non-null. */
1722 void
1723 allocate_string_data (struct Lisp_String *s,
1724 EMACS_INT nchars, EMACS_INT nbytes)
1726 sdata *data, *old_data;
1727 struct sblock *b;
1728 ptrdiff_t needed, old_nbytes;
1730 if (STRING_BYTES_MAX < nbytes)
1731 string_overflow ();
1733 /* Determine the number of bytes needed to store NBYTES bytes
1734 of string data. */
1735 needed = SDATA_SIZE (nbytes);
1736 if (s->data)
1738 old_data = SDATA_OF_STRING (s);
1739 old_nbytes = STRING_BYTES (s);
1741 else
1742 old_data = NULL;
1744 MALLOC_BLOCK_INPUT;
1746 if (nbytes > LARGE_STRING_BYTES)
1748 size_t size = offsetof (struct sblock, data) + needed;
1750 #ifdef DOUG_LEA_MALLOC
1751 if (!mmap_lisp_allowed_p ())
1752 mallopt (M_MMAP_MAX, 0);
1753 #endif
1755 b = lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
1757 #ifdef DOUG_LEA_MALLOC
1758 if (!mmap_lisp_allowed_p ())
1759 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1760 #endif
1762 b->next_free = b->data;
1763 b->data[0].string = NULL;
1764 b->next = large_sblocks;
1765 large_sblocks = b;
1767 else if (current_sblock == NULL
1768 || (((char *) current_sblock + SBLOCK_SIZE
1769 - (char *) current_sblock->next_free)
1770 < (needed + GC_STRING_EXTRA)))
1772 /* Not enough room in the current sblock. */
1773 b = lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1774 b->next_free = b->data;
1775 b->data[0].string = NULL;
1776 b->next = NULL;
1778 if (current_sblock)
1779 current_sblock->next = b;
1780 else
1781 oldest_sblock = b;
1782 current_sblock = b;
1784 else
1785 b = current_sblock;
1787 data = b->next_free;
1788 b->next_free = (sdata *) ((char *) data + needed + GC_STRING_EXTRA);
1790 MALLOC_UNBLOCK_INPUT;
1792 data->string = s;
1793 s->data = SDATA_DATA (data);
1794 #ifdef GC_CHECK_STRING_BYTES
1795 SDATA_NBYTES (data) = nbytes;
1796 #endif
1797 s->size = nchars;
1798 s->size_byte = nbytes;
1799 s->data[nbytes] = '\0';
1800 #ifdef GC_CHECK_STRING_OVERRUN
1801 memcpy ((char *) data + needed, string_overrun_cookie,
1802 GC_STRING_OVERRUN_COOKIE_SIZE);
1803 #endif
1805 /* Note that Faset may call to this function when S has already data
1806 assigned. In this case, mark data as free by setting it's string
1807 back-pointer to null, and record the size of the data in it. */
1808 if (old_data)
1810 SDATA_NBYTES (old_data) = old_nbytes;
1811 old_data->string = NULL;
1814 consing_since_gc += needed;
1818 /* Sweep and compact strings. */
1820 static void
1821 sweep_strings (void)
1823 struct string_block *b, *next;
1824 struct string_block *live_blocks = NULL;
1826 string_free_list = NULL;
1827 total_strings = total_free_strings = 0;
1828 total_string_bytes = 0;
1830 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1831 for (b = string_blocks; b; b = next)
1833 int i, nfree = 0;
1834 struct Lisp_String *free_list_before = string_free_list;
1836 next = b->next;
1838 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
1840 struct Lisp_String *s = b->strings + i;
1842 if (s->data)
1844 /* String was not on free-list before. */
1845 if (STRING_MARKED_P (s))
1847 /* String is live; unmark it and its intervals. */
1848 UNMARK_STRING (s);
1850 /* Do not use string_(set|get)_intervals here. */
1851 s->intervals = balance_intervals (s->intervals);
1853 ++total_strings;
1854 total_string_bytes += STRING_BYTES (s);
1856 else
1858 /* String is dead. Put it on the free-list. */
1859 sdata *data = SDATA_OF_STRING (s);
1861 /* Save the size of S in its sdata so that we know
1862 how large that is. Reset the sdata's string
1863 back-pointer so that we know it's free. */
1864 #ifdef GC_CHECK_STRING_BYTES
1865 if (string_bytes (s) != SDATA_NBYTES (data))
1866 emacs_abort ();
1867 #else
1868 data->n.nbytes = STRING_BYTES (s);
1869 #endif
1870 data->string = NULL;
1872 /* Reset the strings's `data' member so that we
1873 know it's free. */
1874 s->data = NULL;
1876 /* Put the string on the free-list. */
1877 NEXT_FREE_LISP_STRING (s) = string_free_list;
1878 string_free_list = s;
1879 ++nfree;
1882 else
1884 /* S was on the free-list before. Put it there again. */
1885 NEXT_FREE_LISP_STRING (s) = string_free_list;
1886 string_free_list = s;
1887 ++nfree;
1891 /* Free blocks that contain free Lisp_Strings only, except
1892 the first two of them. */
1893 if (nfree == STRING_BLOCK_SIZE
1894 && total_free_strings > STRING_BLOCK_SIZE)
1896 lisp_free (b);
1897 string_free_list = free_list_before;
1899 else
1901 total_free_strings += nfree;
1902 b->next = live_blocks;
1903 live_blocks = b;
1907 check_string_free_list ();
1909 string_blocks = live_blocks;
1910 free_large_strings ();
1911 compact_small_strings ();
1913 check_string_free_list ();
1917 /* Free dead large strings. */
1919 static void
1920 free_large_strings (void)
1922 struct sblock *b, *next;
1923 struct sblock *live_blocks = NULL;
1925 for (b = large_sblocks; b; b = next)
1927 next = b->next;
1929 if (b->data[0].string == NULL)
1930 lisp_free (b);
1931 else
1933 b->next = live_blocks;
1934 live_blocks = b;
1938 large_sblocks = live_blocks;
1942 /* Compact data of small strings. Free sblocks that don't contain
1943 data of live strings after compaction. */
1945 static void
1946 compact_small_strings (void)
1948 struct sblock *b, *tb, *next;
1949 sdata *from, *to, *end, *tb_end;
1950 sdata *to_end, *from_end;
1952 /* TB is the sblock we copy to, TO is the sdata within TB we copy
1953 to, and TB_END is the end of TB. */
1954 tb = oldest_sblock;
1955 tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
1956 to = tb->data;
1958 /* Step through the blocks from the oldest to the youngest. We
1959 expect that old blocks will stabilize over time, so that less
1960 copying will happen this way. */
1961 for (b = oldest_sblock; b; b = b->next)
1963 end = b->next_free;
1964 eassert ((char *) end <= (char *) b + SBLOCK_SIZE);
1966 for (from = b->data; from < end; from = from_end)
1968 /* Compute the next FROM here because copying below may
1969 overwrite data we need to compute it. */
1970 ptrdiff_t nbytes;
1971 struct Lisp_String *s = from->string;
1973 #ifdef GC_CHECK_STRING_BYTES
1974 /* Check that the string size recorded in the string is the
1975 same as the one recorded in the sdata structure. */
1976 if (s && string_bytes (s) != SDATA_NBYTES (from))
1977 emacs_abort ();
1978 #endif /* GC_CHECK_STRING_BYTES */
1980 nbytes = s ? STRING_BYTES (s) : SDATA_NBYTES (from);
1981 eassert (nbytes <= LARGE_STRING_BYTES);
1983 nbytes = SDATA_SIZE (nbytes);
1984 from_end = (sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1986 #ifdef GC_CHECK_STRING_OVERRUN
1987 if (memcmp (string_overrun_cookie,
1988 (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
1989 GC_STRING_OVERRUN_COOKIE_SIZE))
1990 emacs_abort ();
1991 #endif
1993 /* Non-NULL S means it's alive. Copy its data. */
1994 if (s)
1996 /* If TB is full, proceed with the next sblock. */
1997 to_end = (sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
1998 if (to_end > tb_end)
2000 tb->next_free = to;
2001 tb = tb->next;
2002 tb_end = (sdata *) ((char *) tb + SBLOCK_SIZE);
2003 to = tb->data;
2004 to_end = (sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2007 /* Copy, and update the string's `data' pointer. */
2008 if (from != to)
2010 eassert (tb != b || to < from);
2011 memmove (to, from, nbytes + GC_STRING_EXTRA);
2012 to->string->data = SDATA_DATA (to);
2015 /* Advance past the sdata we copied to. */
2016 to = to_end;
2021 /* The rest of the sblocks following TB don't contain live data, so
2022 we can free them. */
2023 for (b = tb->next; b; b = next)
2025 next = b->next;
2026 lisp_free (b);
2029 tb->next_free = to;
2030 tb->next = NULL;
2031 current_sblock = tb;
2034 void
2035 string_overflow (void)
2037 error ("Maximum string size exceeded");
2040 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2041 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2042 LENGTH must be an integer.
2043 INIT must be an integer that represents a character. */)
2044 (Lisp_Object length, Lisp_Object init)
2046 register Lisp_Object val;
2047 int c;
2048 EMACS_INT nbytes;
2050 CHECK_NATNUM (length);
2051 CHECK_CHARACTER (init);
2053 c = XFASTINT (init);
2054 if (ASCII_CHAR_P (c))
2056 nbytes = XINT (length);
2057 val = make_uninit_string (nbytes);
2058 memset (SDATA (val), c, nbytes);
2059 SDATA (val)[nbytes] = 0;
2061 else
2063 unsigned char str[MAX_MULTIBYTE_LENGTH];
2064 ptrdiff_t len = CHAR_STRING (c, str);
2065 EMACS_INT string_len = XINT (length);
2066 unsigned char *p, *beg, *end;
2068 if (string_len > STRING_BYTES_MAX / len)
2069 string_overflow ();
2070 nbytes = len * string_len;
2071 val = make_uninit_multibyte_string (string_len, nbytes);
2072 for (beg = SDATA (val), p = beg, end = beg + nbytes; p < end; p += len)
2074 /* First time we just copy `str' to the data of `val'. */
2075 if (p == beg)
2076 memcpy (p, str, len);
2077 else
2079 /* Next time we copy largest possible chunk from
2080 initialized to uninitialized part of `val'. */
2081 len = min (p - beg, end - p);
2082 memcpy (p, beg, len);
2085 *p = 0;
2088 return val;
2091 /* Fill A with 1 bits if INIT is non-nil, and with 0 bits otherwise.
2092 Return A. */
2094 Lisp_Object
2095 bool_vector_fill (Lisp_Object a, Lisp_Object init)
2097 EMACS_INT nbits = bool_vector_size (a);
2098 if (0 < nbits)
2100 unsigned char *data = bool_vector_uchar_data (a);
2101 int pattern = NILP (init) ? 0 : (1 << BOOL_VECTOR_BITS_PER_CHAR) - 1;
2102 ptrdiff_t nbytes = bool_vector_bytes (nbits);
2103 int last_mask = ~ (~0 << ((nbits - 1) % BOOL_VECTOR_BITS_PER_CHAR + 1));
2104 memset (data, pattern, nbytes - 1);
2105 data[nbytes - 1] = pattern & last_mask;
2107 return a;
2110 /* Return a newly allocated, uninitialized bool vector of size NBITS. */
2112 Lisp_Object
2113 make_uninit_bool_vector (EMACS_INT nbits)
2115 Lisp_Object val;
2116 EMACS_INT words = bool_vector_words (nbits);
2117 EMACS_INT word_bytes = words * sizeof (bits_word);
2118 EMACS_INT needed_elements = ((bool_header_size - header_size + word_bytes
2119 + word_size - 1)
2120 / word_size);
2121 struct Lisp_Bool_Vector *p
2122 = (struct Lisp_Bool_Vector *) allocate_vector (needed_elements);
2123 XSETVECTOR (val, p);
2124 XSETPVECTYPESIZE (XVECTOR (val), PVEC_BOOL_VECTOR, 0, 0);
2125 p->size = nbits;
2127 /* Clear padding at the end. */
2128 if (words)
2129 p->data[words - 1] = 0;
2131 return val;
2134 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2135 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2136 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2137 (Lisp_Object length, Lisp_Object init)
2139 Lisp_Object val;
2141 CHECK_NATNUM (length);
2142 val = make_uninit_bool_vector (XFASTINT (length));
2143 return bool_vector_fill (val, init);
2147 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2148 of characters from the contents. This string may be unibyte or
2149 multibyte, depending on the contents. */
2151 Lisp_Object
2152 make_string (const char *contents, ptrdiff_t nbytes)
2154 register Lisp_Object val;
2155 ptrdiff_t nchars, multibyte_nbytes;
2157 parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
2158 &nchars, &multibyte_nbytes);
2159 if (nbytes == nchars || nbytes != multibyte_nbytes)
2160 /* CONTENTS contains no multibyte sequences or contains an invalid
2161 multibyte sequence. We must make unibyte string. */
2162 val = make_unibyte_string (contents, nbytes);
2163 else
2164 val = make_multibyte_string (contents, nchars, nbytes);
2165 return val;
2169 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
2171 Lisp_Object
2172 make_unibyte_string (const char *contents, ptrdiff_t length)
2174 register Lisp_Object val;
2175 val = make_uninit_string (length);
2176 memcpy (SDATA (val), contents, length);
2177 return val;
2181 /* Make a multibyte string from NCHARS characters occupying NBYTES
2182 bytes at CONTENTS. */
2184 Lisp_Object
2185 make_multibyte_string (const char *contents,
2186 ptrdiff_t nchars, ptrdiff_t nbytes)
2188 register Lisp_Object val;
2189 val = make_uninit_multibyte_string (nchars, nbytes);
2190 memcpy (SDATA (val), contents, nbytes);
2191 return val;
2195 /* Make a string from NCHARS characters occupying NBYTES bytes at
2196 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2198 Lisp_Object
2199 make_string_from_bytes (const char *contents,
2200 ptrdiff_t nchars, ptrdiff_t nbytes)
2202 register Lisp_Object val;
2203 val = make_uninit_multibyte_string (nchars, nbytes);
2204 memcpy (SDATA (val), contents, nbytes);
2205 if (SBYTES (val) == SCHARS (val))
2206 STRING_SET_UNIBYTE (val);
2207 return val;
2211 /* Make a string from NCHARS characters occupying NBYTES bytes at
2212 CONTENTS. The argument MULTIBYTE controls whether to label the
2213 string as multibyte. If NCHARS is negative, it counts the number of
2214 characters by itself. */
2216 Lisp_Object
2217 make_specified_string (const char *contents,
2218 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
2220 Lisp_Object val;
2222 if (nchars < 0)
2224 if (multibyte)
2225 nchars = multibyte_chars_in_text ((const unsigned char *) contents,
2226 nbytes);
2227 else
2228 nchars = nbytes;
2230 val = make_uninit_multibyte_string (nchars, nbytes);
2231 memcpy (SDATA (val), contents, nbytes);
2232 if (!multibyte)
2233 STRING_SET_UNIBYTE (val);
2234 return val;
2238 /* Return an unibyte Lisp_String set up to hold LENGTH characters
2239 occupying LENGTH bytes. */
2241 Lisp_Object
2242 make_uninit_string (EMACS_INT length)
2244 Lisp_Object val;
2246 if (!length)
2247 return empty_unibyte_string;
2248 val = make_uninit_multibyte_string (length, length);
2249 STRING_SET_UNIBYTE (val);
2250 return val;
2254 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2255 which occupy NBYTES bytes. */
2257 Lisp_Object
2258 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2260 Lisp_Object string;
2261 struct Lisp_String *s;
2263 if (nchars < 0)
2264 emacs_abort ();
2265 if (!nbytes)
2266 return empty_multibyte_string;
2268 s = allocate_string ();
2269 s->intervals = NULL;
2270 allocate_string_data (s, nchars, nbytes);
2271 XSETSTRING (string, s);
2272 string_chars_consed += nbytes;
2273 return string;
2276 /* Print arguments to BUF according to a FORMAT, then return
2277 a Lisp_String initialized with the data from BUF. */
2279 Lisp_Object
2280 make_formatted_string (char *buf, const char *format, ...)
2282 va_list ap;
2283 int length;
2285 va_start (ap, format);
2286 length = vsprintf (buf, format, ap);
2287 va_end (ap);
2288 return make_string (buf, length);
2292 /***********************************************************************
2293 Float Allocation
2294 ***********************************************************************/
2296 /* We store float cells inside of float_blocks, allocating a new
2297 float_block with malloc whenever necessary. Float cells reclaimed
2298 by GC are put on a free list to be reallocated before allocating
2299 any new float cells from the latest float_block. */
2301 #define FLOAT_BLOCK_SIZE \
2302 (((BLOCK_BYTES - sizeof (struct float_block *) \
2303 /* The compiler might add padding at the end. */ \
2304 - (sizeof (struct Lisp_Float) - sizeof (int))) * CHAR_BIT) \
2305 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2307 #define GETMARKBIT(block,n) \
2308 (((block)->gcmarkbits[(n) / (sizeof (int) * CHAR_BIT)] \
2309 >> ((n) % (sizeof (int) * CHAR_BIT))) \
2310 & 1)
2312 #define SETMARKBIT(block,n) \
2313 (block)->gcmarkbits[(n) / (sizeof (int) * CHAR_BIT)] \
2314 |= 1 << ((n) % (sizeof (int) * CHAR_BIT))
2316 #define UNSETMARKBIT(block,n) \
2317 (block)->gcmarkbits[(n) / (sizeof (int) * CHAR_BIT)] \
2318 &= ~(1 << ((n) % (sizeof (int) * CHAR_BIT)))
2320 #define FLOAT_BLOCK(fptr) \
2321 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2323 #define FLOAT_INDEX(fptr) \
2324 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2326 struct float_block
2328 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2329 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2330 int gcmarkbits[1 + FLOAT_BLOCK_SIZE / (sizeof (int) * CHAR_BIT)];
2331 struct float_block *next;
2334 #define FLOAT_MARKED_P(fptr) \
2335 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2337 #define FLOAT_MARK(fptr) \
2338 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2340 #define FLOAT_UNMARK(fptr) \
2341 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2343 /* Current float_block. */
2345 static struct float_block *float_block;
2347 /* Index of first unused Lisp_Float in the current float_block. */
2349 static int float_block_index = FLOAT_BLOCK_SIZE;
2351 /* Free-list of Lisp_Floats. */
2353 static struct Lisp_Float *float_free_list;
2355 /* Return a new float object with value FLOAT_VALUE. */
2357 Lisp_Object
2358 make_float (double float_value)
2360 register Lisp_Object val;
2362 MALLOC_BLOCK_INPUT;
2364 if (float_free_list)
2366 /* We use the data field for chaining the free list
2367 so that we won't use the same field that has the mark bit. */
2368 XSETFLOAT (val, float_free_list);
2369 float_free_list = float_free_list->u.chain;
2371 else
2373 if (float_block_index == FLOAT_BLOCK_SIZE)
2375 struct float_block *new
2376 = lisp_align_malloc (sizeof *new, MEM_TYPE_FLOAT);
2377 new->next = float_block;
2378 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2379 float_block = new;
2380 float_block_index = 0;
2381 total_free_floats += FLOAT_BLOCK_SIZE;
2383 XSETFLOAT (val, &float_block->floats[float_block_index]);
2384 float_block_index++;
2387 MALLOC_UNBLOCK_INPUT;
2389 XFLOAT_INIT (val, float_value);
2390 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2391 consing_since_gc += sizeof (struct Lisp_Float);
2392 floats_consed++;
2393 total_free_floats--;
2394 return val;
2399 /***********************************************************************
2400 Cons Allocation
2401 ***********************************************************************/
2403 /* We store cons cells inside of cons_blocks, allocating a new
2404 cons_block with malloc whenever necessary. Cons cells reclaimed by
2405 GC are put on a free list to be reallocated before allocating
2406 any new cons cells from the latest cons_block. */
2408 #define CONS_BLOCK_SIZE \
2409 (((BLOCK_BYTES - sizeof (struct cons_block *) \
2410 /* The compiler might add padding at the end. */ \
2411 - (sizeof (struct Lisp_Cons) - sizeof (int))) * CHAR_BIT) \
2412 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2414 #define CONS_BLOCK(fptr) \
2415 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2417 #define CONS_INDEX(fptr) \
2418 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2420 struct cons_block
2422 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2423 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2424 int gcmarkbits[1 + CONS_BLOCK_SIZE / (sizeof (int) * CHAR_BIT)];
2425 struct cons_block *next;
2428 #define CONS_MARKED_P(fptr) \
2429 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2431 #define CONS_MARK(fptr) \
2432 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2434 #define CONS_UNMARK(fptr) \
2435 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2437 /* Current cons_block. */
2439 static struct cons_block *cons_block;
2441 /* Index of first unused Lisp_Cons in the current block. */
2443 static int cons_block_index = CONS_BLOCK_SIZE;
2445 /* Free-list of Lisp_Cons structures. */
2447 static struct Lisp_Cons *cons_free_list;
2449 /* Explicitly free a cons cell by putting it on the free-list. */
2451 void
2452 free_cons (struct Lisp_Cons *ptr)
2454 ptr->u.chain = cons_free_list;
2455 #if GC_MARK_STACK
2456 ptr->car = Vdead;
2457 #endif
2458 cons_free_list = ptr;
2459 consing_since_gc -= sizeof *ptr;
2460 total_free_conses++;
2463 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2464 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2465 (Lisp_Object car, Lisp_Object cdr)
2467 register Lisp_Object val;
2469 MALLOC_BLOCK_INPUT;
2471 if (cons_free_list)
2473 /* We use the cdr for chaining the free list
2474 so that we won't use the same field that has the mark bit. */
2475 XSETCONS (val, cons_free_list);
2476 cons_free_list = cons_free_list->u.chain;
2478 else
2480 if (cons_block_index == CONS_BLOCK_SIZE)
2482 struct cons_block *new
2483 = lisp_align_malloc (sizeof *new, MEM_TYPE_CONS);
2484 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2485 new->next = cons_block;
2486 cons_block = new;
2487 cons_block_index = 0;
2488 total_free_conses += CONS_BLOCK_SIZE;
2490 XSETCONS (val, &cons_block->conses[cons_block_index]);
2491 cons_block_index++;
2494 MALLOC_UNBLOCK_INPUT;
2496 XSETCAR (val, car);
2497 XSETCDR (val, cdr);
2498 eassert (!CONS_MARKED_P (XCONS (val)));
2499 consing_since_gc += sizeof (struct Lisp_Cons);
2500 total_free_conses--;
2501 cons_cells_consed++;
2502 return val;
2505 #ifdef GC_CHECK_CONS_LIST
2506 /* Get an error now if there's any junk in the cons free list. */
2507 void
2508 check_cons_list (void)
2510 struct Lisp_Cons *tail = cons_free_list;
2512 while (tail)
2513 tail = tail->u.chain;
2515 #endif
2517 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2519 Lisp_Object
2520 list1 (Lisp_Object arg1)
2522 return Fcons (arg1, Qnil);
2525 Lisp_Object
2526 list2 (Lisp_Object arg1, Lisp_Object arg2)
2528 return Fcons (arg1, Fcons (arg2, Qnil));
2532 Lisp_Object
2533 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2535 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2539 Lisp_Object
2540 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2542 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2546 Lisp_Object
2547 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2549 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2550 Fcons (arg5, Qnil)))));
2553 /* Make a list of COUNT Lisp_Objects, where ARG is the
2554 first one. Allocate conses from pure space if TYPE
2555 is CONSTYPE_PURE, or allocate as usual if type is CONSTYPE_HEAP. */
2557 Lisp_Object
2558 listn (enum constype type, ptrdiff_t count, Lisp_Object arg, ...)
2560 va_list ap;
2561 ptrdiff_t i;
2562 Lisp_Object val, *objp;
2564 /* Change to SAFE_ALLOCA if you hit this eassert. */
2565 eassert (count <= MAX_ALLOCA / word_size);
2567 objp = alloca (count * word_size);
2568 objp[0] = arg;
2569 va_start (ap, arg);
2570 for (i = 1; i < count; i++)
2571 objp[i] = va_arg (ap, Lisp_Object);
2572 va_end (ap);
2574 for (val = Qnil, i = count - 1; i >= 0; i--)
2576 if (type == CONSTYPE_PURE)
2577 val = pure_cons (objp[i], val);
2578 else if (type == CONSTYPE_HEAP)
2579 val = Fcons (objp[i], val);
2580 else
2581 emacs_abort ();
2583 return val;
2586 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2587 doc: /* Return a newly created list with specified arguments as elements.
2588 Any number of arguments, even zero arguments, are allowed.
2589 usage: (list &rest OBJECTS) */)
2590 (ptrdiff_t nargs, Lisp_Object *args)
2592 register Lisp_Object val;
2593 val = Qnil;
2595 while (nargs > 0)
2597 nargs--;
2598 val = Fcons (args[nargs], val);
2600 return val;
2604 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2605 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2606 (register Lisp_Object length, Lisp_Object init)
2608 register Lisp_Object val;
2609 register EMACS_INT size;
2611 CHECK_NATNUM (length);
2612 size = XFASTINT (length);
2614 val = Qnil;
2615 while (size > 0)
2617 val = Fcons (init, val);
2618 --size;
2620 if (size > 0)
2622 val = Fcons (init, val);
2623 --size;
2625 if (size > 0)
2627 val = Fcons (init, val);
2628 --size;
2630 if (size > 0)
2632 val = Fcons (init, val);
2633 --size;
2635 if (size > 0)
2637 val = Fcons (init, val);
2638 --size;
2644 QUIT;
2647 return val;
2652 /***********************************************************************
2653 Vector Allocation
2654 ***********************************************************************/
2656 /* Sometimes a vector's contents are merely a pointer internally used
2657 in vector allocation code. Usually you don't want to touch this. */
2659 static struct Lisp_Vector *
2660 next_vector (struct Lisp_Vector *v)
2662 return XUNTAG (v->contents[0], 0);
2665 static void
2666 set_next_vector (struct Lisp_Vector *v, struct Lisp_Vector *p)
2668 v->contents[0] = make_lisp_ptr (p, 0);
2671 /* This value is balanced well enough to avoid too much internal overhead
2672 for the most common cases; it's not required to be a power of two, but
2673 it's expected to be a mult-of-ROUNDUP_SIZE (see below). */
2675 #define VECTOR_BLOCK_SIZE 4096
2677 enum
2679 /* Alignment of struct Lisp_Vector objects. */
2680 vector_alignment = COMMON_MULTIPLE (ALIGNOF_STRUCT_LISP_VECTOR,
2681 USE_LSB_TAG ? GCALIGNMENT : 1),
2683 /* Vector size requests are a multiple of this. */
2684 roundup_size = COMMON_MULTIPLE (vector_alignment, word_size)
2687 /* Verify assumptions described above. */
2688 verify ((VECTOR_BLOCK_SIZE % roundup_size) == 0);
2689 verify (VECTOR_BLOCK_SIZE <= (1 << PSEUDOVECTOR_SIZE_BITS));
2691 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at compile time. */
2692 #define vroundup_ct(x) ROUNDUP (x, roundup_size)
2693 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at runtime. */
2694 #define vroundup(x) (eassume ((x) >= 0), vroundup_ct (x))
2696 /* Rounding helps to maintain alignment constraints if USE_LSB_TAG. */
2698 #define VECTOR_BLOCK_BYTES (VECTOR_BLOCK_SIZE - vroundup_ct (sizeof (void *)))
2700 /* Size of the minimal vector allocated from block. */
2702 #define VBLOCK_BYTES_MIN vroundup_ct (header_size + sizeof (Lisp_Object))
2704 /* Size of the largest vector allocated from block. */
2706 #define VBLOCK_BYTES_MAX \
2707 vroundup ((VECTOR_BLOCK_BYTES / 2) - word_size)
2709 /* We maintain one free list for each possible block-allocated
2710 vector size, and this is the number of free lists we have. */
2712 #define VECTOR_MAX_FREE_LIST_INDEX \
2713 ((VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN) / roundup_size + 1)
2715 /* Common shortcut to advance vector pointer over a block data. */
2717 #define ADVANCE(v, nbytes) ((struct Lisp_Vector *) ((char *) (v) + (nbytes)))
2719 /* Common shortcut to calculate NBYTES-vector index in VECTOR_FREE_LISTS. */
2721 #define VINDEX(nbytes) (((nbytes) - VBLOCK_BYTES_MIN) / roundup_size)
2723 /* Common shortcut to setup vector on a free list. */
2725 #define SETUP_ON_FREE_LIST(v, nbytes, tmp) \
2726 do { \
2727 (tmp) = ((nbytes - header_size) / word_size); \
2728 XSETPVECTYPESIZE (v, PVEC_FREE, 0, (tmp)); \
2729 eassert ((nbytes) % roundup_size == 0); \
2730 (tmp) = VINDEX (nbytes); \
2731 eassert ((tmp) < VECTOR_MAX_FREE_LIST_INDEX); \
2732 set_next_vector (v, vector_free_lists[tmp]); \
2733 vector_free_lists[tmp] = (v); \
2734 total_free_vector_slots += (nbytes) / word_size; \
2735 } while (0)
2737 /* This internal type is used to maintain the list of large vectors
2738 which are allocated at their own, e.g. outside of vector blocks.
2740 struct large_vector itself cannot contain a struct Lisp_Vector, as
2741 the latter contains a flexible array member and C99 does not allow
2742 such structs to be nested. Instead, each struct large_vector
2743 object LV is followed by a struct Lisp_Vector, which is at offset
2744 large_vector_offset from LV, and whose address is therefore
2745 large_vector_vec (&LV). */
2747 struct large_vector
2749 struct large_vector *next;
2752 enum
2754 large_vector_offset = ROUNDUP (sizeof (struct large_vector), vector_alignment)
2757 static struct Lisp_Vector *
2758 large_vector_vec (struct large_vector *p)
2760 return (struct Lisp_Vector *) ((char *) p + large_vector_offset);
2763 /* This internal type is used to maintain an underlying storage
2764 for small vectors. */
2766 struct vector_block
2768 char data[VECTOR_BLOCK_BYTES];
2769 struct vector_block *next;
2772 /* Chain of vector blocks. */
2774 static struct vector_block *vector_blocks;
2776 /* Vector free lists, where NTH item points to a chain of free
2777 vectors of the same NBYTES size, so NTH == VINDEX (NBYTES). */
2779 static struct Lisp_Vector *vector_free_lists[VECTOR_MAX_FREE_LIST_INDEX];
2781 /* Singly-linked list of large vectors. */
2783 static struct large_vector *large_vectors;
2785 /* The only vector with 0 slots, allocated from pure space. */
2787 Lisp_Object zero_vector;
2789 /* Number of live vectors. */
2791 static EMACS_INT total_vectors;
2793 /* Total size of live and free vectors, in Lisp_Object units. */
2795 static EMACS_INT total_vector_slots, total_free_vector_slots;
2797 /* Get a new vector block. */
2799 static struct vector_block *
2800 allocate_vector_block (void)
2802 struct vector_block *block = xmalloc (sizeof *block);
2804 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
2805 mem_insert (block->data, block->data + VECTOR_BLOCK_BYTES,
2806 MEM_TYPE_VECTOR_BLOCK);
2807 #endif
2809 block->next = vector_blocks;
2810 vector_blocks = block;
2811 return block;
2814 /* Called once to initialize vector allocation. */
2816 static void
2817 init_vectors (void)
2819 zero_vector = make_pure_vector (0);
2822 /* Allocate vector from a vector block. */
2824 static struct Lisp_Vector *
2825 allocate_vector_from_block (size_t nbytes)
2827 struct Lisp_Vector *vector;
2828 struct vector_block *block;
2829 size_t index, restbytes;
2831 eassert (VBLOCK_BYTES_MIN <= nbytes && nbytes <= VBLOCK_BYTES_MAX);
2832 eassert (nbytes % roundup_size == 0);
2834 /* First, try to allocate from a free list
2835 containing vectors of the requested size. */
2836 index = VINDEX (nbytes);
2837 if (vector_free_lists[index])
2839 vector = vector_free_lists[index];
2840 vector_free_lists[index] = next_vector (vector);
2841 total_free_vector_slots -= nbytes / word_size;
2842 return vector;
2845 /* Next, check free lists containing larger vectors. Since
2846 we will split the result, we should have remaining space
2847 large enough to use for one-slot vector at least. */
2848 for (index = VINDEX (nbytes + VBLOCK_BYTES_MIN);
2849 index < VECTOR_MAX_FREE_LIST_INDEX; index++)
2850 if (vector_free_lists[index])
2852 /* This vector is larger than requested. */
2853 vector = vector_free_lists[index];
2854 vector_free_lists[index] = next_vector (vector);
2855 total_free_vector_slots -= nbytes / word_size;
2857 /* Excess bytes are used for the smaller vector,
2858 which should be set on an appropriate free list. */
2859 restbytes = index * roundup_size + VBLOCK_BYTES_MIN - nbytes;
2860 eassert (restbytes % roundup_size == 0);
2861 SETUP_ON_FREE_LIST (ADVANCE (vector, nbytes), restbytes, index);
2862 return vector;
2865 /* Finally, need a new vector block. */
2866 block = allocate_vector_block ();
2868 /* New vector will be at the beginning of this block. */
2869 vector = (struct Lisp_Vector *) block->data;
2871 /* If the rest of space from this block is large enough
2872 for one-slot vector at least, set up it on a free list. */
2873 restbytes = VECTOR_BLOCK_BYTES - nbytes;
2874 if (restbytes >= VBLOCK_BYTES_MIN)
2876 eassert (restbytes % roundup_size == 0);
2877 SETUP_ON_FREE_LIST (ADVANCE (vector, nbytes), restbytes, index);
2879 return vector;
2882 /* Nonzero if VECTOR pointer is valid pointer inside BLOCK. */
2884 #define VECTOR_IN_BLOCK(vector, block) \
2885 ((char *) (vector) <= (block)->data \
2886 + VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN)
2888 /* Return the memory footprint of V in bytes. */
2890 static ptrdiff_t
2891 vector_nbytes (struct Lisp_Vector *v)
2893 ptrdiff_t size = v->header.size & ~ARRAY_MARK_FLAG;
2894 ptrdiff_t nwords;
2896 if (size & PSEUDOVECTOR_FLAG)
2898 if (PSEUDOVECTOR_TYPEP (&v->header, PVEC_BOOL_VECTOR))
2900 struct Lisp_Bool_Vector *bv = (struct Lisp_Bool_Vector *) v;
2901 ptrdiff_t word_bytes = (bool_vector_words (bv->size)
2902 * sizeof (bits_word));
2903 ptrdiff_t boolvec_bytes = bool_header_size + word_bytes;
2904 verify (header_size <= bool_header_size);
2905 nwords = (boolvec_bytes - header_size + word_size - 1) / word_size;
2907 else
2908 nwords = ((size & PSEUDOVECTOR_SIZE_MASK)
2909 + ((size & PSEUDOVECTOR_REST_MASK)
2910 >> PSEUDOVECTOR_SIZE_BITS));
2912 else
2913 nwords = size;
2914 return vroundup (header_size + word_size * nwords);
2917 /* Release extra resources still in use by VECTOR, which may be any
2918 vector-like object. For now, this is used just to free data in
2919 font objects. */
2921 static void
2922 cleanup_vector (struct Lisp_Vector *vector)
2924 if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FONT)
2925 && ((vector->header.size & PSEUDOVECTOR_SIZE_MASK)
2926 == FONT_OBJECT_MAX))
2928 /* Attempt to catch subtle bugs like Bug#16140. */
2929 eassert (valid_font_driver (((struct font *) vector)->driver));
2930 ((struct font *) vector)->driver->close ((struct font *) vector);
2934 /* Reclaim space used by unmarked vectors. */
2936 static void
2937 sweep_vectors (void)
2939 struct vector_block *block, **bprev = &vector_blocks;
2940 struct large_vector *lv, **lvprev = &large_vectors;
2941 struct Lisp_Vector *vector, *next;
2943 total_vectors = total_vector_slots = total_free_vector_slots = 0;
2944 memset (vector_free_lists, 0, sizeof (vector_free_lists));
2946 /* Looking through vector blocks. */
2948 for (block = vector_blocks; block; block = *bprev)
2950 bool free_this_block = 0;
2951 ptrdiff_t nbytes;
2953 for (vector = (struct Lisp_Vector *) block->data;
2954 VECTOR_IN_BLOCK (vector, block); vector = next)
2956 if (VECTOR_MARKED_P (vector))
2958 VECTOR_UNMARK (vector);
2959 total_vectors++;
2960 nbytes = vector_nbytes (vector);
2961 total_vector_slots += nbytes / word_size;
2962 next = ADVANCE (vector, nbytes);
2964 else
2966 ptrdiff_t total_bytes;
2968 cleanup_vector (vector);
2969 nbytes = vector_nbytes (vector);
2970 total_bytes = nbytes;
2971 next = ADVANCE (vector, nbytes);
2973 /* While NEXT is not marked, try to coalesce with VECTOR,
2974 thus making VECTOR of the largest possible size. */
2976 while (VECTOR_IN_BLOCK (next, block))
2978 if (VECTOR_MARKED_P (next))
2979 break;
2980 cleanup_vector (next);
2981 nbytes = vector_nbytes (next);
2982 total_bytes += nbytes;
2983 next = ADVANCE (next, nbytes);
2986 eassert (total_bytes % roundup_size == 0);
2988 if (vector == (struct Lisp_Vector *) block->data
2989 && !VECTOR_IN_BLOCK (next, block))
2990 /* This block should be freed because all of it's
2991 space was coalesced into the only free vector. */
2992 free_this_block = 1;
2993 else
2995 size_t tmp;
2996 SETUP_ON_FREE_LIST (vector, total_bytes, tmp);
3001 if (free_this_block)
3003 *bprev = block->next;
3004 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
3005 mem_delete (mem_find (block->data));
3006 #endif
3007 xfree (block);
3009 else
3010 bprev = &block->next;
3013 /* Sweep large vectors. */
3015 for (lv = large_vectors; lv; lv = *lvprev)
3017 vector = large_vector_vec (lv);
3018 if (VECTOR_MARKED_P (vector))
3020 VECTOR_UNMARK (vector);
3021 total_vectors++;
3022 if (vector->header.size & PSEUDOVECTOR_FLAG)
3024 /* All non-bool pseudovectors are small enough to be allocated
3025 from vector blocks. This code should be redesigned if some
3026 pseudovector type grows beyond VBLOCK_BYTES_MAX. */
3027 eassert (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_BOOL_VECTOR));
3028 total_vector_slots += vector_nbytes (vector) / word_size;
3030 else
3031 total_vector_slots
3032 += header_size / word_size + vector->header.size;
3033 lvprev = &lv->next;
3035 else
3037 *lvprev = lv->next;
3038 lisp_free (lv);
3043 /* Value is a pointer to a newly allocated Lisp_Vector structure
3044 with room for LEN Lisp_Objects. */
3046 static struct Lisp_Vector *
3047 allocate_vectorlike (ptrdiff_t len)
3049 struct Lisp_Vector *p;
3051 MALLOC_BLOCK_INPUT;
3053 if (len == 0)
3054 p = XVECTOR (zero_vector);
3055 else
3057 size_t nbytes = header_size + len * word_size;
3059 #ifdef DOUG_LEA_MALLOC
3060 if (!mmap_lisp_allowed_p ())
3061 mallopt (M_MMAP_MAX, 0);
3062 #endif
3064 if (nbytes <= VBLOCK_BYTES_MAX)
3065 p = allocate_vector_from_block (vroundup (nbytes));
3066 else
3068 struct large_vector *lv
3069 = lisp_malloc ((large_vector_offset + header_size
3070 + len * word_size),
3071 MEM_TYPE_VECTORLIKE);
3072 lv->next = large_vectors;
3073 large_vectors = lv;
3074 p = large_vector_vec (lv);
3077 #ifdef DOUG_LEA_MALLOC
3078 if (!mmap_lisp_allowed_p ())
3079 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
3080 #endif
3082 consing_since_gc += nbytes;
3083 vector_cells_consed += len;
3086 MALLOC_UNBLOCK_INPUT;
3088 return p;
3092 /* Allocate a vector with LEN slots. */
3094 struct Lisp_Vector *
3095 allocate_vector (EMACS_INT len)
3097 struct Lisp_Vector *v;
3098 ptrdiff_t nbytes_max = min (PTRDIFF_MAX, SIZE_MAX);
3100 if (min ((nbytes_max - header_size) / word_size, MOST_POSITIVE_FIXNUM) < len)
3101 memory_full (SIZE_MAX);
3102 v = allocate_vectorlike (len);
3103 v->header.size = len;
3104 return v;
3108 /* Allocate other vector-like structures. */
3110 struct Lisp_Vector *
3111 allocate_pseudovector (int memlen, int lisplen, enum pvec_type tag)
3113 struct Lisp_Vector *v = allocate_vectorlike (memlen);
3114 int i;
3116 /* Catch bogus values. */
3117 eassert (tag <= PVEC_FONT);
3118 eassert (memlen - lisplen <= (1 << PSEUDOVECTOR_REST_BITS) - 1);
3119 eassert (lisplen <= (1 << PSEUDOVECTOR_SIZE_BITS) - 1);
3121 /* Only the first lisplen slots will be traced normally by the GC. */
3122 for (i = 0; i < lisplen; ++i)
3123 v->contents[i] = Qnil;
3125 XSETPVECTYPESIZE (v, tag, lisplen, memlen - lisplen);
3126 return v;
3129 struct buffer *
3130 allocate_buffer (void)
3132 struct buffer *b = lisp_malloc (sizeof *b, MEM_TYPE_BUFFER);
3134 BUFFER_PVEC_INIT (b);
3135 /* Put B on the chain of all buffers including killed ones. */
3136 b->next = all_buffers;
3137 all_buffers = b;
3138 /* Note that the rest fields of B are not initialized. */
3139 return b;
3142 struct Lisp_Hash_Table *
3143 allocate_hash_table (void)
3145 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table, count, PVEC_HASH_TABLE);
3148 struct window *
3149 allocate_window (void)
3151 struct window *w;
3153 w = ALLOCATE_PSEUDOVECTOR (struct window, current_matrix, PVEC_WINDOW);
3154 /* Users assumes that non-Lisp data is zeroed. */
3155 memset (&w->current_matrix, 0,
3156 sizeof (*w) - offsetof (struct window, current_matrix));
3157 return w;
3160 struct terminal *
3161 allocate_terminal (void)
3163 struct terminal *t;
3165 t = ALLOCATE_PSEUDOVECTOR (struct terminal, next_terminal, PVEC_TERMINAL);
3166 /* Users assumes that non-Lisp data is zeroed. */
3167 memset (&t->next_terminal, 0,
3168 sizeof (*t) - offsetof (struct terminal, next_terminal));
3169 return t;
3172 struct frame *
3173 allocate_frame (void)
3175 struct frame *f;
3177 f = ALLOCATE_PSEUDOVECTOR (struct frame, face_cache, PVEC_FRAME);
3178 /* Users assumes that non-Lisp data is zeroed. */
3179 memset (&f->face_cache, 0,
3180 sizeof (*f) - offsetof (struct frame, face_cache));
3181 return f;
3184 struct Lisp_Process *
3185 allocate_process (void)
3187 struct Lisp_Process *p;
3189 p = ALLOCATE_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
3190 /* Users assumes that non-Lisp data is zeroed. */
3191 memset (&p->pid, 0,
3192 sizeof (*p) - offsetof (struct Lisp_Process, pid));
3193 return p;
3196 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
3197 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
3198 See also the function `vector'. */)
3199 (register Lisp_Object length, Lisp_Object init)
3201 Lisp_Object vector;
3202 register ptrdiff_t sizei;
3203 register ptrdiff_t i;
3204 register struct Lisp_Vector *p;
3206 CHECK_NATNUM (length);
3208 p = allocate_vector (XFASTINT (length));
3209 sizei = XFASTINT (length);
3210 for (i = 0; i < sizei; i++)
3211 p->contents[i] = init;
3213 XSETVECTOR (vector, p);
3214 return vector;
3218 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3219 doc: /* Return a newly created vector with specified arguments as elements.
3220 Any number of arguments, even zero arguments, are allowed.
3221 usage: (vector &rest OBJECTS) */)
3222 (ptrdiff_t nargs, Lisp_Object *args)
3224 ptrdiff_t i;
3225 register Lisp_Object val = make_uninit_vector (nargs);
3226 register struct Lisp_Vector *p = XVECTOR (val);
3228 for (i = 0; i < nargs; i++)
3229 p->contents[i] = args[i];
3230 return val;
3233 void
3234 make_byte_code (struct Lisp_Vector *v)
3236 /* Don't allow the global zero_vector to become a byte code object. */
3237 eassert (0 < v->header.size);
3239 if (v->header.size > 1 && STRINGP (v->contents[1])
3240 && STRING_MULTIBYTE (v->contents[1]))
3241 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3242 earlier because they produced a raw 8-bit string for byte-code
3243 and now such a byte-code string is loaded as multibyte while
3244 raw 8-bit characters converted to multibyte form. Thus, now we
3245 must convert them back to the original unibyte form. */
3246 v->contents[1] = Fstring_as_unibyte (v->contents[1]);
3247 XSETPVECTYPE (v, PVEC_COMPILED);
3250 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3251 doc: /* Create a byte-code object with specified arguments as elements.
3252 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3253 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3254 and (optional) INTERACTIVE-SPEC.
3255 The first four arguments are required; at most six have any
3256 significance.
3257 The ARGLIST can be either like the one of `lambda', in which case the arguments
3258 will be dynamically bound before executing the byte code, or it can be an
3259 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3260 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3261 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3262 argument to catch the left-over arguments. If such an integer is used, the
3263 arguments will not be dynamically bound but will be instead pushed on the
3264 stack before executing the byte-code.
3265 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3266 (ptrdiff_t nargs, Lisp_Object *args)
3268 ptrdiff_t i;
3269 register Lisp_Object val = make_uninit_vector (nargs);
3270 register struct Lisp_Vector *p = XVECTOR (val);
3272 /* We used to purecopy everything here, if purify-flag was set. This worked
3273 OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
3274 dangerous, since make-byte-code is used during execution to build
3275 closures, so any closure built during the preload phase would end up
3276 copied into pure space, including its free variables, which is sometimes
3277 just wasteful and other times plainly wrong (e.g. those free vars may want
3278 to be setcar'd). */
3280 for (i = 0; i < nargs; i++)
3281 p->contents[i] = args[i];
3282 make_byte_code (p);
3283 XSETCOMPILED (val, p);
3284 return val;
3289 /***********************************************************************
3290 Symbol Allocation
3291 ***********************************************************************/
3293 /* Like struct Lisp_Symbol, but padded so that the size is a multiple
3294 of the required alignment if LSB tags are used. */
3296 union aligned_Lisp_Symbol
3298 struct Lisp_Symbol s;
3299 #if USE_LSB_TAG
3300 unsigned char c[(sizeof (struct Lisp_Symbol) + GCALIGNMENT - 1)
3301 & -GCALIGNMENT];
3302 #endif
3305 /* Each symbol_block is just under 1020 bytes long, since malloc
3306 really allocates in units of powers of two and uses 4 bytes for its
3307 own overhead. */
3309 #define SYMBOL_BLOCK_SIZE \
3310 ((1020 - sizeof (struct symbol_block *)) / sizeof (union aligned_Lisp_Symbol))
3312 struct symbol_block
3314 /* Place `symbols' first, to preserve alignment. */
3315 union aligned_Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3316 struct symbol_block *next;
3319 /* Current symbol block and index of first unused Lisp_Symbol
3320 structure in it. */
3322 static struct symbol_block *symbol_block;
3323 static int symbol_block_index = SYMBOL_BLOCK_SIZE;
3325 /* List of free symbols. */
3327 static struct Lisp_Symbol *symbol_free_list;
3329 static void
3330 set_symbol_name (Lisp_Object sym, Lisp_Object name)
3332 XSYMBOL (sym)->name = name;
3335 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3336 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3337 Its value is void, and its function definition and property list are nil. */)
3338 (Lisp_Object name)
3340 register Lisp_Object val;
3341 register struct Lisp_Symbol *p;
3343 CHECK_STRING (name);
3345 MALLOC_BLOCK_INPUT;
3347 if (symbol_free_list)
3349 XSETSYMBOL (val, symbol_free_list);
3350 symbol_free_list = symbol_free_list->next;
3352 else
3354 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3356 struct symbol_block *new
3357 = lisp_malloc (sizeof *new, MEM_TYPE_SYMBOL);
3358 new->next = symbol_block;
3359 symbol_block = new;
3360 symbol_block_index = 0;
3361 total_free_symbols += SYMBOL_BLOCK_SIZE;
3363 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index].s);
3364 symbol_block_index++;
3367 MALLOC_UNBLOCK_INPUT;
3369 p = XSYMBOL (val);
3370 set_symbol_name (val, name);
3371 set_symbol_plist (val, Qnil);
3372 p->redirect = SYMBOL_PLAINVAL;
3373 SET_SYMBOL_VAL (p, Qunbound);
3374 set_symbol_function (val, Qnil);
3375 set_symbol_next (val, NULL);
3376 p->gcmarkbit = 0;
3377 p->interned = SYMBOL_UNINTERNED;
3378 p->constant = 0;
3379 p->declared_special = 0;
3380 consing_since_gc += sizeof (struct Lisp_Symbol);
3381 symbols_consed++;
3382 total_free_symbols--;
3383 return val;
3388 /***********************************************************************
3389 Marker (Misc) Allocation
3390 ***********************************************************************/
3392 /* Like union Lisp_Misc, but padded so that its size is a multiple of
3393 the required alignment when LSB tags are used. */
3395 union aligned_Lisp_Misc
3397 union Lisp_Misc m;
3398 #if USE_LSB_TAG
3399 unsigned char c[(sizeof (union Lisp_Misc) + GCALIGNMENT - 1)
3400 & -GCALIGNMENT];
3401 #endif
3404 /* Allocation of markers and other objects that share that structure.
3405 Works like allocation of conses. */
3407 #define MARKER_BLOCK_SIZE \
3408 ((1020 - sizeof (struct marker_block *)) / sizeof (union aligned_Lisp_Misc))
3410 struct marker_block
3412 /* Place `markers' first, to preserve alignment. */
3413 union aligned_Lisp_Misc markers[MARKER_BLOCK_SIZE];
3414 struct marker_block *next;
3417 static struct marker_block *marker_block;
3418 static int marker_block_index = MARKER_BLOCK_SIZE;
3420 static union Lisp_Misc *marker_free_list;
3422 /* Return a newly allocated Lisp_Misc object of specified TYPE. */
3424 static Lisp_Object
3425 allocate_misc (enum Lisp_Misc_Type type)
3427 Lisp_Object val;
3429 MALLOC_BLOCK_INPUT;
3431 if (marker_free_list)
3433 XSETMISC (val, marker_free_list);
3434 marker_free_list = marker_free_list->u_free.chain;
3436 else
3438 if (marker_block_index == MARKER_BLOCK_SIZE)
3440 struct marker_block *new = lisp_malloc (sizeof *new, MEM_TYPE_MISC);
3441 new->next = marker_block;
3442 marker_block = new;
3443 marker_block_index = 0;
3444 total_free_markers += MARKER_BLOCK_SIZE;
3446 XSETMISC (val, &marker_block->markers[marker_block_index].m);
3447 marker_block_index++;
3450 MALLOC_UNBLOCK_INPUT;
3452 --total_free_markers;
3453 consing_since_gc += sizeof (union Lisp_Misc);
3454 misc_objects_consed++;
3455 XMISCANY (val)->type = type;
3456 XMISCANY (val)->gcmarkbit = 0;
3457 return val;
3460 /* Free a Lisp_Misc object. */
3462 void
3463 free_misc (Lisp_Object misc)
3465 XMISCANY (misc)->type = Lisp_Misc_Free;
3466 XMISC (misc)->u_free.chain = marker_free_list;
3467 marker_free_list = XMISC (misc);
3468 consing_since_gc -= sizeof (union Lisp_Misc);
3469 total_free_markers++;
3472 /* Verify properties of Lisp_Save_Value's representation
3473 that are assumed here and elsewhere. */
3475 verify (SAVE_UNUSED == 0);
3476 verify (((SAVE_INTEGER | SAVE_POINTER | SAVE_FUNCPOINTER | SAVE_OBJECT)
3477 >> SAVE_SLOT_BITS)
3478 == 0);
3480 /* Return Lisp_Save_Value objects for the various combinations
3481 that callers need. */
3483 Lisp_Object
3484 make_save_int_int_int (ptrdiff_t a, ptrdiff_t b, ptrdiff_t c)
3486 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3487 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3488 p->save_type = SAVE_TYPE_INT_INT_INT;
3489 p->data[0].integer = a;
3490 p->data[1].integer = b;
3491 p->data[2].integer = c;
3492 return val;
3495 Lisp_Object
3496 make_save_obj_obj_obj_obj (Lisp_Object a, Lisp_Object b, Lisp_Object c,
3497 Lisp_Object d)
3499 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3500 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3501 p->save_type = SAVE_TYPE_OBJ_OBJ_OBJ_OBJ;
3502 p->data[0].object = a;
3503 p->data[1].object = b;
3504 p->data[2].object = c;
3505 p->data[3].object = d;
3506 return val;
3509 Lisp_Object
3510 make_save_ptr (void *a)
3512 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3513 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3514 p->save_type = SAVE_POINTER;
3515 p->data[0].pointer = a;
3516 return val;
3519 Lisp_Object
3520 make_save_ptr_int (void *a, ptrdiff_t b)
3522 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3523 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3524 p->save_type = SAVE_TYPE_PTR_INT;
3525 p->data[0].pointer = a;
3526 p->data[1].integer = b;
3527 return val;
3530 #if ! (defined USE_X_TOOLKIT || defined USE_GTK)
3531 Lisp_Object
3532 make_save_ptr_ptr (void *a, void *b)
3534 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3535 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3536 p->save_type = SAVE_TYPE_PTR_PTR;
3537 p->data[0].pointer = a;
3538 p->data[1].pointer = b;
3539 return val;
3541 #endif
3543 Lisp_Object
3544 make_save_funcptr_ptr_obj (void (*a) (void), void *b, Lisp_Object c)
3546 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3547 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3548 p->save_type = SAVE_TYPE_FUNCPTR_PTR_OBJ;
3549 p->data[0].funcpointer = a;
3550 p->data[1].pointer = b;
3551 p->data[2].object = c;
3552 return val;
3555 /* Return a Lisp_Save_Value object that represents an array A
3556 of N Lisp objects. */
3558 Lisp_Object
3559 make_save_memory (Lisp_Object *a, ptrdiff_t n)
3561 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3562 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3563 p->save_type = SAVE_TYPE_MEMORY;
3564 p->data[0].pointer = a;
3565 p->data[1].integer = n;
3566 return val;
3569 /* Free a Lisp_Save_Value object. Do not use this function
3570 if SAVE contains pointer other than returned by xmalloc. */
3572 void
3573 free_save_value (Lisp_Object save)
3575 xfree (XSAVE_POINTER (save, 0));
3576 free_misc (save);
3579 /* Return a Lisp_Misc_Overlay object with specified START, END and PLIST. */
3581 Lisp_Object
3582 build_overlay (Lisp_Object start, Lisp_Object end, Lisp_Object plist)
3584 register Lisp_Object overlay;
3586 overlay = allocate_misc (Lisp_Misc_Overlay);
3587 OVERLAY_START (overlay) = start;
3588 OVERLAY_END (overlay) = end;
3589 set_overlay_plist (overlay, plist);
3590 XOVERLAY (overlay)->next = NULL;
3591 return overlay;
3594 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3595 doc: /* Return a newly allocated marker which does not point at any place. */)
3596 (void)
3598 register Lisp_Object val;
3599 register struct Lisp_Marker *p;
3601 val = allocate_misc (Lisp_Misc_Marker);
3602 p = XMARKER (val);
3603 p->buffer = 0;
3604 p->bytepos = 0;
3605 p->charpos = 0;
3606 p->next = NULL;
3607 p->insertion_type = 0;
3608 p->need_adjustment = 0;
3609 return val;
3612 /* Return a newly allocated marker which points into BUF
3613 at character position CHARPOS and byte position BYTEPOS. */
3615 Lisp_Object
3616 build_marker (struct buffer *buf, ptrdiff_t charpos, ptrdiff_t bytepos)
3618 Lisp_Object obj;
3619 struct Lisp_Marker *m;
3621 /* No dead buffers here. */
3622 eassert (BUFFER_LIVE_P (buf));
3624 /* Every character is at least one byte. */
3625 eassert (charpos <= bytepos);
3627 obj = allocate_misc (Lisp_Misc_Marker);
3628 m = XMARKER (obj);
3629 m->buffer = buf;
3630 m->charpos = charpos;
3631 m->bytepos = bytepos;
3632 m->insertion_type = 0;
3633 m->need_adjustment = 0;
3634 m->next = BUF_MARKERS (buf);
3635 BUF_MARKERS (buf) = m;
3636 return obj;
3639 /* Put MARKER back on the free list after using it temporarily. */
3641 void
3642 free_marker (Lisp_Object marker)
3644 unchain_marker (XMARKER (marker));
3645 free_misc (marker);
3649 /* Return a newly created vector or string with specified arguments as
3650 elements. If all the arguments are characters that can fit
3651 in a string of events, make a string; otherwise, make a vector.
3653 Any number of arguments, even zero arguments, are allowed. */
3655 Lisp_Object
3656 make_event_array (ptrdiff_t nargs, Lisp_Object *args)
3658 ptrdiff_t i;
3660 for (i = 0; i < nargs; i++)
3661 /* The things that fit in a string
3662 are characters that are in 0...127,
3663 after discarding the meta bit and all the bits above it. */
3664 if (!INTEGERP (args[i])
3665 || (XINT (args[i]) & ~(-CHAR_META)) >= 0200)
3666 return Fvector (nargs, args);
3668 /* Since the loop exited, we know that all the things in it are
3669 characters, so we can make a string. */
3671 Lisp_Object result;
3673 result = Fmake_string (make_number (nargs), make_number (0));
3674 for (i = 0; i < nargs; i++)
3676 SSET (result, i, XINT (args[i]));
3677 /* Move the meta bit to the right place for a string char. */
3678 if (XINT (args[i]) & CHAR_META)
3679 SSET (result, i, SREF (result, i) | 0x80);
3682 return result;
3688 /************************************************************************
3689 Memory Full Handling
3690 ************************************************************************/
3693 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
3694 there may have been size_t overflow so that malloc was never
3695 called, or perhaps malloc was invoked successfully but the
3696 resulting pointer had problems fitting into a tagged EMACS_INT. In
3697 either case this counts as memory being full even though malloc did
3698 not fail. */
3700 void
3701 memory_full (size_t nbytes)
3703 /* Do not go into hysterics merely because a large request failed. */
3704 bool enough_free_memory = 0;
3705 if (SPARE_MEMORY < nbytes)
3707 void *p;
3709 MALLOC_BLOCK_INPUT;
3710 p = malloc (SPARE_MEMORY);
3711 if (p)
3713 free (p);
3714 enough_free_memory = 1;
3716 MALLOC_UNBLOCK_INPUT;
3719 if (! enough_free_memory)
3721 int i;
3723 Vmemory_full = Qt;
3725 memory_full_cons_threshold = sizeof (struct cons_block);
3727 /* The first time we get here, free the spare memory. */
3728 for (i = 0; i < sizeof (spare_memory) / sizeof (char *); i++)
3729 if (spare_memory[i])
3731 if (i == 0)
3732 free (spare_memory[i]);
3733 else if (i >= 1 && i <= 4)
3734 lisp_align_free (spare_memory[i]);
3735 else
3736 lisp_free (spare_memory[i]);
3737 spare_memory[i] = 0;
3741 /* This used to call error, but if we've run out of memory, we could
3742 get infinite recursion trying to build the string. */
3743 xsignal (Qnil, Vmemory_signal_data);
3746 /* If we released our reserve (due to running out of memory),
3747 and we have a fair amount free once again,
3748 try to set aside another reserve in case we run out once more.
3750 This is called when a relocatable block is freed in ralloc.c,
3751 and also directly from this file, in case we're not using ralloc.c. */
3753 void
3754 refill_memory_reserve (void)
3756 #ifndef SYSTEM_MALLOC
3757 if (spare_memory[0] == 0)
3758 spare_memory[0] = malloc (SPARE_MEMORY);
3759 if (spare_memory[1] == 0)
3760 spare_memory[1] = lisp_align_malloc (sizeof (struct cons_block),
3761 MEM_TYPE_SPARE);
3762 if (spare_memory[2] == 0)
3763 spare_memory[2] = lisp_align_malloc (sizeof (struct cons_block),
3764 MEM_TYPE_SPARE);
3765 if (spare_memory[3] == 0)
3766 spare_memory[3] = lisp_align_malloc (sizeof (struct cons_block),
3767 MEM_TYPE_SPARE);
3768 if (spare_memory[4] == 0)
3769 spare_memory[4] = lisp_align_malloc (sizeof (struct cons_block),
3770 MEM_TYPE_SPARE);
3771 if (spare_memory[5] == 0)
3772 spare_memory[5] = lisp_malloc (sizeof (struct string_block),
3773 MEM_TYPE_SPARE);
3774 if (spare_memory[6] == 0)
3775 spare_memory[6] = lisp_malloc (sizeof (struct string_block),
3776 MEM_TYPE_SPARE);
3777 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
3778 Vmemory_full = Qnil;
3779 #endif
3782 /************************************************************************
3783 C Stack Marking
3784 ************************************************************************/
3786 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
3788 /* Conservative C stack marking requires a method to identify possibly
3789 live Lisp objects given a pointer value. We do this by keeping
3790 track of blocks of Lisp data that are allocated in a red-black tree
3791 (see also the comment of mem_node which is the type of nodes in
3792 that tree). Function lisp_malloc adds information for an allocated
3793 block to the red-black tree with calls to mem_insert, and function
3794 lisp_free removes it with mem_delete. Functions live_string_p etc
3795 call mem_find to lookup information about a given pointer in the
3796 tree, and use that to determine if the pointer points to a Lisp
3797 object or not. */
3799 /* Initialize this part of alloc.c. */
3801 static void
3802 mem_init (void)
3804 mem_z.left = mem_z.right = MEM_NIL;
3805 mem_z.parent = NULL;
3806 mem_z.color = MEM_BLACK;
3807 mem_z.start = mem_z.end = NULL;
3808 mem_root = MEM_NIL;
3812 /* Value is a pointer to the mem_node containing START. Value is
3813 MEM_NIL if there is no node in the tree containing START. */
3815 static struct mem_node *
3816 mem_find (void *start)
3818 struct mem_node *p;
3820 if (start < min_heap_address || start > max_heap_address)
3821 return MEM_NIL;
3823 /* Make the search always successful to speed up the loop below. */
3824 mem_z.start = start;
3825 mem_z.end = (char *) start + 1;
3827 p = mem_root;
3828 while (start < p->start || start >= p->end)
3829 p = start < p->start ? p->left : p->right;
3830 return p;
3834 /* Insert a new node into the tree for a block of memory with start
3835 address START, end address END, and type TYPE. Value is a
3836 pointer to the node that was inserted. */
3838 static struct mem_node *
3839 mem_insert (void *start, void *end, enum mem_type type)
3841 struct mem_node *c, *parent, *x;
3843 if (min_heap_address == NULL || start < min_heap_address)
3844 min_heap_address = start;
3845 if (max_heap_address == NULL || end > max_heap_address)
3846 max_heap_address = end;
3848 /* See where in the tree a node for START belongs. In this
3849 particular application, it shouldn't happen that a node is already
3850 present. For debugging purposes, let's check that. */
3851 c = mem_root;
3852 parent = NULL;
3854 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
3856 while (c != MEM_NIL)
3858 if (start >= c->start && start < c->end)
3859 emacs_abort ();
3860 parent = c;
3861 c = start < c->start ? c->left : c->right;
3864 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3866 while (c != MEM_NIL)
3868 parent = c;
3869 c = start < c->start ? c->left : c->right;
3872 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3874 /* Create a new node. */
3875 #ifdef GC_MALLOC_CHECK
3876 x = malloc (sizeof *x);
3877 if (x == NULL)
3878 emacs_abort ();
3879 #else
3880 x = xmalloc (sizeof *x);
3881 #endif
3882 x->start = start;
3883 x->end = end;
3884 x->type = type;
3885 x->parent = parent;
3886 x->left = x->right = MEM_NIL;
3887 x->color = MEM_RED;
3889 /* Insert it as child of PARENT or install it as root. */
3890 if (parent)
3892 if (start < parent->start)
3893 parent->left = x;
3894 else
3895 parent->right = x;
3897 else
3898 mem_root = x;
3900 /* Re-establish red-black tree properties. */
3901 mem_insert_fixup (x);
3903 return x;
3907 /* Re-establish the red-black properties of the tree, and thereby
3908 balance the tree, after node X has been inserted; X is always red. */
3910 static void
3911 mem_insert_fixup (struct mem_node *x)
3913 while (x != mem_root && x->parent->color == MEM_RED)
3915 /* X is red and its parent is red. This is a violation of
3916 red-black tree property #3. */
3918 if (x->parent == x->parent->parent->left)
3920 /* We're on the left side of our grandparent, and Y is our
3921 "uncle". */
3922 struct mem_node *y = x->parent->parent->right;
3924 if (y->color == MEM_RED)
3926 /* Uncle and parent are red but should be black because
3927 X is red. Change the colors accordingly and proceed
3928 with the grandparent. */
3929 x->parent->color = MEM_BLACK;
3930 y->color = MEM_BLACK;
3931 x->parent->parent->color = MEM_RED;
3932 x = x->parent->parent;
3934 else
3936 /* Parent and uncle have different colors; parent is
3937 red, uncle is black. */
3938 if (x == x->parent->right)
3940 x = x->parent;
3941 mem_rotate_left (x);
3944 x->parent->color = MEM_BLACK;
3945 x->parent->parent->color = MEM_RED;
3946 mem_rotate_right (x->parent->parent);
3949 else
3951 /* This is the symmetrical case of above. */
3952 struct mem_node *y = x->parent->parent->left;
3954 if (y->color == MEM_RED)
3956 x->parent->color = MEM_BLACK;
3957 y->color = MEM_BLACK;
3958 x->parent->parent->color = MEM_RED;
3959 x = x->parent->parent;
3961 else
3963 if (x == x->parent->left)
3965 x = x->parent;
3966 mem_rotate_right (x);
3969 x->parent->color = MEM_BLACK;
3970 x->parent->parent->color = MEM_RED;
3971 mem_rotate_left (x->parent->parent);
3976 /* The root may have been changed to red due to the algorithm. Set
3977 it to black so that property #5 is satisfied. */
3978 mem_root->color = MEM_BLACK;
3982 /* (x) (y)
3983 / \ / \
3984 a (y) ===> (x) c
3985 / \ / \
3986 b c a b */
3988 static void
3989 mem_rotate_left (struct mem_node *x)
3991 struct mem_node *y;
3993 /* Turn y's left sub-tree into x's right sub-tree. */
3994 y = x->right;
3995 x->right = y->left;
3996 if (y->left != MEM_NIL)
3997 y->left->parent = x;
3999 /* Y's parent was x's parent. */
4000 if (y != MEM_NIL)
4001 y->parent = x->parent;
4003 /* Get the parent to point to y instead of x. */
4004 if (x->parent)
4006 if (x == x->parent->left)
4007 x->parent->left = y;
4008 else
4009 x->parent->right = y;
4011 else
4012 mem_root = y;
4014 /* Put x on y's left. */
4015 y->left = x;
4016 if (x != MEM_NIL)
4017 x->parent = y;
4021 /* (x) (Y)
4022 / \ / \
4023 (y) c ===> a (x)
4024 / \ / \
4025 a b b c */
4027 static void
4028 mem_rotate_right (struct mem_node *x)
4030 struct mem_node *y = x->left;
4032 x->left = y->right;
4033 if (y->right != MEM_NIL)
4034 y->right->parent = x;
4036 if (y != MEM_NIL)
4037 y->parent = x->parent;
4038 if (x->parent)
4040 if (x == x->parent->right)
4041 x->parent->right = y;
4042 else
4043 x->parent->left = y;
4045 else
4046 mem_root = y;
4048 y->right = x;
4049 if (x != MEM_NIL)
4050 x->parent = y;
4054 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
4056 static void
4057 mem_delete (struct mem_node *z)
4059 struct mem_node *x, *y;
4061 if (!z || z == MEM_NIL)
4062 return;
4064 if (z->left == MEM_NIL || z->right == MEM_NIL)
4065 y = z;
4066 else
4068 y = z->right;
4069 while (y->left != MEM_NIL)
4070 y = y->left;
4073 if (y->left != MEM_NIL)
4074 x = y->left;
4075 else
4076 x = y->right;
4078 x->parent = y->parent;
4079 if (y->parent)
4081 if (y == y->parent->left)
4082 y->parent->left = x;
4083 else
4084 y->parent->right = x;
4086 else
4087 mem_root = x;
4089 if (y != z)
4091 z->start = y->start;
4092 z->end = y->end;
4093 z->type = y->type;
4096 if (y->color == MEM_BLACK)
4097 mem_delete_fixup (x);
4099 #ifdef GC_MALLOC_CHECK
4100 free (y);
4101 #else
4102 xfree (y);
4103 #endif
4107 /* Re-establish the red-black properties of the tree, after a
4108 deletion. */
4110 static void
4111 mem_delete_fixup (struct mem_node *x)
4113 while (x != mem_root && x->color == MEM_BLACK)
4115 if (x == x->parent->left)
4117 struct mem_node *w = x->parent->right;
4119 if (w->color == MEM_RED)
4121 w->color = MEM_BLACK;
4122 x->parent->color = MEM_RED;
4123 mem_rotate_left (x->parent);
4124 w = x->parent->right;
4127 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
4129 w->color = MEM_RED;
4130 x = x->parent;
4132 else
4134 if (w->right->color == MEM_BLACK)
4136 w->left->color = MEM_BLACK;
4137 w->color = MEM_RED;
4138 mem_rotate_right (w);
4139 w = x->parent->right;
4141 w->color = x->parent->color;
4142 x->parent->color = MEM_BLACK;
4143 w->right->color = MEM_BLACK;
4144 mem_rotate_left (x->parent);
4145 x = mem_root;
4148 else
4150 struct mem_node *w = x->parent->left;
4152 if (w->color == MEM_RED)
4154 w->color = MEM_BLACK;
4155 x->parent->color = MEM_RED;
4156 mem_rotate_right (x->parent);
4157 w = x->parent->left;
4160 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
4162 w->color = MEM_RED;
4163 x = x->parent;
4165 else
4167 if (w->left->color == MEM_BLACK)
4169 w->right->color = MEM_BLACK;
4170 w->color = MEM_RED;
4171 mem_rotate_left (w);
4172 w = x->parent->left;
4175 w->color = x->parent->color;
4176 x->parent->color = MEM_BLACK;
4177 w->left->color = MEM_BLACK;
4178 mem_rotate_right (x->parent);
4179 x = mem_root;
4184 x->color = MEM_BLACK;
4188 /* Value is non-zero if P is a pointer to a live Lisp string on
4189 the heap. M is a pointer to the mem_block for P. */
4191 static bool
4192 live_string_p (struct mem_node *m, void *p)
4194 if (m->type == MEM_TYPE_STRING)
4196 struct string_block *b = m->start;
4197 ptrdiff_t offset = (char *) p - (char *) &b->strings[0];
4199 /* P must point to the start of a Lisp_String structure, and it
4200 must not be on the free-list. */
4201 return (offset >= 0
4202 && offset % sizeof b->strings[0] == 0
4203 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
4204 && ((struct Lisp_String *) p)->data != NULL);
4206 else
4207 return 0;
4211 /* Value is non-zero if P is a pointer to a live Lisp cons on
4212 the heap. M is a pointer to the mem_block for P. */
4214 static bool
4215 live_cons_p (struct mem_node *m, void *p)
4217 if (m->type == MEM_TYPE_CONS)
4219 struct cons_block *b = m->start;
4220 ptrdiff_t offset = (char *) p - (char *) &b->conses[0];
4222 /* P must point to the start of a Lisp_Cons, not be
4223 one of the unused cells in the current cons block,
4224 and not be on the free-list. */
4225 return (offset >= 0
4226 && offset % sizeof b->conses[0] == 0
4227 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
4228 && (b != cons_block
4229 || offset / sizeof b->conses[0] < cons_block_index)
4230 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
4232 else
4233 return 0;
4237 /* Value is non-zero if P is a pointer to a live Lisp symbol on
4238 the heap. M is a pointer to the mem_block for P. */
4240 static bool
4241 live_symbol_p (struct mem_node *m, void *p)
4243 if (m->type == MEM_TYPE_SYMBOL)
4245 struct symbol_block *b = m->start;
4246 ptrdiff_t offset = (char *) p - (char *) &b->symbols[0];
4248 /* P must point to the start of a Lisp_Symbol, not be
4249 one of the unused cells in the current symbol block,
4250 and not be on the free-list. */
4251 return (offset >= 0
4252 && offset % sizeof b->symbols[0] == 0
4253 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
4254 && (b != symbol_block
4255 || offset / sizeof b->symbols[0] < symbol_block_index)
4256 && !EQ (((struct Lisp_Symbol *)p)->function, Vdead));
4258 else
4259 return 0;
4263 /* Value is non-zero if P is a pointer to a live Lisp float on
4264 the heap. M is a pointer to the mem_block for P. */
4266 static bool
4267 live_float_p (struct mem_node *m, void *p)
4269 if (m->type == MEM_TYPE_FLOAT)
4271 struct float_block *b = m->start;
4272 ptrdiff_t offset = (char *) p - (char *) &b->floats[0];
4274 /* P must point to the start of a Lisp_Float and not be
4275 one of the unused cells in the current float block. */
4276 return (offset >= 0
4277 && offset % sizeof b->floats[0] == 0
4278 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
4279 && (b != float_block
4280 || offset / sizeof b->floats[0] < float_block_index));
4282 else
4283 return 0;
4287 /* Value is non-zero if P is a pointer to a live Lisp Misc on
4288 the heap. M is a pointer to the mem_block for P. */
4290 static bool
4291 live_misc_p (struct mem_node *m, void *p)
4293 if (m->type == MEM_TYPE_MISC)
4295 struct marker_block *b = m->start;
4296 ptrdiff_t offset = (char *) p - (char *) &b->markers[0];
4298 /* P must point to the start of a Lisp_Misc, not be
4299 one of the unused cells in the current misc block,
4300 and not be on the free-list. */
4301 return (offset >= 0
4302 && offset % sizeof b->markers[0] == 0
4303 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
4304 && (b != marker_block
4305 || offset / sizeof b->markers[0] < marker_block_index)
4306 && ((union Lisp_Misc *) p)->u_any.type != Lisp_Misc_Free);
4308 else
4309 return 0;
4313 /* Value is non-zero if P is a pointer to a live vector-like object.
4314 M is a pointer to the mem_block for P. */
4316 static bool
4317 live_vector_p (struct mem_node *m, void *p)
4319 if (m->type == MEM_TYPE_VECTOR_BLOCK)
4321 /* This memory node corresponds to a vector block. */
4322 struct vector_block *block = m->start;
4323 struct Lisp_Vector *vector = (struct Lisp_Vector *) block->data;
4325 /* P is in the block's allocation range. Scan the block
4326 up to P and see whether P points to the start of some
4327 vector which is not on a free list. FIXME: check whether
4328 some allocation patterns (probably a lot of short vectors)
4329 may cause a substantial overhead of this loop. */
4330 while (VECTOR_IN_BLOCK (vector, block)
4331 && vector <= (struct Lisp_Vector *) p)
4333 if (!PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FREE) && vector == p)
4334 return 1;
4335 else
4336 vector = ADVANCE (vector, vector_nbytes (vector));
4339 else if (m->type == MEM_TYPE_VECTORLIKE && p == large_vector_vec (m->start))
4340 /* This memory node corresponds to a large vector. */
4341 return 1;
4342 return 0;
4346 /* Value is non-zero if P is a pointer to a live buffer. M is a
4347 pointer to the mem_block for P. */
4349 static bool
4350 live_buffer_p (struct mem_node *m, void *p)
4352 /* P must point to the start of the block, and the buffer
4353 must not have been killed. */
4354 return (m->type == MEM_TYPE_BUFFER
4355 && p == m->start
4356 && !NILP (((struct buffer *) p)->INTERNAL_FIELD (name)));
4359 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
4361 #if GC_MARK_STACK
4363 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4365 /* Currently not used, but may be called from gdb. */
4367 void dump_zombies (void) EXTERNALLY_VISIBLE;
4369 /* Array of objects that are kept alive because the C stack contains
4370 a pattern that looks like a reference to them. */
4372 #define MAX_ZOMBIES 10
4373 static Lisp_Object zombies[MAX_ZOMBIES];
4375 /* Number of zombie objects. */
4377 static EMACS_INT nzombies;
4379 /* Number of garbage collections. */
4381 static EMACS_INT ngcs;
4383 /* Average percentage of zombies per collection. */
4385 static double avg_zombies;
4387 /* Max. number of live and zombie objects. */
4389 static EMACS_INT max_live, max_zombies;
4391 /* Average number of live objects per GC. */
4393 static double avg_live;
4395 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
4396 doc: /* Show information about live and zombie objects. */)
4397 (void)
4399 Lisp_Object args[8], zombie_list = Qnil;
4400 EMACS_INT i;
4401 for (i = 0; i < min (MAX_ZOMBIES, nzombies); i++)
4402 zombie_list = Fcons (zombies[i], zombie_list);
4403 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
4404 args[1] = make_number (ngcs);
4405 args[2] = make_float (avg_live);
4406 args[3] = make_float (avg_zombies);
4407 args[4] = make_float (avg_zombies / avg_live / 100);
4408 args[5] = make_number (max_live);
4409 args[6] = make_number (max_zombies);
4410 args[7] = zombie_list;
4411 return Fmessage (8, args);
4414 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4417 /* Mark OBJ if we can prove it's a Lisp_Object. */
4419 static void
4420 mark_maybe_object (Lisp_Object obj)
4422 void *po;
4423 struct mem_node *m;
4425 #if USE_VALGRIND
4426 if (valgrind_p)
4427 VALGRIND_MAKE_MEM_DEFINED (&obj, sizeof (obj));
4428 #endif
4430 if (INTEGERP (obj))
4431 return;
4433 po = (void *) XPNTR (obj);
4434 m = mem_find (po);
4436 if (m != MEM_NIL)
4438 bool mark_p = 0;
4440 switch (XTYPE (obj))
4442 case Lisp_String:
4443 mark_p = (live_string_p (m, po)
4444 && !STRING_MARKED_P ((struct Lisp_String *) po));
4445 break;
4447 case Lisp_Cons:
4448 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4449 break;
4451 case Lisp_Symbol:
4452 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4453 break;
4455 case Lisp_Float:
4456 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4457 break;
4459 case Lisp_Vectorlike:
4460 /* Note: can't check BUFFERP before we know it's a
4461 buffer because checking that dereferences the pointer
4462 PO which might point anywhere. */
4463 if (live_vector_p (m, po))
4464 mark_p = !SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4465 else if (live_buffer_p (m, po))
4466 mark_p = BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4467 break;
4469 case Lisp_Misc:
4470 mark_p = (live_misc_p (m, po) && !XMISCANY (obj)->gcmarkbit);
4471 break;
4473 default:
4474 break;
4477 if (mark_p)
4479 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4480 if (nzombies < MAX_ZOMBIES)
4481 zombies[nzombies] = obj;
4482 ++nzombies;
4483 #endif
4484 mark_object (obj);
4490 /* If P points to Lisp data, mark that as live if it isn't already
4491 marked. */
4493 static void
4494 mark_maybe_pointer (void *p)
4496 struct mem_node *m;
4498 #if USE_VALGRIND
4499 if (valgrind_p)
4500 VALGRIND_MAKE_MEM_DEFINED (&p, sizeof (p));
4501 #endif
4503 /* Quickly rule out some values which can't point to Lisp data.
4504 USE_LSB_TAG needs Lisp data to be aligned on multiples of GCALIGNMENT.
4505 Otherwise, assume that Lisp data is aligned on even addresses. */
4506 if ((intptr_t) p % (USE_LSB_TAG ? GCALIGNMENT : 2))
4507 return;
4509 m = mem_find (p);
4510 if (m != MEM_NIL)
4512 Lisp_Object obj = Qnil;
4514 switch (m->type)
4516 case MEM_TYPE_NON_LISP:
4517 case MEM_TYPE_SPARE:
4518 /* Nothing to do; not a pointer to Lisp memory. */
4519 break;
4521 case MEM_TYPE_BUFFER:
4522 if (live_buffer_p (m, p) && !VECTOR_MARKED_P ((struct buffer *)p))
4523 XSETVECTOR (obj, p);
4524 break;
4526 case MEM_TYPE_CONS:
4527 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4528 XSETCONS (obj, p);
4529 break;
4531 case MEM_TYPE_STRING:
4532 if (live_string_p (m, p)
4533 && !STRING_MARKED_P ((struct Lisp_String *) p))
4534 XSETSTRING (obj, p);
4535 break;
4537 case MEM_TYPE_MISC:
4538 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4539 XSETMISC (obj, p);
4540 break;
4542 case MEM_TYPE_SYMBOL:
4543 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4544 XSETSYMBOL (obj, p);
4545 break;
4547 case MEM_TYPE_FLOAT:
4548 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4549 XSETFLOAT (obj, p);
4550 break;
4552 case MEM_TYPE_VECTORLIKE:
4553 case MEM_TYPE_VECTOR_BLOCK:
4554 if (live_vector_p (m, p))
4556 Lisp_Object tem;
4557 XSETVECTOR (tem, p);
4558 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4559 obj = tem;
4561 break;
4563 default:
4564 emacs_abort ();
4567 if (!NILP (obj))
4568 mark_object (obj);
4573 /* Alignment of pointer values. Use alignof, as it sometimes returns
4574 a smaller alignment than GCC's __alignof__ and mark_memory might
4575 miss objects if __alignof__ were used. */
4576 #define GC_POINTER_ALIGNMENT alignof (void *)
4578 /* Define POINTERS_MIGHT_HIDE_IN_OBJECTS to 1 if marking via C pointers does
4579 not suffice, which is the typical case. A host where a Lisp_Object is
4580 wider than a pointer might allocate a Lisp_Object in non-adjacent halves.
4581 If USE_LSB_TAG, the bottom half is not a valid pointer, but it should
4582 suffice to widen it to to a Lisp_Object and check it that way. */
4583 #if USE_LSB_TAG || VAL_MAX < UINTPTR_MAX
4584 # if !USE_LSB_TAG && VAL_MAX < UINTPTR_MAX >> GCTYPEBITS
4585 /* If tag bits straddle pointer-word boundaries, neither mark_maybe_pointer
4586 nor mark_maybe_object can follow the pointers. This should not occur on
4587 any practical porting target. */
4588 # error "MSB type bits straddle pointer-word boundaries"
4589 # endif
4590 /* Marking via C pointers does not suffice, because Lisp_Objects contain
4591 pointer words that hold pointers ORed with type bits. */
4592 # define POINTERS_MIGHT_HIDE_IN_OBJECTS 1
4593 #else
4594 /* Marking via C pointers suffices, because Lisp_Objects contain pointer
4595 words that hold unmodified pointers. */
4596 # define POINTERS_MIGHT_HIDE_IN_OBJECTS 0
4597 #endif
4599 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4600 or END+OFFSET..START. */
4602 static void ATTRIBUTE_NO_SANITIZE_ADDRESS
4603 mark_memory (void *start, void *end)
4605 void **pp;
4606 int i;
4608 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4609 nzombies = 0;
4610 #endif
4612 /* Make START the pointer to the start of the memory region,
4613 if it isn't already. */
4614 if (end < start)
4616 void *tem = start;
4617 start = end;
4618 end = tem;
4621 /* Mark Lisp data pointed to. This is necessary because, in some
4622 situations, the C compiler optimizes Lisp objects away, so that
4623 only a pointer to them remains. Example:
4625 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4628 Lisp_Object obj = build_string ("test");
4629 struct Lisp_String *s = XSTRING (obj);
4630 Fgarbage_collect ();
4631 fprintf (stderr, "test `%s'\n", s->data);
4632 return Qnil;
4635 Here, `obj' isn't really used, and the compiler optimizes it
4636 away. The only reference to the life string is through the
4637 pointer `s'. */
4639 for (pp = start; (void *) pp < end; pp++)
4640 for (i = 0; i < sizeof *pp; i += GC_POINTER_ALIGNMENT)
4642 void *p = *(void **) ((char *) pp + i);
4643 mark_maybe_pointer (p);
4644 if (POINTERS_MIGHT_HIDE_IN_OBJECTS)
4645 mark_maybe_object (XIL ((intptr_t) p));
4649 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4651 static bool setjmp_tested_p;
4652 static int longjmps_done;
4654 #define SETJMP_WILL_LIKELY_WORK "\
4656 Emacs garbage collector has been changed to use conservative stack\n\
4657 marking. Emacs has determined that the method it uses to do the\n\
4658 marking will likely work on your system, but this isn't sure.\n\
4660 If you are a system-programmer, or can get the help of a local wizard\n\
4661 who is, please take a look at the function mark_stack in alloc.c, and\n\
4662 verify that the methods used are appropriate for your system.\n\
4664 Please mail the result to <emacs-devel@gnu.org>.\n\
4667 #define SETJMP_WILL_NOT_WORK "\
4669 Emacs garbage collector has been changed to use conservative stack\n\
4670 marking. Emacs has determined that the default method it uses to do the\n\
4671 marking will not work on your system. We will need a system-dependent\n\
4672 solution for your system.\n\
4674 Please take a look at the function mark_stack in alloc.c, and\n\
4675 try to find a way to make it work on your system.\n\
4677 Note that you may get false negatives, depending on the compiler.\n\
4678 In particular, you need to use -O with GCC for this test.\n\
4680 Please mail the result to <emacs-devel@gnu.org>.\n\
4684 /* Perform a quick check if it looks like setjmp saves registers in a
4685 jmp_buf. Print a message to stderr saying so. When this test
4686 succeeds, this is _not_ a proof that setjmp is sufficient for
4687 conservative stack marking. Only the sources or a disassembly
4688 can prove that. */
4690 static void
4691 test_setjmp (void)
4693 char buf[10];
4694 register int x;
4695 sys_jmp_buf jbuf;
4697 /* Arrange for X to be put in a register. */
4698 sprintf (buf, "1");
4699 x = strlen (buf);
4700 x = 2 * x - 1;
4702 sys_setjmp (jbuf);
4703 if (longjmps_done == 1)
4705 /* Came here after the longjmp at the end of the function.
4707 If x == 1, the longjmp has restored the register to its
4708 value before the setjmp, and we can hope that setjmp
4709 saves all such registers in the jmp_buf, although that
4710 isn't sure.
4712 For other values of X, either something really strange is
4713 taking place, or the setjmp just didn't save the register. */
4715 if (x == 1)
4716 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4717 else
4719 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4720 exit (1);
4724 ++longjmps_done;
4725 x = 2;
4726 if (longjmps_done == 1)
4727 sys_longjmp (jbuf, 1);
4730 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4733 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4735 /* Abort if anything GCPRO'd doesn't survive the GC. */
4737 static void
4738 check_gcpros (void)
4740 struct gcpro *p;
4741 ptrdiff_t i;
4743 for (p = gcprolist; p; p = p->next)
4744 for (i = 0; i < p->nvars; ++i)
4745 if (!survives_gc_p (p->var[i]))
4746 /* FIXME: It's not necessarily a bug. It might just be that the
4747 GCPRO is unnecessary or should release the object sooner. */
4748 emacs_abort ();
4751 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4753 void
4754 dump_zombies (void)
4756 int i;
4758 fprintf (stderr, "\nZombies kept alive = %"pI"d:\n", nzombies);
4759 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
4761 fprintf (stderr, " %d = ", i);
4762 debug_print (zombies[i]);
4766 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4769 /* Mark live Lisp objects on the C stack.
4771 There are several system-dependent problems to consider when
4772 porting this to new architectures:
4774 Processor Registers
4776 We have to mark Lisp objects in CPU registers that can hold local
4777 variables or are used to pass parameters.
4779 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4780 something that either saves relevant registers on the stack, or
4781 calls mark_maybe_object passing it each register's contents.
4783 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4784 implementation assumes that calling setjmp saves registers we need
4785 to see in a jmp_buf which itself lies on the stack. This doesn't
4786 have to be true! It must be verified for each system, possibly
4787 by taking a look at the source code of setjmp.
4789 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4790 can use it as a machine independent method to store all registers
4791 to the stack. In this case the macros described in the previous
4792 two paragraphs are not used.
4794 Stack Layout
4796 Architectures differ in the way their processor stack is organized.
4797 For example, the stack might look like this
4799 +----------------+
4800 | Lisp_Object | size = 4
4801 +----------------+
4802 | something else | size = 2
4803 +----------------+
4804 | Lisp_Object | size = 4
4805 +----------------+
4806 | ... |
4808 In such a case, not every Lisp_Object will be aligned equally. To
4809 find all Lisp_Object on the stack it won't be sufficient to walk
4810 the stack in steps of 4 bytes. Instead, two passes will be
4811 necessary, one starting at the start of the stack, and a second
4812 pass starting at the start of the stack + 2. Likewise, if the
4813 minimal alignment of Lisp_Objects on the stack is 1, four passes
4814 would be necessary, each one starting with one byte more offset
4815 from the stack start. */
4817 static void
4818 mark_stack (void)
4820 void *end;
4822 #ifdef HAVE___BUILTIN_UNWIND_INIT
4823 /* Force callee-saved registers and register windows onto the stack.
4824 This is the preferred method if available, obviating the need for
4825 machine dependent methods. */
4826 __builtin_unwind_init ();
4827 end = &end;
4828 #else /* not HAVE___BUILTIN_UNWIND_INIT */
4829 #ifndef GC_SAVE_REGISTERS_ON_STACK
4830 /* jmp_buf may not be aligned enough on darwin-ppc64 */
4831 union aligned_jmpbuf {
4832 Lisp_Object o;
4833 sys_jmp_buf j;
4834 } j;
4835 volatile bool stack_grows_down_p = (char *) &j > (char *) stack_base;
4836 #endif
4837 /* This trick flushes the register windows so that all the state of
4838 the process is contained in the stack. */
4839 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
4840 needed on ia64 too. See mach_dep.c, where it also says inline
4841 assembler doesn't work with relevant proprietary compilers. */
4842 #ifdef __sparc__
4843 #if defined (__sparc64__) && defined (__FreeBSD__)
4844 /* FreeBSD does not have a ta 3 handler. */
4845 asm ("flushw");
4846 #else
4847 asm ("ta 3");
4848 #endif
4849 #endif
4851 /* Save registers that we need to see on the stack. We need to see
4852 registers used to hold register variables and registers used to
4853 pass parameters. */
4854 #ifdef GC_SAVE_REGISTERS_ON_STACK
4855 GC_SAVE_REGISTERS_ON_STACK (end);
4856 #else /* not GC_SAVE_REGISTERS_ON_STACK */
4858 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
4859 setjmp will definitely work, test it
4860 and print a message with the result
4861 of the test. */
4862 if (!setjmp_tested_p)
4864 setjmp_tested_p = 1;
4865 test_setjmp ();
4867 #endif /* GC_SETJMP_WORKS */
4869 sys_setjmp (j.j);
4870 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
4871 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
4872 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
4874 /* This assumes that the stack is a contiguous region in memory. If
4875 that's not the case, something has to be done here to iterate
4876 over the stack segments. */
4877 mark_memory (stack_base, end);
4879 /* Allow for marking a secondary stack, like the register stack on the
4880 ia64. */
4881 #ifdef GC_MARK_SECONDARY_STACK
4882 GC_MARK_SECONDARY_STACK ();
4883 #endif
4885 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4886 check_gcpros ();
4887 #endif
4890 #else /* GC_MARK_STACK == 0 */
4892 #define mark_maybe_object(obj) emacs_abort ()
4894 #endif /* GC_MARK_STACK != 0 */
4897 /* Determine whether it is safe to access memory at address P. */
4898 static int
4899 valid_pointer_p (void *p)
4901 #ifdef WINDOWSNT
4902 return w32_valid_pointer_p (p, 16);
4903 #else
4904 int fd[2];
4906 /* Obviously, we cannot just access it (we would SEGV trying), so we
4907 trick the o/s to tell us whether p is a valid pointer.
4908 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4909 not validate p in that case. */
4911 if (emacs_pipe (fd) == 0)
4913 bool valid = emacs_write (fd[1], p, 16) == 16;
4914 emacs_close (fd[1]);
4915 emacs_close (fd[0]);
4916 return valid;
4919 return -1;
4920 #endif
4923 /* Return 2 if OBJ is a killed or special buffer object, 1 if OBJ is a
4924 valid lisp object, 0 if OBJ is NOT a valid lisp object, or -1 if we
4925 cannot validate OBJ. This function can be quite slow, so its primary
4926 use is the manual debugging. The only exception is print_object, where
4927 we use it to check whether the memory referenced by the pointer of
4928 Lisp_Save_Value object contains valid objects. */
4931 valid_lisp_object_p (Lisp_Object obj)
4933 void *p;
4934 #if GC_MARK_STACK
4935 struct mem_node *m;
4936 #endif
4938 if (INTEGERP (obj))
4939 return 1;
4941 p = (void *) XPNTR (obj);
4942 if (PURE_POINTER_P (p))
4943 return 1;
4945 if (p == &buffer_defaults || p == &buffer_local_symbols)
4946 return 2;
4948 #if !GC_MARK_STACK
4949 return valid_pointer_p (p);
4950 #else
4952 m = mem_find (p);
4954 if (m == MEM_NIL)
4956 int valid = valid_pointer_p (p);
4957 if (valid <= 0)
4958 return valid;
4960 if (SUBRP (obj))
4961 return 1;
4963 return 0;
4966 switch (m->type)
4968 case MEM_TYPE_NON_LISP:
4969 case MEM_TYPE_SPARE:
4970 return 0;
4972 case MEM_TYPE_BUFFER:
4973 return live_buffer_p (m, p) ? 1 : 2;
4975 case MEM_TYPE_CONS:
4976 return live_cons_p (m, p);
4978 case MEM_TYPE_STRING:
4979 return live_string_p (m, p);
4981 case MEM_TYPE_MISC:
4982 return live_misc_p (m, p);
4984 case MEM_TYPE_SYMBOL:
4985 return live_symbol_p (m, p);
4987 case MEM_TYPE_FLOAT:
4988 return live_float_p (m, p);
4990 case MEM_TYPE_VECTORLIKE:
4991 case MEM_TYPE_VECTOR_BLOCK:
4992 return live_vector_p (m, p);
4994 default:
4995 break;
4998 return 0;
4999 #endif
5005 /***********************************************************************
5006 Pure Storage Management
5007 ***********************************************************************/
5009 /* Allocate room for SIZE bytes from pure Lisp storage and return a
5010 pointer to it. TYPE is the Lisp type for which the memory is
5011 allocated. TYPE < 0 means it's not used for a Lisp object. */
5013 static void *
5014 pure_alloc (size_t size, int type)
5016 void *result;
5017 #if USE_LSB_TAG
5018 size_t alignment = GCALIGNMENT;
5019 #else
5020 size_t alignment = alignof (EMACS_INT);
5022 /* Give Lisp_Floats an extra alignment. */
5023 if (type == Lisp_Float)
5024 alignment = alignof (struct Lisp_Float);
5025 #endif
5027 again:
5028 if (type >= 0)
5030 /* Allocate space for a Lisp object from the beginning of the free
5031 space with taking account of alignment. */
5032 result = ALIGN (purebeg + pure_bytes_used_lisp, alignment);
5033 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
5035 else
5037 /* Allocate space for a non-Lisp object from the end of the free
5038 space. */
5039 pure_bytes_used_non_lisp += size;
5040 result = purebeg + pure_size - pure_bytes_used_non_lisp;
5042 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
5044 if (pure_bytes_used <= pure_size)
5045 return result;
5047 /* Don't allocate a large amount here,
5048 because it might get mmap'd and then its address
5049 might not be usable. */
5050 purebeg = xmalloc (10000);
5051 pure_size = 10000;
5052 pure_bytes_used_before_overflow += pure_bytes_used - size;
5053 pure_bytes_used = 0;
5054 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
5055 goto again;
5059 /* Print a warning if PURESIZE is too small. */
5061 void
5062 check_pure_size (void)
5064 if (pure_bytes_used_before_overflow)
5065 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI"d"
5066 " bytes needed)"),
5067 pure_bytes_used + pure_bytes_used_before_overflow);
5071 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
5072 the non-Lisp data pool of the pure storage, and return its start
5073 address. Return NULL if not found. */
5075 static char *
5076 find_string_data_in_pure (const char *data, ptrdiff_t nbytes)
5078 int i;
5079 ptrdiff_t skip, bm_skip[256], last_char_skip, infinity, start, start_max;
5080 const unsigned char *p;
5081 char *non_lisp_beg;
5083 if (pure_bytes_used_non_lisp <= nbytes)
5084 return NULL;
5086 /* Set up the Boyer-Moore table. */
5087 skip = nbytes + 1;
5088 for (i = 0; i < 256; i++)
5089 bm_skip[i] = skip;
5091 p = (const unsigned char *) data;
5092 while (--skip > 0)
5093 bm_skip[*p++] = skip;
5095 last_char_skip = bm_skip['\0'];
5097 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
5098 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
5100 /* See the comments in the function `boyer_moore' (search.c) for the
5101 use of `infinity'. */
5102 infinity = pure_bytes_used_non_lisp + 1;
5103 bm_skip['\0'] = infinity;
5105 p = (const unsigned char *) non_lisp_beg + nbytes;
5106 start = 0;
5109 /* Check the last character (== '\0'). */
5112 start += bm_skip[*(p + start)];
5114 while (start <= start_max);
5116 if (start < infinity)
5117 /* Couldn't find the last character. */
5118 return NULL;
5120 /* No less than `infinity' means we could find the last
5121 character at `p[start - infinity]'. */
5122 start -= infinity;
5124 /* Check the remaining characters. */
5125 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
5126 /* Found. */
5127 return non_lisp_beg + start;
5129 start += last_char_skip;
5131 while (start <= start_max);
5133 return NULL;
5137 /* Return a string allocated in pure space. DATA is a buffer holding
5138 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
5139 means make the result string multibyte.
5141 Must get an error if pure storage is full, since if it cannot hold
5142 a large string it may be able to hold conses that point to that
5143 string; then the string is not protected from gc. */
5145 Lisp_Object
5146 make_pure_string (const char *data,
5147 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
5149 Lisp_Object string;
5150 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5151 s->data = (unsigned char *) find_string_data_in_pure (data, nbytes);
5152 if (s->data == NULL)
5154 s->data = pure_alloc (nbytes + 1, -1);
5155 memcpy (s->data, data, nbytes);
5156 s->data[nbytes] = '\0';
5158 s->size = nchars;
5159 s->size_byte = multibyte ? nbytes : -1;
5160 s->intervals = NULL;
5161 XSETSTRING (string, s);
5162 return string;
5165 /* Return a string allocated in pure space. Do not
5166 allocate the string data, just point to DATA. */
5168 Lisp_Object
5169 make_pure_c_string (const char *data, ptrdiff_t nchars)
5171 Lisp_Object string;
5172 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5173 s->size = nchars;
5174 s->size_byte = -1;
5175 s->data = (unsigned char *) data;
5176 s->intervals = NULL;
5177 XSETSTRING (string, s);
5178 return string;
5181 /* Return a cons allocated from pure space. Give it pure copies
5182 of CAR as car and CDR as cdr. */
5184 Lisp_Object
5185 pure_cons (Lisp_Object car, Lisp_Object cdr)
5187 Lisp_Object new;
5188 struct Lisp_Cons *p = pure_alloc (sizeof *p, Lisp_Cons);
5189 XSETCONS (new, p);
5190 XSETCAR (new, Fpurecopy (car));
5191 XSETCDR (new, Fpurecopy (cdr));
5192 return new;
5196 /* Value is a float object with value NUM allocated from pure space. */
5198 static Lisp_Object
5199 make_pure_float (double num)
5201 Lisp_Object new;
5202 struct Lisp_Float *p = pure_alloc (sizeof *p, Lisp_Float);
5203 XSETFLOAT (new, p);
5204 XFLOAT_INIT (new, num);
5205 return new;
5209 /* Return a vector with room for LEN Lisp_Objects allocated from
5210 pure space. */
5212 static Lisp_Object
5213 make_pure_vector (ptrdiff_t len)
5215 Lisp_Object new;
5216 size_t size = header_size + len * word_size;
5217 struct Lisp_Vector *p = pure_alloc (size, Lisp_Vectorlike);
5218 XSETVECTOR (new, p);
5219 XVECTOR (new)->header.size = len;
5220 return new;
5224 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
5225 doc: /* Make a copy of object OBJ in pure storage.
5226 Recursively copies contents of vectors and cons cells.
5227 Does not copy symbols. Copies strings without text properties. */)
5228 (register Lisp_Object obj)
5230 if (NILP (Vpurify_flag))
5231 return obj;
5233 if (PURE_POINTER_P (XPNTR (obj)))
5234 return obj;
5236 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5238 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
5239 if (!NILP (tmp))
5240 return tmp;
5243 if (CONSP (obj))
5244 obj = pure_cons (XCAR (obj), XCDR (obj));
5245 else if (FLOATP (obj))
5246 obj = make_pure_float (XFLOAT_DATA (obj));
5247 else if (STRINGP (obj))
5248 obj = make_pure_string (SSDATA (obj), SCHARS (obj),
5249 SBYTES (obj),
5250 STRING_MULTIBYTE (obj));
5251 else if (COMPILEDP (obj) || VECTORP (obj))
5253 register struct Lisp_Vector *vec;
5254 register ptrdiff_t i;
5255 ptrdiff_t size;
5257 size = ASIZE (obj);
5258 if (size & PSEUDOVECTOR_FLAG)
5259 size &= PSEUDOVECTOR_SIZE_MASK;
5260 vec = XVECTOR (make_pure_vector (size));
5261 for (i = 0; i < size; i++)
5262 vec->contents[i] = Fpurecopy (AREF (obj, i));
5263 if (COMPILEDP (obj))
5265 XSETPVECTYPE (vec, PVEC_COMPILED);
5266 XSETCOMPILED (obj, vec);
5268 else
5269 XSETVECTOR (obj, vec);
5271 else if (MARKERP (obj))
5272 error ("Attempt to copy a marker to pure storage");
5273 else
5274 /* Not purified, don't hash-cons. */
5275 return obj;
5277 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5278 Fputhash (obj, obj, Vpurify_flag);
5280 return obj;
5285 /***********************************************************************
5286 Protection from GC
5287 ***********************************************************************/
5289 /* Put an entry in staticvec, pointing at the variable with address
5290 VARADDRESS. */
5292 void
5293 staticpro (Lisp_Object *varaddress)
5295 if (staticidx >= NSTATICS)
5296 fatal ("NSTATICS too small; try increasing and recompiling Emacs.");
5297 staticvec[staticidx++] = varaddress;
5301 /***********************************************************************
5302 Protection from GC
5303 ***********************************************************************/
5305 /* Temporarily prevent garbage collection. */
5307 ptrdiff_t
5308 inhibit_garbage_collection (void)
5310 ptrdiff_t count = SPECPDL_INDEX ();
5312 specbind (Qgc_cons_threshold, make_number (MOST_POSITIVE_FIXNUM));
5313 return count;
5316 /* Used to avoid possible overflows when
5317 converting from C to Lisp integers. */
5319 static Lisp_Object
5320 bounded_number (EMACS_INT number)
5322 return make_number (min (MOST_POSITIVE_FIXNUM, number));
5325 /* Calculate total bytes of live objects. */
5327 static size_t
5328 total_bytes_of_live_objects (void)
5330 size_t tot = 0;
5331 tot += total_conses * sizeof (struct Lisp_Cons);
5332 tot += total_symbols * sizeof (struct Lisp_Symbol);
5333 tot += total_markers * sizeof (union Lisp_Misc);
5334 tot += total_string_bytes;
5335 tot += total_vector_slots * word_size;
5336 tot += total_floats * sizeof (struct Lisp_Float);
5337 tot += total_intervals * sizeof (struct interval);
5338 tot += total_strings * sizeof (struct Lisp_String);
5339 return tot;
5342 #ifdef HAVE_WINDOW_SYSTEM
5344 /* This code has a few issues on MS-Windows, see Bug#15876 and Bug#16140. */
5346 #if !defined (HAVE_NTGUI)
5348 /* Remove unmarked font-spec and font-entity objects from ENTRY, which is
5349 (DRIVER-TYPE NUM-FRAMES FONT-CACHE-DATA ...), and return changed entry. */
5351 static Lisp_Object
5352 compact_font_cache_entry (Lisp_Object entry)
5354 Lisp_Object tail, *prev = &entry;
5356 for (tail = entry; CONSP (tail); tail = XCDR (tail))
5358 bool drop = 0;
5359 Lisp_Object obj = XCAR (tail);
5361 /* Consider OBJ if it is (font-spec . [font-entity font-entity ...]). */
5362 if (CONSP (obj) && FONT_SPEC_P (XCAR (obj))
5363 && !VECTOR_MARKED_P (XFONT_SPEC (XCAR (obj)))
5364 && VECTORP (XCDR (obj)))
5366 ptrdiff_t i, size = ASIZE (XCDR (obj)) & ~ARRAY_MARK_FLAG;
5368 /* If font-spec is not marked, most likely all font-entities
5369 are not marked too. But we must be sure that nothing is
5370 marked within OBJ before we really drop it. */
5371 for (i = 0; i < size; i++)
5372 if (VECTOR_MARKED_P (XFONT_ENTITY (AREF (XCDR (obj), i))))
5373 break;
5375 if (i == size)
5376 drop = 1;
5378 if (drop)
5379 *prev = XCDR (tail);
5380 else
5381 prev = xcdr_addr (tail);
5383 return entry;
5386 #endif /* not HAVE_NTGUI */
5388 /* Compact font caches on all terminals and mark
5389 everything which is still here after compaction. */
5391 static void
5392 compact_font_caches (void)
5394 struct terminal *t;
5396 for (t = terminal_list; t; t = t->next_terminal)
5398 Lisp_Object cache = TERMINAL_FONT_CACHE (t);
5399 #if !defined (HAVE_NTGUI)
5400 if (CONSP (cache))
5402 Lisp_Object entry;
5404 for (entry = XCDR (cache); CONSP (entry); entry = XCDR (entry))
5405 XSETCAR (entry, compact_font_cache_entry (XCAR (entry)));
5407 #endif /* not HAVE_NTGUI */
5408 mark_object (cache);
5412 #else /* not HAVE_WINDOW_SYSTEM */
5414 #define compact_font_caches() (void)(0)
5416 #endif /* HAVE_WINDOW_SYSTEM */
5418 /* Remove (MARKER . DATA) entries with unmarked MARKER
5419 from buffer undo LIST and return changed list. */
5421 static Lisp_Object
5422 compact_undo_list (Lisp_Object list)
5424 Lisp_Object tail, *prev = &list;
5426 for (tail = list; CONSP (tail); tail = XCDR (tail))
5428 if (CONSP (XCAR (tail))
5429 && MARKERP (XCAR (XCAR (tail)))
5430 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5431 *prev = XCDR (tail);
5432 else
5433 prev = xcdr_addr (tail);
5435 return list;
5438 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
5439 doc: /* Reclaim storage for Lisp objects no longer needed.
5440 Garbage collection happens automatically if you cons more than
5441 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5442 `garbage-collect' normally returns a list with info on amount of space in use,
5443 where each entry has the form (NAME SIZE USED FREE), where:
5444 - NAME is a symbol describing the kind of objects this entry represents,
5445 - SIZE is the number of bytes used by each one,
5446 - USED is the number of those objects that were found live in the heap,
5447 - FREE is the number of those objects that are not live but that Emacs
5448 keeps around for future allocations (maybe because it does not know how
5449 to return them to the OS).
5450 However, if there was overflow in pure space, `garbage-collect'
5451 returns nil, because real GC can't be done.
5452 See Info node `(elisp)Garbage Collection'. */)
5453 (void)
5455 struct buffer *nextb;
5456 char stack_top_variable;
5457 ptrdiff_t i;
5458 bool message_p;
5459 ptrdiff_t count = SPECPDL_INDEX ();
5460 struct timespec start;
5461 Lisp_Object retval = Qnil;
5462 size_t tot_before = 0;
5464 if (abort_on_gc)
5465 emacs_abort ();
5467 /* Can't GC if pure storage overflowed because we can't determine
5468 if something is a pure object or not. */
5469 if (pure_bytes_used_before_overflow)
5470 return Qnil;
5472 /* Record this function, so it appears on the profiler's backtraces. */
5473 record_in_backtrace (Qautomatic_gc, &Qnil, 0);
5475 check_cons_list ();
5477 /* Don't keep undo information around forever.
5478 Do this early on, so it is no problem if the user quits. */
5479 FOR_EACH_BUFFER (nextb)
5480 compact_buffer (nextb);
5482 if (profiler_memory_running)
5483 tot_before = total_bytes_of_live_objects ();
5485 start = current_timespec ();
5487 /* In case user calls debug_print during GC,
5488 don't let that cause a recursive GC. */
5489 consing_since_gc = 0;
5491 /* Save what's currently displayed in the echo area. */
5492 message_p = push_message ();
5493 record_unwind_protect_void (pop_message_unwind);
5495 /* Save a copy of the contents of the stack, for debugging. */
5496 #if MAX_SAVE_STACK > 0
5497 if (NILP (Vpurify_flag))
5499 char *stack;
5500 ptrdiff_t stack_size;
5501 if (&stack_top_variable < stack_bottom)
5503 stack = &stack_top_variable;
5504 stack_size = stack_bottom - &stack_top_variable;
5506 else
5508 stack = stack_bottom;
5509 stack_size = &stack_top_variable - stack_bottom;
5511 if (stack_size <= MAX_SAVE_STACK)
5513 if (stack_copy_size < stack_size)
5515 stack_copy = xrealloc (stack_copy, stack_size);
5516 stack_copy_size = stack_size;
5518 no_sanitize_memcpy (stack_copy, stack, stack_size);
5521 #endif /* MAX_SAVE_STACK > 0 */
5523 if (garbage_collection_messages)
5524 message1_nolog ("Garbage collecting...");
5526 block_input ();
5528 shrink_regexp_cache ();
5530 gc_in_progress = 1;
5532 /* Mark all the special slots that serve as the roots of accessibility. */
5534 mark_buffer (&buffer_defaults);
5535 mark_buffer (&buffer_local_symbols);
5537 for (i = 0; i < staticidx; i++)
5538 mark_object (*staticvec[i]);
5540 mark_specpdl ();
5541 mark_terminals ();
5542 mark_kboards ();
5544 #ifdef USE_GTK
5545 xg_mark_data ();
5546 #endif
5548 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
5549 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
5550 mark_stack ();
5551 #else
5553 register struct gcpro *tail;
5554 for (tail = gcprolist; tail; tail = tail->next)
5555 for (i = 0; i < tail->nvars; i++)
5556 mark_object (tail->var[i]);
5558 mark_byte_stack ();
5559 #endif
5561 struct handler *handler;
5562 for (handler = handlerlist; handler; handler = handler->next)
5564 mark_object (handler->tag_or_ch);
5565 mark_object (handler->val);
5568 #ifdef HAVE_WINDOW_SYSTEM
5569 mark_fringe_data ();
5570 #endif
5572 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5573 mark_stack ();
5574 #endif
5576 /* Everything is now marked, except for the data in font caches
5577 and undo lists. They're compacted by removing an items which
5578 aren't reachable otherwise. */
5580 compact_font_caches ();
5582 FOR_EACH_BUFFER (nextb)
5584 if (!EQ (BVAR (nextb, undo_list), Qt))
5585 bset_undo_list (nextb, compact_undo_list (BVAR (nextb, undo_list)));
5586 /* Now that we have stripped the elements that need not be
5587 in the undo_list any more, we can finally mark the list. */
5588 mark_object (BVAR (nextb, undo_list));
5591 gc_sweep ();
5593 /* Clear the mark bits that we set in certain root slots. */
5595 unmark_byte_stack ();
5596 VECTOR_UNMARK (&buffer_defaults);
5597 VECTOR_UNMARK (&buffer_local_symbols);
5599 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
5600 dump_zombies ();
5601 #endif
5603 check_cons_list ();
5605 gc_in_progress = 0;
5607 unblock_input ();
5609 consing_since_gc = 0;
5610 if (gc_cons_threshold < GC_DEFAULT_THRESHOLD / 10)
5611 gc_cons_threshold = GC_DEFAULT_THRESHOLD / 10;
5613 gc_relative_threshold = 0;
5614 if (FLOATP (Vgc_cons_percentage))
5615 { /* Set gc_cons_combined_threshold. */
5616 double tot = total_bytes_of_live_objects ();
5618 tot *= XFLOAT_DATA (Vgc_cons_percentage);
5619 if (0 < tot)
5621 if (tot < TYPE_MAXIMUM (EMACS_INT))
5622 gc_relative_threshold = tot;
5623 else
5624 gc_relative_threshold = TYPE_MAXIMUM (EMACS_INT);
5628 if (garbage_collection_messages)
5630 if (message_p || minibuf_level > 0)
5631 restore_message ();
5632 else
5633 message1_nolog ("Garbage collecting...done");
5636 unbind_to (count, Qnil);
5638 Lisp_Object total[11];
5639 int total_size = 10;
5641 total[0] = list4 (Qconses, make_number (sizeof (struct Lisp_Cons)),
5642 bounded_number (total_conses),
5643 bounded_number (total_free_conses));
5645 total[1] = list4 (Qsymbols, make_number (sizeof (struct Lisp_Symbol)),
5646 bounded_number (total_symbols),
5647 bounded_number (total_free_symbols));
5649 total[2] = list4 (Qmiscs, make_number (sizeof (union Lisp_Misc)),
5650 bounded_number (total_markers),
5651 bounded_number (total_free_markers));
5653 total[3] = list4 (Qstrings, make_number (sizeof (struct Lisp_String)),
5654 bounded_number (total_strings),
5655 bounded_number (total_free_strings));
5657 total[4] = list3 (Qstring_bytes, make_number (1),
5658 bounded_number (total_string_bytes));
5660 total[5] = list3 (Qvectors,
5661 make_number (header_size + sizeof (Lisp_Object)),
5662 bounded_number (total_vectors));
5664 total[6] = list4 (Qvector_slots, make_number (word_size),
5665 bounded_number (total_vector_slots),
5666 bounded_number (total_free_vector_slots));
5668 total[7] = list4 (Qfloats, make_number (sizeof (struct Lisp_Float)),
5669 bounded_number (total_floats),
5670 bounded_number (total_free_floats));
5672 total[8] = list4 (Qintervals, make_number (sizeof (struct interval)),
5673 bounded_number (total_intervals),
5674 bounded_number (total_free_intervals));
5676 total[9] = list3 (Qbuffers, make_number (sizeof (struct buffer)),
5677 bounded_number (total_buffers));
5679 #ifdef DOUG_LEA_MALLOC
5680 total_size++;
5681 total[10] = list4 (Qheap, make_number (1024),
5682 bounded_number ((mallinfo ().uordblks + 1023) >> 10),
5683 bounded_number ((mallinfo ().fordblks + 1023) >> 10));
5684 #endif
5685 retval = Flist (total_size, total);
5688 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5690 /* Compute average percentage of zombies. */
5691 double nlive
5692 = (total_conses + total_symbols + total_markers + total_strings
5693 + total_vectors + total_floats + total_intervals + total_buffers);
5695 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
5696 max_live = max (nlive, max_live);
5697 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
5698 max_zombies = max (nzombies, max_zombies);
5699 ++ngcs;
5701 #endif
5703 if (!NILP (Vpost_gc_hook))
5705 ptrdiff_t gc_count = inhibit_garbage_collection ();
5706 safe_run_hooks (Qpost_gc_hook);
5707 unbind_to (gc_count, Qnil);
5710 /* Accumulate statistics. */
5711 if (FLOATP (Vgc_elapsed))
5713 struct timespec since_start = timespec_sub (current_timespec (), start);
5714 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed)
5715 + timespectod (since_start));
5718 gcs_done++;
5720 /* Collect profiling data. */
5721 if (profiler_memory_running)
5723 size_t swept = 0;
5724 size_t tot_after = total_bytes_of_live_objects ();
5725 if (tot_before > tot_after)
5726 swept = tot_before - tot_after;
5727 malloc_probe (swept);
5730 return retval;
5734 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5735 only interesting objects referenced from glyphs are strings. */
5737 static void
5738 mark_glyph_matrix (struct glyph_matrix *matrix)
5740 struct glyph_row *row = matrix->rows;
5741 struct glyph_row *end = row + matrix->nrows;
5743 for (; row < end; ++row)
5744 if (row->enabled_p)
5746 int area;
5747 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
5749 struct glyph *glyph = row->glyphs[area];
5750 struct glyph *end_glyph = glyph + row->used[area];
5752 for (; glyph < end_glyph; ++glyph)
5753 if (STRINGP (glyph->object)
5754 && !STRING_MARKED_P (XSTRING (glyph->object)))
5755 mark_object (glyph->object);
5760 /* Mark reference to a Lisp_Object.
5761 If the object referred to has not been seen yet, recursively mark
5762 all the references contained in it. */
5764 #define LAST_MARKED_SIZE 500
5765 static Lisp_Object last_marked[LAST_MARKED_SIZE];
5766 static int last_marked_index;
5768 /* For debugging--call abort when we cdr down this many
5769 links of a list, in mark_object. In debugging,
5770 the call to abort will hit a breakpoint.
5771 Normally this is zero and the check never goes off. */
5772 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE;
5774 static void
5775 mark_vectorlike (struct Lisp_Vector *ptr)
5777 ptrdiff_t size = ptr->header.size;
5778 ptrdiff_t i;
5780 eassert (!VECTOR_MARKED_P (ptr));
5781 VECTOR_MARK (ptr); /* Else mark it. */
5782 if (size & PSEUDOVECTOR_FLAG)
5783 size &= PSEUDOVECTOR_SIZE_MASK;
5785 /* Note that this size is not the memory-footprint size, but only
5786 the number of Lisp_Object fields that we should trace.
5787 The distinction is used e.g. by Lisp_Process which places extra
5788 non-Lisp_Object fields at the end of the structure... */
5789 for (i = 0; i < size; i++) /* ...and then mark its elements. */
5790 mark_object (ptr->contents[i]);
5793 /* Like mark_vectorlike but optimized for char-tables (and
5794 sub-char-tables) assuming that the contents are mostly integers or
5795 symbols. */
5797 static void
5798 mark_char_table (struct Lisp_Vector *ptr)
5800 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5801 int i;
5803 eassert (!VECTOR_MARKED_P (ptr));
5804 VECTOR_MARK (ptr);
5805 for (i = 0; i < size; i++)
5807 Lisp_Object val = ptr->contents[i];
5809 if (INTEGERP (val) || (SYMBOLP (val) && XSYMBOL (val)->gcmarkbit))
5810 continue;
5811 if (SUB_CHAR_TABLE_P (val))
5813 if (! VECTOR_MARKED_P (XVECTOR (val)))
5814 mark_char_table (XVECTOR (val));
5816 else
5817 mark_object (val);
5821 /* Mark the chain of overlays starting at PTR. */
5823 static void
5824 mark_overlay (struct Lisp_Overlay *ptr)
5826 for (; ptr && !ptr->gcmarkbit; ptr = ptr->next)
5828 ptr->gcmarkbit = 1;
5829 mark_object (ptr->start);
5830 mark_object (ptr->end);
5831 mark_object (ptr->plist);
5835 /* Mark Lisp_Objects and special pointers in BUFFER. */
5837 static void
5838 mark_buffer (struct buffer *buffer)
5840 /* This is handled much like other pseudovectors... */
5841 mark_vectorlike ((struct Lisp_Vector *) buffer);
5843 /* ...but there are some buffer-specific things. */
5845 MARK_INTERVAL_TREE (buffer_intervals (buffer));
5847 /* For now, we just don't mark the undo_list. It's done later in
5848 a special way just before the sweep phase, and after stripping
5849 some of its elements that are not needed any more. */
5851 mark_overlay (buffer->overlays_before);
5852 mark_overlay (buffer->overlays_after);
5854 /* If this is an indirect buffer, mark its base buffer. */
5855 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5856 mark_buffer (buffer->base_buffer);
5859 /* Mark Lisp faces in the face cache C. */
5861 static void
5862 mark_face_cache (struct face_cache *c)
5864 if (c)
5866 int i, j;
5867 for (i = 0; i < c->used; ++i)
5869 struct face *face = FACE_FROM_ID (c->f, i);
5871 if (face)
5873 if (face->font && !VECTOR_MARKED_P (face->font))
5874 mark_vectorlike ((struct Lisp_Vector *) face->font);
5876 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
5877 mark_object (face->lface[j]);
5883 /* Remove killed buffers or items whose car is a killed buffer from
5884 LIST, and mark other items. Return changed LIST, which is marked. */
5886 static Lisp_Object
5887 mark_discard_killed_buffers (Lisp_Object list)
5889 Lisp_Object tail, *prev = &list;
5891 for (tail = list; CONSP (tail) && !CONS_MARKED_P (XCONS (tail));
5892 tail = XCDR (tail))
5894 Lisp_Object tem = XCAR (tail);
5895 if (CONSP (tem))
5896 tem = XCAR (tem);
5897 if (BUFFERP (tem) && !BUFFER_LIVE_P (XBUFFER (tem)))
5898 *prev = XCDR (tail);
5899 else
5901 CONS_MARK (XCONS (tail));
5902 mark_object (XCAR (tail));
5903 prev = xcdr_addr (tail);
5906 mark_object (tail);
5907 return list;
5910 /* Determine type of generic Lisp_Object and mark it accordingly. */
5912 void
5913 mark_object (Lisp_Object arg)
5915 register Lisp_Object obj = arg;
5916 #ifdef GC_CHECK_MARKED_OBJECTS
5917 void *po;
5918 struct mem_node *m;
5919 #endif
5920 ptrdiff_t cdr_count = 0;
5922 loop:
5924 if (PURE_POINTER_P (XPNTR (obj)))
5925 return;
5927 last_marked[last_marked_index++] = obj;
5928 if (last_marked_index == LAST_MARKED_SIZE)
5929 last_marked_index = 0;
5931 /* Perform some sanity checks on the objects marked here. Abort if
5932 we encounter an object we know is bogus. This increases GC time
5933 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
5934 #ifdef GC_CHECK_MARKED_OBJECTS
5936 po = (void *) XPNTR (obj);
5938 /* Check that the object pointed to by PO is known to be a Lisp
5939 structure allocated from the heap. */
5940 #define CHECK_ALLOCATED() \
5941 do { \
5942 m = mem_find (po); \
5943 if (m == MEM_NIL) \
5944 emacs_abort (); \
5945 } while (0)
5947 /* Check that the object pointed to by PO is live, using predicate
5948 function LIVEP. */
5949 #define CHECK_LIVE(LIVEP) \
5950 do { \
5951 if (!LIVEP (m, po)) \
5952 emacs_abort (); \
5953 } while (0)
5955 /* Check both of the above conditions. */
5956 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
5957 do { \
5958 CHECK_ALLOCATED (); \
5959 CHECK_LIVE (LIVEP); \
5960 } while (0) \
5962 #else /* not GC_CHECK_MARKED_OBJECTS */
5964 #define CHECK_LIVE(LIVEP) (void) 0
5965 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
5967 #endif /* not GC_CHECK_MARKED_OBJECTS */
5969 switch (XTYPE (obj))
5971 case Lisp_String:
5973 register struct Lisp_String *ptr = XSTRING (obj);
5974 if (STRING_MARKED_P (ptr))
5975 break;
5976 CHECK_ALLOCATED_AND_LIVE (live_string_p);
5977 MARK_STRING (ptr);
5978 MARK_INTERVAL_TREE (ptr->intervals);
5979 #ifdef GC_CHECK_STRING_BYTES
5980 /* Check that the string size recorded in the string is the
5981 same as the one recorded in the sdata structure. */
5982 string_bytes (ptr);
5983 #endif /* GC_CHECK_STRING_BYTES */
5985 break;
5987 case Lisp_Vectorlike:
5989 register struct Lisp_Vector *ptr = XVECTOR (obj);
5990 register ptrdiff_t pvectype;
5992 if (VECTOR_MARKED_P (ptr))
5993 break;
5995 #ifdef GC_CHECK_MARKED_OBJECTS
5996 m = mem_find (po);
5997 if (m == MEM_NIL && !SUBRP (obj))
5998 emacs_abort ();
5999 #endif /* GC_CHECK_MARKED_OBJECTS */
6001 if (ptr->header.size & PSEUDOVECTOR_FLAG)
6002 pvectype = ((ptr->header.size & PVEC_TYPE_MASK)
6003 >> PSEUDOVECTOR_AREA_BITS);
6004 else
6005 pvectype = PVEC_NORMAL_VECTOR;
6007 if (pvectype != PVEC_SUBR && pvectype != PVEC_BUFFER)
6008 CHECK_LIVE (live_vector_p);
6010 switch (pvectype)
6012 case PVEC_BUFFER:
6013 #ifdef GC_CHECK_MARKED_OBJECTS
6015 struct buffer *b;
6016 FOR_EACH_BUFFER (b)
6017 if (b == po)
6018 break;
6019 if (b == NULL)
6020 emacs_abort ();
6022 #endif /* GC_CHECK_MARKED_OBJECTS */
6023 mark_buffer ((struct buffer *) ptr);
6024 break;
6026 case PVEC_COMPILED:
6027 { /* We could treat this just like a vector, but it is better
6028 to save the COMPILED_CONSTANTS element for last and avoid
6029 recursion there. */
6030 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
6031 int i;
6033 VECTOR_MARK (ptr);
6034 for (i = 0; i < size; i++)
6035 if (i != COMPILED_CONSTANTS)
6036 mark_object (ptr->contents[i]);
6037 if (size > COMPILED_CONSTANTS)
6039 obj = ptr->contents[COMPILED_CONSTANTS];
6040 goto loop;
6043 break;
6045 case PVEC_FRAME:
6047 struct frame *f = (struct frame *) ptr;
6049 mark_vectorlike (ptr);
6050 mark_face_cache (f->face_cache);
6051 #ifdef HAVE_WINDOW_SYSTEM
6052 if (FRAME_WINDOW_P (f) && FRAME_X_OUTPUT (f))
6054 struct font *font = FRAME_FONT (f);
6056 if (font && !VECTOR_MARKED_P (font))
6057 mark_vectorlike ((struct Lisp_Vector *) font);
6059 #endif
6061 break;
6063 case PVEC_WINDOW:
6065 struct window *w = (struct window *) ptr;
6067 mark_vectorlike (ptr);
6069 /* Mark glyph matrices, if any. Marking window
6070 matrices is sufficient because frame matrices
6071 use the same glyph memory. */
6072 if (w->current_matrix)
6074 mark_glyph_matrix (w->current_matrix);
6075 mark_glyph_matrix (w->desired_matrix);
6078 /* Filter out killed buffers from both buffer lists
6079 in attempt to help GC to reclaim killed buffers faster.
6080 We can do it elsewhere for live windows, but this is the
6081 best place to do it for dead windows. */
6082 wset_prev_buffers
6083 (w, mark_discard_killed_buffers (w->prev_buffers));
6084 wset_next_buffers
6085 (w, mark_discard_killed_buffers (w->next_buffers));
6087 break;
6089 case PVEC_HASH_TABLE:
6091 struct Lisp_Hash_Table *h = (struct Lisp_Hash_Table *) ptr;
6093 mark_vectorlike (ptr);
6094 mark_object (h->test.name);
6095 mark_object (h->test.user_hash_function);
6096 mark_object (h->test.user_cmp_function);
6097 /* If hash table is not weak, mark all keys and values.
6098 For weak tables, mark only the vector. */
6099 if (NILP (h->weak))
6100 mark_object (h->key_and_value);
6101 else
6102 VECTOR_MARK (XVECTOR (h->key_and_value));
6104 break;
6106 case PVEC_CHAR_TABLE:
6107 mark_char_table (ptr);
6108 break;
6110 case PVEC_BOOL_VECTOR:
6111 /* No Lisp_Objects to mark in a bool vector. */
6112 VECTOR_MARK (ptr);
6113 break;
6115 case PVEC_SUBR:
6116 break;
6118 case PVEC_FREE:
6119 emacs_abort ();
6121 default:
6122 mark_vectorlike (ptr);
6125 break;
6127 case Lisp_Symbol:
6129 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
6130 struct Lisp_Symbol *ptrx;
6132 if (ptr->gcmarkbit)
6133 break;
6134 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
6135 ptr->gcmarkbit = 1;
6136 mark_object (ptr->function);
6137 mark_object (ptr->plist);
6138 switch (ptr->redirect)
6140 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
6141 case SYMBOL_VARALIAS:
6143 Lisp_Object tem;
6144 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
6145 mark_object (tem);
6146 break;
6148 case SYMBOL_LOCALIZED:
6150 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
6151 Lisp_Object where = blv->where;
6152 /* If the value is set up for a killed buffer or deleted
6153 frame, restore it's global binding. If the value is
6154 forwarded to a C variable, either it's not a Lisp_Object
6155 var, or it's staticpro'd already. */
6156 if ((BUFFERP (where) && !BUFFER_LIVE_P (XBUFFER (where)))
6157 || (FRAMEP (where) && !FRAME_LIVE_P (XFRAME (where))))
6158 swap_in_global_binding (ptr);
6159 mark_object (blv->where);
6160 mark_object (blv->valcell);
6161 mark_object (blv->defcell);
6162 break;
6164 case SYMBOL_FORWARDED:
6165 /* If the value is forwarded to a buffer or keyboard field,
6166 these are marked when we see the corresponding object.
6167 And if it's forwarded to a C variable, either it's not
6168 a Lisp_Object var, or it's staticpro'd already. */
6169 break;
6170 default: emacs_abort ();
6172 if (!PURE_POINTER_P (XSTRING (ptr->name)))
6173 MARK_STRING (XSTRING (ptr->name));
6174 MARK_INTERVAL_TREE (string_intervals (ptr->name));
6176 ptr = ptr->next;
6177 if (ptr)
6179 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun. */
6180 XSETSYMBOL (obj, ptrx);
6181 goto loop;
6184 break;
6186 case Lisp_Misc:
6187 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
6189 if (XMISCANY (obj)->gcmarkbit)
6190 break;
6192 switch (XMISCTYPE (obj))
6194 case Lisp_Misc_Marker:
6195 /* DO NOT mark thru the marker's chain.
6196 The buffer's markers chain does not preserve markers from gc;
6197 instead, markers are removed from the chain when freed by gc. */
6198 XMISCANY (obj)->gcmarkbit = 1;
6199 break;
6201 case Lisp_Misc_Save_Value:
6202 XMISCANY (obj)->gcmarkbit = 1;
6204 struct Lisp_Save_Value *ptr = XSAVE_VALUE (obj);
6205 /* If `save_type' is zero, `data[0].pointer' is the address
6206 of a memory area containing `data[1].integer' potential
6207 Lisp_Objects. */
6208 if (GC_MARK_STACK && ptr->save_type == SAVE_TYPE_MEMORY)
6210 Lisp_Object *p = ptr->data[0].pointer;
6211 ptrdiff_t nelt;
6212 for (nelt = ptr->data[1].integer; nelt > 0; nelt--, p++)
6213 mark_maybe_object (*p);
6215 else
6217 /* Find Lisp_Objects in `data[N]' slots and mark them. */
6218 int i;
6219 for (i = 0; i < SAVE_VALUE_SLOTS; i++)
6220 if (save_type (ptr, i) == SAVE_OBJECT)
6221 mark_object (ptr->data[i].object);
6224 break;
6226 case Lisp_Misc_Overlay:
6227 mark_overlay (XOVERLAY (obj));
6228 break;
6230 default:
6231 emacs_abort ();
6233 break;
6235 case Lisp_Cons:
6237 register struct Lisp_Cons *ptr = XCONS (obj);
6238 if (CONS_MARKED_P (ptr))
6239 break;
6240 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
6241 CONS_MARK (ptr);
6242 /* If the cdr is nil, avoid recursion for the car. */
6243 if (EQ (ptr->u.cdr, Qnil))
6245 obj = ptr->car;
6246 cdr_count = 0;
6247 goto loop;
6249 mark_object (ptr->car);
6250 obj = ptr->u.cdr;
6251 cdr_count++;
6252 if (cdr_count == mark_object_loop_halt)
6253 emacs_abort ();
6254 goto loop;
6257 case Lisp_Float:
6258 CHECK_ALLOCATED_AND_LIVE (live_float_p);
6259 FLOAT_MARK (XFLOAT (obj));
6260 break;
6262 case_Lisp_Int:
6263 break;
6265 default:
6266 emacs_abort ();
6269 #undef CHECK_LIVE
6270 #undef CHECK_ALLOCATED
6271 #undef CHECK_ALLOCATED_AND_LIVE
6273 /* Mark the Lisp pointers in the terminal objects.
6274 Called by Fgarbage_collect. */
6276 static void
6277 mark_terminals (void)
6279 struct terminal *t;
6280 for (t = terminal_list; t; t = t->next_terminal)
6282 eassert (t->name != NULL);
6283 #ifdef HAVE_WINDOW_SYSTEM
6284 /* If a terminal object is reachable from a stacpro'ed object,
6285 it might have been marked already. Make sure the image cache
6286 gets marked. */
6287 mark_image_cache (t->image_cache);
6288 #endif /* HAVE_WINDOW_SYSTEM */
6289 if (!VECTOR_MARKED_P (t))
6290 mark_vectorlike ((struct Lisp_Vector *)t);
6296 /* Value is non-zero if OBJ will survive the current GC because it's
6297 either marked or does not need to be marked to survive. */
6299 bool
6300 survives_gc_p (Lisp_Object obj)
6302 bool survives_p;
6304 switch (XTYPE (obj))
6306 case_Lisp_Int:
6307 survives_p = 1;
6308 break;
6310 case Lisp_Symbol:
6311 survives_p = XSYMBOL (obj)->gcmarkbit;
6312 break;
6314 case Lisp_Misc:
6315 survives_p = XMISCANY (obj)->gcmarkbit;
6316 break;
6318 case Lisp_String:
6319 survives_p = STRING_MARKED_P (XSTRING (obj));
6320 break;
6322 case Lisp_Vectorlike:
6323 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
6324 break;
6326 case Lisp_Cons:
6327 survives_p = CONS_MARKED_P (XCONS (obj));
6328 break;
6330 case Lisp_Float:
6331 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
6332 break;
6334 default:
6335 emacs_abort ();
6338 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
6343 /* Sweep: find all structures not marked, and free them. */
6345 static void
6346 gc_sweep (void)
6348 /* Remove or mark entries in weak hash tables.
6349 This must be done before any object is unmarked. */
6350 sweep_weak_hash_tables ();
6352 sweep_strings ();
6353 check_string_bytes (!noninteractive);
6355 /* Put all unmarked conses on free list. */
6357 register struct cons_block *cblk;
6358 struct cons_block **cprev = &cons_block;
6359 register int lim = cons_block_index;
6360 EMACS_INT num_free = 0, num_used = 0;
6362 cons_free_list = 0;
6364 for (cblk = cons_block; cblk; cblk = *cprev)
6366 register int i = 0;
6367 int this_free = 0;
6368 int ilim = (lim + BITS_PER_INT - 1) / BITS_PER_INT;
6370 /* Scan the mark bits an int at a time. */
6371 for (i = 0; i < ilim; i++)
6373 if (cblk->gcmarkbits[i] == -1)
6375 /* Fast path - all cons cells for this int are marked. */
6376 cblk->gcmarkbits[i] = 0;
6377 num_used += BITS_PER_INT;
6379 else
6381 /* Some cons cells for this int are not marked.
6382 Find which ones, and free them. */
6383 int start, pos, stop;
6385 start = i * BITS_PER_INT;
6386 stop = lim - start;
6387 if (stop > BITS_PER_INT)
6388 stop = BITS_PER_INT;
6389 stop += start;
6391 for (pos = start; pos < stop; pos++)
6393 if (!CONS_MARKED_P (&cblk->conses[pos]))
6395 this_free++;
6396 cblk->conses[pos].u.chain = cons_free_list;
6397 cons_free_list = &cblk->conses[pos];
6398 #if GC_MARK_STACK
6399 cons_free_list->car = Vdead;
6400 #endif
6402 else
6404 num_used++;
6405 CONS_UNMARK (&cblk->conses[pos]);
6411 lim = CONS_BLOCK_SIZE;
6412 /* If this block contains only free conses and we have already
6413 seen more than two blocks worth of free conses then deallocate
6414 this block. */
6415 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
6417 *cprev = cblk->next;
6418 /* Unhook from the free list. */
6419 cons_free_list = cblk->conses[0].u.chain;
6420 lisp_align_free (cblk);
6422 else
6424 num_free += this_free;
6425 cprev = &cblk->next;
6428 total_conses = num_used;
6429 total_free_conses = num_free;
6432 /* Put all unmarked floats on free list. */
6434 register struct float_block *fblk;
6435 struct float_block **fprev = &float_block;
6436 register int lim = float_block_index;
6437 EMACS_INT num_free = 0, num_used = 0;
6439 float_free_list = 0;
6441 for (fblk = float_block; fblk; fblk = *fprev)
6443 register int i;
6444 int this_free = 0;
6445 for (i = 0; i < lim; i++)
6446 if (!FLOAT_MARKED_P (&fblk->floats[i]))
6448 this_free++;
6449 fblk->floats[i].u.chain = float_free_list;
6450 float_free_list = &fblk->floats[i];
6452 else
6454 num_used++;
6455 FLOAT_UNMARK (&fblk->floats[i]);
6457 lim = FLOAT_BLOCK_SIZE;
6458 /* If this block contains only free floats and we have already
6459 seen more than two blocks worth of free floats then deallocate
6460 this block. */
6461 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6463 *fprev = fblk->next;
6464 /* Unhook from the free list. */
6465 float_free_list = fblk->floats[0].u.chain;
6466 lisp_align_free (fblk);
6468 else
6470 num_free += this_free;
6471 fprev = &fblk->next;
6474 total_floats = num_used;
6475 total_free_floats = num_free;
6478 /* Put all unmarked intervals on free list. */
6480 register struct interval_block *iblk;
6481 struct interval_block **iprev = &interval_block;
6482 register int lim = interval_block_index;
6483 EMACS_INT num_free = 0, num_used = 0;
6485 interval_free_list = 0;
6487 for (iblk = interval_block; iblk; iblk = *iprev)
6489 register int i;
6490 int this_free = 0;
6492 for (i = 0; i < lim; i++)
6494 if (!iblk->intervals[i].gcmarkbit)
6496 set_interval_parent (&iblk->intervals[i], interval_free_list);
6497 interval_free_list = &iblk->intervals[i];
6498 this_free++;
6500 else
6502 num_used++;
6503 iblk->intervals[i].gcmarkbit = 0;
6506 lim = INTERVAL_BLOCK_SIZE;
6507 /* If this block contains only free intervals and we have already
6508 seen more than two blocks worth of free intervals then
6509 deallocate this block. */
6510 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6512 *iprev = iblk->next;
6513 /* Unhook from the free list. */
6514 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
6515 lisp_free (iblk);
6517 else
6519 num_free += this_free;
6520 iprev = &iblk->next;
6523 total_intervals = num_used;
6524 total_free_intervals = num_free;
6527 /* Put all unmarked symbols on free list. */
6529 register struct symbol_block *sblk;
6530 struct symbol_block **sprev = &symbol_block;
6531 register int lim = symbol_block_index;
6532 EMACS_INT num_free = 0, num_used = 0;
6534 symbol_free_list = NULL;
6536 for (sblk = symbol_block; sblk; sblk = *sprev)
6538 int this_free = 0;
6539 union aligned_Lisp_Symbol *sym = sblk->symbols;
6540 union aligned_Lisp_Symbol *end = sym + lim;
6542 for (; sym < end; ++sym)
6544 /* Check if the symbol was created during loadup. In such a case
6545 it might be pointed to by pure bytecode which we don't trace,
6546 so we conservatively assume that it is live. */
6547 bool pure_p = PURE_POINTER_P (XSTRING (sym->s.name));
6549 if (!sym->s.gcmarkbit && !pure_p)
6551 if (sym->s.redirect == SYMBOL_LOCALIZED)
6552 xfree (SYMBOL_BLV (&sym->s));
6553 sym->s.next = symbol_free_list;
6554 symbol_free_list = &sym->s;
6555 #if GC_MARK_STACK
6556 symbol_free_list->function = Vdead;
6557 #endif
6558 ++this_free;
6560 else
6562 ++num_used;
6563 if (!pure_p)
6564 eassert (!STRING_MARKED_P (XSTRING (sym->s.name)));
6565 sym->s.gcmarkbit = 0;
6569 lim = SYMBOL_BLOCK_SIZE;
6570 /* If this block contains only free symbols and we have already
6571 seen more than two blocks worth of free symbols then deallocate
6572 this block. */
6573 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6575 *sprev = sblk->next;
6576 /* Unhook from the free list. */
6577 symbol_free_list = sblk->symbols[0].s.next;
6578 lisp_free (sblk);
6580 else
6582 num_free += this_free;
6583 sprev = &sblk->next;
6586 total_symbols = num_used;
6587 total_free_symbols = num_free;
6590 /* Put all unmarked misc's on free list.
6591 For a marker, first unchain it from the buffer it points into. */
6593 register struct marker_block *mblk;
6594 struct marker_block **mprev = &marker_block;
6595 register int lim = marker_block_index;
6596 EMACS_INT num_free = 0, num_used = 0;
6598 marker_free_list = 0;
6600 for (mblk = marker_block; mblk; mblk = *mprev)
6602 register int i;
6603 int this_free = 0;
6605 for (i = 0; i < lim; i++)
6607 if (!mblk->markers[i].m.u_any.gcmarkbit)
6609 if (mblk->markers[i].m.u_any.type == Lisp_Misc_Marker)
6610 unchain_marker (&mblk->markers[i].m.u_marker);
6611 /* Set the type of the freed object to Lisp_Misc_Free.
6612 We could leave the type alone, since nobody checks it,
6613 but this might catch bugs faster. */
6614 mblk->markers[i].m.u_marker.type = Lisp_Misc_Free;
6615 mblk->markers[i].m.u_free.chain = marker_free_list;
6616 marker_free_list = &mblk->markers[i].m;
6617 this_free++;
6619 else
6621 num_used++;
6622 mblk->markers[i].m.u_any.gcmarkbit = 0;
6625 lim = MARKER_BLOCK_SIZE;
6626 /* If this block contains only free markers and we have already
6627 seen more than two blocks worth of free markers then deallocate
6628 this block. */
6629 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6631 *mprev = mblk->next;
6632 /* Unhook from the free list. */
6633 marker_free_list = mblk->markers[0].m.u_free.chain;
6634 lisp_free (mblk);
6636 else
6638 num_free += this_free;
6639 mprev = &mblk->next;
6643 total_markers = num_used;
6644 total_free_markers = num_free;
6647 /* Free all unmarked buffers */
6649 register struct buffer *buffer, **bprev = &all_buffers;
6651 total_buffers = 0;
6652 for (buffer = all_buffers; buffer; buffer = *bprev)
6653 if (!VECTOR_MARKED_P (buffer))
6655 *bprev = buffer->next;
6656 lisp_free (buffer);
6658 else
6660 VECTOR_UNMARK (buffer);
6661 /* Do not use buffer_(set|get)_intervals here. */
6662 buffer->text->intervals = balance_intervals (buffer->text->intervals);
6663 total_buffers++;
6664 bprev = &buffer->next;
6668 sweep_vectors ();
6669 check_string_bytes (!noninteractive);
6675 /* Debugging aids. */
6677 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
6678 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6679 This may be helpful in debugging Emacs's memory usage.
6680 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6681 (void)
6683 Lisp_Object end;
6685 #ifdef HAVE_NS
6686 /* Avoid warning. sbrk has no relation to memory allocated anyway. */
6687 XSETINT (end, 0);
6688 #else
6689 XSETINT (end, (intptr_t) (char *) sbrk (0) / 1024);
6690 #endif
6692 return end;
6695 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
6696 doc: /* Return a list of counters that measure how much consing there has been.
6697 Each of these counters increments for a certain kind of object.
6698 The counters wrap around from the largest positive integer to zero.
6699 Garbage collection does not decrease them.
6700 The elements of the value are as follows:
6701 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6702 All are in units of 1 = one object consed
6703 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6704 objects consed.
6705 MISCS include overlays, markers, and some internal types.
6706 Frames, windows, buffers, and subprocesses count as vectors
6707 (but the contents of a buffer's text do not count here). */)
6708 (void)
6710 return listn (CONSTYPE_HEAP, 8,
6711 bounded_number (cons_cells_consed),
6712 bounded_number (floats_consed),
6713 bounded_number (vector_cells_consed),
6714 bounded_number (symbols_consed),
6715 bounded_number (string_chars_consed),
6716 bounded_number (misc_objects_consed),
6717 bounded_number (intervals_consed),
6718 bounded_number (strings_consed));
6721 /* Find at most FIND_MAX symbols which have OBJ as their value or
6722 function. This is used in gdbinit's `xwhichsymbols' command. */
6724 Lisp_Object
6725 which_symbols (Lisp_Object obj, EMACS_INT find_max)
6727 struct symbol_block *sblk;
6728 ptrdiff_t gc_count = inhibit_garbage_collection ();
6729 Lisp_Object found = Qnil;
6731 if (! DEADP (obj))
6733 for (sblk = symbol_block; sblk; sblk = sblk->next)
6735 union aligned_Lisp_Symbol *aligned_sym = sblk->symbols;
6736 int bn;
6738 for (bn = 0; bn < SYMBOL_BLOCK_SIZE; bn++, aligned_sym++)
6740 struct Lisp_Symbol *sym = &aligned_sym->s;
6741 Lisp_Object val;
6742 Lisp_Object tem;
6744 if (sblk == symbol_block && bn >= symbol_block_index)
6745 break;
6747 XSETSYMBOL (tem, sym);
6748 val = find_symbol_value (tem);
6749 if (EQ (val, obj)
6750 || EQ (sym->function, obj)
6751 || (!NILP (sym->function)
6752 && COMPILEDP (sym->function)
6753 && EQ (AREF (sym->function, COMPILED_BYTECODE), obj))
6754 || (!NILP (val)
6755 && COMPILEDP (val)
6756 && EQ (AREF (val, COMPILED_BYTECODE), obj)))
6758 found = Fcons (tem, found);
6759 if (--find_max == 0)
6760 goto out;
6766 out:
6767 unbind_to (gc_count, Qnil);
6768 return found;
6771 #ifdef ENABLE_CHECKING
6773 bool suppress_checking;
6775 void
6776 die (const char *msg, const char *file, int line)
6778 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: assertion failed: %s\r\n",
6779 file, line, msg);
6780 terminate_due_to_signal (SIGABRT, INT_MAX);
6782 #endif
6784 /* Initialization. */
6786 void
6787 init_alloc_once (void)
6789 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
6790 purebeg = PUREBEG;
6791 pure_size = PURESIZE;
6793 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
6794 mem_init ();
6795 Vdead = make_pure_string ("DEAD", 4, 4, 0);
6796 #endif
6798 #ifdef DOUG_LEA_MALLOC
6799 mallopt (M_TRIM_THRESHOLD, 128 * 1024); /* Trim threshold. */
6800 mallopt (M_MMAP_THRESHOLD, 64 * 1024); /* Mmap threshold. */
6801 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* Max. number of mmap'ed areas. */
6802 #endif
6803 init_strings ();
6804 init_vectors ();
6806 refill_memory_reserve ();
6807 gc_cons_threshold = GC_DEFAULT_THRESHOLD;
6810 void
6811 init_alloc (void)
6813 gcprolist = 0;
6814 byte_stack_list = 0;
6815 #if GC_MARK_STACK
6816 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
6817 setjmp_tested_p = longjmps_done = 0;
6818 #endif
6819 #endif
6820 Vgc_elapsed = make_float (0.0);
6821 gcs_done = 0;
6823 #if USE_VALGRIND
6824 valgrind_p = RUNNING_ON_VALGRIND != 0;
6825 #endif
6828 void
6829 syms_of_alloc (void)
6831 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
6832 doc: /* Number of bytes of consing between garbage collections.
6833 Garbage collection can happen automatically once this many bytes have been
6834 allocated since the last garbage collection. All data types count.
6836 Garbage collection happens automatically only when `eval' is called.
6838 By binding this temporarily to a large number, you can effectively
6839 prevent garbage collection during a part of the program.
6840 See also `gc-cons-percentage'. */);
6842 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
6843 doc: /* Portion of the heap used for allocation.
6844 Garbage collection can happen automatically once this portion of the heap
6845 has been allocated since the last garbage collection.
6846 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
6847 Vgc_cons_percentage = make_float (0.1);
6849 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
6850 doc: /* Number of bytes of shareable Lisp data allocated so far. */);
6852 DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
6853 doc: /* Number of cons cells that have been consed so far. */);
6855 DEFVAR_INT ("floats-consed", floats_consed,
6856 doc: /* Number of floats that have been consed so far. */);
6858 DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
6859 doc: /* Number of vector cells that have been consed so far. */);
6861 DEFVAR_INT ("symbols-consed", symbols_consed,
6862 doc: /* Number of symbols that have been consed so far. */);
6864 DEFVAR_INT ("string-chars-consed", string_chars_consed,
6865 doc: /* Number of string characters that have been consed so far. */);
6867 DEFVAR_INT ("misc-objects-consed", misc_objects_consed,
6868 doc: /* Number of miscellaneous objects that have been consed so far.
6869 These include markers and overlays, plus certain objects not visible
6870 to users. */);
6872 DEFVAR_INT ("intervals-consed", intervals_consed,
6873 doc: /* Number of intervals that have been consed so far. */);
6875 DEFVAR_INT ("strings-consed", strings_consed,
6876 doc: /* Number of strings that have been consed so far. */);
6878 DEFVAR_LISP ("purify-flag", Vpurify_flag,
6879 doc: /* Non-nil means loading Lisp code in order to dump an executable.
6880 This means that certain objects should be allocated in shared (pure) space.
6881 It can also be set to a hash-table, in which case this table is used to
6882 do hash-consing of the objects allocated to pure space. */);
6884 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
6885 doc: /* Non-nil means display messages at start and end of garbage collection. */);
6886 garbage_collection_messages = 0;
6888 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
6889 doc: /* Hook run after garbage collection has finished. */);
6890 Vpost_gc_hook = Qnil;
6891 DEFSYM (Qpost_gc_hook, "post-gc-hook");
6893 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
6894 doc: /* Precomputed `signal' argument for memory-full error. */);
6895 /* We build this in advance because if we wait until we need it, we might
6896 not be able to allocate the memory to hold it. */
6897 Vmemory_signal_data
6898 = listn (CONSTYPE_PURE, 2, Qerror,
6899 build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
6901 DEFVAR_LISP ("memory-full", Vmemory_full,
6902 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
6903 Vmemory_full = Qnil;
6905 DEFSYM (Qconses, "conses");
6906 DEFSYM (Qsymbols, "symbols");
6907 DEFSYM (Qmiscs, "miscs");
6908 DEFSYM (Qstrings, "strings");
6909 DEFSYM (Qvectors, "vectors");
6910 DEFSYM (Qfloats, "floats");
6911 DEFSYM (Qintervals, "intervals");
6912 DEFSYM (Qbuffers, "buffers");
6913 DEFSYM (Qstring_bytes, "string-bytes");
6914 DEFSYM (Qvector_slots, "vector-slots");
6915 DEFSYM (Qheap, "heap");
6916 DEFSYM (Qautomatic_gc, "Automatic GC");
6918 DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
6919 DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
6921 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
6922 doc: /* Accumulated time elapsed in garbage collections.
6923 The time is in seconds as a floating point value. */);
6924 DEFVAR_INT ("gcs-done", gcs_done,
6925 doc: /* Accumulated number of garbage collections done. */);
6927 defsubr (&Scons);
6928 defsubr (&Slist);
6929 defsubr (&Svector);
6930 defsubr (&Smake_byte_code);
6931 defsubr (&Smake_list);
6932 defsubr (&Smake_vector);
6933 defsubr (&Smake_string);
6934 defsubr (&Smake_bool_vector);
6935 defsubr (&Smake_symbol);
6936 defsubr (&Smake_marker);
6937 defsubr (&Spurecopy);
6938 defsubr (&Sgarbage_collect);
6939 defsubr (&Smemory_limit);
6940 defsubr (&Smemory_use_counts);
6942 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
6943 defsubr (&Sgc_status);
6944 #endif
6947 /* When compiled with GCC, GDB might say "No enum type named
6948 pvec_type" if we don't have at least one symbol with that type, and
6949 then xbacktrace could fail. Similarly for the other enums and
6950 their values. Some non-GCC compilers don't like these constructs. */
6951 #ifdef __GNUC__
6952 union
6954 enum CHARTAB_SIZE_BITS CHARTAB_SIZE_BITS;
6955 enum CHAR_TABLE_STANDARD_SLOTS CHAR_TABLE_STANDARD_SLOTS;
6956 enum char_bits char_bits;
6957 enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE;
6958 enum DEFAULT_HASH_SIZE DEFAULT_HASH_SIZE;
6959 enum enum_USE_LSB_TAG enum_USE_LSB_TAG;
6960 enum FLOAT_TO_STRING_BUFSIZE FLOAT_TO_STRING_BUFSIZE;
6961 enum Lisp_Bits Lisp_Bits;
6962 enum Lisp_Compiled Lisp_Compiled;
6963 enum maxargs maxargs;
6964 enum MAX_ALLOCA MAX_ALLOCA;
6965 enum More_Lisp_Bits More_Lisp_Bits;
6966 enum pvec_type pvec_type;
6967 } const EXTERNALLY_VISIBLE gdb_make_enums_visible = {0};
6968 #endif /* __GNUC__ */