Remove HIDE_LISP_IMPLEMENTATION and cleanup cons free list check.
[emacs.git] / src / alloc.c
blobf6f656fffa30d89399790600262743e18bf5b23e
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 #include "lisp.h"
33 #include "process.h"
34 #include "intervals.h"
35 #include "puresize.h"
36 #include "character.h"
37 #include "buffer.h"
38 #include "window.h"
39 #include "keyboard.h"
40 #include "frame.h"
41 #include "blockinput.h"
42 #include "syssignal.h"
43 #include "termhooks.h" /* For struct terminal. */
44 #include <setjmp.h>
45 #include <verify.h>
47 /* GC_CHECK_MARKED_OBJECTS means do sanity checks on allocated objects.
48 Doable only if GC_MARK_STACK. */
49 #if ! GC_MARK_STACK
50 # undef GC_CHECK_MARKED_OBJECTS
51 #endif
53 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
54 memory. Can do this only if using gmalloc.c and if not checking
55 marked objects. */
57 #if (defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC \
58 || defined GC_CHECK_MARKED_OBJECTS)
59 #undef GC_MALLOC_CHECK
60 #endif
62 #include <unistd.h>
63 #ifndef HAVE_UNISTD_H
64 extern void *sbrk ();
65 #endif
67 #include <fcntl.h>
69 #ifdef WINDOWSNT
70 #include "w32.h"
71 #endif
73 #ifdef DOUG_LEA_MALLOC
75 #include <malloc.h>
77 /* Specify maximum number of areas to mmap. It would be nice to use a
78 value that explicitly means "no limit". */
80 #define MMAP_MAX_AREAS 100000000
82 #else /* not DOUG_LEA_MALLOC */
84 /* The following come from gmalloc.c. */
86 extern size_t _bytes_used;
87 extern size_t __malloc_extra_blocks;
88 extern void *_malloc_internal (size_t);
89 extern void _free_internal (void *);
91 #endif /* not DOUG_LEA_MALLOC */
93 #if ! defined SYSTEM_MALLOC && ! defined SYNC_INPUT
94 #ifdef HAVE_PTHREAD
96 /* When GTK uses the file chooser dialog, different backends can be loaded
97 dynamically. One such a backend is the Gnome VFS backend that gets loaded
98 if you run Gnome. That backend creates several threads and also allocates
99 memory with malloc.
101 Also, gconf and gsettings may create several threads.
103 If Emacs sets malloc hooks (! SYSTEM_MALLOC) and the emacs_blocked_*
104 functions below are called from malloc, there is a chance that one
105 of these threads preempts the Emacs main thread and the hook variables
106 end up in an inconsistent state. So we have a mutex to prevent that (note
107 that the backend handles concurrent access to malloc within its own threads
108 but Emacs code running in the main thread is not included in that control).
110 When UNBLOCK_INPUT is called, reinvoke_input_signal may be called. If this
111 happens in one of the backend threads we will have two threads that tries
112 to run Emacs code at once, and the code is not prepared for that.
113 To prevent that, we only call BLOCK/UNBLOCK from the main thread. */
115 static pthread_mutex_t alloc_mutex;
117 #define BLOCK_INPUT_ALLOC \
118 do \
120 if (pthread_equal (pthread_self (), main_thread)) \
121 BLOCK_INPUT; \
122 pthread_mutex_lock (&alloc_mutex); \
124 while (0)
125 #define UNBLOCK_INPUT_ALLOC \
126 do \
128 pthread_mutex_unlock (&alloc_mutex); \
129 if (pthread_equal (pthread_self (), main_thread)) \
130 UNBLOCK_INPUT; \
132 while (0)
134 #else /* ! defined HAVE_PTHREAD */
136 #define BLOCK_INPUT_ALLOC BLOCK_INPUT
137 #define UNBLOCK_INPUT_ALLOC UNBLOCK_INPUT
139 #endif /* ! defined HAVE_PTHREAD */
140 #endif /* ! defined SYSTEM_MALLOC && ! defined SYNC_INPUT */
142 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
143 to a struct Lisp_String. */
145 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
146 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
147 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
149 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
150 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
151 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
153 /* Value is the number of bytes of S, a pointer to a struct Lisp_String.
154 Be careful during GC, because S->size contains the mark bit for
155 strings. */
157 #define GC_STRING_BYTES(S) (STRING_BYTES (S))
159 /* Default value of gc_cons_threshold (see below). */
161 #define GC_DEFAULT_THRESHOLD (100000 * sizeof (Lisp_Object))
163 /* Global variables. */
164 struct emacs_globals globals;
166 /* Number of bytes of consing done since the last gc. */
168 EMACS_INT consing_since_gc;
170 /* Similar minimum, computed from Vgc_cons_percentage. */
172 EMACS_INT gc_relative_threshold;
174 /* Minimum number of bytes of consing since GC before next GC,
175 when memory is full. */
177 EMACS_INT memory_full_cons_threshold;
179 /* Nonzero during GC. */
181 int gc_in_progress;
183 /* Nonzero means abort if try to GC.
184 This is for code which is written on the assumption that
185 no GC will happen, so as to verify that assumption. */
187 int abort_on_gc;
189 /* Number of live and free conses etc. */
191 static EMACS_INT total_conses, total_markers, total_symbols, total_buffers;
192 static EMACS_INT total_free_conses, total_free_markers, total_free_symbols;
193 static EMACS_INT total_free_floats, total_floats;
195 /* Points to memory space allocated as "spare", to be freed if we run
196 out of memory. We keep one large block, four cons-blocks, and
197 two string blocks. */
199 static char *spare_memory[7];
201 /* Amount of spare memory to keep in large reserve block, or to see
202 whether this much is available when malloc fails on a larger request. */
204 #define SPARE_MEMORY (1 << 14)
206 /* Number of extra blocks malloc should get when it needs more core. */
208 static int malloc_hysteresis;
210 /* Initialize it to a nonzero value to force it into data space
211 (rather than bss space). That way unexec will remap it into text
212 space (pure), on some systems. We have not implemented the
213 remapping on more recent systems because this is less important
214 nowadays than in the days of small memories and timesharing. */
216 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
217 #define PUREBEG (char *) pure
219 /* Pointer to the pure area, and its size. */
221 static char *purebeg;
222 static ptrdiff_t pure_size;
224 /* Number of bytes of pure storage used before pure storage overflowed.
225 If this is non-zero, this implies that an overflow occurred. */
227 static ptrdiff_t pure_bytes_used_before_overflow;
229 /* Value is non-zero if P points into pure space. */
231 #define PURE_POINTER_P(P) \
232 ((uintptr_t) (P) - (uintptr_t) purebeg <= pure_size)
234 /* Index in pure at which next pure Lisp object will be allocated.. */
236 static ptrdiff_t pure_bytes_used_lisp;
238 /* Number of bytes allocated for non-Lisp objects in pure storage. */
240 static ptrdiff_t pure_bytes_used_non_lisp;
242 /* If nonzero, this is a warning delivered by malloc and not yet
243 displayed. */
245 const char *pending_malloc_warning;
247 /* Maximum amount of C stack to save when a GC happens. */
249 #ifndef MAX_SAVE_STACK
250 #define MAX_SAVE_STACK 16000
251 #endif
253 /* Buffer in which we save a copy of the C stack at each GC. */
255 #if MAX_SAVE_STACK > 0
256 static char *stack_copy;
257 static ptrdiff_t stack_copy_size;
258 #endif
260 static Lisp_Object Qstring_bytes, Qvector_slots, Qheap;
261 static Lisp_Object Qgc_cons_threshold;
262 Lisp_Object Qchar_table_extra_slots;
264 /* Hook run after GC has finished. */
266 static Lisp_Object Qpost_gc_hook;
268 static void mark_terminals (void);
269 static void gc_sweep (void);
270 static Lisp_Object make_pure_vector (ptrdiff_t);
271 static void mark_glyph_matrix (struct glyph_matrix *);
272 static void mark_face_cache (struct face_cache *);
274 #if !defined REL_ALLOC || defined SYSTEM_MALLOC
275 static void refill_memory_reserve (void);
276 #endif
277 static struct Lisp_String *allocate_string (void);
278 static void compact_small_strings (void);
279 static void free_large_strings (void);
280 static void sweep_strings (void);
281 static void free_misc (Lisp_Object);
282 extern Lisp_Object which_symbols (Lisp_Object, EMACS_INT) EXTERNALLY_VISIBLE;
284 /* Handy constants for vectorlike objects. */
285 enum
287 header_size = offsetof (struct Lisp_Vector, contents),
288 bool_header_size = offsetof (struct Lisp_Bool_Vector, data),
289 word_size = sizeof (Lisp_Object)
292 /* When scanning the C stack for live Lisp objects, Emacs keeps track
293 of what memory allocated via lisp_malloc is intended for what
294 purpose. This enumeration specifies the type of memory. */
296 enum mem_type
298 MEM_TYPE_NON_LISP,
299 MEM_TYPE_BUFFER,
300 MEM_TYPE_CONS,
301 MEM_TYPE_STRING,
302 MEM_TYPE_MISC,
303 MEM_TYPE_SYMBOL,
304 MEM_TYPE_FLOAT,
305 /* We used to keep separate mem_types for subtypes of vectors such as
306 process, hash_table, frame, terminal, and window, but we never made
307 use of the distinction, so it only caused source-code complexity
308 and runtime slowdown. Minor but pointless. */
309 MEM_TYPE_VECTORLIKE,
310 /* Special type to denote vector blocks. */
311 MEM_TYPE_VECTOR_BLOCK
314 static void *lisp_malloc (size_t, enum mem_type);
317 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
319 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
320 #include <stdio.h> /* For fprintf. */
321 #endif
323 /* A unique object in pure space used to make some Lisp objects
324 on free lists recognizable in O(1). */
326 static Lisp_Object Vdead;
327 #define DEADP(x) EQ (x, Vdead)
329 #ifdef GC_MALLOC_CHECK
331 enum mem_type allocated_mem_type;
333 #endif /* GC_MALLOC_CHECK */
335 /* A node in the red-black tree describing allocated memory containing
336 Lisp data. Each such block is recorded with its start and end
337 address when it is allocated, and removed from the tree when it
338 is freed.
340 A red-black tree is a balanced binary tree with the following
341 properties:
343 1. Every node is either red or black.
344 2. Every leaf is black.
345 3. If a node is red, then both of its children are black.
346 4. Every simple path from a node to a descendant leaf contains
347 the same number of black nodes.
348 5. The root is always black.
350 When nodes are inserted into the tree, or deleted from the tree,
351 the tree is "fixed" so that these properties are always true.
353 A red-black tree with N internal nodes has height at most 2
354 log(N+1). Searches, insertions and deletions are done in O(log N).
355 Please see a text book about data structures for a detailed
356 description of red-black trees. Any book worth its salt should
357 describe them. */
359 struct mem_node
361 /* Children of this node. These pointers are never NULL. When there
362 is no child, the value is MEM_NIL, which points to a dummy node. */
363 struct mem_node *left, *right;
365 /* The parent of this node. In the root node, this is NULL. */
366 struct mem_node *parent;
368 /* Start and end of allocated region. */
369 void *start, *end;
371 /* Node color. */
372 enum {MEM_BLACK, MEM_RED} color;
374 /* Memory type. */
375 enum mem_type type;
378 /* Base address of stack. Set in main. */
380 Lisp_Object *stack_base;
382 /* Root of the tree describing allocated Lisp memory. */
384 static struct mem_node *mem_root;
386 /* Lowest and highest known address in the heap. */
388 static void *min_heap_address, *max_heap_address;
390 /* Sentinel node of the tree. */
392 static struct mem_node mem_z;
393 #define MEM_NIL &mem_z
395 static struct Lisp_Vector *allocate_vectorlike (ptrdiff_t);
396 static void lisp_free (void *);
397 static void mark_stack (void);
398 static int live_vector_p (struct mem_node *, void *);
399 static int live_buffer_p (struct mem_node *, void *);
400 static int live_string_p (struct mem_node *, void *);
401 static int live_cons_p (struct mem_node *, void *);
402 static int live_symbol_p (struct mem_node *, void *);
403 static int live_float_p (struct mem_node *, void *);
404 static int live_misc_p (struct mem_node *, void *);
405 static void mark_maybe_object (Lisp_Object);
406 static void mark_memory (void *, void *);
407 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
408 static void mem_init (void);
409 static struct mem_node *mem_insert (void *, void *, enum mem_type);
410 static void mem_insert_fixup (struct mem_node *);
411 #endif
412 static void mem_rotate_left (struct mem_node *);
413 static void mem_rotate_right (struct mem_node *);
414 static void mem_delete (struct mem_node *);
415 static void mem_delete_fixup (struct mem_node *);
416 static inline struct mem_node *mem_find (void *);
419 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
420 static void check_gcpros (void);
421 #endif
423 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
425 #ifndef DEADP
426 # define DEADP(x) 0
427 #endif
429 /* Recording what needs to be marked for gc. */
431 struct gcpro *gcprolist;
433 /* Addresses of staticpro'd variables. Initialize it to a nonzero
434 value; otherwise some compilers put it into BSS. */
436 #define NSTATICS 0x650
437 static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
439 /* Index of next unused slot in staticvec. */
441 static int staticidx;
443 static void *pure_alloc (size_t, int);
446 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
447 ALIGNMENT must be a power of 2. */
449 #define ALIGN(ptr, ALIGNMENT) \
450 ((void *) (((uintptr_t) (ptr) + (ALIGNMENT) - 1) \
451 & ~ ((ALIGNMENT) - 1)))
455 /************************************************************************
456 Malloc
457 ************************************************************************/
459 /* Function malloc calls this if it finds we are near exhausting storage. */
461 void
462 malloc_warning (const char *str)
464 pending_malloc_warning = str;
468 /* Display an already-pending malloc warning. */
470 void
471 display_malloc_warning (void)
473 call3 (intern ("display-warning"),
474 intern ("alloc"),
475 build_string (pending_malloc_warning),
476 intern ("emergency"));
477 pending_malloc_warning = 0;
480 /* Called if we can't allocate relocatable space for a buffer. */
482 void
483 buffer_memory_full (ptrdiff_t nbytes)
485 /* If buffers use the relocating allocator, no need to free
486 spare_memory, because we may have plenty of malloc space left
487 that we could get, and if we don't, the malloc that fails will
488 itself cause spare_memory to be freed. If buffers don't use the
489 relocating allocator, treat this like any other failing
490 malloc. */
492 #ifndef REL_ALLOC
493 memory_full (nbytes);
494 #endif
496 /* This used to call error, but if we've run out of memory, we could
497 get infinite recursion trying to build the string. */
498 xsignal (Qnil, Vmemory_signal_data);
501 /* A common multiple of the positive integers A and B. Ideally this
502 would be the least common multiple, but there's no way to do that
503 as a constant expression in C, so do the best that we can easily do. */
504 #define COMMON_MULTIPLE(a, b) \
505 ((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
507 #ifndef XMALLOC_OVERRUN_CHECK
508 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
509 #else
511 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
512 around each block.
514 The header consists of XMALLOC_OVERRUN_CHECK_SIZE fixed bytes
515 followed by XMALLOC_OVERRUN_SIZE_SIZE bytes containing the original
516 block size in little-endian order. The trailer consists of
517 XMALLOC_OVERRUN_CHECK_SIZE fixed bytes.
519 The header is used to detect whether this block has been allocated
520 through these functions, as some low-level libc functions may
521 bypass the malloc hooks. */
523 #define XMALLOC_OVERRUN_CHECK_SIZE 16
524 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
525 (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)
527 /* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
528 hold a size_t value and (2) the header size is a multiple of the
529 alignment that Emacs needs for C types and for USE_LSB_TAG. */
530 #define XMALLOC_BASE_ALIGNMENT \
531 alignof (union { long double d; intmax_t i; void *p; })
533 #if USE_LSB_TAG
534 # define XMALLOC_HEADER_ALIGNMENT \
535 COMMON_MULTIPLE (1 << GCTYPEBITS, XMALLOC_BASE_ALIGNMENT)
536 #else
537 # define XMALLOC_HEADER_ALIGNMENT XMALLOC_BASE_ALIGNMENT
538 #endif
539 #define XMALLOC_OVERRUN_SIZE_SIZE \
540 (((XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t) \
541 + XMALLOC_HEADER_ALIGNMENT - 1) \
542 / XMALLOC_HEADER_ALIGNMENT * XMALLOC_HEADER_ALIGNMENT) \
543 - XMALLOC_OVERRUN_CHECK_SIZE)
545 static char const xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE] =
546 { '\x9a', '\x9b', '\xae', '\xaf',
547 '\xbf', '\xbe', '\xce', '\xcf',
548 '\xea', '\xeb', '\xec', '\xed',
549 '\xdf', '\xde', '\x9c', '\x9d' };
551 static char const xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
552 { '\xaa', '\xab', '\xac', '\xad',
553 '\xba', '\xbb', '\xbc', '\xbd',
554 '\xca', '\xcb', '\xcc', '\xcd',
555 '\xda', '\xdb', '\xdc', '\xdd' };
557 /* Insert and extract the block size in the header. */
559 static void
560 xmalloc_put_size (unsigned char *ptr, size_t size)
562 int i;
563 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
565 *--ptr = size & ((1 << CHAR_BIT) - 1);
566 size >>= CHAR_BIT;
570 static size_t
571 xmalloc_get_size (unsigned char *ptr)
573 size_t size = 0;
574 int i;
575 ptr -= XMALLOC_OVERRUN_SIZE_SIZE;
576 for (i = 0; i < XMALLOC_OVERRUN_SIZE_SIZE; i++)
578 size <<= CHAR_BIT;
579 size += *ptr++;
581 return size;
585 /* The call depth in overrun_check functions. For example, this might happen:
586 xmalloc()
587 overrun_check_malloc()
588 -> malloc -> (via hook)_-> emacs_blocked_malloc
589 -> overrun_check_malloc
590 call malloc (hooks are NULL, so real malloc is called).
591 malloc returns 10000.
592 add overhead, return 10016.
593 <- (back in overrun_check_malloc)
594 add overhead again, return 10032
595 xmalloc returns 10032.
597 (time passes).
599 xfree(10032)
600 overrun_check_free(10032)
601 decrease overhead
602 free(10016) <- crash, because 10000 is the original pointer. */
604 static ptrdiff_t check_depth;
606 /* Like malloc, but wraps allocated block with header and trailer. */
608 static void *
609 overrun_check_malloc (size_t size)
611 register unsigned char *val;
612 int overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_OVERHEAD : 0;
613 if (SIZE_MAX - overhead < size)
614 abort ();
616 val = malloc (size + overhead);
617 if (val && check_depth == 1)
619 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
620 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
621 xmalloc_put_size (val, size);
622 memcpy (val + size, xmalloc_overrun_check_trailer,
623 XMALLOC_OVERRUN_CHECK_SIZE);
625 --check_depth;
626 return val;
630 /* Like realloc, but checks old block for overrun, and wraps new block
631 with header and trailer. */
633 static void *
634 overrun_check_realloc (void *block, size_t size)
636 register unsigned char *val = (unsigned char *) block;
637 int overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_OVERHEAD : 0;
638 if (SIZE_MAX - overhead < size)
639 abort ();
641 if (val
642 && check_depth == 1
643 && memcmp (xmalloc_overrun_check_header,
644 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
645 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
647 size_t osize = xmalloc_get_size (val);
648 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
649 XMALLOC_OVERRUN_CHECK_SIZE))
650 abort ();
651 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
652 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
653 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
656 val = realloc (val, size + overhead);
658 if (val && check_depth == 1)
660 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
661 val += XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
662 xmalloc_put_size (val, size);
663 memcpy (val + size, xmalloc_overrun_check_trailer,
664 XMALLOC_OVERRUN_CHECK_SIZE);
666 --check_depth;
667 return val;
670 /* Like free, but checks block for overrun. */
672 static void
673 overrun_check_free (void *block)
675 unsigned char *val = (unsigned char *) block;
677 ++check_depth;
678 if (val
679 && check_depth == 1
680 && memcmp (xmalloc_overrun_check_header,
681 val - XMALLOC_OVERRUN_CHECK_SIZE - XMALLOC_OVERRUN_SIZE_SIZE,
682 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
684 size_t osize = xmalloc_get_size (val);
685 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
686 XMALLOC_OVERRUN_CHECK_SIZE))
687 abort ();
688 #ifdef XMALLOC_CLEAR_FREE_MEMORY
689 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
690 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_OVERHEAD);
691 #else
692 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
693 val -= XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE;
694 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE);
695 #endif
698 free (val);
699 --check_depth;
702 #undef malloc
703 #undef realloc
704 #undef free
705 #define malloc overrun_check_malloc
706 #define realloc overrun_check_realloc
707 #define free overrun_check_free
708 #endif
710 #ifdef SYNC_INPUT
711 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
712 there's no need to block input around malloc. */
713 #define MALLOC_BLOCK_INPUT ((void)0)
714 #define MALLOC_UNBLOCK_INPUT ((void)0)
715 #else
716 #define MALLOC_BLOCK_INPUT BLOCK_INPUT
717 #define MALLOC_UNBLOCK_INPUT UNBLOCK_INPUT
718 #endif
720 /* Like malloc but check for no memory and block interrupt input.. */
722 void *
723 xmalloc (size_t size)
725 void *val;
727 MALLOC_BLOCK_INPUT;
728 val = malloc (size);
729 MALLOC_UNBLOCK_INPUT;
731 if (!val && size)
732 memory_full (size);
733 return val;
736 /* Like the above, but zeroes out the memory just allocated. */
738 void *
739 xzalloc (size_t size)
741 void *val;
743 MALLOC_BLOCK_INPUT;
744 val = malloc (size);
745 MALLOC_UNBLOCK_INPUT;
747 if (!val && size)
748 memory_full (size);
749 memset (val, 0, size);
750 return val;
753 /* Like realloc but check for no memory and block interrupt input.. */
755 void *
756 xrealloc (void *block, size_t size)
758 void *val;
760 MALLOC_BLOCK_INPUT;
761 /* We must call malloc explicitly when BLOCK is 0, since some
762 reallocs don't do this. */
763 if (! block)
764 val = malloc (size);
765 else
766 val = realloc (block, size);
767 MALLOC_UNBLOCK_INPUT;
769 if (!val && size)
770 memory_full (size);
771 return val;
775 /* Like free but block interrupt input. */
777 void
778 xfree (void *block)
780 if (!block)
781 return;
782 MALLOC_BLOCK_INPUT;
783 free (block);
784 MALLOC_UNBLOCK_INPUT;
785 /* We don't call refill_memory_reserve here
786 because that duplicates doing so in emacs_blocked_free
787 and the criterion should go there. */
791 /* Other parts of Emacs pass large int values to allocator functions
792 expecting ptrdiff_t. This is portable in practice, but check it to
793 be safe. */
794 verify (INT_MAX <= PTRDIFF_MAX);
797 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
798 Signal an error on memory exhaustion, and block interrupt input. */
800 void *
801 xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
803 eassert (0 <= nitems && 0 < item_size);
804 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
805 memory_full (SIZE_MAX);
806 return xmalloc (nitems * item_size);
810 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
811 Signal an error on memory exhaustion, and block interrupt input. */
813 void *
814 xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
816 eassert (0 <= nitems && 0 < item_size);
817 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
818 memory_full (SIZE_MAX);
819 return xrealloc (pa, nitems * item_size);
823 /* Grow PA, which points to an array of *NITEMS items, and return the
824 location of the reallocated array, updating *NITEMS to reflect its
825 new size. The new array will contain at least NITEMS_INCR_MIN more
826 items, but will not contain more than NITEMS_MAX items total.
827 ITEM_SIZE is the size of each item, in bytes.
829 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
830 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
831 infinity.
833 If PA is null, then allocate a new array instead of reallocating
834 the old one. Thus, to grow an array A without saving its old
835 contents, invoke xfree (A) immediately followed by xgrowalloc (0,
836 &NITEMS, ...).
838 Block interrupt input as needed. If memory exhaustion occurs, set
839 *NITEMS to zero if PA is null, and signal an error (i.e., do not
840 return). */
842 void *
843 xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
844 ptrdiff_t nitems_max, ptrdiff_t item_size)
846 /* The approximate size to use for initial small allocation
847 requests. This is the largest "small" request for the GNU C
848 library malloc. */
849 enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
851 /* If the array is tiny, grow it to about (but no greater than)
852 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%. */
853 ptrdiff_t n = *nitems;
854 ptrdiff_t tiny_max = DEFAULT_MXFAST / item_size - n;
855 ptrdiff_t half_again = n >> 1;
856 ptrdiff_t incr_estimate = max (tiny_max, half_again);
858 /* Adjust the increment according to three constraints: NITEMS_INCR_MIN,
859 NITEMS_MAX, and what the C language can represent safely. */
860 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / item_size;
861 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
862 ? nitems_max : C_language_max);
863 ptrdiff_t nitems_incr_max = n_max - n;
864 ptrdiff_t incr = max (nitems_incr_min, min (incr_estimate, nitems_incr_max));
866 eassert (0 < item_size && 0 < nitems_incr_min && 0 <= n && -1 <= nitems_max);
867 if (! pa)
868 *nitems = 0;
869 if (nitems_incr_max < incr)
870 memory_full (SIZE_MAX);
871 n += incr;
872 pa = xrealloc (pa, n * item_size);
873 *nitems = n;
874 return pa;
878 /* Like strdup, but uses xmalloc. */
880 char *
881 xstrdup (const char *s)
883 size_t len = strlen (s) + 1;
884 char *p = xmalloc (len);
885 memcpy (p, s, len);
886 return p;
890 /* Unwind for SAFE_ALLOCA */
892 Lisp_Object
893 safe_alloca_unwind (Lisp_Object arg)
895 register struct Lisp_Save_Value *p = XSAVE_VALUE (arg);
897 p->dogc = 0;
898 xfree (p->pointer);
899 p->pointer = 0;
900 free_misc (arg);
901 return Qnil;
905 /* Like malloc but used for allocating Lisp data. NBYTES is the
906 number of bytes to allocate, TYPE describes the intended use of the
907 allocated memory block (for strings, for conses, ...). */
909 #if ! USE_LSB_TAG
910 void *lisp_malloc_loser EXTERNALLY_VISIBLE;
911 #endif
913 static void *
914 lisp_malloc (size_t nbytes, enum mem_type type)
916 register void *val;
918 MALLOC_BLOCK_INPUT;
920 #ifdef GC_MALLOC_CHECK
921 allocated_mem_type = type;
922 #endif
924 val = malloc (nbytes);
926 #if ! USE_LSB_TAG
927 /* If the memory just allocated cannot be addressed thru a Lisp
928 object's pointer, and it needs to be,
929 that's equivalent to running out of memory. */
930 if (val && type != MEM_TYPE_NON_LISP)
932 Lisp_Object tem;
933 XSETCONS (tem, (char *) val + nbytes - 1);
934 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
936 lisp_malloc_loser = val;
937 free (val);
938 val = 0;
941 #endif
943 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
944 if (val && type != MEM_TYPE_NON_LISP)
945 mem_insert (val, (char *) val + nbytes, type);
946 #endif
948 MALLOC_UNBLOCK_INPUT;
949 if (!val && nbytes)
950 memory_full (nbytes);
951 return val;
954 /* Free BLOCK. This must be called to free memory allocated with a
955 call to lisp_malloc. */
957 static void
958 lisp_free (void *block)
960 MALLOC_BLOCK_INPUT;
961 free (block);
962 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
963 mem_delete (mem_find (block));
964 #endif
965 MALLOC_UNBLOCK_INPUT;
968 /***** Allocation of aligned blocks of memory to store Lisp data. *****/
970 /* The entry point is lisp_align_malloc which returns blocks of at most
971 BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
973 #if defined (HAVE_POSIX_MEMALIGN) && defined (SYSTEM_MALLOC)
974 #define USE_POSIX_MEMALIGN 1
975 #endif
977 /* BLOCK_ALIGN has to be a power of 2. */
978 #define BLOCK_ALIGN (1 << 10)
980 /* Padding to leave at the end of a malloc'd block. This is to give
981 malloc a chance to minimize the amount of memory wasted to alignment.
982 It should be tuned to the particular malloc library used.
983 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
984 posix_memalign on the other hand would ideally prefer a value of 4
985 because otherwise, there's 1020 bytes wasted between each ablocks.
986 In Emacs, testing shows that those 1020 can most of the time be
987 efficiently used by malloc to place other objects, so a value of 0 can
988 still preferable unless you have a lot of aligned blocks and virtually
989 nothing else. */
990 #define BLOCK_PADDING 0
991 #define BLOCK_BYTES \
992 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
994 /* Internal data structures and constants. */
996 #define ABLOCKS_SIZE 16
998 /* An aligned block of memory. */
999 struct ablock
1001 union
1003 char payload[BLOCK_BYTES];
1004 struct ablock *next_free;
1005 } x;
1006 /* `abase' is the aligned base of the ablocks. */
1007 /* It is overloaded to hold the virtual `busy' field that counts
1008 the number of used ablock in the parent ablocks.
1009 The first ablock has the `busy' field, the others have the `abase'
1010 field. To tell the difference, we assume that pointers will have
1011 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
1012 is used to tell whether the real base of the parent ablocks is `abase'
1013 (if not, the word before the first ablock holds a pointer to the
1014 real base). */
1015 struct ablocks *abase;
1016 /* The padding of all but the last ablock is unused. The padding of
1017 the last ablock in an ablocks is not allocated. */
1018 #if BLOCK_PADDING
1019 char padding[BLOCK_PADDING];
1020 #endif
1023 /* A bunch of consecutive aligned blocks. */
1024 struct ablocks
1026 struct ablock blocks[ABLOCKS_SIZE];
1029 /* Size of the block requested from malloc or posix_memalign. */
1030 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
1032 #define ABLOCK_ABASE(block) \
1033 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
1034 ? (struct ablocks *)(block) \
1035 : (block)->abase)
1037 /* Virtual `busy' field. */
1038 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
1040 /* Pointer to the (not necessarily aligned) malloc block. */
1041 #ifdef USE_POSIX_MEMALIGN
1042 #define ABLOCKS_BASE(abase) (abase)
1043 #else
1044 #define ABLOCKS_BASE(abase) \
1045 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void**)abase)[-1])
1046 #endif
1048 /* The list of free ablock. */
1049 static struct ablock *free_ablock;
1051 /* Allocate an aligned block of nbytes.
1052 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
1053 smaller or equal to BLOCK_BYTES. */
1054 static void *
1055 lisp_align_malloc (size_t nbytes, enum mem_type type)
1057 void *base, *val;
1058 struct ablocks *abase;
1060 eassert (nbytes <= BLOCK_BYTES);
1062 MALLOC_BLOCK_INPUT;
1064 #ifdef GC_MALLOC_CHECK
1065 allocated_mem_type = type;
1066 #endif
1068 if (!free_ablock)
1070 int i;
1071 intptr_t aligned; /* int gets warning casting to 64-bit pointer. */
1073 #ifdef DOUG_LEA_MALLOC
1074 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1075 because mapped region contents are not preserved in
1076 a dumped Emacs. */
1077 mallopt (M_MMAP_MAX, 0);
1078 #endif
1080 #ifdef USE_POSIX_MEMALIGN
1082 int err = posix_memalign (&base, BLOCK_ALIGN, ABLOCKS_BYTES);
1083 if (err)
1084 base = NULL;
1085 abase = base;
1087 #else
1088 base = malloc (ABLOCKS_BYTES);
1089 abase = ALIGN (base, BLOCK_ALIGN);
1090 #endif
1092 if (base == 0)
1094 MALLOC_UNBLOCK_INPUT;
1095 memory_full (ABLOCKS_BYTES);
1098 aligned = (base == abase);
1099 if (!aligned)
1100 ((void**)abase)[-1] = base;
1102 #ifdef DOUG_LEA_MALLOC
1103 /* Back to a reasonable maximum of mmap'ed areas. */
1104 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1105 #endif
1107 #if ! USE_LSB_TAG
1108 /* If the memory just allocated cannot be addressed thru a Lisp
1109 object's pointer, and it needs to be, that's equivalent to
1110 running out of memory. */
1111 if (type != MEM_TYPE_NON_LISP)
1113 Lisp_Object tem;
1114 char *end = (char *) base + ABLOCKS_BYTES - 1;
1115 XSETCONS (tem, end);
1116 if ((char *) XCONS (tem) != end)
1118 lisp_malloc_loser = base;
1119 free (base);
1120 MALLOC_UNBLOCK_INPUT;
1121 memory_full (SIZE_MAX);
1124 #endif
1126 /* Initialize the blocks and put them on the free list.
1127 If `base' was not properly aligned, we can't use the last block. */
1128 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1130 abase->blocks[i].abase = abase;
1131 abase->blocks[i].x.next_free = free_ablock;
1132 free_ablock = &abase->blocks[i];
1134 ABLOCKS_BUSY (abase) = (struct ablocks *) aligned;
1136 eassert (0 == ((uintptr_t) abase) % BLOCK_ALIGN);
1137 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1138 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1139 eassert (ABLOCKS_BASE (abase) == base);
1140 eassert (aligned == (intptr_t) ABLOCKS_BUSY (abase));
1143 abase = ABLOCK_ABASE (free_ablock);
1144 ABLOCKS_BUSY (abase) =
1145 (struct ablocks *) (2 + (intptr_t) ABLOCKS_BUSY (abase));
1146 val = free_ablock;
1147 free_ablock = free_ablock->x.next_free;
1149 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1150 if (type != MEM_TYPE_NON_LISP)
1151 mem_insert (val, (char *) val + nbytes, type);
1152 #endif
1154 MALLOC_UNBLOCK_INPUT;
1156 eassert (0 == ((uintptr_t) val) % BLOCK_ALIGN);
1157 return val;
1160 static void
1161 lisp_align_free (void *block)
1163 struct ablock *ablock = block;
1164 struct ablocks *abase = ABLOCK_ABASE (ablock);
1166 MALLOC_BLOCK_INPUT;
1167 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1168 mem_delete (mem_find (block));
1169 #endif
1170 /* Put on free list. */
1171 ablock->x.next_free = free_ablock;
1172 free_ablock = ablock;
1173 /* Update busy count. */
1174 ABLOCKS_BUSY (abase)
1175 = (struct ablocks *) (-2 + (intptr_t) ABLOCKS_BUSY (abase));
1177 if (2 > (intptr_t) ABLOCKS_BUSY (abase))
1178 { /* All the blocks are free. */
1179 int i = 0, aligned = (intptr_t) ABLOCKS_BUSY (abase);
1180 struct ablock **tem = &free_ablock;
1181 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1183 while (*tem)
1185 if (*tem >= (struct ablock *) abase && *tem < atop)
1187 i++;
1188 *tem = (*tem)->x.next_free;
1190 else
1191 tem = &(*tem)->x.next_free;
1193 eassert ((aligned & 1) == aligned);
1194 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1195 #ifdef USE_POSIX_MEMALIGN
1196 eassert ((uintptr_t) ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1197 #endif
1198 free (ABLOCKS_BASE (abase));
1200 MALLOC_UNBLOCK_INPUT;
1204 #ifndef SYSTEM_MALLOC
1206 /* Arranging to disable input signals while we're in malloc.
1208 This only works with GNU malloc. To help out systems which can't
1209 use GNU malloc, all the calls to malloc, realloc, and free
1210 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
1211 pair; unfortunately, we have no idea what C library functions
1212 might call malloc, so we can't really protect them unless you're
1213 using GNU malloc. Fortunately, most of the major operating systems
1214 can use GNU malloc. */
1216 #ifndef SYNC_INPUT
1217 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
1218 there's no need to block input around malloc. */
1220 #ifndef DOUG_LEA_MALLOC
1221 extern void * (*__malloc_hook) (size_t, const void *);
1222 extern void * (*__realloc_hook) (void *, size_t, const void *);
1223 extern void (*__free_hook) (void *, const void *);
1224 /* Else declared in malloc.h, perhaps with an extra arg. */
1225 #endif /* DOUG_LEA_MALLOC */
1226 static void * (*old_malloc_hook) (size_t, const void *);
1227 static void * (*old_realloc_hook) (void *, size_t, const void*);
1228 static void (*old_free_hook) (void*, const void*);
1230 #ifdef DOUG_LEA_MALLOC
1231 # define BYTES_USED (mallinfo ().uordblks)
1232 #else
1233 # define BYTES_USED _bytes_used
1234 #endif
1236 #ifdef GC_MALLOC_CHECK
1237 static int dont_register_blocks;
1238 #endif
1240 static size_t bytes_used_when_reconsidered;
1242 /* Value of _bytes_used, when spare_memory was freed. */
1244 static size_t bytes_used_when_full;
1246 /* This function is used as the hook for free to call. */
1248 static void
1249 emacs_blocked_free (void *ptr, const void *ptr2)
1251 BLOCK_INPUT_ALLOC;
1253 #ifdef GC_MALLOC_CHECK
1254 if (ptr)
1256 struct mem_node *m;
1258 m = mem_find (ptr);
1259 if (m == MEM_NIL || m->start != ptr)
1261 fprintf (stderr,
1262 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
1263 abort ();
1265 else
1267 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
1268 mem_delete (m);
1271 #endif /* GC_MALLOC_CHECK */
1273 __free_hook = old_free_hook;
1274 free (ptr);
1276 /* If we released our reserve (due to running out of memory),
1277 and we have a fair amount free once again,
1278 try to set aside another reserve in case we run out once more. */
1279 if (! NILP (Vmemory_full)
1280 /* Verify there is enough space that even with the malloc
1281 hysteresis this call won't run out again.
1282 The code here is correct as long as SPARE_MEMORY
1283 is substantially larger than the block size malloc uses. */
1284 && (bytes_used_when_full
1285 > ((bytes_used_when_reconsidered = BYTES_USED)
1286 + max (malloc_hysteresis, 4) * SPARE_MEMORY)))
1287 refill_memory_reserve ();
1289 __free_hook = emacs_blocked_free;
1290 UNBLOCK_INPUT_ALLOC;
1294 /* This function is the malloc hook that Emacs uses. */
1296 static void *
1297 emacs_blocked_malloc (size_t size, const void *ptr)
1299 void *value;
1301 BLOCK_INPUT_ALLOC;
1302 __malloc_hook = old_malloc_hook;
1303 #ifdef DOUG_LEA_MALLOC
1304 /* Segfaults on my system. --lorentey */
1305 /* mallopt (M_TOP_PAD, malloc_hysteresis * 4096); */
1306 #else
1307 __malloc_extra_blocks = malloc_hysteresis;
1308 #endif
1310 value = malloc (size);
1312 #ifdef GC_MALLOC_CHECK
1314 struct mem_node *m = mem_find (value);
1315 if (m != MEM_NIL)
1317 fprintf (stderr, "Malloc returned %p which is already in use\n",
1318 value);
1319 fprintf (stderr, "Region in use is %p...%p, %td bytes, type %d\n",
1320 m->start, m->end, (char *) m->end - (char *) m->start,
1321 m->type);
1322 abort ();
1325 if (!dont_register_blocks)
1327 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
1328 allocated_mem_type = MEM_TYPE_NON_LISP;
1331 #endif /* GC_MALLOC_CHECK */
1333 __malloc_hook = emacs_blocked_malloc;
1334 UNBLOCK_INPUT_ALLOC;
1336 /* fprintf (stderr, "%p malloc\n", value); */
1337 return value;
1341 /* This function is the realloc hook that Emacs uses. */
1343 static void *
1344 emacs_blocked_realloc (void *ptr, size_t size, const void *ptr2)
1346 void *value;
1348 BLOCK_INPUT_ALLOC;
1349 __realloc_hook = old_realloc_hook;
1351 #ifdef GC_MALLOC_CHECK
1352 if (ptr)
1354 struct mem_node *m = mem_find (ptr);
1355 if (m == MEM_NIL || m->start != ptr)
1357 fprintf (stderr,
1358 "Realloc of %p which wasn't allocated with malloc\n",
1359 ptr);
1360 abort ();
1363 mem_delete (m);
1366 /* fprintf (stderr, "%p -> realloc\n", ptr); */
1368 /* Prevent malloc from registering blocks. */
1369 dont_register_blocks = 1;
1370 #endif /* GC_MALLOC_CHECK */
1372 value = realloc (ptr, size);
1374 #ifdef GC_MALLOC_CHECK
1375 dont_register_blocks = 0;
1378 struct mem_node *m = mem_find (value);
1379 if (m != MEM_NIL)
1381 fprintf (stderr, "Realloc returns memory that is already in use\n");
1382 abort ();
1385 /* Can't handle zero size regions in the red-black tree. */
1386 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
1389 /* fprintf (stderr, "%p <- realloc\n", value); */
1390 #endif /* GC_MALLOC_CHECK */
1392 __realloc_hook = emacs_blocked_realloc;
1393 UNBLOCK_INPUT_ALLOC;
1395 return value;
1399 #ifdef HAVE_PTHREAD
1400 /* Called from Fdump_emacs so that when the dumped Emacs starts, it has a
1401 normal malloc. Some thread implementations need this as they call
1402 malloc before main. The pthread_self call in BLOCK_INPUT_ALLOC then
1403 calls malloc because it is the first call, and we have an endless loop. */
1405 void
1406 reset_malloc_hooks (void)
1408 __free_hook = old_free_hook;
1409 __malloc_hook = old_malloc_hook;
1410 __realloc_hook = old_realloc_hook;
1412 #endif /* HAVE_PTHREAD */
1415 /* Called from main to set up malloc to use our hooks. */
1417 void
1418 uninterrupt_malloc (void)
1420 #ifdef HAVE_PTHREAD
1421 #ifdef DOUG_LEA_MALLOC
1422 pthread_mutexattr_t attr;
1424 /* GLIBC has a faster way to do this, but let's keep it portable.
1425 This is according to the Single UNIX Specification. */
1426 pthread_mutexattr_init (&attr);
1427 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1428 pthread_mutex_init (&alloc_mutex, &attr);
1429 #else /* !DOUG_LEA_MALLOC */
1430 /* Some systems such as Solaris 2.6 don't have a recursive mutex,
1431 and the bundled gmalloc.c doesn't require it. */
1432 pthread_mutex_init (&alloc_mutex, NULL);
1433 #endif /* !DOUG_LEA_MALLOC */
1434 #endif /* HAVE_PTHREAD */
1436 if (__free_hook != emacs_blocked_free)
1437 old_free_hook = __free_hook;
1438 __free_hook = emacs_blocked_free;
1440 if (__malloc_hook != emacs_blocked_malloc)
1441 old_malloc_hook = __malloc_hook;
1442 __malloc_hook = emacs_blocked_malloc;
1444 if (__realloc_hook != emacs_blocked_realloc)
1445 old_realloc_hook = __realloc_hook;
1446 __realloc_hook = emacs_blocked_realloc;
1449 #endif /* not SYNC_INPUT */
1450 #endif /* not SYSTEM_MALLOC */
1454 /***********************************************************************
1455 Interval Allocation
1456 ***********************************************************************/
1458 /* Number of intervals allocated in an interval_block structure.
1459 The 1020 is 1024 minus malloc overhead. */
1461 #define INTERVAL_BLOCK_SIZE \
1462 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1464 /* Intervals are allocated in chunks in form of an interval_block
1465 structure. */
1467 struct interval_block
1469 /* Place `intervals' first, to preserve alignment. */
1470 struct interval intervals[INTERVAL_BLOCK_SIZE];
1471 struct interval_block *next;
1474 /* Current interval block. Its `next' pointer points to older
1475 blocks. */
1477 static struct interval_block *interval_block;
1479 /* Index in interval_block above of the next unused interval
1480 structure. */
1482 static int interval_block_index = INTERVAL_BLOCK_SIZE;
1484 /* Number of free and live intervals. */
1486 static EMACS_INT total_free_intervals, total_intervals;
1488 /* List of free intervals. */
1490 static INTERVAL interval_free_list;
1492 /* Return a new interval. */
1494 INTERVAL
1495 make_interval (void)
1497 INTERVAL val;
1499 /* eassert (!handling_signal); */
1501 MALLOC_BLOCK_INPUT;
1503 if (interval_free_list)
1505 val = interval_free_list;
1506 interval_free_list = INTERVAL_PARENT (interval_free_list);
1508 else
1510 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1512 struct interval_block *newi
1513 = lisp_malloc (sizeof *newi, MEM_TYPE_NON_LISP);
1515 newi->next = interval_block;
1516 interval_block = newi;
1517 interval_block_index = 0;
1518 total_free_intervals += INTERVAL_BLOCK_SIZE;
1520 val = &interval_block->intervals[interval_block_index++];
1523 MALLOC_UNBLOCK_INPUT;
1525 consing_since_gc += sizeof (struct interval);
1526 intervals_consed++;
1527 total_free_intervals--;
1528 RESET_INTERVAL (val);
1529 val->gcmarkbit = 0;
1530 return val;
1534 /* Mark Lisp objects in interval I. */
1536 static void
1537 mark_interval (register INTERVAL i, Lisp_Object dummy)
1539 /* Intervals should never be shared. So, if extra internal checking is
1540 enabled, GC aborts if it seems to have visited an interval twice. */
1541 eassert (!i->gcmarkbit);
1542 i->gcmarkbit = 1;
1543 mark_object (i->plist);
1547 /* Mark the interval tree rooted in TREE. Don't call this directly;
1548 use the macro MARK_INTERVAL_TREE instead. */
1550 static void
1551 mark_interval_tree (register INTERVAL tree)
1553 /* No need to test if this tree has been marked already; this
1554 function is always called through the MARK_INTERVAL_TREE macro,
1555 which takes care of that. */
1557 traverse_intervals_noorder (tree, mark_interval, Qnil);
1561 /* Mark the interval tree rooted in I. */
1563 #define MARK_INTERVAL_TREE(i) \
1564 do { \
1565 if (!NULL_INTERVAL_P (i) && !i->gcmarkbit) \
1566 mark_interval_tree (i); \
1567 } while (0)
1570 #define UNMARK_BALANCE_INTERVALS(i) \
1571 do { \
1572 if (! NULL_INTERVAL_P (i)) \
1573 (i) = balance_intervals (i); \
1574 } while (0)
1576 /***********************************************************************
1577 String Allocation
1578 ***********************************************************************/
1580 /* Lisp_Strings are allocated in string_block structures. When a new
1581 string_block is allocated, all the Lisp_Strings it contains are
1582 added to a free-list string_free_list. When a new Lisp_String is
1583 needed, it is taken from that list. During the sweep phase of GC,
1584 string_blocks that are entirely free are freed, except two which
1585 we keep.
1587 String data is allocated from sblock structures. Strings larger
1588 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1589 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1591 Sblocks consist internally of sdata structures, one for each
1592 Lisp_String. The sdata structure points to the Lisp_String it
1593 belongs to. The Lisp_String points back to the `u.data' member of
1594 its sdata structure.
1596 When a Lisp_String is freed during GC, it is put back on
1597 string_free_list, and its `data' member and its sdata's `string'
1598 pointer is set to null. The size of the string is recorded in the
1599 `u.nbytes' member of the sdata. So, sdata structures that are no
1600 longer used, can be easily recognized, and it's easy to compact the
1601 sblocks of small strings which we do in compact_small_strings. */
1603 /* Size in bytes of an sblock structure used for small strings. This
1604 is 8192 minus malloc overhead. */
1606 #define SBLOCK_SIZE 8188
1608 /* Strings larger than this are considered large strings. String data
1609 for large strings is allocated from individual sblocks. */
1611 #define LARGE_STRING_BYTES 1024
1613 /* Structure describing string memory sub-allocated from an sblock.
1614 This is where the contents of Lisp strings are stored. */
1616 struct sdata
1618 /* Back-pointer to the string this sdata belongs to. If null, this
1619 structure is free, and the NBYTES member of the union below
1620 contains the string's byte size (the same value that STRING_BYTES
1621 would return if STRING were non-null). If non-null, STRING_BYTES
1622 (STRING) is the size of the data, and DATA contains the string's
1623 contents. */
1624 struct Lisp_String *string;
1626 #ifdef GC_CHECK_STRING_BYTES
1628 ptrdiff_t nbytes;
1629 unsigned char data[1];
1631 #define SDATA_NBYTES(S) (S)->nbytes
1632 #define SDATA_DATA(S) (S)->data
1633 #define SDATA_SELECTOR(member) member
1635 #else /* not GC_CHECK_STRING_BYTES */
1637 union
1639 /* When STRING is non-null. */
1640 unsigned char data[1];
1642 /* When STRING is null. */
1643 ptrdiff_t nbytes;
1644 } u;
1646 #define SDATA_NBYTES(S) (S)->u.nbytes
1647 #define SDATA_DATA(S) (S)->u.data
1648 #define SDATA_SELECTOR(member) u.member
1650 #endif /* not GC_CHECK_STRING_BYTES */
1652 #define SDATA_DATA_OFFSET offsetof (struct sdata, SDATA_SELECTOR (data))
1656 /* Structure describing a block of memory which is sub-allocated to
1657 obtain string data memory for strings. Blocks for small strings
1658 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1659 as large as needed. */
1661 struct sblock
1663 /* Next in list. */
1664 struct sblock *next;
1666 /* Pointer to the next free sdata block. This points past the end
1667 of the sblock if there isn't any space left in this block. */
1668 struct sdata *next_free;
1670 /* Start of data. */
1671 struct sdata first_data;
1674 /* Number of Lisp strings in a string_block structure. The 1020 is
1675 1024 minus malloc overhead. */
1677 #define STRING_BLOCK_SIZE \
1678 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1680 /* Structure describing a block from which Lisp_String structures
1681 are allocated. */
1683 struct string_block
1685 /* Place `strings' first, to preserve alignment. */
1686 struct Lisp_String strings[STRING_BLOCK_SIZE];
1687 struct string_block *next;
1690 /* Head and tail of the list of sblock structures holding Lisp string
1691 data. We always allocate from current_sblock. The NEXT pointers
1692 in the sblock structures go from oldest_sblock to current_sblock. */
1694 static struct sblock *oldest_sblock, *current_sblock;
1696 /* List of sblocks for large strings. */
1698 static struct sblock *large_sblocks;
1700 /* List of string_block structures. */
1702 static struct string_block *string_blocks;
1704 /* Free-list of Lisp_Strings. */
1706 static struct Lisp_String *string_free_list;
1708 /* Number of live and free Lisp_Strings. */
1710 static EMACS_INT total_strings, total_free_strings;
1712 /* Number of bytes used by live strings. */
1714 static EMACS_INT total_string_bytes;
1716 /* Given a pointer to a Lisp_String S which is on the free-list
1717 string_free_list, return a pointer to its successor in the
1718 free-list. */
1720 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1722 /* Return a pointer to the sdata structure belonging to Lisp string S.
1723 S must be live, i.e. S->data must not be null. S->data is actually
1724 a pointer to the `u.data' member of its sdata structure; the
1725 structure starts at a constant offset in front of that. */
1727 #define SDATA_OF_STRING(S) ((struct sdata *) ((S)->data - SDATA_DATA_OFFSET))
1730 #ifdef GC_CHECK_STRING_OVERRUN
1732 /* We check for overrun in string data blocks by appending a small
1733 "cookie" after each allocated string data block, and check for the
1734 presence of this cookie during GC. */
1736 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1737 static char const string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1738 { '\xde', '\xad', '\xbe', '\xef' };
1740 #else
1741 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1742 #endif
1744 /* Value is the size of an sdata structure large enough to hold NBYTES
1745 bytes of string data. The value returned includes a terminating
1746 NUL byte, the size of the sdata structure, and padding. */
1748 #ifdef GC_CHECK_STRING_BYTES
1750 #define SDATA_SIZE(NBYTES) \
1751 ((SDATA_DATA_OFFSET \
1752 + (NBYTES) + 1 \
1753 + sizeof (ptrdiff_t) - 1) \
1754 & ~(sizeof (ptrdiff_t) - 1))
1756 #else /* not GC_CHECK_STRING_BYTES */
1758 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1759 less than the size of that member. The 'max' is not needed when
1760 SDATA_DATA_OFFSET is a multiple of sizeof (ptrdiff_t), because then the
1761 alignment code reserves enough space. */
1763 #define SDATA_SIZE(NBYTES) \
1764 ((SDATA_DATA_OFFSET \
1765 + (SDATA_DATA_OFFSET % sizeof (ptrdiff_t) == 0 \
1766 ? NBYTES \
1767 : max (NBYTES, sizeof (ptrdiff_t) - 1)) \
1768 + 1 \
1769 + sizeof (ptrdiff_t) - 1) \
1770 & ~(sizeof (ptrdiff_t) - 1))
1772 #endif /* not GC_CHECK_STRING_BYTES */
1774 /* Extra bytes to allocate for each string. */
1776 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1778 /* Exact bound on the number of bytes in a string, not counting the
1779 terminating null. A string cannot contain more bytes than
1780 STRING_BYTES_BOUND, nor can it be so long that the size_t
1781 arithmetic in allocate_string_data would overflow while it is
1782 calculating a value to be passed to malloc. */
1783 #define STRING_BYTES_MAX \
1784 min (STRING_BYTES_BOUND, \
1785 ((SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD \
1786 - GC_STRING_EXTRA \
1787 - offsetof (struct sblock, first_data) \
1788 - SDATA_DATA_OFFSET) \
1789 & ~(sizeof (EMACS_INT) - 1)))
1791 /* Initialize string allocation. Called from init_alloc_once. */
1793 static void
1794 init_strings (void)
1796 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1797 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1801 #ifdef GC_CHECK_STRING_BYTES
1803 static int check_string_bytes_count;
1805 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1808 /* Like GC_STRING_BYTES, but with debugging check. */
1810 ptrdiff_t
1811 string_bytes (struct Lisp_String *s)
1813 ptrdiff_t nbytes =
1814 (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1816 if (!PURE_POINTER_P (s)
1817 && s->data
1818 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1819 abort ();
1820 return nbytes;
1823 /* Check validity of Lisp strings' string_bytes member in B. */
1825 static void
1826 check_sblock (struct sblock *b)
1828 struct sdata *from, *end, *from_end;
1830 end = b->next_free;
1832 for (from = &b->first_data; from < end; from = from_end)
1834 /* Compute the next FROM here because copying below may
1835 overwrite data we need to compute it. */
1836 ptrdiff_t nbytes;
1838 /* Check that the string size recorded in the string is the
1839 same as the one recorded in the sdata structure. */
1840 if (from->string)
1841 CHECK_STRING_BYTES (from->string);
1843 if (from->string)
1844 nbytes = GC_STRING_BYTES (from->string);
1845 else
1846 nbytes = SDATA_NBYTES (from);
1848 nbytes = SDATA_SIZE (nbytes);
1849 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1854 /* Check validity of Lisp strings' string_bytes member. ALL_P
1855 non-zero means check all strings, otherwise check only most
1856 recently allocated strings. Used for hunting a bug. */
1858 static void
1859 check_string_bytes (int all_p)
1861 if (all_p)
1863 struct sblock *b;
1865 for (b = large_sblocks; b; b = b->next)
1867 struct Lisp_String *s = b->first_data.string;
1868 if (s)
1869 CHECK_STRING_BYTES (s);
1872 for (b = oldest_sblock; b; b = b->next)
1873 check_sblock (b);
1875 else if (current_sblock)
1876 check_sblock (current_sblock);
1879 #endif /* GC_CHECK_STRING_BYTES */
1881 #ifdef GC_CHECK_STRING_FREE_LIST
1883 /* Walk through the string free list looking for bogus next pointers.
1884 This may catch buffer overrun from a previous string. */
1886 static void
1887 check_string_free_list (void)
1889 struct Lisp_String *s;
1891 /* Pop a Lisp_String off the free-list. */
1892 s = string_free_list;
1893 while (s != NULL)
1895 if ((uintptr_t) s < 1024)
1896 abort ();
1897 s = NEXT_FREE_LISP_STRING (s);
1900 #else
1901 #define check_string_free_list()
1902 #endif
1904 /* Return a new Lisp_String. */
1906 static struct Lisp_String *
1907 allocate_string (void)
1909 struct Lisp_String *s;
1911 /* eassert (!handling_signal); */
1913 MALLOC_BLOCK_INPUT;
1915 /* If the free-list is empty, allocate a new string_block, and
1916 add all the Lisp_Strings in it to the free-list. */
1917 if (string_free_list == NULL)
1919 struct string_block *b = lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1920 int i;
1922 b->next = string_blocks;
1923 string_blocks = b;
1925 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1927 s = b->strings + i;
1928 /* Every string on a free list should have NULL data pointer. */
1929 s->data = NULL;
1930 NEXT_FREE_LISP_STRING (s) = string_free_list;
1931 string_free_list = s;
1934 total_free_strings += STRING_BLOCK_SIZE;
1937 check_string_free_list ();
1939 /* Pop a Lisp_String off the free-list. */
1940 s = string_free_list;
1941 string_free_list = NEXT_FREE_LISP_STRING (s);
1943 MALLOC_UNBLOCK_INPUT;
1945 --total_free_strings;
1946 ++total_strings;
1947 ++strings_consed;
1948 consing_since_gc += sizeof *s;
1950 #ifdef GC_CHECK_STRING_BYTES
1951 if (!noninteractive)
1953 if (++check_string_bytes_count == 200)
1955 check_string_bytes_count = 0;
1956 check_string_bytes (1);
1958 else
1959 check_string_bytes (0);
1961 #endif /* GC_CHECK_STRING_BYTES */
1963 return s;
1967 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1968 plus a NUL byte at the end. Allocate an sdata structure for S, and
1969 set S->data to its `u.data' member. Store a NUL byte at the end of
1970 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1971 S->data if it was initially non-null. */
1973 void
1974 allocate_string_data (struct Lisp_String *s,
1975 EMACS_INT nchars, EMACS_INT nbytes)
1977 struct sdata *data, *old_data;
1978 struct sblock *b;
1979 ptrdiff_t needed, old_nbytes;
1981 if (STRING_BYTES_MAX < nbytes)
1982 string_overflow ();
1984 /* Determine the number of bytes needed to store NBYTES bytes
1985 of string data. */
1986 needed = SDATA_SIZE (nbytes);
1987 if (s->data)
1989 old_data = SDATA_OF_STRING (s);
1990 old_nbytes = GC_STRING_BYTES (s);
1992 else
1993 old_data = NULL;
1995 MALLOC_BLOCK_INPUT;
1997 if (nbytes > LARGE_STRING_BYTES)
1999 size_t size = offsetof (struct sblock, first_data) + needed;
2001 #ifdef DOUG_LEA_MALLOC
2002 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2003 because mapped region contents are not preserved in
2004 a dumped Emacs.
2006 In case you think of allowing it in a dumped Emacs at the
2007 cost of not being able to re-dump, there's another reason:
2008 mmap'ed data typically have an address towards the top of the
2009 address space, which won't fit into an EMACS_INT (at least on
2010 32-bit systems with the current tagging scheme). --fx */
2011 mallopt (M_MMAP_MAX, 0);
2012 #endif
2014 b = lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
2016 #ifdef DOUG_LEA_MALLOC
2017 /* Back to a reasonable maximum of mmap'ed areas. */
2018 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2019 #endif
2021 b->next_free = &b->first_data;
2022 b->first_data.string = NULL;
2023 b->next = large_sblocks;
2024 large_sblocks = b;
2026 else if (current_sblock == NULL
2027 || (((char *) current_sblock + SBLOCK_SIZE
2028 - (char *) current_sblock->next_free)
2029 < (needed + GC_STRING_EXTRA)))
2031 /* Not enough room in the current sblock. */
2032 b = lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
2033 b->next_free = &b->first_data;
2034 b->first_data.string = NULL;
2035 b->next = NULL;
2037 if (current_sblock)
2038 current_sblock->next = b;
2039 else
2040 oldest_sblock = b;
2041 current_sblock = b;
2043 else
2044 b = current_sblock;
2046 data = b->next_free;
2047 b->next_free = (struct sdata *) ((char *) data + needed + GC_STRING_EXTRA);
2049 MALLOC_UNBLOCK_INPUT;
2051 data->string = s;
2052 s->data = SDATA_DATA (data);
2053 #ifdef GC_CHECK_STRING_BYTES
2054 SDATA_NBYTES (data) = nbytes;
2055 #endif
2056 s->size = nchars;
2057 s->size_byte = nbytes;
2058 s->data[nbytes] = '\0';
2059 #ifdef GC_CHECK_STRING_OVERRUN
2060 memcpy ((char *) data + needed, string_overrun_cookie,
2061 GC_STRING_OVERRUN_COOKIE_SIZE);
2062 #endif
2064 /* Note that Faset may call to this function when S has already data
2065 assigned. In this case, mark data as free by setting it's string
2066 back-pointer to null, and record the size of the data in it. */
2067 if (old_data)
2069 SDATA_NBYTES (old_data) = old_nbytes;
2070 old_data->string = NULL;
2073 consing_since_gc += needed;
2077 /* Sweep and compact strings. */
2079 static void
2080 sweep_strings (void)
2082 struct string_block *b, *next;
2083 struct string_block *live_blocks = NULL;
2085 string_free_list = NULL;
2086 total_strings = total_free_strings = 0;
2087 total_string_bytes = 0;
2089 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
2090 for (b = string_blocks; b; b = next)
2092 int i, nfree = 0;
2093 struct Lisp_String *free_list_before = string_free_list;
2095 next = b->next;
2097 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
2099 struct Lisp_String *s = b->strings + i;
2101 if (s->data)
2103 /* String was not on free-list before. */
2104 if (STRING_MARKED_P (s))
2106 /* String is live; unmark it and its intervals. */
2107 UNMARK_STRING (s);
2109 if (!NULL_INTERVAL_P (s->intervals))
2110 UNMARK_BALANCE_INTERVALS (s->intervals);
2112 ++total_strings;
2113 total_string_bytes += STRING_BYTES (s);
2115 else
2117 /* String is dead. Put it on the free-list. */
2118 struct sdata *data = SDATA_OF_STRING (s);
2120 /* Save the size of S in its sdata so that we know
2121 how large that is. Reset the sdata's string
2122 back-pointer so that we know it's free. */
2123 #ifdef GC_CHECK_STRING_BYTES
2124 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
2125 abort ();
2126 #else
2127 data->u.nbytes = GC_STRING_BYTES (s);
2128 #endif
2129 data->string = NULL;
2131 /* Reset the strings's `data' member so that we
2132 know it's free. */
2133 s->data = NULL;
2135 /* Put the string on the free-list. */
2136 NEXT_FREE_LISP_STRING (s) = string_free_list;
2137 string_free_list = s;
2138 ++nfree;
2141 else
2143 /* S was on the free-list before. Put it there again. */
2144 NEXT_FREE_LISP_STRING (s) = string_free_list;
2145 string_free_list = s;
2146 ++nfree;
2150 /* Free blocks that contain free Lisp_Strings only, except
2151 the first two of them. */
2152 if (nfree == STRING_BLOCK_SIZE
2153 && total_free_strings > STRING_BLOCK_SIZE)
2155 lisp_free (b);
2156 string_free_list = free_list_before;
2158 else
2160 total_free_strings += nfree;
2161 b->next = live_blocks;
2162 live_blocks = b;
2166 check_string_free_list ();
2168 string_blocks = live_blocks;
2169 free_large_strings ();
2170 compact_small_strings ();
2172 check_string_free_list ();
2176 /* Free dead large strings. */
2178 static void
2179 free_large_strings (void)
2181 struct sblock *b, *next;
2182 struct sblock *live_blocks = NULL;
2184 for (b = large_sblocks; b; b = next)
2186 next = b->next;
2188 if (b->first_data.string == NULL)
2189 lisp_free (b);
2190 else
2192 b->next = live_blocks;
2193 live_blocks = b;
2197 large_sblocks = live_blocks;
2201 /* Compact data of small strings. Free sblocks that don't contain
2202 data of live strings after compaction. */
2204 static void
2205 compact_small_strings (void)
2207 struct sblock *b, *tb, *next;
2208 struct sdata *from, *to, *end, *tb_end;
2209 struct sdata *to_end, *from_end;
2211 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2212 to, and TB_END is the end of TB. */
2213 tb = oldest_sblock;
2214 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2215 to = &tb->first_data;
2217 /* Step through the blocks from the oldest to the youngest. We
2218 expect that old blocks will stabilize over time, so that less
2219 copying will happen this way. */
2220 for (b = oldest_sblock; b; b = b->next)
2222 end = b->next_free;
2223 eassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2225 for (from = &b->first_data; from < end; from = from_end)
2227 /* Compute the next FROM here because copying below may
2228 overwrite data we need to compute it. */
2229 ptrdiff_t nbytes;
2231 #ifdef GC_CHECK_STRING_BYTES
2232 /* Check that the string size recorded in the string is the
2233 same as the one recorded in the sdata structure. */
2234 if (from->string
2235 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
2236 abort ();
2237 #endif /* GC_CHECK_STRING_BYTES */
2239 if (from->string)
2240 nbytes = GC_STRING_BYTES (from->string);
2241 else
2242 nbytes = SDATA_NBYTES (from);
2244 if (nbytes > LARGE_STRING_BYTES)
2245 abort ();
2247 nbytes = SDATA_SIZE (nbytes);
2248 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
2250 #ifdef GC_CHECK_STRING_OVERRUN
2251 if (memcmp (string_overrun_cookie,
2252 (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
2253 GC_STRING_OVERRUN_COOKIE_SIZE))
2254 abort ();
2255 #endif
2257 /* FROM->string non-null means it's alive. Copy its data. */
2258 if (from->string)
2260 /* If TB is full, proceed with the next sblock. */
2261 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2262 if (to_end > tb_end)
2264 tb->next_free = to;
2265 tb = tb->next;
2266 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2267 to = &tb->first_data;
2268 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2271 /* Copy, and update the string's `data' pointer. */
2272 if (from != to)
2274 eassert (tb != b || to < from);
2275 memmove (to, from, nbytes + GC_STRING_EXTRA);
2276 to->string->data = SDATA_DATA (to);
2279 /* Advance past the sdata we copied to. */
2280 to = to_end;
2285 /* The rest of the sblocks following TB don't contain live data, so
2286 we can free them. */
2287 for (b = tb->next; b; b = next)
2289 next = b->next;
2290 lisp_free (b);
2293 tb->next_free = to;
2294 tb->next = NULL;
2295 current_sblock = tb;
2298 void
2299 string_overflow (void)
2301 error ("Maximum string size exceeded");
2304 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2305 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2306 LENGTH must be an integer.
2307 INIT must be an integer that represents a character. */)
2308 (Lisp_Object length, Lisp_Object init)
2310 register Lisp_Object val;
2311 register unsigned char *p, *end;
2312 int c;
2313 EMACS_INT nbytes;
2315 CHECK_NATNUM (length);
2316 CHECK_CHARACTER (init);
2318 c = XFASTINT (init);
2319 if (ASCII_CHAR_P (c))
2321 nbytes = XINT (length);
2322 val = make_uninit_string (nbytes);
2323 p = SDATA (val);
2324 end = p + SCHARS (val);
2325 while (p != end)
2326 *p++ = c;
2328 else
2330 unsigned char str[MAX_MULTIBYTE_LENGTH];
2331 int len = CHAR_STRING (c, str);
2332 EMACS_INT string_len = XINT (length);
2334 if (string_len > STRING_BYTES_MAX / len)
2335 string_overflow ();
2336 nbytes = len * string_len;
2337 val = make_uninit_multibyte_string (string_len, nbytes);
2338 p = SDATA (val);
2339 end = p + nbytes;
2340 while (p != end)
2342 memcpy (p, str, len);
2343 p += len;
2347 *p = 0;
2348 return val;
2352 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2353 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2354 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2355 (Lisp_Object length, Lisp_Object init)
2357 register Lisp_Object val;
2358 struct Lisp_Bool_Vector *p;
2359 ptrdiff_t length_in_chars;
2360 EMACS_INT length_in_elts;
2361 int bits_per_value;
2362 int extra_bool_elts = ((bool_header_size - header_size + word_size - 1)
2363 / word_size);
2365 CHECK_NATNUM (length);
2367 bits_per_value = sizeof (EMACS_INT) * BOOL_VECTOR_BITS_PER_CHAR;
2369 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
2371 val = Fmake_vector (make_number (length_in_elts + extra_bool_elts), Qnil);
2373 /* No Lisp_Object to trace in there. */
2374 XSETPVECTYPESIZE (XVECTOR (val), PVEC_BOOL_VECTOR, 0);
2376 p = XBOOL_VECTOR (val);
2377 p->size = XFASTINT (length);
2379 length_in_chars = ((XFASTINT (length) + BOOL_VECTOR_BITS_PER_CHAR - 1)
2380 / BOOL_VECTOR_BITS_PER_CHAR);
2381 if (length_in_chars)
2383 memset (p->data, ! NILP (init) ? -1 : 0, length_in_chars);
2385 /* Clear any extraneous bits in the last byte. */
2386 p->data[length_in_chars - 1]
2387 &= (1 << ((XFASTINT (length) - 1) % BOOL_VECTOR_BITS_PER_CHAR + 1)) - 1;
2390 return val;
2394 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2395 of characters from the contents. This string may be unibyte or
2396 multibyte, depending on the contents. */
2398 Lisp_Object
2399 make_string (const char *contents, ptrdiff_t nbytes)
2401 register Lisp_Object val;
2402 ptrdiff_t nchars, multibyte_nbytes;
2404 parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
2405 &nchars, &multibyte_nbytes);
2406 if (nbytes == nchars || nbytes != multibyte_nbytes)
2407 /* CONTENTS contains no multibyte sequences or contains an invalid
2408 multibyte sequence. We must make unibyte string. */
2409 val = make_unibyte_string (contents, nbytes);
2410 else
2411 val = make_multibyte_string (contents, nchars, nbytes);
2412 return val;
2416 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
2418 Lisp_Object
2419 make_unibyte_string (const char *contents, ptrdiff_t length)
2421 register Lisp_Object val;
2422 val = make_uninit_string (length);
2423 memcpy (SDATA (val), contents, length);
2424 return val;
2428 /* Make a multibyte string from NCHARS characters occupying NBYTES
2429 bytes at CONTENTS. */
2431 Lisp_Object
2432 make_multibyte_string (const char *contents,
2433 ptrdiff_t nchars, ptrdiff_t nbytes)
2435 register Lisp_Object val;
2436 val = make_uninit_multibyte_string (nchars, nbytes);
2437 memcpy (SDATA (val), contents, nbytes);
2438 return val;
2442 /* Make a string from NCHARS characters occupying NBYTES bytes at
2443 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2445 Lisp_Object
2446 make_string_from_bytes (const char *contents,
2447 ptrdiff_t nchars, ptrdiff_t nbytes)
2449 register Lisp_Object val;
2450 val = make_uninit_multibyte_string (nchars, nbytes);
2451 memcpy (SDATA (val), contents, nbytes);
2452 if (SBYTES (val) == SCHARS (val))
2453 STRING_SET_UNIBYTE (val);
2454 return val;
2458 /* Make a string from NCHARS characters occupying NBYTES bytes at
2459 CONTENTS. The argument MULTIBYTE controls whether to label the
2460 string as multibyte. If NCHARS is negative, it counts the number of
2461 characters by itself. */
2463 Lisp_Object
2464 make_specified_string (const char *contents,
2465 ptrdiff_t nchars, ptrdiff_t nbytes, int multibyte)
2467 register Lisp_Object val;
2469 if (nchars < 0)
2471 if (multibyte)
2472 nchars = multibyte_chars_in_text ((const unsigned char *) contents,
2473 nbytes);
2474 else
2475 nchars = nbytes;
2477 val = make_uninit_multibyte_string (nchars, nbytes);
2478 memcpy (SDATA (val), contents, nbytes);
2479 if (!multibyte)
2480 STRING_SET_UNIBYTE (val);
2481 return val;
2485 /* Return an unibyte Lisp_String set up to hold LENGTH characters
2486 occupying LENGTH bytes. */
2488 Lisp_Object
2489 make_uninit_string (EMACS_INT length)
2491 Lisp_Object val;
2493 if (!length)
2494 return empty_unibyte_string;
2495 val = make_uninit_multibyte_string (length, length);
2496 STRING_SET_UNIBYTE (val);
2497 return val;
2501 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2502 which occupy NBYTES bytes. */
2504 Lisp_Object
2505 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2507 Lisp_Object string;
2508 struct Lisp_String *s;
2510 if (nchars < 0)
2511 abort ();
2512 if (!nbytes)
2513 return empty_multibyte_string;
2515 s = allocate_string ();
2516 s->intervals = NULL_INTERVAL;
2517 allocate_string_data (s, nchars, nbytes);
2518 XSETSTRING (string, s);
2519 string_chars_consed += nbytes;
2520 return string;
2523 /* Print arguments to BUF according to a FORMAT, then return
2524 a Lisp_String initialized with the data from BUF. */
2526 Lisp_Object
2527 make_formatted_string (char *buf, const char *format, ...)
2529 va_list ap;
2530 int length;
2532 va_start (ap, format);
2533 length = vsprintf (buf, format, ap);
2534 va_end (ap);
2535 return make_string (buf, length);
2539 /***********************************************************************
2540 Float Allocation
2541 ***********************************************************************/
2543 /* We store float cells inside of float_blocks, allocating a new
2544 float_block with malloc whenever necessary. Float cells reclaimed
2545 by GC are put on a free list to be reallocated before allocating
2546 any new float cells from the latest float_block. */
2548 #define FLOAT_BLOCK_SIZE \
2549 (((BLOCK_BYTES - sizeof (struct float_block *) \
2550 /* The compiler might add padding at the end. */ \
2551 - (sizeof (struct Lisp_Float) - sizeof (int))) * CHAR_BIT) \
2552 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2554 #define GETMARKBIT(block,n) \
2555 (((block)->gcmarkbits[(n) / (sizeof (int) * CHAR_BIT)] \
2556 >> ((n) % (sizeof (int) * CHAR_BIT))) \
2557 & 1)
2559 #define SETMARKBIT(block,n) \
2560 (block)->gcmarkbits[(n) / (sizeof (int) * CHAR_BIT)] \
2561 |= 1 << ((n) % (sizeof (int) * CHAR_BIT))
2563 #define UNSETMARKBIT(block,n) \
2564 (block)->gcmarkbits[(n) / (sizeof (int) * CHAR_BIT)] \
2565 &= ~(1 << ((n) % (sizeof (int) * CHAR_BIT)))
2567 #define FLOAT_BLOCK(fptr) \
2568 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2570 #define FLOAT_INDEX(fptr) \
2571 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2573 struct float_block
2575 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2576 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2577 int gcmarkbits[1 + FLOAT_BLOCK_SIZE / (sizeof (int) * CHAR_BIT)];
2578 struct float_block *next;
2581 #define FLOAT_MARKED_P(fptr) \
2582 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2584 #define FLOAT_MARK(fptr) \
2585 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2587 #define FLOAT_UNMARK(fptr) \
2588 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2590 /* Current float_block. */
2592 static struct float_block *float_block;
2594 /* Index of first unused Lisp_Float in the current float_block. */
2596 static int float_block_index = FLOAT_BLOCK_SIZE;
2598 /* Free-list of Lisp_Floats. */
2600 static struct Lisp_Float *float_free_list;
2602 /* Return a new float object with value FLOAT_VALUE. */
2604 Lisp_Object
2605 make_float (double float_value)
2607 register Lisp_Object val;
2609 /* eassert (!handling_signal); */
2611 MALLOC_BLOCK_INPUT;
2613 if (float_free_list)
2615 /* We use the data field for chaining the free list
2616 so that we won't use the same field that has the mark bit. */
2617 XSETFLOAT (val, float_free_list);
2618 float_free_list = float_free_list->u.chain;
2620 else
2622 if (float_block_index == FLOAT_BLOCK_SIZE)
2624 struct float_block *new
2625 = lisp_align_malloc (sizeof *new, MEM_TYPE_FLOAT);
2626 new->next = float_block;
2627 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2628 float_block = new;
2629 float_block_index = 0;
2630 total_free_floats += FLOAT_BLOCK_SIZE;
2632 XSETFLOAT (val, &float_block->floats[float_block_index]);
2633 float_block_index++;
2636 MALLOC_UNBLOCK_INPUT;
2638 XFLOAT_INIT (val, float_value);
2639 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2640 consing_since_gc += sizeof (struct Lisp_Float);
2641 floats_consed++;
2642 total_free_floats--;
2643 return val;
2648 /***********************************************************************
2649 Cons Allocation
2650 ***********************************************************************/
2652 /* We store cons cells inside of cons_blocks, allocating a new
2653 cons_block with malloc whenever necessary. Cons cells reclaimed by
2654 GC are put on a free list to be reallocated before allocating
2655 any new cons cells from the latest cons_block. */
2657 #define CONS_BLOCK_SIZE \
2658 (((BLOCK_BYTES - sizeof (struct cons_block *) \
2659 /* The compiler might add padding at the end. */ \
2660 - (sizeof (struct Lisp_Cons) - sizeof (int))) * CHAR_BIT) \
2661 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2663 #define CONS_BLOCK(fptr) \
2664 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2666 #define CONS_INDEX(fptr) \
2667 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2669 struct cons_block
2671 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2672 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2673 int gcmarkbits[1 + CONS_BLOCK_SIZE / (sizeof (int) * CHAR_BIT)];
2674 struct cons_block *next;
2677 #define CONS_MARKED_P(fptr) \
2678 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2680 #define CONS_MARK(fptr) \
2681 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2683 #define CONS_UNMARK(fptr) \
2684 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2686 /* Current cons_block. */
2688 static struct cons_block *cons_block;
2690 /* Index of first unused Lisp_Cons in the current block. */
2692 static int cons_block_index = CONS_BLOCK_SIZE;
2694 /* Free-list of Lisp_Cons structures. */
2696 static struct Lisp_Cons *cons_free_list;
2698 /* Explicitly free a cons cell by putting it on the free-list. */
2700 void
2701 free_cons (struct Lisp_Cons *ptr)
2703 ptr->u.chain = cons_free_list;
2704 #if GC_MARK_STACK
2705 ptr->car = Vdead;
2706 #endif
2707 cons_free_list = ptr;
2708 consing_since_gc -= sizeof *ptr;
2709 total_free_conses++;
2712 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2713 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2714 (Lisp_Object car, Lisp_Object cdr)
2716 register Lisp_Object val;
2718 /* eassert (!handling_signal); */
2720 MALLOC_BLOCK_INPUT;
2722 if (cons_free_list)
2724 /* We use the cdr for chaining the free list
2725 so that we won't use the same field that has the mark bit. */
2726 XSETCONS (val, cons_free_list);
2727 cons_free_list = cons_free_list->u.chain;
2729 else
2731 if (cons_block_index == CONS_BLOCK_SIZE)
2733 struct cons_block *new
2734 = lisp_align_malloc (sizeof *new, MEM_TYPE_CONS);
2735 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2736 new->next = cons_block;
2737 cons_block = new;
2738 cons_block_index = 0;
2739 total_free_conses += CONS_BLOCK_SIZE;
2741 XSETCONS (val, &cons_block->conses[cons_block_index]);
2742 cons_block_index++;
2745 MALLOC_UNBLOCK_INPUT;
2747 XSETCAR (val, car);
2748 XSETCDR (val, cdr);
2749 eassert (!CONS_MARKED_P (XCONS (val)));
2750 consing_since_gc += sizeof (struct Lisp_Cons);
2751 total_free_conses--;
2752 cons_cells_consed++;
2753 return val;
2756 #ifdef GC_CHECK_CONS_LIST
2757 /* Get an error now if there's any junk in the cons free list. */
2758 void
2759 check_cons_list (void)
2761 struct Lisp_Cons *tail = cons_free_list;
2763 while (tail)
2764 tail = tail->u.chain;
2766 #endif
2768 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2770 Lisp_Object
2771 list1 (Lisp_Object arg1)
2773 return Fcons (arg1, Qnil);
2776 Lisp_Object
2777 list2 (Lisp_Object arg1, Lisp_Object arg2)
2779 return Fcons (arg1, Fcons (arg2, Qnil));
2783 Lisp_Object
2784 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2786 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2790 Lisp_Object
2791 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2793 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2797 Lisp_Object
2798 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2800 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2801 Fcons (arg5, Qnil)))));
2804 /* Make a list of COUNT Lisp_Objects, where ARG is the
2805 first one. Allocate conses from pure space if TYPE
2806 is CONSTYPE_PURE, or allocate as usual if type is CONSTYPE_HEAP. */
2808 Lisp_Object
2809 listn (enum constype type, ptrdiff_t count, Lisp_Object arg, ...)
2811 va_list ap;
2812 ptrdiff_t i;
2813 Lisp_Object val, *objp;
2815 /* Change to SAFE_ALLOCA if you hit this eassert. */
2816 eassert (count <= MAX_ALLOCA / sizeof (Lisp_Object));
2818 objp = alloca (count * sizeof (Lisp_Object));
2819 objp[0] = arg;
2820 va_start (ap, arg);
2821 for (i = 1; i < count; i++)
2822 objp[i] = va_arg (ap, Lisp_Object);
2823 va_end (ap);
2825 for (val = Qnil, i = count - 1; i >= 0; i--)
2827 if (type == CONSTYPE_PURE)
2828 val = pure_cons (objp[i], val);
2829 else if (type == CONSTYPE_HEAP)
2830 val = Fcons (objp[i], val);
2831 else
2832 abort ();
2834 return val;
2837 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2838 doc: /* Return a newly created list with specified arguments as elements.
2839 Any number of arguments, even zero arguments, are allowed.
2840 usage: (list &rest OBJECTS) */)
2841 (ptrdiff_t nargs, Lisp_Object *args)
2843 register Lisp_Object val;
2844 val = Qnil;
2846 while (nargs > 0)
2848 nargs--;
2849 val = Fcons (args[nargs], val);
2851 return val;
2855 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2856 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2857 (register Lisp_Object length, Lisp_Object init)
2859 register Lisp_Object val;
2860 register EMACS_INT size;
2862 CHECK_NATNUM (length);
2863 size = XFASTINT (length);
2865 val = Qnil;
2866 while (size > 0)
2868 val = Fcons (init, val);
2869 --size;
2871 if (size > 0)
2873 val = Fcons (init, val);
2874 --size;
2876 if (size > 0)
2878 val = Fcons (init, val);
2879 --size;
2881 if (size > 0)
2883 val = Fcons (init, val);
2884 --size;
2886 if (size > 0)
2888 val = Fcons (init, val);
2889 --size;
2895 QUIT;
2898 return val;
2903 /***********************************************************************
2904 Vector Allocation
2905 ***********************************************************************/
2907 /* This value is balanced well enough to avoid too much internal overhead
2908 for the most common cases; it's not required to be a power of two, but
2909 it's expected to be a mult-of-ROUNDUP_SIZE (see below). */
2911 #define VECTOR_BLOCK_SIZE 4096
2913 /* Align allocation request sizes to be a multiple of ROUNDUP_SIZE. */
2914 enum
2916 roundup_size = COMMON_MULTIPLE (word_size,
2917 USE_LSB_TAG ? 1 << GCTYPEBITS : 1)
2920 /* ROUNDUP_SIZE must be a power of 2. */
2921 verify ((roundup_size & (roundup_size - 1)) == 0);
2923 /* Verify assumptions described above. */
2924 verify ((VECTOR_BLOCK_SIZE % roundup_size) == 0);
2925 verify (VECTOR_BLOCK_SIZE <= (1 << PSEUDOVECTOR_SIZE_BITS));
2927 /* Round up X to nearest mult-of-ROUNDUP_SIZE. */
2929 #define vroundup(x) (((x) + (roundup_size - 1)) & ~(roundup_size - 1))
2931 /* Rounding helps to maintain alignment constraints if USE_LSB_TAG. */
2933 #define VECTOR_BLOCK_BYTES (VECTOR_BLOCK_SIZE - vroundup (sizeof (void *)))
2935 /* Size of the minimal vector allocated from block. */
2937 #define VBLOCK_BYTES_MIN vroundup (sizeof (struct Lisp_Vector))
2939 /* Size of the largest vector allocated from block. */
2941 #define VBLOCK_BYTES_MAX \
2942 vroundup ((VECTOR_BLOCK_BYTES / 2) - word_size)
2944 /* We maintain one free list for each possible block-allocated
2945 vector size, and this is the number of free lists we have. */
2947 #define VECTOR_MAX_FREE_LIST_INDEX \
2948 ((VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN) / roundup_size + 1)
2950 /* Common shortcut to advance vector pointer over a block data. */
2952 #define ADVANCE(v, nbytes) ((struct Lisp_Vector *) ((char *) (v) + (nbytes)))
2954 /* Common shortcut to calculate NBYTES-vector index in VECTOR_FREE_LISTS. */
2956 #define VINDEX(nbytes) (((nbytes) - VBLOCK_BYTES_MIN) / roundup_size)
2958 /* Common shortcut to setup vector on a free list. */
2960 #define SETUP_ON_FREE_LIST(v, nbytes, index) \
2961 do { \
2962 XSETPVECTYPESIZE (v, PVEC_FREE, nbytes); \
2963 eassert ((nbytes) % roundup_size == 0); \
2964 (index) = VINDEX (nbytes); \
2965 eassert ((index) < VECTOR_MAX_FREE_LIST_INDEX); \
2966 (v)->header.next.vector = vector_free_lists[index]; \
2967 vector_free_lists[index] = (v); \
2968 total_free_vector_slots += (nbytes) / word_size; \
2969 } while (0)
2971 struct vector_block
2973 char data[VECTOR_BLOCK_BYTES];
2974 struct vector_block *next;
2977 /* Chain of vector blocks. */
2979 static struct vector_block *vector_blocks;
2981 /* Vector free lists, where NTH item points to a chain of free
2982 vectors of the same NBYTES size, so NTH == VINDEX (NBYTES). */
2984 static struct Lisp_Vector *vector_free_lists[VECTOR_MAX_FREE_LIST_INDEX];
2986 /* Singly-linked list of large vectors. */
2988 static struct Lisp_Vector *large_vectors;
2990 /* The only vector with 0 slots, allocated from pure space. */
2992 Lisp_Object zero_vector;
2994 /* Number of live vectors. */
2996 static EMACS_INT total_vectors;
2998 /* Total size of live and free vectors, in Lisp_Object units. */
3000 static EMACS_INT total_vector_slots, total_free_vector_slots;
3002 /* Get a new vector block. */
3004 static struct vector_block *
3005 allocate_vector_block (void)
3007 struct vector_block *block = xmalloc (sizeof *block);
3009 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
3010 mem_insert (block->data, block->data + VECTOR_BLOCK_BYTES,
3011 MEM_TYPE_VECTOR_BLOCK);
3012 #endif
3014 block->next = vector_blocks;
3015 vector_blocks = block;
3016 return block;
3019 /* Called once to initialize vector allocation. */
3021 static void
3022 init_vectors (void)
3024 zero_vector = make_pure_vector (0);
3027 /* Allocate vector from a vector block. */
3029 static struct Lisp_Vector *
3030 allocate_vector_from_block (size_t nbytes)
3032 struct Lisp_Vector *vector, *rest;
3033 struct vector_block *block;
3034 size_t index, restbytes;
3036 eassert (VBLOCK_BYTES_MIN <= nbytes && nbytes <= VBLOCK_BYTES_MAX);
3037 eassert (nbytes % roundup_size == 0);
3039 /* First, try to allocate from a free list
3040 containing vectors of the requested size. */
3041 index = VINDEX (nbytes);
3042 if (vector_free_lists[index])
3044 vector = vector_free_lists[index];
3045 vector_free_lists[index] = vector->header.next.vector;
3046 vector->header.next.nbytes = nbytes;
3047 total_free_vector_slots -= nbytes / word_size;
3048 return vector;
3051 /* Next, check free lists containing larger vectors. Since
3052 we will split the result, we should have remaining space
3053 large enough to use for one-slot vector at least. */
3054 for (index = VINDEX (nbytes + VBLOCK_BYTES_MIN);
3055 index < VECTOR_MAX_FREE_LIST_INDEX; index++)
3056 if (vector_free_lists[index])
3058 /* This vector is larger than requested. */
3059 vector = vector_free_lists[index];
3060 vector_free_lists[index] = vector->header.next.vector;
3061 vector->header.next.nbytes = nbytes;
3062 total_free_vector_slots -= nbytes / word_size;
3064 /* Excess bytes are used for the smaller vector,
3065 which should be set on an appropriate free list. */
3066 restbytes = index * roundup_size + VBLOCK_BYTES_MIN - nbytes;
3067 eassert (restbytes % roundup_size == 0);
3068 rest = ADVANCE (vector, nbytes);
3069 SETUP_ON_FREE_LIST (rest, restbytes, index);
3070 return vector;
3073 /* Finally, need a new vector block. */
3074 block = allocate_vector_block ();
3076 /* New vector will be at the beginning of this block. */
3077 vector = (struct Lisp_Vector *) block->data;
3078 vector->header.next.nbytes = nbytes;
3080 /* If the rest of space from this block is large enough
3081 for one-slot vector at least, set up it on a free list. */
3082 restbytes = VECTOR_BLOCK_BYTES - nbytes;
3083 if (restbytes >= VBLOCK_BYTES_MIN)
3085 eassert (restbytes % roundup_size == 0);
3086 rest = ADVANCE (vector, nbytes);
3087 SETUP_ON_FREE_LIST (rest, restbytes, index);
3089 return vector;
3092 /* Nonzero if VECTOR pointer is valid pointer inside BLOCK. */
3094 #define VECTOR_IN_BLOCK(vector, block) \
3095 ((char *) (vector) <= (block)->data \
3096 + VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN)
3098 /* Number of bytes used by vector-block-allocated object. This is the only
3099 place where we actually use the `nbytes' field of the vector-header.
3100 I.e. we could get rid of the `nbytes' field by computing it based on the
3101 vector-type. */
3103 #define PSEUDOVECTOR_NBYTES(vector) \
3104 (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FREE) \
3105 ? vector->header.size & PSEUDOVECTOR_SIZE_MASK \
3106 : vector->header.next.nbytes)
3108 /* Reclaim space used by unmarked vectors. */
3110 static void
3111 sweep_vectors (void)
3113 struct vector_block *block = vector_blocks, **bprev = &vector_blocks;
3114 struct Lisp_Vector *vector, *next, **vprev = &large_vectors;
3116 total_vectors = total_vector_slots = total_free_vector_slots = 0;
3117 memset (vector_free_lists, 0, sizeof (vector_free_lists));
3119 /* Looking through vector blocks. */
3121 for (block = vector_blocks; block; block = *bprev)
3123 int free_this_block = 0;
3125 for (vector = (struct Lisp_Vector *) block->data;
3126 VECTOR_IN_BLOCK (vector, block); vector = next)
3128 if (VECTOR_MARKED_P (vector))
3130 VECTOR_UNMARK (vector);
3131 total_vectors++;
3132 total_vector_slots += vector->header.next.nbytes / word_size;
3133 next = ADVANCE (vector, vector->header.next.nbytes);
3135 else
3137 ptrdiff_t nbytes = PSEUDOVECTOR_NBYTES (vector);
3138 ptrdiff_t total_bytes = nbytes;
3140 next = ADVANCE (vector, nbytes);
3142 /* While NEXT is not marked, try to coalesce with VECTOR,
3143 thus making VECTOR of the largest possible size. */
3145 while (VECTOR_IN_BLOCK (next, block))
3147 if (VECTOR_MARKED_P (next))
3148 break;
3149 nbytes = PSEUDOVECTOR_NBYTES (next);
3150 total_bytes += nbytes;
3151 next = ADVANCE (next, nbytes);
3154 eassert (total_bytes % roundup_size == 0);
3156 if (vector == (struct Lisp_Vector *) block->data
3157 && !VECTOR_IN_BLOCK (next, block))
3158 /* This block should be freed because all of it's
3159 space was coalesced into the only free vector. */
3160 free_this_block = 1;
3161 else
3163 int tmp;
3164 SETUP_ON_FREE_LIST (vector, total_bytes, tmp);
3169 if (free_this_block)
3171 *bprev = block->next;
3172 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
3173 mem_delete (mem_find (block->data));
3174 #endif
3175 xfree (block);
3177 else
3178 bprev = &block->next;
3181 /* Sweep large vectors. */
3183 for (vector = large_vectors; vector; vector = *vprev)
3185 if (VECTOR_MARKED_P (vector))
3187 VECTOR_UNMARK (vector);
3188 total_vectors++;
3189 if (vector->header.size & PSEUDOVECTOR_FLAG)
3191 struct Lisp_Bool_Vector *b = (struct Lisp_Bool_Vector *) vector;
3193 /* All non-bool pseudovectors are small enough to be allocated
3194 from vector blocks. This code should be redesigned if some
3195 pseudovector type grows beyond VBLOCK_BYTES_MAX. */
3196 eassert (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_BOOL_VECTOR));
3198 total_vector_slots
3199 += (bool_header_size
3200 + ((b->size + BOOL_VECTOR_BITS_PER_CHAR - 1)
3201 / BOOL_VECTOR_BITS_PER_CHAR)) / word_size;
3203 else
3204 total_vector_slots
3205 += header_size / word_size + vector->header.size;
3206 vprev = &vector->header.next.vector;
3208 else
3210 *vprev = vector->header.next.vector;
3211 lisp_free (vector);
3216 /* Value is a pointer to a newly allocated Lisp_Vector structure
3217 with room for LEN Lisp_Objects. */
3219 static struct Lisp_Vector *
3220 allocate_vectorlike (ptrdiff_t len)
3222 struct Lisp_Vector *p;
3224 MALLOC_BLOCK_INPUT;
3226 /* This gets triggered by code which I haven't bothered to fix. --Stef */
3227 /* eassert (!handling_signal); */
3229 if (len == 0)
3230 p = XVECTOR (zero_vector);
3231 else
3233 size_t nbytes = header_size + len * word_size;
3235 #ifdef DOUG_LEA_MALLOC
3236 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
3237 because mapped region contents are not preserved in
3238 a dumped Emacs. */
3239 mallopt (M_MMAP_MAX, 0);
3240 #endif
3242 if (nbytes <= VBLOCK_BYTES_MAX)
3243 p = allocate_vector_from_block (vroundup (nbytes));
3244 else
3246 p = lisp_malloc (nbytes, MEM_TYPE_VECTORLIKE);
3247 p->header.next.vector = large_vectors;
3248 large_vectors = p;
3251 #ifdef DOUG_LEA_MALLOC
3252 /* Back to a reasonable maximum of mmap'ed areas. */
3253 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
3254 #endif
3256 consing_since_gc += nbytes;
3257 vector_cells_consed += len;
3260 MALLOC_UNBLOCK_INPUT;
3262 return p;
3266 /* Allocate a vector with LEN slots. */
3268 struct Lisp_Vector *
3269 allocate_vector (EMACS_INT len)
3271 struct Lisp_Vector *v;
3272 ptrdiff_t nbytes_max = min (PTRDIFF_MAX, SIZE_MAX);
3274 if (min ((nbytes_max - header_size) / word_size, MOST_POSITIVE_FIXNUM) < len)
3275 memory_full (SIZE_MAX);
3276 v = allocate_vectorlike (len);
3277 v->header.size = len;
3278 return v;
3282 /* Allocate other vector-like structures. */
3284 struct Lisp_Vector *
3285 allocate_pseudovector (int memlen, int lisplen, int tag)
3287 struct Lisp_Vector *v = allocate_vectorlike (memlen);
3288 int i;
3290 /* Only the first lisplen slots will be traced normally by the GC. */
3291 for (i = 0; i < lisplen; ++i)
3292 v->contents[i] = Qnil;
3294 XSETPVECTYPESIZE (v, tag, lisplen);
3295 return v;
3298 struct buffer *
3299 allocate_buffer (void)
3301 struct buffer *b = lisp_malloc (sizeof *b, MEM_TYPE_BUFFER);
3303 XSETPVECTYPESIZE (b, PVEC_BUFFER, (offsetof (struct buffer, own_text)
3304 - header_size) / word_size);
3305 /* Note that the fields of B are not initialized. */
3306 return b;
3309 struct Lisp_Hash_Table *
3310 allocate_hash_table (void)
3312 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table, count, PVEC_HASH_TABLE);
3315 struct window *
3316 allocate_window (void)
3318 struct window *w;
3320 w = ALLOCATE_PSEUDOVECTOR (struct window, current_matrix, PVEC_WINDOW);
3321 /* Users assumes that non-Lisp data is zeroed. */
3322 memset (&w->current_matrix, 0,
3323 sizeof (*w) - offsetof (struct window, current_matrix));
3324 return w;
3327 struct terminal *
3328 allocate_terminal (void)
3330 struct terminal *t;
3332 t = ALLOCATE_PSEUDOVECTOR (struct terminal, next_terminal, PVEC_TERMINAL);
3333 /* Users assumes that non-Lisp data is zeroed. */
3334 memset (&t->next_terminal, 0,
3335 sizeof (*t) - offsetof (struct terminal, next_terminal));
3336 return t;
3339 struct frame *
3340 allocate_frame (void)
3342 struct frame *f;
3344 f = ALLOCATE_PSEUDOVECTOR (struct frame, face_cache, PVEC_FRAME);
3345 /* Users assumes that non-Lisp data is zeroed. */
3346 memset (&f->face_cache, 0,
3347 sizeof (*f) - offsetof (struct frame, face_cache));
3348 return f;
3351 struct Lisp_Process *
3352 allocate_process (void)
3354 struct Lisp_Process *p;
3356 p = ALLOCATE_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
3357 /* Users assumes that non-Lisp data is zeroed. */
3358 memset (&p->pid, 0,
3359 sizeof (*p) - offsetof (struct Lisp_Process, pid));
3360 return p;
3363 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
3364 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
3365 See also the function `vector'. */)
3366 (register Lisp_Object length, Lisp_Object init)
3368 Lisp_Object vector;
3369 register ptrdiff_t sizei;
3370 register ptrdiff_t i;
3371 register struct Lisp_Vector *p;
3373 CHECK_NATNUM (length);
3375 p = allocate_vector (XFASTINT (length));
3376 sizei = XFASTINT (length);
3377 for (i = 0; i < sizei; i++)
3378 p->contents[i] = init;
3380 XSETVECTOR (vector, p);
3381 return vector;
3385 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3386 doc: /* Return a newly created vector with specified arguments as elements.
3387 Any number of arguments, even zero arguments, are allowed.
3388 usage: (vector &rest OBJECTS) */)
3389 (ptrdiff_t nargs, Lisp_Object *args)
3391 register Lisp_Object len, val;
3392 ptrdiff_t i;
3393 register struct Lisp_Vector *p;
3395 XSETFASTINT (len, nargs);
3396 val = Fmake_vector (len, Qnil);
3397 p = XVECTOR (val);
3398 for (i = 0; i < nargs; i++)
3399 p->contents[i] = args[i];
3400 return val;
3403 void
3404 make_byte_code (struct Lisp_Vector *v)
3406 if (v->header.size > 1 && STRINGP (v->contents[1])
3407 && STRING_MULTIBYTE (v->contents[1]))
3408 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3409 earlier because they produced a raw 8-bit string for byte-code
3410 and now such a byte-code string is loaded as multibyte while
3411 raw 8-bit characters converted to multibyte form. Thus, now we
3412 must convert them back to the original unibyte form. */
3413 v->contents[1] = Fstring_as_unibyte (v->contents[1]);
3414 XSETPVECTYPE (v, PVEC_COMPILED);
3417 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3418 doc: /* Create a byte-code object with specified arguments as elements.
3419 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3420 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3421 and (optional) INTERACTIVE-SPEC.
3422 The first four arguments are required; at most six have any
3423 significance.
3424 The ARGLIST can be either like the one of `lambda', in which case the arguments
3425 will be dynamically bound before executing the byte code, or it can be an
3426 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3427 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3428 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3429 argument to catch the left-over arguments. If such an integer is used, the
3430 arguments will not be dynamically bound but will be instead pushed on the
3431 stack before executing the byte-code.
3432 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3433 (ptrdiff_t nargs, Lisp_Object *args)
3435 register Lisp_Object len, val;
3436 ptrdiff_t i;
3437 register struct Lisp_Vector *p;
3439 /* We used to purecopy everything here, if purify-flga was set. This worked
3440 OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
3441 dangerous, since make-byte-code is used during execution to build
3442 closures, so any closure built during the preload phase would end up
3443 copied into pure space, including its free variables, which is sometimes
3444 just wasteful and other times plainly wrong (e.g. those free vars may want
3445 to be setcar'd). */
3447 XSETFASTINT (len, nargs);
3448 val = Fmake_vector (len, Qnil);
3450 p = XVECTOR (val);
3451 for (i = 0; i < nargs; i++)
3452 p->contents[i] = args[i];
3453 make_byte_code (p);
3454 XSETCOMPILED (val, p);
3455 return val;
3460 /***********************************************************************
3461 Symbol Allocation
3462 ***********************************************************************/
3464 /* Like struct Lisp_Symbol, but padded so that the size is a multiple
3465 of the required alignment if LSB tags are used. */
3467 union aligned_Lisp_Symbol
3469 struct Lisp_Symbol s;
3470 #if USE_LSB_TAG
3471 unsigned char c[(sizeof (struct Lisp_Symbol) + (1 << GCTYPEBITS) - 1)
3472 & -(1 << GCTYPEBITS)];
3473 #endif
3476 /* Each symbol_block is just under 1020 bytes long, since malloc
3477 really allocates in units of powers of two and uses 4 bytes for its
3478 own overhead. */
3480 #define SYMBOL_BLOCK_SIZE \
3481 ((1020 - sizeof (struct symbol_block *)) / sizeof (union aligned_Lisp_Symbol))
3483 struct symbol_block
3485 /* Place `symbols' first, to preserve alignment. */
3486 union aligned_Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3487 struct symbol_block *next;
3490 /* Current symbol block and index of first unused Lisp_Symbol
3491 structure in it. */
3493 static struct symbol_block *symbol_block;
3494 static int symbol_block_index = SYMBOL_BLOCK_SIZE;
3496 /* List of free symbols. */
3498 static struct Lisp_Symbol *symbol_free_list;
3500 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3501 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3502 Its value and function definition are void, and its property list is nil. */)
3503 (Lisp_Object name)
3505 register Lisp_Object val;
3506 register struct Lisp_Symbol *p;
3508 CHECK_STRING (name);
3510 /* eassert (!handling_signal); */
3512 MALLOC_BLOCK_INPUT;
3514 if (symbol_free_list)
3516 XSETSYMBOL (val, symbol_free_list);
3517 symbol_free_list = symbol_free_list->next;
3519 else
3521 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3523 struct symbol_block *new
3524 = lisp_malloc (sizeof *new, MEM_TYPE_SYMBOL);
3525 new->next = symbol_block;
3526 symbol_block = new;
3527 symbol_block_index = 0;
3528 total_free_symbols += SYMBOL_BLOCK_SIZE;
3530 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index].s);
3531 symbol_block_index++;
3534 MALLOC_UNBLOCK_INPUT;
3536 p = XSYMBOL (val);
3537 p->xname = name;
3538 p->plist = Qnil;
3539 p->redirect = SYMBOL_PLAINVAL;
3540 SET_SYMBOL_VAL (p, Qunbound);
3541 p->function = Qunbound;
3542 p->next = NULL;
3543 p->gcmarkbit = 0;
3544 p->interned = SYMBOL_UNINTERNED;
3545 p->constant = 0;
3546 p->declared_special = 0;
3547 consing_since_gc += sizeof (struct Lisp_Symbol);
3548 symbols_consed++;
3549 total_free_symbols--;
3550 return val;
3555 /***********************************************************************
3556 Marker (Misc) Allocation
3557 ***********************************************************************/
3559 /* Like union Lisp_Misc, but padded so that its size is a multiple of
3560 the required alignment when LSB tags are used. */
3562 union aligned_Lisp_Misc
3564 union Lisp_Misc m;
3565 #if USE_LSB_TAG
3566 unsigned char c[(sizeof (union Lisp_Misc) + (1 << GCTYPEBITS) - 1)
3567 & -(1 << GCTYPEBITS)];
3568 #endif
3571 /* Allocation of markers and other objects that share that structure.
3572 Works like allocation of conses. */
3574 #define MARKER_BLOCK_SIZE \
3575 ((1020 - sizeof (struct marker_block *)) / sizeof (union aligned_Lisp_Misc))
3577 struct marker_block
3579 /* Place `markers' first, to preserve alignment. */
3580 union aligned_Lisp_Misc markers[MARKER_BLOCK_SIZE];
3581 struct marker_block *next;
3584 static struct marker_block *marker_block;
3585 static int marker_block_index = MARKER_BLOCK_SIZE;
3587 static union Lisp_Misc *marker_free_list;
3589 /* Return a newly allocated Lisp_Misc object of specified TYPE. */
3591 static Lisp_Object
3592 allocate_misc (enum Lisp_Misc_Type type)
3594 Lisp_Object val;
3596 /* eassert (!handling_signal); */
3598 MALLOC_BLOCK_INPUT;
3600 if (marker_free_list)
3602 XSETMISC (val, marker_free_list);
3603 marker_free_list = marker_free_list->u_free.chain;
3605 else
3607 if (marker_block_index == MARKER_BLOCK_SIZE)
3609 struct marker_block *new = lisp_malloc (sizeof *new, MEM_TYPE_MISC);
3610 new->next = marker_block;
3611 marker_block = new;
3612 marker_block_index = 0;
3613 total_free_markers += MARKER_BLOCK_SIZE;
3615 XSETMISC (val, &marker_block->markers[marker_block_index].m);
3616 marker_block_index++;
3619 MALLOC_UNBLOCK_INPUT;
3621 --total_free_markers;
3622 consing_since_gc += sizeof (union Lisp_Misc);
3623 misc_objects_consed++;
3624 XMISCTYPE (val) = type;
3625 XMISCANY (val)->gcmarkbit = 0;
3626 return val;
3629 /* Free a Lisp_Misc object */
3631 static void
3632 free_misc (Lisp_Object misc)
3634 XMISCTYPE (misc) = Lisp_Misc_Free;
3635 XMISC (misc)->u_free.chain = marker_free_list;
3636 marker_free_list = XMISC (misc);
3637 consing_since_gc -= sizeof (union Lisp_Misc);
3638 total_free_markers++;
3641 /* Return a Lisp_Misc_Save_Value object containing POINTER and
3642 INTEGER. This is used to package C values to call record_unwind_protect.
3643 The unwind function can get the C values back using XSAVE_VALUE. */
3645 Lisp_Object
3646 make_save_value (void *pointer, ptrdiff_t integer)
3648 register Lisp_Object val;
3649 register struct Lisp_Save_Value *p;
3651 val = allocate_misc (Lisp_Misc_Save_Value);
3652 p = XSAVE_VALUE (val);
3653 p->pointer = pointer;
3654 p->integer = integer;
3655 p->dogc = 0;
3656 return val;
3659 /* Return a Lisp_Misc_Overlay object with specified START, END and PLIST. */
3661 Lisp_Object
3662 build_overlay (Lisp_Object start, Lisp_Object end, Lisp_Object plist)
3664 register Lisp_Object overlay;
3666 overlay = allocate_misc (Lisp_Misc_Overlay);
3667 OVERLAY_START (overlay) = start;
3668 OVERLAY_END (overlay) = end;
3669 OVERLAY_PLIST (overlay) = plist;
3670 XOVERLAY (overlay)->next = NULL;
3671 return overlay;
3674 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3675 doc: /* Return a newly allocated marker which does not point at any place. */)
3676 (void)
3678 register Lisp_Object val;
3679 register struct Lisp_Marker *p;
3681 val = allocate_misc (Lisp_Misc_Marker);
3682 p = XMARKER (val);
3683 p->buffer = 0;
3684 p->bytepos = 0;
3685 p->charpos = 0;
3686 p->next = NULL;
3687 p->insertion_type = 0;
3688 return val;
3691 /* Return a newly allocated marker which points into BUF
3692 at character position CHARPOS and byte position BYTEPOS. */
3694 Lisp_Object
3695 build_marker (struct buffer *buf, ptrdiff_t charpos, ptrdiff_t bytepos)
3697 Lisp_Object obj;
3698 struct Lisp_Marker *m;
3700 /* No dead buffers here. */
3701 eassert (!NILP (BVAR (buf, name)));
3703 /* Every character is at least one byte. */
3704 eassert (charpos <= bytepos);
3706 obj = allocate_misc (Lisp_Misc_Marker);
3707 m = XMARKER (obj);
3708 m->buffer = buf;
3709 m->charpos = charpos;
3710 m->bytepos = bytepos;
3711 m->insertion_type = 0;
3712 m->next = BUF_MARKERS (buf);
3713 BUF_MARKERS (buf) = m;
3714 return obj;
3717 /* Put MARKER back on the free list after using it temporarily. */
3719 void
3720 free_marker (Lisp_Object marker)
3722 unchain_marker (XMARKER (marker));
3723 free_misc (marker);
3727 /* Return a newly created vector or string with specified arguments as
3728 elements. If all the arguments are characters that can fit
3729 in a string of events, make a string; otherwise, make a vector.
3731 Any number of arguments, even zero arguments, are allowed. */
3733 Lisp_Object
3734 make_event_array (register int nargs, Lisp_Object *args)
3736 int i;
3738 for (i = 0; i < nargs; i++)
3739 /* The things that fit in a string
3740 are characters that are in 0...127,
3741 after discarding the meta bit and all the bits above it. */
3742 if (!INTEGERP (args[i])
3743 || (XINT (args[i]) & ~(-CHAR_META)) >= 0200)
3744 return Fvector (nargs, args);
3746 /* Since the loop exited, we know that all the things in it are
3747 characters, so we can make a string. */
3749 Lisp_Object result;
3751 result = Fmake_string (make_number (nargs), make_number (0));
3752 for (i = 0; i < nargs; i++)
3754 SSET (result, i, XINT (args[i]));
3755 /* Move the meta bit to the right place for a string char. */
3756 if (XINT (args[i]) & CHAR_META)
3757 SSET (result, i, SREF (result, i) | 0x80);
3760 return result;
3766 /************************************************************************
3767 Memory Full Handling
3768 ************************************************************************/
3771 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
3772 there may have been size_t overflow so that malloc was never
3773 called, or perhaps malloc was invoked successfully but the
3774 resulting pointer had problems fitting into a tagged EMACS_INT. In
3775 either case this counts as memory being full even though malloc did
3776 not fail. */
3778 void
3779 memory_full (size_t nbytes)
3781 /* Do not go into hysterics merely because a large request failed. */
3782 int enough_free_memory = 0;
3783 if (SPARE_MEMORY < nbytes)
3785 void *p;
3787 MALLOC_BLOCK_INPUT;
3788 p = malloc (SPARE_MEMORY);
3789 if (p)
3791 free (p);
3792 enough_free_memory = 1;
3794 MALLOC_UNBLOCK_INPUT;
3797 if (! enough_free_memory)
3799 int i;
3801 Vmemory_full = Qt;
3803 memory_full_cons_threshold = sizeof (struct cons_block);
3805 /* The first time we get here, free the spare memory. */
3806 for (i = 0; i < sizeof (spare_memory) / sizeof (char *); i++)
3807 if (spare_memory[i])
3809 if (i == 0)
3810 free (spare_memory[i]);
3811 else if (i >= 1 && i <= 4)
3812 lisp_align_free (spare_memory[i]);
3813 else
3814 lisp_free (spare_memory[i]);
3815 spare_memory[i] = 0;
3818 /* Record the space now used. When it decreases substantially,
3819 we can refill the memory reserve. */
3820 #if !defined SYSTEM_MALLOC && !defined SYNC_INPUT
3821 bytes_used_when_full = BYTES_USED;
3822 #endif
3825 /* This used to call error, but if we've run out of memory, we could
3826 get infinite recursion trying to build the string. */
3827 xsignal (Qnil, Vmemory_signal_data);
3830 /* If we released our reserve (due to running out of memory),
3831 and we have a fair amount free once again,
3832 try to set aside another reserve in case we run out once more.
3834 This is called when a relocatable block is freed in ralloc.c,
3835 and also directly from this file, in case we're not using ralloc.c. */
3837 void
3838 refill_memory_reserve (void)
3840 #ifndef SYSTEM_MALLOC
3841 if (spare_memory[0] == 0)
3842 spare_memory[0] = malloc (SPARE_MEMORY);
3843 if (spare_memory[1] == 0)
3844 spare_memory[1] = lisp_align_malloc (sizeof (struct cons_block),
3845 MEM_TYPE_CONS);
3846 if (spare_memory[2] == 0)
3847 spare_memory[2] = lisp_align_malloc (sizeof (struct cons_block),
3848 MEM_TYPE_CONS);
3849 if (spare_memory[3] == 0)
3850 spare_memory[3] = lisp_align_malloc (sizeof (struct cons_block),
3851 MEM_TYPE_CONS);
3852 if (spare_memory[4] == 0)
3853 spare_memory[4] = lisp_align_malloc (sizeof (struct cons_block),
3854 MEM_TYPE_CONS);
3855 if (spare_memory[5] == 0)
3856 spare_memory[5] = lisp_malloc (sizeof (struct string_block),
3857 MEM_TYPE_STRING);
3858 if (spare_memory[6] == 0)
3859 spare_memory[6] = lisp_malloc (sizeof (struct string_block),
3860 MEM_TYPE_STRING);
3861 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
3862 Vmemory_full = Qnil;
3863 #endif
3866 /************************************************************************
3867 C Stack Marking
3868 ************************************************************************/
3870 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
3872 /* Conservative C stack marking requires a method to identify possibly
3873 live Lisp objects given a pointer value. We do this by keeping
3874 track of blocks of Lisp data that are allocated in a red-black tree
3875 (see also the comment of mem_node which is the type of nodes in
3876 that tree). Function lisp_malloc adds information for an allocated
3877 block to the red-black tree with calls to mem_insert, and function
3878 lisp_free removes it with mem_delete. Functions live_string_p etc
3879 call mem_find to lookup information about a given pointer in the
3880 tree, and use that to determine if the pointer points to a Lisp
3881 object or not. */
3883 /* Initialize this part of alloc.c. */
3885 static void
3886 mem_init (void)
3888 mem_z.left = mem_z.right = MEM_NIL;
3889 mem_z.parent = NULL;
3890 mem_z.color = MEM_BLACK;
3891 mem_z.start = mem_z.end = NULL;
3892 mem_root = MEM_NIL;
3896 /* Value is a pointer to the mem_node containing START. Value is
3897 MEM_NIL if there is no node in the tree containing START. */
3899 static inline struct mem_node *
3900 mem_find (void *start)
3902 struct mem_node *p;
3904 if (start < min_heap_address || start > max_heap_address)
3905 return MEM_NIL;
3907 /* Make the search always successful to speed up the loop below. */
3908 mem_z.start = start;
3909 mem_z.end = (char *) start + 1;
3911 p = mem_root;
3912 while (start < p->start || start >= p->end)
3913 p = start < p->start ? p->left : p->right;
3914 return p;
3918 /* Insert a new node into the tree for a block of memory with start
3919 address START, end address END, and type TYPE. Value is a
3920 pointer to the node that was inserted. */
3922 static struct mem_node *
3923 mem_insert (void *start, void *end, enum mem_type type)
3925 struct mem_node *c, *parent, *x;
3927 if (min_heap_address == NULL || start < min_heap_address)
3928 min_heap_address = start;
3929 if (max_heap_address == NULL || end > max_heap_address)
3930 max_heap_address = end;
3932 /* See where in the tree a node for START belongs. In this
3933 particular application, it shouldn't happen that a node is already
3934 present. For debugging purposes, let's check that. */
3935 c = mem_root;
3936 parent = NULL;
3938 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
3940 while (c != MEM_NIL)
3942 if (start >= c->start && start < c->end)
3943 abort ();
3944 parent = c;
3945 c = start < c->start ? c->left : c->right;
3948 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3950 while (c != MEM_NIL)
3952 parent = c;
3953 c = start < c->start ? c->left : c->right;
3956 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3958 /* Create a new node. */
3959 #ifdef GC_MALLOC_CHECK
3960 x = _malloc_internal (sizeof *x);
3961 if (x == NULL)
3962 abort ();
3963 #else
3964 x = xmalloc (sizeof *x);
3965 #endif
3966 x->start = start;
3967 x->end = end;
3968 x->type = type;
3969 x->parent = parent;
3970 x->left = x->right = MEM_NIL;
3971 x->color = MEM_RED;
3973 /* Insert it as child of PARENT or install it as root. */
3974 if (parent)
3976 if (start < parent->start)
3977 parent->left = x;
3978 else
3979 parent->right = x;
3981 else
3982 mem_root = x;
3984 /* Re-establish red-black tree properties. */
3985 mem_insert_fixup (x);
3987 return x;
3991 /* Re-establish the red-black properties of the tree, and thereby
3992 balance the tree, after node X has been inserted; X is always red. */
3994 static void
3995 mem_insert_fixup (struct mem_node *x)
3997 while (x != mem_root && x->parent->color == MEM_RED)
3999 /* X is red and its parent is red. This is a violation of
4000 red-black tree property #3. */
4002 if (x->parent == x->parent->parent->left)
4004 /* We're on the left side of our grandparent, and Y is our
4005 "uncle". */
4006 struct mem_node *y = x->parent->parent->right;
4008 if (y->color == MEM_RED)
4010 /* Uncle and parent are red but should be black because
4011 X is red. Change the colors accordingly and proceed
4012 with the grandparent. */
4013 x->parent->color = MEM_BLACK;
4014 y->color = MEM_BLACK;
4015 x->parent->parent->color = MEM_RED;
4016 x = x->parent->parent;
4018 else
4020 /* Parent and uncle have different colors; parent is
4021 red, uncle is black. */
4022 if (x == x->parent->right)
4024 x = x->parent;
4025 mem_rotate_left (x);
4028 x->parent->color = MEM_BLACK;
4029 x->parent->parent->color = MEM_RED;
4030 mem_rotate_right (x->parent->parent);
4033 else
4035 /* This is the symmetrical case of above. */
4036 struct mem_node *y = x->parent->parent->left;
4038 if (y->color == MEM_RED)
4040 x->parent->color = MEM_BLACK;
4041 y->color = MEM_BLACK;
4042 x->parent->parent->color = MEM_RED;
4043 x = x->parent->parent;
4045 else
4047 if (x == x->parent->left)
4049 x = x->parent;
4050 mem_rotate_right (x);
4053 x->parent->color = MEM_BLACK;
4054 x->parent->parent->color = MEM_RED;
4055 mem_rotate_left (x->parent->parent);
4060 /* The root may have been changed to red due to the algorithm. Set
4061 it to black so that property #5 is satisfied. */
4062 mem_root->color = MEM_BLACK;
4066 /* (x) (y)
4067 / \ / \
4068 a (y) ===> (x) c
4069 / \ / \
4070 b c a b */
4072 static void
4073 mem_rotate_left (struct mem_node *x)
4075 struct mem_node *y;
4077 /* Turn y's left sub-tree into x's right sub-tree. */
4078 y = x->right;
4079 x->right = y->left;
4080 if (y->left != MEM_NIL)
4081 y->left->parent = x;
4083 /* Y's parent was x's parent. */
4084 if (y != MEM_NIL)
4085 y->parent = x->parent;
4087 /* Get the parent to point to y instead of x. */
4088 if (x->parent)
4090 if (x == x->parent->left)
4091 x->parent->left = y;
4092 else
4093 x->parent->right = y;
4095 else
4096 mem_root = y;
4098 /* Put x on y's left. */
4099 y->left = x;
4100 if (x != MEM_NIL)
4101 x->parent = y;
4105 /* (x) (Y)
4106 / \ / \
4107 (y) c ===> a (x)
4108 / \ / \
4109 a b b c */
4111 static void
4112 mem_rotate_right (struct mem_node *x)
4114 struct mem_node *y = x->left;
4116 x->left = y->right;
4117 if (y->right != MEM_NIL)
4118 y->right->parent = x;
4120 if (y != MEM_NIL)
4121 y->parent = x->parent;
4122 if (x->parent)
4124 if (x == x->parent->right)
4125 x->parent->right = y;
4126 else
4127 x->parent->left = y;
4129 else
4130 mem_root = y;
4132 y->right = x;
4133 if (x != MEM_NIL)
4134 x->parent = y;
4138 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
4140 static void
4141 mem_delete (struct mem_node *z)
4143 struct mem_node *x, *y;
4145 if (!z || z == MEM_NIL)
4146 return;
4148 if (z->left == MEM_NIL || z->right == MEM_NIL)
4149 y = z;
4150 else
4152 y = z->right;
4153 while (y->left != MEM_NIL)
4154 y = y->left;
4157 if (y->left != MEM_NIL)
4158 x = y->left;
4159 else
4160 x = y->right;
4162 x->parent = y->parent;
4163 if (y->parent)
4165 if (y == y->parent->left)
4166 y->parent->left = x;
4167 else
4168 y->parent->right = x;
4170 else
4171 mem_root = x;
4173 if (y != z)
4175 z->start = y->start;
4176 z->end = y->end;
4177 z->type = y->type;
4180 if (y->color == MEM_BLACK)
4181 mem_delete_fixup (x);
4183 #ifdef GC_MALLOC_CHECK
4184 _free_internal (y);
4185 #else
4186 xfree (y);
4187 #endif
4191 /* Re-establish the red-black properties of the tree, after a
4192 deletion. */
4194 static void
4195 mem_delete_fixup (struct mem_node *x)
4197 while (x != mem_root && x->color == MEM_BLACK)
4199 if (x == x->parent->left)
4201 struct mem_node *w = x->parent->right;
4203 if (w->color == MEM_RED)
4205 w->color = MEM_BLACK;
4206 x->parent->color = MEM_RED;
4207 mem_rotate_left (x->parent);
4208 w = x->parent->right;
4211 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
4213 w->color = MEM_RED;
4214 x = x->parent;
4216 else
4218 if (w->right->color == MEM_BLACK)
4220 w->left->color = MEM_BLACK;
4221 w->color = MEM_RED;
4222 mem_rotate_right (w);
4223 w = x->parent->right;
4225 w->color = x->parent->color;
4226 x->parent->color = MEM_BLACK;
4227 w->right->color = MEM_BLACK;
4228 mem_rotate_left (x->parent);
4229 x = mem_root;
4232 else
4234 struct mem_node *w = x->parent->left;
4236 if (w->color == MEM_RED)
4238 w->color = MEM_BLACK;
4239 x->parent->color = MEM_RED;
4240 mem_rotate_right (x->parent);
4241 w = x->parent->left;
4244 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
4246 w->color = MEM_RED;
4247 x = x->parent;
4249 else
4251 if (w->left->color == MEM_BLACK)
4253 w->right->color = MEM_BLACK;
4254 w->color = MEM_RED;
4255 mem_rotate_left (w);
4256 w = x->parent->left;
4259 w->color = x->parent->color;
4260 x->parent->color = MEM_BLACK;
4261 w->left->color = MEM_BLACK;
4262 mem_rotate_right (x->parent);
4263 x = mem_root;
4268 x->color = MEM_BLACK;
4272 /* Value is non-zero if P is a pointer to a live Lisp string on
4273 the heap. M is a pointer to the mem_block for P. */
4275 static inline int
4276 live_string_p (struct mem_node *m, void *p)
4278 if (m->type == MEM_TYPE_STRING)
4280 struct string_block *b = (struct string_block *) m->start;
4281 ptrdiff_t offset = (char *) p - (char *) &b->strings[0];
4283 /* P must point to the start of a Lisp_String structure, and it
4284 must not be on the free-list. */
4285 return (offset >= 0
4286 && offset % sizeof b->strings[0] == 0
4287 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
4288 && ((struct Lisp_String *) p)->data != NULL);
4290 else
4291 return 0;
4295 /* Value is non-zero if P is a pointer to a live Lisp cons on
4296 the heap. M is a pointer to the mem_block for P. */
4298 static inline int
4299 live_cons_p (struct mem_node *m, void *p)
4301 if (m->type == MEM_TYPE_CONS)
4303 struct cons_block *b = (struct cons_block *) m->start;
4304 ptrdiff_t offset = (char *) p - (char *) &b->conses[0];
4306 /* P must point to the start of a Lisp_Cons, not be
4307 one of the unused cells in the current cons block,
4308 and not be on the free-list. */
4309 return (offset >= 0
4310 && offset % sizeof b->conses[0] == 0
4311 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
4312 && (b != cons_block
4313 || offset / sizeof b->conses[0] < cons_block_index)
4314 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
4316 else
4317 return 0;
4321 /* Value is non-zero if P is a pointer to a live Lisp symbol on
4322 the heap. M is a pointer to the mem_block for P. */
4324 static inline int
4325 live_symbol_p (struct mem_node *m, void *p)
4327 if (m->type == MEM_TYPE_SYMBOL)
4329 struct symbol_block *b = (struct symbol_block *) m->start;
4330 ptrdiff_t offset = (char *) p - (char *) &b->symbols[0];
4332 /* P must point to the start of a Lisp_Symbol, not be
4333 one of the unused cells in the current symbol block,
4334 and not be on the free-list. */
4335 return (offset >= 0
4336 && offset % sizeof b->symbols[0] == 0
4337 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
4338 && (b != symbol_block
4339 || offset / sizeof b->symbols[0] < symbol_block_index)
4340 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
4342 else
4343 return 0;
4347 /* Value is non-zero if P is a pointer to a live Lisp float on
4348 the heap. M is a pointer to the mem_block for P. */
4350 static inline int
4351 live_float_p (struct mem_node *m, void *p)
4353 if (m->type == MEM_TYPE_FLOAT)
4355 struct float_block *b = (struct float_block *) m->start;
4356 ptrdiff_t offset = (char *) p - (char *) &b->floats[0];
4358 /* P must point to the start of a Lisp_Float and not be
4359 one of the unused cells in the current float block. */
4360 return (offset >= 0
4361 && offset % sizeof b->floats[0] == 0
4362 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
4363 && (b != float_block
4364 || offset / sizeof b->floats[0] < float_block_index));
4366 else
4367 return 0;
4371 /* Value is non-zero if P is a pointer to a live Lisp Misc on
4372 the heap. M is a pointer to the mem_block for P. */
4374 static inline int
4375 live_misc_p (struct mem_node *m, void *p)
4377 if (m->type == MEM_TYPE_MISC)
4379 struct marker_block *b = (struct marker_block *) m->start;
4380 ptrdiff_t offset = (char *) p - (char *) &b->markers[0];
4382 /* P must point to the start of a Lisp_Misc, not be
4383 one of the unused cells in the current misc block,
4384 and not be on the free-list. */
4385 return (offset >= 0
4386 && offset % sizeof b->markers[0] == 0
4387 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
4388 && (b != marker_block
4389 || offset / sizeof b->markers[0] < marker_block_index)
4390 && ((union Lisp_Misc *) p)->u_any.type != Lisp_Misc_Free);
4392 else
4393 return 0;
4397 /* Value is non-zero if P is a pointer to a live vector-like object.
4398 M is a pointer to the mem_block for P. */
4400 static inline int
4401 live_vector_p (struct mem_node *m, void *p)
4403 if (m->type == MEM_TYPE_VECTOR_BLOCK)
4405 /* This memory node corresponds to a vector block. */
4406 struct vector_block *block = (struct vector_block *) m->start;
4407 struct Lisp_Vector *vector = (struct Lisp_Vector *) block->data;
4409 /* P is in the block's allocation range. Scan the block
4410 up to P and see whether P points to the start of some
4411 vector which is not on a free list. FIXME: check whether
4412 some allocation patterns (probably a lot of short vectors)
4413 may cause a substantial overhead of this loop. */
4414 while (VECTOR_IN_BLOCK (vector, block)
4415 && vector <= (struct Lisp_Vector *) p)
4417 if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FREE))
4418 vector = ADVANCE (vector, (vector->header.size
4419 & PSEUDOVECTOR_SIZE_MASK));
4420 else if (vector == p)
4421 return 1;
4422 else
4423 vector = ADVANCE (vector, vector->header.next.nbytes);
4426 else if (m->type == MEM_TYPE_VECTORLIKE && p == m->start)
4427 /* This memory node corresponds to a large vector. */
4428 return 1;
4429 return 0;
4433 /* Value is non-zero if P is a pointer to a live buffer. M is a
4434 pointer to the mem_block for P. */
4436 static inline int
4437 live_buffer_p (struct mem_node *m, void *p)
4439 /* P must point to the start of the block, and the buffer
4440 must not have been killed. */
4441 return (m->type == MEM_TYPE_BUFFER
4442 && p == m->start
4443 && !NILP (((struct buffer *) p)->BUFFER_INTERNAL_FIELD (name)));
4446 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
4448 #if GC_MARK_STACK
4450 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4452 /* Array of objects that are kept alive because the C stack contains
4453 a pattern that looks like a reference to them . */
4455 #define MAX_ZOMBIES 10
4456 static Lisp_Object zombies[MAX_ZOMBIES];
4458 /* Number of zombie objects. */
4460 static EMACS_INT nzombies;
4462 /* Number of garbage collections. */
4464 static EMACS_INT ngcs;
4466 /* Average percentage of zombies per collection. */
4468 static double avg_zombies;
4470 /* Max. number of live and zombie objects. */
4472 static EMACS_INT max_live, max_zombies;
4474 /* Average number of live objects per GC. */
4476 static double avg_live;
4478 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
4479 doc: /* Show information about live and zombie objects. */)
4480 (void)
4482 Lisp_Object args[8], zombie_list = Qnil;
4483 EMACS_INT i;
4484 for (i = 0; i < min (MAX_ZOMBIES, nzombies); i++)
4485 zombie_list = Fcons (zombies[i], zombie_list);
4486 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
4487 args[1] = make_number (ngcs);
4488 args[2] = make_float (avg_live);
4489 args[3] = make_float (avg_zombies);
4490 args[4] = make_float (avg_zombies / avg_live / 100);
4491 args[5] = make_number (max_live);
4492 args[6] = make_number (max_zombies);
4493 args[7] = zombie_list;
4494 return Fmessage (8, args);
4497 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4500 /* Mark OBJ if we can prove it's a Lisp_Object. */
4502 static inline void
4503 mark_maybe_object (Lisp_Object obj)
4505 void *po;
4506 struct mem_node *m;
4508 if (INTEGERP (obj))
4509 return;
4511 po = (void *) XPNTR (obj);
4512 m = mem_find (po);
4514 if (m != MEM_NIL)
4516 int mark_p = 0;
4518 switch (XTYPE (obj))
4520 case Lisp_String:
4521 mark_p = (live_string_p (m, po)
4522 && !STRING_MARKED_P ((struct Lisp_String *) po));
4523 break;
4525 case Lisp_Cons:
4526 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4527 break;
4529 case Lisp_Symbol:
4530 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4531 break;
4533 case Lisp_Float:
4534 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4535 break;
4537 case Lisp_Vectorlike:
4538 /* Note: can't check BUFFERP before we know it's a
4539 buffer because checking that dereferences the pointer
4540 PO which might point anywhere. */
4541 if (live_vector_p (m, po))
4542 mark_p = !SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4543 else if (live_buffer_p (m, po))
4544 mark_p = BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4545 break;
4547 case Lisp_Misc:
4548 mark_p = (live_misc_p (m, po) && !XMISCANY (obj)->gcmarkbit);
4549 break;
4551 default:
4552 break;
4555 if (mark_p)
4557 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4558 if (nzombies < MAX_ZOMBIES)
4559 zombies[nzombies] = obj;
4560 ++nzombies;
4561 #endif
4562 mark_object (obj);
4568 /* If P points to Lisp data, mark that as live if it isn't already
4569 marked. */
4571 static inline void
4572 mark_maybe_pointer (void *p)
4574 struct mem_node *m;
4576 /* Quickly rule out some values which can't point to Lisp data.
4577 USE_LSB_TAG needs Lisp data to be aligned on multiples of 1 << GCTYPEBITS.
4578 Otherwise, assume that Lisp data is aligned on even addresses. */
4579 if ((intptr_t) p % (USE_LSB_TAG ? 1 << GCTYPEBITS : 2))
4580 return;
4582 m = mem_find (p);
4583 if (m != MEM_NIL)
4585 Lisp_Object obj = Qnil;
4587 switch (m->type)
4589 case MEM_TYPE_NON_LISP:
4590 /* Nothing to do; not a pointer to Lisp memory. */
4591 break;
4593 case MEM_TYPE_BUFFER:
4594 if (live_buffer_p (m, p) && !VECTOR_MARKED_P ((struct buffer *)p))
4595 XSETVECTOR (obj, p);
4596 break;
4598 case MEM_TYPE_CONS:
4599 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4600 XSETCONS (obj, p);
4601 break;
4603 case MEM_TYPE_STRING:
4604 if (live_string_p (m, p)
4605 && !STRING_MARKED_P ((struct Lisp_String *) p))
4606 XSETSTRING (obj, p);
4607 break;
4609 case MEM_TYPE_MISC:
4610 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4611 XSETMISC (obj, p);
4612 break;
4614 case MEM_TYPE_SYMBOL:
4615 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4616 XSETSYMBOL (obj, p);
4617 break;
4619 case MEM_TYPE_FLOAT:
4620 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4621 XSETFLOAT (obj, p);
4622 break;
4624 case MEM_TYPE_VECTORLIKE:
4625 case MEM_TYPE_VECTOR_BLOCK:
4626 if (live_vector_p (m, p))
4628 Lisp_Object tem;
4629 XSETVECTOR (tem, p);
4630 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4631 obj = tem;
4633 break;
4635 default:
4636 abort ();
4639 if (!NILP (obj))
4640 mark_object (obj);
4645 /* Alignment of pointer values. Use alignof, as it sometimes returns
4646 a smaller alignment than GCC's __alignof__ and mark_memory might
4647 miss objects if __alignof__ were used. */
4648 #define GC_POINTER_ALIGNMENT alignof (void *)
4650 /* Define POINTERS_MIGHT_HIDE_IN_OBJECTS to 1 if marking via C pointers does
4651 not suffice, which is the typical case. A host where a Lisp_Object is
4652 wider than a pointer might allocate a Lisp_Object in non-adjacent halves.
4653 If USE_LSB_TAG, the bottom half is not a valid pointer, but it should
4654 suffice to widen it to to a Lisp_Object and check it that way. */
4655 #if USE_LSB_TAG || VAL_MAX < UINTPTR_MAX
4656 # if !USE_LSB_TAG && VAL_MAX < UINTPTR_MAX >> GCTYPEBITS
4657 /* If tag bits straddle pointer-word boundaries, neither mark_maybe_pointer
4658 nor mark_maybe_object can follow the pointers. This should not occur on
4659 any practical porting target. */
4660 # error "MSB type bits straddle pointer-word boundaries"
4661 # endif
4662 /* Marking via C pointers does not suffice, because Lisp_Objects contain
4663 pointer words that hold pointers ORed with type bits. */
4664 # define POINTERS_MIGHT_HIDE_IN_OBJECTS 1
4665 #else
4666 /* Marking via C pointers suffices, because Lisp_Objects contain pointer
4667 words that hold unmodified pointers. */
4668 # define POINTERS_MIGHT_HIDE_IN_OBJECTS 0
4669 #endif
4671 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4672 or END+OFFSET..START. */
4674 static void
4675 mark_memory (void *start, void *end)
4676 #if defined (__clang__) && defined (__has_feature)
4677 #if __has_feature(address_sanitizer)
4678 /* Do not allow -faddress-sanitizer to check this function, since it
4679 crosses the function stack boundary, and thus would yield many
4680 false positives. */
4681 __attribute__((no_address_safety_analysis))
4682 #endif
4683 #endif
4685 void **pp;
4686 int i;
4688 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4689 nzombies = 0;
4690 #endif
4692 /* Make START the pointer to the start of the memory region,
4693 if it isn't already. */
4694 if (end < start)
4696 void *tem = start;
4697 start = end;
4698 end = tem;
4701 /* Mark Lisp data pointed to. This is necessary because, in some
4702 situations, the C compiler optimizes Lisp objects away, so that
4703 only a pointer to them remains. Example:
4705 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4708 Lisp_Object obj = build_string ("test");
4709 struct Lisp_String *s = XSTRING (obj);
4710 Fgarbage_collect ();
4711 fprintf (stderr, "test `%s'\n", s->data);
4712 return Qnil;
4715 Here, `obj' isn't really used, and the compiler optimizes it
4716 away. The only reference to the life string is through the
4717 pointer `s'. */
4719 for (pp = start; (void *) pp < end; pp++)
4720 for (i = 0; i < sizeof *pp; i += GC_POINTER_ALIGNMENT)
4722 void *p = *(void **) ((char *) pp + i);
4723 mark_maybe_pointer (p);
4724 if (POINTERS_MIGHT_HIDE_IN_OBJECTS)
4725 mark_maybe_object (XIL ((intptr_t) p));
4729 /* setjmp will work with GCC unless NON_SAVING_SETJMP is defined in
4730 the GCC system configuration. In gcc 3.2, the only systems for
4731 which this is so are i386-sco5 non-ELF, i386-sysv3 (maybe included
4732 by others?) and ns32k-pc532-min. */
4734 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4736 static int setjmp_tested_p, longjmps_done;
4738 #define SETJMP_WILL_LIKELY_WORK "\
4740 Emacs garbage collector has been changed to use conservative stack\n\
4741 marking. Emacs has determined that the method it uses to do the\n\
4742 marking will likely work on your system, but this isn't sure.\n\
4744 If you are a system-programmer, or can get the help of a local wizard\n\
4745 who is, please take a look at the function mark_stack in alloc.c, and\n\
4746 verify that the methods used are appropriate for your system.\n\
4748 Please mail the result to <emacs-devel@gnu.org>.\n\
4751 #define SETJMP_WILL_NOT_WORK "\
4753 Emacs garbage collector has been changed to use conservative stack\n\
4754 marking. Emacs has determined that the default method it uses to do the\n\
4755 marking will not work on your system. We will need a system-dependent\n\
4756 solution for your system.\n\
4758 Please take a look at the function mark_stack in alloc.c, and\n\
4759 try to find a way to make it work on your system.\n\
4761 Note that you may get false negatives, depending on the compiler.\n\
4762 In particular, you need to use -O with GCC for this test.\n\
4764 Please mail the result to <emacs-devel@gnu.org>.\n\
4768 /* Perform a quick check if it looks like setjmp saves registers in a
4769 jmp_buf. Print a message to stderr saying so. When this test
4770 succeeds, this is _not_ a proof that setjmp is sufficient for
4771 conservative stack marking. Only the sources or a disassembly
4772 can prove that. */
4774 static void
4775 test_setjmp (void)
4777 char buf[10];
4778 register int x;
4779 jmp_buf jbuf;
4780 int result = 0;
4782 /* Arrange for X to be put in a register. */
4783 sprintf (buf, "1");
4784 x = strlen (buf);
4785 x = 2 * x - 1;
4787 setjmp (jbuf);
4788 if (longjmps_done == 1)
4790 /* Came here after the longjmp at the end of the function.
4792 If x == 1, the longjmp has restored the register to its
4793 value before the setjmp, and we can hope that setjmp
4794 saves all such registers in the jmp_buf, although that
4795 isn't sure.
4797 For other values of X, either something really strange is
4798 taking place, or the setjmp just didn't save the register. */
4800 if (x == 1)
4801 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4802 else
4804 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4805 exit (1);
4809 ++longjmps_done;
4810 x = 2;
4811 if (longjmps_done == 1)
4812 longjmp (jbuf, 1);
4815 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4818 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4820 /* Abort if anything GCPRO'd doesn't survive the GC. */
4822 static void
4823 check_gcpros (void)
4825 struct gcpro *p;
4826 ptrdiff_t i;
4828 for (p = gcprolist; p; p = p->next)
4829 for (i = 0; i < p->nvars; ++i)
4830 if (!survives_gc_p (p->var[i]))
4831 /* FIXME: It's not necessarily a bug. It might just be that the
4832 GCPRO is unnecessary or should release the object sooner. */
4833 abort ();
4836 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4838 static void
4839 dump_zombies (void)
4841 int i;
4843 fprintf (stderr, "\nZombies kept alive = %"pI"d:\n", nzombies);
4844 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
4846 fprintf (stderr, " %d = ", i);
4847 debug_print (zombies[i]);
4851 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4854 /* Mark live Lisp objects on the C stack.
4856 There are several system-dependent problems to consider when
4857 porting this to new architectures:
4859 Processor Registers
4861 We have to mark Lisp objects in CPU registers that can hold local
4862 variables or are used to pass parameters.
4864 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4865 something that either saves relevant registers on the stack, or
4866 calls mark_maybe_object passing it each register's contents.
4868 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4869 implementation assumes that calling setjmp saves registers we need
4870 to see in a jmp_buf which itself lies on the stack. This doesn't
4871 have to be true! It must be verified for each system, possibly
4872 by taking a look at the source code of setjmp.
4874 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4875 can use it as a machine independent method to store all registers
4876 to the stack. In this case the macros described in the previous
4877 two paragraphs are not used.
4879 Stack Layout
4881 Architectures differ in the way their processor stack is organized.
4882 For example, the stack might look like this
4884 +----------------+
4885 | Lisp_Object | size = 4
4886 +----------------+
4887 | something else | size = 2
4888 +----------------+
4889 | Lisp_Object | size = 4
4890 +----------------+
4891 | ... |
4893 In such a case, not every Lisp_Object will be aligned equally. To
4894 find all Lisp_Object on the stack it won't be sufficient to walk
4895 the stack in steps of 4 bytes. Instead, two passes will be
4896 necessary, one starting at the start of the stack, and a second
4897 pass starting at the start of the stack + 2. Likewise, if the
4898 minimal alignment of Lisp_Objects on the stack is 1, four passes
4899 would be necessary, each one starting with one byte more offset
4900 from the stack start. */
4902 static void
4903 mark_stack (void)
4905 void *end;
4907 #ifdef HAVE___BUILTIN_UNWIND_INIT
4908 /* Force callee-saved registers and register windows onto the stack.
4909 This is the preferred method if available, obviating the need for
4910 machine dependent methods. */
4911 __builtin_unwind_init ();
4912 end = &end;
4913 #else /* not HAVE___BUILTIN_UNWIND_INIT */
4914 #ifndef GC_SAVE_REGISTERS_ON_STACK
4915 /* jmp_buf may not be aligned enough on darwin-ppc64 */
4916 union aligned_jmpbuf {
4917 Lisp_Object o;
4918 jmp_buf j;
4919 } j;
4920 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
4921 #endif
4922 /* This trick flushes the register windows so that all the state of
4923 the process is contained in the stack. */
4924 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
4925 needed on ia64 too. See mach_dep.c, where it also says inline
4926 assembler doesn't work with relevant proprietary compilers. */
4927 #ifdef __sparc__
4928 #if defined (__sparc64__) && defined (__FreeBSD__)
4929 /* FreeBSD does not have a ta 3 handler. */
4930 asm ("flushw");
4931 #else
4932 asm ("ta 3");
4933 #endif
4934 #endif
4936 /* Save registers that we need to see on the stack. We need to see
4937 registers used to hold register variables and registers used to
4938 pass parameters. */
4939 #ifdef GC_SAVE_REGISTERS_ON_STACK
4940 GC_SAVE_REGISTERS_ON_STACK (end);
4941 #else /* not GC_SAVE_REGISTERS_ON_STACK */
4943 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
4944 setjmp will definitely work, test it
4945 and print a message with the result
4946 of the test. */
4947 if (!setjmp_tested_p)
4949 setjmp_tested_p = 1;
4950 test_setjmp ();
4952 #endif /* GC_SETJMP_WORKS */
4954 setjmp (j.j);
4955 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
4956 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
4957 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
4959 /* This assumes that the stack is a contiguous region in memory. If
4960 that's not the case, something has to be done here to iterate
4961 over the stack segments. */
4962 mark_memory (stack_base, end);
4964 /* Allow for marking a secondary stack, like the register stack on the
4965 ia64. */
4966 #ifdef GC_MARK_SECONDARY_STACK
4967 GC_MARK_SECONDARY_STACK ();
4968 #endif
4970 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4971 check_gcpros ();
4972 #endif
4975 #endif /* GC_MARK_STACK != 0 */
4978 /* Determine whether it is safe to access memory at address P. */
4979 static int
4980 valid_pointer_p (void *p)
4982 #ifdef WINDOWSNT
4983 return w32_valid_pointer_p (p, 16);
4984 #else
4985 int fd[2];
4987 /* Obviously, we cannot just access it (we would SEGV trying), so we
4988 trick the o/s to tell us whether p is a valid pointer.
4989 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4990 not validate p in that case. */
4992 if (pipe (fd) == 0)
4994 int valid = (emacs_write (fd[1], (char *) p, 16) == 16);
4995 emacs_close (fd[1]);
4996 emacs_close (fd[0]);
4997 return valid;
5000 return -1;
5001 #endif
5004 /* Return 1 if OBJ is a valid lisp object.
5005 Return 0 if OBJ is NOT a valid lisp object.
5006 Return -1 if we cannot validate OBJ.
5007 This function can be quite slow,
5008 so it should only be used in code for manual debugging. */
5011 valid_lisp_object_p (Lisp_Object obj)
5013 void *p;
5014 #if GC_MARK_STACK
5015 struct mem_node *m;
5016 #endif
5018 if (INTEGERP (obj))
5019 return 1;
5021 p = (void *) XPNTR (obj);
5022 if (PURE_POINTER_P (p))
5023 return 1;
5025 #if !GC_MARK_STACK
5026 return valid_pointer_p (p);
5027 #else
5029 m = mem_find (p);
5031 if (m == MEM_NIL)
5033 int valid = valid_pointer_p (p);
5034 if (valid <= 0)
5035 return valid;
5037 if (SUBRP (obj))
5038 return 1;
5040 return 0;
5043 switch (m->type)
5045 case MEM_TYPE_NON_LISP:
5046 return 0;
5048 case MEM_TYPE_BUFFER:
5049 return live_buffer_p (m, p);
5051 case MEM_TYPE_CONS:
5052 return live_cons_p (m, p);
5054 case MEM_TYPE_STRING:
5055 return live_string_p (m, p);
5057 case MEM_TYPE_MISC:
5058 return live_misc_p (m, p);
5060 case MEM_TYPE_SYMBOL:
5061 return live_symbol_p (m, p);
5063 case MEM_TYPE_FLOAT:
5064 return live_float_p (m, p);
5066 case MEM_TYPE_VECTORLIKE:
5067 case MEM_TYPE_VECTOR_BLOCK:
5068 return live_vector_p (m, p);
5070 default:
5071 break;
5074 return 0;
5075 #endif
5081 /***********************************************************************
5082 Pure Storage Management
5083 ***********************************************************************/
5085 /* Allocate room for SIZE bytes from pure Lisp storage and return a
5086 pointer to it. TYPE is the Lisp type for which the memory is
5087 allocated. TYPE < 0 means it's not used for a Lisp object. */
5089 static void *
5090 pure_alloc (size_t size, int type)
5092 void *result;
5093 #if USE_LSB_TAG
5094 size_t alignment = (1 << GCTYPEBITS);
5095 #else
5096 size_t alignment = alignof (EMACS_INT);
5098 /* Give Lisp_Floats an extra alignment. */
5099 if (type == Lisp_Float)
5100 alignment = alignof (struct Lisp_Float);
5101 #endif
5103 again:
5104 if (type >= 0)
5106 /* Allocate space for a Lisp object from the beginning of the free
5107 space with taking account of alignment. */
5108 result = ALIGN (purebeg + pure_bytes_used_lisp, alignment);
5109 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
5111 else
5113 /* Allocate space for a non-Lisp object from the end of the free
5114 space. */
5115 pure_bytes_used_non_lisp += size;
5116 result = purebeg + pure_size - pure_bytes_used_non_lisp;
5118 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
5120 if (pure_bytes_used <= pure_size)
5121 return result;
5123 /* Don't allocate a large amount here,
5124 because it might get mmap'd and then its address
5125 might not be usable. */
5126 purebeg = xmalloc (10000);
5127 pure_size = 10000;
5128 pure_bytes_used_before_overflow += pure_bytes_used - size;
5129 pure_bytes_used = 0;
5130 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
5131 goto again;
5135 /* Print a warning if PURESIZE is too small. */
5137 void
5138 check_pure_size (void)
5140 if (pure_bytes_used_before_overflow)
5141 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI"d"
5142 " bytes needed)"),
5143 pure_bytes_used + pure_bytes_used_before_overflow);
5147 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
5148 the non-Lisp data pool of the pure storage, and return its start
5149 address. Return NULL if not found. */
5151 static char *
5152 find_string_data_in_pure (const char *data, ptrdiff_t nbytes)
5154 int i;
5155 ptrdiff_t skip, bm_skip[256], last_char_skip, infinity, start, start_max;
5156 const unsigned char *p;
5157 char *non_lisp_beg;
5159 if (pure_bytes_used_non_lisp <= nbytes)
5160 return NULL;
5162 /* Set up the Boyer-Moore table. */
5163 skip = nbytes + 1;
5164 for (i = 0; i < 256; i++)
5165 bm_skip[i] = skip;
5167 p = (const unsigned char *) data;
5168 while (--skip > 0)
5169 bm_skip[*p++] = skip;
5171 last_char_skip = bm_skip['\0'];
5173 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
5174 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
5176 /* See the comments in the function `boyer_moore' (search.c) for the
5177 use of `infinity'. */
5178 infinity = pure_bytes_used_non_lisp + 1;
5179 bm_skip['\0'] = infinity;
5181 p = (const unsigned char *) non_lisp_beg + nbytes;
5182 start = 0;
5185 /* Check the last character (== '\0'). */
5188 start += bm_skip[*(p + start)];
5190 while (start <= start_max);
5192 if (start < infinity)
5193 /* Couldn't find the last character. */
5194 return NULL;
5196 /* No less than `infinity' means we could find the last
5197 character at `p[start - infinity]'. */
5198 start -= infinity;
5200 /* Check the remaining characters. */
5201 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
5202 /* Found. */
5203 return non_lisp_beg + start;
5205 start += last_char_skip;
5207 while (start <= start_max);
5209 return NULL;
5213 /* Return a string allocated in pure space. DATA is a buffer holding
5214 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
5215 non-zero means make the result string multibyte.
5217 Must get an error if pure storage is full, since if it cannot hold
5218 a large string it may be able to hold conses that point to that
5219 string; then the string is not protected from gc. */
5221 Lisp_Object
5222 make_pure_string (const char *data,
5223 ptrdiff_t nchars, ptrdiff_t nbytes, int multibyte)
5225 Lisp_Object string;
5226 struct Lisp_String *s;
5228 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
5229 s->data = (unsigned char *) find_string_data_in_pure (data, nbytes);
5230 if (s->data == NULL)
5232 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
5233 memcpy (s->data, data, nbytes);
5234 s->data[nbytes] = '\0';
5236 s->size = nchars;
5237 s->size_byte = multibyte ? nbytes : -1;
5238 s->intervals = NULL_INTERVAL;
5239 XSETSTRING (string, s);
5240 return string;
5243 /* Return a string allocated in pure space. Do not
5244 allocate the string data, just point to DATA. */
5246 Lisp_Object
5247 make_pure_c_string (const char *data, ptrdiff_t nchars)
5249 Lisp_Object string;
5250 struct Lisp_String *s;
5252 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
5253 s->size = nchars;
5254 s->size_byte = -1;
5255 s->data = (unsigned char *) data;
5256 s->intervals = NULL_INTERVAL;
5257 XSETSTRING (string, s);
5258 return string;
5261 /* Return a cons allocated from pure space. Give it pure copies
5262 of CAR as car and CDR as cdr. */
5264 Lisp_Object
5265 pure_cons (Lisp_Object car, Lisp_Object cdr)
5267 register Lisp_Object new;
5268 struct Lisp_Cons *p;
5270 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
5271 XSETCONS (new, p);
5272 XSETCAR (new, Fpurecopy (car));
5273 XSETCDR (new, Fpurecopy (cdr));
5274 return new;
5278 /* Value is a float object with value NUM allocated from pure space. */
5280 static Lisp_Object
5281 make_pure_float (double num)
5283 register Lisp_Object new;
5284 struct Lisp_Float *p;
5286 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
5287 XSETFLOAT (new, p);
5288 XFLOAT_INIT (new, num);
5289 return new;
5293 /* Return a vector with room for LEN Lisp_Objects allocated from
5294 pure space. */
5296 static Lisp_Object
5297 make_pure_vector (ptrdiff_t len)
5299 Lisp_Object new;
5300 struct Lisp_Vector *p;
5301 size_t size = header_size + len * word_size;
5303 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
5304 XSETVECTOR (new, p);
5305 XVECTOR (new)->header.size = len;
5306 return new;
5310 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
5311 doc: /* Make a copy of object OBJ in pure storage.
5312 Recursively copies contents of vectors and cons cells.
5313 Does not copy symbols. Copies strings without text properties. */)
5314 (register Lisp_Object obj)
5316 if (NILP (Vpurify_flag))
5317 return obj;
5319 if (PURE_POINTER_P (XPNTR (obj)))
5320 return obj;
5322 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5324 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
5325 if (!NILP (tmp))
5326 return tmp;
5329 if (CONSP (obj))
5330 obj = pure_cons (XCAR (obj), XCDR (obj));
5331 else if (FLOATP (obj))
5332 obj = make_pure_float (XFLOAT_DATA (obj));
5333 else if (STRINGP (obj))
5334 obj = make_pure_string (SSDATA (obj), SCHARS (obj),
5335 SBYTES (obj),
5336 STRING_MULTIBYTE (obj));
5337 else if (COMPILEDP (obj) || VECTORP (obj))
5339 register struct Lisp_Vector *vec;
5340 register ptrdiff_t i;
5341 ptrdiff_t size;
5343 size = ASIZE (obj);
5344 if (size & PSEUDOVECTOR_FLAG)
5345 size &= PSEUDOVECTOR_SIZE_MASK;
5346 vec = XVECTOR (make_pure_vector (size));
5347 for (i = 0; i < size; i++)
5348 vec->contents[i] = Fpurecopy (AREF (obj, i));
5349 if (COMPILEDP (obj))
5351 XSETPVECTYPE (vec, PVEC_COMPILED);
5352 XSETCOMPILED (obj, vec);
5354 else
5355 XSETVECTOR (obj, vec);
5357 else if (MARKERP (obj))
5358 error ("Attempt to copy a marker to pure storage");
5359 else
5360 /* Not purified, don't hash-cons. */
5361 return obj;
5363 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5364 Fputhash (obj, obj, Vpurify_flag);
5366 return obj;
5371 /***********************************************************************
5372 Protection from GC
5373 ***********************************************************************/
5375 /* Put an entry in staticvec, pointing at the variable with address
5376 VARADDRESS. */
5378 void
5379 staticpro (Lisp_Object *varaddress)
5381 staticvec[staticidx++] = varaddress;
5382 if (staticidx >= NSTATICS)
5383 abort ();
5387 /***********************************************************************
5388 Protection from GC
5389 ***********************************************************************/
5391 /* Temporarily prevent garbage collection. */
5393 ptrdiff_t
5394 inhibit_garbage_collection (void)
5396 ptrdiff_t count = SPECPDL_INDEX ();
5398 specbind (Qgc_cons_threshold, make_number (MOST_POSITIVE_FIXNUM));
5399 return count;
5402 /* Used to avoid possible overflows when
5403 converting from C to Lisp integers. */
5405 static inline Lisp_Object
5406 bounded_number (EMACS_INT number)
5408 return make_number (min (MOST_POSITIVE_FIXNUM, number));
5411 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
5412 doc: /* Reclaim storage for Lisp objects no longer needed.
5413 Garbage collection happens automatically if you cons more than
5414 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5415 `garbage-collect' normally returns a list with info on amount of space in use,
5416 where each entry has the form (NAME SIZE USED FREE), where:
5417 - NAME is a symbol describing the kind of objects this entry represents,
5418 - SIZE is the number of bytes used by each one,
5419 - USED is the number of those objects that were found live in the heap,
5420 - FREE is the number of those objects that are not live but that Emacs
5421 keeps around for future allocations (maybe because it does not know how
5422 to return them to the OS).
5423 However, if there was overflow in pure space, `garbage-collect'
5424 returns nil, because real GC can't be done.
5425 See Info node `(elisp)Garbage Collection'. */)
5426 (void)
5428 register struct specbinding *bind;
5429 register struct buffer *nextb;
5430 char stack_top_variable;
5431 ptrdiff_t i;
5432 int message_p;
5433 Lisp_Object total[11];
5434 ptrdiff_t count = SPECPDL_INDEX ();
5435 EMACS_TIME start;
5437 if (abort_on_gc)
5438 abort ();
5440 /* Can't GC if pure storage overflowed because we can't determine
5441 if something is a pure object or not. */
5442 if (pure_bytes_used_before_overflow)
5443 return Qnil;
5445 check_cons_list ();
5447 /* Don't keep undo information around forever.
5448 Do this early on, so it is no problem if the user quits. */
5449 FOR_EACH_BUFFER (nextb)
5450 compact_buffer (nextb);
5452 start = current_emacs_time ();
5454 /* In case user calls debug_print during GC,
5455 don't let that cause a recursive GC. */
5456 consing_since_gc = 0;
5458 /* Save what's currently displayed in the echo area. */
5459 message_p = push_message ();
5460 record_unwind_protect (pop_message_unwind, Qnil);
5462 /* Save a copy of the contents of the stack, for debugging. */
5463 #if MAX_SAVE_STACK > 0
5464 if (NILP (Vpurify_flag))
5466 char *stack;
5467 ptrdiff_t stack_size;
5468 if (&stack_top_variable < stack_bottom)
5470 stack = &stack_top_variable;
5471 stack_size = stack_bottom - &stack_top_variable;
5473 else
5475 stack = stack_bottom;
5476 stack_size = &stack_top_variable - stack_bottom;
5478 if (stack_size <= MAX_SAVE_STACK)
5480 if (stack_copy_size < stack_size)
5482 stack_copy = xrealloc (stack_copy, stack_size);
5483 stack_copy_size = stack_size;
5485 memcpy (stack_copy, stack, stack_size);
5488 #endif /* MAX_SAVE_STACK > 0 */
5490 if (garbage_collection_messages)
5491 message1_nolog ("Garbage collecting...");
5493 BLOCK_INPUT;
5495 shrink_regexp_cache ();
5497 gc_in_progress = 1;
5499 /* Mark all the special slots that serve as the roots of accessibility. */
5501 for (i = 0; i < staticidx; i++)
5502 mark_object (*staticvec[i]);
5504 for (bind = specpdl; bind != specpdl_ptr; bind++)
5506 mark_object (bind->symbol);
5507 mark_object (bind->old_value);
5509 mark_terminals ();
5510 mark_kboards ();
5511 mark_ttys ();
5513 #ifdef USE_GTK
5515 extern void xg_mark_data (void);
5516 xg_mark_data ();
5518 #endif
5520 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
5521 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
5522 mark_stack ();
5523 #else
5525 register struct gcpro *tail;
5526 for (tail = gcprolist; tail; tail = tail->next)
5527 for (i = 0; i < tail->nvars; i++)
5528 mark_object (tail->var[i]);
5530 mark_byte_stack ();
5532 struct catchtag *catch;
5533 struct handler *handler;
5535 for (catch = catchlist; catch; catch = catch->next)
5537 mark_object (catch->tag);
5538 mark_object (catch->val);
5540 for (handler = handlerlist; handler; handler = handler->next)
5542 mark_object (handler->handler);
5543 mark_object (handler->var);
5546 mark_backtrace ();
5547 #endif
5549 #ifdef HAVE_WINDOW_SYSTEM
5550 mark_fringe_data ();
5551 #endif
5553 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5554 mark_stack ();
5555 #endif
5557 /* Everything is now marked, except for the things that require special
5558 finalization, i.e. the undo_list.
5559 Look thru every buffer's undo list
5560 for elements that update markers that were not marked,
5561 and delete them. */
5562 FOR_EACH_BUFFER (nextb)
5564 /* If a buffer's undo list is Qt, that means that undo is
5565 turned off in that buffer. Calling truncate_undo_list on
5566 Qt tends to return NULL, which effectively turns undo back on.
5567 So don't call truncate_undo_list if undo_list is Qt. */
5568 if (! EQ (nextb->BUFFER_INTERNAL_FIELD (undo_list), Qt))
5570 Lisp_Object tail, prev;
5571 tail = nextb->BUFFER_INTERNAL_FIELD (undo_list);
5572 prev = Qnil;
5573 while (CONSP (tail))
5575 if (CONSP (XCAR (tail))
5576 && MARKERP (XCAR (XCAR (tail)))
5577 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5579 if (NILP (prev))
5580 nextb->BUFFER_INTERNAL_FIELD (undo_list) = tail = XCDR (tail);
5581 else
5583 tail = XCDR (tail);
5584 XSETCDR (prev, tail);
5587 else
5589 prev = tail;
5590 tail = XCDR (tail);
5594 /* Now that we have stripped the elements that need not be in the
5595 undo_list any more, we can finally mark the list. */
5596 mark_object (nextb->BUFFER_INTERNAL_FIELD (undo_list));
5599 gc_sweep ();
5601 /* Clear the mark bits that we set in certain root slots. */
5603 unmark_byte_stack ();
5604 VECTOR_UNMARK (&buffer_defaults);
5605 VECTOR_UNMARK (&buffer_local_symbols);
5607 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
5608 dump_zombies ();
5609 #endif
5611 UNBLOCK_INPUT;
5613 check_cons_list ();
5615 gc_in_progress = 0;
5617 consing_since_gc = 0;
5618 if (gc_cons_threshold < GC_DEFAULT_THRESHOLD / 10)
5619 gc_cons_threshold = GC_DEFAULT_THRESHOLD / 10;
5621 gc_relative_threshold = 0;
5622 if (FLOATP (Vgc_cons_percentage))
5623 { /* Set gc_cons_combined_threshold. */
5624 double tot = 0;
5626 tot += total_conses * sizeof (struct Lisp_Cons);
5627 tot += total_symbols * sizeof (struct Lisp_Symbol);
5628 tot += total_markers * sizeof (union Lisp_Misc);
5629 tot += total_string_bytes;
5630 tot += total_vector_slots * word_size;
5631 tot += total_floats * sizeof (struct Lisp_Float);
5632 tot += total_intervals * sizeof (struct interval);
5633 tot += total_strings * sizeof (struct Lisp_String);
5635 tot *= XFLOAT_DATA (Vgc_cons_percentage);
5636 if (0 < tot)
5638 if (tot < TYPE_MAXIMUM (EMACS_INT))
5639 gc_relative_threshold = tot;
5640 else
5641 gc_relative_threshold = TYPE_MAXIMUM (EMACS_INT);
5645 if (garbage_collection_messages)
5647 if (message_p || minibuf_level > 0)
5648 restore_message ();
5649 else
5650 message1_nolog ("Garbage collecting...done");
5653 unbind_to (count, Qnil);
5655 total[0] = list4 (Qcons, make_number (sizeof (struct Lisp_Cons)),
5656 bounded_number (total_conses),
5657 bounded_number (total_free_conses));
5659 total[1] = list4 (Qsymbol, make_number (sizeof (struct Lisp_Symbol)),
5660 bounded_number (total_symbols),
5661 bounded_number (total_free_symbols));
5663 total[2] = list4 (Qmisc, make_number (sizeof (union Lisp_Misc)),
5664 bounded_number (total_markers),
5665 bounded_number (total_free_markers));
5667 total[3] = list4 (Qstring, make_number (sizeof (struct Lisp_String)),
5668 bounded_number (total_strings),
5669 bounded_number (total_free_strings));
5671 total[4] = list3 (Qstring_bytes, make_number (1),
5672 bounded_number (total_string_bytes));
5674 total[5] = list3 (Qvector, make_number (sizeof (struct Lisp_Vector)),
5675 bounded_number (total_vectors));
5677 total[6] = list4 (Qvector_slots, make_number (word_size),
5678 bounded_number (total_vector_slots),
5679 bounded_number (total_free_vector_slots));
5681 total[7] = list4 (Qfloat, make_number (sizeof (struct Lisp_Float)),
5682 bounded_number (total_floats),
5683 bounded_number (total_free_floats));
5685 total[8] = list4 (Qinterval, make_number (sizeof (struct interval)),
5686 bounded_number (total_intervals),
5687 bounded_number (total_free_intervals));
5689 total[9] = list3 (Qbuffer, make_number (sizeof (struct buffer)),
5690 bounded_number (total_buffers));
5692 total[10] = list4 (Qheap, make_number (1024),
5693 #ifdef DOUG_LEA_MALLOC
5694 bounded_number ((mallinfo ().uordblks + 1023) >> 10),
5695 bounded_number ((mallinfo ().fordblks + 1023) >> 10)
5696 #else
5697 Qnil, Qnil
5698 #endif
5701 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5703 /* Compute average percentage of zombies. */
5704 double nlive =
5705 (total_conses + total_symbols + total_markers + total_strings
5706 + total_vectors + total_floats + total_intervals + total_buffers);
5708 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
5709 max_live = max (nlive, max_live);
5710 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
5711 max_zombies = max (nzombies, max_zombies);
5712 ++ngcs;
5714 #endif
5716 if (!NILP (Vpost_gc_hook))
5718 ptrdiff_t gc_count = inhibit_garbage_collection ();
5719 safe_run_hooks (Qpost_gc_hook);
5720 unbind_to (gc_count, Qnil);
5723 /* Accumulate statistics. */
5724 if (FLOATP (Vgc_elapsed))
5726 EMACS_TIME since_start = sub_emacs_time (current_emacs_time (), start);
5727 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed)
5728 + EMACS_TIME_TO_DOUBLE (since_start));
5731 gcs_done++;
5733 return Flist (sizeof total / sizeof *total, total);
5737 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5738 only interesting objects referenced from glyphs are strings. */
5740 static void
5741 mark_glyph_matrix (struct glyph_matrix *matrix)
5743 struct glyph_row *row = matrix->rows;
5744 struct glyph_row *end = row + matrix->nrows;
5746 for (; row < end; ++row)
5747 if (row->enabled_p)
5749 int area;
5750 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
5752 struct glyph *glyph = row->glyphs[area];
5753 struct glyph *end_glyph = glyph + row->used[area];
5755 for (; glyph < end_glyph; ++glyph)
5756 if (STRINGP (glyph->object)
5757 && !STRING_MARKED_P (XSTRING (glyph->object)))
5758 mark_object (glyph->object);
5764 /* Mark Lisp faces in the face cache C. */
5766 static void
5767 mark_face_cache (struct face_cache *c)
5769 if (c)
5771 int i, j;
5772 for (i = 0; i < c->used; ++i)
5774 struct face *face = FACE_FROM_ID (c->f, i);
5776 if (face)
5778 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
5779 mark_object (face->lface[j]);
5787 /* Mark reference to a Lisp_Object.
5788 If the object referred to has not been seen yet, recursively mark
5789 all the references contained in it. */
5791 #define LAST_MARKED_SIZE 500
5792 static Lisp_Object last_marked[LAST_MARKED_SIZE];
5793 static int last_marked_index;
5795 /* For debugging--call abort when we cdr down this many
5796 links of a list, in mark_object. In debugging,
5797 the call to abort will hit a breakpoint.
5798 Normally this is zero and the check never goes off. */
5799 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE;
5801 static void
5802 mark_vectorlike (struct Lisp_Vector *ptr)
5804 ptrdiff_t size = ptr->header.size;
5805 ptrdiff_t i;
5807 eassert (!VECTOR_MARKED_P (ptr));
5808 VECTOR_MARK (ptr); /* Else mark it. */
5809 if (size & PSEUDOVECTOR_FLAG)
5810 size &= PSEUDOVECTOR_SIZE_MASK;
5812 /* Note that this size is not the memory-footprint size, but only
5813 the number of Lisp_Object fields that we should trace.
5814 The distinction is used e.g. by Lisp_Process which places extra
5815 non-Lisp_Object fields at the end of the structure... */
5816 for (i = 0; i < size; i++) /* ...and then mark its elements. */
5817 mark_object (ptr->contents[i]);
5820 /* Like mark_vectorlike but optimized for char-tables (and
5821 sub-char-tables) assuming that the contents are mostly integers or
5822 symbols. */
5824 static void
5825 mark_char_table (struct Lisp_Vector *ptr)
5827 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5828 int i;
5830 eassert (!VECTOR_MARKED_P (ptr));
5831 VECTOR_MARK (ptr);
5832 for (i = 0; i < size; i++)
5834 Lisp_Object val = ptr->contents[i];
5836 if (INTEGERP (val) || (SYMBOLP (val) && XSYMBOL (val)->gcmarkbit))
5837 continue;
5838 if (SUB_CHAR_TABLE_P (val))
5840 if (! VECTOR_MARKED_P (XVECTOR (val)))
5841 mark_char_table (XVECTOR (val));
5843 else
5844 mark_object (val);
5848 /* Mark the chain of overlays starting at PTR. */
5850 static void
5851 mark_overlay (struct Lisp_Overlay *ptr)
5853 for (; ptr && !ptr->gcmarkbit; ptr = ptr->next)
5855 ptr->gcmarkbit = 1;
5856 mark_object (ptr->start);
5857 mark_object (ptr->end);
5858 mark_object (ptr->plist);
5862 /* Mark Lisp_Objects and special pointers in BUFFER. */
5864 static void
5865 mark_buffer (struct buffer *buffer)
5867 /* This is handled much like other pseudovectors... */
5868 mark_vectorlike ((struct Lisp_Vector *) buffer);
5870 /* ...but there are some buffer-specific things. */
5872 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
5874 /* For now, we just don't mark the undo_list. It's done later in
5875 a special way just before the sweep phase, and after stripping
5876 some of its elements that are not needed any more. */
5878 mark_overlay (buffer->overlays_before);
5879 mark_overlay (buffer->overlays_after);
5881 /* If this is an indirect buffer, mark its base buffer. */
5882 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5883 mark_buffer (buffer->base_buffer);
5886 /* Determine type of generic Lisp_Object and mark it accordingly. */
5888 void
5889 mark_object (Lisp_Object arg)
5891 register Lisp_Object obj = arg;
5892 #ifdef GC_CHECK_MARKED_OBJECTS
5893 void *po;
5894 struct mem_node *m;
5895 #endif
5896 ptrdiff_t cdr_count = 0;
5898 loop:
5900 if (PURE_POINTER_P (XPNTR (obj)))
5901 return;
5903 last_marked[last_marked_index++] = obj;
5904 if (last_marked_index == LAST_MARKED_SIZE)
5905 last_marked_index = 0;
5907 /* Perform some sanity checks on the objects marked here. Abort if
5908 we encounter an object we know is bogus. This increases GC time
5909 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
5910 #ifdef GC_CHECK_MARKED_OBJECTS
5912 po = (void *) XPNTR (obj);
5914 /* Check that the object pointed to by PO is known to be a Lisp
5915 structure allocated from the heap. */
5916 #define CHECK_ALLOCATED() \
5917 do { \
5918 m = mem_find (po); \
5919 if (m == MEM_NIL) \
5920 abort (); \
5921 } while (0)
5923 /* Check that the object pointed to by PO is live, using predicate
5924 function LIVEP. */
5925 #define CHECK_LIVE(LIVEP) \
5926 do { \
5927 if (!LIVEP (m, po)) \
5928 abort (); \
5929 } while (0)
5931 /* Check both of the above conditions. */
5932 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
5933 do { \
5934 CHECK_ALLOCATED (); \
5935 CHECK_LIVE (LIVEP); \
5936 } while (0) \
5938 #else /* not GC_CHECK_MARKED_OBJECTS */
5940 #define CHECK_LIVE(LIVEP) (void) 0
5941 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
5943 #endif /* not GC_CHECK_MARKED_OBJECTS */
5945 switch (SWITCH_ENUM_CAST (XTYPE (obj)))
5947 case Lisp_String:
5949 register struct Lisp_String *ptr = XSTRING (obj);
5950 if (STRING_MARKED_P (ptr))
5951 break;
5952 CHECK_ALLOCATED_AND_LIVE (live_string_p);
5953 MARK_STRING (ptr);
5954 MARK_INTERVAL_TREE (ptr->intervals);
5955 #ifdef GC_CHECK_STRING_BYTES
5956 /* Check that the string size recorded in the string is the
5957 same as the one recorded in the sdata structure. */
5958 CHECK_STRING_BYTES (ptr);
5959 #endif /* GC_CHECK_STRING_BYTES */
5961 break;
5963 case Lisp_Vectorlike:
5965 register struct Lisp_Vector *ptr = XVECTOR (obj);
5966 register ptrdiff_t pvectype;
5968 if (VECTOR_MARKED_P (ptr))
5969 break;
5971 #ifdef GC_CHECK_MARKED_OBJECTS
5972 m = mem_find (po);
5973 if (m == MEM_NIL && !SUBRP (obj)
5974 && po != &buffer_defaults
5975 && po != &buffer_local_symbols)
5976 abort ();
5977 #endif /* GC_CHECK_MARKED_OBJECTS */
5979 if (ptr->header.size & PSEUDOVECTOR_FLAG)
5980 pvectype = ((ptr->header.size & PVEC_TYPE_MASK)
5981 >> PSEUDOVECTOR_SIZE_BITS);
5982 else
5983 pvectype = 0;
5985 if (pvectype != PVEC_SUBR && pvectype != PVEC_BUFFER)
5986 CHECK_LIVE (live_vector_p);
5988 switch (pvectype)
5990 case PVEC_BUFFER:
5991 #ifdef GC_CHECK_MARKED_OBJECTS
5992 if (po != &buffer_defaults && po != &buffer_local_symbols)
5994 struct buffer *b;
5995 FOR_EACH_BUFFER (b)
5996 if (b == po)
5997 break;
5998 if (b == NULL)
5999 abort ();
6001 #endif /* GC_CHECK_MARKED_OBJECTS */
6002 mark_buffer ((struct buffer *) ptr);
6003 break;
6005 case PVEC_COMPILED:
6006 { /* We could treat this just like a vector, but it is better
6007 to save the COMPILED_CONSTANTS element for last and avoid
6008 recursion there. */
6009 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
6010 int i;
6012 VECTOR_MARK (ptr);
6013 for (i = 0; i < size; i++)
6014 if (i != COMPILED_CONSTANTS)
6015 mark_object (ptr->contents[i]);
6016 if (size > COMPILED_CONSTANTS)
6018 obj = ptr->contents[COMPILED_CONSTANTS];
6019 goto loop;
6022 break;
6024 case PVEC_FRAME:
6026 mark_vectorlike (ptr);
6027 mark_face_cache (((struct frame *) ptr)->face_cache);
6029 break;
6031 case PVEC_WINDOW:
6033 struct window *w = (struct window *) ptr;
6035 mark_vectorlike (ptr);
6036 /* Mark glyphs for leaf windows. Marking window
6037 matrices is sufficient because frame matrices
6038 use the same glyph memory. */
6039 if (NILP (w->hchild) && NILP (w->vchild) && w->current_matrix)
6041 mark_glyph_matrix (w->current_matrix);
6042 mark_glyph_matrix (w->desired_matrix);
6045 break;
6047 case PVEC_HASH_TABLE:
6049 struct Lisp_Hash_Table *h = (struct Lisp_Hash_Table *) ptr;
6051 mark_vectorlike (ptr);
6052 /* If hash table is not weak, mark all keys and values.
6053 For weak tables, mark only the vector. */
6054 if (NILP (h->weak))
6055 mark_object (h->key_and_value);
6056 else
6057 VECTOR_MARK (XVECTOR (h->key_and_value));
6059 break;
6061 case PVEC_CHAR_TABLE:
6062 mark_char_table (ptr);
6063 break;
6065 case PVEC_BOOL_VECTOR:
6066 /* No Lisp_Objects to mark in a bool vector. */
6067 VECTOR_MARK (ptr);
6068 break;
6070 case PVEC_SUBR:
6071 break;
6073 case PVEC_FREE:
6074 abort ();
6076 default:
6077 mark_vectorlike (ptr);
6080 break;
6082 case Lisp_Symbol:
6084 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
6085 struct Lisp_Symbol *ptrx;
6087 if (ptr->gcmarkbit)
6088 break;
6089 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
6090 ptr->gcmarkbit = 1;
6091 mark_object (ptr->function);
6092 mark_object (ptr->plist);
6093 switch (ptr->redirect)
6095 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
6096 case SYMBOL_VARALIAS:
6098 Lisp_Object tem;
6099 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
6100 mark_object (tem);
6101 break;
6103 case SYMBOL_LOCALIZED:
6105 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
6106 /* If the value is forwarded to a buffer or keyboard field,
6107 these are marked when we see the corresponding object.
6108 And if it's forwarded to a C variable, either it's not
6109 a Lisp_Object var, or it's staticpro'd already. */
6110 mark_object (blv->where);
6111 mark_object (blv->valcell);
6112 mark_object (blv->defcell);
6113 break;
6115 case SYMBOL_FORWARDED:
6116 /* If the value is forwarded to a buffer or keyboard field,
6117 these are marked when we see the corresponding object.
6118 And if it's forwarded to a C variable, either it's not
6119 a Lisp_Object var, or it's staticpro'd already. */
6120 break;
6121 default: abort ();
6123 if (!PURE_POINTER_P (XSTRING (ptr->xname)))
6124 MARK_STRING (XSTRING (ptr->xname));
6125 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr->xname));
6127 ptr = ptr->next;
6128 if (ptr)
6130 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun. */
6131 XSETSYMBOL (obj, ptrx);
6132 goto loop;
6135 break;
6137 case Lisp_Misc:
6138 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
6140 if (XMISCANY (obj)->gcmarkbit)
6141 break;
6143 switch (XMISCTYPE (obj))
6145 case Lisp_Misc_Marker:
6146 /* DO NOT mark thru the marker's chain.
6147 The buffer's markers chain does not preserve markers from gc;
6148 instead, markers are removed from the chain when freed by gc. */
6149 XMISCANY (obj)->gcmarkbit = 1;
6150 break;
6152 case Lisp_Misc_Save_Value:
6153 XMISCANY (obj)->gcmarkbit = 1;
6154 #if GC_MARK_STACK
6156 register struct Lisp_Save_Value *ptr = XSAVE_VALUE (obj);
6157 /* If DOGC is set, POINTER is the address of a memory
6158 area containing INTEGER potential Lisp_Objects. */
6159 if (ptr->dogc)
6161 Lisp_Object *p = (Lisp_Object *) ptr->pointer;
6162 ptrdiff_t nelt;
6163 for (nelt = ptr->integer; nelt > 0; nelt--, p++)
6164 mark_maybe_object (*p);
6167 #endif
6168 break;
6170 case Lisp_Misc_Overlay:
6171 mark_overlay (XOVERLAY (obj));
6172 break;
6174 default:
6175 abort ();
6177 break;
6179 case Lisp_Cons:
6181 register struct Lisp_Cons *ptr = XCONS (obj);
6182 if (CONS_MARKED_P (ptr))
6183 break;
6184 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
6185 CONS_MARK (ptr);
6186 /* If the cdr is nil, avoid recursion for the car. */
6187 if (EQ (ptr->u.cdr, Qnil))
6189 obj = ptr->car;
6190 cdr_count = 0;
6191 goto loop;
6193 mark_object (ptr->car);
6194 obj = ptr->u.cdr;
6195 cdr_count++;
6196 if (cdr_count == mark_object_loop_halt)
6197 abort ();
6198 goto loop;
6201 case Lisp_Float:
6202 CHECK_ALLOCATED_AND_LIVE (live_float_p);
6203 FLOAT_MARK (XFLOAT (obj));
6204 break;
6206 case_Lisp_Int:
6207 break;
6209 default:
6210 abort ();
6213 #undef CHECK_LIVE
6214 #undef CHECK_ALLOCATED
6215 #undef CHECK_ALLOCATED_AND_LIVE
6217 /* Mark the Lisp pointers in the terminal objects.
6218 Called by Fgarbage_collect. */
6220 static void
6221 mark_terminals (void)
6223 struct terminal *t;
6224 for (t = terminal_list; t; t = t->next_terminal)
6226 eassert (t->name != NULL);
6227 #ifdef HAVE_WINDOW_SYSTEM
6228 /* If a terminal object is reachable from a stacpro'ed object,
6229 it might have been marked already. Make sure the image cache
6230 gets marked. */
6231 mark_image_cache (t->image_cache);
6232 #endif /* HAVE_WINDOW_SYSTEM */
6233 if (!VECTOR_MARKED_P (t))
6234 mark_vectorlike ((struct Lisp_Vector *)t);
6240 /* Value is non-zero if OBJ will survive the current GC because it's
6241 either marked or does not need to be marked to survive. */
6244 survives_gc_p (Lisp_Object obj)
6246 int survives_p;
6248 switch (XTYPE (obj))
6250 case_Lisp_Int:
6251 survives_p = 1;
6252 break;
6254 case Lisp_Symbol:
6255 survives_p = XSYMBOL (obj)->gcmarkbit;
6256 break;
6258 case Lisp_Misc:
6259 survives_p = XMISCANY (obj)->gcmarkbit;
6260 break;
6262 case Lisp_String:
6263 survives_p = STRING_MARKED_P (XSTRING (obj));
6264 break;
6266 case Lisp_Vectorlike:
6267 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
6268 break;
6270 case Lisp_Cons:
6271 survives_p = CONS_MARKED_P (XCONS (obj));
6272 break;
6274 case Lisp_Float:
6275 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
6276 break;
6278 default:
6279 abort ();
6282 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
6287 /* Sweep: find all structures not marked, and free them. */
6289 static void
6290 gc_sweep (void)
6292 /* Remove or mark entries in weak hash tables.
6293 This must be done before any object is unmarked. */
6294 sweep_weak_hash_tables ();
6296 sweep_strings ();
6297 #ifdef GC_CHECK_STRING_BYTES
6298 if (!noninteractive)
6299 check_string_bytes (1);
6300 #endif
6302 /* Put all unmarked conses on free list */
6304 register struct cons_block *cblk;
6305 struct cons_block **cprev = &cons_block;
6306 register int lim = cons_block_index;
6307 EMACS_INT num_free = 0, num_used = 0;
6309 cons_free_list = 0;
6311 for (cblk = cons_block; cblk; cblk = *cprev)
6313 register int i = 0;
6314 int this_free = 0;
6315 int ilim = (lim + BITS_PER_INT - 1) / BITS_PER_INT;
6317 /* Scan the mark bits an int at a time. */
6318 for (i = 0; i < ilim; i++)
6320 if (cblk->gcmarkbits[i] == -1)
6322 /* Fast path - all cons cells for this int are marked. */
6323 cblk->gcmarkbits[i] = 0;
6324 num_used += BITS_PER_INT;
6326 else
6328 /* Some cons cells for this int are not marked.
6329 Find which ones, and free them. */
6330 int start, pos, stop;
6332 start = i * BITS_PER_INT;
6333 stop = lim - start;
6334 if (stop > BITS_PER_INT)
6335 stop = BITS_PER_INT;
6336 stop += start;
6338 for (pos = start; pos < stop; pos++)
6340 if (!CONS_MARKED_P (&cblk->conses[pos]))
6342 this_free++;
6343 cblk->conses[pos].u.chain = cons_free_list;
6344 cons_free_list = &cblk->conses[pos];
6345 #if GC_MARK_STACK
6346 cons_free_list->car = Vdead;
6347 #endif
6349 else
6351 num_used++;
6352 CONS_UNMARK (&cblk->conses[pos]);
6358 lim = CONS_BLOCK_SIZE;
6359 /* If this block contains only free conses and we have already
6360 seen more than two blocks worth of free conses then deallocate
6361 this block. */
6362 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
6364 *cprev = cblk->next;
6365 /* Unhook from the free list. */
6366 cons_free_list = cblk->conses[0].u.chain;
6367 lisp_align_free (cblk);
6369 else
6371 num_free += this_free;
6372 cprev = &cblk->next;
6375 total_conses = num_used;
6376 total_free_conses = num_free;
6379 /* Put all unmarked floats on free list */
6381 register struct float_block *fblk;
6382 struct float_block **fprev = &float_block;
6383 register int lim = float_block_index;
6384 EMACS_INT num_free = 0, num_used = 0;
6386 float_free_list = 0;
6388 for (fblk = float_block; fblk; fblk = *fprev)
6390 register int i;
6391 int this_free = 0;
6392 for (i = 0; i < lim; i++)
6393 if (!FLOAT_MARKED_P (&fblk->floats[i]))
6395 this_free++;
6396 fblk->floats[i].u.chain = float_free_list;
6397 float_free_list = &fblk->floats[i];
6399 else
6401 num_used++;
6402 FLOAT_UNMARK (&fblk->floats[i]);
6404 lim = FLOAT_BLOCK_SIZE;
6405 /* If this block contains only free floats and we have already
6406 seen more than two blocks worth of free floats then deallocate
6407 this block. */
6408 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6410 *fprev = fblk->next;
6411 /* Unhook from the free list. */
6412 float_free_list = fblk->floats[0].u.chain;
6413 lisp_align_free (fblk);
6415 else
6417 num_free += this_free;
6418 fprev = &fblk->next;
6421 total_floats = num_used;
6422 total_free_floats = num_free;
6425 /* Put all unmarked intervals on free list */
6427 register struct interval_block *iblk;
6428 struct interval_block **iprev = &interval_block;
6429 register int lim = interval_block_index;
6430 EMACS_INT num_free = 0, num_used = 0;
6432 interval_free_list = 0;
6434 for (iblk = interval_block; iblk; iblk = *iprev)
6436 register int i;
6437 int this_free = 0;
6439 for (i = 0; i < lim; i++)
6441 if (!iblk->intervals[i].gcmarkbit)
6443 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
6444 interval_free_list = &iblk->intervals[i];
6445 this_free++;
6447 else
6449 num_used++;
6450 iblk->intervals[i].gcmarkbit = 0;
6453 lim = INTERVAL_BLOCK_SIZE;
6454 /* If this block contains only free intervals and we have already
6455 seen more than two blocks worth of free intervals then
6456 deallocate this block. */
6457 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6459 *iprev = iblk->next;
6460 /* Unhook from the free list. */
6461 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
6462 lisp_free (iblk);
6464 else
6466 num_free += this_free;
6467 iprev = &iblk->next;
6470 total_intervals = num_used;
6471 total_free_intervals = num_free;
6474 /* Put all unmarked symbols on free list */
6476 register struct symbol_block *sblk;
6477 struct symbol_block **sprev = &symbol_block;
6478 register int lim = symbol_block_index;
6479 EMACS_INT num_free = 0, num_used = 0;
6481 symbol_free_list = NULL;
6483 for (sblk = symbol_block; sblk; sblk = *sprev)
6485 int this_free = 0;
6486 union aligned_Lisp_Symbol *sym = sblk->symbols;
6487 union aligned_Lisp_Symbol *end = sym + lim;
6489 for (; sym < end; ++sym)
6491 /* Check if the symbol was created during loadup. In such a case
6492 it might be pointed to by pure bytecode which we don't trace,
6493 so we conservatively assume that it is live. */
6494 int pure_p = PURE_POINTER_P (XSTRING (sym->s.xname));
6496 if (!sym->s.gcmarkbit && !pure_p)
6498 if (sym->s.redirect == SYMBOL_LOCALIZED)
6499 xfree (SYMBOL_BLV (&sym->s));
6500 sym->s.next = symbol_free_list;
6501 symbol_free_list = &sym->s;
6502 #if GC_MARK_STACK
6503 symbol_free_list->function = Vdead;
6504 #endif
6505 ++this_free;
6507 else
6509 ++num_used;
6510 if (!pure_p)
6511 UNMARK_STRING (XSTRING (sym->s.xname));
6512 sym->s.gcmarkbit = 0;
6516 lim = SYMBOL_BLOCK_SIZE;
6517 /* If this block contains only free symbols and we have already
6518 seen more than two blocks worth of free symbols then deallocate
6519 this block. */
6520 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6522 *sprev = sblk->next;
6523 /* Unhook from the free list. */
6524 symbol_free_list = sblk->symbols[0].s.next;
6525 lisp_free (sblk);
6527 else
6529 num_free += this_free;
6530 sprev = &sblk->next;
6533 total_symbols = num_used;
6534 total_free_symbols = num_free;
6537 /* Put all unmarked misc's on free list.
6538 For a marker, first unchain it from the buffer it points into. */
6540 register struct marker_block *mblk;
6541 struct marker_block **mprev = &marker_block;
6542 register int lim = marker_block_index;
6543 EMACS_INT num_free = 0, num_used = 0;
6545 marker_free_list = 0;
6547 for (mblk = marker_block; mblk; mblk = *mprev)
6549 register int i;
6550 int this_free = 0;
6552 for (i = 0; i < lim; i++)
6554 if (!mblk->markers[i].m.u_any.gcmarkbit)
6556 if (mblk->markers[i].m.u_any.type == Lisp_Misc_Marker)
6557 unchain_marker (&mblk->markers[i].m.u_marker);
6558 /* Set the type of the freed object to Lisp_Misc_Free.
6559 We could leave the type alone, since nobody checks it,
6560 but this might catch bugs faster. */
6561 mblk->markers[i].m.u_marker.type = Lisp_Misc_Free;
6562 mblk->markers[i].m.u_free.chain = marker_free_list;
6563 marker_free_list = &mblk->markers[i].m;
6564 this_free++;
6566 else
6568 num_used++;
6569 mblk->markers[i].m.u_any.gcmarkbit = 0;
6572 lim = MARKER_BLOCK_SIZE;
6573 /* If this block contains only free markers and we have already
6574 seen more than two blocks worth of free markers then deallocate
6575 this block. */
6576 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6578 *mprev = mblk->next;
6579 /* Unhook from the free list. */
6580 marker_free_list = mblk->markers[0].m.u_free.chain;
6581 lisp_free (mblk);
6583 else
6585 num_free += this_free;
6586 mprev = &mblk->next;
6590 total_markers = num_used;
6591 total_free_markers = num_free;
6594 /* Free all unmarked buffers */
6596 register struct buffer *buffer = all_buffers, *prev = 0, *next;
6598 total_buffers = 0;
6599 while (buffer)
6600 if (!VECTOR_MARKED_P (buffer))
6602 if (prev)
6603 prev->header.next = buffer->header.next;
6604 else
6605 all_buffers = buffer->header.next.buffer;
6606 next = buffer->header.next.buffer;
6607 lisp_free (buffer);
6608 buffer = next;
6610 else
6612 VECTOR_UNMARK (buffer);
6613 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
6614 total_buffers++;
6615 prev = buffer, buffer = buffer->header.next.buffer;
6619 sweep_vectors ();
6621 #ifdef GC_CHECK_STRING_BYTES
6622 if (!noninteractive)
6623 check_string_bytes (1);
6624 #endif
6630 /* Debugging aids. */
6632 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
6633 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6634 This may be helpful in debugging Emacs's memory usage.
6635 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6636 (void)
6638 Lisp_Object end;
6640 XSETINT (end, (intptr_t) (char *) sbrk (0) / 1024);
6642 return end;
6645 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
6646 doc: /* Return a list of counters that measure how much consing there has been.
6647 Each of these counters increments for a certain kind of object.
6648 The counters wrap around from the largest positive integer to zero.
6649 Garbage collection does not decrease them.
6650 The elements of the value are as follows:
6651 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6652 All are in units of 1 = one object consed
6653 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6654 objects consed.
6655 MISCS include overlays, markers, and some internal types.
6656 Frames, windows, buffers, and subprocesses count as vectors
6657 (but the contents of a buffer's text do not count here). */)
6658 (void)
6660 return listn (CONSTYPE_HEAP, 8,
6661 bounded_number (cons_cells_consed),
6662 bounded_number (floats_consed),
6663 bounded_number (vector_cells_consed),
6664 bounded_number (symbols_consed),
6665 bounded_number (string_chars_consed),
6666 bounded_number (misc_objects_consed),
6667 bounded_number (intervals_consed),
6668 bounded_number (strings_consed));
6671 /* Find at most FIND_MAX symbols which have OBJ as their value or
6672 function. This is used in gdbinit's `xwhichsymbols' command. */
6674 Lisp_Object
6675 which_symbols (Lisp_Object obj, EMACS_INT find_max)
6677 struct symbol_block *sblk;
6678 ptrdiff_t gc_count = inhibit_garbage_collection ();
6679 Lisp_Object found = Qnil;
6681 if (! DEADP (obj))
6683 for (sblk = symbol_block; sblk; sblk = sblk->next)
6685 union aligned_Lisp_Symbol *aligned_sym = sblk->symbols;
6686 int bn;
6688 for (bn = 0; bn < SYMBOL_BLOCK_SIZE; bn++, aligned_sym++)
6690 struct Lisp_Symbol *sym = &aligned_sym->s;
6691 Lisp_Object val;
6692 Lisp_Object tem;
6694 if (sblk == symbol_block && bn >= symbol_block_index)
6695 break;
6697 XSETSYMBOL (tem, sym);
6698 val = find_symbol_value (tem);
6699 if (EQ (val, obj)
6700 || EQ (sym->function, obj)
6701 || (!NILP (sym->function)
6702 && COMPILEDP (sym->function)
6703 && EQ (AREF (sym->function, COMPILED_BYTECODE), obj))
6704 || (!NILP (val)
6705 && COMPILEDP (val)
6706 && EQ (AREF (val, COMPILED_BYTECODE), obj)))
6708 found = Fcons (tem, found);
6709 if (--find_max == 0)
6710 goto out;
6716 out:
6717 unbind_to (gc_count, Qnil);
6718 return found;
6721 #ifdef ENABLE_CHECKING
6722 int suppress_checking;
6724 void
6725 die (const char *msg, const char *file, int line)
6727 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: %s\r\n",
6728 file, line, msg);
6729 abort ();
6731 #endif
6733 /* Initialization */
6735 void
6736 init_alloc_once (void)
6738 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
6739 purebeg = PUREBEG;
6740 pure_size = PURESIZE;
6742 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
6743 mem_init ();
6744 Vdead = make_pure_string ("DEAD", 4, 4, 0);
6745 #endif
6747 #ifdef DOUG_LEA_MALLOC
6748 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
6749 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
6750 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
6751 #endif
6752 init_strings ();
6753 init_vectors ();
6755 #ifdef REL_ALLOC
6756 malloc_hysteresis = 32;
6757 #else
6758 malloc_hysteresis = 0;
6759 #endif
6761 refill_memory_reserve ();
6762 gc_cons_threshold = GC_DEFAULT_THRESHOLD;
6765 void
6766 init_alloc (void)
6768 gcprolist = 0;
6769 byte_stack_list = 0;
6770 #if GC_MARK_STACK
6771 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
6772 setjmp_tested_p = longjmps_done = 0;
6773 #endif
6774 #endif
6775 Vgc_elapsed = make_float (0.0);
6776 gcs_done = 0;
6779 void
6780 syms_of_alloc (void)
6782 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
6783 doc: /* Number of bytes of consing between garbage collections.
6784 Garbage collection can happen automatically once this many bytes have been
6785 allocated since the last garbage collection. All data types count.
6787 Garbage collection happens automatically only when `eval' is called.
6789 By binding this temporarily to a large number, you can effectively
6790 prevent garbage collection during a part of the program.
6791 See also `gc-cons-percentage'. */);
6793 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
6794 doc: /* Portion of the heap used for allocation.
6795 Garbage collection can happen automatically once this portion of the heap
6796 has been allocated since the last garbage collection.
6797 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
6798 Vgc_cons_percentage = make_float (0.1);
6800 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
6801 doc: /* Number of bytes of shareable Lisp data allocated so far. */);
6803 DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
6804 doc: /* Number of cons cells that have been consed so far. */);
6806 DEFVAR_INT ("floats-consed", floats_consed,
6807 doc: /* Number of floats that have been consed so far. */);
6809 DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
6810 doc: /* Number of vector cells that have been consed so far. */);
6812 DEFVAR_INT ("symbols-consed", symbols_consed,
6813 doc: /* Number of symbols that have been consed so far. */);
6815 DEFVAR_INT ("string-chars-consed", string_chars_consed,
6816 doc: /* Number of string characters that have been consed so far. */);
6818 DEFVAR_INT ("misc-objects-consed", misc_objects_consed,
6819 doc: /* Number of miscellaneous objects that have been consed so far.
6820 These include markers and overlays, plus certain objects not visible
6821 to users. */);
6823 DEFVAR_INT ("intervals-consed", intervals_consed,
6824 doc: /* Number of intervals that have been consed so far. */);
6826 DEFVAR_INT ("strings-consed", strings_consed,
6827 doc: /* Number of strings that have been consed so far. */);
6829 DEFVAR_LISP ("purify-flag", Vpurify_flag,
6830 doc: /* Non-nil means loading Lisp code in order to dump an executable.
6831 This means that certain objects should be allocated in shared (pure) space.
6832 It can also be set to a hash-table, in which case this table is used to
6833 do hash-consing of the objects allocated to pure space. */);
6835 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
6836 doc: /* Non-nil means display messages at start and end of garbage collection. */);
6837 garbage_collection_messages = 0;
6839 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
6840 doc: /* Hook run after garbage collection has finished. */);
6841 Vpost_gc_hook = Qnil;
6842 DEFSYM (Qpost_gc_hook, "post-gc-hook");
6844 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
6845 doc: /* Precomputed `signal' argument for memory-full error. */);
6846 /* We build this in advance because if we wait until we need it, we might
6847 not be able to allocate the memory to hold it. */
6848 Vmemory_signal_data
6849 = listn (CONSTYPE_PURE, 2, Qerror,
6850 build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
6852 DEFVAR_LISP ("memory-full", Vmemory_full,
6853 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
6854 Vmemory_full = Qnil;
6856 DEFSYM (Qstring_bytes, "string-bytes");
6857 DEFSYM (Qvector_slots, "vector-slots");
6858 DEFSYM (Qheap, "heap");
6860 DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
6861 DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
6863 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
6864 doc: /* Accumulated time elapsed in garbage collections.
6865 The time is in seconds as a floating point value. */);
6866 DEFVAR_INT ("gcs-done", gcs_done,
6867 doc: /* Accumulated number of garbage collections done. */);
6869 defsubr (&Scons);
6870 defsubr (&Slist);
6871 defsubr (&Svector);
6872 defsubr (&Smake_byte_code);
6873 defsubr (&Smake_list);
6874 defsubr (&Smake_vector);
6875 defsubr (&Smake_string);
6876 defsubr (&Smake_bool_vector);
6877 defsubr (&Smake_symbol);
6878 defsubr (&Smake_marker);
6879 defsubr (&Spurecopy);
6880 defsubr (&Sgarbage_collect);
6881 defsubr (&Smemory_limit);
6882 defsubr (&Smemory_use_counts);
6884 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
6885 defsubr (&Sgc_status);
6886 #endif
6889 /* Make some symbols visible to GDB. This section is last, so that
6890 the #undef lines don't mess up later code. */
6892 /* When compiled with GCC, GDB might say "No enum type named
6893 pvec_type" if we don't have at least one symbol with that type, and
6894 then xbacktrace could fail. Similarly for the other enums and
6895 their values. */
6896 union
6898 enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE;
6899 enum enum_USE_LSB_TAG enum_USE_LSB_TAG;
6900 enum Lisp_Bits Lisp_Bits;
6901 enum More_Lisp_Bits More_Lisp_Bits;
6902 enum pvec_type pvec_type;
6903 } const EXTERNALLY_VISIBLE gdb_make_enums_visible = {0};
6905 /* These symbols cannot be done as enums, since values might not be
6906 in 'int' range. Each symbol X has a corresponding X_VAL symbol,
6907 verified to have the correct value. */
6909 #define ARRAY_MARK_FLAG_VAL PTRDIFF_MIN
6910 #define PSEUDOVECTOR_FLAG_VAL (PTRDIFF_MAX - PTRDIFF_MAX / 2)
6911 #define VALMASK_VAL (USE_LSB_TAG ? -1 << GCTYPEBITS : VAL_MAX)
6913 verify (ARRAY_MARK_FLAG_VAL == ARRAY_MARK_FLAG);
6914 verify (PSEUDOVECTOR_FLAG_VAL == PSEUDOVECTOR_FLAG);
6915 verify (VALMASK_VAL == VALMASK);
6917 #undef ARRAY_MARK_FLAG
6918 #undef PSEUDOVECTOR_FLAG
6919 #undef VALMASK
6921 ptrdiff_t const EXTERNALLY_VISIBLE
6922 ARRAY_MARK_FLAG = ARRAY_MARK_FLAG_VAL,
6923 PSEUDOVECTOR_FLAG = PSEUDOVECTOR_FLAG_VAL;
6925 EMACS_INT const EXTERNALLY_VISIBLE
6926 VALMASK = VALMASK_VAL;