Extend the value returned by Fgarbage_collect with heap statistics.
[emacs.git] / src / alloc.c
blob05e676836c572f7b0d137c81de68581bc315a821
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>
22 #include <stdio.h>
23 #include <limits.h> /* For CHAR_BIT. */
24 #include <setjmp.h>
26 #include <signal.h>
28 #ifdef HAVE_PTHREAD
29 #include <pthread.h>
30 #endif
32 /* This file is part of the core Lisp implementation, and thus must
33 deal with the real data structures. If the Lisp implementation is
34 replaced, this file likely will not be used. */
36 #undef HIDE_LISP_IMPLEMENTATION
37 #include "lisp.h"
38 #include "process.h"
39 #include "intervals.h"
40 #include "puresize.h"
41 #include "character.h"
42 #include "buffer.h"
43 #include "window.h"
44 #include "keyboard.h"
45 #include "frame.h"
46 #include "blockinput.h"
47 #include "syssignal.h"
48 #include "termhooks.h" /* For struct terminal. */
49 #include <setjmp.h>
50 #include <verify.h>
52 /* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects.
53 Doable only if GC_MARK_STACK. */
54 #if ! GC_MARK_STACK
55 # undef GC_CHECK_MARKED_OBJECTS
56 #endif
58 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
59 memory. Can do this only if using gmalloc.c and if not checking
60 marked objects. */
62 #if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
63 || defined GC_CHECK_MARKED_OBJECTS)
64 #undef GC_MALLOC_CHECK
65 #endif
67 #include <unistd.h>
68 #ifndef HAVE_UNISTD_H
69 extern void *sbrk ();
70 #endif
72 #include <fcntl.h>
74 #ifdef WINDOWSNT
75 #include "w32.h"
76 #endif
78 #ifdef DOUG_LEA_MALLOC
80 #include <malloc.h>
82 /* Specify maximum number of areas to mmap. It would be nice to use a
83 value that explicitly means "no limit". */
85 #define MMAP_MAX_AREAS 100000000
87 #else /* not DOUG_LEA_MALLOC */
89 /* The following come from gmalloc.c. */
91 extern size_t _bytes_used;
92 extern size_t __malloc_extra_blocks;
93 extern void *_malloc_internal (size_t);
94 extern void _free_internal (void *);
96 #endif /* not DOUG_LEA_MALLOC */
98 #if ! defined SYSTEM_MALLOC && ! defined SYNC_INPUT
99 #ifdef HAVE_PTHREAD
101 /* When GTK uses the file chooser dialog, different backends can be loaded
102 dynamically. One such a backend is the Gnome VFS backend that gets loaded
103 if you run Gnome. That backend creates several threads and also allocates
104 memory with malloc.
106 Also, gconf and gsettings may create several threads.
108 If Emacs sets malloc hooks (! SYSTEM_MALLOC) and the emacs_blocked_*
109 functions below are called from malloc, there is a chance that one
110 of these threads preempts the Emacs main thread and the hook variables
111 end up in an inconsistent state. So we have a mutex to prevent that (note
112 that the backend handles concurrent access to malloc within its own threads
113 but Emacs code running in the main thread is not included in that control).
115 When UNBLOCK_INPUT is called, reinvoke_input_signal may be called. If this
116 happens in one of the backend threads we will have two threads that tries
117 to run Emacs code at once, and the code is not prepared for that.
118 To prevent that, we only call BLOCK/UNBLOCK from the main thread. */
120 static pthread_mutex_t alloc_mutex;
122 #define BLOCK_INPUT_ALLOC \
123 do \
125 if (pthread_equal (pthread_self (), main_thread)) \
126 BLOCK_INPUT; \
127 pthread_mutex_lock (&alloc_mutex); \
129 while (0)
130 #define UNBLOCK_INPUT_ALLOC \
131 do \
133 pthread_mutex_unlock (&alloc_mutex); \
134 if (pthread_equal (pthread_self (), main_thread)) \
135 UNBLOCK_INPUT; \
137 while (0)
139 #else /* ! defined HAVE_PTHREAD */
141 #define BLOCK_INPUT_ALLOC BLOCK_INPUT
142 #define UNBLOCK_INPUT_ALLOC UNBLOCK_INPUT
144 #endif /* ! defined HAVE_PTHREAD */
145 #endif /* ! defined SYSTEM_MALLOC && ! defined SYNC_INPUT */
147 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
148 to a struct Lisp_String. */
150 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
151 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
152 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
154 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
155 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
156 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
158 /* Value is the number of bytes of S, a pointer to a struct Lisp_String.
159 Be careful during GC, because S->size contains the mark bit for
160 strings. */
162 #define GC_STRING_BYTES(S) (STRING_BYTES (S))
164 /* Global variables. */
165 struct emacs_globals globals;
167 /* Number of bytes of consing done since the last gc. */
169 EMACS_INT consing_since_gc;
171 /* Similar minimum, computed from Vgc_cons_percentage. */
173 EMACS_INT gc_relative_threshold;
175 /* Minimum number of bytes of consing since GC before next GC,
176 when memory is full. */
178 EMACS_INT memory_full_cons_threshold;
180 /* Nonzero during GC. */
182 int gc_in_progress;
184 /* Nonzero means abort if try to GC.
185 This is for code which is written on the assumption that
186 no GC will happen, so as to verify that assumption. */
188 int abort_on_gc;
190 /* Number of live and free conses etc. */
192 static EMACS_INT total_conses, total_markers, total_symbols, total_buffers;
193 static EMACS_INT total_free_conses, total_free_markers, total_free_symbols;
194 static EMACS_INT total_free_floats, total_floats;
196 /* Points to memory space allocated as "spare", to be freed if we run
197 out of memory. We keep one large block, four cons-blocks, and
198 two string blocks. */
200 static char *spare_memory[7];
202 /* Amount of spare memory to keep in large reserve block, or to see
203 whether this much is available when malloc fails on a larger request. */
205 #define SPARE_MEMORY (1 << 14)
207 /* Number of extra blocks malloc should get when it needs more core. */
209 static int malloc_hysteresis;
211 /* Initialize it to a nonzero value to force it into data space
212 (rather than bss space). That way unexec will remap it into text
213 space (pure), on some systems. We have not implemented the
214 remapping on more recent systems because this is less important
215 nowadays than in the days of small memories and timesharing. */
217 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
218 #define PUREBEG (char *) pure
220 /* Pointer to the pure area, and its size. */
222 static char *purebeg;
223 static ptrdiff_t pure_size;
225 /* Number of bytes of pure storage used before pure storage overflowed.
226 If this is non-zero, this implies that an overflow occurred. */
228 static ptrdiff_t pure_bytes_used_before_overflow;
230 /* Value is non-zero if P points into pure space. */
232 #define PURE_POINTER_P(P) \
233 ((uintptr_t) (P) - (uintptr_t) purebeg <= pure_size)
235 /* Index in pure at which next pure Lisp object will be allocated.. */
237 static ptrdiff_t pure_bytes_used_lisp;
239 /* Number of bytes allocated for non-Lisp objects in pure storage. */
241 static ptrdiff_t pure_bytes_used_non_lisp;
243 /* If nonzero, this is a warning delivered by malloc and not yet
244 displayed. */
246 const char *pending_malloc_warning;
248 /* Maximum amount of C stack to save when a GC happens. */
250 #ifndef MAX_SAVE_STACK
251 #define MAX_SAVE_STACK 16000
252 #endif
254 /* Buffer in which we save a copy of the C stack at each GC. */
256 #if MAX_SAVE_STACK > 0
257 static char *stack_copy;
258 static ptrdiff_t stack_copy_size;
259 #endif
261 static Lisp_Object Qstring_bytes, Qvector_slots, Qheap;
262 static Lisp_Object Qgc_cons_threshold;
263 Lisp_Object Qchar_table_extra_slots;
265 /* Hook run after GC has finished. */
267 static Lisp_Object Qpost_gc_hook;
269 static void mark_terminals (void);
270 static void gc_sweep (void);
271 static Lisp_Object make_pure_vector (ptrdiff_t);
272 static void mark_glyph_matrix (struct glyph_matrix *);
273 static void mark_face_cache (struct face_cache *);
275 #if !defined REL_ALLOC || defined SYSTEM_MALLOC
276 static void refill_memory_reserve (void);
277 #endif
278 static struct Lisp_String *allocate_string (void);
279 static void compact_small_strings (void);
280 static void free_large_strings (void);
281 static void sweep_strings (void);
282 static void free_misc (Lisp_Object);
283 extern Lisp_Object which_symbols (Lisp_Object, EMACS_INT) EXTERNALLY_VISIBLE;
285 /* Handy constants for vectorlike objects. */
286 enum
288 header_size = offsetof (struct Lisp_Vector, contents),
289 bool_header_size = offsetof (struct Lisp_Bool_Vector, data),
290 word_size = sizeof (Lisp_Object)
293 /* When scanning the C stack for live Lisp objects, Emacs keeps track
294 of what memory allocated via lisp_malloc is intended for what
295 purpose. This enumeration specifies the type of memory. */
297 enum mem_type
299 MEM_TYPE_NON_LISP,
300 MEM_TYPE_BUFFER,
301 MEM_TYPE_CONS,
302 MEM_TYPE_STRING,
303 MEM_TYPE_MISC,
304 MEM_TYPE_SYMBOL,
305 MEM_TYPE_FLOAT,
306 /* We used to keep separate mem_types for subtypes of vectors such as
307 process, hash_table, frame, terminal, and window, but we never made
308 use of the distinction, so it only caused source-code complexity
309 and runtime slowdown. Minor but pointless. */
310 MEM_TYPE_VECTORLIKE,
311 /* Special type to denote vector blocks. */
312 MEM_TYPE_VECTOR_BLOCK
315 static void *lisp_malloc (size_t, enum mem_type);
318 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
320 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
321 #include <stdio.h> /* For fprintf. */
322 #endif
324 /* A unique object in pure space used to make some Lisp objects
325 on free lists recognizable in O(1). */
327 static Lisp_Object Vdead;
328 #define DEADP(x) EQ (x, Vdead)
330 #ifdef GC_MALLOC_CHECK
332 enum mem_type allocated_mem_type;
334 #endif /* GC_MALLOC_CHECK */
336 /* A node in the red-black tree describing allocated memory containing
337 Lisp data. Each such block is recorded with its start and end
338 address when it is allocated, and removed from the tree when it
339 is freed.
341 A red-black tree is a balanced binary tree with the following
342 properties:
344 1. Every node is either red or black.
345 2. Every leaf is black.
346 3. If a node is red, then both of its children are black.
347 4. Every simple path from a node to a descendant leaf contains
348 the same number of black nodes.
349 5. The root is always black.
351 When nodes are inserted into the tree, or deleted from the tree,
352 the tree is "fixed" so that these properties are always true.
354 A red-black tree with N internal nodes has height at most 2
355 log(N+1). Searches, insertions and deletions are done in O(log N).
356 Please see a text book about data structures for a detailed
357 description of red-black trees. Any book worth its salt should
358 describe them. */
360 struct mem_node
362 /* Children of this node. These pointers are never NULL. When there
363 is no child, the value is MEM_NIL, which points to a dummy node. */
364 struct mem_node *left, *right;
366 /* The parent of this node. In the root node, this is NULL. */
367 struct mem_node *parent;
369 /* Start and end of allocated region. */
370 void *start, *end;
372 /* Node color. */
373 enum {MEM_BLACK, MEM_RED} color;
375 /* Memory type. */
376 enum mem_type type;
379 /* Base address of stack. Set in main. */
381 Lisp_Object *stack_base;
383 /* Root of the tree describing allocated Lisp memory. */
385 static struct mem_node *mem_root;
387 /* Lowest and highest known address in the heap. */
389 static void *min_heap_address, *max_heap_address;
391 /* Sentinel node of the tree. */
393 static struct mem_node mem_z;
394 #define MEM_NIL &mem_z
396 static struct Lisp_Vector *allocate_vectorlike (ptrdiff_t);
397 static void lisp_free (void *);
398 static void mark_stack (void);
399 static int live_vector_p (struct mem_node *, void *);
400 static int live_buffer_p (struct mem_node *, void *);
401 static int live_string_p (struct mem_node *, void *);
402 static int live_cons_p (struct mem_node *, void *);
403 static int live_symbol_p (struct mem_node *, void *);
404 static int live_float_p (struct mem_node *, void *);
405 static int live_misc_p (struct mem_node *, void *);
406 static void mark_maybe_object (Lisp_Object);
407 static void mark_memory (void *, void *);
408 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
409 static void mem_init (void);
410 static struct mem_node *mem_insert (void *, void *, enum mem_type);
411 static void mem_insert_fixup (struct mem_node *);
412 #endif
413 static void mem_rotate_left (struct mem_node *);
414 static void mem_rotate_right (struct mem_node *);
415 static void mem_delete (struct mem_node *);
416 static void mem_delete_fixup (struct mem_node *);
417 static inline struct mem_node *mem_find (void *);
420 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
421 static void check_gcpros (void);
422 #endif
424 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
426 #ifndef DEADP
427 # define DEADP(x) 0
428 #endif
430 /* Recording what needs to be marked for gc. */
432 struct gcpro *gcprolist;
434 /* Addresses of staticpro'd variables. Initialize it to a nonzero
435 value; otherwise some compilers put it into BSS. */
437 #define NSTATICS 0x650
438 static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
440 /* Index of next unused slot in staticvec. */
442 static int staticidx;
444 static void *pure_alloc (size_t, int);
447 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
448 ALIGNMENT must be a power of 2. */
450 #define ALIGN(ptr, ALIGNMENT) \
451 ((void *) (((uintptr_t) (ptr) + (ALIGNMENT) - 1) \
452 & ~ ((ALIGNMENT) - 1)))
456 /************************************************************************
457 Malloc
458 ************************************************************************/
460 /* Function malloc calls this if it finds we are near exhausting storage. */
462 void
463 malloc_warning (const char *str)
465 pending_malloc_warning = str;
469 /* Display an already-pending malloc warning. */
471 void
472 display_malloc_warning (void)
474 call3 (intern ("display-warning"),
475 intern ("alloc"),
476 build_string (pending_malloc_warning),
477 intern ("emergency"));
478 pending_malloc_warning = 0;
481 /* Called if we can't allocate relocatable space for a buffer. */
483 void
484 buffer_memory_full (ptrdiff_t nbytes)
486 /* If buffers use the relocating allocator, no need to free
487 spare_memory, because we may have plenty of malloc space left
488 that we could get, and if we don't, the malloc that fails will
489 itself cause spare_memory to be freed. If buffers don't use the
490 relocating allocator, treat this like any other failing
491 malloc. */
493 #ifndef REL_ALLOC
494 memory_full (nbytes);
495 #endif
497 /* This used to call error, but if we've run out of memory, we could
498 get infinite recursion trying to build the string. */
499 xsignal (Qnil, Vmemory_signal_data);
502 /* A common multiple of the positive integers A and B. Ideally this
503 would be the least common multiple, but there's no way to do that
504 as a constant expression in C, so do the best that we can easily do. */
505 #define COMMON_MULTIPLE(a, b) \
506 ((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
508 #ifndef XMALLOC_OVERRUN_CHECK
509 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
510 #else
512 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
513 around each block.
515 The header consists of XMALLOC_OVERRUN_CHECK_SIZE fixed bytes
516 followed by XMALLOC_OVERRUN_SIZE_SIZE bytes containing the original
517 block size in little-endian order. The trailer consists of
518 XMALLOC_OVERRUN_CHECK_SIZE fixed bytes.
520 The header is used to detect whether this block has been allocated
521 through these functions, as some low-level libc functions may
522 bypass the malloc hooks. */
524 #define XMALLOC_OVERRUN_CHECK_SIZE 16
525 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
526 (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)
528 /* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
529 hold a size_t value and (2) the header size is a multiple of the
530 alignment that Emacs needs for C types and for USE_LSB_TAG. */
531 #define XMALLOC_BASE_ALIGNMENT \
532 offsetof ( \
533 struct { \
534 union { long double d; intmax_t i; void *p; } u; \
535 char c; \
536 }, \
539 #if USE_LSB_TAG
540 # define XMALLOC_HEADER_ALIGNMENT \
541 COMMON_MULTIPLE (1 << GCTYPEBITS, XMALLOC_BASE_ALIGNMENT)
542 #else
543 # define XMALLOC_HEADER_ALIGNMENT XMALLOC_BASE_ALIGNMENT
544 #endif
545 #define XMALLOC_OVERRUN_SIZE_SIZE \
546 (((XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t) \
547 + XMALLOC_HEADER_ALIGNMENT - 1) \
548 / XMALLOC_HEADER_ALIGNMENT * XMALLOC_HEADER_ALIGNMENT) \
549 - XMALLOC_OVERRUN_CHECK_SIZE)
551 static char const xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE] =
552 { '\x9a', '\x9b', '\xae', '\xaf',
553 '\xbf', '\xbe', '\xce', '\xcf',
554 '\xea', '\xeb', '\xec', '\xed',
555 '\xdf', '\xde', '\x9c', '\x9d' };
557 static char const xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
558 { '\xaa', '\xab', '\xac', '\xad',
559 '\xba', '\xbb', '\xbc', '\xbd',
560 '\xca', '\xcb', '\xcc', '\xcd',
561 '\xda', '\xdb', '\xdc', '\xdd' };
563 /* Insert and extract the block size in the header. */
565 static void
566 xmalloc_put_size (unsigned char *ptr, size_t size)
568 int i;
569 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
571 *--ptr = size & ((1 << CHAR_BIT) - 1);
572 size >>= CHAR_BIT;
576 static size_t
577 xmalloc_get_size (unsigned char *ptr)
579 size_t size = 0;
580 int i;
581 ptr -= XMALLOC_OVERRUN_SIZE_SIZE;
582 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
584 size <<= CHAR_BIT;
585 size += *ptr++;
587 return size;
591 /* The call depth in overrun_check functions. For example, this might happen:
592 xmalloc()
593 overrun_check_malloc()
594 -> malloc -> (via hook)_-> emacs_blocked_malloc
595 -> overrun_check_malloc
596 call malloc (hooks are NULL, so real malloc is called).
597 malloc returns 10000.
598 add overhead, return 10016.
599 <- (back in overrun_check_malloc)
600 add overhead again, return 10032
601 xmalloc returns 10032.
603 (time passes).
605 xfree(10032)
606 overrun_check_free(10032)
607 decrease overhead
608 free(10016) <- crash, because 10000 is the original pointer. */
610 static ptrdiff_t check_depth;
612 /* Like malloc, but wraps allocated block with header and trailer. */
614 static void *
615 overrun_check_malloc (size_t size)
617 register unsigned char *val;
618 int overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_OVERHEAD : 0;
619 if (SIZE_MAX - overhead < size)
620 abort ();
622 val = malloc (size + overhead);
623 if (val && check_depth == 1)
625 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
626 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
627 xmalloc_put_size (val, size);
628 memcpy (val + size, xmalloc_overrun_check_trailer,
629 XMALLOC_OVERRUN_CHECK_SIZE);
631 --check_depth;
632 return val;
636 /* Like realloc, but checks old block for overrun, and wraps new block
637 with header and trailer. */
639 static void *
640 overrun_check_realloc (void *block, size_t size)
642 register unsigned char *val = (unsigned char *) block;
643 int overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_OVERHEAD : 0;
644 if (SIZE_MAX - overhead < size)
645 abort ();
647 if (val
648 && check_depth == 1
649 && memcmp (xmalloc_overrun_check_header,
650 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
651 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
653 size_t osize = xmalloc_get_size (val);
654 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
655 XMALLOC_OVERRUN_CHECK_SIZE))
656 abort ();
657 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
658 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
659 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
662 val = realloc (val, size + overhead);
664 if (val && check_depth == 1)
666 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
667 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
668 xmalloc_put_size (val, size);
669 memcpy (val + size, xmalloc_overrun_check_trailer,
670 XMALLOC_OVERRUN_CHECK_SIZE);
672 --check_depth;
673 return val;
676 /* Like free, but checks block for overrun. */
678 static void
679 overrun_check_free (void *block)
681 unsigned char *val = (unsigned char *) block;
683 ++check_depth;
684 if (val
685 && check_depth == 1
686 && memcmp (xmalloc_overrun_check_header,
687 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
688 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
690 size_t osize = xmalloc_get_size (val);
691 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
692 XMALLOC_OVERRUN_CHECK_SIZE))
693 abort ();
694 #ifdef XMALLOC_CLEAR_FREE_MEMORY
695 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
696 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_OVERHEAD);
697 #else
698 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
699 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
700 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
701 #endif
704 free (val);
705 --check_depth;
708 #undef malloc
709 #undef realloc
710 #undef free
711 #define malloc overrun_check_malloc
712 #define realloc overrun_check_realloc
713 #define free overrun_check_free
714 #endif
716 #ifdef SYNC_INPUT
717 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
718 there's no need to block input around malloc. */
719 #define MALLOC_BLOCK_INPUT ((void)0)
720 #define MALLOC_UNBLOCK_INPUT ((void)0)
721 #else
722 #define MALLOC_BLOCK_INPUT BLOCK_INPUT
723 #define MALLOC_UNBLOCK_INPUT UNBLOCK_INPUT
724 #endif
726 /* Like malloc but check for no memory and block interrupt input.. */
728 void *
729 xmalloc (size_t size)
731 void *val;
733 MALLOC_BLOCK_INPUT;
734 val = malloc (size);
735 MALLOC_UNBLOCK_INPUT;
737 if (!val && size)
738 memory_full (size);
739 return val;
742 /* Like the above, but zeroes out the memory just allocated. */
744 void *
745 xzalloc (size_t size)
747 void *val;
749 MALLOC_BLOCK_INPUT;
750 val = malloc (size);
751 MALLOC_UNBLOCK_INPUT;
753 if (!val && size)
754 memory_full (size);
755 memset (val, 0, size);
756 return val;
759 /* Like realloc but check for no memory and block interrupt input.. */
761 void *
762 xrealloc (void *block, size_t size)
764 void *val;
766 MALLOC_BLOCK_INPUT;
767 /* We must call malloc explicitly when BLOCK is 0, since some
768 reallocs don't do this. */
769 if (! block)
770 val = malloc (size);
771 else
772 val = realloc (block, size);
773 MALLOC_UNBLOCK_INPUT;
775 if (!val && size)
776 memory_full (size);
777 return val;
781 /* Like free but block interrupt input. */
783 void
784 xfree (void *block)
786 if (!block)
787 return;
788 MALLOC_BLOCK_INPUT;
789 free (block);
790 MALLOC_UNBLOCK_INPUT;
791 /* We don't call refill_memory_reserve here
792 because that duplicates doing so in emacs_blocked_free
793 and the criterion should go there. */
797 /* Other parts of Emacs pass large int values to allocator functions
798 expecting ptrdiff_t. This is portable in practice, but check it to
799 be safe. */
800 verify (INT_MAX <= PTRDIFF_MAX);
803 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
804 Signal an error on memory exhaustion, and block interrupt input. */
806 void *
807 xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
809 eassert (0 <= nitems && 0 < item_size);
810 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
811 memory_full (SIZE_MAX);
812 return xmalloc (nitems * item_size);
816 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
817 Signal an error on memory exhaustion, and block interrupt input. */
819 void *
820 xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
822 eassert (0 <= nitems && 0 < item_size);
823 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
824 memory_full (SIZE_MAX);
825 return xrealloc (pa, nitems * item_size);
829 /* Grow PA, which points to an array of *NITEMS items, and return the
830 location of the reallocated array, updating *NITEMS to reflect its
831 new size. The new array will contain at least NITEMS_INCR_MIN more
832 items, but will not contain more than NITEMS_MAX items total.
833 ITEM_SIZE is the size of each item, in bytes.
835 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
836 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
837 infinity.
839 If PA is null, then allocate a new array instead of reallocating
840 the old one. Thus, to grow an array A without saving its old
841 contents, invoke xfree (A) immediately followed by xgrowalloc (0,
842 &NITEMS, ...).
844 Block interrupt input as needed. If memory exhaustion occurs, set
845 *NITEMS to zero if PA is null, and signal an error (i.e., do not
846 return). */
848 void *
849 xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
850 ptrdiff_t nitems_max, ptrdiff_t item_size)
852 /* The approximate size to use for initial small allocation
853 requests. This is the largest "small" request for the GNU C
854 library malloc. */
855 enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
857 /* If the array is tiny, grow it to about (but no greater than)
858 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%. */
859 ptrdiff_t n = *nitems;
860 ptrdiff_t tiny_max = DEFAULT_MXFAST / item_size - n;
861 ptrdiff_t half_again = n >> 1;
862 ptrdiff_t incr_estimate = max (tiny_max, half_again);
864 /* Adjust the increment according to three constraints: NITEMS_INCR_MIN,
865 NITEMS_MAX, and what the C language can represent safely. */
866 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / item_size;
867 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
868 ? nitems_max : C_language_max);
869 ptrdiff_t nitems_incr_max = n_max - n;
870 ptrdiff_t incr = max (nitems_incr_min, min (incr_estimate, nitems_incr_max));
872 eassert (0 < item_size && 0 < nitems_incr_min && 0 <= n && -1 <= nitems_max);
873 if (! pa)
874 *nitems = 0;
875 if (nitems_incr_max < incr)
876 memory_full (SIZE_MAX);
877 n += incr;
878 pa = xrealloc (pa, n * item_size);
879 *nitems = n;
880 return pa;
884 /* Like strdup, but uses xmalloc. */
886 char *
887 xstrdup (const char *s)
889 size_t len = strlen (s) + 1;
890 char *p = xmalloc (len);
891 memcpy (p, s, len);
892 return p;
896 /* Unwind for SAFE_ALLOCA */
898 Lisp_Object
899 safe_alloca_unwind (Lisp_Object arg)
901 register struct Lisp_Save_Value *p = XSAVE_VALUE (arg);
903 p->dogc = 0;
904 xfree (p->pointer);
905 p->pointer = 0;
906 free_misc (arg);
907 return Qnil;
911 /* Like malloc but used for allocating Lisp data. NBYTES is the
912 number of bytes to allocate, TYPE describes the intended use of the
913 allocated memory block (for strings, for conses, ...). */
915 #if ! USE_LSB_TAG
916 void *lisp_malloc_loser EXTERNALLY_VISIBLE;
917 #endif
919 static void *
920 lisp_malloc (size_t nbytes, enum mem_type type)
922 register void *val;
924 MALLOC_BLOCK_INPUT;
926 #ifdef GC_MALLOC_CHECK
927 allocated_mem_type = type;
928 #endif
930 val = malloc (nbytes);
932 #if ! USE_LSB_TAG
933 /* If the memory just allocated cannot be addressed thru a Lisp
934 object's pointer, and it needs to be,
935 that's equivalent to running out of memory. */
936 if (val && type != MEM_TYPE_NON_LISP)
938 Lisp_Object tem;
939 XSETCONS (tem, (char *) val + nbytes - 1);
940 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
942 lisp_malloc_loser = val;
943 free (val);
944 val = 0;
947 #endif
949 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
950 if (val && type != MEM_TYPE_NON_LISP)
951 mem_insert (val, (char *) val + nbytes, type);
952 #endif
954 MALLOC_UNBLOCK_INPUT;
955 if (!val && nbytes)
956 memory_full (nbytes);
957 return val;
960 /* Free BLOCK. This must be called to free memory allocated with a
961 call to lisp_malloc. */
963 static void
964 lisp_free (void *block)
966 MALLOC_BLOCK_INPUT;
967 free (block);
968 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
969 mem_delete (mem_find (block));
970 #endif
971 MALLOC_UNBLOCK_INPUT;
974 /***** Allocation of aligned blocks of memory to store Lisp data. *****/
976 /* The entry point is lisp_align_malloc which returns blocks of at most
977 BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
979 #if defined (HAVE_POSIX_MEMALIGN) && defined (SYSTEM_MALLOC)
980 #define USE_POSIX_MEMALIGN 1
981 #endif
983 /* BLOCK_ALIGN has to be a power of 2. */
984 #define BLOCK_ALIGN (1 << 10)
986 /* Padding to leave at the end of a malloc'd block. This is to give
987 malloc a chance to minimize the amount of memory wasted to alignment.
988 It should be tuned to the particular malloc library used.
989 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
990 posix_memalign on the other hand would ideally prefer a value of 4
991 because otherwise, there's 1020 bytes wasted between each ablocks.
992 In Emacs, testing shows that those 1020 can most of the time be
993 efficiently used by malloc to place other objects, so a value of 0 can
994 still preferable unless you have a lot of aligned blocks and virtually
995 nothing else. */
996 #define BLOCK_PADDING 0
997 #define BLOCK_BYTES \
998 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
1000 /* Internal data structures and constants. */
1002 #define ABLOCKS_SIZE 16
1004 /* An aligned block of memory. */
1005 struct ablock
1007 union
1009 char payload[BLOCK_BYTES];
1010 struct ablock *next_free;
1011 } x;
1012 /* `abase' is the aligned base of the ablocks. */
1013 /* It is overloaded to hold the virtual `busy' field that counts
1014 the number of used ablock in the parent ablocks.
1015 The first ablock has the `busy' field, the others have the `abase'
1016 field. To tell the difference, we assume that pointers will have
1017 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
1018 is used to tell whether the real base of the parent ablocks is `abase'
1019 (if not, the word before the first ablock holds a pointer to the
1020 real base). */
1021 struct ablocks *abase;
1022 /* The padding of all but the last ablock is unused. The padding of
1023 the last ablock in an ablocks is not allocated. */
1024 #if BLOCK_PADDING
1025 char padding[BLOCK_PADDING];
1026 #endif
1029 /* A bunch of consecutive aligned blocks. */
1030 struct ablocks
1032 struct ablock blocks[ABLOCKS_SIZE];
1035 /* Size of the block requested from malloc or posix_memalign. */
1036 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
1038 #define ABLOCK_ABASE(block) \
1039 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
1040 ? (struct ablocks *)(block) \
1041 : (block)->abase)
1043 /* Virtual `busy' field. */
1044 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
1046 /* Pointer to the (not necessarily aligned) malloc block. */
1047 #ifdef USE_POSIX_MEMALIGN
1048 #define ABLOCKS_BASE(abase) (abase)
1049 #else
1050 #define ABLOCKS_BASE(abase) \
1051 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void**)abase)[-1])
1052 #endif
1054 /* The list of free ablock. */
1055 static struct ablock *free_ablock;
1057 /* Allocate an aligned block of nbytes.
1058 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
1059 smaller or equal to BLOCK_BYTES. */
1060 static void *
1061 lisp_align_malloc (size_t nbytes, enum mem_type type)
1063 void *base, *val;
1064 struct ablocks *abase;
1066 eassert (nbytes <= BLOCK_BYTES);
1068 MALLOC_BLOCK_INPUT;
1070 #ifdef GC_MALLOC_CHECK
1071 allocated_mem_type = type;
1072 #endif
1074 if (!free_ablock)
1076 int i;
1077 intptr_t aligned; /* int gets warning casting to 64-bit pointer. */
1079 #ifdef DOUG_LEA_MALLOC
1080 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1081 because mapped region contents are not preserved in
1082 a dumped Emacs. */
1083 mallopt (M_MMAP_MAX, 0);
1084 #endif
1086 #ifdef USE_POSIX_MEMALIGN
1088 int err = posix_memalign (&base, BLOCK_ALIGN, ABLOCKS_BYTES);
1089 if (err)
1090 base = NULL;
1091 abase = base;
1093 #else
1094 base = malloc (ABLOCKS_BYTES);
1095 abase = ALIGN (base, BLOCK_ALIGN);
1096 #endif
1098 if (base == 0)
1100 MALLOC_UNBLOCK_INPUT;
1101 memory_full (ABLOCKS_BYTES);
1104 aligned = (base == abase);
1105 if (!aligned)
1106 ((void**)abase)[-1] = base;
1108 #ifdef DOUG_LEA_MALLOC
1109 /* Back to a reasonable maximum of mmap'ed areas. */
1110 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1111 #endif
1113 #if ! USE_LSB_TAG
1114 /* If the memory just allocated cannot be addressed thru a Lisp
1115 object's pointer, and it needs to be, that's equivalent to
1116 running out of memory. */
1117 if (type != MEM_TYPE_NON_LISP)
1119 Lisp_Object tem;
1120 char *end = (char *) base + ABLOCKS_BYTES - 1;
1121 XSETCONS (tem, end);
1122 if ((char *) XCONS (tem) != end)
1124 lisp_malloc_loser = base;
1125 free (base);
1126 MALLOC_UNBLOCK_INPUT;
1127 memory_full (SIZE_MAX);
1130 #endif
1132 /* Initialize the blocks and put them on the free list.
1133 If `base' was not properly aligned, we can't use the last block. */
1134 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1136 abase->blocks[i].abase = abase;
1137 abase->blocks[i].x.next_free = free_ablock;
1138 free_ablock = &abase->blocks[i];
1140 ABLOCKS_BUSY (abase) = (struct ablocks *) aligned;
1142 eassert (0 == ((uintptr_t) abase) % BLOCK_ALIGN);
1143 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1144 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1145 eassert (ABLOCKS_BASE (abase) == base);
1146 eassert (aligned == (intptr_t) ABLOCKS_BUSY (abase));
1149 abase = ABLOCK_ABASE (free_ablock);
1150 ABLOCKS_BUSY (abase) =
1151 (struct ablocks *) (2 + (intptr_t) ABLOCKS_BUSY (abase));
1152 val = free_ablock;
1153 free_ablock = free_ablock->x.next_free;
1155 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1156 if (type != MEM_TYPE_NON_LISP)
1157 mem_insert (val, (char *) val + nbytes, type);
1158 #endif
1160 MALLOC_UNBLOCK_INPUT;
1162 eassert (0 == ((uintptr_t) val) % BLOCK_ALIGN);
1163 return val;
1166 static void
1167 lisp_align_free (void *block)
1169 struct ablock *ablock = block;
1170 struct ablocks *abase = ABLOCK_ABASE (ablock);
1172 MALLOC_BLOCK_INPUT;
1173 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1174 mem_delete (mem_find (block));
1175 #endif
1176 /* Put on free list. */
1177 ablock->x.next_free = free_ablock;
1178 free_ablock = ablock;
1179 /* Update busy count. */
1180 ABLOCKS_BUSY (abase)
1181 = (struct ablocks *) (-2 + (intptr_t) ABLOCKS_BUSY (abase));
1183 if (2 > (intptr_t) ABLOCKS_BUSY (abase))
1184 { /* All the blocks are free. */
1185 int i = 0, aligned = (intptr_t) ABLOCKS_BUSY (abase);
1186 struct ablock **tem = &free_ablock;
1187 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1189 while (*tem)
1191 if (*tem >= (struct ablock *) abase && *tem < atop)
1193 i++;
1194 *tem = (*tem)->x.next_free;
1196 else
1197 tem = &(*tem)->x.next_free;
1199 eassert ((aligned & 1) == aligned);
1200 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1201 #ifdef USE_POSIX_MEMALIGN
1202 eassert ((uintptr_t) ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1203 #endif
1204 free (ABLOCKS_BASE (abase));
1206 MALLOC_UNBLOCK_INPUT;
1210 #ifndef SYSTEM_MALLOC
1212 /* Arranging to disable input signals while we're in malloc.
1214 This only works with GNU malloc. To help out systems which can't
1215 use GNU malloc, all the calls to malloc, realloc, and free
1216 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
1217 pair; unfortunately, we have no idea what C library functions
1218 might call malloc, so we can't really protect them unless you're
1219 using GNU malloc. Fortunately, most of the major operating systems
1220 can use GNU malloc. */
1222 #ifndef SYNC_INPUT
1223 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
1224 there's no need to block input around malloc. */
1226 #ifndef DOUG_LEA_MALLOC
1227 extern void * (*__malloc_hook) (size_t, const void *);
1228 extern void * (*__realloc_hook) (void *, size_t, const void *);
1229 extern void (*__free_hook) (void *, const void *);
1230 /* Else declared in malloc.h, perhaps with an extra arg. */
1231 #endif /* DOUG_LEA_MALLOC */
1232 static void * (*old_malloc_hook) (size_t, const void *);
1233 static void * (*old_realloc_hook) (void *, size_t, const void*);
1234 static void (*old_free_hook) (void*, const void*);
1236 #ifdef DOUG_LEA_MALLOC
1237 # define BYTES_USED (mallinfo ().uordblks)
1238 #else
1239 # define BYTES_USED _bytes_used
1240 #endif
1242 #ifdef GC_MALLOC_CHECK
1243 static int dont_register_blocks;
1244 #endif
1246 static size_t bytes_used_when_reconsidered;
1248 /* Value of _bytes_used, when spare_memory was freed. */
1250 static size_t bytes_used_when_full;
1252 /* This function is used as the hook for free to call. */
1254 static void
1255 emacs_blocked_free (void *ptr, const void *ptr2)
1257 BLOCK_INPUT_ALLOC;
1259 #ifdef GC_MALLOC_CHECK
1260 if (ptr)
1262 struct mem_node *m;
1264 m = mem_find (ptr);
1265 if (m == MEM_NIL || m->start != ptr)
1267 fprintf (stderr,
1268 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
1269 abort ();
1271 else
1273 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
1274 mem_delete (m);
1277 #endif /* GC_MALLOC_CHECK */
1279 __free_hook = old_free_hook;
1280 free (ptr);
1282 /* If we released our reserve (due to running out of memory),
1283 and we have a fair amount free once again,
1284 try to set aside another reserve in case we run out once more. */
1285 if (! NILP (Vmemory_full)
1286 /* Verify there is enough space that even with the malloc
1287 hysteresis this call won't run out again.
1288 The code here is correct as long as SPARE_MEMORY
1289 is substantially larger than the block size malloc uses. */
1290 && (bytes_used_when_full
1291 > ((bytes_used_when_reconsidered = BYTES_USED)
1292 + max (malloc_hysteresis, 4) * SPARE_MEMORY)))
1293 refill_memory_reserve ();
1295 __free_hook = emacs_blocked_free;
1296 UNBLOCK_INPUT_ALLOC;
1300 /* This function is the malloc hook that Emacs uses. */
1302 static void *
1303 emacs_blocked_malloc (size_t size, const void *ptr)
1305 void *value;
1307 BLOCK_INPUT_ALLOC;
1308 __malloc_hook = old_malloc_hook;
1309 #ifdef DOUG_LEA_MALLOC
1310 /* Segfaults on my system. --lorentey */
1311 /* mallopt (M_TOP_PAD, malloc_hysteresis * 4096); */
1312 #else
1313 __malloc_extra_blocks = malloc_hysteresis;
1314 #endif
1316 value = malloc (size);
1318 #ifdef GC_MALLOC_CHECK
1320 struct mem_node *m = mem_find (value);
1321 if (m != MEM_NIL)
1323 fprintf (stderr, "Malloc returned %p which is already in use\n",
1324 value);
1325 fprintf (stderr, "Region in use is %p...%p, %td bytes, type %d\n",
1326 m->start, m->end, (char *) m->end - (char *) m->start,
1327 m->type);
1328 abort ();
1331 if (!dont_register_blocks)
1333 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
1334 allocated_mem_type = MEM_TYPE_NON_LISP;
1337 #endif /* GC_MALLOC_CHECK */
1339 __malloc_hook = emacs_blocked_malloc;
1340 UNBLOCK_INPUT_ALLOC;
1342 /* fprintf (stderr, "%p malloc\n", value); */
1343 return value;
1347 /* This function is the realloc hook that Emacs uses. */
1349 static void *
1350 emacs_blocked_realloc (void *ptr, size_t size, const void *ptr2)
1352 void *value;
1354 BLOCK_INPUT_ALLOC;
1355 __realloc_hook = old_realloc_hook;
1357 #ifdef GC_MALLOC_CHECK
1358 if (ptr)
1360 struct mem_node *m = mem_find (ptr);
1361 if (m == MEM_NIL || m->start != ptr)
1363 fprintf (stderr,
1364 "Realloc of %p which wasn't allocated with malloc\n",
1365 ptr);
1366 abort ();
1369 mem_delete (m);
1372 /* fprintf (stderr, "%p -> realloc\n", ptr); */
1374 /* Prevent malloc from registering blocks. */
1375 dont_register_blocks = 1;
1376 #endif /* GC_MALLOC_CHECK */
1378 value = realloc (ptr, size);
1380 #ifdef GC_MALLOC_CHECK
1381 dont_register_blocks = 0;
1384 struct mem_node *m = mem_find (value);
1385 if (m != MEM_NIL)
1387 fprintf (stderr, "Realloc returns memory that is already in use\n");
1388 abort ();
1391 /* Can't handle zero size regions in the red-black tree. */
1392 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
1395 /* fprintf (stderr, "%p <- realloc\n", value); */
1396 #endif /* GC_MALLOC_CHECK */
1398 __realloc_hook = emacs_blocked_realloc;
1399 UNBLOCK_INPUT_ALLOC;
1401 return value;
1405 #ifdef HAVE_PTHREAD
1406 /* Called from Fdump_emacs so that when the dumped Emacs starts, it has a
1407 normal malloc. Some thread implementations need this as they call
1408 malloc before main. The pthread_self call in BLOCK_INPUT_ALLOC then
1409 calls malloc because it is the first call, and we have an endless loop. */
1411 void
1412 reset_malloc_hooks (void)
1414 __free_hook = old_free_hook;
1415 __malloc_hook = old_malloc_hook;
1416 __realloc_hook = old_realloc_hook;
1418 #endif /* HAVE_PTHREAD */
1421 /* Called from main to set up malloc to use our hooks. */
1423 void
1424 uninterrupt_malloc (void)
1426 #ifdef HAVE_PTHREAD
1427 #ifdef DOUG_LEA_MALLOC
1428 pthread_mutexattr_t attr;
1430 /* GLIBC has a faster way to do this, but let's keep it portable.
1431 This is according to the Single UNIX Specification. */
1432 pthread_mutexattr_init (&attr);
1433 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1434 pthread_mutex_init (&alloc_mutex, &attr);
1435 #else /* !DOUG_LEA_MALLOC */
1436 /* Some systems such as Solaris 2.6 don't have a recursive mutex,
1437 and the bundled gmalloc.c doesn't require it. */
1438 pthread_mutex_init (&alloc_mutex, NULL);
1439 #endif /* !DOUG_LEA_MALLOC */
1440 #endif /* HAVE_PTHREAD */
1442 if (__free_hook != emacs_blocked_free)
1443 old_free_hook = __free_hook;
1444 __free_hook = emacs_blocked_free;
1446 if (__malloc_hook != emacs_blocked_malloc)
1447 old_malloc_hook = __malloc_hook;
1448 __malloc_hook = emacs_blocked_malloc;
1450 if (__realloc_hook != emacs_blocked_realloc)
1451 old_realloc_hook = __realloc_hook;
1452 __realloc_hook = emacs_blocked_realloc;
1455 #endif /* not SYNC_INPUT */
1456 #endif /* not SYSTEM_MALLOC */
1460 /***********************************************************************
1461 Interval Allocation
1462 ***********************************************************************/
1464 /* Number of intervals allocated in an interval_block structure.
1465 The 1020 is 1024 minus malloc overhead. */
1467 #define INTERVAL_BLOCK_SIZE \
1468 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1470 /* Intervals are allocated in chunks in form of an interval_block
1471 structure. */
1473 struct interval_block
1475 /* Place `intervals' first, to preserve alignment. */
1476 struct interval intervals[INTERVAL_BLOCK_SIZE];
1477 struct interval_block *next;
1480 /* Current interval block. Its `next' pointer points to older
1481 blocks. */
1483 static struct interval_block *interval_block;
1485 /* Index in interval_block above of the next unused interval
1486 structure. */
1488 static int interval_block_index = INTERVAL_BLOCK_SIZE;
1490 /* Number of free and live intervals. */
1492 static EMACS_INT total_free_intervals, total_intervals;
1494 /* List of free intervals. */
1496 static INTERVAL interval_free_list;
1498 /* Return a new interval. */
1500 INTERVAL
1501 make_interval (void)
1503 INTERVAL val;
1505 /* eassert (!handling_signal); */
1507 MALLOC_BLOCK_INPUT;
1509 if (interval_free_list)
1511 val = interval_free_list;
1512 interval_free_list = INTERVAL_PARENT (interval_free_list);
1514 else
1516 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1518 struct interval_block *newi
1519 = lisp_malloc (sizeof *newi, MEM_TYPE_NON_LISP);
1521 newi->next = interval_block;
1522 interval_block = newi;
1523 interval_block_index = 0;
1524 total_free_intervals += INTERVAL_BLOCK_SIZE;
1526 val = &interval_block->intervals[interval_block_index++];
1529 MALLOC_UNBLOCK_INPUT;
1531 consing_since_gc += sizeof (struct interval);
1532 intervals_consed++;
1533 total_free_intervals--;
1534 RESET_INTERVAL (val);
1535 val->gcmarkbit = 0;
1536 return val;
1540 /* Mark Lisp objects in interval I. */
1542 static void
1543 mark_interval (register INTERVAL i, Lisp_Object dummy)
1545 /* Intervals should never be shared. So, if extra internal checking is
1546 enabled, GC aborts if it seems to have visited an interval twice. */
1547 eassert (!i->gcmarkbit);
1548 i->gcmarkbit = 1;
1549 mark_object (i->plist);
1553 /* Mark the interval tree rooted in TREE. Don't call this directly;
1554 use the macro MARK_INTERVAL_TREE instead. */
1556 static void
1557 mark_interval_tree (register INTERVAL tree)
1559 /* No need to test if this tree has been marked already; this
1560 function is always called through the MARK_INTERVAL_TREE macro,
1561 which takes care of that. */
1563 traverse_intervals_noorder (tree, mark_interval, Qnil);
1567 /* Mark the interval tree rooted in I. */
1569 #define MARK_INTERVAL_TREE(i) \
1570 do { \
1571 if (!NULL_INTERVAL_P (i) && !i->gcmarkbit) \
1572 mark_interval_tree (i); \
1573 } while (0)
1576 #define UNMARK_BALANCE_INTERVALS(i) \
1577 do { \
1578 if (! NULL_INTERVAL_P (i)) \
1579 (i) = balance_intervals (i); \
1580 } while (0)
1582 /***********************************************************************
1583 String Allocation
1584 ***********************************************************************/
1586 /* Lisp_Strings are allocated in string_block structures. When a new
1587 string_block is allocated, all the Lisp_Strings it contains are
1588 added to a free-list string_free_list. When a new Lisp_String is
1589 needed, it is taken from that list. During the sweep phase of GC,
1590 string_blocks that are entirely free are freed, except two which
1591 we keep.
1593 String data is allocated from sblock structures. Strings larger
1594 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1595 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1597 Sblocks consist internally of sdata structures, one for each
1598 Lisp_String. The sdata structure points to the Lisp_String it
1599 belongs to. The Lisp_String points back to the `u.data' member of
1600 its sdata structure.
1602 When a Lisp_String is freed during GC, it is put back on
1603 string_free_list, and its `data' member and its sdata's `string'
1604 pointer is set to null. The size of the string is recorded in the
1605 `u.nbytes' member of the sdata. So, sdata structures that are no
1606 longer used, can be easily recognized, and it's easy to compact the
1607 sblocks of small strings which we do in compact_small_strings. */
1609 /* Size in bytes of an sblock structure used for small strings. This
1610 is 8192 minus malloc overhead. */
1612 #define SBLOCK_SIZE 8188
1614 /* Strings larger than this are considered large strings. String data
1615 for large strings is allocated from individual sblocks. */
1617 #define LARGE_STRING_BYTES 1024
1619 /* Structure describing string memory sub-allocated from an sblock.
1620 This is where the contents of Lisp strings are stored. */
1622 struct sdata
1624 /* Back-pointer to the string this sdata belongs to. If null, this
1625 structure is free, and the NBYTES member of the union below
1626 contains the string's byte size (the same value that STRING_BYTES
1627 would return if STRING were non-null). If non-null, STRING_BYTES
1628 (STRING) is the size of the data, and DATA contains the string's
1629 contents. */
1630 struct Lisp_String *string;
1632 #ifdef GC_CHECK_STRING_BYTES
1634 ptrdiff_t nbytes;
1635 unsigned char data[1];
1637 #define SDATA_NBYTES(S) (S)->nbytes
1638 #define SDATA_DATA(S) (S)->data
1639 #define SDATA_SELECTOR(member) member
1641 #else /* not GC_CHECK_STRING_BYTES */
1643 union
1645 /* When STRING is non-null. */
1646 unsigned char data[1];
1648 /* When STRING is null. */
1649 ptrdiff_t nbytes;
1650 } u;
1652 #define SDATA_NBYTES(S) (S)->u.nbytes
1653 #define SDATA_DATA(S) (S)->u.data
1654 #define SDATA_SELECTOR(member) u.member
1656 #endif /* not GC_CHECK_STRING_BYTES */
1658 #define SDATA_DATA_OFFSET offsetof (struct sdata, SDATA_SELECTOR (data))
1662 /* Structure describing a block of memory which is sub-allocated to
1663 obtain string data memory for strings. Blocks for small strings
1664 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1665 as large as needed. */
1667 struct sblock
1669 /* Next in list. */
1670 struct sblock *next;
1672 /* Pointer to the next free sdata block. This points past the end
1673 of the sblock if there isn't any space left in this block. */
1674 struct sdata *next_free;
1676 /* Start of data. */
1677 struct sdata first_data;
1680 /* Number of Lisp strings in a string_block structure. The 1020 is
1681 1024 minus malloc overhead. */
1683 #define STRING_BLOCK_SIZE \
1684 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1686 /* Structure describing a block from which Lisp_String structures
1687 are allocated. */
1689 struct string_block
1691 /* Place `strings' first, to preserve alignment. */
1692 struct Lisp_String strings[STRING_BLOCK_SIZE];
1693 struct string_block *next;
1696 /* Head and tail of the list of sblock structures holding Lisp string
1697 data. We always allocate from current_sblock. The NEXT pointers
1698 in the sblock structures go from oldest_sblock to current_sblock. */
1700 static struct sblock *oldest_sblock, *current_sblock;
1702 /* List of sblocks for large strings. */
1704 static struct sblock *large_sblocks;
1706 /* List of string_block structures. */
1708 static struct string_block *string_blocks;
1710 /* Free-list of Lisp_Strings. */
1712 static struct Lisp_String *string_free_list;
1714 /* Number of live and free Lisp_Strings. */
1716 static EMACS_INT total_strings, total_free_strings;
1718 /* Number of bytes used by live strings. */
1720 static EMACS_INT total_string_bytes;
1722 /* Given a pointer to a Lisp_String S which is on the free-list
1723 string_free_list, return a pointer to its successor in the
1724 free-list. */
1726 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1728 /* Return a pointer to the sdata structure belonging to Lisp string S.
1729 S must be live, i.e. S->data must not be null. S->data is actually
1730 a pointer to the `u.data' member of its sdata structure; the
1731 structure starts at a constant offset in front of that. */
1733 #define SDATA_OF_STRING(S) ((struct sdata *) ((S)->data - SDATA_DATA_OFFSET))
1736 #ifdef GC_CHECK_STRING_OVERRUN
1738 /* We check for overrun in string data blocks by appending a small
1739 "cookie" after each allocated string data block, and check for the
1740 presence of this cookie during GC. */
1742 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1743 static char const string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1744 { '\xde', '\xad', '\xbe', '\xef' };
1746 #else
1747 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1748 #endif
1750 /* Value is the size of an sdata structure large enough to hold NBYTES
1751 bytes of string data. The value returned includes a terminating
1752 NUL byte, the size of the sdata structure, and padding. */
1754 #ifdef GC_CHECK_STRING_BYTES
1756 #define SDATA_SIZE(NBYTES) \
1757 ((SDATA_DATA_OFFSET \
1758 + (NBYTES) + 1 \
1759 + sizeof (ptrdiff_t) - 1) \
1760 & ~(sizeof (ptrdiff_t) - 1))
1762 #else /* not GC_CHECK_STRING_BYTES */
1764 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1765 less than the size of that member. The 'max' is not needed when
1766 SDATA_DATA_OFFSET is a multiple of sizeof (ptrdiff_t), because then the
1767 alignment code reserves enough space. */
1769 #define SDATA_SIZE(NBYTES) \
1770 ((SDATA_DATA_OFFSET \
1771 + (SDATA_DATA_OFFSET % sizeof (ptrdiff_t) == 0 \
1772 ? NBYTES \
1773 : max (NBYTES, sizeof (ptrdiff_t) - 1)) \
1774 + 1 \
1775 + sizeof (ptrdiff_t) - 1) \
1776 & ~(sizeof (ptrdiff_t) - 1))
1778 #endif /* not GC_CHECK_STRING_BYTES */
1780 /* Extra bytes to allocate for each string. */
1782 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1784 /* Exact bound on the number of bytes in a string, not counting the
1785 terminating null. A string cannot contain more bytes than
1786 STRING_BYTES_BOUND, nor can it be so long that the size_t
1787 arithmetic in allocate_string_data would overflow while it is
1788 calculating a value to be passed to malloc. */
1789 #define STRING_BYTES_MAX \
1790 min (STRING_BYTES_BOUND, \
1791 ((SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD \
1792 - GC_STRING_EXTRA \
1793 - offsetof (struct sblock, first_data) \
1794 - SDATA_DATA_OFFSET) \
1795 & ~(sizeof (EMACS_INT) - 1)))
1797 /* Initialize string allocation. Called from init_alloc_once. */
1799 static void
1800 init_strings (void)
1802 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1803 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1807 #ifdef GC_CHECK_STRING_BYTES
1809 static int check_string_bytes_count;
1811 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1814 /* Like GC_STRING_BYTES, but with debugging check. */
1816 ptrdiff_t
1817 string_bytes (struct Lisp_String *s)
1819 ptrdiff_t nbytes =
1820 (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1822 if (!PURE_POINTER_P (s)
1823 && s->data
1824 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1825 abort ();
1826 return nbytes;
1829 /* Check validity of Lisp strings' string_bytes member in B. */
1831 static void
1832 check_sblock (struct sblock *b)
1834 struct sdata *from, *end, *from_end;
1836 end = b->next_free;
1838 for (from = &b->first_data; from < end; from = from_end)
1840 /* Compute the next FROM here because copying below may
1841 overwrite data we need to compute it. */
1842 ptrdiff_t nbytes;
1844 /* Check that the string size recorded in the string is the
1845 same as the one recorded in the sdata structure. */
1846 if (from->string)
1847 CHECK_STRING_BYTES (from->string);
1849 if (from->string)
1850 nbytes = GC_STRING_BYTES (from->string);
1851 else
1852 nbytes = SDATA_NBYTES (from);
1854 nbytes = SDATA_SIZE (nbytes);
1855 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1860 /* Check validity of Lisp strings' string_bytes member. ALL_P
1861 non-zero means check all strings, otherwise check only most
1862 recently allocated strings. Used for hunting a bug. */
1864 static void
1865 check_string_bytes (int all_p)
1867 if (all_p)
1869 struct sblock *b;
1871 for (b = large_sblocks; b; b = b->next)
1873 struct Lisp_String *s = b->first_data.string;
1874 if (s)
1875 CHECK_STRING_BYTES (s);
1878 for (b = oldest_sblock; b; b = b->next)
1879 check_sblock (b);
1881 else if (current_sblock)
1882 check_sblock (current_sblock);
1885 #endif /* GC_CHECK_STRING_BYTES */
1887 #ifdef GC_CHECK_STRING_FREE_LIST
1889 /* Walk through the string free list looking for bogus next pointers.
1890 This may catch buffer overrun from a previous string. */
1892 static void
1893 check_string_free_list (void)
1895 struct Lisp_String *s;
1897 /* Pop a Lisp_String off the free-list. */
1898 s = string_free_list;
1899 while (s != NULL)
1901 if ((uintptr_t) s < 1024)
1902 abort ();
1903 s = NEXT_FREE_LISP_STRING (s);
1906 #else
1907 #define check_string_free_list()
1908 #endif
1910 /* Return a new Lisp_String. */
1912 static struct Lisp_String *
1913 allocate_string (void)
1915 struct Lisp_String *s;
1917 /* eassert (!handling_signal); */
1919 MALLOC_BLOCK_INPUT;
1921 /* If the free-list is empty, allocate a new string_block, and
1922 add all the Lisp_Strings in it to the free-list. */
1923 if (string_free_list == NULL)
1925 struct string_block *b = lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1926 int i;
1928 b->next = string_blocks;
1929 string_blocks = b;
1931 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1933 s = b->strings + i;
1934 /* Every string on a free list should have NULL data pointer. */
1935 s->data = NULL;
1936 NEXT_FREE_LISP_STRING (s) = string_free_list;
1937 string_free_list = s;
1940 total_free_strings += STRING_BLOCK_SIZE;
1943 check_string_free_list ();
1945 /* Pop a Lisp_String off the free-list. */
1946 s = string_free_list;
1947 string_free_list = NEXT_FREE_LISP_STRING (s);
1949 MALLOC_UNBLOCK_INPUT;
1951 --total_free_strings;
1952 ++total_strings;
1953 ++strings_consed;
1954 consing_since_gc += sizeof *s;
1956 #ifdef GC_CHECK_STRING_BYTES
1957 if (!noninteractive)
1959 if (++check_string_bytes_count == 200)
1961 check_string_bytes_count = 0;
1962 check_string_bytes (1);
1964 else
1965 check_string_bytes (0);
1967 #endif /* GC_CHECK_STRING_BYTES */
1969 return s;
1973 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1974 plus a NUL byte at the end. Allocate an sdata structure for S, and
1975 set S->data to its `u.data' member. Store a NUL byte at the end of
1976 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1977 S->data if it was initially non-null. */
1979 void
1980 allocate_string_data (struct Lisp_String *s,
1981 EMACS_INT nchars, EMACS_INT nbytes)
1983 struct sdata *data, *old_data;
1984 struct sblock *b;
1985 ptrdiff_t needed, old_nbytes;
1987 if (STRING_BYTES_MAX < nbytes)
1988 string_overflow ();
1990 /* Determine the number of bytes needed to store NBYTES bytes
1991 of string data. */
1992 needed = SDATA_SIZE (nbytes);
1993 if (s->data)
1995 old_data = SDATA_OF_STRING (s);
1996 old_nbytes = GC_STRING_BYTES (s);
1998 else
1999 old_data = NULL;
2001 MALLOC_BLOCK_INPUT;
2003 if (nbytes > LARGE_STRING_BYTES)
2005 size_t size = offsetof (struct sblock, first_data) + needed;
2007 #ifdef DOUG_LEA_MALLOC
2008 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2009 because mapped region contents are not preserved in
2010 a dumped Emacs.
2012 In case you think of allowing it in a dumped Emacs at the
2013 cost of not being able to re-dump, there's another reason:
2014 mmap'ed data typically have an address towards the top of the
2015 address space, which won't fit into an EMACS_INT (at least on
2016 32-bit systems with the current tagging scheme). --fx */
2017 mallopt (M_MMAP_MAX, 0);
2018 #endif
2020 b = lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
2022 #ifdef DOUG_LEA_MALLOC
2023 /* Back to a reasonable maximum of mmap'ed areas. */
2024 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2025 #endif
2027 b->next_free = &b->first_data;
2028 b->first_data.string = NULL;
2029 b->next = large_sblocks;
2030 large_sblocks = b;
2032 else if (current_sblock == NULL
2033 || (((char *) current_sblock + SBLOCK_SIZE
2034 - (char *) current_sblock->next_free)
2035 < (needed + GC_STRING_EXTRA)))
2037 /* Not enough room in the current sblock. */
2038 b = lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
2039 b->next_free = &b->first_data;
2040 b->first_data.string = NULL;
2041 b->next = NULL;
2043 if (current_sblock)
2044 current_sblock->next = b;
2045 else
2046 oldest_sblock = b;
2047 current_sblock = b;
2049 else
2050 b = current_sblock;
2052 data = b->next_free;
2053 b->next_free = (struct sdata *) ((char *) data + needed + GC_STRING_EXTRA);
2055 MALLOC_UNBLOCK_INPUT;
2057 data->string = s;
2058 s->data = SDATA_DATA (data);
2059 #ifdef GC_CHECK_STRING_BYTES
2060 SDATA_NBYTES (data) = nbytes;
2061 #endif
2062 s->size = nchars;
2063 s->size_byte = nbytes;
2064 s->data[nbytes] = '\0';
2065 #ifdef GC_CHECK_STRING_OVERRUN
2066 memcpy ((char *) data + needed, string_overrun_cookie,
2067 GC_STRING_OVERRUN_COOKIE_SIZE);
2068 #endif
2070 /* Note that Faset may call to this function when S has already data
2071 assigned. In this case, mark data as free by setting it's string
2072 back-pointer to null, and record the size of the data in it. */
2073 if (old_data)
2075 SDATA_NBYTES (old_data) = old_nbytes;
2076 old_data->string = NULL;
2079 consing_since_gc += needed;
2083 /* Sweep and compact strings. */
2085 static void
2086 sweep_strings (void)
2088 struct string_block *b, *next;
2089 struct string_block *live_blocks = NULL;
2091 string_free_list = NULL;
2092 total_strings = total_free_strings = 0;
2093 total_string_bytes = 0;
2095 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
2096 for (b = string_blocks; b; b = next)
2098 int i, nfree = 0;
2099 struct Lisp_String *free_list_before = string_free_list;
2101 next = b->next;
2103 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
2105 struct Lisp_String *s = b->strings + i;
2107 if (s->data)
2109 /* String was not on free-list before. */
2110 if (STRING_MARKED_P (s))
2112 /* String is live; unmark it and its intervals. */
2113 UNMARK_STRING (s);
2115 if (!NULL_INTERVAL_P (s->intervals))
2116 UNMARK_BALANCE_INTERVALS (s->intervals);
2118 ++total_strings;
2119 total_string_bytes += STRING_BYTES (s);
2121 else
2123 /* String is dead. Put it on the free-list. */
2124 struct sdata *data = SDATA_OF_STRING (s);
2126 /* Save the size of S in its sdata so that we know
2127 how large that is. Reset the sdata's string
2128 back-pointer so that we know it's free. */
2129 #ifdef GC_CHECK_STRING_BYTES
2130 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
2131 abort ();
2132 #else
2133 data->u.nbytes = GC_STRING_BYTES (s);
2134 #endif
2135 data->string = NULL;
2137 /* Reset the strings's `data' member so that we
2138 know it's free. */
2139 s->data = NULL;
2141 /* Put the string on the free-list. */
2142 NEXT_FREE_LISP_STRING (s) = string_free_list;
2143 string_free_list = s;
2144 ++nfree;
2147 else
2149 /* S was on the free-list before. Put it there again. */
2150 NEXT_FREE_LISP_STRING (s) = string_free_list;
2151 string_free_list = s;
2152 ++nfree;
2156 /* Free blocks that contain free Lisp_Strings only, except
2157 the first two of them. */
2158 if (nfree == STRING_BLOCK_SIZE
2159 && total_free_strings > STRING_BLOCK_SIZE)
2161 lisp_free (b);
2162 string_free_list = free_list_before;
2164 else
2166 total_free_strings += nfree;
2167 b->next = live_blocks;
2168 live_blocks = b;
2172 check_string_free_list ();
2174 string_blocks = live_blocks;
2175 free_large_strings ();
2176 compact_small_strings ();
2178 check_string_free_list ();
2182 /* Free dead large strings. */
2184 static void
2185 free_large_strings (void)
2187 struct sblock *b, *next;
2188 struct sblock *live_blocks = NULL;
2190 for (b = large_sblocks; b; b = next)
2192 next = b->next;
2194 if (b->first_data.string == NULL)
2195 lisp_free (b);
2196 else
2198 b->next = live_blocks;
2199 live_blocks = b;
2203 large_sblocks = live_blocks;
2207 /* Compact data of small strings. Free sblocks that don't contain
2208 data of live strings after compaction. */
2210 static void
2211 compact_small_strings (void)
2213 struct sblock *b, *tb, *next;
2214 struct sdata *from, *to, *end, *tb_end;
2215 struct sdata *to_end, *from_end;
2217 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2218 to, and TB_END is the end of TB. */
2219 tb = oldest_sblock;
2220 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2221 to = &tb->first_data;
2223 /* Step through the blocks from the oldest to the youngest. We
2224 expect that old blocks will stabilize over time, so that less
2225 copying will happen this way. */
2226 for (b = oldest_sblock; b; b = b->next)
2228 end = b->next_free;
2229 eassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2231 for (from = &b->first_data; from < end; from = from_end)
2233 /* Compute the next FROM here because copying below may
2234 overwrite data we need to compute it. */
2235 ptrdiff_t nbytes;
2237 #ifdef GC_CHECK_STRING_BYTES
2238 /* Check that the string size recorded in the string is the
2239 same as the one recorded in the sdata structure. */
2240 if (from->string
2241 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
2242 abort ();
2243 #endif /* GC_CHECK_STRING_BYTES */
2245 if (from->string)
2246 nbytes = GC_STRING_BYTES (from->string);
2247 else
2248 nbytes = SDATA_NBYTES (from);
2250 if (nbytes > LARGE_STRING_BYTES)
2251 abort ();
2253 nbytes = SDATA_SIZE (nbytes);
2254 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
2256 #ifdef GC_CHECK_STRING_OVERRUN
2257 if (memcmp (string_overrun_cookie,
2258 (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
2259 GC_STRING_OVERRUN_COOKIE_SIZE))
2260 abort ();
2261 #endif
2263 /* FROM->string non-null means it's alive. Copy its data. */
2264 if (from->string)
2266 /* If TB is full, proceed with the next sblock. */
2267 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2268 if (to_end > tb_end)
2270 tb->next_free = to;
2271 tb = tb->next;
2272 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2273 to = &tb->first_data;
2274 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2277 /* Copy, and update the string's `data' pointer. */
2278 if (from != to)
2280 eassert (tb != b || to < from);
2281 memmove (to, from, nbytes + GC_STRING_EXTRA);
2282 to->string->data = SDATA_DATA (to);
2285 /* Advance past the sdata we copied to. */
2286 to = to_end;
2291 /* The rest of the sblocks following TB don't contain live data, so
2292 we can free them. */
2293 for (b = tb->next; b; b = next)
2295 next = b->next;
2296 lisp_free (b);
2299 tb->next_free = to;
2300 tb->next = NULL;
2301 current_sblock = tb;
2304 void
2305 string_overflow (void)
2307 error ("Maximum string size exceeded");
2310 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2311 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2312 LENGTH must be an integer.
2313 INIT must be an integer that represents a character. */)
2314 (Lisp_Object length, Lisp_Object init)
2316 register Lisp_Object val;
2317 register unsigned char *p, *end;
2318 int c;
2319 EMACS_INT nbytes;
2321 CHECK_NATNUM (length);
2322 CHECK_CHARACTER (init);
2324 c = XFASTINT (init);
2325 if (ASCII_CHAR_P (c))
2327 nbytes = XINT (length);
2328 val = make_uninit_string (nbytes);
2329 p = SDATA (val);
2330 end = p + SCHARS (val);
2331 while (p != end)
2332 *p++ = c;
2334 else
2336 unsigned char str[MAX_MULTIBYTE_LENGTH];
2337 int len = CHAR_STRING (c, str);
2338 EMACS_INT string_len = XINT (length);
2340 if (string_len > STRING_BYTES_MAX / len)
2341 string_overflow ();
2342 nbytes = len * string_len;
2343 val = make_uninit_multibyte_string (string_len, nbytes);
2344 p = SDATA (val);
2345 end = p + nbytes;
2346 while (p != end)
2348 memcpy (p, str, len);
2349 p += len;
2353 *p = 0;
2354 return val;
2358 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2359 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2360 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2361 (Lisp_Object length, Lisp_Object init)
2363 register Lisp_Object val;
2364 struct Lisp_Bool_Vector *p;
2365 ptrdiff_t length_in_chars;
2366 EMACS_INT length_in_elts;
2367 int bits_per_value;
2368 int extra_bool_elts = ((bool_header_size - header_size + word_size - 1)
2369 / word_size);
2371 CHECK_NATNUM (length);
2373 bits_per_value = sizeof (EMACS_INT) * BOOL_VECTOR_BITS_PER_CHAR;
2375 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
2377 val = Fmake_vector (make_number (length_in_elts + extra_bool_elts), Qnil);
2379 /* No Lisp_Object to trace in there. */
2380 XSETPVECTYPESIZE (XVECTOR (val), PVEC_BOOL_VECTOR, 0);
2382 p = XBOOL_VECTOR (val);
2383 p->size = XFASTINT (length);
2385 length_in_chars = ((XFASTINT (length) + BOOL_VECTOR_BITS_PER_CHAR - 1)
2386 / BOOL_VECTOR_BITS_PER_CHAR);
2387 if (length_in_chars)
2389 memset (p->data, ! NILP (init) ? -1 : 0, length_in_chars);
2391 /* Clear any extraneous bits in the last byte. */
2392 p->data[length_in_chars - 1]
2393 &= (1 << ((XFASTINT (length) - 1) % BOOL_VECTOR_BITS_PER_CHAR + 1)) - 1;
2396 return val;
2400 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2401 of characters from the contents. This string may be unibyte or
2402 multibyte, depending on the contents. */
2404 Lisp_Object
2405 make_string (const char *contents, ptrdiff_t nbytes)
2407 register Lisp_Object val;
2408 ptrdiff_t nchars, multibyte_nbytes;
2410 parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
2411 &nchars, &multibyte_nbytes);
2412 if (nbytes == nchars || nbytes != multibyte_nbytes)
2413 /* CONTENTS contains no multibyte sequences or contains an invalid
2414 multibyte sequence. We must make unibyte string. */
2415 val = make_unibyte_string (contents, nbytes);
2416 else
2417 val = make_multibyte_string (contents, nchars, nbytes);
2418 return val;
2422 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
2424 Lisp_Object
2425 make_unibyte_string (const char *contents, ptrdiff_t length)
2427 register Lisp_Object val;
2428 val = make_uninit_string (length);
2429 memcpy (SDATA (val), contents, length);
2430 return val;
2434 /* Make a multibyte string from NCHARS characters occupying NBYTES
2435 bytes at CONTENTS. */
2437 Lisp_Object
2438 make_multibyte_string (const char *contents,
2439 ptrdiff_t nchars, ptrdiff_t nbytes)
2441 register Lisp_Object val;
2442 val = make_uninit_multibyte_string (nchars, nbytes);
2443 memcpy (SDATA (val), contents, nbytes);
2444 return val;
2448 /* Make a string from NCHARS characters occupying NBYTES bytes at
2449 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2451 Lisp_Object
2452 make_string_from_bytes (const char *contents,
2453 ptrdiff_t nchars, ptrdiff_t nbytes)
2455 register Lisp_Object val;
2456 val = make_uninit_multibyte_string (nchars, nbytes);
2457 memcpy (SDATA (val), contents, nbytes);
2458 if (SBYTES (val) == SCHARS (val))
2459 STRING_SET_UNIBYTE (val);
2460 return val;
2464 /* Make a string from NCHARS characters occupying NBYTES bytes at
2465 CONTENTS. The argument MULTIBYTE controls whether to label the
2466 string as multibyte. If NCHARS is negative, it counts the number of
2467 characters by itself. */
2469 Lisp_Object
2470 make_specified_string (const char *contents,
2471 ptrdiff_t nchars, ptrdiff_t nbytes, int multibyte)
2473 register Lisp_Object val;
2475 if (nchars < 0)
2477 if (multibyte)
2478 nchars = multibyte_chars_in_text ((const unsigned char *) contents,
2479 nbytes);
2480 else
2481 nchars = nbytes;
2483 val = make_uninit_multibyte_string (nchars, nbytes);
2484 memcpy (SDATA (val), contents, nbytes);
2485 if (!multibyte)
2486 STRING_SET_UNIBYTE (val);
2487 return val;
2491 /* Return an unibyte Lisp_String set up to hold LENGTH characters
2492 occupying LENGTH bytes. */
2494 Lisp_Object
2495 make_uninit_string (EMACS_INT length)
2497 Lisp_Object val;
2499 if (!length)
2500 return empty_unibyte_string;
2501 val = make_uninit_multibyte_string (length, length);
2502 STRING_SET_UNIBYTE (val);
2503 return val;
2507 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2508 which occupy NBYTES bytes. */
2510 Lisp_Object
2511 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2513 Lisp_Object string;
2514 struct Lisp_String *s;
2516 if (nchars < 0)
2517 abort ();
2518 if (!nbytes)
2519 return empty_multibyte_string;
2521 s = allocate_string ();
2522 s->intervals = NULL_INTERVAL;
2523 allocate_string_data (s, nchars, nbytes);
2524 XSETSTRING (string, s);
2525 string_chars_consed += nbytes;
2526 return string;
2529 /* Print arguments to BUF according to a FORMAT, then return
2530 a Lisp_String initialized with the data from BUF. */
2532 Lisp_Object
2533 make_formatted_string (char *buf, const char *format, ...)
2535 va_list ap;
2536 int length;
2538 va_start (ap, format);
2539 length = vsprintf (buf, format, ap);
2540 va_end (ap);
2541 return make_string (buf, length);
2545 /***********************************************************************
2546 Float Allocation
2547 ***********************************************************************/
2549 /* We store float cells inside of float_blocks, allocating a new
2550 float_block with malloc whenever necessary. Float cells reclaimed
2551 by GC are put on a free list to be reallocated before allocating
2552 any new float cells from the latest float_block. */
2554 #define FLOAT_BLOCK_SIZE \
2555 (((BLOCK_BYTES - sizeof (struct float_block *) \
2556 /* The compiler might add padding at the end. */ \
2557 - (sizeof (struct Lisp_Float) - sizeof (int))) * CHAR_BIT) \
2558 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2560 #define GETMARKBIT(block,n) \
2561 (((block)->gcmarkbits[(n) / (sizeof (int) * CHAR_BIT)] \
2562 >> ((n) % (sizeof (int) * CHAR_BIT))) \
2563 & 1)
2565 #define SETMARKBIT(block,n) \
2566 (block)->gcmarkbits[(n) / (sizeof (int) * CHAR_BIT)] \
2567 |= 1 << ((n) % (sizeof (int) * CHAR_BIT))
2569 #define UNSETMARKBIT(block,n) \
2570 (block)->gcmarkbits[(n) / (sizeof (int) * CHAR_BIT)] \
2571 &= ~(1 << ((n) % (sizeof (int) * CHAR_BIT)))
2573 #define FLOAT_BLOCK(fptr) \
2574 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2576 #define FLOAT_INDEX(fptr) \
2577 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2579 struct float_block
2581 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2582 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2583 int gcmarkbits[1 + FLOAT_BLOCK_SIZE / (sizeof (int) * CHAR_BIT)];
2584 struct float_block *next;
2587 #define FLOAT_MARKED_P(fptr) \
2588 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2590 #define FLOAT_MARK(fptr) \
2591 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2593 #define FLOAT_UNMARK(fptr) \
2594 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2596 /* Current float_block. */
2598 static struct float_block *float_block;
2600 /* Index of first unused Lisp_Float in the current float_block. */
2602 static int float_block_index = FLOAT_BLOCK_SIZE;
2604 /* Free-list of Lisp_Floats. */
2606 static struct Lisp_Float *float_free_list;
2608 /* Return a new float object with value FLOAT_VALUE. */
2610 Lisp_Object
2611 make_float (double float_value)
2613 register Lisp_Object val;
2615 /* eassert (!handling_signal); */
2617 MALLOC_BLOCK_INPUT;
2619 if (float_free_list)
2621 /* We use the data field for chaining the free list
2622 so that we won't use the same field that has the mark bit. */
2623 XSETFLOAT (val, float_free_list);
2624 float_free_list = float_free_list->u.chain;
2626 else
2628 if (float_block_index == FLOAT_BLOCK_SIZE)
2630 struct float_block *new
2631 = lisp_align_malloc (sizeof *new, MEM_TYPE_FLOAT);
2632 new->next = float_block;
2633 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2634 float_block = new;
2635 float_block_index = 0;
2636 total_free_floats += FLOAT_BLOCK_SIZE;
2638 XSETFLOAT (val, &float_block->floats[float_block_index]);
2639 float_block_index++;
2642 MALLOC_UNBLOCK_INPUT;
2644 XFLOAT_INIT (val, float_value);
2645 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2646 consing_since_gc += sizeof (struct Lisp_Float);
2647 floats_consed++;
2648 total_free_floats--;
2649 return val;
2654 /***********************************************************************
2655 Cons Allocation
2656 ***********************************************************************/
2658 /* We store cons cells inside of cons_blocks, allocating a new
2659 cons_block with malloc whenever necessary. Cons cells reclaimed by
2660 GC are put on a free list to be reallocated before allocating
2661 any new cons cells from the latest cons_block. */
2663 #define CONS_BLOCK_SIZE \
2664 (((BLOCK_BYTES - sizeof (struct cons_block *) \
2665 /* The compiler might add padding at the end. */ \
2666 - (sizeof (struct Lisp_Cons) - sizeof (int))) * CHAR_BIT) \
2667 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2669 #define CONS_BLOCK(fptr) \
2670 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2672 #define CONS_INDEX(fptr) \
2673 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2675 struct cons_block
2677 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2678 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2679 int gcmarkbits[1 + CONS_BLOCK_SIZE / (sizeof (int) * CHAR_BIT)];
2680 struct cons_block *next;
2683 #define CONS_MARKED_P(fptr) \
2684 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2686 #define CONS_MARK(fptr) \
2687 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2689 #define CONS_UNMARK(fptr) \
2690 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2692 /* Current cons_block. */
2694 static struct cons_block *cons_block;
2696 /* Index of first unused Lisp_Cons in the current block. */
2698 static int cons_block_index = CONS_BLOCK_SIZE;
2700 /* Free-list of Lisp_Cons structures. */
2702 static struct Lisp_Cons *cons_free_list;
2704 /* Explicitly free a cons cell by putting it on the free-list. */
2706 void
2707 free_cons (struct Lisp_Cons *ptr)
2709 ptr->u.chain = cons_free_list;
2710 #if GC_MARK_STACK
2711 ptr->car = Vdead;
2712 #endif
2713 cons_free_list = ptr;
2714 total_free_conses++;
2717 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2718 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2719 (Lisp_Object car, Lisp_Object cdr)
2721 register Lisp_Object val;
2723 /* eassert (!handling_signal); */
2725 MALLOC_BLOCK_INPUT;
2727 if (cons_free_list)
2729 /* We use the cdr for chaining the free list
2730 so that we won't use the same field that has the mark bit. */
2731 XSETCONS (val, cons_free_list);
2732 cons_free_list = cons_free_list->u.chain;
2734 else
2736 if (cons_block_index == CONS_BLOCK_SIZE)
2738 struct cons_block *new
2739 = lisp_align_malloc (sizeof *new, MEM_TYPE_CONS);
2740 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2741 new->next = cons_block;
2742 cons_block = new;
2743 cons_block_index = 0;
2744 total_free_conses += CONS_BLOCK_SIZE;
2746 XSETCONS (val, &cons_block->conses[cons_block_index]);
2747 cons_block_index++;
2750 MALLOC_UNBLOCK_INPUT;
2752 XSETCAR (val, car);
2753 XSETCDR (val, cdr);
2754 eassert (!CONS_MARKED_P (XCONS (val)));
2755 consing_since_gc += sizeof (struct Lisp_Cons);
2756 total_free_conses--;
2757 cons_cells_consed++;
2758 return val;
2761 #ifdef GC_CHECK_CONS_LIST
2762 /* Get an error now if there's any junk in the cons free list. */
2763 void
2764 check_cons_list (void)
2766 struct Lisp_Cons *tail = cons_free_list;
2768 while (tail)
2769 tail = tail->u.chain;
2771 #endif
2773 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2775 Lisp_Object
2776 list1 (Lisp_Object arg1)
2778 return Fcons (arg1, Qnil);
2781 Lisp_Object
2782 list2 (Lisp_Object arg1, Lisp_Object arg2)
2784 return Fcons (arg1, Fcons (arg2, Qnil));
2788 Lisp_Object
2789 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2791 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2795 Lisp_Object
2796 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2798 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2802 Lisp_Object
2803 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2805 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2806 Fcons (arg5, Qnil)))));
2810 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2811 doc: /* Return a newly created list with specified arguments as elements.
2812 Any number of arguments, even zero arguments, are allowed.
2813 usage: (list &rest OBJECTS) */)
2814 (ptrdiff_t nargs, Lisp_Object *args)
2816 register Lisp_Object val;
2817 val = Qnil;
2819 while (nargs > 0)
2821 nargs--;
2822 val = Fcons (args[nargs], val);
2824 return val;
2828 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2829 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2830 (register Lisp_Object length, Lisp_Object init)
2832 register Lisp_Object val;
2833 register EMACS_INT size;
2835 CHECK_NATNUM (length);
2836 size = XFASTINT (length);
2838 val = Qnil;
2839 while (size > 0)
2841 val = Fcons (init, val);
2842 --size;
2844 if (size > 0)
2846 val = Fcons (init, val);
2847 --size;
2849 if (size > 0)
2851 val = Fcons (init, val);
2852 --size;
2854 if (size > 0)
2856 val = Fcons (init, val);
2857 --size;
2859 if (size > 0)
2861 val = Fcons (init, val);
2862 --size;
2868 QUIT;
2871 return val;
2876 /***********************************************************************
2877 Vector Allocation
2878 ***********************************************************************/
2880 /* This value is balanced well enough to avoid too much internal overhead
2881 for the most common cases; it's not required to be a power of two, but
2882 it's expected to be a mult-of-ROUNDUP_SIZE (see below). */
2884 #define VECTOR_BLOCK_SIZE 4096
2886 /* Align allocation request sizes to be a multiple of ROUNDUP_SIZE. */
2887 enum
2889 roundup_size = COMMON_MULTIPLE (word_size,
2890 USE_LSB_TAG ? 1 << GCTYPEBITS : 1)
2893 /* ROUNDUP_SIZE must be a power of 2. */
2894 verify ((roundup_size & (roundup_size - 1)) == 0);
2896 /* Verify assumptions described above. */
2897 verify ((VECTOR_BLOCK_SIZE % roundup_size) == 0);
2898 verify (VECTOR_BLOCK_SIZE <= (1 << PSEUDOVECTOR_SIZE_BITS));
2900 /* Round up X to nearest mult-of-ROUNDUP_SIZE. */
2902 #define vroundup(x) (((x) + (roundup_size - 1)) & ~(roundup_size - 1))
2904 /* Rounding helps to maintain alignment constraints if USE_LSB_TAG. */
2906 #define VECTOR_BLOCK_BYTES (VECTOR_BLOCK_SIZE - vroundup (sizeof (void *)))
2908 /* Size of the minimal vector allocated from block. */
2910 #define VBLOCK_BYTES_MIN vroundup (sizeof (struct Lisp_Vector))
2912 /* Size of the largest vector allocated from block. */
2914 #define VBLOCK_BYTES_MAX \
2915 vroundup ((VECTOR_BLOCK_BYTES / 2) - word_size)
2917 /* We maintain one free list for each possible block-allocated
2918 vector size, and this is the number of free lists we have. */
2920 #define VECTOR_MAX_FREE_LIST_INDEX \
2921 ((VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN) / roundup_size + 1)
2923 /* Common shortcut to advance vector pointer over a block data. */
2925 #define ADVANCE(v, nbytes) ((struct Lisp_Vector *) ((char *) (v) + (nbytes)))
2927 /* Common shortcut to calculate NBYTES-vector index in VECTOR_FREE_LISTS. */
2929 #define VINDEX(nbytes) (((nbytes) - VBLOCK_BYTES_MIN) / roundup_size)
2931 /* Common shortcut to setup vector on a free list. */
2933 #define SETUP_ON_FREE_LIST(v, nbytes, index) \
2934 do { \
2935 XSETPVECTYPESIZE (v, PVEC_FREE, nbytes); \
2936 eassert ((nbytes) % roundup_size == 0); \
2937 (index) = VINDEX (nbytes); \
2938 eassert ((index) < VECTOR_MAX_FREE_LIST_INDEX); \
2939 (v)->header.next.vector = vector_free_lists[index]; \
2940 vector_free_lists[index] = (v); \
2941 total_free_vector_slots += (nbytes) / word_size; \
2942 } while (0)
2944 struct vector_block
2946 char data[VECTOR_BLOCK_BYTES];
2947 struct vector_block *next;
2950 /* Chain of vector blocks. */
2952 static struct vector_block *vector_blocks;
2954 /* Vector free lists, where NTH item points to a chain of free
2955 vectors of the same NBYTES size, so NTH == VINDEX (NBYTES). */
2957 static struct Lisp_Vector *vector_free_lists[VECTOR_MAX_FREE_LIST_INDEX];
2959 /* Singly-linked list of large vectors. */
2961 static struct Lisp_Vector *large_vectors;
2963 /* The only vector with 0 slots, allocated from pure space. */
2965 Lisp_Object zero_vector;
2967 /* Number of live vectors. */
2969 static EMACS_INT total_vectors;
2971 /* Total size of live and free vectors, in Lisp_Object units. */
2973 static EMACS_INT total_vector_slots, total_free_vector_slots;
2975 /* Get a new vector block. */
2977 static struct vector_block *
2978 allocate_vector_block (void)
2980 struct vector_block *block = xmalloc (sizeof *block);
2982 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
2983 mem_insert (block->data, block->data + VECTOR_BLOCK_BYTES,
2984 MEM_TYPE_VECTOR_BLOCK);
2985 #endif
2987 block->next = vector_blocks;
2988 vector_blocks = block;
2989 return block;
2992 /* Called once to initialize vector allocation. */
2994 static void
2995 init_vectors (void)
2997 zero_vector = make_pure_vector (0);
3000 /* Allocate vector from a vector block. */
3002 static struct Lisp_Vector *
3003 allocate_vector_from_block (size_t nbytes)
3005 struct Lisp_Vector *vector, *rest;
3006 struct vector_block *block;
3007 size_t index, restbytes;
3009 eassert (VBLOCK_BYTES_MIN <= nbytes && nbytes <= VBLOCK_BYTES_MAX);
3010 eassert (nbytes % roundup_size == 0);
3012 /* First, try to allocate from a free list
3013 containing vectors of the requested size. */
3014 index = VINDEX (nbytes);
3015 if (vector_free_lists[index])
3017 vector = vector_free_lists[index];
3018 vector_free_lists[index] = vector->header.next.vector;
3019 vector->header.next.nbytes = nbytes;
3020 total_free_vector_slots -= nbytes / word_size;
3021 return vector;
3024 /* Next, check free lists containing larger vectors. Since
3025 we will split the result, we should have remaining space
3026 large enough to use for one-slot vector at least. */
3027 for (index = VINDEX (nbytes + VBLOCK_BYTES_MIN);
3028 index < VECTOR_MAX_FREE_LIST_INDEX; index++)
3029 if (vector_free_lists[index])
3031 /* This vector is larger than requested. */
3032 vector = vector_free_lists[index];
3033 vector_free_lists[index] = vector->header.next.vector;
3034 vector->header.next.nbytes = nbytes;
3035 total_free_vector_slots -= nbytes / word_size;
3037 /* Excess bytes are used for the smaller vector,
3038 which should be set on an appropriate free list. */
3039 restbytes = index * roundup_size + VBLOCK_BYTES_MIN - nbytes;
3040 eassert (restbytes % roundup_size == 0);
3041 rest = ADVANCE (vector, nbytes);
3042 SETUP_ON_FREE_LIST (rest, restbytes, index);
3043 return vector;
3046 /* Finally, need a new vector block. */
3047 block = allocate_vector_block ();
3049 /* New vector will be at the beginning of this block. */
3050 vector = (struct Lisp_Vector *) block->data;
3051 vector->header.next.nbytes = nbytes;
3053 /* If the rest of space from this block is large enough
3054 for one-slot vector at least, set up it on a free list. */
3055 restbytes = VECTOR_BLOCK_BYTES - nbytes;
3056 if (restbytes >= VBLOCK_BYTES_MIN)
3058 eassert (restbytes % roundup_size == 0);
3059 rest = ADVANCE (vector, nbytes);
3060 SETUP_ON_FREE_LIST (rest, restbytes, index);
3062 return vector;
3065 /* Nonzero if VECTOR pointer is valid pointer inside BLOCK. */
3067 #define VECTOR_IN_BLOCK(vector, block) \
3068 ((char *) (vector) <= (block)->data \
3069 + VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN)
3071 /* Number of bytes used by vector-block-allocated object. This is the only
3072 place where we actually use the `nbytes' field of the vector-header.
3073 I.e. we could get rid of the `nbytes' field by computing it based on the
3074 vector-type. */
3076 #define PSEUDOVECTOR_NBYTES(vector) \
3077 (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FREE) \
3078 ? vector->header.size & PSEUDOVECTOR_SIZE_MASK \
3079 : vector->header.next.nbytes)
3081 /* Reclaim space used by unmarked vectors. */
3083 static void
3084 sweep_vectors (void)
3086 struct vector_block *block = vector_blocks, **bprev = &vector_blocks;
3087 struct Lisp_Vector *vector, *next, **vprev = &large_vectors;
3089 total_vectors = total_vector_slots = total_free_vector_slots = 0;
3090 memset (vector_free_lists, 0, sizeof (vector_free_lists));
3092 /* Looking through vector blocks. */
3094 for (block = vector_blocks; block; block = *bprev)
3096 int free_this_block = 0;
3098 for (vector = (struct Lisp_Vector *) block->data;
3099 VECTOR_IN_BLOCK (vector, block); vector = next)
3101 if (VECTOR_MARKED_P (vector))
3103 VECTOR_UNMARK (vector);
3104 total_vectors++;
3105 total_vector_slots += vector->header.next.nbytes / word_size;
3106 next = ADVANCE (vector, vector->header.next.nbytes);
3108 else
3110 ptrdiff_t nbytes = PSEUDOVECTOR_NBYTES (vector);
3111 ptrdiff_t total_bytes = nbytes;
3113 next = ADVANCE (vector, nbytes);
3115 /* While NEXT is not marked, try to coalesce with VECTOR,
3116 thus making VECTOR of the largest possible size. */
3118 while (VECTOR_IN_BLOCK (next, block))
3120 if (VECTOR_MARKED_P (next))
3121 break;
3122 nbytes = PSEUDOVECTOR_NBYTES (next);
3123 total_bytes += nbytes;
3124 next = ADVANCE (next, nbytes);
3127 eassert (total_bytes % roundup_size == 0);
3129 if (vector == (struct Lisp_Vector *) block->data
3130 && !VECTOR_IN_BLOCK (next, block))
3131 /* This block should be freed because all of it's
3132 space was coalesced into the only free vector. */
3133 free_this_block = 1;
3134 else
3136 int tmp;
3137 SETUP_ON_FREE_LIST (vector, total_bytes, tmp);
3142 if (free_this_block)
3144 *bprev = block->next;
3145 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
3146 mem_delete (mem_find (block->data));
3147 #endif
3148 xfree (block);
3150 else
3151 bprev = &block->next;
3154 /* Sweep large vectors. */
3156 for (vector = large_vectors; vector; vector = *vprev)
3158 if (VECTOR_MARKED_P (vector))
3160 VECTOR_UNMARK (vector);
3161 total_vectors++;
3162 if (vector->header.size & PSEUDOVECTOR_FLAG)
3164 struct Lisp_Bool_Vector *b = (struct Lisp_Bool_Vector *) vector;
3166 /* All non-bool pseudovectors are small enough to be allocated
3167 from vector blocks. This code should be redesigned if some
3168 pseudovector type grows beyond VBLOCK_BYTES_MAX. */
3169 eassert (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_BOOL_VECTOR));
3171 total_vector_slots
3172 += (bool_header_size
3173 + ((b->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
3174 / BOOL_VECTOR_BITS_PER_CHAR)) / word_size;
3176 else
3177 total_vector_slots
3178 += header_size / word_size + vector->header.size;
3179 vprev = &vector->header.next.vector;
3181 else
3183 *vprev = vector->header.next.vector;
3184 lisp_free (vector);
3189 /* Value is a pointer to a newly allocated Lisp_Vector structure
3190 with room for LEN Lisp_Objects. */
3192 static struct Lisp_Vector *
3193 allocate_vectorlike (ptrdiff_t len)
3195 struct Lisp_Vector *p;
3197 MALLOC_BLOCK_INPUT;
3199 /* This gets triggered by code which I haven't bothered to fix. --Stef */
3200 /* eassert (!handling_signal); */
3202 if (len == 0)
3203 p = XVECTOR (zero_vector);
3204 else
3206 size_t nbytes = header_size + len * word_size;
3208 #ifdef DOUG_LEA_MALLOC
3209 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
3210 because mapped region contents are not preserved in
3211 a dumped Emacs. */
3212 mallopt (M_MMAP_MAX, 0);
3213 #endif
3215 if (nbytes <= VBLOCK_BYTES_MAX)
3216 p = allocate_vector_from_block (vroundup (nbytes));
3217 else
3219 p = lisp_malloc (nbytes, MEM_TYPE_VECTORLIKE);
3220 p->header.next.vector = large_vectors;
3221 large_vectors = p;
3224 #ifdef DOUG_LEA_MALLOC
3225 /* Back to a reasonable maximum of mmap'ed areas. */
3226 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
3227 #endif
3229 consing_since_gc += nbytes;
3230 vector_cells_consed += len;
3233 MALLOC_UNBLOCK_INPUT;
3235 return p;
3239 /* Allocate a vector with LEN slots. */
3241 struct Lisp_Vector *
3242 allocate_vector (EMACS_INT len)
3244 struct Lisp_Vector *v;
3245 ptrdiff_t nbytes_max = min (PTRDIFF_MAX, SIZE_MAX);
3247 if (min ((nbytes_max - header_size) / word_size, MOST_POSITIVE_FIXNUM) < len)
3248 memory_full (SIZE_MAX);
3249 v = allocate_vectorlike (len);
3250 v->header.size = len;
3251 return v;
3255 /* Allocate other vector-like structures. */
3257 struct Lisp_Vector *
3258 allocate_pseudovector (int memlen, int lisplen, int tag)
3260 struct Lisp_Vector *v = allocate_vectorlike (memlen);
3261 int i;
3263 /* Only the first lisplen slots will be traced normally by the GC. */
3264 for (i = 0; i < lisplen; ++i)
3265 v->contents[i] = Qnil;
3267 XSETPVECTYPESIZE (v, tag, lisplen);
3268 return v;
3271 struct buffer *
3272 allocate_buffer (void)
3274 struct buffer *b = lisp_malloc (sizeof *b, MEM_TYPE_BUFFER);
3276 XSETPVECTYPESIZE (b, PVEC_BUFFER, (offsetof (struct buffer, own_text)
3277 - header_size) / word_size);
3278 /* Note that the fields of B are not initialized. */
3279 return b;
3282 struct Lisp_Hash_Table *
3283 allocate_hash_table (void)
3285 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table, count, PVEC_HASH_TABLE);
3288 struct window *
3289 allocate_window (void)
3291 struct window *w;
3293 w = ALLOCATE_PSEUDOVECTOR (struct window, current_matrix, PVEC_WINDOW);
3294 /* Users assumes that non-Lisp data is zeroed. */
3295 memset (&w->current_matrix, 0,
3296 sizeof (*w) - offsetof (struct window, current_matrix));
3297 return w;
3300 struct terminal *
3301 allocate_terminal (void)
3303 struct terminal *t;
3305 t = ALLOCATE_PSEUDOVECTOR (struct terminal, next_terminal, PVEC_TERMINAL);
3306 /* Users assumes that non-Lisp data is zeroed. */
3307 memset (&t->next_terminal, 0,
3308 sizeof (*t) - offsetof (struct terminal, next_terminal));
3309 return t;
3312 struct frame *
3313 allocate_frame (void)
3315 struct frame *f;
3317 f = ALLOCATE_PSEUDOVECTOR (struct frame, face_cache, PVEC_FRAME);
3318 /* Users assumes that non-Lisp data is zeroed. */
3319 memset (&f->face_cache, 0,
3320 sizeof (*f) - offsetof (struct frame, face_cache));
3321 return f;
3324 struct Lisp_Process *
3325 allocate_process (void)
3327 struct Lisp_Process *p;
3329 p = ALLOCATE_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
3330 /* Users assumes that non-Lisp data is zeroed. */
3331 memset (&p->pid, 0,
3332 sizeof (*p) - offsetof (struct Lisp_Process, pid));
3333 return p;
3336 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
3337 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
3338 See also the function `vector'. */)
3339 (register Lisp_Object length, Lisp_Object init)
3341 Lisp_Object vector;
3342 register ptrdiff_t sizei;
3343 register ptrdiff_t i;
3344 register struct Lisp_Vector *p;
3346 CHECK_NATNUM (length);
3348 p = allocate_vector (XFASTINT (length));
3349 sizei = XFASTINT (length);
3350 for (i = 0; i < sizei; i++)
3351 p->contents[i] = init;
3353 XSETVECTOR (vector, p);
3354 return vector;
3358 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3359 doc: /* Return a newly created vector with specified arguments as elements.
3360 Any number of arguments, even zero arguments, are allowed.
3361 usage: (vector &rest OBJECTS) */)
3362 (ptrdiff_t nargs, Lisp_Object *args)
3364 register Lisp_Object len, val;
3365 ptrdiff_t i;
3366 register struct Lisp_Vector *p;
3368 XSETFASTINT (len, nargs);
3369 val = Fmake_vector (len, Qnil);
3370 p = XVECTOR (val);
3371 for (i = 0; i < nargs; i++)
3372 p->contents[i] = args[i];
3373 return val;
3376 void
3377 make_byte_code (struct Lisp_Vector *v)
3379 if (v->header.size > 1 && STRINGP (v->contents[1])
3380 && STRING_MULTIBYTE (v->contents[1]))
3381 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3382 earlier because they produced a raw 8-bit string for byte-code
3383 and now such a byte-code string is loaded as multibyte while
3384 raw 8-bit characters converted to multibyte form. Thus, now we
3385 must convert them back to the original unibyte form. */
3386 v->contents[1] = Fstring_as_unibyte (v->contents[1]);
3387 XSETPVECTYPE (v, PVEC_COMPILED);
3390 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3391 doc: /* Create a byte-code object with specified arguments as elements.
3392 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3393 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3394 and (optional) INTERACTIVE-SPEC.
3395 The first four arguments are required; at most six have any
3396 significance.
3397 The ARGLIST can be either like the one of `lambda', in which case the arguments
3398 will be dynamically bound before executing the byte code, or it can be an
3399 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3400 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3401 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3402 argument to catch the left-over arguments. If such an integer is used, the
3403 arguments will not be dynamically bound but will be instead pushed on the
3404 stack before executing the byte-code.
3405 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3406 (ptrdiff_t nargs, Lisp_Object *args)
3408 register Lisp_Object len, val;
3409 ptrdiff_t i;
3410 register struct Lisp_Vector *p;
3412 /* We used to purecopy everything here, if purify-flga was set. This worked
3413 OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
3414 dangerous, since make-byte-code is used during execution to build
3415 closures, so any closure built during the preload phase would end up
3416 copied into pure space, including its free variables, which is sometimes
3417 just wasteful and other times plainly wrong (e.g. those free vars may want
3418 to be setcar'd). */
3420 XSETFASTINT (len, nargs);
3421 val = Fmake_vector (len, Qnil);
3423 p = XVECTOR (val);
3424 for (i = 0; i < nargs; i++)
3425 p->contents[i] = args[i];
3426 make_byte_code (p);
3427 XSETCOMPILED (val, p);
3428 return val;
3433 /***********************************************************************
3434 Symbol Allocation
3435 ***********************************************************************/
3437 /* Like struct Lisp_Symbol, but padded so that the size is a multiple
3438 of the required alignment if LSB tags are used. */
3440 union aligned_Lisp_Symbol
3442 struct Lisp_Symbol s;
3443 #if USE_LSB_TAG
3444 unsigned char c[(sizeof (struct Lisp_Symbol) + (1 << GCTYPEBITS) - 1)
3445 & -(1 << GCTYPEBITS)];
3446 #endif
3449 /* Each symbol_block is just under 1020 bytes long, since malloc
3450 really allocates in units of powers of two and uses 4 bytes for its
3451 own overhead. */
3453 #define SYMBOL_BLOCK_SIZE \
3454 ((1020 - sizeof (struct symbol_block *)) / sizeof (union aligned_Lisp_Symbol))
3456 struct symbol_block
3458 /* Place `symbols' first, to preserve alignment. */
3459 union aligned_Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3460 struct symbol_block *next;
3463 /* Current symbol block and index of first unused Lisp_Symbol
3464 structure in it. */
3466 static struct symbol_block *symbol_block;
3467 static int symbol_block_index = SYMBOL_BLOCK_SIZE;
3469 /* List of free symbols. */
3471 static struct Lisp_Symbol *symbol_free_list;
3473 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3474 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3475 Its value and function definition are void, and its property list is nil. */)
3476 (Lisp_Object name)
3478 register Lisp_Object val;
3479 register struct Lisp_Symbol *p;
3481 CHECK_STRING (name);
3483 /* eassert (!handling_signal); */
3485 MALLOC_BLOCK_INPUT;
3487 if (symbol_free_list)
3489 XSETSYMBOL (val, symbol_free_list);
3490 symbol_free_list = symbol_free_list->next;
3492 else
3494 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3496 struct symbol_block *new
3497 = lisp_malloc (sizeof *new, MEM_TYPE_SYMBOL);
3498 new->next = symbol_block;
3499 symbol_block = new;
3500 symbol_block_index = 0;
3501 total_free_symbols += SYMBOL_BLOCK_SIZE;
3503 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index].s);
3504 symbol_block_index++;
3507 MALLOC_UNBLOCK_INPUT;
3509 p = XSYMBOL (val);
3510 p->xname = name;
3511 p->plist = Qnil;
3512 p->redirect = SYMBOL_PLAINVAL;
3513 SET_SYMBOL_VAL (p, Qunbound);
3514 p->function = Qunbound;
3515 p->next = NULL;
3516 p->gcmarkbit = 0;
3517 p->interned = SYMBOL_UNINTERNED;
3518 p->constant = 0;
3519 p->declared_special = 0;
3520 consing_since_gc += sizeof (struct Lisp_Symbol);
3521 symbols_consed++;
3522 total_free_symbols--;
3523 return val;
3528 /***********************************************************************
3529 Marker (Misc) Allocation
3530 ***********************************************************************/
3532 /* Like union Lisp_Misc, but padded so that its size is a multiple of
3533 the required alignment when LSB tags are used. */
3535 union aligned_Lisp_Misc
3537 union Lisp_Misc m;
3538 #if USE_LSB_TAG
3539 unsigned char c[(sizeof (union Lisp_Misc) + (1 << GCTYPEBITS) - 1)
3540 & -(1 << GCTYPEBITS)];
3541 #endif
3544 /* Allocation of markers and other objects that share that structure.
3545 Works like allocation of conses. */
3547 #define MARKER_BLOCK_SIZE \
3548 ((1020 - sizeof (struct marker_block *)) / sizeof (union aligned_Lisp_Misc))
3550 struct marker_block
3552 /* Place `markers' first, to preserve alignment. */
3553 union aligned_Lisp_Misc markers[MARKER_BLOCK_SIZE];
3554 struct marker_block *next;
3557 static struct marker_block *marker_block;
3558 static int marker_block_index = MARKER_BLOCK_SIZE;
3560 static union Lisp_Misc *marker_free_list;
3562 /* Return a newly allocated Lisp_Misc object, with no substructure. */
3564 Lisp_Object
3565 allocate_misc (void)
3567 Lisp_Object val;
3569 /* eassert (!handling_signal); */
3571 MALLOC_BLOCK_INPUT;
3573 if (marker_free_list)
3575 XSETMISC (val, marker_free_list);
3576 marker_free_list = marker_free_list->u_free.chain;
3578 else
3580 if (marker_block_index == MARKER_BLOCK_SIZE)
3582 struct marker_block *new = lisp_malloc (sizeof *new, MEM_TYPE_MISC);
3583 new->next = marker_block;
3584 marker_block = new;
3585 marker_block_index = 0;
3586 total_free_markers += MARKER_BLOCK_SIZE;
3588 XSETMISC (val, &marker_block->markers[marker_block_index].m);
3589 marker_block_index++;
3592 MALLOC_UNBLOCK_INPUT;
3594 --total_free_markers;
3595 consing_since_gc += sizeof (union Lisp_Misc);
3596 misc_objects_consed++;
3597 XMISCANY (val)->gcmarkbit = 0;
3598 return val;
3601 /* Free a Lisp_Misc object */
3603 static void
3604 free_misc (Lisp_Object misc)
3606 XMISCTYPE (misc) = Lisp_Misc_Free;
3607 XMISC (misc)->u_free.chain = marker_free_list;
3608 marker_free_list = XMISC (misc);
3610 total_free_markers++;
3613 /* Return a Lisp_Misc_Save_Value object containing POINTER and
3614 INTEGER. This is used to package C values to call record_unwind_protect.
3615 The unwind function can get the C values back using XSAVE_VALUE. */
3617 Lisp_Object
3618 make_save_value (void *pointer, ptrdiff_t integer)
3620 register Lisp_Object val;
3621 register struct Lisp_Save_Value *p;
3623 val = allocate_misc ();
3624 XMISCTYPE (val) = Lisp_Misc_Save_Value;
3625 p = XSAVE_VALUE (val);
3626 p->pointer = pointer;
3627 p->integer = integer;
3628 p->dogc = 0;
3629 return val;
3632 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3633 doc: /* Return a newly allocated marker which does not point at any place. */)
3634 (void)
3636 register Lisp_Object val;
3637 register struct Lisp_Marker *p;
3639 val = allocate_misc ();
3640 XMISCTYPE (val) = Lisp_Misc_Marker;
3641 p = XMARKER (val);
3642 p->buffer = 0;
3643 p->bytepos = 0;
3644 p->charpos = 0;
3645 p->next = NULL;
3646 p->insertion_type = 0;
3647 return val;
3650 /* Return a newly allocated marker which points into BUF
3651 at character position CHARPOS and byte position BYTEPOS. */
3653 Lisp_Object
3654 build_marker (struct buffer *buf, ptrdiff_t charpos, ptrdiff_t bytepos)
3656 Lisp_Object obj;
3657 struct Lisp_Marker *m;
3659 /* No dead buffers here. */
3660 eassert (!NILP (BVAR (buf, name)));
3662 /* Every character is at least one byte. */
3663 eassert (charpos <= bytepos);
3665 obj = allocate_misc ();
3666 XMISCTYPE (obj) = Lisp_Misc_Marker;
3667 m = XMARKER (obj);
3668 m->buffer = buf;
3669 m->charpos = charpos;
3670 m->bytepos = bytepos;
3671 m->insertion_type = 0;
3672 m->next = BUF_MARKERS (buf);
3673 BUF_MARKERS (buf) = m;
3674 return obj;
3677 /* Put MARKER back on the free list after using it temporarily. */
3679 void
3680 free_marker (Lisp_Object marker)
3682 unchain_marker (XMARKER (marker));
3683 free_misc (marker);
3687 /* Return a newly created vector or string with specified arguments as
3688 elements. If all the arguments are characters that can fit
3689 in a string of events, make a string; otherwise, make a vector.
3691 Any number of arguments, even zero arguments, are allowed. */
3693 Lisp_Object
3694 make_event_array (register int nargs, Lisp_Object *args)
3696 int i;
3698 for (i = 0; i < nargs; i++)
3699 /* The things that fit in a string
3700 are characters that are in 0...127,
3701 after discarding the meta bit and all the bits above it. */
3702 if (!INTEGERP (args[i])
3703 || (XINT (args[i]) & ~(-CHAR_META)) >= 0200)
3704 return Fvector (nargs, args);
3706 /* Since the loop exited, we know that all the things in it are
3707 characters, so we can make a string. */
3709 Lisp_Object result;
3711 result = Fmake_string (make_number (nargs), make_number (0));
3712 for (i = 0; i < nargs; i++)
3714 SSET (result, i, XINT (args[i]));
3715 /* Move the meta bit to the right place for a string char. */
3716 if (XINT (args[i]) & CHAR_META)
3717 SSET (result, i, SREF (result, i) | 0x80);
3720 return result;
3726 /************************************************************************
3727 Memory Full Handling
3728 ************************************************************************/
3731 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
3732 there may have been size_t overflow so that malloc was never
3733 called, or perhaps malloc was invoked successfully but the
3734 resulting pointer had problems fitting into a tagged EMACS_INT. In
3735 either case this counts as memory being full even though malloc did
3736 not fail. */
3738 void
3739 memory_full (size_t nbytes)
3741 /* Do not go into hysterics merely because a large request failed. */
3742 int enough_free_memory = 0;
3743 if (SPARE_MEMORY < nbytes)
3745 void *p;
3747 MALLOC_BLOCK_INPUT;
3748 p = malloc (SPARE_MEMORY);
3749 if (p)
3751 free (p);
3752 enough_free_memory = 1;
3754 MALLOC_UNBLOCK_INPUT;
3757 if (! enough_free_memory)
3759 int i;
3761 Vmemory_full = Qt;
3763 memory_full_cons_threshold = sizeof (struct cons_block);
3765 /* The first time we get here, free the spare memory. */
3766 for (i = 0; i < sizeof (spare_memory) / sizeof (char *); i++)
3767 if (spare_memory[i])
3769 if (i == 0)
3770 free (spare_memory[i]);
3771 else if (i >= 1 && i <= 4)
3772 lisp_align_free (spare_memory[i]);
3773 else
3774 lisp_free (spare_memory[i]);
3775 spare_memory[i] = 0;
3778 /* Record the space now used. When it decreases substantially,
3779 we can refill the memory reserve. */
3780 #if !defined SYSTEM_MALLOC && !defined SYNC_INPUT
3781 bytes_used_when_full = BYTES_USED;
3782 #endif
3785 /* This used to call error, but if we've run out of memory, we could
3786 get infinite recursion trying to build the string. */
3787 xsignal (Qnil, Vmemory_signal_data);
3790 /* If we released our reserve (due to running out of memory),
3791 and we have a fair amount free once again,
3792 try to set aside another reserve in case we run out once more.
3794 This is called when a relocatable block is freed in ralloc.c,
3795 and also directly from this file, in case we're not using ralloc.c. */
3797 void
3798 refill_memory_reserve (void)
3800 #ifndef SYSTEM_MALLOC
3801 if (spare_memory[0] == 0)
3802 spare_memory[0] = malloc (SPARE_MEMORY);
3803 if (spare_memory[1] == 0)
3804 spare_memory[1] = lisp_align_malloc (sizeof (struct cons_block),
3805 MEM_TYPE_CONS);
3806 if (spare_memory[2] == 0)
3807 spare_memory[2] = lisp_align_malloc (sizeof (struct cons_block),
3808 MEM_TYPE_CONS);
3809 if (spare_memory[3] == 0)
3810 spare_memory[3] = lisp_align_malloc (sizeof (struct cons_block),
3811 MEM_TYPE_CONS);
3812 if (spare_memory[4] == 0)
3813 spare_memory[4] = lisp_align_malloc (sizeof (struct cons_block),
3814 MEM_TYPE_CONS);
3815 if (spare_memory[5] == 0)
3816 spare_memory[5] = lisp_malloc (sizeof (struct string_block),
3817 MEM_TYPE_STRING);
3818 if (spare_memory[6] == 0)
3819 spare_memory[6] = lisp_malloc (sizeof (struct string_block),
3820 MEM_TYPE_STRING);
3821 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
3822 Vmemory_full = Qnil;
3823 #endif
3826 /************************************************************************
3827 C Stack Marking
3828 ************************************************************************/
3830 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
3832 /* Conservative C stack marking requires a method to identify possibly
3833 live Lisp objects given a pointer value. We do this by keeping
3834 track of blocks of Lisp data that are allocated in a red-black tree
3835 (see also the comment of mem_node which is the type of nodes in
3836 that tree). Function lisp_malloc adds information for an allocated
3837 block to the red-black tree with calls to mem_insert, and function
3838 lisp_free removes it with mem_delete. Functions live_string_p etc
3839 call mem_find to lookup information about a given pointer in the
3840 tree, and use that to determine if the pointer points to a Lisp
3841 object or not. */
3843 /* Initialize this part of alloc.c. */
3845 static void
3846 mem_init (void)
3848 mem_z.left = mem_z.right = MEM_NIL;
3849 mem_z.parent = NULL;
3850 mem_z.color = MEM_BLACK;
3851 mem_z.start = mem_z.end = NULL;
3852 mem_root = MEM_NIL;
3856 /* Value is a pointer to the mem_node containing START. Value is
3857 MEM_NIL if there is no node in the tree containing START. */
3859 static inline struct mem_node *
3860 mem_find (void *start)
3862 struct mem_node *p;
3864 if (start < min_heap_address || start > max_heap_address)
3865 return MEM_NIL;
3867 /* Make the search always successful to speed up the loop below. */
3868 mem_z.start = start;
3869 mem_z.end = (char *) start + 1;
3871 p = mem_root;
3872 while (start < p->start || start >= p->end)
3873 p = start < p->start ? p->left : p->right;
3874 return p;
3878 /* Insert a new node into the tree for a block of memory with start
3879 address START, end address END, and type TYPE. Value is a
3880 pointer to the node that was inserted. */
3882 static struct mem_node *
3883 mem_insert (void *start, void *end, enum mem_type type)
3885 struct mem_node *c, *parent, *x;
3887 if (min_heap_address == NULL || start < min_heap_address)
3888 min_heap_address = start;
3889 if (max_heap_address == NULL || end > max_heap_address)
3890 max_heap_address = end;
3892 /* See where in the tree a node for START belongs. In this
3893 particular application, it shouldn't happen that a node is already
3894 present. For debugging purposes, let's check that. */
3895 c = mem_root;
3896 parent = NULL;
3898 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
3900 while (c != MEM_NIL)
3902 if (start >= c->start && start < c->end)
3903 abort ();
3904 parent = c;
3905 c = start < c->start ? c->left : c->right;
3908 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3910 while (c != MEM_NIL)
3912 parent = c;
3913 c = start < c->start ? c->left : c->right;
3916 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3918 /* Create a new node. */
3919 #ifdef GC_MALLOC_CHECK
3920 x = _malloc_internal (sizeof *x);
3921 if (x == NULL)
3922 abort ();
3923 #else
3924 x = xmalloc (sizeof *x);
3925 #endif
3926 x->start = start;
3927 x->end = end;
3928 x->type = type;
3929 x->parent = parent;
3930 x->left = x->right = MEM_NIL;
3931 x->color = MEM_RED;
3933 /* Insert it as child of PARENT or install it as root. */
3934 if (parent)
3936 if (start < parent->start)
3937 parent->left = x;
3938 else
3939 parent->right = x;
3941 else
3942 mem_root = x;
3944 /* Re-establish red-black tree properties. */
3945 mem_insert_fixup (x);
3947 return x;
3951 /* Re-establish the red-black properties of the tree, and thereby
3952 balance the tree, after node X has been inserted; X is always red. */
3954 static void
3955 mem_insert_fixup (struct mem_node *x)
3957 while (x != mem_root && x->parent->color == MEM_RED)
3959 /* X is red and its parent is red. This is a violation of
3960 red-black tree property #3. */
3962 if (x->parent == x->parent->parent->left)
3964 /* We're on the left side of our grandparent, and Y is our
3965 "uncle". */
3966 struct mem_node *y = x->parent->parent->right;
3968 if (y->color == MEM_RED)
3970 /* Uncle and parent are red but should be black because
3971 X is red. Change the colors accordingly and proceed
3972 with the grandparent. */
3973 x->parent->color = MEM_BLACK;
3974 y->color = MEM_BLACK;
3975 x->parent->parent->color = MEM_RED;
3976 x = x->parent->parent;
3978 else
3980 /* Parent and uncle have different colors; parent is
3981 red, uncle is black. */
3982 if (x == x->parent->right)
3984 x = x->parent;
3985 mem_rotate_left (x);
3988 x->parent->color = MEM_BLACK;
3989 x->parent->parent->color = MEM_RED;
3990 mem_rotate_right (x->parent->parent);
3993 else
3995 /* This is the symmetrical case of above. */
3996 struct mem_node *y = x->parent->parent->left;
3998 if (y->color == MEM_RED)
4000 x->parent->color = MEM_BLACK;
4001 y->color = MEM_BLACK;
4002 x->parent->parent->color = MEM_RED;
4003 x = x->parent->parent;
4005 else
4007 if (x == x->parent->left)
4009 x = x->parent;
4010 mem_rotate_right (x);
4013 x->parent->color = MEM_BLACK;
4014 x->parent->parent->color = MEM_RED;
4015 mem_rotate_left (x->parent->parent);
4020 /* The root may have been changed to red due to the algorithm. Set
4021 it to black so that property #5 is satisfied. */
4022 mem_root->color = MEM_BLACK;
4026 /* (x) (y)
4027 / \ / \
4028 a (y) ===> (x) c
4029 / \ / \
4030 b c a b */
4032 static void
4033 mem_rotate_left (struct mem_node *x)
4035 struct mem_node *y;
4037 /* Turn y's left sub-tree into x's right sub-tree. */
4038 y = x->right;
4039 x->right = y->left;
4040 if (y->left != MEM_NIL)
4041 y->left->parent = x;
4043 /* Y's parent was x's parent. */
4044 if (y != MEM_NIL)
4045 y->parent = x->parent;
4047 /* Get the parent to point to y instead of x. */
4048 if (x->parent)
4050 if (x == x->parent->left)
4051 x->parent->left = y;
4052 else
4053 x->parent->right = y;
4055 else
4056 mem_root = y;
4058 /* Put x on y's left. */
4059 y->left = x;
4060 if (x != MEM_NIL)
4061 x->parent = y;
4065 /* (x) (Y)
4066 / \ / \
4067 (y) c ===> a (x)
4068 / \ / \
4069 a b b c */
4071 static void
4072 mem_rotate_right (struct mem_node *x)
4074 struct mem_node *y = x->left;
4076 x->left = y->right;
4077 if (y->right != MEM_NIL)
4078 y->right->parent = x;
4080 if (y != MEM_NIL)
4081 y->parent = x->parent;
4082 if (x->parent)
4084 if (x == x->parent->right)
4085 x->parent->right = y;
4086 else
4087 x->parent->left = y;
4089 else
4090 mem_root = y;
4092 y->right = x;
4093 if (x != MEM_NIL)
4094 x->parent = y;
4098 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
4100 static void
4101 mem_delete (struct mem_node *z)
4103 struct mem_node *x, *y;
4105 if (!z || z == MEM_NIL)
4106 return;
4108 if (z->left == MEM_NIL || z->right == MEM_NIL)
4109 y = z;
4110 else
4112 y = z->right;
4113 while (y->left != MEM_NIL)
4114 y = y->left;
4117 if (y->left != MEM_NIL)
4118 x = y->left;
4119 else
4120 x = y->right;
4122 x->parent = y->parent;
4123 if (y->parent)
4125 if (y == y->parent->left)
4126 y->parent->left = x;
4127 else
4128 y->parent->right = x;
4130 else
4131 mem_root = x;
4133 if (y != z)
4135 z->start = y->start;
4136 z->end = y->end;
4137 z->type = y->type;
4140 if (y->color == MEM_BLACK)
4141 mem_delete_fixup (x);
4143 #ifdef GC_MALLOC_CHECK
4144 _free_internal (y);
4145 #else
4146 xfree (y);
4147 #endif
4151 /* Re-establish the red-black properties of the tree, after a
4152 deletion. */
4154 static void
4155 mem_delete_fixup (struct mem_node *x)
4157 while (x != mem_root && x->color == MEM_BLACK)
4159 if (x == x->parent->left)
4161 struct mem_node *w = x->parent->right;
4163 if (w->color == MEM_RED)
4165 w->color = MEM_BLACK;
4166 x->parent->color = MEM_RED;
4167 mem_rotate_left (x->parent);
4168 w = x->parent->right;
4171 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
4173 w->color = MEM_RED;
4174 x = x->parent;
4176 else
4178 if (w->right->color == MEM_BLACK)
4180 w->left->color = MEM_BLACK;
4181 w->color = MEM_RED;
4182 mem_rotate_right (w);
4183 w = x->parent->right;
4185 w->color = x->parent->color;
4186 x->parent->color = MEM_BLACK;
4187 w->right->color = MEM_BLACK;
4188 mem_rotate_left (x->parent);
4189 x = mem_root;
4192 else
4194 struct mem_node *w = x->parent->left;
4196 if (w->color == MEM_RED)
4198 w->color = MEM_BLACK;
4199 x->parent->color = MEM_RED;
4200 mem_rotate_right (x->parent);
4201 w = x->parent->left;
4204 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
4206 w->color = MEM_RED;
4207 x = x->parent;
4209 else
4211 if (w->left->color == MEM_BLACK)
4213 w->right->color = MEM_BLACK;
4214 w->color = MEM_RED;
4215 mem_rotate_left (w);
4216 w = x->parent->left;
4219 w->color = x->parent->color;
4220 x->parent->color = MEM_BLACK;
4221 w->left->color = MEM_BLACK;
4222 mem_rotate_right (x->parent);
4223 x = mem_root;
4228 x->color = MEM_BLACK;
4232 /* Value is non-zero if P is a pointer to a live Lisp string on
4233 the heap. M is a pointer to the mem_block for P. */
4235 static inline int
4236 live_string_p (struct mem_node *m, void *p)
4238 if (m->type == MEM_TYPE_STRING)
4240 struct string_block *b = (struct string_block *) m->start;
4241 ptrdiff_t offset = (char *) p - (char *) &b->strings[0];
4243 /* P must point to the start of a Lisp_String structure, and it
4244 must not be on the free-list. */
4245 return (offset >= 0
4246 && offset % sizeof b->strings[0] == 0
4247 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
4248 && ((struct Lisp_String *) p)->data != NULL);
4250 else
4251 return 0;
4255 /* Value is non-zero if P is a pointer to a live Lisp cons on
4256 the heap. M is a pointer to the mem_block for P. */
4258 static inline int
4259 live_cons_p (struct mem_node *m, void *p)
4261 if (m->type == MEM_TYPE_CONS)
4263 struct cons_block *b = (struct cons_block *) m->start;
4264 ptrdiff_t offset = (char *) p - (char *) &b->conses[0];
4266 /* P must point to the start of a Lisp_Cons, not be
4267 one of the unused cells in the current cons block,
4268 and not be on the free-list. */
4269 return (offset >= 0
4270 && offset % sizeof b->conses[0] == 0
4271 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
4272 && (b != cons_block
4273 || offset / sizeof b->conses[0] < cons_block_index)
4274 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
4276 else
4277 return 0;
4281 /* Value is non-zero if P is a pointer to a live Lisp symbol on
4282 the heap. M is a pointer to the mem_block for P. */
4284 static inline int
4285 live_symbol_p (struct mem_node *m, void *p)
4287 if (m->type == MEM_TYPE_SYMBOL)
4289 struct symbol_block *b = (struct symbol_block *) m->start;
4290 ptrdiff_t offset = (char *) p - (char *) &b->symbols[0];
4292 /* P must point to the start of a Lisp_Symbol, not be
4293 one of the unused cells in the current symbol block,
4294 and not be on the free-list. */
4295 return (offset >= 0
4296 && offset % sizeof b->symbols[0] == 0
4297 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
4298 && (b != symbol_block
4299 || offset / sizeof b->symbols[0] < symbol_block_index)
4300 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
4302 else
4303 return 0;
4307 /* Value is non-zero if P is a pointer to a live Lisp float on
4308 the heap. M is a pointer to the mem_block for P. */
4310 static inline int
4311 live_float_p (struct mem_node *m, void *p)
4313 if (m->type == MEM_TYPE_FLOAT)
4315 struct float_block *b = (struct float_block *) m->start;
4316 ptrdiff_t offset = (char *) p - (char *) &b->floats[0];
4318 /* P must point to the start of a Lisp_Float and not be
4319 one of the unused cells in the current float block. */
4320 return (offset >= 0
4321 && offset % sizeof b->floats[0] == 0
4322 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
4323 && (b != float_block
4324 || offset / sizeof b->floats[0] < float_block_index));
4326 else
4327 return 0;
4331 /* Value is non-zero if P is a pointer to a live Lisp Misc on
4332 the heap. M is a pointer to the mem_block for P. */
4334 static inline int
4335 live_misc_p (struct mem_node *m, void *p)
4337 if (m->type == MEM_TYPE_MISC)
4339 struct marker_block *b = (struct marker_block *) m->start;
4340 ptrdiff_t offset = (char *) p - (char *) &b->markers[0];
4342 /* P must point to the start of a Lisp_Misc, not be
4343 one of the unused cells in the current misc block,
4344 and not be on the free-list. */
4345 return (offset >= 0
4346 && offset % sizeof b->markers[0] == 0
4347 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
4348 && (b != marker_block
4349 || offset / sizeof b->markers[0] < marker_block_index)
4350 && ((union Lisp_Misc *) p)->u_any.type != Lisp_Misc_Free);
4352 else
4353 return 0;
4357 /* Value is non-zero if P is a pointer to a live vector-like object.
4358 M is a pointer to the mem_block for P. */
4360 static inline int
4361 live_vector_p (struct mem_node *m, void *p)
4363 if (m->type == MEM_TYPE_VECTOR_BLOCK)
4365 /* This memory node corresponds to a vector block. */
4366 struct vector_block *block = (struct vector_block *) m->start;
4367 struct Lisp_Vector *vector = (struct Lisp_Vector *) block->data;
4369 /* P is in the block's allocation range. Scan the block
4370 up to P and see whether P points to the start of some
4371 vector which is not on a free list. FIXME: check whether
4372 some allocation patterns (probably a lot of short vectors)
4373 may cause a substantial overhead of this loop. */
4374 while (VECTOR_IN_BLOCK (vector, block)
4375 && vector <= (struct Lisp_Vector *) p)
4377 if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FREE))
4378 vector = ADVANCE (vector, (vector->header.size
4379 & PSEUDOVECTOR_SIZE_MASK));
4380 else if (vector == p)
4381 return 1;
4382 else
4383 vector = ADVANCE (vector, vector->header.next.nbytes);
4386 else if (m->type == MEM_TYPE_VECTORLIKE && p == m->start)
4387 /* This memory node corresponds to a large vector. */
4388 return 1;
4389 return 0;
4393 /* Value is non-zero if P is a pointer to a live buffer. M is a
4394 pointer to the mem_block for P. */
4396 static inline int
4397 live_buffer_p (struct mem_node *m, void *p)
4399 /* P must point to the start of the block, and the buffer
4400 must not have been killed. */
4401 return (m->type == MEM_TYPE_BUFFER
4402 && p == m->start
4403 && !NILP (((struct buffer *) p)->BUFFER_INTERNAL_FIELD (name)));
4406 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
4408 #if GC_MARK_STACK
4410 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4412 /* Array of objects that are kept alive because the C stack contains
4413 a pattern that looks like a reference to them . */
4415 #define MAX_ZOMBIES 10
4416 static Lisp_Object zombies[MAX_ZOMBIES];
4418 /* Number of zombie objects. */
4420 static EMACS_INT nzombies;
4422 /* Number of garbage collections. */
4424 static EMACS_INT ngcs;
4426 /* Average percentage of zombies per collection. */
4428 static double avg_zombies;
4430 /* Max. number of live and zombie objects. */
4432 static EMACS_INT max_live, max_zombies;
4434 /* Average number of live objects per GC. */
4436 static double avg_live;
4438 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
4439 doc: /* Show information about live and zombie objects. */)
4440 (void)
4442 Lisp_Object args[8], zombie_list = Qnil;
4443 EMACS_INT i;
4444 for (i = 0; i < min (MAX_ZOMBIES, nzombies); i++)
4445 zombie_list = Fcons (zombies[i], zombie_list);
4446 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
4447 args[1] = make_number (ngcs);
4448 args[2] = make_float (avg_live);
4449 args[3] = make_float (avg_zombies);
4450 args[4] = make_float (avg_zombies / avg_live / 100);
4451 args[5] = make_number (max_live);
4452 args[6] = make_number (max_zombies);
4453 args[7] = zombie_list;
4454 return Fmessage (8, args);
4457 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4460 /* Mark OBJ if we can prove it's a Lisp_Object. */
4462 static inline void
4463 mark_maybe_object (Lisp_Object obj)
4465 void *po;
4466 struct mem_node *m;
4468 if (INTEGERP (obj))
4469 return;
4471 po = (void *) XPNTR (obj);
4472 m = mem_find (po);
4474 if (m != MEM_NIL)
4476 int mark_p = 0;
4478 switch (XTYPE (obj))
4480 case Lisp_String:
4481 mark_p = (live_string_p (m, po)
4482 && !STRING_MARKED_P ((struct Lisp_String *) po));
4483 break;
4485 case Lisp_Cons:
4486 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4487 break;
4489 case Lisp_Symbol:
4490 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4491 break;
4493 case Lisp_Float:
4494 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4495 break;
4497 case Lisp_Vectorlike:
4498 /* Note: can't check BUFFERP before we know it's a
4499 buffer because checking that dereferences the pointer
4500 PO which might point anywhere. */
4501 if (live_vector_p (m, po))
4502 mark_p = !SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4503 else if (live_buffer_p (m, po))
4504 mark_p = BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4505 break;
4507 case Lisp_Misc:
4508 mark_p = (live_misc_p (m, po) && !XMISCANY (obj)->gcmarkbit);
4509 break;
4511 default:
4512 break;
4515 if (mark_p)
4517 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4518 if (nzombies < MAX_ZOMBIES)
4519 zombies[nzombies] = obj;
4520 ++nzombies;
4521 #endif
4522 mark_object (obj);
4528 /* If P points to Lisp data, mark that as live if it isn't already
4529 marked. */
4531 static inline void
4532 mark_maybe_pointer (void *p)
4534 struct mem_node *m;
4536 /* Quickly rule out some values which can't point to Lisp data.
4537 USE_LSB_TAG needs Lisp data to be aligned on multiples of 1 << GCTYPEBITS.
4538 Otherwise, assume that Lisp data is aligned on even addresses. */
4539 if ((intptr_t) p % (USE_LSB_TAG ? 1 << GCTYPEBITS : 2))
4540 return;
4542 m = mem_find (p);
4543 if (m != MEM_NIL)
4545 Lisp_Object obj = Qnil;
4547 switch (m->type)
4549 case MEM_TYPE_NON_LISP:
4550 /* Nothing to do; not a pointer to Lisp memory. */
4551 break;
4553 case MEM_TYPE_BUFFER:
4554 if (live_buffer_p (m, p) && !VECTOR_MARKED_P ((struct buffer *)p))
4555 XSETVECTOR (obj, p);
4556 break;
4558 case MEM_TYPE_CONS:
4559 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4560 XSETCONS (obj, p);
4561 break;
4563 case MEM_TYPE_STRING:
4564 if (live_string_p (m, p)
4565 && !STRING_MARKED_P ((struct Lisp_String *) p))
4566 XSETSTRING (obj, p);
4567 break;
4569 case MEM_TYPE_MISC:
4570 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4571 XSETMISC (obj, p);
4572 break;
4574 case MEM_TYPE_SYMBOL:
4575 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4576 XSETSYMBOL (obj, p);
4577 break;
4579 case MEM_TYPE_FLOAT:
4580 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4581 XSETFLOAT (obj, p);
4582 break;
4584 case MEM_TYPE_VECTORLIKE:
4585 case MEM_TYPE_VECTOR_BLOCK:
4586 if (live_vector_p (m, p))
4588 Lisp_Object tem;
4589 XSETVECTOR (tem, p);
4590 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4591 obj = tem;
4593 break;
4595 default:
4596 abort ();
4599 if (!NILP (obj))
4600 mark_object (obj);
4605 /* Alignment of pointer values. Use offsetof, as it sometimes returns
4606 a smaller alignment than GCC's __alignof__ and mark_memory might
4607 miss objects if __alignof__ were used. */
4608 #define GC_POINTER_ALIGNMENT offsetof (struct {char a; void *b;}, b)
4610 /* Define POINTERS_MIGHT_HIDE_IN_OBJECTS to 1 if marking via C pointers does
4611 not suffice, which is the typical case. A host where a Lisp_Object is
4612 wider than a pointer might allocate a Lisp_Object in non-adjacent halves.
4613 If USE_LSB_TAG, the bottom half is not a valid pointer, but it should
4614 suffice to widen it to to a Lisp_Object and check it that way. */
4615 #if USE_LSB_TAG || VAL_MAX < UINTPTR_MAX
4616 # if !USE_LSB_TAG && VAL_MAX < UINTPTR_MAX >> GCTYPEBITS
4617 /* If tag bits straddle pointer-word boundaries, neither mark_maybe_pointer
4618 nor mark_maybe_object can follow the pointers. This should not occur on
4619 any practical porting target. */
4620 # error "MSB type bits straddle pointer-word boundaries"
4621 # endif
4622 /* Marking via C pointers does not suffice, because Lisp_Objects contain
4623 pointer words that hold pointers ORed with type bits. */
4624 # define POINTERS_MIGHT_HIDE_IN_OBJECTS 1
4625 #else
4626 /* Marking via C pointers suffices, because Lisp_Objects contain pointer
4627 words that hold unmodified pointers. */
4628 # define POINTERS_MIGHT_HIDE_IN_OBJECTS 0
4629 #endif
4631 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4632 or END+OFFSET..START. */
4634 static void
4635 mark_memory (void *start, void *end)
4636 #if defined (__clang__) && defined (__has_feature)
4637 #if __has_feature(address_sanitizer)
4638 /* Do not allow -faddress-sanitizer to check this function, since it
4639 crosses the function stack boundary, and thus would yield many
4640 false positives. */
4641 __attribute__((no_address_safety_analysis))
4642 #endif
4643 #endif
4645 void **pp;
4646 int i;
4648 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4649 nzombies = 0;
4650 #endif
4652 /* Make START the pointer to the start of the memory region,
4653 if it isn't already. */
4654 if (end < start)
4656 void *tem = start;
4657 start = end;
4658 end = tem;
4661 /* Mark Lisp data pointed to. This is necessary because, in some
4662 situations, the C compiler optimizes Lisp objects away, so that
4663 only a pointer to them remains. Example:
4665 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4668 Lisp_Object obj = build_string ("test");
4669 struct Lisp_String *s = XSTRING (obj);
4670 Fgarbage_collect ();
4671 fprintf (stderr, "test `%s'\n", s->data);
4672 return Qnil;
4675 Here, `obj' isn't really used, and the compiler optimizes it
4676 away. The only reference to the life string is through the
4677 pointer `s'. */
4679 for (pp = start; (void *) pp < end; pp++)
4680 for (i = 0; i < sizeof *pp; i += GC_POINTER_ALIGNMENT)
4682 void *p = *(void **) ((char *) pp + i);
4683 mark_maybe_pointer (p);
4684 if (POINTERS_MIGHT_HIDE_IN_OBJECTS)
4685 mark_maybe_object (XIL ((intptr_t) p));
4689 /* setjmp will work with GCC unless NON_SAVING_SETJMP is defined in
4690 the GCC system configuration. In gcc 3.2, the only systems for
4691 which this is so are i386-sco5 non-ELF, i386-sysv3 (maybe included
4692 by others?) and ns32k-pc532-min. */
4694 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4696 static int setjmp_tested_p, longjmps_done;
4698 #define SETJMP_WILL_LIKELY_WORK "\
4700 Emacs garbage collector has been changed to use conservative stack\n\
4701 marking. Emacs has determined that the method it uses to do the\n\
4702 marking will likely work on your system, but this isn't sure.\n\
4704 If you are a system-programmer, or can get the help of a local wizard\n\
4705 who is, please take a look at the function mark_stack in alloc.c, and\n\
4706 verify that the methods used are appropriate for your system.\n\
4708 Please mail the result to <emacs-devel@gnu.org>.\n\
4711 #define SETJMP_WILL_NOT_WORK "\
4713 Emacs garbage collector has been changed to use conservative stack\n\
4714 marking. Emacs has determined that the default method it uses to do the\n\
4715 marking will not work on your system. We will need a system-dependent\n\
4716 solution for your system.\n\
4718 Please take a look at the function mark_stack in alloc.c, and\n\
4719 try to find a way to make it work on your system.\n\
4721 Note that you may get false negatives, depending on the compiler.\n\
4722 In particular, you need to use -O with GCC for this test.\n\
4724 Please mail the result to <emacs-devel@gnu.org>.\n\
4728 /* Perform a quick check if it looks like setjmp saves registers in a
4729 jmp_buf. Print a message to stderr saying so. When this test
4730 succeeds, this is _not_ a proof that setjmp is sufficient for
4731 conservative stack marking. Only the sources or a disassembly
4732 can prove that. */
4734 static void
4735 test_setjmp (void)
4737 char buf[10];
4738 register int x;
4739 jmp_buf jbuf;
4740 int result = 0;
4742 /* Arrange for X to be put in a register. */
4743 sprintf (buf, "1");
4744 x = strlen (buf);
4745 x = 2 * x - 1;
4747 setjmp (jbuf);
4748 if (longjmps_done == 1)
4750 /* Came here after the longjmp at the end of the function.
4752 If x == 1, the longjmp has restored the register to its
4753 value before the setjmp, and we can hope that setjmp
4754 saves all such registers in the jmp_buf, although that
4755 isn't sure.
4757 For other values of X, either something really strange is
4758 taking place, or the setjmp just didn't save the register. */
4760 if (x == 1)
4761 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4762 else
4764 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4765 exit (1);
4769 ++longjmps_done;
4770 x = 2;
4771 if (longjmps_done == 1)
4772 longjmp (jbuf, 1);
4775 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4778 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4780 /* Abort if anything GCPRO'd doesn't survive the GC. */
4782 static void
4783 check_gcpros (void)
4785 struct gcpro *p;
4786 ptrdiff_t i;
4788 for (p = gcprolist; p; p = p->next)
4789 for (i = 0; i < p->nvars; ++i)
4790 if (!survives_gc_p (p->var[i]))
4791 /* FIXME: It's not necessarily a bug. It might just be that the
4792 GCPRO is unnecessary or should release the object sooner. */
4793 abort ();
4796 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4798 static void
4799 dump_zombies (void)
4801 int i;
4803 fprintf (stderr, "\nZombies kept alive = %"pI"d:\n", nzombies);
4804 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
4806 fprintf (stderr, " %d = ", i);
4807 debug_print (zombies[i]);
4811 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4814 /* Mark live Lisp objects on the C stack.
4816 There are several system-dependent problems to consider when
4817 porting this to new architectures:
4819 Processor Registers
4821 We have to mark Lisp objects in CPU registers that can hold local
4822 variables or are used to pass parameters.
4824 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4825 something that either saves relevant registers on the stack, or
4826 calls mark_maybe_object passing it each register's contents.
4828 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4829 implementation assumes that calling setjmp saves registers we need
4830 to see in a jmp_buf which itself lies on the stack. This doesn't
4831 have to be true! It must be verified for each system, possibly
4832 by taking a look at the source code of setjmp.
4834 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4835 can use it as a machine independent method to store all registers
4836 to the stack. In this case the macros described in the previous
4837 two paragraphs are not used.
4839 Stack Layout
4841 Architectures differ in the way their processor stack is organized.
4842 For example, the stack might look like this
4844 +----------------+
4845 | Lisp_Object | size = 4
4846 +----------------+
4847 | something else | size = 2
4848 +----------------+
4849 | Lisp_Object | size = 4
4850 +----------------+
4851 | ... |
4853 In such a case, not every Lisp_Object will be aligned equally. To
4854 find all Lisp_Object on the stack it won't be sufficient to walk
4855 the stack in steps of 4 bytes. Instead, two passes will be
4856 necessary, one starting at the start of the stack, and a second
4857 pass starting at the start of the stack + 2. Likewise, if the
4858 minimal alignment of Lisp_Objects on the stack is 1, four passes
4859 would be necessary, each one starting with one byte more offset
4860 from the stack start. */
4862 static void
4863 mark_stack (void)
4865 void *end;
4867 #ifdef HAVE___BUILTIN_UNWIND_INIT
4868 /* Force callee-saved registers and register windows onto the stack.
4869 This is the preferred method if available, obviating the need for
4870 machine dependent methods. */
4871 __builtin_unwind_init ();
4872 end = &end;
4873 #else /* not HAVE___BUILTIN_UNWIND_INIT */
4874 #ifndef GC_SAVE_REGISTERS_ON_STACK
4875 /* jmp_buf may not be aligned enough on darwin-ppc64 */
4876 union aligned_jmpbuf {
4877 Lisp_Object o;
4878 jmp_buf j;
4879 } j;
4880 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
4881 #endif
4882 /* This trick flushes the register windows so that all the state of
4883 the process is contained in the stack. */
4884 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
4885 needed on ia64 too. See mach_dep.c, where it also says inline
4886 assembler doesn't work with relevant proprietary compilers. */
4887 #ifdef __sparc__
4888 #if defined (__sparc64__) && defined (__FreeBSD__)
4889 /* FreeBSD does not have a ta 3 handler. */
4890 asm ("flushw");
4891 #else
4892 asm ("ta 3");
4893 #endif
4894 #endif
4896 /* Save registers that we need to see on the stack. We need to see
4897 registers used to hold register variables and registers used to
4898 pass parameters. */
4899 #ifdef GC_SAVE_REGISTERS_ON_STACK
4900 GC_SAVE_REGISTERS_ON_STACK (end);
4901 #else /* not GC_SAVE_REGISTERS_ON_STACK */
4903 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
4904 setjmp will definitely work, test it
4905 and print a message with the result
4906 of the test. */
4907 if (!setjmp_tested_p)
4909 setjmp_tested_p = 1;
4910 test_setjmp ();
4912 #endif /* GC_SETJMP_WORKS */
4914 setjmp (j.j);
4915 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
4916 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
4917 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
4919 /* This assumes that the stack is a contiguous region in memory. If
4920 that's not the case, something has to be done here to iterate
4921 over the stack segments. */
4922 mark_memory (stack_base, end);
4924 /* Allow for marking a secondary stack, like the register stack on the
4925 ia64. */
4926 #ifdef GC_MARK_SECONDARY_STACK
4927 GC_MARK_SECONDARY_STACK ();
4928 #endif
4930 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4931 check_gcpros ();
4932 #endif
4935 #endif /* GC_MARK_STACK != 0 */
4938 /* Determine whether it is safe to access memory at address P. */
4939 static int
4940 valid_pointer_p (void *p)
4942 #ifdef WINDOWSNT
4943 return w32_valid_pointer_p (p, 16);
4944 #else
4945 int fd[2];
4947 /* Obviously, we cannot just access it (we would SEGV trying), so we
4948 trick the o/s to tell us whether p is a valid pointer.
4949 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4950 not validate p in that case. */
4952 if (pipe (fd) == 0)
4954 int valid = (emacs_write (fd[1], (char *) p, 16) == 16);
4955 emacs_close (fd[1]);
4956 emacs_close (fd[0]);
4957 return valid;
4960 return -1;
4961 #endif
4964 /* Return 1 if OBJ is a valid lisp object.
4965 Return 0 if OBJ is NOT a valid lisp object.
4966 Return -1 if we cannot validate OBJ.
4967 This function can be quite slow,
4968 so it should only be used in code for manual debugging. */
4971 valid_lisp_object_p (Lisp_Object obj)
4973 void *p;
4974 #if GC_MARK_STACK
4975 struct mem_node *m;
4976 #endif
4978 if (INTEGERP (obj))
4979 return 1;
4981 p = (void *) XPNTR (obj);
4982 if (PURE_POINTER_P (p))
4983 return 1;
4985 #if !GC_MARK_STACK
4986 return valid_pointer_p (p);
4987 #else
4989 m = mem_find (p);
4991 if (m == MEM_NIL)
4993 int valid = valid_pointer_p (p);
4994 if (valid <= 0)
4995 return valid;
4997 if (SUBRP (obj))
4998 return 1;
5000 return 0;
5003 switch (m->type)
5005 case MEM_TYPE_NON_LISP:
5006 return 0;
5008 case MEM_TYPE_BUFFER:
5009 return live_buffer_p (m, p);
5011 case MEM_TYPE_CONS:
5012 return live_cons_p (m, p);
5014 case MEM_TYPE_STRING:
5015 return live_string_p (m, p);
5017 case MEM_TYPE_MISC:
5018 return live_misc_p (m, p);
5020 case MEM_TYPE_SYMBOL:
5021 return live_symbol_p (m, p);
5023 case MEM_TYPE_FLOAT:
5024 return live_float_p (m, p);
5026 case MEM_TYPE_VECTORLIKE:
5027 case MEM_TYPE_VECTOR_BLOCK:
5028 return live_vector_p (m, p);
5030 default:
5031 break;
5034 return 0;
5035 #endif
5041 /***********************************************************************
5042 Pure Storage Management
5043 ***********************************************************************/
5045 /* Allocate room for SIZE bytes from pure Lisp storage and return a
5046 pointer to it. TYPE is the Lisp type for which the memory is
5047 allocated. TYPE < 0 means it's not used for a Lisp object. */
5049 static void *
5050 pure_alloc (size_t size, int type)
5052 void *result;
5053 #if USE_LSB_TAG
5054 size_t alignment = (1 << GCTYPEBITS);
5055 #else
5056 size_t alignment = sizeof (EMACS_INT);
5058 /* Give Lisp_Floats an extra alignment. */
5059 if (type == Lisp_Float)
5061 #if defined __GNUC__ && __GNUC__ >= 2
5062 alignment = __alignof (struct Lisp_Float);
5063 #else
5064 alignment = sizeof (struct Lisp_Float);
5065 #endif
5067 #endif
5069 again:
5070 if (type >= 0)
5072 /* Allocate space for a Lisp object from the beginning of the free
5073 space with taking account of alignment. */
5074 result = ALIGN (purebeg + pure_bytes_used_lisp, alignment);
5075 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
5077 else
5079 /* Allocate space for a non-Lisp object from the end of the free
5080 space. */
5081 pure_bytes_used_non_lisp += size;
5082 result = purebeg + pure_size - pure_bytes_used_non_lisp;
5084 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
5086 if (pure_bytes_used <= pure_size)
5087 return result;
5089 /* Don't allocate a large amount here,
5090 because it might get mmap'd and then its address
5091 might not be usable. */
5092 purebeg = xmalloc (10000);
5093 pure_size = 10000;
5094 pure_bytes_used_before_overflow += pure_bytes_used - size;
5095 pure_bytes_used = 0;
5096 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
5097 goto again;
5101 /* Print a warning if PURESIZE is too small. */
5103 void
5104 check_pure_size (void)
5106 if (pure_bytes_used_before_overflow)
5107 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI"d"
5108 " bytes needed)"),
5109 pure_bytes_used + pure_bytes_used_before_overflow);
5113 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
5114 the non-Lisp data pool of the pure storage, and return its start
5115 address. Return NULL if not found. */
5117 static char *
5118 find_string_data_in_pure (const char *data, ptrdiff_t nbytes)
5120 int i;
5121 ptrdiff_t skip, bm_skip[256], last_char_skip, infinity, start, start_max;
5122 const unsigned char *p;
5123 char *non_lisp_beg;
5125 if (pure_bytes_used_non_lisp <= nbytes)
5126 return NULL;
5128 /* Set up the Boyer-Moore table. */
5129 skip = nbytes + 1;
5130 for (i = 0; i < 256; i++)
5131 bm_skip[i] = skip;
5133 p = (const unsigned char *) data;
5134 while (--skip > 0)
5135 bm_skip[*p++] = skip;
5137 last_char_skip = bm_skip['\0'];
5139 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
5140 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
5142 /* See the comments in the function `boyer_moore' (search.c) for the
5143 use of `infinity'. */
5144 infinity = pure_bytes_used_non_lisp + 1;
5145 bm_skip['\0'] = infinity;
5147 p = (const unsigned char *) non_lisp_beg + nbytes;
5148 start = 0;
5151 /* Check the last character (== '\0'). */
5154 start += bm_skip[*(p + start)];
5156 while (start <= start_max);
5158 if (start < infinity)
5159 /* Couldn't find the last character. */
5160 return NULL;
5162 /* No less than `infinity' means we could find the last
5163 character at `p[start - infinity]'. */
5164 start -= infinity;
5166 /* Check the remaining characters. */
5167 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
5168 /* Found. */
5169 return non_lisp_beg + start;
5171 start += last_char_skip;
5173 while (start <= start_max);
5175 return NULL;
5179 /* Return a string allocated in pure space. DATA is a buffer holding
5180 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
5181 non-zero means make the result string multibyte.
5183 Must get an error if pure storage is full, since if it cannot hold
5184 a large string it may be able to hold conses that point to that
5185 string; then the string is not protected from gc. */
5187 Lisp_Object
5188 make_pure_string (const char *data,
5189 ptrdiff_t nchars, ptrdiff_t nbytes, int multibyte)
5191 Lisp_Object string;
5192 struct Lisp_String *s;
5194 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
5195 s->data = (unsigned char *) find_string_data_in_pure (data, nbytes);
5196 if (s->data == NULL)
5198 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
5199 memcpy (s->data, data, nbytes);
5200 s->data[nbytes] = '\0';
5202 s->size = nchars;
5203 s->size_byte = multibyte ? nbytes : -1;
5204 s->intervals = NULL_INTERVAL;
5205 XSETSTRING (string, s);
5206 return string;
5209 /* Return a string allocated in pure space. Do not
5210 allocate the string data, just point to DATA. */
5212 Lisp_Object
5213 make_pure_c_string (const char *data, ptrdiff_t nchars)
5215 Lisp_Object string;
5216 struct Lisp_String *s;
5218 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
5219 s->size = nchars;
5220 s->size_byte = -1;
5221 s->data = (unsigned char *) data;
5222 s->intervals = NULL_INTERVAL;
5223 XSETSTRING (string, s);
5224 return string;
5227 /* Return a cons allocated from pure space. Give it pure copies
5228 of CAR as car and CDR as cdr. */
5230 Lisp_Object
5231 pure_cons (Lisp_Object car, Lisp_Object cdr)
5233 register Lisp_Object new;
5234 struct Lisp_Cons *p;
5236 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
5237 XSETCONS (new, p);
5238 XSETCAR (new, Fpurecopy (car));
5239 XSETCDR (new, Fpurecopy (cdr));
5240 return new;
5244 /* Value is a float object with value NUM allocated from pure space. */
5246 static Lisp_Object
5247 make_pure_float (double num)
5249 register Lisp_Object new;
5250 struct Lisp_Float *p;
5252 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
5253 XSETFLOAT (new, p);
5254 XFLOAT_INIT (new, num);
5255 return new;
5259 /* Return a vector with room for LEN Lisp_Objects allocated from
5260 pure space. */
5262 static Lisp_Object
5263 make_pure_vector (ptrdiff_t len)
5265 Lisp_Object new;
5266 struct Lisp_Vector *p;
5267 size_t size = header_size + len * word_size;
5269 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
5270 XSETVECTOR (new, p);
5271 XVECTOR (new)->header.size = len;
5272 return new;
5276 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
5277 doc: /* Make a copy of object OBJ in pure storage.
5278 Recursively copies contents of vectors and cons cells.
5279 Does not copy symbols. Copies strings without text properties. */)
5280 (register Lisp_Object obj)
5282 if (NILP (Vpurify_flag))
5283 return obj;
5285 if (PURE_POINTER_P (XPNTR (obj)))
5286 return obj;
5288 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5290 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
5291 if (!NILP (tmp))
5292 return tmp;
5295 if (CONSP (obj))
5296 obj = pure_cons (XCAR (obj), XCDR (obj));
5297 else if (FLOATP (obj))
5298 obj = make_pure_float (XFLOAT_DATA (obj));
5299 else if (STRINGP (obj))
5300 obj = make_pure_string (SSDATA (obj), SCHARS (obj),
5301 SBYTES (obj),
5302 STRING_MULTIBYTE (obj));
5303 else if (COMPILEDP (obj) || VECTORP (obj))
5305 register struct Lisp_Vector *vec;
5306 register ptrdiff_t i;
5307 ptrdiff_t size;
5309 size = ASIZE (obj);
5310 if (size & PSEUDOVECTOR_FLAG)
5311 size &= PSEUDOVECTOR_SIZE_MASK;
5312 vec = XVECTOR (make_pure_vector (size));
5313 for (i = 0; i < size; i++)
5314 vec->contents[i] = Fpurecopy (AREF (obj, i));
5315 if (COMPILEDP (obj))
5317 XSETPVECTYPE (vec, PVEC_COMPILED);
5318 XSETCOMPILED (obj, vec);
5320 else
5321 XSETVECTOR (obj, vec);
5323 else if (MARKERP (obj))
5324 error ("Attempt to copy a marker to pure storage");
5325 else
5326 /* Not purified, don't hash-cons. */
5327 return obj;
5329 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5330 Fputhash (obj, obj, Vpurify_flag);
5332 return obj;
5337 /***********************************************************************
5338 Protection from GC
5339 ***********************************************************************/
5341 /* Put an entry in staticvec, pointing at the variable with address
5342 VARADDRESS. */
5344 void
5345 staticpro (Lisp_Object *varaddress)
5347 staticvec[staticidx++] = varaddress;
5348 if (staticidx >= NSTATICS)
5349 abort ();
5353 /***********************************************************************
5354 Protection from GC
5355 ***********************************************************************/
5357 /* Temporarily prevent garbage collection. */
5359 ptrdiff_t
5360 inhibit_garbage_collection (void)
5362 ptrdiff_t count = SPECPDL_INDEX ();
5364 specbind (Qgc_cons_threshold, make_number (MOST_POSITIVE_FIXNUM));
5365 return count;
5368 /* Used to avoid possible overflows when
5369 converting from C to Lisp integers. */
5371 static inline Lisp_Object
5372 bounded_number (EMACS_INT number)
5374 return make_number (min (MOST_POSITIVE_FIXNUM, number));
5377 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
5378 doc: /* Reclaim storage for Lisp objects no longer needed.
5379 Garbage collection happens automatically if you cons more than
5380 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5381 `garbage-collect' normally returns a list with info on amount of space in use,
5382 where each entry has the form (NAME SIZE USED FREE), where:
5383 - NAME is a symbol describing the kind of objects this entry represents,
5384 - SIZE is the number of bytes used by each one,
5385 - USED is the number of those objects that were found live in the heap,
5386 - FREE is the number of those objects that are not live but that Emacs
5387 keeps around for future allocations (maybe because it does not know how
5388 to return them to the OS).
5389 However, if there was overflow in pure space, `garbage-collect'
5390 returns nil, because real GC can't be done.
5391 See Info node `(elisp)Garbage Collection'. */)
5392 (void)
5394 register struct specbinding *bind;
5395 register struct buffer *nextb;
5396 char stack_top_variable;
5397 ptrdiff_t i;
5398 int message_p;
5399 Lisp_Object total[11];
5400 ptrdiff_t count = SPECPDL_INDEX ();
5401 EMACS_TIME t1;
5403 if (abort_on_gc)
5404 abort ();
5406 /* Can't GC if pure storage overflowed because we can't determine
5407 if something is a pure object or not. */
5408 if (pure_bytes_used_before_overflow)
5409 return Qnil;
5411 CHECK_CONS_LIST ();
5413 /* Don't keep undo information around forever.
5414 Do this early on, so it is no problem if the user quits. */
5415 FOR_EACH_BUFFER (nextb)
5416 compact_buffer (nextb);
5418 t1 = current_emacs_time ();
5420 /* In case user calls debug_print during GC,
5421 don't let that cause a recursive GC. */
5422 consing_since_gc = 0;
5424 /* Save what's currently displayed in the echo area. */
5425 message_p = push_message ();
5426 record_unwind_protect (pop_message_unwind, Qnil);
5428 /* Save a copy of the contents of the stack, for debugging. */
5429 #if MAX_SAVE_STACK > 0
5430 if (NILP (Vpurify_flag))
5432 char *stack;
5433 ptrdiff_t stack_size;
5434 if (&stack_top_variable < stack_bottom)
5436 stack = &stack_top_variable;
5437 stack_size = stack_bottom - &stack_top_variable;
5439 else
5441 stack = stack_bottom;
5442 stack_size = &stack_top_variable - stack_bottom;
5444 if (stack_size <= MAX_SAVE_STACK)
5446 if (stack_copy_size < stack_size)
5448 stack_copy = xrealloc (stack_copy, stack_size);
5449 stack_copy_size = stack_size;
5451 memcpy (stack_copy, stack, stack_size);
5454 #endif /* MAX_SAVE_STACK > 0 */
5456 if (garbage_collection_messages)
5457 message1_nolog ("Garbage collecting...");
5459 BLOCK_INPUT;
5461 shrink_regexp_cache ();
5463 gc_in_progress = 1;
5465 /* Mark all the special slots that serve as the roots of accessibility. */
5467 for (i = 0; i < staticidx; i++)
5468 mark_object (*staticvec[i]);
5470 for (bind = specpdl; bind != specpdl_ptr; bind++)
5472 mark_object (bind->symbol);
5473 mark_object (bind->old_value);
5475 mark_terminals ();
5476 mark_kboards ();
5477 mark_ttys ();
5479 #ifdef USE_GTK
5481 extern void xg_mark_data (void);
5482 xg_mark_data ();
5484 #endif
5486 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
5487 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
5488 mark_stack ();
5489 #else
5491 register struct gcpro *tail;
5492 for (tail = gcprolist; tail; tail = tail->next)
5493 for (i = 0; i < tail->nvars; i++)
5494 mark_object (tail->var[i]);
5496 mark_byte_stack ();
5498 struct catchtag *catch;
5499 struct handler *handler;
5501 for (catch = catchlist; catch; catch = catch->next)
5503 mark_object (catch->tag);
5504 mark_object (catch->val);
5506 for (handler = handlerlist; handler; handler = handler->next)
5508 mark_object (handler->handler);
5509 mark_object (handler->var);
5512 mark_backtrace ();
5513 #endif
5515 #ifdef HAVE_WINDOW_SYSTEM
5516 mark_fringe_data ();
5517 #endif
5519 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5520 mark_stack ();
5521 #endif
5523 /* Everything is now marked, except for the things that require special
5524 finalization, i.e. the undo_list.
5525 Look thru every buffer's undo list
5526 for elements that update markers that were not marked,
5527 and delete them. */
5528 FOR_EACH_BUFFER (nextb)
5530 /* If a buffer's undo list is Qt, that means that undo is
5531 turned off in that buffer. Calling truncate_undo_list on
5532 Qt tends to return NULL, which effectively turns undo back on.
5533 So don't call truncate_undo_list if undo_list is Qt. */
5534 if (! EQ (nextb->BUFFER_INTERNAL_FIELD (undo_list), Qt))
5536 Lisp_Object tail, prev;
5537 tail = nextb->BUFFER_INTERNAL_FIELD (undo_list);
5538 prev = Qnil;
5539 while (CONSP (tail))
5541 if (CONSP (XCAR (tail))
5542 && MARKERP (XCAR (XCAR (tail)))
5543 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5545 if (NILP (prev))
5546 nextb->BUFFER_INTERNAL_FIELD (undo_list) = tail = XCDR (tail);
5547 else
5549 tail = XCDR (tail);
5550 XSETCDR (prev, tail);
5553 else
5555 prev = tail;
5556 tail = XCDR (tail);
5560 /* Now that we have stripped the elements that need not be in the
5561 undo_list any more, we can finally mark the list. */
5562 mark_object (nextb->BUFFER_INTERNAL_FIELD (undo_list));
5565 gc_sweep ();
5567 /* Clear the mark bits that we set in certain root slots. */
5569 unmark_byte_stack ();
5570 VECTOR_UNMARK (&buffer_defaults);
5571 VECTOR_UNMARK (&buffer_local_symbols);
5573 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
5574 dump_zombies ();
5575 #endif
5577 UNBLOCK_INPUT;
5579 CHECK_CONS_LIST ();
5581 gc_in_progress = 0;
5583 consing_since_gc = 0;
5584 if (gc_cons_threshold < 10000)
5585 gc_cons_threshold = 10000;
5587 gc_relative_threshold = 0;
5588 if (FLOATP (Vgc_cons_percentage))
5589 { /* Set gc_cons_combined_threshold. */
5590 double tot = 0;
5592 tot += total_conses * sizeof (struct Lisp_Cons);
5593 tot += total_symbols * sizeof (struct Lisp_Symbol);
5594 tot += total_markers * sizeof (union Lisp_Misc);
5595 tot += total_string_bytes;
5596 tot += total_vector_slots * word_size;
5597 tot += total_floats * sizeof (struct Lisp_Float);
5598 tot += total_intervals * sizeof (struct interval);
5599 tot += total_strings * sizeof (struct Lisp_String);
5601 tot *= XFLOAT_DATA (Vgc_cons_percentage);
5602 if (0 < tot)
5604 if (tot < TYPE_MAXIMUM (EMACS_INT))
5605 gc_relative_threshold = tot;
5606 else
5607 gc_relative_threshold = TYPE_MAXIMUM (EMACS_INT);
5611 if (garbage_collection_messages)
5613 if (message_p || minibuf_level > 0)
5614 restore_message ();
5615 else
5616 message1_nolog ("Garbage collecting...done");
5619 unbind_to (count, Qnil);
5621 total[0] = list4 (Qcons, make_number (sizeof (struct Lisp_Cons)),
5622 bounded_number (total_conses),
5623 bounded_number (total_free_conses));
5625 total[1] = list4 (Qsymbol, make_number (sizeof (struct Lisp_Symbol)),
5626 bounded_number (total_symbols),
5627 bounded_number (total_free_symbols));
5629 total[2] = list4 (Qmisc, make_number (sizeof (union Lisp_Misc)),
5630 bounded_number (total_markers),
5631 bounded_number (total_free_markers));
5633 total[3] = list4 (Qstring, make_number (sizeof (struct Lisp_String)),
5634 bounded_number (total_strings),
5635 bounded_number (total_free_strings));
5637 total[4] = list3 (Qstring_bytes, make_number (1),
5638 bounded_number (total_string_bytes));
5640 total[5] = list3 (Qvector, make_number (sizeof (struct Lisp_Vector)),
5641 bounded_number (total_vectors));
5643 total[6] = list4 (Qvector_slots, make_number (word_size),
5644 bounded_number (total_vector_slots),
5645 bounded_number (total_free_vector_slots));
5647 total[7] = list4 (Qfloat, make_number (sizeof (struct Lisp_Float)),
5648 bounded_number (total_floats),
5649 bounded_number (total_free_floats));
5651 total[8] = list4 (Qinterval, make_number (sizeof (struct interval)),
5652 bounded_number (total_intervals),
5653 bounded_number (total_free_intervals));
5655 total[9] = list3 (Qbuffer, make_number (sizeof (struct buffer)),
5656 bounded_number (total_buffers));
5658 total[10] = list4 (Qheap, make_number (1024),
5659 #ifdef DOUG_LEA_MALLOC
5660 bounded_number ((mallinfo ().uordblks + 1023) >> 10),
5661 bounded_number ((mallinfo ().fordblks + 1023) >> 10)
5662 #else
5663 Qnil, Qnil
5664 #endif
5667 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5669 /* Compute average percentage of zombies. */
5670 double nlive = 0;
5672 for (i = 0; i < 7; ++i)
5673 if (CONSP (total[i]))
5674 nlive += XFASTINT (XCAR (total[i]));
5676 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
5677 max_live = max (nlive, max_live);
5678 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
5679 max_zombies = max (nzombies, max_zombies);
5680 ++ngcs;
5682 #endif
5684 if (!NILP (Vpost_gc_hook))
5686 ptrdiff_t gc_count = inhibit_garbage_collection ();
5687 safe_run_hooks (Qpost_gc_hook);
5688 unbind_to (gc_count, Qnil);
5691 /* Accumulate statistics. */
5692 if (FLOATP (Vgc_elapsed))
5694 EMACS_TIME t2 = current_emacs_time ();
5695 EMACS_TIME t3 = sub_emacs_time (t2, t1);
5696 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed)
5697 + EMACS_TIME_TO_DOUBLE (t3));
5700 gcs_done++;
5702 return Flist (sizeof total / sizeof *total, total);
5706 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5707 only interesting objects referenced from glyphs are strings. */
5709 static void
5710 mark_glyph_matrix (struct glyph_matrix *matrix)
5712 struct glyph_row *row = matrix->rows;
5713 struct glyph_row *end = row + matrix->nrows;
5715 for (; row < end; ++row)
5716 if (row->enabled_p)
5718 int area;
5719 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
5721 struct glyph *glyph = row->glyphs[area];
5722 struct glyph *end_glyph = glyph + row->used[area];
5724 for (; glyph < end_glyph; ++glyph)
5725 if (STRINGP (glyph->object)
5726 && !STRING_MARKED_P (XSTRING (glyph->object)))
5727 mark_object (glyph->object);
5733 /* Mark Lisp faces in the face cache C. */
5735 static void
5736 mark_face_cache (struct face_cache *c)
5738 if (c)
5740 int i, j;
5741 for (i = 0; i < c->used; ++i)
5743 struct face *face = FACE_FROM_ID (c->f, i);
5745 if (face)
5747 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
5748 mark_object (face->lface[j]);
5756 /* Mark reference to a Lisp_Object.
5757 If the object referred to has not been seen yet, recursively mark
5758 all the references contained in it. */
5760 #define LAST_MARKED_SIZE 500
5761 static Lisp_Object last_marked[LAST_MARKED_SIZE];
5762 static int last_marked_index;
5764 /* For debugging--call abort when we cdr down this many
5765 links of a list, in mark_object. In debugging,
5766 the call to abort will hit a breakpoint.
5767 Normally this is zero and the check never goes off. */
5768 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE;
5770 static void
5771 mark_vectorlike (struct Lisp_Vector *ptr)
5773 ptrdiff_t size = ptr->header.size;
5774 ptrdiff_t i;
5776 eassert (!VECTOR_MARKED_P (ptr));
5777 VECTOR_MARK (ptr); /* Else mark it. */
5778 if (size & PSEUDOVECTOR_FLAG)
5779 size &= PSEUDOVECTOR_SIZE_MASK;
5781 /* Note that this size is not the memory-footprint size, but only
5782 the number of Lisp_Object fields that we should trace.
5783 The distinction is used e.g. by Lisp_Process which places extra
5784 non-Lisp_Object fields at the end of the structure... */
5785 for (i = 0; i < size; i++) /* ...and then mark its elements. */
5786 mark_object (ptr->contents[i]);
5789 /* Like mark_vectorlike but optimized for char-tables (and
5790 sub-char-tables) assuming that the contents are mostly integers or
5791 symbols. */
5793 static void
5794 mark_char_table (struct Lisp_Vector *ptr)
5796 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5797 int i;
5799 eassert (!VECTOR_MARKED_P (ptr));
5800 VECTOR_MARK (ptr);
5801 for (i = 0; i < size; i++)
5803 Lisp_Object val = ptr->contents[i];
5805 if (INTEGERP (val) || (SYMBOLP (val) && XSYMBOL (val)->gcmarkbit))
5806 continue;
5807 if (SUB_CHAR_TABLE_P (val))
5809 if (! VECTOR_MARKED_P (XVECTOR (val)))
5810 mark_char_table (XVECTOR (val));
5812 else
5813 mark_object (val);
5817 /* Mark the chain of overlays starting at PTR. */
5819 static void
5820 mark_overlay (struct Lisp_Overlay *ptr)
5822 for (; ptr && !ptr->gcmarkbit; ptr = ptr->next)
5824 ptr->gcmarkbit = 1;
5825 mark_object (ptr->start);
5826 mark_object (ptr->end);
5827 mark_object (ptr->plist);
5831 /* Mark Lisp_Objects and special pointers in BUFFER. */
5833 static void
5834 mark_buffer (struct buffer *buffer)
5836 /* This is handled much like other pseudovectors... */
5837 mark_vectorlike ((struct Lisp_Vector *) buffer);
5839 /* ...but there are some buffer-specific things. */
5841 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
5843 /* For now, we just don't mark the undo_list. It's done later in
5844 a special way just before the sweep phase, and after stripping
5845 some of its elements that are not needed any more. */
5847 mark_overlay (buffer->overlays_before);
5848 mark_overlay (buffer->overlays_after);
5850 /* If this is an indirect buffer, mark its base buffer. */
5851 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5852 mark_buffer (buffer->base_buffer);
5855 /* Determine type of generic Lisp_Object and mark it accordingly. */
5857 void
5858 mark_object (Lisp_Object arg)
5860 register Lisp_Object obj = arg;
5861 #ifdef GC_CHECK_MARKED_OBJECTS
5862 void *po;
5863 struct mem_node *m;
5864 #endif
5865 ptrdiff_t cdr_count = 0;
5867 loop:
5869 if (PURE_POINTER_P (XPNTR (obj)))
5870 return;
5872 last_marked[last_marked_index++] = obj;
5873 if (last_marked_index == LAST_MARKED_SIZE)
5874 last_marked_index = 0;
5876 /* Perform some sanity checks on the objects marked here. Abort if
5877 we encounter an object we know is bogus. This increases GC time
5878 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
5879 #ifdef GC_CHECK_MARKED_OBJECTS
5881 po = (void *) XPNTR (obj);
5883 /* Check that the object pointed to by PO is known to be a Lisp
5884 structure allocated from the heap. */
5885 #define CHECK_ALLOCATED() \
5886 do { \
5887 m = mem_find (po); \
5888 if (m == MEM_NIL) \
5889 abort (); \
5890 } while (0)
5892 /* Check that the object pointed to by PO is live, using predicate
5893 function LIVEP. */
5894 #define CHECK_LIVE(LIVEP) \
5895 do { \
5896 if (!LIVEP (m, po)) \
5897 abort (); \
5898 } while (0)
5900 /* Check both of the above conditions. */
5901 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
5902 do { \
5903 CHECK_ALLOCATED (); \
5904 CHECK_LIVE (LIVEP); \
5905 } while (0) \
5907 #else /* not GC_CHECK_MARKED_OBJECTS */
5909 #define CHECK_LIVE(LIVEP) (void) 0
5910 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
5912 #endif /* not GC_CHECK_MARKED_OBJECTS */
5914 switch (SWITCH_ENUM_CAST (XTYPE (obj)))
5916 case Lisp_String:
5918 register struct Lisp_String *ptr = XSTRING (obj);
5919 if (STRING_MARKED_P (ptr))
5920 break;
5921 CHECK_ALLOCATED_AND_LIVE (live_string_p);
5922 MARK_STRING (ptr);
5923 MARK_INTERVAL_TREE (ptr->intervals);
5924 #ifdef GC_CHECK_STRING_BYTES
5925 /* Check that the string size recorded in the string is the
5926 same as the one recorded in the sdata structure. */
5927 CHECK_STRING_BYTES (ptr);
5928 #endif /* GC_CHECK_STRING_BYTES */
5930 break;
5932 case Lisp_Vectorlike:
5934 register struct Lisp_Vector *ptr = XVECTOR (obj);
5935 register ptrdiff_t pvectype;
5937 if (VECTOR_MARKED_P (ptr))
5938 break;
5940 #ifdef GC_CHECK_MARKED_OBJECTS
5941 m = mem_find (po);
5942 if (m == MEM_NIL && !SUBRP (obj)
5943 && po != &buffer_defaults
5944 && po != &buffer_local_symbols)
5945 abort ();
5946 #endif /* GC_CHECK_MARKED_OBJECTS */
5948 if (ptr->header.size & PSEUDOVECTOR_FLAG)
5949 pvectype = ((ptr->header.size & PVEC_TYPE_MASK)
5950 >> PSEUDOVECTOR_SIZE_BITS);
5951 else
5952 pvectype = 0;
5954 if (pvectype != PVEC_SUBR && pvectype != PVEC_BUFFER)
5955 CHECK_LIVE (live_vector_p);
5957 switch (pvectype)
5959 case PVEC_BUFFER:
5960 #ifdef GC_CHECK_MARKED_OBJECTS
5961 if (po != &buffer_defaults && po != &buffer_local_symbols)
5963 struct buffer *b;
5964 FOR_EACH_BUFFER (b)
5965 if (b == po)
5966 break;
5967 if (b == NULL)
5968 abort ();
5970 #endif /* GC_CHECK_MARKED_OBJECTS */
5971 mark_buffer ((struct buffer *) ptr);
5972 break;
5974 case PVEC_COMPILED:
5975 { /* We could treat this just like a vector, but it is better
5976 to save the COMPILED_CONSTANTS element for last and avoid
5977 recursion there. */
5978 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5979 int i;
5981 VECTOR_MARK (ptr);
5982 for (i = 0; i < size; i++)
5983 if (i != COMPILED_CONSTANTS)
5984 mark_object (ptr->contents[i]);
5985 if (size > COMPILED_CONSTANTS)
5987 obj = ptr->contents[COMPILED_CONSTANTS];
5988 goto loop;
5991 break;
5993 case PVEC_FRAME:
5995 mark_vectorlike (ptr);
5996 mark_face_cache (((struct frame *) ptr)->face_cache);
5998 break;
6000 case PVEC_WINDOW:
6002 struct window *w = (struct window *) ptr;
6004 mark_vectorlike (ptr);
6005 /* Mark glyphs for leaf windows. Marking window
6006 matrices is sufficient because frame matrices
6007 use the same glyph memory. */
6008 if (NILP (w->hchild) && NILP (w->vchild) && w->current_matrix)
6010 mark_glyph_matrix (w->current_matrix);
6011 mark_glyph_matrix (w->desired_matrix);
6014 break;
6016 case PVEC_HASH_TABLE:
6018 struct Lisp_Hash_Table *h = (struct Lisp_Hash_Table *) ptr;
6020 mark_vectorlike (ptr);
6021 /* If hash table is not weak, mark all keys and values.
6022 For weak tables, mark only the vector. */
6023 if (NILP (h->weak))
6024 mark_object (h->key_and_value);
6025 else
6026 VECTOR_MARK (XVECTOR (h->key_and_value));
6028 break;
6030 case PVEC_CHAR_TABLE:
6031 mark_char_table (ptr);
6032 break;
6034 case PVEC_BOOL_VECTOR:
6035 /* No Lisp_Objects to mark in a bool vector. */
6036 VECTOR_MARK (ptr);
6037 break;
6039 case PVEC_SUBR:
6040 break;
6042 case PVEC_FREE:
6043 abort ();
6045 default:
6046 mark_vectorlike (ptr);
6049 break;
6051 case Lisp_Symbol:
6053 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
6054 struct Lisp_Symbol *ptrx;
6056 if (ptr->gcmarkbit)
6057 break;
6058 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
6059 ptr->gcmarkbit = 1;
6060 mark_object (ptr->function);
6061 mark_object (ptr->plist);
6062 switch (ptr->redirect)
6064 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
6065 case SYMBOL_VARALIAS:
6067 Lisp_Object tem;
6068 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
6069 mark_object (tem);
6070 break;
6072 case SYMBOL_LOCALIZED:
6074 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
6075 /* If the value is forwarded to a buffer or keyboard field,
6076 these are marked when we see the corresponding object.
6077 And if it's forwarded to a C variable, either it's not
6078 a Lisp_Object var, or it's staticpro'd already. */
6079 mark_object (blv->where);
6080 mark_object (blv->valcell);
6081 mark_object (blv->defcell);
6082 break;
6084 case SYMBOL_FORWARDED:
6085 /* If the value is forwarded to a buffer or keyboard field,
6086 these are marked when we see the corresponding object.
6087 And if it's forwarded to a C variable, either it's not
6088 a Lisp_Object var, or it's staticpro'd already. */
6089 break;
6090 default: abort ();
6092 if (!PURE_POINTER_P (XSTRING (ptr->xname)))
6093 MARK_STRING (XSTRING (ptr->xname));
6094 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr->xname));
6096 ptr = ptr->next;
6097 if (ptr)
6099 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun. */
6100 XSETSYMBOL (obj, ptrx);
6101 goto loop;
6104 break;
6106 case Lisp_Misc:
6107 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
6109 if (XMISCANY (obj)->gcmarkbit)
6110 break;
6112 switch (XMISCTYPE (obj))
6114 case Lisp_Misc_Marker:
6115 /* DO NOT mark thru the marker's chain.
6116 The buffer's markers chain does not preserve markers from gc;
6117 instead, markers are removed from the chain when freed by gc. */
6118 XMISCANY (obj)->gcmarkbit = 1;
6119 break;
6121 case Lisp_Misc_Save_Value:
6122 XMISCANY (obj)->gcmarkbit = 1;
6123 #if GC_MARK_STACK
6125 register struct Lisp_Save_Value *ptr = XSAVE_VALUE (obj);
6126 /* If DOGC is set, POINTER is the address of a memory
6127 area containing INTEGER potential Lisp_Objects. */
6128 if (ptr->dogc)
6130 Lisp_Object *p = (Lisp_Object *) ptr->pointer;
6131 ptrdiff_t nelt;
6132 for (nelt = ptr->integer; nelt > 0; nelt--, p++)
6133 mark_maybe_object (*p);
6136 #endif
6137 break;
6139 case Lisp_Misc_Overlay:
6140 mark_overlay (XOVERLAY (obj));
6141 break;
6143 default:
6144 abort ();
6146 break;
6148 case Lisp_Cons:
6150 register struct Lisp_Cons *ptr = XCONS (obj);
6151 if (CONS_MARKED_P (ptr))
6152 break;
6153 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
6154 CONS_MARK (ptr);
6155 /* If the cdr is nil, avoid recursion for the car. */
6156 if (EQ (ptr->u.cdr, Qnil))
6158 obj = ptr->car;
6159 cdr_count = 0;
6160 goto loop;
6162 mark_object (ptr->car);
6163 obj = ptr->u.cdr;
6164 cdr_count++;
6165 if (cdr_count == mark_object_loop_halt)
6166 abort ();
6167 goto loop;
6170 case Lisp_Float:
6171 CHECK_ALLOCATED_AND_LIVE (live_float_p);
6172 FLOAT_MARK (XFLOAT (obj));
6173 break;
6175 case_Lisp_Int:
6176 break;
6178 default:
6179 abort ();
6182 #undef CHECK_LIVE
6183 #undef CHECK_ALLOCATED
6184 #undef CHECK_ALLOCATED_AND_LIVE
6186 /* Mark the Lisp pointers in the terminal objects.
6187 Called by Fgarbage_collect. */
6189 static void
6190 mark_terminals (void)
6192 struct terminal *t;
6193 for (t = terminal_list; t; t = t->next_terminal)
6195 eassert (t->name != NULL);
6196 #ifdef HAVE_WINDOW_SYSTEM
6197 /* If a terminal object is reachable from a stacpro'ed object,
6198 it might have been marked already. Make sure the image cache
6199 gets marked. */
6200 mark_image_cache (t->image_cache);
6201 #endif /* HAVE_WINDOW_SYSTEM */
6202 if (!VECTOR_MARKED_P (t))
6203 mark_vectorlike ((struct Lisp_Vector *)t);
6209 /* Value is non-zero if OBJ will survive the current GC because it's
6210 either marked or does not need to be marked to survive. */
6213 survives_gc_p (Lisp_Object obj)
6215 int survives_p;
6217 switch (XTYPE (obj))
6219 case_Lisp_Int:
6220 survives_p = 1;
6221 break;
6223 case Lisp_Symbol:
6224 survives_p = XSYMBOL (obj)->gcmarkbit;
6225 break;
6227 case Lisp_Misc:
6228 survives_p = XMISCANY (obj)->gcmarkbit;
6229 break;
6231 case Lisp_String:
6232 survives_p = STRING_MARKED_P (XSTRING (obj));
6233 break;
6235 case Lisp_Vectorlike:
6236 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
6237 break;
6239 case Lisp_Cons:
6240 survives_p = CONS_MARKED_P (XCONS (obj));
6241 break;
6243 case Lisp_Float:
6244 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
6245 break;
6247 default:
6248 abort ();
6251 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
6256 /* Sweep: find all structures not marked, and free them. */
6258 static void
6259 gc_sweep (void)
6261 /* Remove or mark entries in weak hash tables.
6262 This must be done before any object is unmarked. */
6263 sweep_weak_hash_tables ();
6265 sweep_strings ();
6266 #ifdef GC_CHECK_STRING_BYTES
6267 if (!noninteractive)
6268 check_string_bytes (1);
6269 #endif
6271 /* Put all unmarked conses on free list */
6273 register struct cons_block *cblk;
6274 struct cons_block **cprev = &cons_block;
6275 register int lim = cons_block_index;
6276 EMACS_INT num_free = 0, num_used = 0;
6278 cons_free_list = 0;
6280 for (cblk = cons_block; cblk; cblk = *cprev)
6282 register int i = 0;
6283 int this_free = 0;
6284 int ilim = (lim + BITS_PER_INT - 1) / BITS_PER_INT;
6286 /* Scan the mark bits an int at a time. */
6287 for (i = 0; i < ilim; i++)
6289 if (cblk->gcmarkbits[i] == -1)
6291 /* Fast path - all cons cells for this int are marked. */
6292 cblk->gcmarkbits[i] = 0;
6293 num_used += BITS_PER_INT;
6295 else
6297 /* Some cons cells for this int are not marked.
6298 Find which ones, and free them. */
6299 int start, pos, stop;
6301 start = i * BITS_PER_INT;
6302 stop = lim - start;
6303 if (stop > BITS_PER_INT)
6304 stop = BITS_PER_INT;
6305 stop += start;
6307 for (pos = start; pos < stop; pos++)
6309 if (!CONS_MARKED_P (&cblk->conses[pos]))
6311 this_free++;
6312 cblk->conses[pos].u.chain = cons_free_list;
6313 cons_free_list = &cblk->conses[pos];
6314 #if GC_MARK_STACK
6315 cons_free_list->car = Vdead;
6316 #endif
6318 else
6320 num_used++;
6321 CONS_UNMARK (&cblk->conses[pos]);
6327 lim = CONS_BLOCK_SIZE;
6328 /* If this block contains only free conses and we have already
6329 seen more than two blocks worth of free conses then deallocate
6330 this block. */
6331 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
6333 *cprev = cblk->next;
6334 /* Unhook from the free list. */
6335 cons_free_list = cblk->conses[0].u.chain;
6336 lisp_align_free (cblk);
6338 else
6340 num_free += this_free;
6341 cprev = &cblk->next;
6344 total_conses = num_used;
6345 total_free_conses = num_free;
6348 /* Put all unmarked floats on free list */
6350 register struct float_block *fblk;
6351 struct float_block **fprev = &float_block;
6352 register int lim = float_block_index;
6353 EMACS_INT num_free = 0, num_used = 0;
6355 float_free_list = 0;
6357 for (fblk = float_block; fblk; fblk = *fprev)
6359 register int i;
6360 int this_free = 0;
6361 for (i = 0; i < lim; i++)
6362 if (!FLOAT_MARKED_P (&fblk->floats[i]))
6364 this_free++;
6365 fblk->floats[i].u.chain = float_free_list;
6366 float_free_list = &fblk->floats[i];
6368 else
6370 num_used++;
6371 FLOAT_UNMARK (&fblk->floats[i]);
6373 lim = FLOAT_BLOCK_SIZE;
6374 /* If this block contains only free floats and we have already
6375 seen more than two blocks worth of free floats then deallocate
6376 this block. */
6377 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6379 *fprev = fblk->next;
6380 /* Unhook from the free list. */
6381 float_free_list = fblk->floats[0].u.chain;
6382 lisp_align_free (fblk);
6384 else
6386 num_free += this_free;
6387 fprev = &fblk->next;
6390 total_floats = num_used;
6391 total_free_floats = num_free;
6394 /* Put all unmarked intervals on free list */
6396 register struct interval_block *iblk;
6397 struct interval_block **iprev = &interval_block;
6398 register int lim = interval_block_index;
6399 EMACS_INT num_free = 0, num_used = 0;
6401 interval_free_list = 0;
6403 for (iblk = interval_block; iblk; iblk = *iprev)
6405 register int i;
6406 int this_free = 0;
6408 for (i = 0; i < lim; i++)
6410 if (!iblk->intervals[i].gcmarkbit)
6412 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
6413 interval_free_list = &iblk->intervals[i];
6414 this_free++;
6416 else
6418 num_used++;
6419 iblk->intervals[i].gcmarkbit = 0;
6422 lim = INTERVAL_BLOCK_SIZE;
6423 /* If this block contains only free intervals and we have already
6424 seen more than two blocks worth of free intervals then
6425 deallocate this block. */
6426 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6428 *iprev = iblk->next;
6429 /* Unhook from the free list. */
6430 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
6431 lisp_free (iblk);
6433 else
6435 num_free += this_free;
6436 iprev = &iblk->next;
6439 total_intervals = num_used;
6440 total_free_intervals = num_free;
6443 /* Put all unmarked symbols on free list */
6445 register struct symbol_block *sblk;
6446 struct symbol_block **sprev = &symbol_block;
6447 register int lim = symbol_block_index;
6448 EMACS_INT num_free = 0, num_used = 0;
6450 symbol_free_list = NULL;
6452 for (sblk = symbol_block; sblk; sblk = *sprev)
6454 int this_free = 0;
6455 union aligned_Lisp_Symbol *sym = sblk->symbols;
6456 union aligned_Lisp_Symbol *end = sym + lim;
6458 for (; sym < end; ++sym)
6460 /* Check if the symbol was created during loadup. In such a case
6461 it might be pointed to by pure bytecode which we don't trace,
6462 so we conservatively assume that it is live. */
6463 int pure_p = PURE_POINTER_P (XSTRING (sym->s.xname));
6465 if (!sym->s.gcmarkbit && !pure_p)
6467 if (sym->s.redirect == SYMBOL_LOCALIZED)
6468 xfree (SYMBOL_BLV (&sym->s));
6469 sym->s.next = symbol_free_list;
6470 symbol_free_list = &sym->s;
6471 #if GC_MARK_STACK
6472 symbol_free_list->function = Vdead;
6473 #endif
6474 ++this_free;
6476 else
6478 ++num_used;
6479 if (!pure_p)
6480 UNMARK_STRING (XSTRING (sym->s.xname));
6481 sym->s.gcmarkbit = 0;
6485 lim = SYMBOL_BLOCK_SIZE;
6486 /* If this block contains only free symbols and we have already
6487 seen more than two blocks worth of free symbols then deallocate
6488 this block. */
6489 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6491 *sprev = sblk->next;
6492 /* Unhook from the free list. */
6493 symbol_free_list = sblk->symbols[0].s.next;
6494 lisp_free (sblk);
6496 else
6498 num_free += this_free;
6499 sprev = &sblk->next;
6502 total_symbols = num_used;
6503 total_free_symbols = num_free;
6506 /* Put all unmarked misc's on free list.
6507 For a marker, first unchain it from the buffer it points into. */
6509 register struct marker_block *mblk;
6510 struct marker_block **mprev = &marker_block;
6511 register int lim = marker_block_index;
6512 EMACS_INT num_free = 0, num_used = 0;
6514 marker_free_list = 0;
6516 for (mblk = marker_block; mblk; mblk = *mprev)
6518 register int i;
6519 int this_free = 0;
6521 for (i = 0; i < lim; i++)
6523 if (!mblk->markers[i].m.u_any.gcmarkbit)
6525 if (mblk->markers[i].m.u_any.type == Lisp_Misc_Marker)
6526 unchain_marker (&mblk->markers[i].m.u_marker);
6527 /* Set the type of the freed object to Lisp_Misc_Free.
6528 We could leave the type alone, since nobody checks it,
6529 but this might catch bugs faster. */
6530 mblk->markers[i].m.u_marker.type = Lisp_Misc_Free;
6531 mblk->markers[i].m.u_free.chain = marker_free_list;
6532 marker_free_list = &mblk->markers[i].m;
6533 this_free++;
6535 else
6537 num_used++;
6538 mblk->markers[i].m.u_any.gcmarkbit = 0;
6541 lim = MARKER_BLOCK_SIZE;
6542 /* If this block contains only free markers and we have already
6543 seen more than two blocks worth of free markers then deallocate
6544 this block. */
6545 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6547 *mprev = mblk->next;
6548 /* Unhook from the free list. */
6549 marker_free_list = mblk->markers[0].m.u_free.chain;
6550 lisp_free (mblk);
6552 else
6554 num_free += this_free;
6555 mprev = &mblk->next;
6559 total_markers = num_used;
6560 total_free_markers = num_free;
6563 /* Free all unmarked buffers */
6565 register struct buffer *buffer = all_buffers, *prev = 0, *next;
6567 total_buffers = 0;
6568 while (buffer)
6569 if (!VECTOR_MARKED_P (buffer))
6571 if (prev)
6572 prev->header.next = buffer->header.next;
6573 else
6574 all_buffers = buffer->header.next.buffer;
6575 next = buffer->header.next.buffer;
6576 lisp_free (buffer);
6577 buffer = next;
6579 else
6581 VECTOR_UNMARK (buffer);
6582 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
6583 total_buffers++;
6584 prev = buffer, buffer = buffer->header.next.buffer;
6588 sweep_vectors ();
6590 #ifdef GC_CHECK_STRING_BYTES
6591 if (!noninteractive)
6592 check_string_bytes (1);
6593 #endif
6599 /* Debugging aids. */
6601 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
6602 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6603 This may be helpful in debugging Emacs's memory usage.
6604 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6605 (void)
6607 Lisp_Object end;
6609 XSETINT (end, (intptr_t) (char *) sbrk (0) / 1024);
6611 return end;
6614 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
6615 doc: /* Return a list of counters that measure how much consing there has been.
6616 Each of these counters increments for a certain kind of object.
6617 The counters wrap around from the largest positive integer to zero.
6618 Garbage collection does not decrease them.
6619 The elements of the value are as follows:
6620 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6621 All are in units of 1 = one object consed
6622 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6623 objects consed.
6624 MISCS include overlays, markers, and some internal types.
6625 Frames, windows, buffers, and subprocesses count as vectors
6626 (but the contents of a buffer's text do not count here). */)
6627 (void)
6629 Lisp_Object consed[8];
6631 consed[0] = bounded_number (cons_cells_consed);
6632 consed[1] = bounded_number (floats_consed);
6633 consed[2] = bounded_number (vector_cells_consed);
6634 consed[3] = bounded_number (symbols_consed);
6635 consed[4] = bounded_number (string_chars_consed);
6636 consed[5] = bounded_number (misc_objects_consed);
6637 consed[6] = bounded_number (intervals_consed);
6638 consed[7] = bounded_number (strings_consed);
6640 return Flist (8, consed);
6643 /* Find at most FIND_MAX symbols which have OBJ as their value or
6644 function. This is used in gdbinit's `xwhichsymbols' command. */
6646 Lisp_Object
6647 which_symbols (Lisp_Object obj, EMACS_INT find_max)
6649 struct symbol_block *sblk;
6650 ptrdiff_t gc_count = inhibit_garbage_collection ();
6651 Lisp_Object found = Qnil;
6653 if (! DEADP (obj))
6655 for (sblk = symbol_block; sblk; sblk = sblk->next)
6657 union aligned_Lisp_Symbol *aligned_sym = sblk->symbols;
6658 int bn;
6660 for (bn = 0; bn < SYMBOL_BLOCK_SIZE; bn++, aligned_sym++)
6662 struct Lisp_Symbol *sym = &aligned_sym->s;
6663 Lisp_Object val;
6664 Lisp_Object tem;
6666 if (sblk == symbol_block && bn >= symbol_block_index)
6667 break;
6669 XSETSYMBOL (tem, sym);
6670 val = find_symbol_value (tem);
6671 if (EQ (val, obj)
6672 || EQ (sym->function, obj)
6673 || (!NILP (sym->function)
6674 && COMPILEDP (sym->function)
6675 && EQ (AREF (sym->function, COMPILED_BYTECODE), obj))
6676 || (!NILP (val)
6677 && COMPILEDP (val)
6678 && EQ (AREF (val, COMPILED_BYTECODE), obj)))
6680 found = Fcons (tem, found);
6681 if (--find_max == 0)
6682 goto out;
6688 out:
6689 unbind_to (gc_count, Qnil);
6690 return found;
6693 #ifdef ENABLE_CHECKING
6694 int suppress_checking;
6696 void
6697 die (const char *msg, const char *file, int line)
6699 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: %s\r\n",
6700 file, line, msg);
6701 abort ();
6703 #endif
6705 /* Initialization */
6707 void
6708 init_alloc_once (void)
6710 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
6711 purebeg = PUREBEG;
6712 pure_size = PURESIZE;
6714 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
6715 mem_init ();
6716 Vdead = make_pure_string ("DEAD", 4, 4, 0);
6717 #endif
6719 #ifdef DOUG_LEA_MALLOC
6720 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
6721 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
6722 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
6723 #endif
6724 init_strings ();
6725 init_vectors ();
6727 #ifdef REL_ALLOC
6728 malloc_hysteresis = 32;
6729 #else
6730 malloc_hysteresis = 0;
6731 #endif
6733 refill_memory_reserve ();
6734 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
6737 void
6738 init_alloc (void)
6740 gcprolist = 0;
6741 byte_stack_list = 0;
6742 #if GC_MARK_STACK
6743 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
6744 setjmp_tested_p = longjmps_done = 0;
6745 #endif
6746 #endif
6747 Vgc_elapsed = make_float (0.0);
6748 gcs_done = 0;
6751 void
6752 syms_of_alloc (void)
6754 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
6755 doc: /* Number of bytes of consing between garbage collections.
6756 Garbage collection can happen automatically once this many bytes have been
6757 allocated since the last garbage collection. All data types count.
6759 Garbage collection happens automatically only when `eval' is called.
6761 By binding this temporarily to a large number, you can effectively
6762 prevent garbage collection during a part of the program.
6763 See also `gc-cons-percentage'. */);
6765 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
6766 doc: /* Portion of the heap used for allocation.
6767 Garbage collection can happen automatically once this portion of the heap
6768 has been allocated since the last garbage collection.
6769 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
6770 Vgc_cons_percentage = make_float (0.1);
6772 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
6773 doc: /* Number of bytes of shareable Lisp data allocated so far. */);
6775 DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
6776 doc: /* Number of cons cells that have been consed so far. */);
6778 DEFVAR_INT ("floats-consed", floats_consed,
6779 doc: /* Number of floats that have been consed so far. */);
6781 DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
6782 doc: /* Number of vector cells that have been consed so far. */);
6784 DEFVAR_INT ("symbols-consed", symbols_consed,
6785 doc: /* Number of symbols that have been consed so far. */);
6787 DEFVAR_INT ("string-chars-consed", string_chars_consed,
6788 doc: /* Number of string characters that have been consed so far. */);
6790 DEFVAR_INT ("misc-objects-consed", misc_objects_consed,
6791 doc: /* Number of miscellaneous objects that have been consed so far.
6792 These include markers and overlays, plus certain objects not visible
6793 to users. */);
6795 DEFVAR_INT ("intervals-consed", intervals_consed,
6796 doc: /* Number of intervals that have been consed so far. */);
6798 DEFVAR_INT ("strings-consed", strings_consed,
6799 doc: /* Number of strings that have been consed so far. */);
6801 DEFVAR_LISP ("purify-flag", Vpurify_flag,
6802 doc: /* Non-nil means loading Lisp code in order to dump an executable.
6803 This means that certain objects should be allocated in shared (pure) space.
6804 It can also be set to a hash-table, in which case this table is used to
6805 do hash-consing of the objects allocated to pure space. */);
6807 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
6808 doc: /* Non-nil means display messages at start and end of garbage collection. */);
6809 garbage_collection_messages = 0;
6811 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
6812 doc: /* Hook run after garbage collection has finished. */);
6813 Vpost_gc_hook = Qnil;
6814 DEFSYM (Qpost_gc_hook, "post-gc-hook");
6816 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
6817 doc: /* Precomputed `signal' argument for memory-full error. */);
6818 /* We build this in advance because if we wait until we need it, we might
6819 not be able to allocate the memory to hold it. */
6820 Vmemory_signal_data
6821 = pure_cons (Qerror,
6822 pure_cons (build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"), Qnil));
6824 DEFVAR_LISP ("memory-full", Vmemory_full,
6825 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
6826 Vmemory_full = Qnil;
6828 DEFSYM (Qstring_bytes, "string-bytes");
6829 DEFSYM (Qvector_slots, "vector-slots");
6830 DEFSYM (Qheap, "heap");
6832 DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
6833 DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
6835 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
6836 doc: /* Accumulated time elapsed in garbage collections.
6837 The time is in seconds as a floating point value. */);
6838 DEFVAR_INT ("gcs-done", gcs_done,
6839 doc: /* Accumulated number of garbage collections done. */);
6841 defsubr (&Scons);
6842 defsubr (&Slist);
6843 defsubr (&Svector);
6844 defsubr (&Smake_byte_code);
6845 defsubr (&Smake_list);
6846 defsubr (&Smake_vector);
6847 defsubr (&Smake_string);
6848 defsubr (&Smake_bool_vector);
6849 defsubr (&Smake_symbol);
6850 defsubr (&Smake_marker);
6851 defsubr (&Spurecopy);
6852 defsubr (&Sgarbage_collect);
6853 defsubr (&Smemory_limit);
6854 defsubr (&Smemory_use_counts);
6856 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
6857 defsubr (&Sgc_status);
6858 #endif