Make pcomplete less eager to add an extra space.
[emacs.git] / src / alloc.c
blobfb7d35b55902f0ad286c0566f828b7ddaf57840d
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
3 Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2012
4 Free Software 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 #define LISP_INLINE EXTERN_INLINE
25 #include <stdio.h>
26 #include <limits.h> /* For CHAR_BIT. */
28 #ifdef ENABLE_CHECKING
29 #include <signal.h> /* For SIGABRT. */
30 #endif
32 #ifdef HAVE_PTHREAD
33 #include <pthread.h>
34 #endif
36 #include "lisp.h"
37 #include "process.h"
38 #include "intervals.h"
39 #include "puresize.h"
40 #include "character.h"
41 #include "buffer.h"
42 #include "window.h"
43 #include "keyboard.h"
44 #include "frame.h"
45 #include "blockinput.h"
46 #include "termhooks.h" /* For struct terminal. */
48 #include <verify.h>
50 /* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects.
51 Doable only if GC_MARK_STACK. */
52 #if ! GC_MARK_STACK
53 # undef GC_CHECK_MARKED_OBJECTS
54 #endif
56 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
57 memory. Can do this only if using gmalloc.c and if not checking
58 marked objects. */
60 #if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
61 || defined GC_CHECK_MARKED_OBJECTS)
62 #undef GC_MALLOC_CHECK
63 #endif
65 #include <unistd.h>
66 #ifndef HAVE_UNISTD_H
67 extern void *sbrk ();
68 #endif
70 #include <fcntl.h>
72 #ifdef USE_GTK
73 # include "gtkutil.h"
74 #endif
75 #ifdef WINDOWSNT
76 #include "w32.h"
77 #endif
79 #ifdef DOUG_LEA_MALLOC
81 #include <malloc.h>
83 /* Specify maximum number of areas to mmap. It would be nice to use a
84 value that explicitly means "no limit". */
86 #define MMAP_MAX_AREAS 100000000
88 #endif /* not DOUG_LEA_MALLOC */
90 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
91 to a struct Lisp_String. */
93 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
94 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
95 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
97 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
98 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
99 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
101 /* Default value of gc_cons_threshold (see below). */
103 #define GC_DEFAULT_THRESHOLD (100000 * word_size)
105 /* Global variables. */
106 struct emacs_globals globals;
108 /* Number of bytes of consing done since the last gc. */
110 EMACS_INT consing_since_gc;
112 /* Similar minimum, computed from Vgc_cons_percentage. */
114 EMACS_INT gc_relative_threshold;
116 /* Minimum number of bytes of consing since GC before next GC,
117 when memory is full. */
119 EMACS_INT memory_full_cons_threshold;
121 /* True during GC. */
123 bool gc_in_progress;
125 /* True means abort if try to GC.
126 This is for code which is written on the assumption that
127 no GC will happen, so as to verify that assumption. */
129 bool abort_on_gc;
131 /* Number of live and free conses etc. */
133 static EMACS_INT total_conses, total_markers, total_symbols, total_buffers;
134 static EMACS_INT total_free_conses, total_free_markers, total_free_symbols;
135 static EMACS_INT total_free_floats, total_floats;
137 /* Points to memory space allocated as "spare", to be freed if we run
138 out of memory. We keep one large block, four cons-blocks, and
139 two string blocks. */
141 static char *spare_memory[7];
143 /* Amount of spare memory to keep in large reserve block, or to see
144 whether this much is available when malloc fails on a larger request. */
146 #define SPARE_MEMORY (1 << 14)
148 /* Initialize it to a nonzero value to force it into data space
149 (rather than bss space). That way unexec will remap it into text
150 space (pure), on some systems. We have not implemented the
151 remapping on more recent systems because this is less important
152 nowadays than in the days of small memories and timesharing. */
154 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
155 #define PUREBEG (char *) pure
157 /* Pointer to the pure area, and its size. */
159 static char *purebeg;
160 static ptrdiff_t pure_size;
162 /* Number of bytes of pure storage used before pure storage overflowed.
163 If this is non-zero, this implies that an overflow occurred. */
165 static ptrdiff_t pure_bytes_used_before_overflow;
167 /* True if P points into pure space. */
169 #define PURE_POINTER_P(P) \
170 ((uintptr_t) (P) - (uintptr_t) purebeg <= pure_size)
172 /* Index in pure at which next pure Lisp object will be allocated.. */
174 static ptrdiff_t pure_bytes_used_lisp;
176 /* Number of bytes allocated for non-Lisp objects in pure storage. */
178 static ptrdiff_t pure_bytes_used_non_lisp;
180 /* If nonzero, this is a warning delivered by malloc and not yet
181 displayed. */
183 const char *pending_malloc_warning;
185 /* Maximum amount of C stack to save when a GC happens. */
187 #ifndef MAX_SAVE_STACK
188 #define MAX_SAVE_STACK 16000
189 #endif
191 /* Buffer in which we save a copy of the C stack at each GC. */
193 #if MAX_SAVE_STACK > 0
194 static char *stack_copy;
195 static ptrdiff_t stack_copy_size;
196 #endif
198 static Lisp_Object Qconses;
199 static Lisp_Object Qsymbols;
200 static Lisp_Object Qmiscs;
201 static Lisp_Object Qstrings;
202 static Lisp_Object Qvectors;
203 static Lisp_Object Qfloats;
204 static Lisp_Object Qintervals;
205 static Lisp_Object Qbuffers;
206 static Lisp_Object Qstring_bytes, Qvector_slots, Qheap;
207 static Lisp_Object Qgc_cons_threshold;
208 Lisp_Object Qchar_table_extra_slots;
210 /* Hook run after GC has finished. */
212 static Lisp_Object Qpost_gc_hook;
214 static void mark_terminals (void);
215 static void gc_sweep (void);
216 static Lisp_Object make_pure_vector (ptrdiff_t);
217 static void mark_glyph_matrix (struct glyph_matrix *);
218 static void mark_face_cache (struct face_cache *);
219 static void mark_buffer (struct buffer *);
221 #if !defined REL_ALLOC || defined SYSTEM_MALLOC
222 static void refill_memory_reserve (void);
223 #endif
224 static struct Lisp_String *allocate_string (void);
225 static void compact_small_strings (void);
226 static void free_large_strings (void);
227 static void sweep_strings (void);
228 static void free_misc (Lisp_Object);
229 extern Lisp_Object which_symbols (Lisp_Object, EMACS_INT) EXTERNALLY_VISIBLE;
231 /* When scanning the C stack for live Lisp objects, Emacs keeps track
232 of what memory allocated via lisp_malloc is intended for what
233 purpose. This enumeration specifies the type of memory. */
235 enum mem_type
237 MEM_TYPE_NON_LISP,
238 MEM_TYPE_BUFFER,
239 MEM_TYPE_CONS,
240 MEM_TYPE_STRING,
241 MEM_TYPE_MISC,
242 MEM_TYPE_SYMBOL,
243 MEM_TYPE_FLOAT,
244 /* We used to keep separate mem_types for subtypes of vectors such as
245 process, hash_table, frame, terminal, and window, but we never made
246 use of the distinction, so it only caused source-code complexity
247 and runtime slowdown. Minor but pointless. */
248 MEM_TYPE_VECTORLIKE,
249 /* Special type to denote vector blocks. */
250 MEM_TYPE_VECTOR_BLOCK,
251 /* Special type to denote reserved memory. */
252 MEM_TYPE_SPARE
255 static void *lisp_malloc (size_t, enum mem_type);
258 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
260 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
261 #include <stdio.h> /* For fprintf. */
262 #endif
264 /* A unique object in pure space used to make some Lisp objects
265 on free lists recognizable in O(1). */
267 static Lisp_Object Vdead;
268 #define DEADP(x) EQ (x, Vdead)
270 #ifdef GC_MALLOC_CHECK
272 enum mem_type allocated_mem_type;
274 #endif /* GC_MALLOC_CHECK */
276 /* A node in the red-black tree describing allocated memory containing
277 Lisp data. Each such block is recorded with its start and end
278 address when it is allocated, and removed from the tree when it
279 is freed.
281 A red-black tree is a balanced binary tree with the following
282 properties:
284 1. Every node is either red or black.
285 2. Every leaf is black.
286 3. If a node is red, then both of its children are black.
287 4. Every simple path from a node to a descendant leaf contains
288 the same number of black nodes.
289 5. The root is always black.
291 When nodes are inserted into the tree, or deleted from the tree,
292 the tree is "fixed" so that these properties are always true.
294 A red-black tree with N internal nodes has height at most 2
295 log(N+1). Searches, insertions and deletions are done in O(log N).
296 Please see a text book about data structures for a detailed
297 description of red-black trees. Any book worth its salt should
298 describe them. */
300 struct mem_node
302 /* Children of this node. These pointers are never NULL. When there
303 is no child, the value is MEM_NIL, which points to a dummy node. */
304 struct mem_node *left, *right;
306 /* The parent of this node. In the root node, this is NULL. */
307 struct mem_node *parent;
309 /* Start and end of allocated region. */
310 void *start, *end;
312 /* Node color. */
313 enum {MEM_BLACK, MEM_RED} color;
315 /* Memory type. */
316 enum mem_type type;
319 /* Base address of stack. Set in main. */
321 Lisp_Object *stack_base;
323 /* Root of the tree describing allocated Lisp memory. */
325 static struct mem_node *mem_root;
327 /* Lowest and highest known address in the heap. */
329 static void *min_heap_address, *max_heap_address;
331 /* Sentinel node of the tree. */
333 static struct mem_node mem_z;
334 #define MEM_NIL &mem_z
336 static struct Lisp_Vector *allocate_vectorlike (ptrdiff_t);
337 static void lisp_free (void *);
338 static void mark_stack (void);
339 static bool live_vector_p (struct mem_node *, void *);
340 static bool live_buffer_p (struct mem_node *, void *);
341 static bool live_string_p (struct mem_node *, void *);
342 static bool live_cons_p (struct mem_node *, void *);
343 static bool live_symbol_p (struct mem_node *, void *);
344 static bool live_float_p (struct mem_node *, void *);
345 static bool live_misc_p (struct mem_node *, void *);
346 static void mark_maybe_object (Lisp_Object);
347 static void mark_memory (void *, void *);
348 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
349 static void mem_init (void);
350 static struct mem_node *mem_insert (void *, void *, enum mem_type);
351 static void mem_insert_fixup (struct mem_node *);
352 static void mem_rotate_left (struct mem_node *);
353 static void mem_rotate_right (struct mem_node *);
354 static void mem_delete (struct mem_node *);
355 static void mem_delete_fixup (struct mem_node *);
356 static inline struct mem_node *mem_find (void *);
357 #endif
360 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
361 static void check_gcpros (void);
362 #endif
364 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
366 #ifndef DEADP
367 # define DEADP(x) 0
368 #endif
370 /* Recording what needs to be marked for gc. */
372 struct gcpro *gcprolist;
374 /* Addresses of staticpro'd variables. Initialize it to a nonzero
375 value; otherwise some compilers put it into BSS. */
377 #define NSTATICS 0x650
378 static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
380 /* Index of next unused slot in staticvec. */
382 static int staticidx;
384 static void *pure_alloc (size_t, int);
387 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
388 ALIGNMENT must be a power of 2. */
390 #define ALIGN(ptr, ALIGNMENT) \
391 ((void *) (((uintptr_t) (ptr) + (ALIGNMENT) - 1) \
392 & ~ ((ALIGNMENT) - 1)))
396 /************************************************************************
397 Malloc
398 ************************************************************************/
400 /* Function malloc calls this if it finds we are near exhausting storage. */
402 void
403 malloc_warning (const char *str)
405 pending_malloc_warning = str;
409 /* Display an already-pending malloc warning. */
411 void
412 display_malloc_warning (void)
414 call3 (intern ("display-warning"),
415 intern ("alloc"),
416 build_string (pending_malloc_warning),
417 intern ("emergency"));
418 pending_malloc_warning = 0;
421 /* Called if we can't allocate relocatable space for a buffer. */
423 void
424 buffer_memory_full (ptrdiff_t nbytes)
426 /* If buffers use the relocating allocator, no need to free
427 spare_memory, because we may have plenty of malloc space left
428 that we could get, and if we don't, the malloc that fails will
429 itself cause spare_memory to be freed. If buffers don't use the
430 relocating allocator, treat this like any other failing
431 malloc. */
433 #ifndef REL_ALLOC
434 memory_full (nbytes);
435 #endif
437 /* This used to call error, but if we've run out of memory, we could
438 get infinite recursion trying to build the string. */
439 xsignal (Qnil, Vmemory_signal_data);
442 /* A common multiple of the positive integers A and B. Ideally this
443 would be the least common multiple, but there's no way to do that
444 as a constant expression in C, so do the best that we can easily do. */
445 #define COMMON_MULTIPLE(a, b) \
446 ((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
448 #ifndef XMALLOC_OVERRUN_CHECK
449 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
450 #else
452 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
453 around each block.
455 The header consists of XMALLOC_OVERRUN_CHECK_SIZE fixed bytes
456 followed by XMALLOC_OVERRUN_SIZE_SIZE bytes containing the original
457 block size in little-endian order. The trailer consists of
458 XMALLOC_OVERRUN_CHECK_SIZE fixed bytes.
460 The header is used to detect whether this block has been allocated
461 through these functions, as some low-level libc functions may
462 bypass the malloc hooks. */
464 #define XMALLOC_OVERRUN_CHECK_SIZE 16
465 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
466 (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)
468 /* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
469 hold a size_t value and (2) the header size is a multiple of the
470 alignment that Emacs needs for C types and for USE_LSB_TAG. */
471 #define XMALLOC_BASE_ALIGNMENT \
472 alignof (union { long double d; intmax_t i; void *p; })
474 #if USE_LSB_TAG
475 # define XMALLOC_HEADER_ALIGNMENT \
476 COMMON_MULTIPLE (GCALIGNMENT, XMALLOC_BASE_ALIGNMENT)
477 #else
478 # define XMALLOC_HEADER_ALIGNMENT XMALLOC_BASE_ALIGNMENT
479 #endif
480 #define XMALLOC_OVERRUN_SIZE_SIZE \
481 (((XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t) \
482 + XMALLOC_HEADER_ALIGNMENT - 1) \
483 / XMALLOC_HEADER_ALIGNMENT * XMALLOC_HEADER_ALIGNMENT) \
484 - XMALLOC_OVERRUN_CHECK_SIZE)
486 static char const xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE] =
487 { '\x9a', '\x9b', '\xae', '\xaf',
488 '\xbf', '\xbe', '\xce', '\xcf',
489 '\xea', '\xeb', '\xec', '\xed',
490 '\xdf', '\xde', '\x9c', '\x9d' };
492 static char const xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
493 { '\xaa', '\xab', '\xac', '\xad',
494 '\xba', '\xbb', '\xbc', '\xbd',
495 '\xca', '\xcb', '\xcc', '\xcd',
496 '\xda', '\xdb', '\xdc', '\xdd' };
498 /* Insert and extract the block size in the header. */
500 static void
501 xmalloc_put_size (unsigned char *ptr, size_t size)
503 int i;
504 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
506 *--ptr = size & ((1 << CHAR_BIT) - 1);
507 size >>= CHAR_BIT;
511 static size_t
512 xmalloc_get_size (unsigned char *ptr)
514 size_t size = 0;
515 int i;
516 ptr -= XMALLOC_OVERRUN_SIZE_SIZE;
517 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
519 size <<= CHAR_BIT;
520 size += *ptr++;
522 return size;
526 /* Like malloc, but wraps allocated block with header and trailer. */
528 static void *
529 overrun_check_malloc (size_t size)
531 register unsigned char *val;
532 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
533 emacs_abort ();
535 val = malloc (size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
536 if (val)
538 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
539 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
540 xmalloc_put_size (val, size);
541 memcpy (val + size, xmalloc_overrun_check_trailer,
542 XMALLOC_OVERRUN_CHECK_SIZE);
544 return val;
548 /* Like realloc, but checks old block for overrun, and wraps new block
549 with header and trailer. */
551 static void *
552 overrun_check_realloc (void *block, size_t size)
554 register unsigned char *val = (unsigned char *) block;
555 if (SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD < size)
556 emacs_abort ();
558 if (val
559 && memcmp (xmalloc_overrun_check_header,
560 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
561 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
563 size_t osize = xmalloc_get_size (val);
564 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
565 XMALLOC_OVERRUN_CHECK_SIZE))
566 emacs_abort ();
567 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
568 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
569 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
572 val = realloc (val, size + XMALLOC_OVERRUN_CHECK_OVERHEAD);
574 if (val)
576 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
577 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
578 xmalloc_put_size (val, size);
579 memcpy (val + size, xmalloc_overrun_check_trailer,
580 XMALLOC_OVERRUN_CHECK_SIZE);
582 return val;
585 /* Like free, but checks block for overrun. */
587 static void
588 overrun_check_free (void *block)
590 unsigned char *val = (unsigned char *) block;
592 if (val
593 && memcmp (xmalloc_overrun_check_header,
594 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
595 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
597 size_t osize = xmalloc_get_size (val);
598 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
599 XMALLOC_OVERRUN_CHECK_SIZE))
600 emacs_abort ();
601 #ifdef XMALLOC_CLEAR_FREE_MEMORY
602 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
603 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_OVERHEAD);
604 #else
605 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
606 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
607 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
608 #endif
611 free (val);
614 #undef malloc
615 #undef realloc
616 #undef free
617 #define malloc overrun_check_malloc
618 #define realloc overrun_check_realloc
619 #define free overrun_check_free
620 #endif
622 /* If compiled with XMALLOC_BLOCK_INPUT_CHECK, define a symbol
623 BLOCK_INPUT_IN_MEMORY_ALLOCATORS that is visible to the debugger.
624 If that variable is set, block input while in one of Emacs's memory
625 allocation functions. There should be no need for this debugging
626 option, since signal handlers do not allocate memory, but Emacs
627 formerly allocated memory in signal handlers and this compile-time
628 option remains as a way to help debug the issue should it rear its
629 ugly head again. */
630 #ifdef XMALLOC_BLOCK_INPUT_CHECK
631 bool block_input_in_memory_allocators EXTERNALLY_VISIBLE;
632 static void
633 malloc_block_input (void)
635 if (block_input_in_memory_allocators)
636 BLOCK_INPUT;
638 static void
639 malloc_unblock_input (void)
641 if (block_input_in_memory_allocators)
642 UNBLOCK_INPUT;
644 # define MALLOC_BLOCK_INPUT malloc_block_input ()
645 # define MALLOC_UNBLOCK_INPUT malloc_unblock_input ()
646 #else
647 # define MALLOC_BLOCK_INPUT ((void) 0)
648 # define MALLOC_UNBLOCK_INPUT ((void) 0)
649 #endif
651 /* Like malloc but check for no memory and block interrupt input.. */
653 void *
654 xmalloc (size_t size)
656 void *val;
658 MALLOC_BLOCK_INPUT;
659 val = malloc (size);
660 MALLOC_UNBLOCK_INPUT;
662 if (!val && size)
663 memory_full (size);
664 return val;
667 /* Like the above, but zeroes out the memory just allocated. */
669 void *
670 xzalloc (size_t size)
672 void *val;
674 MALLOC_BLOCK_INPUT;
675 val = malloc (size);
676 MALLOC_UNBLOCK_INPUT;
678 if (!val && size)
679 memory_full (size);
680 memset (val, 0, size);
681 return val;
684 /* Like realloc but check for no memory and block interrupt input.. */
686 void *
687 xrealloc (void *block, size_t size)
689 void *val;
691 MALLOC_BLOCK_INPUT;
692 /* We must call malloc explicitly when BLOCK is 0, since some
693 reallocs don't do this. */
694 if (! block)
695 val = malloc (size);
696 else
697 val = realloc (block, size);
698 MALLOC_UNBLOCK_INPUT;
700 if (!val && size)
701 memory_full (size);
702 return val;
706 /* Like free but block interrupt input. */
708 void
709 xfree (void *block)
711 if (!block)
712 return;
713 MALLOC_BLOCK_INPUT;
714 free (block);
715 MALLOC_UNBLOCK_INPUT;
716 /* We don't call refill_memory_reserve here
717 because in practice the call in r_alloc_free seems to suffice. */
721 /* Other parts of Emacs pass large int values to allocator functions
722 expecting ptrdiff_t. This is portable in practice, but check it to
723 be safe. */
724 verify (INT_MAX <= PTRDIFF_MAX);
727 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
728 Signal an error on memory exhaustion, and block interrupt input. */
730 void *
731 xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
733 eassert (0 <= nitems && 0 < item_size);
734 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
735 memory_full (SIZE_MAX);
736 return xmalloc (nitems * item_size);
740 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
741 Signal an error on memory exhaustion, and block interrupt input. */
743 void *
744 xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
746 eassert (0 <= nitems && 0 < item_size);
747 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
748 memory_full (SIZE_MAX);
749 return xrealloc (pa, nitems * item_size);
753 /* Grow PA, which points to an array of *NITEMS items, and return the
754 location of the reallocated array, updating *NITEMS to reflect its
755 new size. The new array will contain at least NITEMS_INCR_MIN more
756 items, but will not contain more than NITEMS_MAX items total.
757 ITEM_SIZE is the size of each item, in bytes.
759 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
760 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
761 infinity.
763 If PA is null, then allocate a new array instead of reallocating
764 the old one. Thus, to grow an array A without saving its old
765 contents, invoke xfree (A) immediately followed by xgrowalloc (0,
766 &NITEMS, ...).
768 Block interrupt input as needed. If memory exhaustion occurs, set
769 *NITEMS to zero if PA is null, and signal an error (i.e., do not
770 return). */
772 void *
773 xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
774 ptrdiff_t nitems_max, ptrdiff_t item_size)
776 /* The approximate size to use for initial small allocation
777 requests. This is the largest "small" request for the GNU C
778 library malloc. */
779 enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
781 /* If the array is tiny, grow it to about (but no greater than)
782 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%. */
783 ptrdiff_t n = *nitems;
784 ptrdiff_t tiny_max = DEFAULT_MXFAST / item_size - n;
785 ptrdiff_t half_again = n >> 1;
786 ptrdiff_t incr_estimate = max (tiny_max, half_again);
788 /* Adjust the increment according to three constraints: NITEMS_INCR_MIN,
789 NITEMS_MAX, and what the C language can represent safely. */
790 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / item_size;
791 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
792 ? nitems_max : C_language_max);
793 ptrdiff_t nitems_incr_max = n_max - n;
794 ptrdiff_t incr = max (nitems_incr_min, min (incr_estimate, nitems_incr_max));
796 eassert (0 < item_size && 0 < nitems_incr_min && 0 <= n && -1 <= nitems_max);
797 if (! pa)
798 *nitems = 0;
799 if (nitems_incr_max < incr)
800 memory_full (SIZE_MAX);
801 n += incr;
802 pa = xrealloc (pa, n * item_size);
803 *nitems = n;
804 return pa;
808 /* Like strdup, but uses xmalloc. */
810 char *
811 xstrdup (const char *s)
813 size_t len = strlen (s) + 1;
814 char *p = xmalloc (len);
815 memcpy (p, s, len);
816 return p;
820 /* Unwind for SAFE_ALLOCA */
822 Lisp_Object
823 safe_alloca_unwind (Lisp_Object arg)
825 register struct Lisp_Save_Value *p = XSAVE_VALUE (arg);
827 p->dogc = 0;
828 xfree (p->pointer);
829 p->pointer = 0;
830 free_misc (arg);
831 return Qnil;
834 /* Return a newly allocated memory block of SIZE bytes, remembering
835 to free it when unwinding. */
836 void *
837 record_xmalloc (size_t size)
839 void *p = xmalloc (size);
840 record_unwind_protect (safe_alloca_unwind, make_save_value (p, 0));
841 return p;
845 /* Like malloc but used for allocating Lisp data. NBYTES is the
846 number of bytes to allocate, TYPE describes the intended use of the
847 allocated memory block (for strings, for conses, ...). */
849 #if ! USE_LSB_TAG
850 void *lisp_malloc_loser EXTERNALLY_VISIBLE;
851 #endif
853 static void *
854 lisp_malloc (size_t nbytes, enum mem_type type)
856 register void *val;
858 MALLOC_BLOCK_INPUT;
860 #ifdef GC_MALLOC_CHECK
861 allocated_mem_type = type;
862 #endif
864 val = malloc (nbytes);
866 #if ! USE_LSB_TAG
867 /* If the memory just allocated cannot be addressed thru a Lisp
868 object's pointer, and it needs to be,
869 that's equivalent to running out of memory. */
870 if (val && type != MEM_TYPE_NON_LISP)
872 Lisp_Object tem;
873 XSETCONS (tem, (char *) val + nbytes - 1);
874 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
876 lisp_malloc_loser = val;
877 free (val);
878 val = 0;
881 #endif
883 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
884 if (val && type != MEM_TYPE_NON_LISP)
885 mem_insert (val, (char *) val + nbytes, type);
886 #endif
888 MALLOC_UNBLOCK_INPUT;
889 if (!val && nbytes)
890 memory_full (nbytes);
891 return val;
894 /* Free BLOCK. This must be called to free memory allocated with a
895 call to lisp_malloc. */
897 static void
898 lisp_free (void *block)
900 MALLOC_BLOCK_INPUT;
901 free (block);
902 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
903 mem_delete (mem_find (block));
904 #endif
905 MALLOC_UNBLOCK_INPUT;
908 /***** Allocation of aligned blocks of memory to store Lisp data. *****/
910 /* The entry point is lisp_align_malloc which returns blocks of at most
911 BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
913 #if defined (HAVE_POSIX_MEMALIGN) && defined (SYSTEM_MALLOC)
914 #define USE_POSIX_MEMALIGN 1
915 #endif
917 /* BLOCK_ALIGN has to be a power of 2. */
918 #define BLOCK_ALIGN (1 << 10)
920 /* Padding to leave at the end of a malloc'd block. This is to give
921 malloc a chance to minimize the amount of memory wasted to alignment.
922 It should be tuned to the particular malloc library used.
923 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
924 posix_memalign on the other hand would ideally prefer a value of 4
925 because otherwise, there's 1020 bytes wasted between each ablocks.
926 In Emacs, testing shows that those 1020 can most of the time be
927 efficiently used by malloc to place other objects, so a value of 0 can
928 still preferable unless you have a lot of aligned blocks and virtually
929 nothing else. */
930 #define BLOCK_PADDING 0
931 #define BLOCK_BYTES \
932 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
934 /* Internal data structures and constants. */
936 #define ABLOCKS_SIZE 16
938 /* An aligned block of memory. */
939 struct ablock
941 union
943 char payload[BLOCK_BYTES];
944 struct ablock *next_free;
945 } x;
946 /* `abase' is the aligned base of the ablocks. */
947 /* It is overloaded to hold the virtual `busy' field that counts
948 the number of used ablock in the parent ablocks.
949 The first ablock has the `busy' field, the others have the `abase'
950 field. To tell the difference, we assume that pointers will have
951 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
952 is used to tell whether the real base of the parent ablocks is `abase'
953 (if not, the word before the first ablock holds a pointer to the
954 real base). */
955 struct ablocks *abase;
956 /* The padding of all but the last ablock is unused. The padding of
957 the last ablock in an ablocks is not allocated. */
958 #if BLOCK_PADDING
959 char padding[BLOCK_PADDING];
960 #endif
963 /* A bunch of consecutive aligned blocks. */
964 struct ablocks
966 struct ablock blocks[ABLOCKS_SIZE];
969 /* Size of the block requested from malloc or posix_memalign. */
970 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
972 #define ABLOCK_ABASE(block) \
973 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
974 ? (struct ablocks *)(block) \
975 : (block)->abase)
977 /* Virtual `busy' field. */
978 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
980 /* Pointer to the (not necessarily aligned) malloc block. */
981 #ifdef USE_POSIX_MEMALIGN
982 #define ABLOCKS_BASE(abase) (abase)
983 #else
984 #define ABLOCKS_BASE(abase) \
985 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void**)abase)[-1])
986 #endif
988 /* The list of free ablock. */
989 static struct ablock *free_ablock;
991 /* Allocate an aligned block of nbytes.
992 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
993 smaller or equal to BLOCK_BYTES. */
994 static void *
995 lisp_align_malloc (size_t nbytes, enum mem_type type)
997 void *base, *val;
998 struct ablocks *abase;
1000 eassert (nbytes <= BLOCK_BYTES);
1002 MALLOC_BLOCK_INPUT;
1004 #ifdef GC_MALLOC_CHECK
1005 allocated_mem_type = type;
1006 #endif
1008 if (!free_ablock)
1010 int i;
1011 intptr_t aligned; /* int gets warning casting to 64-bit pointer. */
1013 #ifdef DOUG_LEA_MALLOC
1014 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1015 because mapped region contents are not preserved in
1016 a dumped Emacs. */
1017 mallopt (M_MMAP_MAX, 0);
1018 #endif
1020 #ifdef USE_POSIX_MEMALIGN
1022 int err = posix_memalign (&base, BLOCK_ALIGN, ABLOCKS_BYTES);
1023 if (err)
1024 base = NULL;
1025 abase = base;
1027 #else
1028 base = malloc (ABLOCKS_BYTES);
1029 abase = ALIGN (base, BLOCK_ALIGN);
1030 #endif
1032 if (base == 0)
1034 MALLOC_UNBLOCK_INPUT;
1035 memory_full (ABLOCKS_BYTES);
1038 aligned = (base == abase);
1039 if (!aligned)
1040 ((void**)abase)[-1] = base;
1042 #ifdef DOUG_LEA_MALLOC
1043 /* Back to a reasonable maximum of mmap'ed areas. */
1044 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1045 #endif
1047 #if ! USE_LSB_TAG
1048 /* If the memory just allocated cannot be addressed thru a Lisp
1049 object's pointer, and it needs to be, that's equivalent to
1050 running out of memory. */
1051 if (type != MEM_TYPE_NON_LISP)
1053 Lisp_Object tem;
1054 char *end = (char *) base + ABLOCKS_BYTES - 1;
1055 XSETCONS (tem, end);
1056 if ((char *) XCONS (tem) != end)
1058 lisp_malloc_loser = base;
1059 free (base);
1060 MALLOC_UNBLOCK_INPUT;
1061 memory_full (SIZE_MAX);
1064 #endif
1066 /* Initialize the blocks and put them on the free list.
1067 If `base' was not properly aligned, we can't use the last block. */
1068 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1070 abase->blocks[i].abase = abase;
1071 abase->blocks[i].x.next_free = free_ablock;
1072 free_ablock = &abase->blocks[i];
1074 ABLOCKS_BUSY (abase) = (struct ablocks *) aligned;
1076 eassert (0 == ((uintptr_t) abase) % BLOCK_ALIGN);
1077 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1078 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1079 eassert (ABLOCKS_BASE (abase) == base);
1080 eassert (aligned == (intptr_t) ABLOCKS_BUSY (abase));
1083 abase = ABLOCK_ABASE (free_ablock);
1084 ABLOCKS_BUSY (abase) =
1085 (struct ablocks *) (2 + (intptr_t) ABLOCKS_BUSY (abase));
1086 val = free_ablock;
1087 free_ablock = free_ablock->x.next_free;
1089 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1090 if (type != MEM_TYPE_NON_LISP)
1091 mem_insert (val, (char *) val + nbytes, type);
1092 #endif
1094 MALLOC_UNBLOCK_INPUT;
1096 eassert (0 == ((uintptr_t) val) % BLOCK_ALIGN);
1097 return val;
1100 static void
1101 lisp_align_free (void *block)
1103 struct ablock *ablock = block;
1104 struct ablocks *abase = ABLOCK_ABASE (ablock);
1106 MALLOC_BLOCK_INPUT;
1107 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1108 mem_delete (mem_find (block));
1109 #endif
1110 /* Put on free list. */
1111 ablock->x.next_free = free_ablock;
1112 free_ablock = ablock;
1113 /* Update busy count. */
1114 ABLOCKS_BUSY (abase)
1115 = (struct ablocks *) (-2 + (intptr_t) ABLOCKS_BUSY (abase));
1117 if (2 > (intptr_t) ABLOCKS_BUSY (abase))
1118 { /* All the blocks are free. */
1119 int i = 0, aligned = (intptr_t) ABLOCKS_BUSY (abase);
1120 struct ablock **tem = &free_ablock;
1121 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1123 while (*tem)
1125 if (*tem >= (struct ablock *) abase && *tem < atop)
1127 i++;
1128 *tem = (*tem)->x.next_free;
1130 else
1131 tem = &(*tem)->x.next_free;
1133 eassert ((aligned & 1) == aligned);
1134 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1135 #ifdef USE_POSIX_MEMALIGN
1136 eassert ((uintptr_t) ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1137 #endif
1138 free (ABLOCKS_BASE (abase));
1140 MALLOC_UNBLOCK_INPUT;
1144 /***********************************************************************
1145 Interval Allocation
1146 ***********************************************************************/
1148 /* Number of intervals allocated in an interval_block structure.
1149 The 1020 is 1024 minus malloc overhead. */
1151 #define INTERVAL_BLOCK_SIZE \
1152 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1154 /* Intervals are allocated in chunks in form of an interval_block
1155 structure. */
1157 struct interval_block
1159 /* Place `intervals' first, to preserve alignment. */
1160 struct interval intervals[INTERVAL_BLOCK_SIZE];
1161 struct interval_block *next;
1164 /* Current interval block. Its `next' pointer points to older
1165 blocks. */
1167 static struct interval_block *interval_block;
1169 /* Index in interval_block above of the next unused interval
1170 structure. */
1172 static int interval_block_index = INTERVAL_BLOCK_SIZE;
1174 /* Number of free and live intervals. */
1176 static EMACS_INT total_free_intervals, total_intervals;
1178 /* List of free intervals. */
1180 static INTERVAL interval_free_list;
1182 /* Return a new interval. */
1184 INTERVAL
1185 make_interval (void)
1187 INTERVAL val;
1189 MALLOC_BLOCK_INPUT;
1191 if (interval_free_list)
1193 val = interval_free_list;
1194 interval_free_list = INTERVAL_PARENT (interval_free_list);
1196 else
1198 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1200 struct interval_block *newi
1201 = lisp_malloc (sizeof *newi, MEM_TYPE_NON_LISP);
1203 newi->next = interval_block;
1204 interval_block = newi;
1205 interval_block_index = 0;
1206 total_free_intervals += INTERVAL_BLOCK_SIZE;
1208 val = &interval_block->intervals[interval_block_index++];
1211 MALLOC_UNBLOCK_INPUT;
1213 consing_since_gc += sizeof (struct interval);
1214 intervals_consed++;
1215 total_free_intervals--;
1216 RESET_INTERVAL (val);
1217 val->gcmarkbit = 0;
1218 return val;
1222 /* Mark Lisp objects in interval I. */
1224 static void
1225 mark_interval (register INTERVAL i, Lisp_Object dummy)
1227 /* Intervals should never be shared. So, if extra internal checking is
1228 enabled, GC aborts if it seems to have visited an interval twice. */
1229 eassert (!i->gcmarkbit);
1230 i->gcmarkbit = 1;
1231 mark_object (i->plist);
1234 /* Mark the interval tree rooted in I. */
1236 #define MARK_INTERVAL_TREE(i) \
1237 do { \
1238 if (i && !i->gcmarkbit) \
1239 traverse_intervals_noorder (i, mark_interval, Qnil); \
1240 } while (0)
1242 /***********************************************************************
1243 String Allocation
1244 ***********************************************************************/
1246 /* Lisp_Strings are allocated in string_block structures. When a new
1247 string_block is allocated, all the Lisp_Strings it contains are
1248 added to a free-list string_free_list. When a new Lisp_String is
1249 needed, it is taken from that list. During the sweep phase of GC,
1250 string_blocks that are entirely free are freed, except two which
1251 we keep.
1253 String data is allocated from sblock structures. Strings larger
1254 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1255 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1257 Sblocks consist internally of sdata structures, one for each
1258 Lisp_String. The sdata structure points to the Lisp_String it
1259 belongs to. The Lisp_String points back to the `u.data' member of
1260 its sdata structure.
1262 When a Lisp_String is freed during GC, it is put back on
1263 string_free_list, and its `data' member and its sdata's `string'
1264 pointer is set to null. The size of the string is recorded in the
1265 `u.nbytes' member of the sdata. So, sdata structures that are no
1266 longer used, can be easily recognized, and it's easy to compact the
1267 sblocks of small strings which we do in compact_small_strings. */
1269 /* Size in bytes of an sblock structure used for small strings. This
1270 is 8192 minus malloc overhead. */
1272 #define SBLOCK_SIZE 8188
1274 /* Strings larger than this are considered large strings. String data
1275 for large strings is allocated from individual sblocks. */
1277 #define LARGE_STRING_BYTES 1024
1279 /* Structure describing string memory sub-allocated from an sblock.
1280 This is where the contents of Lisp strings are stored. */
1282 struct sdata
1284 /* Back-pointer to the string this sdata belongs to. If null, this
1285 structure is free, and the NBYTES member of the union below
1286 contains the string's byte size (the same value that STRING_BYTES
1287 would return if STRING were non-null). If non-null, STRING_BYTES
1288 (STRING) is the size of the data, and DATA contains the string's
1289 contents. */
1290 struct Lisp_String *string;
1292 #ifdef GC_CHECK_STRING_BYTES
1294 ptrdiff_t nbytes;
1295 unsigned char data[1];
1297 #define SDATA_NBYTES(S) (S)->nbytes
1298 #define SDATA_DATA(S) (S)->data
1299 #define SDATA_SELECTOR(member) member
1301 #else /* not GC_CHECK_STRING_BYTES */
1303 union
1305 /* When STRING is non-null. */
1306 unsigned char data[1];
1308 /* When STRING is null. */
1309 ptrdiff_t nbytes;
1310 } u;
1312 #define SDATA_NBYTES(S) (S)->u.nbytes
1313 #define SDATA_DATA(S) (S)->u.data
1314 #define SDATA_SELECTOR(member) u.member
1316 #endif /* not GC_CHECK_STRING_BYTES */
1318 #define SDATA_DATA_OFFSET offsetof (struct sdata, SDATA_SELECTOR (data))
1322 /* Structure describing a block of memory which is sub-allocated to
1323 obtain string data memory for strings. Blocks for small strings
1324 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1325 as large as needed. */
1327 struct sblock
1329 /* Next in list. */
1330 struct sblock *next;
1332 /* Pointer to the next free sdata block. This points past the end
1333 of the sblock if there isn't any space left in this block. */
1334 struct sdata *next_free;
1336 /* Start of data. */
1337 struct sdata first_data;
1340 /* Number of Lisp strings in a string_block structure. The 1020 is
1341 1024 minus malloc overhead. */
1343 #define STRING_BLOCK_SIZE \
1344 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1346 /* Structure describing a block from which Lisp_String structures
1347 are allocated. */
1349 struct string_block
1351 /* Place `strings' first, to preserve alignment. */
1352 struct Lisp_String strings[STRING_BLOCK_SIZE];
1353 struct string_block *next;
1356 /* Head and tail of the list of sblock structures holding Lisp string
1357 data. We always allocate from current_sblock. The NEXT pointers
1358 in the sblock structures go from oldest_sblock to current_sblock. */
1360 static struct sblock *oldest_sblock, *current_sblock;
1362 /* List of sblocks for large strings. */
1364 static struct sblock *large_sblocks;
1366 /* List of string_block structures. */
1368 static struct string_block *string_blocks;
1370 /* Free-list of Lisp_Strings. */
1372 static struct Lisp_String *string_free_list;
1374 /* Number of live and free Lisp_Strings. */
1376 static EMACS_INT total_strings, total_free_strings;
1378 /* Number of bytes used by live strings. */
1380 static EMACS_INT total_string_bytes;
1382 /* Given a pointer to a Lisp_String S which is on the free-list
1383 string_free_list, return a pointer to its successor in the
1384 free-list. */
1386 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1388 /* Return a pointer to the sdata structure belonging to Lisp string S.
1389 S must be live, i.e. S->data must not be null. S->data is actually
1390 a pointer to the `u.data' member of its sdata structure; the
1391 structure starts at a constant offset in front of that. */
1393 #define SDATA_OF_STRING(S) ((struct sdata *) ((S)->data - SDATA_DATA_OFFSET))
1396 #ifdef GC_CHECK_STRING_OVERRUN
1398 /* We check for overrun in string data blocks by appending a small
1399 "cookie" after each allocated string data block, and check for the
1400 presence of this cookie during GC. */
1402 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1403 static char const string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1404 { '\xde', '\xad', '\xbe', '\xef' };
1406 #else
1407 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1408 #endif
1410 /* Value is the size of an sdata structure large enough to hold NBYTES
1411 bytes of string data. The value returned includes a terminating
1412 NUL byte, the size of the sdata structure, and padding. */
1414 #ifdef GC_CHECK_STRING_BYTES
1416 #define SDATA_SIZE(NBYTES) \
1417 ((SDATA_DATA_OFFSET \
1418 + (NBYTES) + 1 \
1419 + sizeof (ptrdiff_t) - 1) \
1420 & ~(sizeof (ptrdiff_t) - 1))
1422 #else /* not GC_CHECK_STRING_BYTES */
1424 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1425 less than the size of that member. The 'max' is not needed when
1426 SDATA_DATA_OFFSET is a multiple of sizeof (ptrdiff_t), because then the
1427 alignment code reserves enough space. */
1429 #define SDATA_SIZE(NBYTES) \
1430 ((SDATA_DATA_OFFSET \
1431 + (SDATA_DATA_OFFSET % sizeof (ptrdiff_t) == 0 \
1432 ? NBYTES \
1433 : max (NBYTES, sizeof (ptrdiff_t) - 1)) \
1434 + 1 \
1435 + sizeof (ptrdiff_t) - 1) \
1436 & ~(sizeof (ptrdiff_t) - 1))
1438 #endif /* not GC_CHECK_STRING_BYTES */
1440 /* Extra bytes to allocate for each string. */
1442 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1444 /* Exact bound on the number of bytes in a string, not counting the
1445 terminating null. A string cannot contain more bytes than
1446 STRING_BYTES_BOUND, nor can it be so long that the size_t
1447 arithmetic in allocate_string_data would overflow while it is
1448 calculating a value to be passed to malloc. */
1449 static ptrdiff_t const STRING_BYTES_MAX =
1450 min (STRING_BYTES_BOUND,
1451 ((SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD
1452 - GC_STRING_EXTRA
1453 - offsetof (struct sblock, first_data)
1454 - SDATA_DATA_OFFSET)
1455 & ~(sizeof (EMACS_INT) - 1)));
1457 /* Initialize string allocation. Called from init_alloc_once. */
1459 static void
1460 init_strings (void)
1462 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1463 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1467 #ifdef GC_CHECK_STRING_BYTES
1469 static int check_string_bytes_count;
1471 /* Like STRING_BYTES, but with debugging check. Can be
1472 called during GC, so pay attention to the mark bit. */
1474 ptrdiff_t
1475 string_bytes (struct Lisp_String *s)
1477 ptrdiff_t nbytes =
1478 (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1480 if (!PURE_POINTER_P (s)
1481 && s->data
1482 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1483 emacs_abort ();
1484 return nbytes;
1487 /* Check validity of Lisp strings' string_bytes member in B. */
1489 static void
1490 check_sblock (struct sblock *b)
1492 struct sdata *from, *end, *from_end;
1494 end = b->next_free;
1496 for (from = &b->first_data; from < end; from = from_end)
1498 /* Compute the next FROM here because copying below may
1499 overwrite data we need to compute it. */
1500 ptrdiff_t nbytes;
1502 /* Check that the string size recorded in the string is the
1503 same as the one recorded in the sdata structure. */
1504 nbytes = SDATA_SIZE (from->string ? string_bytes (from->string)
1505 : SDATA_NBYTES (from));
1506 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1511 /* Check validity of Lisp strings' string_bytes member. ALL_P
1512 means check all strings, otherwise check only most
1513 recently allocated strings. Used for hunting a bug. */
1515 static void
1516 check_string_bytes (bool all_p)
1518 if (all_p)
1520 struct sblock *b;
1522 for (b = large_sblocks; b; b = b->next)
1524 struct Lisp_String *s = b->first_data.string;
1525 if (s)
1526 string_bytes (s);
1529 for (b = oldest_sblock; b; b = b->next)
1530 check_sblock (b);
1532 else if (current_sblock)
1533 check_sblock (current_sblock);
1536 #else /* not GC_CHECK_STRING_BYTES */
1538 #define check_string_bytes(all) ((void) 0)
1540 #endif /* GC_CHECK_STRING_BYTES */
1542 #ifdef GC_CHECK_STRING_FREE_LIST
1544 /* Walk through the string free list looking for bogus next pointers.
1545 This may catch buffer overrun from a previous string. */
1547 static void
1548 check_string_free_list (void)
1550 struct Lisp_String *s;
1552 /* Pop a Lisp_String off the free-list. */
1553 s = string_free_list;
1554 while (s != NULL)
1556 if ((uintptr_t) s < 1024)
1557 emacs_abort ();
1558 s = NEXT_FREE_LISP_STRING (s);
1561 #else
1562 #define check_string_free_list()
1563 #endif
1565 /* Return a new Lisp_String. */
1567 static struct Lisp_String *
1568 allocate_string (void)
1570 struct Lisp_String *s;
1572 MALLOC_BLOCK_INPUT;
1574 /* If the free-list is empty, allocate a new string_block, and
1575 add all the Lisp_Strings in it to the free-list. */
1576 if (string_free_list == NULL)
1578 struct string_block *b = lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1579 int i;
1581 b->next = string_blocks;
1582 string_blocks = b;
1584 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1586 s = b->strings + i;
1587 /* Every string on a free list should have NULL data pointer. */
1588 s->data = NULL;
1589 NEXT_FREE_LISP_STRING (s) = string_free_list;
1590 string_free_list = s;
1593 total_free_strings += STRING_BLOCK_SIZE;
1596 check_string_free_list ();
1598 /* Pop a Lisp_String off the free-list. */
1599 s = string_free_list;
1600 string_free_list = NEXT_FREE_LISP_STRING (s);
1602 MALLOC_UNBLOCK_INPUT;
1604 --total_free_strings;
1605 ++total_strings;
1606 ++strings_consed;
1607 consing_since_gc += sizeof *s;
1609 #ifdef GC_CHECK_STRING_BYTES
1610 if (!noninteractive)
1612 if (++check_string_bytes_count == 200)
1614 check_string_bytes_count = 0;
1615 check_string_bytes (1);
1617 else
1618 check_string_bytes (0);
1620 #endif /* GC_CHECK_STRING_BYTES */
1622 return s;
1626 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1627 plus a NUL byte at the end. Allocate an sdata structure for S, and
1628 set S->data to its `u.data' member. Store a NUL byte at the end of
1629 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1630 S->data if it was initially non-null. */
1632 void
1633 allocate_string_data (struct Lisp_String *s,
1634 EMACS_INT nchars, EMACS_INT nbytes)
1636 struct sdata *data, *old_data;
1637 struct sblock *b;
1638 ptrdiff_t needed, old_nbytes;
1640 if (STRING_BYTES_MAX < nbytes)
1641 string_overflow ();
1643 /* Determine the number of bytes needed to store NBYTES bytes
1644 of string data. */
1645 needed = SDATA_SIZE (nbytes);
1646 if (s->data)
1648 old_data = SDATA_OF_STRING (s);
1649 old_nbytes = STRING_BYTES (s);
1651 else
1652 old_data = NULL;
1654 MALLOC_BLOCK_INPUT;
1656 if (nbytes > LARGE_STRING_BYTES)
1658 size_t size = offsetof (struct sblock, first_data) + needed;
1660 #ifdef DOUG_LEA_MALLOC
1661 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1662 because mapped region contents are not preserved in
1663 a dumped Emacs.
1665 In case you think of allowing it in a dumped Emacs at the
1666 cost of not being able to re-dump, there's another reason:
1667 mmap'ed data typically have an address towards the top of the
1668 address space, which won't fit into an EMACS_INT (at least on
1669 32-bit systems with the current tagging scheme). --fx */
1670 mallopt (M_MMAP_MAX, 0);
1671 #endif
1673 b = lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
1675 #ifdef DOUG_LEA_MALLOC
1676 /* Back to a reasonable maximum of mmap'ed areas. */
1677 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1678 #endif
1680 b->next_free = &b->first_data;
1681 b->first_data.string = NULL;
1682 b->next = large_sblocks;
1683 large_sblocks = b;
1685 else if (current_sblock == NULL
1686 || (((char *) current_sblock + SBLOCK_SIZE
1687 - (char *) current_sblock->next_free)
1688 < (needed + GC_STRING_EXTRA)))
1690 /* Not enough room in the current sblock. */
1691 b = lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1692 b->next_free = &b->first_data;
1693 b->first_data.string = NULL;
1694 b->next = NULL;
1696 if (current_sblock)
1697 current_sblock->next = b;
1698 else
1699 oldest_sblock = b;
1700 current_sblock = b;
1702 else
1703 b = current_sblock;
1705 data = b->next_free;
1706 b->next_free = (struct sdata *) ((char *) data + needed + GC_STRING_EXTRA);
1708 MALLOC_UNBLOCK_INPUT;
1710 data->string = s;
1711 s->data = SDATA_DATA (data);
1712 #ifdef GC_CHECK_STRING_BYTES
1713 SDATA_NBYTES (data) = nbytes;
1714 #endif
1715 s->size = nchars;
1716 s->size_byte = nbytes;
1717 s->data[nbytes] = '\0';
1718 #ifdef GC_CHECK_STRING_OVERRUN
1719 memcpy ((char *) data + needed, string_overrun_cookie,
1720 GC_STRING_OVERRUN_COOKIE_SIZE);
1721 #endif
1723 /* Note that Faset may call to this function when S has already data
1724 assigned. In this case, mark data as free by setting it's string
1725 back-pointer to null, and record the size of the data in it. */
1726 if (old_data)
1728 SDATA_NBYTES (old_data) = old_nbytes;
1729 old_data->string = NULL;
1732 consing_since_gc += needed;
1736 /* Sweep and compact strings. */
1738 static void
1739 sweep_strings (void)
1741 struct string_block *b, *next;
1742 struct string_block *live_blocks = NULL;
1744 string_free_list = NULL;
1745 total_strings = total_free_strings = 0;
1746 total_string_bytes = 0;
1748 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1749 for (b = string_blocks; b; b = next)
1751 int i, nfree = 0;
1752 struct Lisp_String *free_list_before = string_free_list;
1754 next = b->next;
1756 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
1758 struct Lisp_String *s = b->strings + i;
1760 if (s->data)
1762 /* String was not on free-list before. */
1763 if (STRING_MARKED_P (s))
1765 /* String is live; unmark it and its intervals. */
1766 UNMARK_STRING (s);
1768 /* Do not use string_(set|get)_intervals here. */
1769 s->intervals = balance_intervals (s->intervals);
1771 ++total_strings;
1772 total_string_bytes += STRING_BYTES (s);
1774 else
1776 /* String is dead. Put it on the free-list. */
1777 struct sdata *data = SDATA_OF_STRING (s);
1779 /* Save the size of S in its sdata so that we know
1780 how large that is. Reset the sdata's string
1781 back-pointer so that we know it's free. */
1782 #ifdef GC_CHECK_STRING_BYTES
1783 if (string_bytes (s) != SDATA_NBYTES (data))
1784 emacs_abort ();
1785 #else
1786 data->u.nbytes = STRING_BYTES (s);
1787 #endif
1788 data->string = NULL;
1790 /* Reset the strings's `data' member so that we
1791 know it's free. */
1792 s->data = NULL;
1794 /* Put the string on the free-list. */
1795 NEXT_FREE_LISP_STRING (s) = string_free_list;
1796 string_free_list = s;
1797 ++nfree;
1800 else
1802 /* S was on the free-list before. Put it there again. */
1803 NEXT_FREE_LISP_STRING (s) = string_free_list;
1804 string_free_list = s;
1805 ++nfree;
1809 /* Free blocks that contain free Lisp_Strings only, except
1810 the first two of them. */
1811 if (nfree == STRING_BLOCK_SIZE
1812 && total_free_strings > STRING_BLOCK_SIZE)
1814 lisp_free (b);
1815 string_free_list = free_list_before;
1817 else
1819 total_free_strings += nfree;
1820 b->next = live_blocks;
1821 live_blocks = b;
1825 check_string_free_list ();
1827 string_blocks = live_blocks;
1828 free_large_strings ();
1829 compact_small_strings ();
1831 check_string_free_list ();
1835 /* Free dead large strings. */
1837 static void
1838 free_large_strings (void)
1840 struct sblock *b, *next;
1841 struct sblock *live_blocks = NULL;
1843 for (b = large_sblocks; b; b = next)
1845 next = b->next;
1847 if (b->first_data.string == NULL)
1848 lisp_free (b);
1849 else
1851 b->next = live_blocks;
1852 live_blocks = b;
1856 large_sblocks = live_blocks;
1860 /* Compact data of small strings. Free sblocks that don't contain
1861 data of live strings after compaction. */
1863 static void
1864 compact_small_strings (void)
1866 struct sblock *b, *tb, *next;
1867 struct sdata *from, *to, *end, *tb_end;
1868 struct sdata *to_end, *from_end;
1870 /* TB is the sblock we copy to, TO is the sdata within TB we copy
1871 to, and TB_END is the end of TB. */
1872 tb = oldest_sblock;
1873 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1874 to = &tb->first_data;
1876 /* Step through the blocks from the oldest to the youngest. We
1877 expect that old blocks will stabilize over time, so that less
1878 copying will happen this way. */
1879 for (b = oldest_sblock; b; b = b->next)
1881 end = b->next_free;
1882 eassert ((char *) end <= (char *) b + SBLOCK_SIZE);
1884 for (from = &b->first_data; from < end; from = from_end)
1886 /* Compute the next FROM here because copying below may
1887 overwrite data we need to compute it. */
1888 ptrdiff_t nbytes;
1889 struct Lisp_String *s = from->string;
1891 #ifdef GC_CHECK_STRING_BYTES
1892 /* Check that the string size recorded in the string is the
1893 same as the one recorded in the sdata structure. */
1894 if (s && string_bytes (s) != SDATA_NBYTES (from))
1895 emacs_abort ();
1896 #endif /* GC_CHECK_STRING_BYTES */
1898 nbytes = s ? STRING_BYTES (s) : SDATA_NBYTES (from);
1899 eassert (nbytes <= LARGE_STRING_BYTES);
1901 nbytes = SDATA_SIZE (nbytes);
1902 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1904 #ifdef GC_CHECK_STRING_OVERRUN
1905 if (memcmp (string_overrun_cookie,
1906 (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
1907 GC_STRING_OVERRUN_COOKIE_SIZE))
1908 emacs_abort ();
1909 #endif
1911 /* Non-NULL S means it's alive. Copy its data. */
1912 if (s)
1914 /* If TB is full, proceed with the next sblock. */
1915 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
1916 if (to_end > tb_end)
1918 tb->next_free = to;
1919 tb = tb->next;
1920 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1921 to = &tb->first_data;
1922 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
1925 /* Copy, and update the string's `data' pointer. */
1926 if (from != to)
1928 eassert (tb != b || to < from);
1929 memmove (to, from, nbytes + GC_STRING_EXTRA);
1930 to->string->data = SDATA_DATA (to);
1933 /* Advance past the sdata we copied to. */
1934 to = to_end;
1939 /* The rest of the sblocks following TB don't contain live data, so
1940 we can free them. */
1941 for (b = tb->next; b; b = next)
1943 next = b->next;
1944 lisp_free (b);
1947 tb->next_free = to;
1948 tb->next = NULL;
1949 current_sblock = tb;
1952 void
1953 string_overflow (void)
1955 error ("Maximum string size exceeded");
1958 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
1959 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
1960 LENGTH must be an integer.
1961 INIT must be an integer that represents a character. */)
1962 (Lisp_Object length, Lisp_Object init)
1964 register Lisp_Object val;
1965 register unsigned char *p, *end;
1966 int c;
1967 EMACS_INT nbytes;
1969 CHECK_NATNUM (length);
1970 CHECK_CHARACTER (init);
1972 c = XFASTINT (init);
1973 if (ASCII_CHAR_P (c))
1975 nbytes = XINT (length);
1976 val = make_uninit_string (nbytes);
1977 p = SDATA (val);
1978 end = p + SCHARS (val);
1979 while (p != end)
1980 *p++ = c;
1982 else
1984 unsigned char str[MAX_MULTIBYTE_LENGTH];
1985 int len = CHAR_STRING (c, str);
1986 EMACS_INT string_len = XINT (length);
1988 if (string_len > STRING_BYTES_MAX / len)
1989 string_overflow ();
1990 nbytes = len * string_len;
1991 val = make_uninit_multibyte_string (string_len, nbytes);
1992 p = SDATA (val);
1993 end = p + nbytes;
1994 while (p != end)
1996 memcpy (p, str, len);
1997 p += len;
2001 *p = 0;
2002 return val;
2006 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2007 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2008 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2009 (Lisp_Object length, Lisp_Object init)
2011 register Lisp_Object val;
2012 struct Lisp_Bool_Vector *p;
2013 ptrdiff_t length_in_chars;
2014 EMACS_INT length_in_elts;
2015 int bits_per_value;
2016 int extra_bool_elts = ((bool_header_size - header_size + word_size - 1)
2017 / word_size);
2019 CHECK_NATNUM (length);
2021 bits_per_value = sizeof (EMACS_INT) * BOOL_VECTOR_BITS_PER_CHAR;
2023 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
2025 val = Fmake_vector (make_number (length_in_elts + extra_bool_elts), Qnil);
2027 /* No Lisp_Object to trace in there. */
2028 XSETPVECTYPESIZE (XVECTOR (val), PVEC_BOOL_VECTOR, 0);
2030 p = XBOOL_VECTOR (val);
2031 p->size = XFASTINT (length);
2033 length_in_chars = ((XFASTINT (length) + BOOL_VECTOR_BITS_PER_CHAR - 1)
2034 / BOOL_VECTOR_BITS_PER_CHAR);
2035 if (length_in_chars)
2037 memset (p->data, ! NILP (init) ? -1 : 0, length_in_chars);
2039 /* Clear any extraneous bits in the last byte. */
2040 p->data[length_in_chars - 1]
2041 &= (1 << ((XFASTINT (length) - 1) % BOOL_VECTOR_BITS_PER_CHAR + 1)) - 1;
2044 return val;
2048 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2049 of characters from the contents. This string may be unibyte or
2050 multibyte, depending on the contents. */
2052 Lisp_Object
2053 make_string (const char *contents, ptrdiff_t nbytes)
2055 register Lisp_Object val;
2056 ptrdiff_t nchars, multibyte_nbytes;
2058 parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
2059 &nchars, &multibyte_nbytes);
2060 if (nbytes == nchars || nbytes != multibyte_nbytes)
2061 /* CONTENTS contains no multibyte sequences or contains an invalid
2062 multibyte sequence. We must make unibyte string. */
2063 val = make_unibyte_string (contents, nbytes);
2064 else
2065 val = make_multibyte_string (contents, nchars, nbytes);
2066 return val;
2070 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
2072 Lisp_Object
2073 make_unibyte_string (const char *contents, ptrdiff_t length)
2075 register Lisp_Object val;
2076 val = make_uninit_string (length);
2077 memcpy (SDATA (val), contents, length);
2078 return val;
2082 /* Make a multibyte string from NCHARS characters occupying NBYTES
2083 bytes at CONTENTS. */
2085 Lisp_Object
2086 make_multibyte_string (const char *contents,
2087 ptrdiff_t nchars, ptrdiff_t nbytes)
2089 register Lisp_Object val;
2090 val = make_uninit_multibyte_string (nchars, nbytes);
2091 memcpy (SDATA (val), contents, nbytes);
2092 return val;
2096 /* Make a string from NCHARS characters occupying NBYTES bytes at
2097 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2099 Lisp_Object
2100 make_string_from_bytes (const char *contents,
2101 ptrdiff_t nchars, ptrdiff_t nbytes)
2103 register Lisp_Object val;
2104 val = make_uninit_multibyte_string (nchars, nbytes);
2105 memcpy (SDATA (val), contents, nbytes);
2106 if (SBYTES (val) == SCHARS (val))
2107 STRING_SET_UNIBYTE (val);
2108 return val;
2112 /* Make a string from NCHARS characters occupying NBYTES bytes at
2113 CONTENTS. The argument MULTIBYTE controls whether to label the
2114 string as multibyte. If NCHARS is negative, it counts the number of
2115 characters by itself. */
2117 Lisp_Object
2118 make_specified_string (const char *contents,
2119 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
2121 Lisp_Object val;
2123 if (nchars < 0)
2125 if (multibyte)
2126 nchars = multibyte_chars_in_text ((const unsigned char *) contents,
2127 nbytes);
2128 else
2129 nchars = nbytes;
2131 val = make_uninit_multibyte_string (nchars, nbytes);
2132 memcpy (SDATA (val), contents, nbytes);
2133 if (!multibyte)
2134 STRING_SET_UNIBYTE (val);
2135 return val;
2139 /* Return an unibyte Lisp_String set up to hold LENGTH characters
2140 occupying LENGTH bytes. */
2142 Lisp_Object
2143 make_uninit_string (EMACS_INT length)
2145 Lisp_Object val;
2147 if (!length)
2148 return empty_unibyte_string;
2149 val = make_uninit_multibyte_string (length, length);
2150 STRING_SET_UNIBYTE (val);
2151 return val;
2155 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2156 which occupy NBYTES bytes. */
2158 Lisp_Object
2159 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2161 Lisp_Object string;
2162 struct Lisp_String *s;
2164 if (nchars < 0)
2165 emacs_abort ();
2166 if (!nbytes)
2167 return empty_multibyte_string;
2169 s = allocate_string ();
2170 s->intervals = NULL;
2171 allocate_string_data (s, nchars, nbytes);
2172 XSETSTRING (string, s);
2173 string_chars_consed += nbytes;
2174 return string;
2177 /* Print arguments to BUF according to a FORMAT, then return
2178 a Lisp_String initialized with the data from BUF. */
2180 Lisp_Object
2181 make_formatted_string (char *buf, const char *format, ...)
2183 va_list ap;
2184 int length;
2186 va_start (ap, format);
2187 length = vsprintf (buf, format, ap);
2188 va_end (ap);
2189 return make_string (buf, length);
2193 /***********************************************************************
2194 Float Allocation
2195 ***********************************************************************/
2197 /* We store float cells inside of float_blocks, allocating a new
2198 float_block with malloc whenever necessary. Float cells reclaimed
2199 by GC are put on a free list to be reallocated before allocating
2200 any new float cells from the latest float_block. */
2202 #define FLOAT_BLOCK_SIZE \
2203 (((BLOCK_BYTES - sizeof (struct float_block *) \
2204 /* The compiler might add padding at the end. */ \
2205 - (sizeof (struct Lisp_Float) - sizeof (int))) * CHAR_BIT) \
2206 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2208 #define GETMARKBIT(block,n) \
2209 (((block)->gcmarkbits[(n) / (sizeof (int) * CHAR_BIT)] \
2210 >> ((n) % (sizeof (int) * CHAR_BIT))) \
2211 & 1)
2213 #define SETMARKBIT(block,n) \
2214 (block)->gcmarkbits[(n) / (sizeof (int) * CHAR_BIT)] \
2215 |= 1 << ((n) % (sizeof (int) * CHAR_BIT))
2217 #define UNSETMARKBIT(block,n) \
2218 (block)->gcmarkbits[(n) / (sizeof (int) * CHAR_BIT)] \
2219 &= ~(1 << ((n) % (sizeof (int) * CHAR_BIT)))
2221 #define FLOAT_BLOCK(fptr) \
2222 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2224 #define FLOAT_INDEX(fptr) \
2225 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2227 struct float_block
2229 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2230 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2231 int gcmarkbits[1 + FLOAT_BLOCK_SIZE / (sizeof (int) * CHAR_BIT)];
2232 struct float_block *next;
2235 #define FLOAT_MARKED_P(fptr) \
2236 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2238 #define FLOAT_MARK(fptr) \
2239 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2241 #define FLOAT_UNMARK(fptr) \
2242 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2244 /* Current float_block. */
2246 static struct float_block *float_block;
2248 /* Index of first unused Lisp_Float in the current float_block. */
2250 static int float_block_index = FLOAT_BLOCK_SIZE;
2252 /* Free-list of Lisp_Floats. */
2254 static struct Lisp_Float *float_free_list;
2256 /* Return a new float object with value FLOAT_VALUE. */
2258 Lisp_Object
2259 make_float (double float_value)
2261 register Lisp_Object val;
2263 MALLOC_BLOCK_INPUT;
2265 if (float_free_list)
2267 /* We use the data field for chaining the free list
2268 so that we won't use the same field that has the mark bit. */
2269 XSETFLOAT (val, float_free_list);
2270 float_free_list = float_free_list->u.chain;
2272 else
2274 if (float_block_index == FLOAT_BLOCK_SIZE)
2276 struct float_block *new
2277 = lisp_align_malloc (sizeof *new, MEM_TYPE_FLOAT);
2278 new->next = float_block;
2279 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2280 float_block = new;
2281 float_block_index = 0;
2282 total_free_floats += FLOAT_BLOCK_SIZE;
2284 XSETFLOAT (val, &float_block->floats[float_block_index]);
2285 float_block_index++;
2288 MALLOC_UNBLOCK_INPUT;
2290 XFLOAT_INIT (val, float_value);
2291 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2292 consing_since_gc += sizeof (struct Lisp_Float);
2293 floats_consed++;
2294 total_free_floats--;
2295 return val;
2300 /***********************************************************************
2301 Cons Allocation
2302 ***********************************************************************/
2304 /* We store cons cells inside of cons_blocks, allocating a new
2305 cons_block with malloc whenever necessary. Cons cells reclaimed by
2306 GC are put on a free list to be reallocated before allocating
2307 any new cons cells from the latest cons_block. */
2309 #define CONS_BLOCK_SIZE \
2310 (((BLOCK_BYTES - sizeof (struct cons_block *) \
2311 /* The compiler might add padding at the end. */ \
2312 - (sizeof (struct Lisp_Cons) - sizeof (int))) * CHAR_BIT) \
2313 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2315 #define CONS_BLOCK(fptr) \
2316 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2318 #define CONS_INDEX(fptr) \
2319 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2321 struct cons_block
2323 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2324 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2325 int gcmarkbits[1 + CONS_BLOCK_SIZE / (sizeof (int) * CHAR_BIT)];
2326 struct cons_block *next;
2329 #define CONS_MARKED_P(fptr) \
2330 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2332 #define CONS_MARK(fptr) \
2333 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2335 #define CONS_UNMARK(fptr) \
2336 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2338 /* Current cons_block. */
2340 static struct cons_block *cons_block;
2342 /* Index of first unused Lisp_Cons in the current block. */
2344 static int cons_block_index = CONS_BLOCK_SIZE;
2346 /* Free-list of Lisp_Cons structures. */
2348 static struct Lisp_Cons *cons_free_list;
2350 /* Explicitly free a cons cell by putting it on the free-list. */
2352 void
2353 free_cons (struct Lisp_Cons *ptr)
2355 ptr->u.chain = cons_free_list;
2356 #if GC_MARK_STACK
2357 ptr->car = Vdead;
2358 #endif
2359 cons_free_list = ptr;
2360 consing_since_gc -= sizeof *ptr;
2361 total_free_conses++;
2364 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2365 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2366 (Lisp_Object car, Lisp_Object cdr)
2368 register Lisp_Object val;
2370 MALLOC_BLOCK_INPUT;
2372 if (cons_free_list)
2374 /* We use the cdr for chaining the free list
2375 so that we won't use the same field that has the mark bit. */
2376 XSETCONS (val, cons_free_list);
2377 cons_free_list = cons_free_list->u.chain;
2379 else
2381 if (cons_block_index == CONS_BLOCK_SIZE)
2383 struct cons_block *new
2384 = lisp_align_malloc (sizeof *new, MEM_TYPE_CONS);
2385 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2386 new->next = cons_block;
2387 cons_block = new;
2388 cons_block_index = 0;
2389 total_free_conses += CONS_BLOCK_SIZE;
2391 XSETCONS (val, &cons_block->conses[cons_block_index]);
2392 cons_block_index++;
2395 MALLOC_UNBLOCK_INPUT;
2397 XSETCAR (val, car);
2398 XSETCDR (val, cdr);
2399 eassert (!CONS_MARKED_P (XCONS (val)));
2400 consing_since_gc += sizeof (struct Lisp_Cons);
2401 total_free_conses--;
2402 cons_cells_consed++;
2403 return val;
2406 #ifdef GC_CHECK_CONS_LIST
2407 /* Get an error now if there's any junk in the cons free list. */
2408 void
2409 check_cons_list (void)
2411 struct Lisp_Cons *tail = cons_free_list;
2413 while (tail)
2414 tail = tail->u.chain;
2416 #endif
2418 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2420 Lisp_Object
2421 list1 (Lisp_Object arg1)
2423 return Fcons (arg1, Qnil);
2426 Lisp_Object
2427 list2 (Lisp_Object arg1, Lisp_Object arg2)
2429 return Fcons (arg1, Fcons (arg2, Qnil));
2433 Lisp_Object
2434 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2436 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2440 Lisp_Object
2441 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2443 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2447 Lisp_Object
2448 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2450 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2451 Fcons (arg5, Qnil)))));
2454 /* Make a list of COUNT Lisp_Objects, where ARG is the
2455 first one. Allocate conses from pure space if TYPE
2456 is CONSTYPE_PURE, or allocate as usual if type is CONSTYPE_HEAP. */
2458 Lisp_Object
2459 listn (enum constype type, ptrdiff_t count, Lisp_Object arg, ...)
2461 va_list ap;
2462 ptrdiff_t i;
2463 Lisp_Object val, *objp;
2465 /* Change to SAFE_ALLOCA if you hit this eassert. */
2466 eassert (count <= MAX_ALLOCA / word_size);
2468 objp = alloca (count * word_size);
2469 objp[0] = arg;
2470 va_start (ap, arg);
2471 for (i = 1; i < count; i++)
2472 objp[i] = va_arg (ap, Lisp_Object);
2473 va_end (ap);
2475 for (val = Qnil, i = count - 1; i >= 0; i--)
2477 if (type == CONSTYPE_PURE)
2478 val = pure_cons (objp[i], val);
2479 else if (type == CONSTYPE_HEAP)
2480 val = Fcons (objp[i], val);
2481 else
2482 emacs_abort ();
2484 return val;
2487 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2488 doc: /* Return a newly created list with specified arguments as elements.
2489 Any number of arguments, even zero arguments, are allowed.
2490 usage: (list &rest OBJECTS) */)
2491 (ptrdiff_t nargs, Lisp_Object *args)
2493 register Lisp_Object val;
2494 val = Qnil;
2496 while (nargs > 0)
2498 nargs--;
2499 val = Fcons (args[nargs], val);
2501 return val;
2505 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2506 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2507 (register Lisp_Object length, Lisp_Object init)
2509 register Lisp_Object val;
2510 register EMACS_INT size;
2512 CHECK_NATNUM (length);
2513 size = XFASTINT (length);
2515 val = Qnil;
2516 while (size > 0)
2518 val = Fcons (init, val);
2519 --size;
2521 if (size > 0)
2523 val = Fcons (init, val);
2524 --size;
2526 if (size > 0)
2528 val = Fcons (init, val);
2529 --size;
2531 if (size > 0)
2533 val = Fcons (init, val);
2534 --size;
2536 if (size > 0)
2538 val = Fcons (init, val);
2539 --size;
2545 QUIT;
2548 return val;
2553 /***********************************************************************
2554 Vector Allocation
2555 ***********************************************************************/
2557 /* This value is balanced well enough to avoid too much internal overhead
2558 for the most common cases; it's not required to be a power of two, but
2559 it's expected to be a mult-of-ROUNDUP_SIZE (see below). */
2561 #define VECTOR_BLOCK_SIZE 4096
2563 /* Align allocation request sizes to be a multiple of ROUNDUP_SIZE. */
2564 enum
2566 roundup_size = COMMON_MULTIPLE (word_size, USE_LSB_TAG ? GCALIGNMENT : 1)
2569 /* ROUNDUP_SIZE must be a power of 2. */
2570 verify ((roundup_size & (roundup_size - 1)) == 0);
2572 /* Verify assumptions described above. */
2573 verify ((VECTOR_BLOCK_SIZE % roundup_size) == 0);
2574 verify (VECTOR_BLOCK_SIZE <= (1 << PSEUDOVECTOR_SIZE_BITS));
2576 /* Round up X to nearest mult-of-ROUNDUP_SIZE. */
2578 #define vroundup(x) (((x) + (roundup_size - 1)) & ~(roundup_size - 1))
2580 /* Rounding helps to maintain alignment constraints if USE_LSB_TAG. */
2582 #define VECTOR_BLOCK_BYTES (VECTOR_BLOCK_SIZE - vroundup (sizeof (void *)))
2584 /* Size of the minimal vector allocated from block. */
2586 #define VBLOCK_BYTES_MIN vroundup (sizeof (struct Lisp_Vector))
2588 /* Size of the largest vector allocated from block. */
2590 #define VBLOCK_BYTES_MAX \
2591 vroundup ((VECTOR_BLOCK_BYTES / 2) - word_size)
2593 /* We maintain one free list for each possible block-allocated
2594 vector size, and this is the number of free lists we have. */
2596 #define VECTOR_MAX_FREE_LIST_INDEX \
2597 ((VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN) / roundup_size + 1)
2599 /* Common shortcut to advance vector pointer over a block data. */
2601 #define ADVANCE(v, nbytes) ((struct Lisp_Vector *) ((char *) (v) + (nbytes)))
2603 /* Common shortcut to calculate NBYTES-vector index in VECTOR_FREE_LISTS. */
2605 #define VINDEX(nbytes) (((nbytes) - VBLOCK_BYTES_MIN) / roundup_size)
2607 /* Common shortcut to setup vector on a free list. */
2609 #define SETUP_ON_FREE_LIST(v, nbytes, index) \
2610 do { \
2611 XSETPVECTYPESIZE (v, PVEC_FREE, nbytes); \
2612 eassert ((nbytes) % roundup_size == 0); \
2613 (index) = VINDEX (nbytes); \
2614 eassert ((index) < VECTOR_MAX_FREE_LIST_INDEX); \
2615 (v)->header.next.vector = vector_free_lists[index]; \
2616 vector_free_lists[index] = (v); \
2617 total_free_vector_slots += (nbytes) / word_size; \
2618 } while (0)
2620 struct vector_block
2622 char data[VECTOR_BLOCK_BYTES];
2623 struct vector_block *next;
2626 /* Chain of vector blocks. */
2628 static struct vector_block *vector_blocks;
2630 /* Vector free lists, where NTH item points to a chain of free
2631 vectors of the same NBYTES size, so NTH == VINDEX (NBYTES). */
2633 static struct Lisp_Vector *vector_free_lists[VECTOR_MAX_FREE_LIST_INDEX];
2635 /* Singly-linked list of large vectors. */
2637 static struct Lisp_Vector *large_vectors;
2639 /* The only vector with 0 slots, allocated from pure space. */
2641 Lisp_Object zero_vector;
2643 /* Number of live vectors. */
2645 static EMACS_INT total_vectors;
2647 /* Total size of live and free vectors, in Lisp_Object units. */
2649 static EMACS_INT total_vector_slots, total_free_vector_slots;
2651 /* Get a new vector block. */
2653 static struct vector_block *
2654 allocate_vector_block (void)
2656 struct vector_block *block = xmalloc (sizeof *block);
2658 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
2659 mem_insert (block->data, block->data + VECTOR_BLOCK_BYTES,
2660 MEM_TYPE_VECTOR_BLOCK);
2661 #endif
2663 block->next = vector_blocks;
2664 vector_blocks = block;
2665 return block;
2668 /* Called once to initialize vector allocation. */
2670 static void
2671 init_vectors (void)
2673 zero_vector = make_pure_vector (0);
2676 /* Allocate vector from a vector block. */
2678 static struct Lisp_Vector *
2679 allocate_vector_from_block (size_t nbytes)
2681 struct Lisp_Vector *vector, *rest;
2682 struct vector_block *block;
2683 size_t index, restbytes;
2685 eassert (VBLOCK_BYTES_MIN <= nbytes && nbytes <= VBLOCK_BYTES_MAX);
2686 eassert (nbytes % roundup_size == 0);
2688 /* First, try to allocate from a free list
2689 containing vectors of the requested size. */
2690 index = VINDEX (nbytes);
2691 if (vector_free_lists[index])
2693 vector = vector_free_lists[index];
2694 vector_free_lists[index] = vector->header.next.vector;
2695 vector->header.next.nbytes = nbytes;
2696 total_free_vector_slots -= nbytes / word_size;
2697 return vector;
2700 /* Next, check free lists containing larger vectors. Since
2701 we will split the result, we should have remaining space
2702 large enough to use for one-slot vector at least. */
2703 for (index = VINDEX (nbytes + VBLOCK_BYTES_MIN);
2704 index < VECTOR_MAX_FREE_LIST_INDEX; index++)
2705 if (vector_free_lists[index])
2707 /* This vector is larger than requested. */
2708 vector = vector_free_lists[index];
2709 vector_free_lists[index] = vector->header.next.vector;
2710 vector->header.next.nbytes = nbytes;
2711 total_free_vector_slots -= nbytes / word_size;
2713 /* Excess bytes are used for the smaller vector,
2714 which should be set on an appropriate free list. */
2715 restbytes = index * roundup_size + VBLOCK_BYTES_MIN - nbytes;
2716 eassert (restbytes % roundup_size == 0);
2717 rest = ADVANCE (vector, nbytes);
2718 SETUP_ON_FREE_LIST (rest, restbytes, index);
2719 return vector;
2722 /* Finally, need a new vector block. */
2723 block = allocate_vector_block ();
2725 /* New vector will be at the beginning of this block. */
2726 vector = (struct Lisp_Vector *) block->data;
2727 vector->header.next.nbytes = nbytes;
2729 /* If the rest of space from this block is large enough
2730 for one-slot vector at least, set up it on a free list. */
2731 restbytes = VECTOR_BLOCK_BYTES - nbytes;
2732 if (restbytes >= VBLOCK_BYTES_MIN)
2734 eassert (restbytes % roundup_size == 0);
2735 rest = ADVANCE (vector, nbytes);
2736 SETUP_ON_FREE_LIST (rest, restbytes, index);
2738 return vector;
2741 /* Nonzero if VECTOR pointer is valid pointer inside BLOCK. */
2743 #define VECTOR_IN_BLOCK(vector, block) \
2744 ((char *) (vector) <= (block)->data \
2745 + VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN)
2747 /* Number of bytes used by vector-block-allocated object. This is the only
2748 place where we actually use the `nbytes' field of the vector-header.
2749 I.e. we could get rid of the `nbytes' field by computing it based on the
2750 vector-type. */
2752 #define PSEUDOVECTOR_NBYTES(vector) \
2753 (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FREE) \
2754 ? vector->header.size & PSEUDOVECTOR_SIZE_MASK \
2755 : vector->header.next.nbytes)
2757 /* Reclaim space used by unmarked vectors. */
2759 static void
2760 sweep_vectors (void)
2762 struct vector_block *block = vector_blocks, **bprev = &vector_blocks;
2763 struct Lisp_Vector *vector, *next, **vprev = &large_vectors;
2765 total_vectors = total_vector_slots = total_free_vector_slots = 0;
2766 memset (vector_free_lists, 0, sizeof (vector_free_lists));
2768 /* Looking through vector blocks. */
2770 for (block = vector_blocks; block; block = *bprev)
2772 bool free_this_block = 0;
2774 for (vector = (struct Lisp_Vector *) block->data;
2775 VECTOR_IN_BLOCK (vector, block); vector = next)
2777 if (VECTOR_MARKED_P (vector))
2779 VECTOR_UNMARK (vector);
2780 total_vectors++;
2781 total_vector_slots += vector->header.next.nbytes / word_size;
2782 next = ADVANCE (vector, vector->header.next.nbytes);
2784 else
2786 ptrdiff_t nbytes = PSEUDOVECTOR_NBYTES (vector);
2787 ptrdiff_t total_bytes = nbytes;
2789 next = ADVANCE (vector, nbytes);
2791 /* While NEXT is not marked, try to coalesce with VECTOR,
2792 thus making VECTOR of the largest possible size. */
2794 while (VECTOR_IN_BLOCK (next, block))
2796 if (VECTOR_MARKED_P (next))
2797 break;
2798 nbytes = PSEUDOVECTOR_NBYTES (next);
2799 total_bytes += nbytes;
2800 next = ADVANCE (next, nbytes);
2803 eassert (total_bytes % roundup_size == 0);
2805 if (vector == (struct Lisp_Vector *) block->data
2806 && !VECTOR_IN_BLOCK (next, block))
2807 /* This block should be freed because all of it's
2808 space was coalesced into the only free vector. */
2809 free_this_block = 1;
2810 else
2812 int tmp;
2813 SETUP_ON_FREE_LIST (vector, total_bytes, tmp);
2818 if (free_this_block)
2820 *bprev = block->next;
2821 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
2822 mem_delete (mem_find (block->data));
2823 #endif
2824 xfree (block);
2826 else
2827 bprev = &block->next;
2830 /* Sweep large vectors. */
2832 for (vector = large_vectors; vector; vector = *vprev)
2834 if (VECTOR_MARKED_P (vector))
2836 VECTOR_UNMARK (vector);
2837 total_vectors++;
2838 if (vector->header.size & PSEUDOVECTOR_FLAG)
2840 struct Lisp_Bool_Vector *b = (struct Lisp_Bool_Vector *) vector;
2842 /* All non-bool pseudovectors are small enough to be allocated
2843 from vector blocks. This code should be redesigned if some
2844 pseudovector type grows beyond VBLOCK_BYTES_MAX. */
2845 eassert (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_BOOL_VECTOR));
2847 total_vector_slots
2848 += (bool_header_size
2849 + ((b->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
2850 / BOOL_VECTOR_BITS_PER_CHAR)) / word_size;
2852 else
2853 total_vector_slots
2854 += header_size / word_size + vector->header.size;
2855 vprev = &vector->header.next.vector;
2857 else
2859 *vprev = vector->header.next.vector;
2860 lisp_free (vector);
2865 /* Value is a pointer to a newly allocated Lisp_Vector structure
2866 with room for LEN Lisp_Objects. */
2868 static struct Lisp_Vector *
2869 allocate_vectorlike (ptrdiff_t len)
2871 struct Lisp_Vector *p;
2873 MALLOC_BLOCK_INPUT;
2875 if (len == 0)
2876 p = XVECTOR (zero_vector);
2877 else
2879 size_t nbytes = header_size + len * word_size;
2881 #ifdef DOUG_LEA_MALLOC
2882 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2883 because mapped region contents are not preserved in
2884 a dumped Emacs. */
2885 mallopt (M_MMAP_MAX, 0);
2886 #endif
2888 if (nbytes <= VBLOCK_BYTES_MAX)
2889 p = allocate_vector_from_block (vroundup (nbytes));
2890 else
2892 p = lisp_malloc (nbytes, MEM_TYPE_VECTORLIKE);
2893 p->header.next.vector = large_vectors;
2894 large_vectors = p;
2897 #ifdef DOUG_LEA_MALLOC
2898 /* Back to a reasonable maximum of mmap'ed areas. */
2899 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2900 #endif
2902 consing_since_gc += nbytes;
2903 vector_cells_consed += len;
2906 MALLOC_UNBLOCK_INPUT;
2908 return p;
2912 /* Allocate a vector with LEN slots. */
2914 struct Lisp_Vector *
2915 allocate_vector (EMACS_INT len)
2917 struct Lisp_Vector *v;
2918 ptrdiff_t nbytes_max = min (PTRDIFF_MAX, SIZE_MAX);
2920 if (min ((nbytes_max - header_size) / word_size, MOST_POSITIVE_FIXNUM) < len)
2921 memory_full (SIZE_MAX);
2922 v = allocate_vectorlike (len);
2923 v->header.size = len;
2924 return v;
2928 /* Allocate other vector-like structures. */
2930 struct Lisp_Vector *
2931 allocate_pseudovector (int memlen, int lisplen, int tag)
2933 struct Lisp_Vector *v = allocate_vectorlike (memlen);
2934 int i;
2936 /* Only the first lisplen slots will be traced normally by the GC. */
2937 for (i = 0; i < lisplen; ++i)
2938 v->contents[i] = Qnil;
2940 XSETPVECTYPESIZE (v, tag, lisplen);
2941 return v;
2944 struct buffer *
2945 allocate_buffer (void)
2947 struct buffer *b = lisp_malloc (sizeof *b, MEM_TYPE_BUFFER);
2949 XSETPVECTYPESIZE (b, PVEC_BUFFER, (offsetof (struct buffer, own_text)
2950 - header_size) / word_size);
2951 /* Put B on the chain of all buffers including killed ones. */
2952 b->header.next.buffer = all_buffers;
2953 all_buffers = b;
2954 /* Note that the rest fields of B are not initialized. */
2955 return b;
2958 struct Lisp_Hash_Table *
2959 allocate_hash_table (void)
2961 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table, count, PVEC_HASH_TABLE);
2964 struct window *
2965 allocate_window (void)
2967 struct window *w;
2969 w = ALLOCATE_PSEUDOVECTOR (struct window, current_matrix, PVEC_WINDOW);
2970 /* Users assumes that non-Lisp data is zeroed. */
2971 memset (&w->current_matrix, 0,
2972 sizeof (*w) - offsetof (struct window, current_matrix));
2973 return w;
2976 struct terminal *
2977 allocate_terminal (void)
2979 struct terminal *t;
2981 t = ALLOCATE_PSEUDOVECTOR (struct terminal, next_terminal, PVEC_TERMINAL);
2982 /* Users assumes that non-Lisp data is zeroed. */
2983 memset (&t->next_terminal, 0,
2984 sizeof (*t) - offsetof (struct terminal, next_terminal));
2985 return t;
2988 struct frame *
2989 allocate_frame (void)
2991 struct frame *f;
2993 f = ALLOCATE_PSEUDOVECTOR (struct frame, face_cache, PVEC_FRAME);
2994 /* Users assumes that non-Lisp data is zeroed. */
2995 memset (&f->face_cache, 0,
2996 sizeof (*f) - offsetof (struct frame, face_cache));
2997 return f;
3000 struct Lisp_Process *
3001 allocate_process (void)
3003 struct Lisp_Process *p;
3005 p = ALLOCATE_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
3006 /* Users assumes that non-Lisp data is zeroed. */
3007 memset (&p->pid, 0,
3008 sizeof (*p) - offsetof (struct Lisp_Process, pid));
3009 return p;
3012 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
3013 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
3014 See also the function `vector'. */)
3015 (register Lisp_Object length, Lisp_Object init)
3017 Lisp_Object vector;
3018 register ptrdiff_t sizei;
3019 register ptrdiff_t i;
3020 register struct Lisp_Vector *p;
3022 CHECK_NATNUM (length);
3024 p = allocate_vector (XFASTINT (length));
3025 sizei = XFASTINT (length);
3026 for (i = 0; i < sizei; i++)
3027 p->contents[i] = init;
3029 XSETVECTOR (vector, p);
3030 return vector;
3034 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3035 doc: /* Return a newly created vector with specified arguments as elements.
3036 Any number of arguments, even zero arguments, are allowed.
3037 usage: (vector &rest OBJECTS) */)
3038 (ptrdiff_t nargs, Lisp_Object *args)
3040 register Lisp_Object len, val;
3041 ptrdiff_t i;
3042 register struct Lisp_Vector *p;
3044 XSETFASTINT (len, nargs);
3045 val = Fmake_vector (len, Qnil);
3046 p = XVECTOR (val);
3047 for (i = 0; i < nargs; i++)
3048 p->contents[i] = args[i];
3049 return val;
3052 void
3053 make_byte_code (struct Lisp_Vector *v)
3055 if (v->header.size > 1 && STRINGP (v->contents[1])
3056 && STRING_MULTIBYTE (v->contents[1]))
3057 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3058 earlier because they produced a raw 8-bit string for byte-code
3059 and now such a byte-code string is loaded as multibyte while
3060 raw 8-bit characters converted to multibyte form. Thus, now we
3061 must convert them back to the original unibyte form. */
3062 v->contents[1] = Fstring_as_unibyte (v->contents[1]);
3063 XSETPVECTYPE (v, PVEC_COMPILED);
3066 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3067 doc: /* Create a byte-code object with specified arguments as elements.
3068 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3069 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3070 and (optional) INTERACTIVE-SPEC.
3071 The first four arguments are required; at most six have any
3072 significance.
3073 The ARGLIST can be either like the one of `lambda', in which case the arguments
3074 will be dynamically bound before executing the byte code, or it can be an
3075 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3076 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3077 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3078 argument to catch the left-over arguments. If such an integer is used, the
3079 arguments will not be dynamically bound but will be instead pushed on the
3080 stack before executing the byte-code.
3081 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3082 (ptrdiff_t nargs, Lisp_Object *args)
3084 register Lisp_Object len, val;
3085 ptrdiff_t i;
3086 register struct Lisp_Vector *p;
3088 /* We used to purecopy everything here, if purify-flga was set. This worked
3089 OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
3090 dangerous, since make-byte-code is used during execution to build
3091 closures, so any closure built during the preload phase would end up
3092 copied into pure space, including its free variables, which is sometimes
3093 just wasteful and other times plainly wrong (e.g. those free vars may want
3094 to be setcar'd). */
3096 XSETFASTINT (len, nargs);
3097 val = Fmake_vector (len, Qnil);
3099 p = XVECTOR (val);
3100 for (i = 0; i < nargs; i++)
3101 p->contents[i] = args[i];
3102 make_byte_code (p);
3103 XSETCOMPILED (val, p);
3104 return val;
3109 /***********************************************************************
3110 Symbol Allocation
3111 ***********************************************************************/
3113 /* Like struct Lisp_Symbol, but padded so that the size is a multiple
3114 of the required alignment if LSB tags are used. */
3116 union aligned_Lisp_Symbol
3118 struct Lisp_Symbol s;
3119 #if USE_LSB_TAG
3120 unsigned char c[(sizeof (struct Lisp_Symbol) + GCALIGNMENT - 1)
3121 & -GCALIGNMENT];
3122 #endif
3125 /* Each symbol_block is just under 1020 bytes long, since malloc
3126 really allocates in units of powers of two and uses 4 bytes for its
3127 own overhead. */
3129 #define SYMBOL_BLOCK_SIZE \
3130 ((1020 - sizeof (struct symbol_block *)) / sizeof (union aligned_Lisp_Symbol))
3132 struct symbol_block
3134 /* Place `symbols' first, to preserve alignment. */
3135 union aligned_Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3136 struct symbol_block *next;
3139 /* Current symbol block and index of first unused Lisp_Symbol
3140 structure in it. */
3142 static struct symbol_block *symbol_block;
3143 static int symbol_block_index = SYMBOL_BLOCK_SIZE;
3145 /* List of free symbols. */
3147 static struct Lisp_Symbol *symbol_free_list;
3149 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3150 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3151 Its value and function definition are void, and its property list is nil. */)
3152 (Lisp_Object name)
3154 register Lisp_Object val;
3155 register struct Lisp_Symbol *p;
3157 CHECK_STRING (name);
3159 MALLOC_BLOCK_INPUT;
3161 if (symbol_free_list)
3163 XSETSYMBOL (val, symbol_free_list);
3164 symbol_free_list = symbol_free_list->next;
3166 else
3168 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3170 struct symbol_block *new
3171 = lisp_malloc (sizeof *new, MEM_TYPE_SYMBOL);
3172 new->next = symbol_block;
3173 symbol_block = new;
3174 symbol_block_index = 0;
3175 total_free_symbols += SYMBOL_BLOCK_SIZE;
3177 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index].s);
3178 symbol_block_index++;
3181 MALLOC_UNBLOCK_INPUT;
3183 p = XSYMBOL (val);
3184 set_symbol_name (val, name);
3185 set_symbol_plist (val, Qnil);
3186 p->redirect = SYMBOL_PLAINVAL;
3187 SET_SYMBOL_VAL (p, Qunbound);
3188 set_symbol_function (val, Qunbound);
3189 set_symbol_next (val, NULL);
3190 p->gcmarkbit = 0;
3191 p->interned = SYMBOL_UNINTERNED;
3192 p->constant = 0;
3193 p->declared_special = 0;
3194 consing_since_gc += sizeof (struct Lisp_Symbol);
3195 symbols_consed++;
3196 total_free_symbols--;
3197 return val;
3202 /***********************************************************************
3203 Marker (Misc) Allocation
3204 ***********************************************************************/
3206 /* Like union Lisp_Misc, but padded so that its size is a multiple of
3207 the required alignment when LSB tags are used. */
3209 union aligned_Lisp_Misc
3211 union Lisp_Misc m;
3212 #if USE_LSB_TAG
3213 unsigned char c[(sizeof (union Lisp_Misc) + GCALIGNMENT - 1)
3214 & -GCALIGNMENT];
3215 #endif
3218 /* Allocation of markers and other objects that share that structure.
3219 Works like allocation of conses. */
3221 #define MARKER_BLOCK_SIZE \
3222 ((1020 - sizeof (struct marker_block *)) / sizeof (union aligned_Lisp_Misc))
3224 struct marker_block
3226 /* Place `markers' first, to preserve alignment. */
3227 union aligned_Lisp_Misc markers[MARKER_BLOCK_SIZE];
3228 struct marker_block *next;
3231 static struct marker_block *marker_block;
3232 static int marker_block_index = MARKER_BLOCK_SIZE;
3234 static union Lisp_Misc *marker_free_list;
3236 /* Return a newly allocated Lisp_Misc object of specified TYPE. */
3238 static Lisp_Object
3239 allocate_misc (enum Lisp_Misc_Type type)
3241 Lisp_Object val;
3243 MALLOC_BLOCK_INPUT;
3245 if (marker_free_list)
3247 XSETMISC (val, marker_free_list);
3248 marker_free_list = marker_free_list->u_free.chain;
3250 else
3252 if (marker_block_index == MARKER_BLOCK_SIZE)
3254 struct marker_block *new = lisp_malloc (sizeof *new, MEM_TYPE_MISC);
3255 new->next = marker_block;
3256 marker_block = new;
3257 marker_block_index = 0;
3258 total_free_markers += MARKER_BLOCK_SIZE;
3260 XSETMISC (val, &marker_block->markers[marker_block_index].m);
3261 marker_block_index++;
3264 MALLOC_UNBLOCK_INPUT;
3266 --total_free_markers;
3267 consing_since_gc += sizeof (union Lisp_Misc);
3268 misc_objects_consed++;
3269 XMISCTYPE (val) = type;
3270 XMISCANY (val)->gcmarkbit = 0;
3271 return val;
3274 /* Free a Lisp_Misc object */
3276 static void
3277 free_misc (Lisp_Object misc)
3279 XMISCTYPE (misc) = Lisp_Misc_Free;
3280 XMISC (misc)->u_free.chain = marker_free_list;
3281 marker_free_list = XMISC (misc);
3282 consing_since_gc -= sizeof (union Lisp_Misc);
3283 total_free_markers++;
3286 /* Return a Lisp_Misc_Save_Value object containing POINTER and
3287 INTEGER. This is used to package C values to call record_unwind_protect.
3288 The unwind function can get the C values back using XSAVE_VALUE. */
3290 Lisp_Object
3291 make_save_value (void *pointer, ptrdiff_t integer)
3293 register Lisp_Object val;
3294 register struct Lisp_Save_Value *p;
3296 val = allocate_misc (Lisp_Misc_Save_Value);
3297 p = XSAVE_VALUE (val);
3298 p->pointer = pointer;
3299 p->integer = integer;
3300 p->dogc = 0;
3301 return val;
3304 /* Return a Lisp_Misc_Overlay object with specified START, END and PLIST. */
3306 Lisp_Object
3307 build_overlay (Lisp_Object start, Lisp_Object end, Lisp_Object plist)
3309 register Lisp_Object overlay;
3311 overlay = allocate_misc (Lisp_Misc_Overlay);
3312 OVERLAY_START (overlay) = start;
3313 OVERLAY_END (overlay) = end;
3314 set_overlay_plist (overlay, plist);
3315 XOVERLAY (overlay)->next = NULL;
3316 return overlay;
3319 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3320 doc: /* Return a newly allocated marker which does not point at any place. */)
3321 (void)
3323 register Lisp_Object val;
3324 register struct Lisp_Marker *p;
3326 val = allocate_misc (Lisp_Misc_Marker);
3327 p = XMARKER (val);
3328 p->buffer = 0;
3329 p->bytepos = 0;
3330 p->charpos = 0;
3331 p->next = NULL;
3332 p->insertion_type = 0;
3333 return val;
3336 /* Return a newly allocated marker which points into BUF
3337 at character position CHARPOS and byte position BYTEPOS. */
3339 Lisp_Object
3340 build_marker (struct buffer *buf, ptrdiff_t charpos, ptrdiff_t bytepos)
3342 Lisp_Object obj;
3343 struct Lisp_Marker *m;
3345 /* No dead buffers here. */
3346 eassert (BUFFER_LIVE_P (buf));
3348 /* Every character is at least one byte. */
3349 eassert (charpos <= bytepos);
3351 obj = allocate_misc (Lisp_Misc_Marker);
3352 m = XMARKER (obj);
3353 m->buffer = buf;
3354 m->charpos = charpos;
3355 m->bytepos = bytepos;
3356 m->insertion_type = 0;
3357 m->next = BUF_MARKERS (buf);
3358 BUF_MARKERS (buf) = m;
3359 return obj;
3362 /* Put MARKER back on the free list after using it temporarily. */
3364 void
3365 free_marker (Lisp_Object marker)
3367 unchain_marker (XMARKER (marker));
3368 free_misc (marker);
3372 /* Return a newly created vector or string with specified arguments as
3373 elements. If all the arguments are characters that can fit
3374 in a string of events, make a string; otherwise, make a vector.
3376 Any number of arguments, even zero arguments, are allowed. */
3378 Lisp_Object
3379 make_event_array (register int nargs, Lisp_Object *args)
3381 int i;
3383 for (i = 0; i < nargs; i++)
3384 /* The things that fit in a string
3385 are characters that are in 0...127,
3386 after discarding the meta bit and all the bits above it. */
3387 if (!INTEGERP (args[i])
3388 || (XINT (args[i]) & ~(-CHAR_META)) >= 0200)
3389 return Fvector (nargs, args);
3391 /* Since the loop exited, we know that all the things in it are
3392 characters, so we can make a string. */
3394 Lisp_Object result;
3396 result = Fmake_string (make_number (nargs), make_number (0));
3397 for (i = 0; i < nargs; i++)
3399 SSET (result, i, XINT (args[i]));
3400 /* Move the meta bit to the right place for a string char. */
3401 if (XINT (args[i]) & CHAR_META)
3402 SSET (result, i, SREF (result, i) | 0x80);
3405 return result;
3411 /************************************************************************
3412 Memory Full Handling
3413 ************************************************************************/
3416 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
3417 there may have been size_t overflow so that malloc was never
3418 called, or perhaps malloc was invoked successfully but the
3419 resulting pointer had problems fitting into a tagged EMACS_INT. In
3420 either case this counts as memory being full even though malloc did
3421 not fail. */
3423 void
3424 memory_full (size_t nbytes)
3426 /* Do not go into hysterics merely because a large request failed. */
3427 bool enough_free_memory = 0;
3428 if (SPARE_MEMORY < nbytes)
3430 void *p;
3432 MALLOC_BLOCK_INPUT;
3433 p = malloc (SPARE_MEMORY);
3434 if (p)
3436 free (p);
3437 enough_free_memory = 1;
3439 MALLOC_UNBLOCK_INPUT;
3442 if (! enough_free_memory)
3444 int i;
3446 Vmemory_full = Qt;
3448 memory_full_cons_threshold = sizeof (struct cons_block);
3450 /* The first time we get here, free the spare memory. */
3451 for (i = 0; i < sizeof (spare_memory) / sizeof (char *); i++)
3452 if (spare_memory[i])
3454 if (i == 0)
3455 free (spare_memory[i]);
3456 else if (i >= 1 && i <= 4)
3457 lisp_align_free (spare_memory[i]);
3458 else
3459 lisp_free (spare_memory[i]);
3460 spare_memory[i] = 0;
3464 /* This used to call error, but if we've run out of memory, we could
3465 get infinite recursion trying to build the string. */
3466 xsignal (Qnil, Vmemory_signal_data);
3469 /* If we released our reserve (due to running out of memory),
3470 and we have a fair amount free once again,
3471 try to set aside another reserve in case we run out once more.
3473 This is called when a relocatable block is freed in ralloc.c,
3474 and also directly from this file, in case we're not using ralloc.c. */
3476 void
3477 refill_memory_reserve (void)
3479 #ifndef SYSTEM_MALLOC
3480 if (spare_memory[0] == 0)
3481 spare_memory[0] = malloc (SPARE_MEMORY);
3482 if (spare_memory[1] == 0)
3483 spare_memory[1] = lisp_align_malloc (sizeof (struct cons_block),
3484 MEM_TYPE_SPARE);
3485 if (spare_memory[2] == 0)
3486 spare_memory[2] = lisp_align_malloc (sizeof (struct cons_block),
3487 MEM_TYPE_SPARE);
3488 if (spare_memory[3] == 0)
3489 spare_memory[3] = lisp_align_malloc (sizeof (struct cons_block),
3490 MEM_TYPE_SPARE);
3491 if (spare_memory[4] == 0)
3492 spare_memory[4] = lisp_align_malloc (sizeof (struct cons_block),
3493 MEM_TYPE_SPARE);
3494 if (spare_memory[5] == 0)
3495 spare_memory[5] = lisp_malloc (sizeof (struct string_block),
3496 MEM_TYPE_SPARE);
3497 if (spare_memory[6] == 0)
3498 spare_memory[6] = lisp_malloc (sizeof (struct string_block),
3499 MEM_TYPE_SPARE);
3500 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
3501 Vmemory_full = Qnil;
3502 #endif
3505 /************************************************************************
3506 C Stack Marking
3507 ************************************************************************/
3509 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
3511 /* Conservative C stack marking requires a method to identify possibly
3512 live Lisp objects given a pointer value. We do this by keeping
3513 track of blocks of Lisp data that are allocated in a red-black tree
3514 (see also the comment of mem_node which is the type of nodes in
3515 that tree). Function lisp_malloc adds information for an allocated
3516 block to the red-black tree with calls to mem_insert, and function
3517 lisp_free removes it with mem_delete. Functions live_string_p etc
3518 call mem_find to lookup information about a given pointer in the
3519 tree, and use that to determine if the pointer points to a Lisp
3520 object or not. */
3522 /* Initialize this part of alloc.c. */
3524 static void
3525 mem_init (void)
3527 mem_z.left = mem_z.right = MEM_NIL;
3528 mem_z.parent = NULL;
3529 mem_z.color = MEM_BLACK;
3530 mem_z.start = mem_z.end = NULL;
3531 mem_root = MEM_NIL;
3535 /* Value is a pointer to the mem_node containing START. Value is
3536 MEM_NIL if there is no node in the tree containing START. */
3538 static inline struct mem_node *
3539 mem_find (void *start)
3541 struct mem_node *p;
3543 if (start < min_heap_address || start > max_heap_address)
3544 return MEM_NIL;
3546 /* Make the search always successful to speed up the loop below. */
3547 mem_z.start = start;
3548 mem_z.end = (char *) start + 1;
3550 p = mem_root;
3551 while (start < p->start || start >= p->end)
3552 p = start < p->start ? p->left : p->right;
3553 return p;
3557 /* Insert a new node into the tree for a block of memory with start
3558 address START, end address END, and type TYPE. Value is a
3559 pointer to the node that was inserted. */
3561 static struct mem_node *
3562 mem_insert (void *start, void *end, enum mem_type type)
3564 struct mem_node *c, *parent, *x;
3566 if (min_heap_address == NULL || start < min_heap_address)
3567 min_heap_address = start;
3568 if (max_heap_address == NULL || end > max_heap_address)
3569 max_heap_address = end;
3571 /* See where in the tree a node for START belongs. In this
3572 particular application, it shouldn't happen that a node is already
3573 present. For debugging purposes, let's check that. */
3574 c = mem_root;
3575 parent = NULL;
3577 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
3579 while (c != MEM_NIL)
3581 if (start >= c->start && start < c->end)
3582 emacs_abort ();
3583 parent = c;
3584 c = start < c->start ? c->left : c->right;
3587 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3589 while (c != MEM_NIL)
3591 parent = c;
3592 c = start < c->start ? c->left : c->right;
3595 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3597 /* Create a new node. */
3598 #ifdef GC_MALLOC_CHECK
3599 x = malloc (sizeof *x);
3600 if (x == NULL)
3601 emacs_abort ();
3602 #else
3603 x = xmalloc (sizeof *x);
3604 #endif
3605 x->start = start;
3606 x->end = end;
3607 x->type = type;
3608 x->parent = parent;
3609 x->left = x->right = MEM_NIL;
3610 x->color = MEM_RED;
3612 /* Insert it as child of PARENT or install it as root. */
3613 if (parent)
3615 if (start < parent->start)
3616 parent->left = x;
3617 else
3618 parent->right = x;
3620 else
3621 mem_root = x;
3623 /* Re-establish red-black tree properties. */
3624 mem_insert_fixup (x);
3626 return x;
3630 /* Re-establish the red-black properties of the tree, and thereby
3631 balance the tree, after node X has been inserted; X is always red. */
3633 static void
3634 mem_insert_fixup (struct mem_node *x)
3636 while (x != mem_root && x->parent->color == MEM_RED)
3638 /* X is red and its parent is red. This is a violation of
3639 red-black tree property #3. */
3641 if (x->parent == x->parent->parent->left)
3643 /* We're on the left side of our grandparent, and Y is our
3644 "uncle". */
3645 struct mem_node *y = x->parent->parent->right;
3647 if (y->color == MEM_RED)
3649 /* Uncle and parent are red but should be black because
3650 X is red. Change the colors accordingly and proceed
3651 with the grandparent. */
3652 x->parent->color = MEM_BLACK;
3653 y->color = MEM_BLACK;
3654 x->parent->parent->color = MEM_RED;
3655 x = x->parent->parent;
3657 else
3659 /* Parent and uncle have different colors; parent is
3660 red, uncle is black. */
3661 if (x == x->parent->right)
3663 x = x->parent;
3664 mem_rotate_left (x);
3667 x->parent->color = MEM_BLACK;
3668 x->parent->parent->color = MEM_RED;
3669 mem_rotate_right (x->parent->parent);
3672 else
3674 /* This is the symmetrical case of above. */
3675 struct mem_node *y = x->parent->parent->left;
3677 if (y->color == MEM_RED)
3679 x->parent->color = MEM_BLACK;
3680 y->color = MEM_BLACK;
3681 x->parent->parent->color = MEM_RED;
3682 x = x->parent->parent;
3684 else
3686 if (x == x->parent->left)
3688 x = x->parent;
3689 mem_rotate_right (x);
3692 x->parent->color = MEM_BLACK;
3693 x->parent->parent->color = MEM_RED;
3694 mem_rotate_left (x->parent->parent);
3699 /* The root may have been changed to red due to the algorithm. Set
3700 it to black so that property #5 is satisfied. */
3701 mem_root->color = MEM_BLACK;
3705 /* (x) (y)
3706 / \ / \
3707 a (y) ===> (x) c
3708 / \ / \
3709 b c a b */
3711 static void
3712 mem_rotate_left (struct mem_node *x)
3714 struct mem_node *y;
3716 /* Turn y's left sub-tree into x's right sub-tree. */
3717 y = x->right;
3718 x->right = y->left;
3719 if (y->left != MEM_NIL)
3720 y->left->parent = x;
3722 /* Y's parent was x's parent. */
3723 if (y != MEM_NIL)
3724 y->parent = x->parent;
3726 /* Get the parent to point to y instead of x. */
3727 if (x->parent)
3729 if (x == x->parent->left)
3730 x->parent->left = y;
3731 else
3732 x->parent->right = y;
3734 else
3735 mem_root = y;
3737 /* Put x on y's left. */
3738 y->left = x;
3739 if (x != MEM_NIL)
3740 x->parent = y;
3744 /* (x) (Y)
3745 / \ / \
3746 (y) c ===> a (x)
3747 / \ / \
3748 a b b c */
3750 static void
3751 mem_rotate_right (struct mem_node *x)
3753 struct mem_node *y = x->left;
3755 x->left = y->right;
3756 if (y->right != MEM_NIL)
3757 y->right->parent = x;
3759 if (y != MEM_NIL)
3760 y->parent = x->parent;
3761 if (x->parent)
3763 if (x == x->parent->right)
3764 x->parent->right = y;
3765 else
3766 x->parent->left = y;
3768 else
3769 mem_root = y;
3771 y->right = x;
3772 if (x != MEM_NIL)
3773 x->parent = y;
3777 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
3779 static void
3780 mem_delete (struct mem_node *z)
3782 struct mem_node *x, *y;
3784 if (!z || z == MEM_NIL)
3785 return;
3787 if (z->left == MEM_NIL || z->right == MEM_NIL)
3788 y = z;
3789 else
3791 y = z->right;
3792 while (y->left != MEM_NIL)
3793 y = y->left;
3796 if (y->left != MEM_NIL)
3797 x = y->left;
3798 else
3799 x = y->right;
3801 x->parent = y->parent;
3802 if (y->parent)
3804 if (y == y->parent->left)
3805 y->parent->left = x;
3806 else
3807 y->parent->right = x;
3809 else
3810 mem_root = x;
3812 if (y != z)
3814 z->start = y->start;
3815 z->end = y->end;
3816 z->type = y->type;
3819 if (y->color == MEM_BLACK)
3820 mem_delete_fixup (x);
3822 #ifdef GC_MALLOC_CHECK
3823 free (y);
3824 #else
3825 xfree (y);
3826 #endif
3830 /* Re-establish the red-black properties of the tree, after a
3831 deletion. */
3833 static void
3834 mem_delete_fixup (struct mem_node *x)
3836 while (x != mem_root && x->color == MEM_BLACK)
3838 if (x == x->parent->left)
3840 struct mem_node *w = x->parent->right;
3842 if (w->color == MEM_RED)
3844 w->color = MEM_BLACK;
3845 x->parent->color = MEM_RED;
3846 mem_rotate_left (x->parent);
3847 w = x->parent->right;
3850 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
3852 w->color = MEM_RED;
3853 x = x->parent;
3855 else
3857 if (w->right->color == MEM_BLACK)
3859 w->left->color = MEM_BLACK;
3860 w->color = MEM_RED;
3861 mem_rotate_right (w);
3862 w = x->parent->right;
3864 w->color = x->parent->color;
3865 x->parent->color = MEM_BLACK;
3866 w->right->color = MEM_BLACK;
3867 mem_rotate_left (x->parent);
3868 x = mem_root;
3871 else
3873 struct mem_node *w = x->parent->left;
3875 if (w->color == MEM_RED)
3877 w->color = MEM_BLACK;
3878 x->parent->color = MEM_RED;
3879 mem_rotate_right (x->parent);
3880 w = x->parent->left;
3883 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
3885 w->color = MEM_RED;
3886 x = x->parent;
3888 else
3890 if (w->left->color == MEM_BLACK)
3892 w->right->color = MEM_BLACK;
3893 w->color = MEM_RED;
3894 mem_rotate_left (w);
3895 w = x->parent->left;
3898 w->color = x->parent->color;
3899 x->parent->color = MEM_BLACK;
3900 w->left->color = MEM_BLACK;
3901 mem_rotate_right (x->parent);
3902 x = mem_root;
3907 x->color = MEM_BLACK;
3911 /* Value is non-zero if P is a pointer to a live Lisp string on
3912 the heap. M is a pointer to the mem_block for P. */
3914 static inline bool
3915 live_string_p (struct mem_node *m, void *p)
3917 if (m->type == MEM_TYPE_STRING)
3919 struct string_block *b = (struct string_block *) m->start;
3920 ptrdiff_t offset = (char *) p - (char *) &b->strings[0];
3922 /* P must point to the start of a Lisp_String structure, and it
3923 must not be on the free-list. */
3924 return (offset >= 0
3925 && offset % sizeof b->strings[0] == 0
3926 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
3927 && ((struct Lisp_String *) p)->data != NULL);
3929 else
3930 return 0;
3934 /* Value is non-zero if P is a pointer to a live Lisp cons on
3935 the heap. M is a pointer to the mem_block for P. */
3937 static inline bool
3938 live_cons_p (struct mem_node *m, void *p)
3940 if (m->type == MEM_TYPE_CONS)
3942 struct cons_block *b = (struct cons_block *) m->start;
3943 ptrdiff_t offset = (char *) p - (char *) &b->conses[0];
3945 /* P must point to the start of a Lisp_Cons, not be
3946 one of the unused cells in the current cons block,
3947 and not be on the free-list. */
3948 return (offset >= 0
3949 && offset % sizeof b->conses[0] == 0
3950 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
3951 && (b != cons_block
3952 || offset / sizeof b->conses[0] < cons_block_index)
3953 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
3955 else
3956 return 0;
3960 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3961 the heap. M is a pointer to the mem_block for P. */
3963 static inline bool
3964 live_symbol_p (struct mem_node *m, void *p)
3966 if (m->type == MEM_TYPE_SYMBOL)
3968 struct symbol_block *b = (struct symbol_block *) m->start;
3969 ptrdiff_t offset = (char *) p - (char *) &b->symbols[0];
3971 /* P must point to the start of a Lisp_Symbol, not be
3972 one of the unused cells in the current symbol block,
3973 and not be on the free-list. */
3974 return (offset >= 0
3975 && offset % sizeof b->symbols[0] == 0
3976 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
3977 && (b != symbol_block
3978 || offset / sizeof b->symbols[0] < symbol_block_index)
3979 && !EQ (((struct Lisp_Symbol *)p)->function, Vdead));
3981 else
3982 return 0;
3986 /* Value is non-zero if P is a pointer to a live Lisp float on
3987 the heap. M is a pointer to the mem_block for P. */
3989 static inline bool
3990 live_float_p (struct mem_node *m, void *p)
3992 if (m->type == MEM_TYPE_FLOAT)
3994 struct float_block *b = (struct float_block *) m->start;
3995 ptrdiff_t offset = (char *) p - (char *) &b->floats[0];
3997 /* P must point to the start of a Lisp_Float and not be
3998 one of the unused cells in the current float block. */
3999 return (offset >= 0
4000 && offset % sizeof b->floats[0] == 0
4001 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
4002 && (b != float_block
4003 || offset / sizeof b->floats[0] < float_block_index));
4005 else
4006 return 0;
4010 /* Value is non-zero if P is a pointer to a live Lisp Misc on
4011 the heap. M is a pointer to the mem_block for P. */
4013 static inline bool
4014 live_misc_p (struct mem_node *m, void *p)
4016 if (m->type == MEM_TYPE_MISC)
4018 struct marker_block *b = (struct marker_block *) m->start;
4019 ptrdiff_t offset = (char *) p - (char *) &b->markers[0];
4021 /* P must point to the start of a Lisp_Misc, not be
4022 one of the unused cells in the current misc block,
4023 and not be on the free-list. */
4024 return (offset >= 0
4025 && offset % sizeof b->markers[0] == 0
4026 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
4027 && (b != marker_block
4028 || offset / sizeof b->markers[0] < marker_block_index)
4029 && ((union Lisp_Misc *) p)->u_any.type != Lisp_Misc_Free);
4031 else
4032 return 0;
4036 /* Value is non-zero if P is a pointer to a live vector-like object.
4037 M is a pointer to the mem_block for P. */
4039 static inline bool
4040 live_vector_p (struct mem_node *m, void *p)
4042 if (m->type == MEM_TYPE_VECTOR_BLOCK)
4044 /* This memory node corresponds to a vector block. */
4045 struct vector_block *block = (struct vector_block *) m->start;
4046 struct Lisp_Vector *vector = (struct Lisp_Vector *) block->data;
4048 /* P is in the block's allocation range. Scan the block
4049 up to P and see whether P points to the start of some
4050 vector which is not on a free list. FIXME: check whether
4051 some allocation patterns (probably a lot of short vectors)
4052 may cause a substantial overhead of this loop. */
4053 while (VECTOR_IN_BLOCK (vector, block)
4054 && vector <= (struct Lisp_Vector *) p)
4056 if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FREE))
4057 vector = ADVANCE (vector, (vector->header.size
4058 & PSEUDOVECTOR_SIZE_MASK));
4059 else if (vector == p)
4060 return 1;
4061 else
4062 vector = ADVANCE (vector, vector->header.next.nbytes);
4065 else if (m->type == MEM_TYPE_VECTORLIKE && p == m->start)
4066 /* This memory node corresponds to a large vector. */
4067 return 1;
4068 return 0;
4072 /* Value is non-zero if P is a pointer to a live buffer. M is a
4073 pointer to the mem_block for P. */
4075 static inline bool
4076 live_buffer_p (struct mem_node *m, void *p)
4078 /* P must point to the start of the block, and the buffer
4079 must not have been killed. */
4080 return (m->type == MEM_TYPE_BUFFER
4081 && p == m->start
4082 && !NILP (((struct buffer *) p)->INTERNAL_FIELD (name)));
4085 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
4087 #if GC_MARK_STACK
4089 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4091 /* Array of objects that are kept alive because the C stack contains
4092 a pattern that looks like a reference to them . */
4094 #define MAX_ZOMBIES 10
4095 static Lisp_Object zombies[MAX_ZOMBIES];
4097 /* Number of zombie objects. */
4099 static EMACS_INT nzombies;
4101 /* Number of garbage collections. */
4103 static EMACS_INT ngcs;
4105 /* Average percentage of zombies per collection. */
4107 static double avg_zombies;
4109 /* Max. number of live and zombie objects. */
4111 static EMACS_INT max_live, max_zombies;
4113 /* Average number of live objects per GC. */
4115 static double avg_live;
4117 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
4118 doc: /* Show information about live and zombie objects. */)
4119 (void)
4121 Lisp_Object args[8], zombie_list = Qnil;
4122 EMACS_INT i;
4123 for (i = 0; i < min (MAX_ZOMBIES, nzombies); i++)
4124 zombie_list = Fcons (zombies[i], zombie_list);
4125 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
4126 args[1] = make_number (ngcs);
4127 args[2] = make_float (avg_live);
4128 args[3] = make_float (avg_zombies);
4129 args[4] = make_float (avg_zombies / avg_live / 100);
4130 args[5] = make_number (max_live);
4131 args[6] = make_number (max_zombies);
4132 args[7] = zombie_list;
4133 return Fmessage (8, args);
4136 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4139 /* Mark OBJ if we can prove it's a Lisp_Object. */
4141 static inline void
4142 mark_maybe_object (Lisp_Object obj)
4144 void *po;
4145 struct mem_node *m;
4147 if (INTEGERP (obj))
4148 return;
4150 po = (void *) XPNTR (obj);
4151 m = mem_find (po);
4153 if (m != MEM_NIL)
4155 bool mark_p = 0;
4157 switch (XTYPE (obj))
4159 case Lisp_String:
4160 mark_p = (live_string_p (m, po)
4161 && !STRING_MARKED_P ((struct Lisp_String *) po));
4162 break;
4164 case Lisp_Cons:
4165 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4166 break;
4168 case Lisp_Symbol:
4169 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4170 break;
4172 case Lisp_Float:
4173 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4174 break;
4176 case Lisp_Vectorlike:
4177 /* Note: can't check BUFFERP before we know it's a
4178 buffer because checking that dereferences the pointer
4179 PO which might point anywhere. */
4180 if (live_vector_p (m, po))
4181 mark_p = !SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4182 else if (live_buffer_p (m, po))
4183 mark_p = BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4184 break;
4186 case Lisp_Misc:
4187 mark_p = (live_misc_p (m, po) && !XMISCANY (obj)->gcmarkbit);
4188 break;
4190 default:
4191 break;
4194 if (mark_p)
4196 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4197 if (nzombies < MAX_ZOMBIES)
4198 zombies[nzombies] = obj;
4199 ++nzombies;
4200 #endif
4201 mark_object (obj);
4207 /* If P points to Lisp data, mark that as live if it isn't already
4208 marked. */
4210 static inline void
4211 mark_maybe_pointer (void *p)
4213 struct mem_node *m;
4215 /* Quickly rule out some values which can't point to Lisp data.
4216 USE_LSB_TAG needs Lisp data to be aligned on multiples of GCALIGNMENT.
4217 Otherwise, assume that Lisp data is aligned on even addresses. */
4218 if ((intptr_t) p % (USE_LSB_TAG ? GCALIGNMENT : 2))
4219 return;
4221 m = mem_find (p);
4222 if (m != MEM_NIL)
4224 Lisp_Object obj = Qnil;
4226 switch (m->type)
4228 case MEM_TYPE_NON_LISP:
4229 case MEM_TYPE_SPARE:
4230 /* Nothing to do; not a pointer to Lisp memory. */
4231 break;
4233 case MEM_TYPE_BUFFER:
4234 if (live_buffer_p (m, p) && !VECTOR_MARKED_P ((struct buffer *)p))
4235 XSETVECTOR (obj, p);
4236 break;
4238 case MEM_TYPE_CONS:
4239 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4240 XSETCONS (obj, p);
4241 break;
4243 case MEM_TYPE_STRING:
4244 if (live_string_p (m, p)
4245 && !STRING_MARKED_P ((struct Lisp_String *) p))
4246 XSETSTRING (obj, p);
4247 break;
4249 case MEM_TYPE_MISC:
4250 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4251 XSETMISC (obj, p);
4252 break;
4254 case MEM_TYPE_SYMBOL:
4255 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4256 XSETSYMBOL (obj, p);
4257 break;
4259 case MEM_TYPE_FLOAT:
4260 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4261 XSETFLOAT (obj, p);
4262 break;
4264 case MEM_TYPE_VECTORLIKE:
4265 case MEM_TYPE_VECTOR_BLOCK:
4266 if (live_vector_p (m, p))
4268 Lisp_Object tem;
4269 XSETVECTOR (tem, p);
4270 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4271 obj = tem;
4273 break;
4275 default:
4276 emacs_abort ();
4279 if (!NILP (obj))
4280 mark_object (obj);
4285 /* Alignment of pointer values. Use alignof, as it sometimes returns
4286 a smaller alignment than GCC's __alignof__ and mark_memory might
4287 miss objects if __alignof__ were used. */
4288 #define GC_POINTER_ALIGNMENT alignof (void *)
4290 /* Define POINTERS_MIGHT_HIDE_IN_OBJECTS to 1 if marking via C pointers does
4291 not suffice, which is the typical case. A host where a Lisp_Object is
4292 wider than a pointer might allocate a Lisp_Object in non-adjacent halves.
4293 If USE_LSB_TAG, the bottom half is not a valid pointer, but it should
4294 suffice to widen it to to a Lisp_Object and check it that way. */
4295 #if USE_LSB_TAG || VAL_MAX < UINTPTR_MAX
4296 # if !USE_LSB_TAG && VAL_MAX < UINTPTR_MAX >> GCTYPEBITS
4297 /* If tag bits straddle pointer-word boundaries, neither mark_maybe_pointer
4298 nor mark_maybe_object can follow the pointers. This should not occur on
4299 any practical porting target. */
4300 # error "MSB type bits straddle pointer-word boundaries"
4301 # endif
4302 /* Marking via C pointers does not suffice, because Lisp_Objects contain
4303 pointer words that hold pointers ORed with type bits. */
4304 # define POINTERS_MIGHT_HIDE_IN_OBJECTS 1
4305 #else
4306 /* Marking via C pointers suffices, because Lisp_Objects contain pointer
4307 words that hold unmodified pointers. */
4308 # define POINTERS_MIGHT_HIDE_IN_OBJECTS 0
4309 #endif
4311 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4312 or END+OFFSET..START. */
4314 static void
4315 mark_memory (void *start, void *end)
4316 #if defined (__clang__) && defined (__has_feature)
4317 #if __has_feature(address_sanitizer)
4318 /* Do not allow -faddress-sanitizer to check this function, since it
4319 crosses the function stack boundary, and thus would yield many
4320 false positives. */
4321 __attribute__((no_address_safety_analysis))
4322 #endif
4323 #endif
4325 void **pp;
4326 int i;
4328 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4329 nzombies = 0;
4330 #endif
4332 /* Make START the pointer to the start of the memory region,
4333 if it isn't already. */
4334 if (end < start)
4336 void *tem = start;
4337 start = end;
4338 end = tem;
4341 /* Mark Lisp data pointed to. This is necessary because, in some
4342 situations, the C compiler optimizes Lisp objects away, so that
4343 only a pointer to them remains. Example:
4345 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4348 Lisp_Object obj = build_string ("test");
4349 struct Lisp_String *s = XSTRING (obj);
4350 Fgarbage_collect ();
4351 fprintf (stderr, "test `%s'\n", s->data);
4352 return Qnil;
4355 Here, `obj' isn't really used, and the compiler optimizes it
4356 away. The only reference to the life string is through the
4357 pointer `s'. */
4359 for (pp = start; (void *) pp < end; pp++)
4360 for (i = 0; i < sizeof *pp; i += GC_POINTER_ALIGNMENT)
4362 void *p = *(void **) ((char *) pp + i);
4363 mark_maybe_pointer (p);
4364 if (POINTERS_MIGHT_HIDE_IN_OBJECTS)
4365 mark_maybe_object (XIL ((intptr_t) p));
4369 /* setjmp will work with GCC unless NON_SAVING_SETJMP is defined in
4370 the GCC system configuration. In gcc 3.2, the only systems for
4371 which this is so are i386-sco5 non-ELF, i386-sysv3 (maybe included
4372 by others?) and ns32k-pc532-min. */
4374 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4376 static bool setjmp_tested_p;
4377 static int longjmps_done;
4379 #define SETJMP_WILL_LIKELY_WORK "\
4381 Emacs garbage collector has been changed to use conservative stack\n\
4382 marking. Emacs has determined that the method it uses to do the\n\
4383 marking will likely work on your system, but this isn't sure.\n\
4385 If you are a system-programmer, or can get the help of a local wizard\n\
4386 who is, please take a look at the function mark_stack in alloc.c, and\n\
4387 verify that the methods used are appropriate for your system.\n\
4389 Please mail the result to <emacs-devel@gnu.org>.\n\
4392 #define SETJMP_WILL_NOT_WORK "\
4394 Emacs garbage collector has been changed to use conservative stack\n\
4395 marking. Emacs has determined that the default method it uses to do the\n\
4396 marking will not work on your system. We will need a system-dependent\n\
4397 solution for your system.\n\
4399 Please take a look at the function mark_stack in alloc.c, and\n\
4400 try to find a way to make it work on your system.\n\
4402 Note that you may get false negatives, depending on the compiler.\n\
4403 In particular, you need to use -O with GCC for this test.\n\
4405 Please mail the result to <emacs-devel@gnu.org>.\n\
4409 /* Perform a quick check if it looks like setjmp saves registers in a
4410 jmp_buf. Print a message to stderr saying so. When this test
4411 succeeds, this is _not_ a proof that setjmp is sufficient for
4412 conservative stack marking. Only the sources or a disassembly
4413 can prove that. */
4415 static void
4416 test_setjmp (void)
4418 char buf[10];
4419 register int x;
4420 sys_jmp_buf jbuf;
4422 /* Arrange for X to be put in a register. */
4423 sprintf (buf, "1");
4424 x = strlen (buf);
4425 x = 2 * x - 1;
4427 sys_setjmp (jbuf);
4428 if (longjmps_done == 1)
4430 /* Came here after the longjmp at the end of the function.
4432 If x == 1, the longjmp has restored the register to its
4433 value before the setjmp, and we can hope that setjmp
4434 saves all such registers in the jmp_buf, although that
4435 isn't sure.
4437 For other values of X, either something really strange is
4438 taking place, or the setjmp just didn't save the register. */
4440 if (x == 1)
4441 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4442 else
4444 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4445 exit (1);
4449 ++longjmps_done;
4450 x = 2;
4451 if (longjmps_done == 1)
4452 sys_longjmp (jbuf, 1);
4455 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4458 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4460 /* Abort if anything GCPRO'd doesn't survive the GC. */
4462 static void
4463 check_gcpros (void)
4465 struct gcpro *p;
4466 ptrdiff_t i;
4468 for (p = gcprolist; p; p = p->next)
4469 for (i = 0; i < p->nvars; ++i)
4470 if (!survives_gc_p (p->var[i]))
4471 /* FIXME: It's not necessarily a bug. It might just be that the
4472 GCPRO is unnecessary or should release the object sooner. */
4473 emacs_abort ();
4476 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4478 static void
4479 dump_zombies (void)
4481 int i;
4483 fprintf (stderr, "\nZombies kept alive = %"pI"d:\n", nzombies);
4484 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
4486 fprintf (stderr, " %d = ", i);
4487 debug_print (zombies[i]);
4491 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4494 /* Mark live Lisp objects on the C stack.
4496 There are several system-dependent problems to consider when
4497 porting this to new architectures:
4499 Processor Registers
4501 We have to mark Lisp objects in CPU registers that can hold local
4502 variables or are used to pass parameters.
4504 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4505 something that either saves relevant registers on the stack, or
4506 calls mark_maybe_object passing it each register's contents.
4508 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4509 implementation assumes that calling setjmp saves registers we need
4510 to see in a jmp_buf which itself lies on the stack. This doesn't
4511 have to be true! It must be verified for each system, possibly
4512 by taking a look at the source code of setjmp.
4514 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4515 can use it as a machine independent method to store all registers
4516 to the stack. In this case the macros described in the previous
4517 two paragraphs are not used.
4519 Stack Layout
4521 Architectures differ in the way their processor stack is organized.
4522 For example, the stack might look like this
4524 +----------------+
4525 | Lisp_Object | size = 4
4526 +----------------+
4527 | something else | size = 2
4528 +----------------+
4529 | Lisp_Object | size = 4
4530 +----------------+
4531 | ... |
4533 In such a case, not every Lisp_Object will be aligned equally. To
4534 find all Lisp_Object on the stack it won't be sufficient to walk
4535 the stack in steps of 4 bytes. Instead, two passes will be
4536 necessary, one starting at the start of the stack, and a second
4537 pass starting at the start of the stack + 2. Likewise, if the
4538 minimal alignment of Lisp_Objects on the stack is 1, four passes
4539 would be necessary, each one starting with one byte more offset
4540 from the stack start. */
4542 static void
4543 mark_stack (void)
4545 void *end;
4547 #ifdef HAVE___BUILTIN_UNWIND_INIT
4548 /* Force callee-saved registers and register windows onto the stack.
4549 This is the preferred method if available, obviating the need for
4550 machine dependent methods. */
4551 __builtin_unwind_init ();
4552 end = &end;
4553 #else /* not HAVE___BUILTIN_UNWIND_INIT */
4554 #ifndef GC_SAVE_REGISTERS_ON_STACK
4555 /* jmp_buf may not be aligned enough on darwin-ppc64 */
4556 union aligned_jmpbuf {
4557 Lisp_Object o;
4558 sys_jmp_buf j;
4559 } j;
4560 volatile bool stack_grows_down_p = (char *) &j > (char *) stack_base;
4561 #endif
4562 /* This trick flushes the register windows so that all the state of
4563 the process is contained in the stack. */
4564 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
4565 needed on ia64 too. See mach_dep.c, where it also says inline
4566 assembler doesn't work with relevant proprietary compilers. */
4567 #ifdef __sparc__
4568 #if defined (__sparc64__) && defined (__FreeBSD__)
4569 /* FreeBSD does not have a ta 3 handler. */
4570 asm ("flushw");
4571 #else
4572 asm ("ta 3");
4573 #endif
4574 #endif
4576 /* Save registers that we need to see on the stack. We need to see
4577 registers used to hold register variables and registers used to
4578 pass parameters. */
4579 #ifdef GC_SAVE_REGISTERS_ON_STACK
4580 GC_SAVE_REGISTERS_ON_STACK (end);
4581 #else /* not GC_SAVE_REGISTERS_ON_STACK */
4583 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
4584 setjmp will definitely work, test it
4585 and print a message with the result
4586 of the test. */
4587 if (!setjmp_tested_p)
4589 setjmp_tested_p = 1;
4590 test_setjmp ();
4592 #endif /* GC_SETJMP_WORKS */
4594 sys_setjmp (j.j);
4595 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
4596 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
4597 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
4599 /* This assumes that the stack is a contiguous region in memory. If
4600 that's not the case, something has to be done here to iterate
4601 over the stack segments. */
4602 mark_memory (stack_base, end);
4604 /* Allow for marking a secondary stack, like the register stack on the
4605 ia64. */
4606 #ifdef GC_MARK_SECONDARY_STACK
4607 GC_MARK_SECONDARY_STACK ();
4608 #endif
4610 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4611 check_gcpros ();
4612 #endif
4615 #endif /* GC_MARK_STACK != 0 */
4618 /* Determine whether it is safe to access memory at address P. */
4619 static int
4620 valid_pointer_p (void *p)
4622 #ifdef WINDOWSNT
4623 return w32_valid_pointer_p (p, 16);
4624 #else
4625 int fd[2];
4627 /* Obviously, we cannot just access it (we would SEGV trying), so we
4628 trick the o/s to tell us whether p is a valid pointer.
4629 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4630 not validate p in that case. */
4632 if (pipe (fd) == 0)
4634 bool valid = emacs_write (fd[1], (char *) p, 16) == 16;
4635 emacs_close (fd[1]);
4636 emacs_close (fd[0]);
4637 return valid;
4640 return -1;
4641 #endif
4644 /* Return 2 if OBJ is a killed or special buffer object.
4645 Return 1 if OBJ is a valid lisp object.
4646 Return 0 if OBJ is NOT a valid lisp object.
4647 Return -1 if we cannot validate OBJ.
4648 This function can be quite slow,
4649 so it should only be used in code for manual debugging. */
4652 valid_lisp_object_p (Lisp_Object obj)
4654 void *p;
4655 #if GC_MARK_STACK
4656 struct mem_node *m;
4657 #endif
4659 if (INTEGERP (obj))
4660 return 1;
4662 p = (void *) XPNTR (obj);
4663 if (PURE_POINTER_P (p))
4664 return 1;
4666 if (p == &buffer_defaults || p == &buffer_local_symbols)
4667 return 2;
4669 #if !GC_MARK_STACK
4670 return valid_pointer_p (p);
4671 #else
4673 m = mem_find (p);
4675 if (m == MEM_NIL)
4677 int valid = valid_pointer_p (p);
4678 if (valid <= 0)
4679 return valid;
4681 if (SUBRP (obj))
4682 return 1;
4684 return 0;
4687 switch (m->type)
4689 case MEM_TYPE_NON_LISP:
4690 case MEM_TYPE_SPARE:
4691 return 0;
4693 case MEM_TYPE_BUFFER:
4694 return live_buffer_p (m, p) ? 1 : 2;
4696 case MEM_TYPE_CONS:
4697 return live_cons_p (m, p);
4699 case MEM_TYPE_STRING:
4700 return live_string_p (m, p);
4702 case MEM_TYPE_MISC:
4703 return live_misc_p (m, p);
4705 case MEM_TYPE_SYMBOL:
4706 return live_symbol_p (m, p);
4708 case MEM_TYPE_FLOAT:
4709 return live_float_p (m, p);
4711 case MEM_TYPE_VECTORLIKE:
4712 case MEM_TYPE_VECTOR_BLOCK:
4713 return live_vector_p (m, p);
4715 default:
4716 break;
4719 return 0;
4720 #endif
4726 /***********************************************************************
4727 Pure Storage Management
4728 ***********************************************************************/
4730 /* Allocate room for SIZE bytes from pure Lisp storage and return a
4731 pointer to it. TYPE is the Lisp type for which the memory is
4732 allocated. TYPE < 0 means it's not used for a Lisp object. */
4734 static void *
4735 pure_alloc (size_t size, int type)
4737 void *result;
4738 #if USE_LSB_TAG
4739 size_t alignment = GCALIGNMENT;
4740 #else
4741 size_t alignment = alignof (EMACS_INT);
4743 /* Give Lisp_Floats an extra alignment. */
4744 if (type == Lisp_Float)
4745 alignment = alignof (struct Lisp_Float);
4746 #endif
4748 again:
4749 if (type >= 0)
4751 /* Allocate space for a Lisp object from the beginning of the free
4752 space with taking account of alignment. */
4753 result = ALIGN (purebeg + pure_bytes_used_lisp, alignment);
4754 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
4756 else
4758 /* Allocate space for a non-Lisp object from the end of the free
4759 space. */
4760 pure_bytes_used_non_lisp += size;
4761 result = purebeg + pure_size - pure_bytes_used_non_lisp;
4763 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
4765 if (pure_bytes_used <= pure_size)
4766 return result;
4768 /* Don't allocate a large amount here,
4769 because it might get mmap'd and then its address
4770 might not be usable. */
4771 purebeg = xmalloc (10000);
4772 pure_size = 10000;
4773 pure_bytes_used_before_overflow += pure_bytes_used - size;
4774 pure_bytes_used = 0;
4775 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
4776 goto again;
4780 /* Print a warning if PURESIZE is too small. */
4782 void
4783 check_pure_size (void)
4785 if (pure_bytes_used_before_overflow)
4786 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI"d"
4787 " bytes needed)"),
4788 pure_bytes_used + pure_bytes_used_before_overflow);
4792 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
4793 the non-Lisp data pool of the pure storage, and return its start
4794 address. Return NULL if not found. */
4796 static char *
4797 find_string_data_in_pure (const char *data, ptrdiff_t nbytes)
4799 int i;
4800 ptrdiff_t skip, bm_skip[256], last_char_skip, infinity, start, start_max;
4801 const unsigned char *p;
4802 char *non_lisp_beg;
4804 if (pure_bytes_used_non_lisp <= nbytes)
4805 return NULL;
4807 /* Set up the Boyer-Moore table. */
4808 skip = nbytes + 1;
4809 for (i = 0; i < 256; i++)
4810 bm_skip[i] = skip;
4812 p = (const unsigned char *) data;
4813 while (--skip > 0)
4814 bm_skip[*p++] = skip;
4816 last_char_skip = bm_skip['\0'];
4818 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
4819 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
4821 /* See the comments in the function `boyer_moore' (search.c) for the
4822 use of `infinity'. */
4823 infinity = pure_bytes_used_non_lisp + 1;
4824 bm_skip['\0'] = infinity;
4826 p = (const unsigned char *) non_lisp_beg + nbytes;
4827 start = 0;
4830 /* Check the last character (== '\0'). */
4833 start += bm_skip[*(p + start)];
4835 while (start <= start_max);
4837 if (start < infinity)
4838 /* Couldn't find the last character. */
4839 return NULL;
4841 /* No less than `infinity' means we could find the last
4842 character at `p[start - infinity]'. */
4843 start -= infinity;
4845 /* Check the remaining characters. */
4846 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
4847 /* Found. */
4848 return non_lisp_beg + start;
4850 start += last_char_skip;
4852 while (start <= start_max);
4854 return NULL;
4858 /* Return a string allocated in pure space. DATA is a buffer holding
4859 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
4860 means make the result string multibyte.
4862 Must get an error if pure storage is full, since if it cannot hold
4863 a large string it may be able to hold conses that point to that
4864 string; then the string is not protected from gc. */
4866 Lisp_Object
4867 make_pure_string (const char *data,
4868 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
4870 Lisp_Object string;
4871 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
4872 s->data = (unsigned char *) find_string_data_in_pure (data, nbytes);
4873 if (s->data == NULL)
4875 s->data = pure_alloc (nbytes + 1, -1);
4876 memcpy (s->data, data, nbytes);
4877 s->data[nbytes] = '\0';
4879 s->size = nchars;
4880 s->size_byte = multibyte ? nbytes : -1;
4881 s->intervals = NULL;
4882 XSETSTRING (string, s);
4883 return string;
4886 /* Return a string allocated in pure space. Do not
4887 allocate the string data, just point to DATA. */
4889 Lisp_Object
4890 make_pure_c_string (const char *data, ptrdiff_t nchars)
4892 Lisp_Object string;
4893 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
4894 s->size = nchars;
4895 s->size_byte = -1;
4896 s->data = (unsigned char *) data;
4897 s->intervals = NULL;
4898 XSETSTRING (string, s);
4899 return string;
4902 /* Return a cons allocated from pure space. Give it pure copies
4903 of CAR as car and CDR as cdr. */
4905 Lisp_Object
4906 pure_cons (Lisp_Object car, Lisp_Object cdr)
4908 Lisp_Object new;
4909 struct Lisp_Cons *p = pure_alloc (sizeof *p, Lisp_Cons);
4910 XSETCONS (new, p);
4911 XSETCAR (new, Fpurecopy (car));
4912 XSETCDR (new, Fpurecopy (cdr));
4913 return new;
4917 /* Value is a float object with value NUM allocated from pure space. */
4919 static Lisp_Object
4920 make_pure_float (double num)
4922 Lisp_Object new;
4923 struct Lisp_Float *p = pure_alloc (sizeof *p, Lisp_Float);
4924 XSETFLOAT (new, p);
4925 XFLOAT_INIT (new, num);
4926 return new;
4930 /* Return a vector with room for LEN Lisp_Objects allocated from
4931 pure space. */
4933 static Lisp_Object
4934 make_pure_vector (ptrdiff_t len)
4936 Lisp_Object new;
4937 size_t size = header_size + len * word_size;
4938 struct Lisp_Vector *p = pure_alloc (size, Lisp_Vectorlike);
4939 XSETVECTOR (new, p);
4940 XVECTOR (new)->header.size = len;
4941 return new;
4945 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
4946 doc: /* Make a copy of object OBJ in pure storage.
4947 Recursively copies contents of vectors and cons cells.
4948 Does not copy symbols. Copies strings without text properties. */)
4949 (register Lisp_Object obj)
4951 if (NILP (Vpurify_flag))
4952 return obj;
4954 if (PURE_POINTER_P (XPNTR (obj)))
4955 return obj;
4957 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
4959 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
4960 if (!NILP (tmp))
4961 return tmp;
4964 if (CONSP (obj))
4965 obj = pure_cons (XCAR (obj), XCDR (obj));
4966 else if (FLOATP (obj))
4967 obj = make_pure_float (XFLOAT_DATA (obj));
4968 else if (STRINGP (obj))
4969 obj = make_pure_string (SSDATA (obj), SCHARS (obj),
4970 SBYTES (obj),
4971 STRING_MULTIBYTE (obj));
4972 else if (COMPILEDP (obj) || VECTORP (obj))
4974 register struct Lisp_Vector *vec;
4975 register ptrdiff_t i;
4976 ptrdiff_t size;
4978 size = ASIZE (obj);
4979 if (size & PSEUDOVECTOR_FLAG)
4980 size &= PSEUDOVECTOR_SIZE_MASK;
4981 vec = XVECTOR (make_pure_vector (size));
4982 for (i = 0; i < size; i++)
4983 vec->contents[i] = Fpurecopy (AREF (obj, i));
4984 if (COMPILEDP (obj))
4986 XSETPVECTYPE (vec, PVEC_COMPILED);
4987 XSETCOMPILED (obj, vec);
4989 else
4990 XSETVECTOR (obj, vec);
4992 else if (MARKERP (obj))
4993 error ("Attempt to copy a marker to pure storage");
4994 else
4995 /* Not purified, don't hash-cons. */
4996 return obj;
4998 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
4999 Fputhash (obj, obj, Vpurify_flag);
5001 return obj;
5006 /***********************************************************************
5007 Protection from GC
5008 ***********************************************************************/
5010 /* Put an entry in staticvec, pointing at the variable with address
5011 VARADDRESS. */
5013 void
5014 staticpro (Lisp_Object *varaddress)
5016 staticvec[staticidx++] = varaddress;
5017 if (staticidx >= NSTATICS)
5018 emacs_abort ();
5022 /***********************************************************************
5023 Protection from GC
5024 ***********************************************************************/
5026 /* Temporarily prevent garbage collection. */
5028 ptrdiff_t
5029 inhibit_garbage_collection (void)
5031 ptrdiff_t count = SPECPDL_INDEX ();
5033 specbind (Qgc_cons_threshold, make_number (MOST_POSITIVE_FIXNUM));
5034 return count;
5037 /* Used to avoid possible overflows when
5038 converting from C to Lisp integers. */
5040 static inline Lisp_Object
5041 bounded_number (EMACS_INT number)
5043 return make_number (min (MOST_POSITIVE_FIXNUM, number));
5046 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
5047 doc: /* Reclaim storage for Lisp objects no longer needed.
5048 Garbage collection happens automatically if you cons more than
5049 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5050 `garbage-collect' normally returns a list with info on amount of space in use,
5051 where each entry has the form (NAME SIZE USED FREE), where:
5052 - NAME is a symbol describing the kind of objects this entry represents,
5053 - SIZE is the number of bytes used by each one,
5054 - USED is the number of those objects that were found live in the heap,
5055 - FREE is the number of those objects that are not live but that Emacs
5056 keeps around for future allocations (maybe because it does not know how
5057 to return them to the OS).
5058 However, if there was overflow in pure space, `garbage-collect'
5059 returns nil, because real GC can't be done.
5060 See Info node `(elisp)Garbage Collection'. */)
5061 (void)
5063 struct specbinding *bind;
5064 struct buffer *nextb;
5065 char stack_top_variable;
5066 ptrdiff_t i;
5067 bool message_p;
5068 ptrdiff_t count = SPECPDL_INDEX ();
5069 EMACS_TIME start;
5070 Lisp_Object retval = Qnil;
5072 if (abort_on_gc)
5073 emacs_abort ();
5075 /* Can't GC if pure storage overflowed because we can't determine
5076 if something is a pure object or not. */
5077 if (pure_bytes_used_before_overflow)
5078 return Qnil;
5080 check_cons_list ();
5082 /* Don't keep undo information around forever.
5083 Do this early on, so it is no problem if the user quits. */
5084 FOR_EACH_BUFFER (nextb)
5085 compact_buffer (nextb);
5087 start = current_emacs_time ();
5089 /* In case user calls debug_print during GC,
5090 don't let that cause a recursive GC. */
5091 consing_since_gc = 0;
5093 /* Save what's currently displayed in the echo area. */
5094 message_p = push_message ();
5095 record_unwind_protect (pop_message_unwind, Qnil);
5097 /* Save a copy of the contents of the stack, for debugging. */
5098 #if MAX_SAVE_STACK > 0
5099 if (NILP (Vpurify_flag))
5101 char *stack;
5102 ptrdiff_t stack_size;
5103 if (&stack_top_variable < stack_bottom)
5105 stack = &stack_top_variable;
5106 stack_size = stack_bottom - &stack_top_variable;
5108 else
5110 stack = stack_bottom;
5111 stack_size = &stack_top_variable - stack_bottom;
5113 if (stack_size <= MAX_SAVE_STACK)
5115 if (stack_copy_size < stack_size)
5117 stack_copy = xrealloc (stack_copy, stack_size);
5118 stack_copy_size = stack_size;
5120 memcpy (stack_copy, stack, stack_size);
5123 #endif /* MAX_SAVE_STACK > 0 */
5125 if (garbage_collection_messages)
5126 message1_nolog ("Garbage collecting...");
5128 BLOCK_INPUT;
5130 shrink_regexp_cache ();
5132 gc_in_progress = 1;
5134 /* Mark all the special slots that serve as the roots of accessibility. */
5136 mark_buffer (&buffer_defaults);
5137 mark_buffer (&buffer_local_symbols);
5139 for (i = 0; i < staticidx; i++)
5140 mark_object (*staticvec[i]);
5142 for (bind = specpdl; bind != specpdl_ptr; bind++)
5144 mark_object (bind->symbol);
5145 mark_object (bind->old_value);
5147 mark_terminals ();
5148 mark_kboards ();
5150 #ifdef USE_GTK
5151 xg_mark_data ();
5152 #endif
5154 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
5155 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
5156 mark_stack ();
5157 #else
5159 register struct gcpro *tail;
5160 for (tail = gcprolist; tail; tail = tail->next)
5161 for (i = 0; i < tail->nvars; i++)
5162 mark_object (tail->var[i]);
5164 mark_byte_stack ();
5166 struct catchtag *catch;
5167 struct handler *handler;
5169 for (catch = catchlist; catch; catch = catch->next)
5171 mark_object (catch->tag);
5172 mark_object (catch->val);
5174 for (handler = handlerlist; handler; handler = handler->next)
5176 mark_object (handler->handler);
5177 mark_object (handler->var);
5180 mark_backtrace ();
5181 #endif
5183 #ifdef HAVE_WINDOW_SYSTEM
5184 mark_fringe_data ();
5185 #endif
5187 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5188 mark_stack ();
5189 #endif
5191 /* Everything is now marked, except for the things that require special
5192 finalization, i.e. the undo_list.
5193 Look thru every buffer's undo list
5194 for elements that update markers that were not marked,
5195 and delete them. */
5196 FOR_EACH_BUFFER (nextb)
5198 /* If a buffer's undo list is Qt, that means that undo is
5199 turned off in that buffer. Calling truncate_undo_list on
5200 Qt tends to return NULL, which effectively turns undo back on.
5201 So don't call truncate_undo_list if undo_list is Qt. */
5202 if (! EQ (nextb->INTERNAL_FIELD (undo_list), Qt))
5204 Lisp_Object tail, prev;
5205 tail = nextb->INTERNAL_FIELD (undo_list);
5206 prev = Qnil;
5207 while (CONSP (tail))
5209 if (CONSP (XCAR (tail))
5210 && MARKERP (XCAR (XCAR (tail)))
5211 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5213 if (NILP (prev))
5214 nextb->INTERNAL_FIELD (undo_list) = tail = XCDR (tail);
5215 else
5217 tail = XCDR (tail);
5218 XSETCDR (prev, tail);
5221 else
5223 prev = tail;
5224 tail = XCDR (tail);
5228 /* Now that we have stripped the elements that need not be in the
5229 undo_list any more, we can finally mark the list. */
5230 mark_object (nextb->INTERNAL_FIELD (undo_list));
5233 gc_sweep ();
5235 /* Clear the mark bits that we set in certain root slots. */
5237 unmark_byte_stack ();
5238 VECTOR_UNMARK (&buffer_defaults);
5239 VECTOR_UNMARK (&buffer_local_symbols);
5241 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
5242 dump_zombies ();
5243 #endif
5245 UNBLOCK_INPUT;
5247 check_cons_list ();
5249 gc_in_progress = 0;
5251 consing_since_gc = 0;
5252 if (gc_cons_threshold < GC_DEFAULT_THRESHOLD / 10)
5253 gc_cons_threshold = GC_DEFAULT_THRESHOLD / 10;
5255 gc_relative_threshold = 0;
5256 if (FLOATP (Vgc_cons_percentage))
5257 { /* Set gc_cons_combined_threshold. */
5258 double tot = 0;
5260 tot += total_conses * sizeof (struct Lisp_Cons);
5261 tot += total_symbols * sizeof (struct Lisp_Symbol);
5262 tot += total_markers * sizeof (union Lisp_Misc);
5263 tot += total_string_bytes;
5264 tot += total_vector_slots * word_size;
5265 tot += total_floats * sizeof (struct Lisp_Float);
5266 tot += total_intervals * sizeof (struct interval);
5267 tot += total_strings * sizeof (struct Lisp_String);
5269 tot *= XFLOAT_DATA (Vgc_cons_percentage);
5270 if (0 < tot)
5272 if (tot < TYPE_MAXIMUM (EMACS_INT))
5273 gc_relative_threshold = tot;
5274 else
5275 gc_relative_threshold = TYPE_MAXIMUM (EMACS_INT);
5279 if (garbage_collection_messages)
5281 if (message_p || minibuf_level > 0)
5282 restore_message ();
5283 else
5284 message1_nolog ("Garbage collecting...done");
5287 unbind_to (count, Qnil);
5289 Lisp_Object total[11];
5290 int total_size = 10;
5292 total[0] = list4 (Qconses, make_number (sizeof (struct Lisp_Cons)),
5293 bounded_number (total_conses),
5294 bounded_number (total_free_conses));
5296 total[1] = list4 (Qsymbols, make_number (sizeof (struct Lisp_Symbol)),
5297 bounded_number (total_symbols),
5298 bounded_number (total_free_symbols));
5300 total[2] = list4 (Qmiscs, make_number (sizeof (union Lisp_Misc)),
5301 bounded_number (total_markers),
5302 bounded_number (total_free_markers));
5304 total[3] = list4 (Qstrings, make_number (sizeof (struct Lisp_String)),
5305 bounded_number (total_strings),
5306 bounded_number (total_free_strings));
5308 total[4] = list3 (Qstring_bytes, make_number (1),
5309 bounded_number (total_string_bytes));
5311 total[5] = list3 (Qvectors, make_number (sizeof (struct Lisp_Vector)),
5312 bounded_number (total_vectors));
5314 total[6] = list4 (Qvector_slots, make_number (word_size),
5315 bounded_number (total_vector_slots),
5316 bounded_number (total_free_vector_slots));
5318 total[7] = list4 (Qfloats, make_number (sizeof (struct Lisp_Float)),
5319 bounded_number (total_floats),
5320 bounded_number (total_free_floats));
5322 total[8] = list4 (Qintervals, make_number (sizeof (struct interval)),
5323 bounded_number (total_intervals),
5324 bounded_number (total_free_intervals));
5326 total[9] = list3 (Qbuffers, make_number (sizeof (struct buffer)),
5327 bounded_number (total_buffers));
5329 #ifdef DOUG_LEA_MALLOC
5330 total_size++;
5331 total[10] = list4 (Qheap, make_number (1024),
5332 bounded_number ((mallinfo ().uordblks + 1023) >> 10),
5333 bounded_number ((mallinfo ().fordblks + 1023) >> 10));
5334 #endif
5335 retval = Flist (total_size, total);
5338 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5340 /* Compute average percentage of zombies. */
5341 double nlive
5342 = (total_conses + total_symbols + total_markers + total_strings
5343 + total_vectors + total_floats + total_intervals + total_buffers);
5345 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
5346 max_live = max (nlive, max_live);
5347 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
5348 max_zombies = max (nzombies, max_zombies);
5349 ++ngcs;
5351 #endif
5353 if (!NILP (Vpost_gc_hook))
5355 ptrdiff_t gc_count = inhibit_garbage_collection ();
5356 safe_run_hooks (Qpost_gc_hook);
5357 unbind_to (gc_count, Qnil);
5360 /* Accumulate statistics. */
5361 if (FLOATP (Vgc_elapsed))
5363 EMACS_TIME since_start = sub_emacs_time (current_emacs_time (), start);
5364 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed)
5365 + EMACS_TIME_TO_DOUBLE (since_start));
5368 gcs_done++;
5370 return retval;
5374 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5375 only interesting objects referenced from glyphs are strings. */
5377 static void
5378 mark_glyph_matrix (struct glyph_matrix *matrix)
5380 struct glyph_row *row = matrix->rows;
5381 struct glyph_row *end = row + matrix->nrows;
5383 for (; row < end; ++row)
5384 if (row->enabled_p)
5386 int area;
5387 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
5389 struct glyph *glyph = row->glyphs[area];
5390 struct glyph *end_glyph = glyph + row->used[area];
5392 for (; glyph < end_glyph; ++glyph)
5393 if (STRINGP (glyph->object)
5394 && !STRING_MARKED_P (XSTRING (glyph->object)))
5395 mark_object (glyph->object);
5401 /* Mark Lisp faces in the face cache C. */
5403 static void
5404 mark_face_cache (struct face_cache *c)
5406 if (c)
5408 int i, j;
5409 for (i = 0; i < c->used; ++i)
5411 struct face *face = FACE_FROM_ID (c->f, i);
5413 if (face)
5415 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
5416 mark_object (face->lface[j]);
5424 /* Mark reference to a Lisp_Object.
5425 If the object referred to has not been seen yet, recursively mark
5426 all the references contained in it. */
5428 #define LAST_MARKED_SIZE 500
5429 static Lisp_Object last_marked[LAST_MARKED_SIZE];
5430 static int last_marked_index;
5432 /* For debugging--call abort when we cdr down this many
5433 links of a list, in mark_object. In debugging,
5434 the call to abort will hit a breakpoint.
5435 Normally this is zero and the check never goes off. */
5436 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE;
5438 static void
5439 mark_vectorlike (struct Lisp_Vector *ptr)
5441 ptrdiff_t size = ptr->header.size;
5442 ptrdiff_t i;
5444 eassert (!VECTOR_MARKED_P (ptr));
5445 VECTOR_MARK (ptr); /* Else mark it. */
5446 if (size & PSEUDOVECTOR_FLAG)
5447 size &= PSEUDOVECTOR_SIZE_MASK;
5449 /* Note that this size is not the memory-footprint size, but only
5450 the number of Lisp_Object fields that we should trace.
5451 The distinction is used e.g. by Lisp_Process which places extra
5452 non-Lisp_Object fields at the end of the structure... */
5453 for (i = 0; i < size; i++) /* ...and then mark its elements. */
5454 mark_object (ptr->contents[i]);
5457 /* Like mark_vectorlike but optimized for char-tables (and
5458 sub-char-tables) assuming that the contents are mostly integers or
5459 symbols. */
5461 static void
5462 mark_char_table (struct Lisp_Vector *ptr)
5464 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5465 int i;
5467 eassert (!VECTOR_MARKED_P (ptr));
5468 VECTOR_MARK (ptr);
5469 for (i = 0; i < size; i++)
5471 Lisp_Object val = ptr->contents[i];
5473 if (INTEGERP (val) || (SYMBOLP (val) && XSYMBOL (val)->gcmarkbit))
5474 continue;
5475 if (SUB_CHAR_TABLE_P (val))
5477 if (! VECTOR_MARKED_P (XVECTOR (val)))
5478 mark_char_table (XVECTOR (val));
5480 else
5481 mark_object (val);
5485 /* Mark the chain of overlays starting at PTR. */
5487 static void
5488 mark_overlay (struct Lisp_Overlay *ptr)
5490 for (; ptr && !ptr->gcmarkbit; ptr = ptr->next)
5492 ptr->gcmarkbit = 1;
5493 mark_object (ptr->start);
5494 mark_object (ptr->end);
5495 mark_object (ptr->plist);
5499 /* Mark Lisp_Objects and special pointers in BUFFER. */
5501 static void
5502 mark_buffer (struct buffer *buffer)
5504 /* This is handled much like other pseudovectors... */
5505 mark_vectorlike ((struct Lisp_Vector *) buffer);
5507 /* ...but there are some buffer-specific things. */
5509 MARK_INTERVAL_TREE (buffer_intervals (buffer));
5511 /* For now, we just don't mark the undo_list. It's done later in
5512 a special way just before the sweep phase, and after stripping
5513 some of its elements that are not needed any more. */
5515 mark_overlay (buffer->overlays_before);
5516 mark_overlay (buffer->overlays_after);
5518 /* If this is an indirect buffer, mark its base buffer. */
5519 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5520 mark_buffer (buffer->base_buffer);
5523 /* Remove killed buffers or items whose car is a killed buffer from
5524 LIST, and mark other items. Return changed LIST, which is marked. */
5526 static Lisp_Object
5527 mark_discard_killed_buffers (Lisp_Object list)
5529 Lisp_Object tail, *prev = &list;
5531 for (tail = list; CONSP (tail) && !CONS_MARKED_P (XCONS (tail));
5532 tail = XCDR (tail))
5534 Lisp_Object tem = XCAR (tail);
5535 if (CONSP (tem))
5536 tem = XCAR (tem);
5537 if (BUFFERP (tem) && !BUFFER_LIVE_P (XBUFFER (tem)))
5538 *prev = XCDR (tail);
5539 else
5541 CONS_MARK (XCONS (tail));
5542 mark_object (XCAR (tail));
5543 prev = &XCDR_AS_LVALUE (tail);
5546 return list;
5549 /* Determine type of generic Lisp_Object and mark it accordingly. */
5551 void
5552 mark_object (Lisp_Object arg)
5554 register Lisp_Object obj = arg;
5555 #ifdef GC_CHECK_MARKED_OBJECTS
5556 void *po;
5557 struct mem_node *m;
5558 #endif
5559 ptrdiff_t cdr_count = 0;
5561 loop:
5563 if (PURE_POINTER_P (XPNTR (obj)))
5564 return;
5566 last_marked[last_marked_index++] = obj;
5567 if (last_marked_index == LAST_MARKED_SIZE)
5568 last_marked_index = 0;
5570 /* Perform some sanity checks on the objects marked here. Abort if
5571 we encounter an object we know is bogus. This increases GC time
5572 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
5573 #ifdef GC_CHECK_MARKED_OBJECTS
5575 po = (void *) XPNTR (obj);
5577 /* Check that the object pointed to by PO is known to be a Lisp
5578 structure allocated from the heap. */
5579 #define CHECK_ALLOCATED() \
5580 do { \
5581 m = mem_find (po); \
5582 if (m == MEM_NIL) \
5583 emacs_abort (); \
5584 } while (0)
5586 /* Check that the object pointed to by PO is live, using predicate
5587 function LIVEP. */
5588 #define CHECK_LIVE(LIVEP) \
5589 do { \
5590 if (!LIVEP (m, po)) \
5591 emacs_abort (); \
5592 } while (0)
5594 /* Check both of the above conditions. */
5595 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
5596 do { \
5597 CHECK_ALLOCATED (); \
5598 CHECK_LIVE (LIVEP); \
5599 } while (0) \
5601 #else /* not GC_CHECK_MARKED_OBJECTS */
5603 #define CHECK_LIVE(LIVEP) (void) 0
5604 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
5606 #endif /* not GC_CHECK_MARKED_OBJECTS */
5608 switch (XTYPE (obj))
5610 case Lisp_String:
5612 register struct Lisp_String *ptr = XSTRING (obj);
5613 if (STRING_MARKED_P (ptr))
5614 break;
5615 CHECK_ALLOCATED_AND_LIVE (live_string_p);
5616 MARK_STRING (ptr);
5617 MARK_INTERVAL_TREE (ptr->intervals);
5618 #ifdef GC_CHECK_STRING_BYTES
5619 /* Check that the string size recorded in the string is the
5620 same as the one recorded in the sdata structure. */
5621 string_bytes (ptr);
5622 #endif /* GC_CHECK_STRING_BYTES */
5624 break;
5626 case Lisp_Vectorlike:
5628 register struct Lisp_Vector *ptr = XVECTOR (obj);
5629 register ptrdiff_t pvectype;
5631 if (VECTOR_MARKED_P (ptr))
5632 break;
5634 #ifdef GC_CHECK_MARKED_OBJECTS
5635 m = mem_find (po);
5636 if (m == MEM_NIL && !SUBRP (obj))
5637 emacs_abort ();
5638 #endif /* GC_CHECK_MARKED_OBJECTS */
5640 if (ptr->header.size & PSEUDOVECTOR_FLAG)
5641 pvectype = ((ptr->header.size & PVEC_TYPE_MASK)
5642 >> PSEUDOVECTOR_SIZE_BITS);
5643 else
5644 pvectype = 0;
5646 if (pvectype != PVEC_SUBR && pvectype != PVEC_BUFFER)
5647 CHECK_LIVE (live_vector_p);
5649 switch (pvectype)
5651 case PVEC_BUFFER:
5652 #ifdef GC_CHECK_MARKED_OBJECTS
5654 struct buffer *b;
5655 FOR_EACH_BUFFER (b)
5656 if (b == po)
5657 break;
5658 if (b == NULL)
5659 emacs_abort ();
5661 #endif /* GC_CHECK_MARKED_OBJECTS */
5662 mark_buffer ((struct buffer *) ptr);
5663 break;
5665 case PVEC_COMPILED:
5666 { /* We could treat this just like a vector, but it is better
5667 to save the COMPILED_CONSTANTS element for last and avoid
5668 recursion there. */
5669 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5670 int i;
5672 VECTOR_MARK (ptr);
5673 for (i = 0; i < size; i++)
5674 if (i != COMPILED_CONSTANTS)
5675 mark_object (ptr->contents[i]);
5676 if (size > COMPILED_CONSTANTS)
5678 obj = ptr->contents[COMPILED_CONSTANTS];
5679 goto loop;
5682 break;
5684 case PVEC_FRAME:
5685 mark_vectorlike (ptr);
5686 mark_face_cache (((struct frame *) ptr)->face_cache);
5687 break;
5689 case PVEC_WINDOW:
5691 struct window *w = (struct window *) ptr;
5692 bool leaf = NILP (w->hchild) && NILP (w->vchild);
5694 /* For live windows, Lisp code filters out killed buffers
5695 from both buffer lists. For dead windows, we do it here
5696 in attempt to help GC to reclaim killed buffers faster. */
5697 if (leaf && NILP (w->buffer))
5699 wset_prev_buffers
5700 (w, mark_discard_killed_buffers (w->prev_buffers));
5701 wset_next_buffers
5702 (w, mark_discard_killed_buffers (w->next_buffers));
5705 mark_vectorlike (ptr);
5706 /* Mark glyphs for leaf windows. Marking window
5707 matrices is sufficient because frame matrices
5708 use the same glyph memory. */
5709 if (leaf && w->current_matrix)
5711 mark_glyph_matrix (w->current_matrix);
5712 mark_glyph_matrix (w->desired_matrix);
5715 break;
5717 case PVEC_HASH_TABLE:
5719 struct Lisp_Hash_Table *h = (struct Lisp_Hash_Table *) ptr;
5721 mark_vectorlike (ptr);
5722 /* If hash table is not weak, mark all keys and values.
5723 For weak tables, mark only the vector. */
5724 if (NILP (h->weak))
5725 mark_object (h->key_and_value);
5726 else
5727 VECTOR_MARK (XVECTOR (h->key_and_value));
5729 break;
5731 case PVEC_CHAR_TABLE:
5732 mark_char_table (ptr);
5733 break;
5735 case PVEC_BOOL_VECTOR:
5736 /* No Lisp_Objects to mark in a bool vector. */
5737 VECTOR_MARK (ptr);
5738 break;
5740 case PVEC_SUBR:
5741 break;
5743 case PVEC_FREE:
5744 emacs_abort ();
5746 default:
5747 mark_vectorlike (ptr);
5750 break;
5752 case Lisp_Symbol:
5754 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
5755 struct Lisp_Symbol *ptrx;
5757 if (ptr->gcmarkbit)
5758 break;
5759 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
5760 ptr->gcmarkbit = 1;
5761 mark_object (ptr->function);
5762 mark_object (ptr->plist);
5763 switch (ptr->redirect)
5765 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
5766 case SYMBOL_VARALIAS:
5768 Lisp_Object tem;
5769 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
5770 mark_object (tem);
5771 break;
5773 case SYMBOL_LOCALIZED:
5775 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
5776 Lisp_Object where = blv->where;
5777 /* If the value is set up for a killed buffer or deleted
5778 frame, restore it's global binding. If the value is
5779 forwarded to a C variable, either it's not a Lisp_Object
5780 var, or it's staticpro'd already. */
5781 if ((BUFFERP (where) && !BUFFER_LIVE_P (XBUFFER (where)))
5782 || (FRAMEP (where) && !FRAME_LIVE_P (XFRAME (where))))
5783 swap_in_global_binding (ptr);
5784 mark_object (blv->where);
5785 mark_object (blv->valcell);
5786 mark_object (blv->defcell);
5787 break;
5789 case SYMBOL_FORWARDED:
5790 /* If the value is forwarded to a buffer or keyboard field,
5791 these are marked when we see the corresponding object.
5792 And if it's forwarded to a C variable, either it's not
5793 a Lisp_Object var, or it's staticpro'd already. */
5794 break;
5795 default: emacs_abort ();
5797 if (!PURE_POINTER_P (XSTRING (ptr->name)))
5798 MARK_STRING (XSTRING (ptr->name));
5799 MARK_INTERVAL_TREE (string_intervals (ptr->name));
5801 ptr = ptr->next;
5802 if (ptr)
5804 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun. */
5805 XSETSYMBOL (obj, ptrx);
5806 goto loop;
5809 break;
5811 case Lisp_Misc:
5812 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
5814 if (XMISCANY (obj)->gcmarkbit)
5815 break;
5817 switch (XMISCTYPE (obj))
5819 case Lisp_Misc_Marker:
5820 /* DO NOT mark thru the marker's chain.
5821 The buffer's markers chain does not preserve markers from gc;
5822 instead, markers are removed from the chain when freed by gc. */
5823 XMISCANY (obj)->gcmarkbit = 1;
5824 break;
5826 case Lisp_Misc_Save_Value:
5827 XMISCANY (obj)->gcmarkbit = 1;
5828 #if GC_MARK_STACK
5830 register struct Lisp_Save_Value *ptr = XSAVE_VALUE (obj);
5831 /* If DOGC is set, POINTER is the address of a memory
5832 area containing INTEGER potential Lisp_Objects. */
5833 if (ptr->dogc)
5835 Lisp_Object *p = (Lisp_Object *) ptr->pointer;
5836 ptrdiff_t nelt;
5837 for (nelt = ptr->integer; nelt > 0; nelt--, p++)
5838 mark_maybe_object (*p);
5841 #endif
5842 break;
5844 case Lisp_Misc_Overlay:
5845 mark_overlay (XOVERLAY (obj));
5846 break;
5848 default:
5849 emacs_abort ();
5851 break;
5853 case Lisp_Cons:
5855 register struct Lisp_Cons *ptr = XCONS (obj);
5856 if (CONS_MARKED_P (ptr))
5857 break;
5858 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
5859 CONS_MARK (ptr);
5860 /* If the cdr is nil, avoid recursion for the car. */
5861 if (EQ (ptr->u.cdr, Qnil))
5863 obj = ptr->car;
5864 cdr_count = 0;
5865 goto loop;
5867 mark_object (ptr->car);
5868 obj = ptr->u.cdr;
5869 cdr_count++;
5870 if (cdr_count == mark_object_loop_halt)
5871 emacs_abort ();
5872 goto loop;
5875 case Lisp_Float:
5876 CHECK_ALLOCATED_AND_LIVE (live_float_p);
5877 FLOAT_MARK (XFLOAT (obj));
5878 break;
5880 case_Lisp_Int:
5881 break;
5883 default:
5884 emacs_abort ();
5887 #undef CHECK_LIVE
5888 #undef CHECK_ALLOCATED
5889 #undef CHECK_ALLOCATED_AND_LIVE
5891 /* Mark the Lisp pointers in the terminal objects.
5892 Called by Fgarbage_collect. */
5894 static void
5895 mark_terminals (void)
5897 struct terminal *t;
5898 for (t = terminal_list; t; t = t->next_terminal)
5900 eassert (t->name != NULL);
5901 #ifdef HAVE_WINDOW_SYSTEM
5902 /* If a terminal object is reachable from a stacpro'ed object,
5903 it might have been marked already. Make sure the image cache
5904 gets marked. */
5905 mark_image_cache (t->image_cache);
5906 #endif /* HAVE_WINDOW_SYSTEM */
5907 if (!VECTOR_MARKED_P (t))
5908 mark_vectorlike ((struct Lisp_Vector *)t);
5914 /* Value is non-zero if OBJ will survive the current GC because it's
5915 either marked or does not need to be marked to survive. */
5917 bool
5918 survives_gc_p (Lisp_Object obj)
5920 bool survives_p;
5922 switch (XTYPE (obj))
5924 case_Lisp_Int:
5925 survives_p = 1;
5926 break;
5928 case Lisp_Symbol:
5929 survives_p = XSYMBOL (obj)->gcmarkbit;
5930 break;
5932 case Lisp_Misc:
5933 survives_p = XMISCANY (obj)->gcmarkbit;
5934 break;
5936 case Lisp_String:
5937 survives_p = STRING_MARKED_P (XSTRING (obj));
5938 break;
5940 case Lisp_Vectorlike:
5941 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
5942 break;
5944 case Lisp_Cons:
5945 survives_p = CONS_MARKED_P (XCONS (obj));
5946 break;
5948 case Lisp_Float:
5949 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
5950 break;
5952 default:
5953 emacs_abort ();
5956 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
5961 /* Sweep: find all structures not marked, and free them. */
5963 static void
5964 gc_sweep (void)
5966 /* Remove or mark entries in weak hash tables.
5967 This must be done before any object is unmarked. */
5968 sweep_weak_hash_tables ();
5970 sweep_strings ();
5971 check_string_bytes (!noninteractive);
5973 /* Put all unmarked conses on free list */
5975 register struct cons_block *cblk;
5976 struct cons_block **cprev = &cons_block;
5977 register int lim = cons_block_index;
5978 EMACS_INT num_free = 0, num_used = 0;
5980 cons_free_list = 0;
5982 for (cblk = cons_block; cblk; cblk = *cprev)
5984 register int i = 0;
5985 int this_free = 0;
5986 int ilim = (lim + BITS_PER_INT - 1) / BITS_PER_INT;
5988 /* Scan the mark bits an int at a time. */
5989 for (i = 0; i < ilim; i++)
5991 if (cblk->gcmarkbits[i] == -1)
5993 /* Fast path - all cons cells for this int are marked. */
5994 cblk->gcmarkbits[i] = 0;
5995 num_used += BITS_PER_INT;
5997 else
5999 /* Some cons cells for this int are not marked.
6000 Find which ones, and free them. */
6001 int start, pos, stop;
6003 start = i * BITS_PER_INT;
6004 stop = lim - start;
6005 if (stop > BITS_PER_INT)
6006 stop = BITS_PER_INT;
6007 stop += start;
6009 for (pos = start; pos < stop; pos++)
6011 if (!CONS_MARKED_P (&cblk->conses[pos]))
6013 this_free++;
6014 cblk->conses[pos].u.chain = cons_free_list;
6015 cons_free_list = &cblk->conses[pos];
6016 #if GC_MARK_STACK
6017 cons_free_list->car = Vdead;
6018 #endif
6020 else
6022 num_used++;
6023 CONS_UNMARK (&cblk->conses[pos]);
6029 lim = CONS_BLOCK_SIZE;
6030 /* If this block contains only free conses and we have already
6031 seen more than two blocks worth of free conses then deallocate
6032 this block. */
6033 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
6035 *cprev = cblk->next;
6036 /* Unhook from the free list. */
6037 cons_free_list = cblk->conses[0].u.chain;
6038 lisp_align_free (cblk);
6040 else
6042 num_free += this_free;
6043 cprev = &cblk->next;
6046 total_conses = num_used;
6047 total_free_conses = num_free;
6050 /* Put all unmarked floats on free list */
6052 register struct float_block *fblk;
6053 struct float_block **fprev = &float_block;
6054 register int lim = float_block_index;
6055 EMACS_INT num_free = 0, num_used = 0;
6057 float_free_list = 0;
6059 for (fblk = float_block; fblk; fblk = *fprev)
6061 register int i;
6062 int this_free = 0;
6063 for (i = 0; i < lim; i++)
6064 if (!FLOAT_MARKED_P (&fblk->floats[i]))
6066 this_free++;
6067 fblk->floats[i].u.chain = float_free_list;
6068 float_free_list = &fblk->floats[i];
6070 else
6072 num_used++;
6073 FLOAT_UNMARK (&fblk->floats[i]);
6075 lim = FLOAT_BLOCK_SIZE;
6076 /* If this block contains only free floats and we have already
6077 seen more than two blocks worth of free floats then deallocate
6078 this block. */
6079 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6081 *fprev = fblk->next;
6082 /* Unhook from the free list. */
6083 float_free_list = fblk->floats[0].u.chain;
6084 lisp_align_free (fblk);
6086 else
6088 num_free += this_free;
6089 fprev = &fblk->next;
6092 total_floats = num_used;
6093 total_free_floats = num_free;
6096 /* Put all unmarked intervals on free list */
6098 register struct interval_block *iblk;
6099 struct interval_block **iprev = &interval_block;
6100 register int lim = interval_block_index;
6101 EMACS_INT num_free = 0, num_used = 0;
6103 interval_free_list = 0;
6105 for (iblk = interval_block; iblk; iblk = *iprev)
6107 register int i;
6108 int this_free = 0;
6110 for (i = 0; i < lim; i++)
6112 if (!iblk->intervals[i].gcmarkbit)
6114 set_interval_parent (&iblk->intervals[i], interval_free_list);
6115 interval_free_list = &iblk->intervals[i];
6116 this_free++;
6118 else
6120 num_used++;
6121 iblk->intervals[i].gcmarkbit = 0;
6124 lim = INTERVAL_BLOCK_SIZE;
6125 /* If this block contains only free intervals and we have already
6126 seen more than two blocks worth of free intervals then
6127 deallocate this block. */
6128 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6130 *iprev = iblk->next;
6131 /* Unhook from the free list. */
6132 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
6133 lisp_free (iblk);
6135 else
6137 num_free += this_free;
6138 iprev = &iblk->next;
6141 total_intervals = num_used;
6142 total_free_intervals = num_free;
6145 /* Put all unmarked symbols on free list */
6147 register struct symbol_block *sblk;
6148 struct symbol_block **sprev = &symbol_block;
6149 register int lim = symbol_block_index;
6150 EMACS_INT num_free = 0, num_used = 0;
6152 symbol_free_list = NULL;
6154 for (sblk = symbol_block; sblk; sblk = *sprev)
6156 int this_free = 0;
6157 union aligned_Lisp_Symbol *sym = sblk->symbols;
6158 union aligned_Lisp_Symbol *end = sym + lim;
6160 for (; sym < end; ++sym)
6162 /* Check if the symbol was created during loadup. In such a case
6163 it might be pointed to by pure bytecode which we don't trace,
6164 so we conservatively assume that it is live. */
6165 bool pure_p = PURE_POINTER_P (XSTRING (sym->s.name));
6167 if (!sym->s.gcmarkbit && !pure_p)
6169 if (sym->s.redirect == SYMBOL_LOCALIZED)
6170 xfree (SYMBOL_BLV (&sym->s));
6171 sym->s.next = symbol_free_list;
6172 symbol_free_list = &sym->s;
6173 #if GC_MARK_STACK
6174 symbol_free_list->function = Vdead;
6175 #endif
6176 ++this_free;
6178 else
6180 ++num_used;
6181 if (!pure_p)
6182 UNMARK_STRING (XSTRING (sym->s.name));
6183 sym->s.gcmarkbit = 0;
6187 lim = SYMBOL_BLOCK_SIZE;
6188 /* If this block contains only free symbols and we have already
6189 seen more than two blocks worth of free symbols then deallocate
6190 this block. */
6191 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6193 *sprev = sblk->next;
6194 /* Unhook from the free list. */
6195 symbol_free_list = sblk->symbols[0].s.next;
6196 lisp_free (sblk);
6198 else
6200 num_free += this_free;
6201 sprev = &sblk->next;
6204 total_symbols = num_used;
6205 total_free_symbols = num_free;
6208 /* Put all unmarked misc's on free list.
6209 For a marker, first unchain it from the buffer it points into. */
6211 register struct marker_block *mblk;
6212 struct marker_block **mprev = &marker_block;
6213 register int lim = marker_block_index;
6214 EMACS_INT num_free = 0, num_used = 0;
6216 marker_free_list = 0;
6218 for (mblk = marker_block; mblk; mblk = *mprev)
6220 register int i;
6221 int this_free = 0;
6223 for (i = 0; i < lim; i++)
6225 if (!mblk->markers[i].m.u_any.gcmarkbit)
6227 if (mblk->markers[i].m.u_any.type == Lisp_Misc_Marker)
6228 unchain_marker (&mblk->markers[i].m.u_marker);
6229 /* Set the type of the freed object to Lisp_Misc_Free.
6230 We could leave the type alone, since nobody checks it,
6231 but this might catch bugs faster. */
6232 mblk->markers[i].m.u_marker.type = Lisp_Misc_Free;
6233 mblk->markers[i].m.u_free.chain = marker_free_list;
6234 marker_free_list = &mblk->markers[i].m;
6235 this_free++;
6237 else
6239 num_used++;
6240 mblk->markers[i].m.u_any.gcmarkbit = 0;
6243 lim = MARKER_BLOCK_SIZE;
6244 /* If this block contains only free markers and we have already
6245 seen more than two blocks worth of free markers then deallocate
6246 this block. */
6247 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6249 *mprev = mblk->next;
6250 /* Unhook from the free list. */
6251 marker_free_list = mblk->markers[0].m.u_free.chain;
6252 lisp_free (mblk);
6254 else
6256 num_free += this_free;
6257 mprev = &mblk->next;
6261 total_markers = num_used;
6262 total_free_markers = num_free;
6265 /* Free all unmarked buffers */
6267 register struct buffer *buffer = all_buffers, *prev = 0, *next;
6269 total_buffers = 0;
6270 while (buffer)
6271 if (!VECTOR_MARKED_P (buffer))
6273 if (prev)
6274 prev->header.next = buffer->header.next;
6275 else
6276 all_buffers = buffer->header.next.buffer;
6277 next = buffer->header.next.buffer;
6278 lisp_free (buffer);
6279 buffer = next;
6281 else
6283 VECTOR_UNMARK (buffer);
6284 /* Do not use buffer_(set|get)_intervals here. */
6285 buffer->text->intervals = balance_intervals (buffer->text->intervals);
6286 total_buffers++;
6287 prev = buffer, buffer = buffer->header.next.buffer;
6291 sweep_vectors ();
6292 check_string_bytes (!noninteractive);
6298 /* Debugging aids. */
6300 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
6301 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6302 This may be helpful in debugging Emacs's memory usage.
6303 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6304 (void)
6306 Lisp_Object end;
6308 XSETINT (end, (intptr_t) (char *) sbrk (0) / 1024);
6310 return end;
6313 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
6314 doc: /* Return a list of counters that measure how much consing there has been.
6315 Each of these counters increments for a certain kind of object.
6316 The counters wrap around from the largest positive integer to zero.
6317 Garbage collection does not decrease them.
6318 The elements of the value are as follows:
6319 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6320 All are in units of 1 = one object consed
6321 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6322 objects consed.
6323 MISCS include overlays, markers, and some internal types.
6324 Frames, windows, buffers, and subprocesses count as vectors
6325 (but the contents of a buffer's text do not count here). */)
6326 (void)
6328 return listn (CONSTYPE_HEAP, 8,
6329 bounded_number (cons_cells_consed),
6330 bounded_number (floats_consed),
6331 bounded_number (vector_cells_consed),
6332 bounded_number (symbols_consed),
6333 bounded_number (string_chars_consed),
6334 bounded_number (misc_objects_consed),
6335 bounded_number (intervals_consed),
6336 bounded_number (strings_consed));
6339 /* Find at most FIND_MAX symbols which have OBJ as their value or
6340 function. This is used in gdbinit's `xwhichsymbols' command. */
6342 Lisp_Object
6343 which_symbols (Lisp_Object obj, EMACS_INT find_max)
6345 struct symbol_block *sblk;
6346 ptrdiff_t gc_count = inhibit_garbage_collection ();
6347 Lisp_Object found = Qnil;
6349 if (! DEADP (obj))
6351 for (sblk = symbol_block; sblk; sblk = sblk->next)
6353 union aligned_Lisp_Symbol *aligned_sym = sblk->symbols;
6354 int bn;
6356 for (bn = 0; bn < SYMBOL_BLOCK_SIZE; bn++, aligned_sym++)
6358 struct Lisp_Symbol *sym = &aligned_sym->s;
6359 Lisp_Object val;
6360 Lisp_Object tem;
6362 if (sblk == symbol_block && bn >= symbol_block_index)
6363 break;
6365 XSETSYMBOL (tem, sym);
6366 val = find_symbol_value (tem);
6367 if (EQ (val, obj)
6368 || EQ (sym->function, obj)
6369 || (!NILP (sym->function)
6370 && COMPILEDP (sym->function)
6371 && EQ (AREF (sym->function, COMPILED_BYTECODE), obj))
6372 || (!NILP (val)
6373 && COMPILEDP (val)
6374 && EQ (AREF (val, COMPILED_BYTECODE), obj)))
6376 found = Fcons (tem, found);
6377 if (--find_max == 0)
6378 goto out;
6384 out:
6385 unbind_to (gc_count, Qnil);
6386 return found;
6389 #ifdef ENABLE_CHECKING
6391 bool suppress_checking;
6393 void
6394 die (const char *msg, const char *file, int line)
6396 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: %s\r\n",
6397 file, line, msg);
6398 fatal_error_backtrace (SIGABRT, INT_MAX);
6400 #endif
6402 /* Initialization */
6404 void
6405 init_alloc_once (void)
6407 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
6408 purebeg = PUREBEG;
6409 pure_size = PURESIZE;
6411 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
6412 mem_init ();
6413 Vdead = make_pure_string ("DEAD", 4, 4, 0);
6414 #endif
6416 #ifdef DOUG_LEA_MALLOC
6417 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
6418 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
6419 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
6420 #endif
6421 init_strings ();
6422 init_vectors ();
6424 refill_memory_reserve ();
6425 gc_cons_threshold = GC_DEFAULT_THRESHOLD;
6428 void
6429 init_alloc (void)
6431 gcprolist = 0;
6432 byte_stack_list = 0;
6433 #if GC_MARK_STACK
6434 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
6435 setjmp_tested_p = longjmps_done = 0;
6436 #endif
6437 #endif
6438 Vgc_elapsed = make_float (0.0);
6439 gcs_done = 0;
6442 void
6443 syms_of_alloc (void)
6445 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
6446 doc: /* Number of bytes of consing between garbage collections.
6447 Garbage collection can happen automatically once this many bytes have been
6448 allocated since the last garbage collection. All data types count.
6450 Garbage collection happens automatically only when `eval' is called.
6452 By binding this temporarily to a large number, you can effectively
6453 prevent garbage collection during a part of the program.
6454 See also `gc-cons-percentage'. */);
6456 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
6457 doc: /* Portion of the heap used for allocation.
6458 Garbage collection can happen automatically once this portion of the heap
6459 has been allocated since the last garbage collection.
6460 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
6461 Vgc_cons_percentage = make_float (0.1);
6463 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
6464 doc: /* Number of bytes of shareable Lisp data allocated so far. */);
6466 DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
6467 doc: /* Number of cons cells that have been consed so far. */);
6469 DEFVAR_INT ("floats-consed", floats_consed,
6470 doc: /* Number of floats that have been consed so far. */);
6472 DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
6473 doc: /* Number of vector cells that have been consed so far. */);
6475 DEFVAR_INT ("symbols-consed", symbols_consed,
6476 doc: /* Number of symbols that have been consed so far. */);
6478 DEFVAR_INT ("string-chars-consed", string_chars_consed,
6479 doc: /* Number of string characters that have been consed so far. */);
6481 DEFVAR_INT ("misc-objects-consed", misc_objects_consed,
6482 doc: /* Number of miscellaneous objects that have been consed so far.
6483 These include markers and overlays, plus certain objects not visible
6484 to users. */);
6486 DEFVAR_INT ("intervals-consed", intervals_consed,
6487 doc: /* Number of intervals that have been consed so far. */);
6489 DEFVAR_INT ("strings-consed", strings_consed,
6490 doc: /* Number of strings that have been consed so far. */);
6492 DEFVAR_LISP ("purify-flag", Vpurify_flag,
6493 doc: /* Non-nil means loading Lisp code in order to dump an executable.
6494 This means that certain objects should be allocated in shared (pure) space.
6495 It can also be set to a hash-table, in which case this table is used to
6496 do hash-consing of the objects allocated to pure space. */);
6498 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
6499 doc: /* Non-nil means display messages at start and end of garbage collection. */);
6500 garbage_collection_messages = 0;
6502 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
6503 doc: /* Hook run after garbage collection has finished. */);
6504 Vpost_gc_hook = Qnil;
6505 DEFSYM (Qpost_gc_hook, "post-gc-hook");
6507 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
6508 doc: /* Precomputed `signal' argument for memory-full error. */);
6509 /* We build this in advance because if we wait until we need it, we might
6510 not be able to allocate the memory to hold it. */
6511 Vmemory_signal_data
6512 = listn (CONSTYPE_PURE, 2, Qerror,
6513 build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
6515 DEFVAR_LISP ("memory-full", Vmemory_full,
6516 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
6517 Vmemory_full = Qnil;
6519 DEFSYM (Qconses, "conses");
6520 DEFSYM (Qsymbols, "symbols");
6521 DEFSYM (Qmiscs, "miscs");
6522 DEFSYM (Qstrings, "strings");
6523 DEFSYM (Qvectors, "vectors");
6524 DEFSYM (Qfloats, "floats");
6525 DEFSYM (Qintervals, "intervals");
6526 DEFSYM (Qbuffers, "buffers");
6527 DEFSYM (Qstring_bytes, "string-bytes");
6528 DEFSYM (Qvector_slots, "vector-slots");
6529 DEFSYM (Qheap, "heap");
6531 DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
6532 DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
6534 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
6535 doc: /* Accumulated time elapsed in garbage collections.
6536 The time is in seconds as a floating point value. */);
6537 DEFVAR_INT ("gcs-done", gcs_done,
6538 doc: /* Accumulated number of garbage collections done. */);
6540 defsubr (&Scons);
6541 defsubr (&Slist);
6542 defsubr (&Svector);
6543 defsubr (&Smake_byte_code);
6544 defsubr (&Smake_list);
6545 defsubr (&Smake_vector);
6546 defsubr (&Smake_string);
6547 defsubr (&Smake_bool_vector);
6548 defsubr (&Smake_symbol);
6549 defsubr (&Smake_marker);
6550 defsubr (&Spurecopy);
6551 defsubr (&Sgarbage_collect);
6552 defsubr (&Smemory_limit);
6553 defsubr (&Smemory_use_counts);
6555 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
6556 defsubr (&Sgc_status);
6557 #endif
6560 /* When compiled with GCC, GDB might say "No enum type named
6561 pvec_type" if we don't have at least one symbol with that type, and
6562 then xbacktrace could fail. Similarly for the other enums and
6563 their values. */
6564 union
6566 enum CHARTAB_SIZE_BITS CHARTAB_SIZE_BITS;
6567 enum CHAR_TABLE_STANDARD_SLOTS CHAR_TABLE_STANDARD_SLOTS;
6568 enum char_bits char_bits;
6569 enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE;
6570 enum DEFAULT_HASH_SIZE DEFAULT_HASH_SIZE;
6571 enum enum_USE_LSB_TAG enum_USE_LSB_TAG;
6572 enum FLOAT_TO_STRING_BUFSIZE FLOAT_TO_STRING_BUFSIZE;
6573 enum Lisp_Bits Lisp_Bits;
6574 enum Lisp_Compiled Lisp_Compiled;
6575 enum maxargs maxargs;
6576 enum MAX_ALLOCA MAX_ALLOCA;
6577 enum More_Lisp_Bits More_Lisp_Bits;
6578 enum pvec_type pvec_type;
6579 #if USE_LSB_TAG
6580 enum lsb_bits lsb_bits;
6581 #endif
6582 } const EXTERNALLY_VISIBLE gdb_make_enums_visible = {0};