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/>. */
23 #include <limits.h> /* For CHAR_BIT. */
32 /* This file is part of the core Lisp implementation, and thus must
33 deal with the real data structures. If the Lisp implementation is
34 replaced, this file likely will not be used. */
36 #undef HIDE_LISP_IMPLEMENTATION
39 #include "intervals.h"
45 #include "blockinput.h"
46 #include "character.h"
47 #include "syssignal.h"
48 #include "termhooks.h" /* For struct terminal. */
52 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
53 memory. Can do this only if using gmalloc.c. */
55 #if defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC
56 #undef GC_MALLOC_CHECK
61 extern POINTER_TYPE
*sbrk ();
70 #ifdef DOUG_LEA_MALLOC
74 /* Specify maximum number of areas to mmap. It would be nice to use a
75 value that explicitly means "no limit". */
77 #define MMAP_MAX_AREAS 100000000
79 #else /* not DOUG_LEA_MALLOC */
81 /* The following come from gmalloc.c. */
83 extern size_t _bytes_used
;
84 extern size_t __malloc_extra_blocks
;
85 extern void *_malloc_internal (size_t);
86 extern void _free_internal (void *);
88 #endif /* not DOUG_LEA_MALLOC */
90 #if ! defined SYSTEM_MALLOC && ! defined SYNC_INPUT
93 /* When GTK uses the file chooser dialog, different backends can be loaded
94 dynamically. One such a backend is the Gnome VFS backend that gets loaded
95 if you run Gnome. That backend creates several threads and also allocates
98 Also, gconf and gsettings may create several threads.
100 If Emacs sets malloc hooks (! SYSTEM_MALLOC) and the emacs_blocked_*
101 functions below are called from malloc, there is a chance that one
102 of these threads preempts the Emacs main thread and the hook variables
103 end up in an inconsistent state. So we have a mutex to prevent that (note
104 that the backend handles concurrent access to malloc within its own threads
105 but Emacs code running in the main thread is not included in that control).
107 When UNBLOCK_INPUT is called, reinvoke_input_signal may be called. If this
108 happens in one of the backend threads we will have two threads that tries
109 to run Emacs code at once, and the code is not prepared for that.
110 To prevent that, we only call BLOCK/UNBLOCK from the main thread. */
112 static pthread_mutex_t alloc_mutex
;
114 #define BLOCK_INPUT_ALLOC \
117 if (pthread_equal (pthread_self (), main_thread)) \
119 pthread_mutex_lock (&alloc_mutex); \
122 #define UNBLOCK_INPUT_ALLOC \
125 pthread_mutex_unlock (&alloc_mutex); \
126 if (pthread_equal (pthread_self (), main_thread)) \
131 #else /* ! defined HAVE_PTHREAD */
133 #define BLOCK_INPUT_ALLOC BLOCK_INPUT
134 #define UNBLOCK_INPUT_ALLOC UNBLOCK_INPUT
136 #endif /* ! defined HAVE_PTHREAD */
137 #endif /* ! defined SYSTEM_MALLOC && ! defined SYNC_INPUT */
139 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
140 to a struct Lisp_String. */
142 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
143 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
144 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
146 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
147 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
148 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
150 /* Value is the number of bytes of S, a pointer to a struct Lisp_String.
151 Be careful during GC, because S->size contains the mark bit for
154 #define GC_STRING_BYTES(S) (STRING_BYTES (S))
156 /* Global variables. */
157 struct emacs_globals globals
;
159 /* Number of bytes of consing done since the last gc. */
161 EMACS_INT consing_since_gc
;
163 /* Similar minimum, computed from Vgc_cons_percentage. */
165 EMACS_INT gc_relative_threshold
;
167 /* Minimum number of bytes of consing since GC before next GC,
168 when memory is full. */
170 EMACS_INT memory_full_cons_threshold
;
172 /* Nonzero during GC. */
176 /* Nonzero means abort if try to GC.
177 This is for code which is written on the assumption that
178 no GC will happen, so as to verify that assumption. */
182 /* Number of live and free conses etc. */
184 static EMACS_INT total_conses
, total_markers
, total_symbols
, total_vector_size
;
185 static EMACS_INT total_free_conses
, total_free_markers
, total_free_symbols
;
186 static EMACS_INT total_free_floats
, total_floats
;
188 /* Points to memory space allocated as "spare", to be freed if we run
189 out of memory. We keep one large block, four cons-blocks, and
190 two string blocks. */
192 static char *spare_memory
[7];
194 /* Amount of spare memory to keep in large reserve block, or to see
195 whether this much is available when malloc fails on a larger request. */
197 #define SPARE_MEMORY (1 << 14)
199 /* Number of extra blocks malloc should get when it needs more core. */
201 static int malloc_hysteresis
;
203 /* Initialize it to a nonzero value to force it into data space
204 (rather than bss space). That way unexec will remap it into text
205 space (pure), on some systems. We have not implemented the
206 remapping on more recent systems because this is less important
207 nowadays than in the days of small memories and timesharing. */
209 EMACS_INT pure
[(PURESIZE
+ sizeof (EMACS_INT
) - 1) / sizeof (EMACS_INT
)] = {1,};
210 #define PUREBEG (char *) pure
212 /* Pointer to the pure area, and its size. */
214 static char *purebeg
;
215 static ptrdiff_t pure_size
;
217 /* Number of bytes of pure storage used before pure storage overflowed.
218 If this is non-zero, this implies that an overflow occurred. */
220 static ptrdiff_t pure_bytes_used_before_overflow
;
222 /* Value is non-zero if P points into pure space. */
224 #define PURE_POINTER_P(P) \
225 ((uintptr_t) (P) - (uintptr_t) purebeg <= pure_size)
227 /* Index in pure at which next pure Lisp object will be allocated.. */
229 static EMACS_INT pure_bytes_used_lisp
;
231 /* Number of bytes allocated for non-Lisp objects in pure storage. */
233 static EMACS_INT pure_bytes_used_non_lisp
;
235 /* If nonzero, this is a warning delivered by malloc and not yet
238 const char *pending_malloc_warning
;
240 /* Maximum amount of C stack to save when a GC happens. */
242 #ifndef MAX_SAVE_STACK
243 #define MAX_SAVE_STACK 16000
246 /* Buffer in which we save a copy of the C stack at each GC. */
248 #if MAX_SAVE_STACK > 0
249 static char *stack_copy
;
250 static ptrdiff_t stack_copy_size
;
253 /* Non-zero means ignore malloc warnings. Set during initialization.
254 Currently not used. */
256 static int ignore_warnings
;
258 static Lisp_Object Qgc_cons_threshold
;
259 Lisp_Object Qchar_table_extra_slots
;
261 /* Hook run after GC has finished. */
263 static Lisp_Object Qpost_gc_hook
;
265 static void mark_buffer (Lisp_Object
);
266 static void mark_terminals (void);
267 static void gc_sweep (void);
268 static void mark_glyph_matrix (struct glyph_matrix
*);
269 static void mark_face_cache (struct face_cache
*);
271 #if !defined REL_ALLOC || defined SYSTEM_MALLOC
272 static void refill_memory_reserve (void);
274 static struct Lisp_String
*allocate_string (void);
275 static void compact_small_strings (void);
276 static void free_large_strings (void);
277 static void sweep_strings (void);
278 static void free_misc (Lisp_Object
);
279 extern Lisp_Object
which_symbols (Lisp_Object
, EMACS_INT
) EXTERNALLY_VISIBLE
;
281 /* When scanning the C stack for live Lisp objects, Emacs keeps track
282 of what memory allocated via lisp_malloc is intended for what
283 purpose. This enumeration specifies the type of memory. */
294 /* We used to keep separate mem_types for subtypes of vectors such as
295 process, hash_table, frame, terminal, and window, but we never made
296 use of the distinction, so it only caused source-code complexity
297 and runtime slowdown. Minor but pointless. */
301 static POINTER_TYPE
*lisp_malloc (size_t, enum mem_type
);
304 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
306 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
307 #include <stdio.h> /* For fprintf. */
310 /* A unique object in pure space used to make some Lisp objects
311 on free lists recognizable in O(1). */
313 static Lisp_Object Vdead
;
314 #define DEADP(x) EQ (x, Vdead)
316 #ifdef GC_MALLOC_CHECK
318 enum mem_type allocated_mem_type
;
320 #endif /* GC_MALLOC_CHECK */
322 /* A node in the red-black tree describing allocated memory containing
323 Lisp data. Each such block is recorded with its start and end
324 address when it is allocated, and removed from the tree when it
327 A red-black tree is a balanced binary tree with the following
330 1. Every node is either red or black.
331 2. Every leaf is black.
332 3. If a node is red, then both of its children are black.
333 4. Every simple path from a node to a descendant leaf contains
334 the same number of black nodes.
335 5. The root is always black.
337 When nodes are inserted into the tree, or deleted from the tree,
338 the tree is "fixed" so that these properties are always true.
340 A red-black tree with N internal nodes has height at most 2
341 log(N+1). Searches, insertions and deletions are done in O(log N).
342 Please see a text book about data structures for a detailed
343 description of red-black trees. Any book worth its salt should
348 /* Children of this node. These pointers are never NULL. When there
349 is no child, the value is MEM_NIL, which points to a dummy node. */
350 struct mem_node
*left
, *right
;
352 /* The parent of this node. In the root node, this is NULL. */
353 struct mem_node
*parent
;
355 /* Start and end of allocated region. */
359 enum {MEM_BLACK
, MEM_RED
} color
;
365 /* Base address of stack. Set in main. */
367 Lisp_Object
*stack_base
;
369 /* Root of the tree describing allocated Lisp memory. */
371 static struct mem_node
*mem_root
;
373 /* Lowest and highest known address in the heap. */
375 static void *min_heap_address
, *max_heap_address
;
377 /* Sentinel node of the tree. */
379 static struct mem_node mem_z
;
380 #define MEM_NIL &mem_z
382 static struct Lisp_Vector
*allocate_vectorlike (EMACS_INT
);
383 static void lisp_free (POINTER_TYPE
*);
384 static void mark_stack (void);
385 static int live_vector_p (struct mem_node
*, void *);
386 static int live_buffer_p (struct mem_node
*, void *);
387 static int live_string_p (struct mem_node
*, void *);
388 static int live_cons_p (struct mem_node
*, void *);
389 static int live_symbol_p (struct mem_node
*, void *);
390 static int live_float_p (struct mem_node
*, void *);
391 static int live_misc_p (struct mem_node
*, void *);
392 static void mark_maybe_object (Lisp_Object
);
393 static void mark_memory (void *, void *);
394 static void mem_init (void);
395 #if (defined GC_MALLOC_CHECK \
396 ? !defined SYSTEM_MALLOC && !defined SYNC_INPUT \
398 # define NEED_MEM_INSERT
399 static struct mem_node
*mem_insert (void *, void *, enum mem_type
);
400 static void mem_insert_fixup (struct mem_node
*);
402 static void mem_rotate_left (struct mem_node
*);
403 static void mem_rotate_right (struct mem_node
*);
404 static void mem_delete (struct mem_node
*);
405 static void mem_delete_fixup (struct mem_node
*);
406 static inline struct mem_node
*mem_find (void *);
409 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
410 static void check_gcpros (void);
413 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
419 /* Recording what needs to be marked for gc. */
421 struct gcpro
*gcprolist
;
423 /* Addresses of staticpro'd variables. Initialize it to a nonzero
424 value; otherwise some compilers put it into BSS. */
426 #define NSTATICS 0x640
427 static Lisp_Object
*staticvec
[NSTATICS
] = {&Vpurify_flag
};
429 /* Index of next unused slot in staticvec. */
431 static int staticidx
= 0;
433 static POINTER_TYPE
*pure_alloc (size_t, int);
436 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
437 ALIGNMENT must be a power of 2. */
439 #define ALIGN(ptr, ALIGNMENT) \
440 ((POINTER_TYPE *) ((((uintptr_t) (ptr)) + (ALIGNMENT) - 1) \
441 & ~((ALIGNMENT) - 1)))
445 /************************************************************************
447 ************************************************************************/
449 /* Function malloc calls this if it finds we are near exhausting storage. */
452 malloc_warning (const char *str
)
454 pending_malloc_warning
= str
;
458 /* Display an already-pending malloc warning. */
461 display_malloc_warning (void)
463 call3 (intern ("display-warning"),
465 build_string (pending_malloc_warning
),
466 intern ("emergency"));
467 pending_malloc_warning
= 0;
470 /* Called if we can't allocate relocatable space for a buffer. */
473 buffer_memory_full (EMACS_INT nbytes
)
475 /* If buffers use the relocating allocator, no need to free
476 spare_memory, because we may have plenty of malloc space left
477 that we could get, and if we don't, the malloc that fails will
478 itself cause spare_memory to be freed. If buffers don't use the
479 relocating allocator, treat this like any other failing
483 memory_full (nbytes
);
486 /* This used to call error, but if we've run out of memory, we could
487 get infinite recursion trying to build the string. */
488 xsignal (Qnil
, Vmemory_signal_data
);
492 #ifndef XMALLOC_OVERRUN_CHECK
493 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
496 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
499 The header consists of XMALLOC_OVERRUN_CHECK_SIZE fixed bytes
500 followed by XMALLOC_OVERRUN_SIZE_SIZE bytes containing the original
501 block size in little-endian order. The trailer consists of
502 XMALLOC_OVERRUN_CHECK_SIZE fixed bytes.
504 The header is used to detect whether this block has been allocated
505 through these functions, as some low-level libc functions may
506 bypass the malloc hooks. */
508 #define XMALLOC_OVERRUN_CHECK_SIZE 16
509 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
510 (2 * XMALLOC_OVERRUN_CHECK_SIZE + XMALLOC_OVERRUN_SIZE_SIZE)
512 /* Define XMALLOC_OVERRUN_SIZE_SIZE so that (1) it's large enough to
513 hold a size_t value and (2) the header size is a multiple of the
514 alignment that Emacs needs for C types and for USE_LSB_TAG. */
515 #define XMALLOC_BASE_ALIGNMENT \
518 union { long double d; intmax_t i; void *p; } u; \
523 /* A common multiple of the positive integers A and B. Ideally this
524 would be the least common multiple, but there's no way to do that
525 as a constant expression in C, so do the best that we can easily do. */
526 # define COMMON_MULTIPLE(a, b) \
527 ((a) % (b) == 0 ? (a) : (b) % (a) == 0 ? (b) : (a) * (b))
528 # define XMALLOC_HEADER_ALIGNMENT \
529 COMMON_MULTIPLE (1 << GCTYPEBITS, XMALLOC_BASE_ALIGNMENT)
531 # define XMALLOC_HEADER_ALIGNMENT XMALLOC_BASE_ALIGNMENT
533 #define XMALLOC_OVERRUN_SIZE_SIZE \
534 (((XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t) \
535 + XMALLOC_HEADER_ALIGNMENT - 1) \
536 / XMALLOC_HEADER_ALIGNMENT * XMALLOC_HEADER_ALIGNMENT) \
537 - XMALLOC_OVERRUN_CHECK_SIZE)
539 static char const xmalloc_overrun_check_header
[XMALLOC_OVERRUN_CHECK_SIZE
] =
540 { '\x9a', '\x9b', '\xae', '\xaf',
541 '\xbf', '\xbe', '\xce', '\xcf',
542 '\xea', '\xeb', '\xec', '\xed',
543 '\xdf', '\xde', '\x9c', '\x9d' };
545 static char const xmalloc_overrun_check_trailer
[XMALLOC_OVERRUN_CHECK_SIZE
] =
546 { '\xaa', '\xab', '\xac', '\xad',
547 '\xba', '\xbb', '\xbc', '\xbd',
548 '\xca', '\xcb', '\xcc', '\xcd',
549 '\xda', '\xdb', '\xdc', '\xdd' };
551 /* Insert and extract the block size in the header. */
554 xmalloc_put_size (unsigned char *ptr
, size_t size
)
557 for (i
= 0; i
< XMALLOC_OVERRUN_SIZE_SIZE
; i
++)
559 *--ptr
= size
& ((1 << CHAR_BIT
) - 1);
565 xmalloc_get_size (unsigned char *ptr
)
569 ptr
-= XMALLOC_OVERRUN_SIZE_SIZE
;
570 for (i
= 0; i
< XMALLOC_OVERRUN_SIZE_SIZE
; i
++)
579 /* The call depth in overrun_check functions. For example, this might happen:
581 overrun_check_malloc()
582 -> malloc -> (via hook)_-> emacs_blocked_malloc
583 -> overrun_check_malloc
584 call malloc (hooks are NULL, so real malloc is called).
585 malloc returns 10000.
586 add overhead, return 10016.
587 <- (back in overrun_check_malloc)
588 add overhead again, return 10032
589 xmalloc returns 10032.
594 overrun_check_free(10032)
596 free(10016) <- crash, because 10000 is the original pointer. */
598 static ptrdiff_t check_depth
;
600 /* Like malloc, but wraps allocated block with header and trailer. */
602 static POINTER_TYPE
*
603 overrun_check_malloc (size_t size
)
605 register unsigned char *val
;
606 int overhead
= ++check_depth
== 1 ? XMALLOC_OVERRUN_CHECK_OVERHEAD
: 0;
607 if (SIZE_MAX
- overhead
< size
)
610 val
= (unsigned char *) malloc (size
+ overhead
);
611 if (val
&& check_depth
== 1)
613 memcpy (val
, xmalloc_overrun_check_header
, XMALLOC_OVERRUN_CHECK_SIZE
);
614 val
+= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
615 xmalloc_put_size (val
, size
);
616 memcpy (val
+ size
, xmalloc_overrun_check_trailer
,
617 XMALLOC_OVERRUN_CHECK_SIZE
);
620 return (POINTER_TYPE
*)val
;
624 /* Like realloc, but checks old block for overrun, and wraps new block
625 with header and trailer. */
627 static POINTER_TYPE
*
628 overrun_check_realloc (POINTER_TYPE
*block
, size_t size
)
630 register unsigned char *val
= (unsigned char *) block
;
631 int overhead
= ++check_depth
== 1 ? XMALLOC_OVERRUN_CHECK_OVERHEAD
: 0;
632 if (SIZE_MAX
- overhead
< size
)
637 && memcmp (xmalloc_overrun_check_header
,
638 val
- XMALLOC_OVERRUN_CHECK_SIZE
- XMALLOC_OVERRUN_SIZE_SIZE
,
639 XMALLOC_OVERRUN_CHECK_SIZE
) == 0)
641 size_t osize
= xmalloc_get_size (val
);
642 if (memcmp (xmalloc_overrun_check_trailer
, val
+ osize
,
643 XMALLOC_OVERRUN_CHECK_SIZE
))
645 memset (val
+ osize
, 0, XMALLOC_OVERRUN_CHECK_SIZE
);
646 val
-= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
647 memset (val
, 0, XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
);
650 val
= (unsigned char *) realloc ((POINTER_TYPE
*)val
, size
+ overhead
);
652 if (val
&& check_depth
== 1)
654 memcpy (val
, xmalloc_overrun_check_header
, XMALLOC_OVERRUN_CHECK_SIZE
);
655 val
+= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
656 xmalloc_put_size (val
, size
);
657 memcpy (val
+ size
, xmalloc_overrun_check_trailer
,
658 XMALLOC_OVERRUN_CHECK_SIZE
);
661 return (POINTER_TYPE
*)val
;
664 /* Like free, but checks block for overrun. */
667 overrun_check_free (POINTER_TYPE
*block
)
669 unsigned char *val
= (unsigned char *) block
;
674 && memcmp (xmalloc_overrun_check_header
,
675 val
- XMALLOC_OVERRUN_CHECK_SIZE
- XMALLOC_OVERRUN_SIZE_SIZE
,
676 XMALLOC_OVERRUN_CHECK_SIZE
) == 0)
678 size_t osize
= xmalloc_get_size (val
);
679 if (memcmp (xmalloc_overrun_check_trailer
, val
+ osize
,
680 XMALLOC_OVERRUN_CHECK_SIZE
))
682 #ifdef XMALLOC_CLEAR_FREE_MEMORY
683 val
-= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
684 memset (val
, 0xff, osize
+ XMALLOC_OVERRUN_CHECK_OVERHEAD
);
686 memset (val
+ osize
, 0, XMALLOC_OVERRUN_CHECK_SIZE
);
687 val
-= XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
;
688 memset (val
, 0, XMALLOC_OVERRUN_CHECK_SIZE
+ XMALLOC_OVERRUN_SIZE_SIZE
);
699 #define malloc overrun_check_malloc
700 #define realloc overrun_check_realloc
701 #define free overrun_check_free
705 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
706 there's no need to block input around malloc. */
707 #define MALLOC_BLOCK_INPUT ((void)0)
708 #define MALLOC_UNBLOCK_INPUT ((void)0)
710 #define MALLOC_BLOCK_INPUT BLOCK_INPUT
711 #define MALLOC_UNBLOCK_INPUT UNBLOCK_INPUT
714 /* Like malloc but check for no memory and block interrupt input.. */
717 xmalloc (size_t size
)
719 register POINTER_TYPE
*val
;
722 val
= (POINTER_TYPE
*) malloc (size
);
723 MALLOC_UNBLOCK_INPUT
;
731 /* Like realloc but check for no memory and block interrupt input.. */
734 xrealloc (POINTER_TYPE
*block
, size_t size
)
736 register POINTER_TYPE
*val
;
739 /* We must call malloc explicitly when BLOCK is 0, since some
740 reallocs don't do this. */
742 val
= (POINTER_TYPE
*) malloc (size
);
744 val
= (POINTER_TYPE
*) realloc (block
, size
);
745 MALLOC_UNBLOCK_INPUT
;
753 /* Like free but block interrupt input. */
756 xfree (POINTER_TYPE
*block
)
762 MALLOC_UNBLOCK_INPUT
;
763 /* We don't call refill_memory_reserve here
764 because that duplicates doing so in emacs_blocked_free
765 and the criterion should go there. */
769 /* Other parts of Emacs pass large int values to allocator functions
770 expecting ptrdiff_t. This is portable in practice, but check it to
772 verify (INT_MAX
<= PTRDIFF_MAX
);
775 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
776 Signal an error on memory exhaustion, and block interrupt input. */
779 xnmalloc (ptrdiff_t nitems
, ptrdiff_t item_size
)
781 xassert (0 <= nitems
&& 0 < item_size
);
782 if (min (PTRDIFF_MAX
, SIZE_MAX
) / item_size
< nitems
)
783 memory_full (SIZE_MAX
);
784 return xmalloc (nitems
* item_size
);
788 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
789 Signal an error on memory exhaustion, and block interrupt input. */
792 xnrealloc (void *pa
, ptrdiff_t nitems
, ptrdiff_t item_size
)
794 xassert (0 <= nitems
&& 0 < item_size
);
795 if (min (PTRDIFF_MAX
, SIZE_MAX
) / item_size
< nitems
)
796 memory_full (SIZE_MAX
);
797 return xrealloc (pa
, nitems
* item_size
);
801 /* Grow PA, which points to an array of *NITEMS items, and return the
802 location of the reallocated array, updating *NITEMS to reflect its
803 new size. The new array will contain at least NITEMS_INCR_MIN more
804 items, but will not contain more than NITEMS_MAX items total.
805 ITEM_SIZE is the size of each item, in bytes.
807 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
808 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
811 If PA is null, then allocate a new array instead of reallocating
812 the old one. Thus, to grow an array A without saving its old
813 contents, invoke xfree (A) immediately followed by xgrowalloc (0,
816 Block interrupt input as needed. If memory exhaustion occurs, set
817 *NITEMS to zero if PA is null, and signal an error (i.e., do not
821 xpalloc (void *pa
, ptrdiff_t *nitems
, ptrdiff_t nitems_incr_min
,
822 ptrdiff_t nitems_max
, ptrdiff_t item_size
)
824 /* The approximate size to use for initial small allocation
825 requests. This is the largest "small" request for the GNU C
827 enum { DEFAULT_MXFAST
= 64 * sizeof (size_t) / 4 };
829 /* If the array is tiny, grow it to about (but no greater than)
830 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%. */
831 ptrdiff_t n
= *nitems
;
832 ptrdiff_t tiny_max
= DEFAULT_MXFAST
/ item_size
- n
;
833 ptrdiff_t half_again
= n
>> 1;
834 ptrdiff_t incr_estimate
= max (tiny_max
, half_again
);
836 /* Adjust the increment according to three constraints: NITEMS_INCR_MIN,
837 NITEMS_MAX, and what the C language can represent safely. */
838 ptrdiff_t C_language_max
= min (PTRDIFF_MAX
, SIZE_MAX
) / item_size
;
839 ptrdiff_t n_max
= (0 <= nitems_max
&& nitems_max
< C_language_max
840 ? nitems_max
: C_language_max
);
841 ptrdiff_t nitems_incr_max
= n_max
- n
;
842 ptrdiff_t incr
= max (nitems_incr_min
, min (incr_estimate
, nitems_incr_max
));
844 xassert (0 < item_size
&& 0 < nitems_incr_min
&& 0 <= n
&& -1 <= nitems_max
);
847 if (nitems_incr_max
< incr
)
848 memory_full (SIZE_MAX
);
850 pa
= xrealloc (pa
, n
* item_size
);
856 /* Like strdup, but uses xmalloc. */
859 xstrdup (const char *s
)
861 size_t len
= strlen (s
) + 1;
862 char *p
= (char *) xmalloc (len
);
868 /* Unwind for SAFE_ALLOCA */
871 safe_alloca_unwind (Lisp_Object arg
)
873 register struct Lisp_Save_Value
*p
= XSAVE_VALUE (arg
);
883 /* Like malloc but used for allocating Lisp data. NBYTES is the
884 number of bytes to allocate, TYPE describes the intended use of the
885 allocated memory block (for strings, for conses, ...). */
888 static void *lisp_malloc_loser
;
891 static POINTER_TYPE
*
892 lisp_malloc (size_t nbytes
, enum mem_type type
)
898 #ifdef GC_MALLOC_CHECK
899 allocated_mem_type
= type
;
902 val
= (void *) malloc (nbytes
);
905 /* If the memory just allocated cannot be addressed thru a Lisp
906 object's pointer, and it needs to be,
907 that's equivalent to running out of memory. */
908 if (val
&& type
!= MEM_TYPE_NON_LISP
)
911 XSETCONS (tem
, (char *) val
+ nbytes
- 1);
912 if ((char *) XCONS (tem
) != (char *) val
+ nbytes
- 1)
914 lisp_malloc_loser
= val
;
921 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
922 if (val
&& type
!= MEM_TYPE_NON_LISP
)
923 mem_insert (val
, (char *) val
+ nbytes
, type
);
926 MALLOC_UNBLOCK_INPUT
;
928 memory_full (nbytes
);
932 /* Free BLOCK. This must be called to free memory allocated with a
933 call to lisp_malloc. */
936 lisp_free (POINTER_TYPE
*block
)
940 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
941 mem_delete (mem_find (block
));
943 MALLOC_UNBLOCK_INPUT
;
946 /***** Allocation of aligned blocks of memory to store Lisp data. *****/
948 /* The entry point is lisp_align_malloc which returns blocks of at most
949 BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
951 #if defined (HAVE_POSIX_MEMALIGN) && defined (SYSTEM_MALLOC)
952 #define USE_POSIX_MEMALIGN 1
955 /* BLOCK_ALIGN has to be a power of 2. */
956 #define BLOCK_ALIGN (1 << 10)
958 /* Padding to leave at the end of a malloc'd block. This is to give
959 malloc a chance to minimize the amount of memory wasted to alignment.
960 It should be tuned to the particular malloc library used.
961 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
962 posix_memalign on the other hand would ideally prefer a value of 4
963 because otherwise, there's 1020 bytes wasted between each ablocks.
964 In Emacs, testing shows that those 1020 can most of the time be
965 efficiently used by malloc to place other objects, so a value of 0 can
966 still preferable unless you have a lot of aligned blocks and virtually
968 #define BLOCK_PADDING 0
969 #define BLOCK_BYTES \
970 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
972 /* Internal data structures and constants. */
974 #define ABLOCKS_SIZE 16
976 /* An aligned block of memory. */
981 char payload
[BLOCK_BYTES
];
982 struct ablock
*next_free
;
984 /* `abase' is the aligned base of the ablocks. */
985 /* It is overloaded to hold the virtual `busy' field that counts
986 the number of used ablock in the parent ablocks.
987 The first ablock has the `busy' field, the others have the `abase'
988 field. To tell the difference, we assume that pointers will have
989 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
990 is used to tell whether the real base of the parent ablocks is `abase'
991 (if not, the word before the first ablock holds a pointer to the
993 struct ablocks
*abase
;
994 /* The padding of all but the last ablock is unused. The padding of
995 the last ablock in an ablocks is not allocated. */
997 char padding
[BLOCK_PADDING
];
1001 /* A bunch of consecutive aligned blocks. */
1004 struct ablock blocks
[ABLOCKS_SIZE
];
1007 /* Size of the block requested from malloc or posix_memalign. */
1008 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
1010 #define ABLOCK_ABASE(block) \
1011 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
1012 ? (struct ablocks *)(block) \
1015 /* Virtual `busy' field. */
1016 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
1018 /* Pointer to the (not necessarily aligned) malloc block. */
1019 #ifdef USE_POSIX_MEMALIGN
1020 #define ABLOCKS_BASE(abase) (abase)
1022 #define ABLOCKS_BASE(abase) \
1023 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void**)abase)[-1])
1026 /* The list of free ablock. */
1027 static struct ablock
*free_ablock
;
1029 /* Allocate an aligned block of nbytes.
1030 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
1031 smaller or equal to BLOCK_BYTES. */
1032 static POINTER_TYPE
*
1033 lisp_align_malloc (size_t nbytes
, enum mem_type type
)
1036 struct ablocks
*abase
;
1038 eassert (nbytes
<= BLOCK_BYTES
);
1042 #ifdef GC_MALLOC_CHECK
1043 allocated_mem_type
= type
;
1049 intptr_t aligned
; /* int gets warning casting to 64-bit pointer. */
1051 #ifdef DOUG_LEA_MALLOC
1052 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1053 because mapped region contents are not preserved in
1055 mallopt (M_MMAP_MAX
, 0);
1058 #ifdef USE_POSIX_MEMALIGN
1060 int err
= posix_memalign (&base
, BLOCK_ALIGN
, ABLOCKS_BYTES
);
1066 base
= malloc (ABLOCKS_BYTES
);
1067 abase
= ALIGN (base
, BLOCK_ALIGN
);
1072 MALLOC_UNBLOCK_INPUT
;
1073 memory_full (ABLOCKS_BYTES
);
1076 aligned
= (base
== abase
);
1078 ((void**)abase
)[-1] = base
;
1080 #ifdef DOUG_LEA_MALLOC
1081 /* Back to a reasonable maximum of mmap'ed areas. */
1082 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
);
1086 /* If the memory just allocated cannot be addressed thru a Lisp
1087 object's pointer, and it needs to be, that's equivalent to
1088 running out of memory. */
1089 if (type
!= MEM_TYPE_NON_LISP
)
1092 char *end
= (char *) base
+ ABLOCKS_BYTES
- 1;
1093 XSETCONS (tem
, end
);
1094 if ((char *) XCONS (tem
) != end
)
1096 lisp_malloc_loser
= base
;
1098 MALLOC_UNBLOCK_INPUT
;
1099 memory_full (SIZE_MAX
);
1104 /* Initialize the blocks and put them on the free list.
1105 If `base' was not properly aligned, we can't use the last block. */
1106 for (i
= 0; i
< (aligned
? ABLOCKS_SIZE
: ABLOCKS_SIZE
- 1); i
++)
1108 abase
->blocks
[i
].abase
= abase
;
1109 abase
->blocks
[i
].x
.next_free
= free_ablock
;
1110 free_ablock
= &abase
->blocks
[i
];
1112 ABLOCKS_BUSY (abase
) = (struct ablocks
*) aligned
;
1114 eassert (0 == ((uintptr_t) abase
) % BLOCK_ALIGN
);
1115 eassert (ABLOCK_ABASE (&abase
->blocks
[3]) == abase
); /* 3 is arbitrary */
1116 eassert (ABLOCK_ABASE (&abase
->blocks
[0]) == abase
);
1117 eassert (ABLOCKS_BASE (abase
) == base
);
1118 eassert (aligned
== (intptr_t) ABLOCKS_BUSY (abase
));
1121 abase
= ABLOCK_ABASE (free_ablock
);
1122 ABLOCKS_BUSY (abase
) =
1123 (struct ablocks
*) (2 + (intptr_t) ABLOCKS_BUSY (abase
));
1125 free_ablock
= free_ablock
->x
.next_free
;
1127 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1128 if (type
!= MEM_TYPE_NON_LISP
)
1129 mem_insert (val
, (char *) val
+ nbytes
, type
);
1132 MALLOC_UNBLOCK_INPUT
;
1134 eassert (0 == ((uintptr_t) val
) % BLOCK_ALIGN
);
1139 lisp_align_free (POINTER_TYPE
*block
)
1141 struct ablock
*ablock
= block
;
1142 struct ablocks
*abase
= ABLOCK_ABASE (ablock
);
1145 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1146 mem_delete (mem_find (block
));
1148 /* Put on free list. */
1149 ablock
->x
.next_free
= free_ablock
;
1150 free_ablock
= ablock
;
1151 /* Update busy count. */
1152 ABLOCKS_BUSY (abase
)
1153 = (struct ablocks
*) (-2 + (intptr_t) ABLOCKS_BUSY (abase
));
1155 if (2 > (intptr_t) ABLOCKS_BUSY (abase
))
1156 { /* All the blocks are free. */
1157 int i
= 0, aligned
= (intptr_t) ABLOCKS_BUSY (abase
);
1158 struct ablock
**tem
= &free_ablock
;
1159 struct ablock
*atop
= &abase
->blocks
[aligned
? ABLOCKS_SIZE
: ABLOCKS_SIZE
- 1];
1163 if (*tem
>= (struct ablock
*) abase
&& *tem
< atop
)
1166 *tem
= (*tem
)->x
.next_free
;
1169 tem
= &(*tem
)->x
.next_free
;
1171 eassert ((aligned
& 1) == aligned
);
1172 eassert (i
== (aligned
? ABLOCKS_SIZE
: ABLOCKS_SIZE
- 1));
1173 #ifdef USE_POSIX_MEMALIGN
1174 eassert ((uintptr_t) ABLOCKS_BASE (abase
) % BLOCK_ALIGN
== 0);
1176 free (ABLOCKS_BASE (abase
));
1178 MALLOC_UNBLOCK_INPUT
;
1181 /* Return a new buffer structure allocated from the heap with
1182 a call to lisp_malloc. */
1185 allocate_buffer (void)
1188 = (struct buffer
*) lisp_malloc (sizeof (struct buffer
),
1190 XSETPVECTYPESIZE (b
, PVEC_BUFFER
,
1191 ((sizeof (struct buffer
) + sizeof (EMACS_INT
) - 1)
1192 / sizeof (EMACS_INT
)));
1197 #ifndef SYSTEM_MALLOC
1199 /* Arranging to disable input signals while we're in malloc.
1201 This only works with GNU malloc. To help out systems which can't
1202 use GNU malloc, all the calls to malloc, realloc, and free
1203 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
1204 pair; unfortunately, we have no idea what C library functions
1205 might call malloc, so we can't really protect them unless you're
1206 using GNU malloc. Fortunately, most of the major operating systems
1207 can use GNU malloc. */
1210 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
1211 there's no need to block input around malloc. */
1213 #ifndef DOUG_LEA_MALLOC
1214 extern void * (*__malloc_hook
) (size_t, const void *);
1215 extern void * (*__realloc_hook
) (void *, size_t, const void *);
1216 extern void (*__free_hook
) (void *, const void *);
1217 /* Else declared in malloc.h, perhaps with an extra arg. */
1218 #endif /* DOUG_LEA_MALLOC */
1219 static void * (*old_malloc_hook
) (size_t, const void *);
1220 static void * (*old_realloc_hook
) (void *, size_t, const void*);
1221 static void (*old_free_hook
) (void*, const void*);
1223 #ifdef DOUG_LEA_MALLOC
1224 # define BYTES_USED (mallinfo ().uordblks)
1226 # define BYTES_USED _bytes_used
1229 #ifdef GC_MALLOC_CHECK
1230 static int dont_register_blocks
;
1233 static size_t bytes_used_when_reconsidered
;
1235 /* Value of _bytes_used, when spare_memory was freed. */
1237 static size_t bytes_used_when_full
;
1239 /* This function is used as the hook for free to call. */
1242 emacs_blocked_free (void *ptr
, const void *ptr2
)
1246 #ifdef GC_MALLOC_CHECK
1252 if (m
== MEM_NIL
|| m
->start
!= ptr
)
1255 "Freeing `%p' which wasn't allocated with malloc\n", ptr
);
1260 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
1264 #endif /* GC_MALLOC_CHECK */
1266 __free_hook
= old_free_hook
;
1269 /* If we released our reserve (due to running out of memory),
1270 and we have a fair amount free once again,
1271 try to set aside another reserve in case we run out once more. */
1272 if (! NILP (Vmemory_full
)
1273 /* Verify there is enough space that even with the malloc
1274 hysteresis this call won't run out again.
1275 The code here is correct as long as SPARE_MEMORY
1276 is substantially larger than the block size malloc uses. */
1277 && (bytes_used_when_full
1278 > ((bytes_used_when_reconsidered
= BYTES_USED
)
1279 + max (malloc_hysteresis
, 4) * SPARE_MEMORY
)))
1280 refill_memory_reserve ();
1282 __free_hook
= emacs_blocked_free
;
1283 UNBLOCK_INPUT_ALLOC
;
1287 /* This function is the malloc hook that Emacs uses. */
1290 emacs_blocked_malloc (size_t size
, const void *ptr
)
1295 __malloc_hook
= old_malloc_hook
;
1296 #ifdef DOUG_LEA_MALLOC
1297 /* Segfaults on my system. --lorentey */
1298 /* mallopt (M_TOP_PAD, malloc_hysteresis * 4096); */
1300 __malloc_extra_blocks
= malloc_hysteresis
;
1303 value
= (void *) malloc (size
);
1305 #ifdef GC_MALLOC_CHECK
1307 struct mem_node
*m
= mem_find (value
);
1310 fprintf (stderr
, "Malloc returned %p which is already in use\n",
1312 fprintf (stderr
, "Region in use is %p...%p, %u bytes, type %d\n",
1313 m
->start
, m
->end
, (char *) m
->end
- (char *) m
->start
,
1318 if (!dont_register_blocks
)
1320 mem_insert (value
, (char *) value
+ max (1, size
), allocated_mem_type
);
1321 allocated_mem_type
= MEM_TYPE_NON_LISP
;
1324 #endif /* GC_MALLOC_CHECK */
1326 __malloc_hook
= emacs_blocked_malloc
;
1327 UNBLOCK_INPUT_ALLOC
;
1329 /* fprintf (stderr, "%p malloc\n", value); */
1334 /* This function is the realloc hook that Emacs uses. */
1337 emacs_blocked_realloc (void *ptr
, size_t size
, const void *ptr2
)
1342 __realloc_hook
= old_realloc_hook
;
1344 #ifdef GC_MALLOC_CHECK
1347 struct mem_node
*m
= mem_find (ptr
);
1348 if (m
== MEM_NIL
|| m
->start
!= ptr
)
1351 "Realloc of %p which wasn't allocated with malloc\n",
1359 /* fprintf (stderr, "%p -> realloc\n", ptr); */
1361 /* Prevent malloc from registering blocks. */
1362 dont_register_blocks
= 1;
1363 #endif /* GC_MALLOC_CHECK */
1365 value
= (void *) realloc (ptr
, size
);
1367 #ifdef GC_MALLOC_CHECK
1368 dont_register_blocks
= 0;
1371 struct mem_node
*m
= mem_find (value
);
1374 fprintf (stderr
, "Realloc returns memory that is already in use\n");
1378 /* Can't handle zero size regions in the red-black tree. */
1379 mem_insert (value
, (char *) value
+ max (size
, 1), MEM_TYPE_NON_LISP
);
1382 /* fprintf (stderr, "%p <- realloc\n", value); */
1383 #endif /* GC_MALLOC_CHECK */
1385 __realloc_hook
= emacs_blocked_realloc
;
1386 UNBLOCK_INPUT_ALLOC
;
1393 /* Called from Fdump_emacs so that when the dumped Emacs starts, it has a
1394 normal malloc. Some thread implementations need this as they call
1395 malloc before main. The pthread_self call in BLOCK_INPUT_ALLOC then
1396 calls malloc because it is the first call, and we have an endless loop. */
1399 reset_malloc_hooks (void)
1401 __free_hook
= old_free_hook
;
1402 __malloc_hook
= old_malloc_hook
;
1403 __realloc_hook
= old_realloc_hook
;
1405 #endif /* HAVE_PTHREAD */
1408 /* Called from main to set up malloc to use our hooks. */
1411 uninterrupt_malloc (void)
1414 #ifdef DOUG_LEA_MALLOC
1415 pthread_mutexattr_t attr
;
1417 /* GLIBC has a faster way to do this, but let's keep it portable.
1418 This is according to the Single UNIX Specification. */
1419 pthread_mutexattr_init (&attr
);
1420 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
1421 pthread_mutex_init (&alloc_mutex
, &attr
);
1422 #else /* !DOUG_LEA_MALLOC */
1423 /* Some systems such as Solaris 2.6 don't have a recursive mutex,
1424 and the bundled gmalloc.c doesn't require it. */
1425 pthread_mutex_init (&alloc_mutex
, NULL
);
1426 #endif /* !DOUG_LEA_MALLOC */
1427 #endif /* HAVE_PTHREAD */
1429 if (__free_hook
!= emacs_blocked_free
)
1430 old_free_hook
= __free_hook
;
1431 __free_hook
= emacs_blocked_free
;
1433 if (__malloc_hook
!= emacs_blocked_malloc
)
1434 old_malloc_hook
= __malloc_hook
;
1435 __malloc_hook
= emacs_blocked_malloc
;
1437 if (__realloc_hook
!= emacs_blocked_realloc
)
1438 old_realloc_hook
= __realloc_hook
;
1439 __realloc_hook
= emacs_blocked_realloc
;
1442 #endif /* not SYNC_INPUT */
1443 #endif /* not SYSTEM_MALLOC */
1447 /***********************************************************************
1449 ***********************************************************************/
1451 /* Number of intervals allocated in an interval_block structure.
1452 The 1020 is 1024 minus malloc overhead. */
1454 #define INTERVAL_BLOCK_SIZE \
1455 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1457 /* Intervals are allocated in chunks in form of an interval_block
1460 struct interval_block
1462 /* Place `intervals' first, to preserve alignment. */
1463 struct interval intervals
[INTERVAL_BLOCK_SIZE
];
1464 struct interval_block
*next
;
1467 /* Current interval block. Its `next' pointer points to older
1470 static struct interval_block
*interval_block
;
1472 /* Index in interval_block above of the next unused interval
1475 static int interval_block_index
;
1477 /* Number of free and live intervals. */
1479 static EMACS_INT total_free_intervals
, total_intervals
;
1481 /* List of free intervals. */
1483 static INTERVAL interval_free_list
;
1486 /* Initialize interval allocation. */
1489 init_intervals (void)
1491 interval_block
= NULL
;
1492 interval_block_index
= INTERVAL_BLOCK_SIZE
;
1493 interval_free_list
= 0;
1497 /* Return a new interval. */
1500 make_interval (void)
1504 /* eassert (!handling_signal); */
1508 if (interval_free_list
)
1510 val
= interval_free_list
;
1511 interval_free_list
= INTERVAL_PARENT (interval_free_list
);
1515 if (interval_block_index
== INTERVAL_BLOCK_SIZE
)
1517 register struct interval_block
*newi
;
1519 newi
= (struct interval_block
*) lisp_malloc (sizeof *newi
,
1522 newi
->next
= interval_block
;
1523 interval_block
= newi
;
1524 interval_block_index
= 0;
1526 val
= &interval_block
->intervals
[interval_block_index
++];
1529 MALLOC_UNBLOCK_INPUT
;
1531 consing_since_gc
+= sizeof (struct interval
);
1533 RESET_INTERVAL (val
);
1539 /* Mark Lisp objects in interval I. */
1542 mark_interval (register INTERVAL i
, Lisp_Object dummy
)
1544 eassert (!i
->gcmarkbit
); /* Intervals are never shared. */
1546 mark_object (i
->plist
);
1550 /* Mark the interval tree rooted in TREE. Don't call this directly;
1551 use the macro MARK_INTERVAL_TREE instead. */
1554 mark_interval_tree (register INTERVAL tree
)
1556 /* No need to test if this tree has been marked already; this
1557 function is always called through the MARK_INTERVAL_TREE macro,
1558 which takes care of that. */
1560 traverse_intervals_noorder (tree
, mark_interval
, Qnil
);
1564 /* Mark the interval tree rooted in I. */
1566 #define MARK_INTERVAL_TREE(i) \
1568 if (!NULL_INTERVAL_P (i) && !i->gcmarkbit) \
1569 mark_interval_tree (i); \
1573 #define UNMARK_BALANCE_INTERVALS(i) \
1575 if (! NULL_INTERVAL_P (i)) \
1576 (i) = balance_intervals (i); \
1580 /* Number support. If USE_LISP_UNION_TYPE is in effect, we
1581 can't create number objects in macros. */
1584 make_number (EMACS_INT n
)
1588 obj
.s
.type
= Lisp_Int
;
1593 /* Convert the pointer-sized word P to EMACS_INT while preserving its
1594 type and ptr fields. */
1596 widen_to_Lisp_Object (void *p
)
1598 intptr_t i
= (intptr_t) p
;
1599 #ifdef USE_LISP_UNION_TYPE
1608 /***********************************************************************
1610 ***********************************************************************/
1612 /* Lisp_Strings are allocated in string_block structures. When a new
1613 string_block is allocated, all the Lisp_Strings it contains are
1614 added to a free-list string_free_list. When a new Lisp_String is
1615 needed, it is taken from that list. During the sweep phase of GC,
1616 string_blocks that are entirely free are freed, except two which
1619 String data is allocated from sblock structures. Strings larger
1620 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1621 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1623 Sblocks consist internally of sdata structures, one for each
1624 Lisp_String. The sdata structure points to the Lisp_String it
1625 belongs to. The Lisp_String points back to the `u.data' member of
1626 its sdata structure.
1628 When a Lisp_String is freed during GC, it is put back on
1629 string_free_list, and its `data' member and its sdata's `string'
1630 pointer is set to null. The size of the string is recorded in the
1631 `u.nbytes' member of the sdata. So, sdata structures that are no
1632 longer used, can be easily recognized, and it's easy to compact the
1633 sblocks of small strings which we do in compact_small_strings. */
1635 /* Size in bytes of an sblock structure used for small strings. This
1636 is 8192 minus malloc overhead. */
1638 #define SBLOCK_SIZE 8188
1640 /* Strings larger than this are considered large strings. String data
1641 for large strings is allocated from individual sblocks. */
1643 #define LARGE_STRING_BYTES 1024
1645 /* Structure describing string memory sub-allocated from an sblock.
1646 This is where the contents of Lisp strings are stored. */
1650 /* Back-pointer to the string this sdata belongs to. If null, this
1651 structure is free, and the NBYTES member of the union below
1652 contains the string's byte size (the same value that STRING_BYTES
1653 would return if STRING were non-null). If non-null, STRING_BYTES
1654 (STRING) is the size of the data, and DATA contains the string's
1656 struct Lisp_String
*string
;
1658 #ifdef GC_CHECK_STRING_BYTES
1661 unsigned char data
[1];
1663 #define SDATA_NBYTES(S) (S)->nbytes
1664 #define SDATA_DATA(S) (S)->data
1665 #define SDATA_SELECTOR(member) member
1667 #else /* not GC_CHECK_STRING_BYTES */
1671 /* When STRING is non-null. */
1672 unsigned char data
[1];
1674 /* When STRING is null. */
1678 #define SDATA_NBYTES(S) (S)->u.nbytes
1679 #define SDATA_DATA(S) (S)->u.data
1680 #define SDATA_SELECTOR(member) u.member
1682 #endif /* not GC_CHECK_STRING_BYTES */
1684 #define SDATA_DATA_OFFSET offsetof (struct sdata, SDATA_SELECTOR (data))
1688 /* Structure describing a block of memory which is sub-allocated to
1689 obtain string data memory for strings. Blocks for small strings
1690 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1691 as large as needed. */
1696 struct sblock
*next
;
1698 /* Pointer to the next free sdata block. This points past the end
1699 of the sblock if there isn't any space left in this block. */
1700 struct sdata
*next_free
;
1702 /* Start of data. */
1703 struct sdata first_data
;
1706 /* Number of Lisp strings in a string_block structure. The 1020 is
1707 1024 minus malloc overhead. */
1709 #define STRING_BLOCK_SIZE \
1710 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1712 /* Structure describing a block from which Lisp_String structures
1717 /* Place `strings' first, to preserve alignment. */
1718 struct Lisp_String strings
[STRING_BLOCK_SIZE
];
1719 struct string_block
*next
;
1722 /* Head and tail of the list of sblock structures holding Lisp string
1723 data. We always allocate from current_sblock. The NEXT pointers
1724 in the sblock structures go from oldest_sblock to current_sblock. */
1726 static struct sblock
*oldest_sblock
, *current_sblock
;
1728 /* List of sblocks for large strings. */
1730 static struct sblock
*large_sblocks
;
1732 /* List of string_block structures. */
1734 static struct string_block
*string_blocks
;
1736 /* Free-list of Lisp_Strings. */
1738 static struct Lisp_String
*string_free_list
;
1740 /* Number of live and free Lisp_Strings. */
1742 static EMACS_INT total_strings
, total_free_strings
;
1744 /* Number of bytes used by live strings. */
1746 static EMACS_INT total_string_size
;
1748 /* Given a pointer to a Lisp_String S which is on the free-list
1749 string_free_list, return a pointer to its successor in the
1752 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1754 /* Return a pointer to the sdata structure belonging to Lisp string S.
1755 S must be live, i.e. S->data must not be null. S->data is actually
1756 a pointer to the `u.data' member of its sdata structure; the
1757 structure starts at a constant offset in front of that. */
1759 #define SDATA_OF_STRING(S) ((struct sdata *) ((S)->data - SDATA_DATA_OFFSET))
1762 #ifdef GC_CHECK_STRING_OVERRUN
1764 /* We check for overrun in string data blocks by appending a small
1765 "cookie" after each allocated string data block, and check for the
1766 presence of this cookie during GC. */
1768 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1769 static char const string_overrun_cookie
[GC_STRING_OVERRUN_COOKIE_SIZE
] =
1770 { '\xde', '\xad', '\xbe', '\xef' };
1773 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1776 /* Value is the size of an sdata structure large enough to hold NBYTES
1777 bytes of string data. The value returned includes a terminating
1778 NUL byte, the size of the sdata structure, and padding. */
1780 #ifdef GC_CHECK_STRING_BYTES
1782 #define SDATA_SIZE(NBYTES) \
1783 ((SDATA_DATA_OFFSET \
1785 + sizeof (EMACS_INT) - 1) \
1786 & ~(sizeof (EMACS_INT) - 1))
1788 #else /* not GC_CHECK_STRING_BYTES */
1790 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1791 less than the size of that member. The 'max' is not needed when
1792 SDATA_DATA_OFFSET is a multiple of sizeof (EMACS_INT), because then the
1793 alignment code reserves enough space. */
1795 #define SDATA_SIZE(NBYTES) \
1796 ((SDATA_DATA_OFFSET \
1797 + (SDATA_DATA_OFFSET % sizeof (EMACS_INT) == 0 \
1799 : max (NBYTES, sizeof (EMACS_INT) - 1)) \
1801 + sizeof (EMACS_INT) - 1) \
1802 & ~(sizeof (EMACS_INT) - 1))
1804 #endif /* not GC_CHECK_STRING_BYTES */
1806 /* Extra bytes to allocate for each string. */
1808 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1810 /* Exact bound on the number of bytes in a string, not counting the
1811 terminating null. A string cannot contain more bytes than
1812 STRING_BYTES_BOUND, nor can it be so long that the size_t
1813 arithmetic in allocate_string_data would overflow while it is
1814 calculating a value to be passed to malloc. */
1815 #define STRING_BYTES_MAX \
1816 min (STRING_BYTES_BOUND, \
1817 ((SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD \
1819 - offsetof (struct sblock, first_data) \
1820 - SDATA_DATA_OFFSET) \
1821 & ~(sizeof (EMACS_INT) - 1)))
1823 /* Initialize string allocation. Called from init_alloc_once. */
1828 total_strings
= total_free_strings
= total_string_size
= 0;
1829 oldest_sblock
= current_sblock
= large_sblocks
= NULL
;
1830 string_blocks
= NULL
;
1831 string_free_list
= NULL
;
1832 empty_unibyte_string
= make_pure_string ("", 0, 0, 0);
1833 empty_multibyte_string
= make_pure_string ("", 0, 0, 1);
1837 #ifdef GC_CHECK_STRING_BYTES
1839 static int check_string_bytes_count
;
1841 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1844 /* Like GC_STRING_BYTES, but with debugging check. */
1847 string_bytes (struct Lisp_String
*s
)
1850 (s
->size_byte
< 0 ? s
->size
& ~ARRAY_MARK_FLAG
: s
->size_byte
);
1852 if (!PURE_POINTER_P (s
)
1854 && nbytes
!= SDATA_NBYTES (SDATA_OF_STRING (s
)))
1859 /* Check validity of Lisp strings' string_bytes member in B. */
1862 check_sblock (struct sblock
*b
)
1864 struct sdata
*from
, *end
, *from_end
;
1868 for (from
= &b
->first_data
; from
< end
; from
= from_end
)
1870 /* Compute the next FROM here because copying below may
1871 overwrite data we need to compute it. */
1874 /* Check that the string size recorded in the string is the
1875 same as the one recorded in the sdata structure. */
1877 CHECK_STRING_BYTES (from
->string
);
1880 nbytes
= GC_STRING_BYTES (from
->string
);
1882 nbytes
= SDATA_NBYTES (from
);
1884 nbytes
= SDATA_SIZE (nbytes
);
1885 from_end
= (struct sdata
*) ((char *) from
+ nbytes
+ GC_STRING_EXTRA
);
1890 /* Check validity of Lisp strings' string_bytes member. ALL_P
1891 non-zero means check all strings, otherwise check only most
1892 recently allocated strings. Used for hunting a bug. */
1895 check_string_bytes (int all_p
)
1901 for (b
= large_sblocks
; b
; b
= b
->next
)
1903 struct Lisp_String
*s
= b
->first_data
.string
;
1905 CHECK_STRING_BYTES (s
);
1908 for (b
= oldest_sblock
; b
; b
= b
->next
)
1912 check_sblock (current_sblock
);
1915 #endif /* GC_CHECK_STRING_BYTES */
1917 #ifdef GC_CHECK_STRING_FREE_LIST
1919 /* Walk through the string free list looking for bogus next pointers.
1920 This may catch buffer overrun from a previous string. */
1923 check_string_free_list (void)
1925 struct Lisp_String
*s
;
1927 /* Pop a Lisp_String off the free-list. */
1928 s
= string_free_list
;
1931 if ((uintptr_t) s
< 1024)
1933 s
= NEXT_FREE_LISP_STRING (s
);
1937 #define check_string_free_list()
1940 /* Return a new Lisp_String. */
1942 static struct Lisp_String
*
1943 allocate_string (void)
1945 struct Lisp_String
*s
;
1947 /* eassert (!handling_signal); */
1951 /* If the free-list is empty, allocate a new string_block, and
1952 add all the Lisp_Strings in it to the free-list. */
1953 if (string_free_list
== NULL
)
1955 struct string_block
*b
;
1958 b
= (struct string_block
*) lisp_malloc (sizeof *b
, MEM_TYPE_STRING
);
1959 memset (b
, 0, sizeof *b
);
1960 b
->next
= string_blocks
;
1963 for (i
= STRING_BLOCK_SIZE
- 1; i
>= 0; --i
)
1966 NEXT_FREE_LISP_STRING (s
) = string_free_list
;
1967 string_free_list
= s
;
1970 total_free_strings
+= STRING_BLOCK_SIZE
;
1973 check_string_free_list ();
1975 /* Pop a Lisp_String off the free-list. */
1976 s
= string_free_list
;
1977 string_free_list
= NEXT_FREE_LISP_STRING (s
);
1979 MALLOC_UNBLOCK_INPUT
;
1981 /* Probably not strictly necessary, but play it safe. */
1982 memset (s
, 0, sizeof *s
);
1984 --total_free_strings
;
1987 consing_since_gc
+= sizeof *s
;
1989 #ifdef GC_CHECK_STRING_BYTES
1990 if (!noninteractive
)
1992 if (++check_string_bytes_count
== 200)
1994 check_string_bytes_count
= 0;
1995 check_string_bytes (1);
1998 check_string_bytes (0);
2000 #endif /* GC_CHECK_STRING_BYTES */
2006 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
2007 plus a NUL byte at the end. Allocate an sdata structure for S, and
2008 set S->data to its `u.data' member. Store a NUL byte at the end of
2009 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
2010 S->data if it was initially non-null. */
2013 allocate_string_data (struct Lisp_String
*s
,
2014 EMACS_INT nchars
, EMACS_INT nbytes
)
2016 struct sdata
*data
, *old_data
;
2018 EMACS_INT needed
, old_nbytes
;
2020 if (STRING_BYTES_MAX
< nbytes
)
2023 /* Determine the number of bytes needed to store NBYTES bytes
2025 needed
= SDATA_SIZE (nbytes
);
2026 old_data
= s
->data
? SDATA_OF_STRING (s
) : NULL
;
2027 old_nbytes
= GC_STRING_BYTES (s
);
2031 if (nbytes
> LARGE_STRING_BYTES
)
2033 size_t size
= offsetof (struct sblock
, first_data
) + needed
;
2035 #ifdef DOUG_LEA_MALLOC
2036 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2037 because mapped region contents are not preserved in
2040 In case you think of allowing it in a dumped Emacs at the
2041 cost of not being able to re-dump, there's another reason:
2042 mmap'ed data typically have an address towards the top of the
2043 address space, which won't fit into an EMACS_INT (at least on
2044 32-bit systems with the current tagging scheme). --fx */
2045 mallopt (M_MMAP_MAX
, 0);
2048 b
= (struct sblock
*) lisp_malloc (size
+ GC_STRING_EXTRA
, MEM_TYPE_NON_LISP
);
2050 #ifdef DOUG_LEA_MALLOC
2051 /* Back to a reasonable maximum of mmap'ed areas. */
2052 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
);
2055 b
->next_free
= &b
->first_data
;
2056 b
->first_data
.string
= NULL
;
2057 b
->next
= large_sblocks
;
2060 else if (current_sblock
== NULL
2061 || (((char *) current_sblock
+ SBLOCK_SIZE
2062 - (char *) current_sblock
->next_free
)
2063 < (needed
+ GC_STRING_EXTRA
)))
2065 /* Not enough room in the current sblock. */
2066 b
= (struct sblock
*) lisp_malloc (SBLOCK_SIZE
, MEM_TYPE_NON_LISP
);
2067 b
->next_free
= &b
->first_data
;
2068 b
->first_data
.string
= NULL
;
2072 current_sblock
->next
= b
;
2080 data
= b
->next_free
;
2081 b
->next_free
= (struct sdata
*) ((char *) data
+ needed
+ GC_STRING_EXTRA
);
2083 MALLOC_UNBLOCK_INPUT
;
2086 s
->data
= SDATA_DATA (data
);
2087 #ifdef GC_CHECK_STRING_BYTES
2088 SDATA_NBYTES (data
) = nbytes
;
2091 s
->size_byte
= nbytes
;
2092 s
->data
[nbytes
] = '\0';
2093 #ifdef GC_CHECK_STRING_OVERRUN
2094 memcpy ((char *) data
+ needed
, string_overrun_cookie
,
2095 GC_STRING_OVERRUN_COOKIE_SIZE
);
2098 /* If S had already data assigned, mark that as free by setting its
2099 string back-pointer to null, and recording the size of the data
2103 SDATA_NBYTES (old_data
) = old_nbytes
;
2104 old_data
->string
= NULL
;
2107 consing_since_gc
+= needed
;
2111 /* Sweep and compact strings. */
2114 sweep_strings (void)
2116 struct string_block
*b
, *next
;
2117 struct string_block
*live_blocks
= NULL
;
2119 string_free_list
= NULL
;
2120 total_strings
= total_free_strings
= 0;
2121 total_string_size
= 0;
2123 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
2124 for (b
= string_blocks
; b
; b
= next
)
2127 struct Lisp_String
*free_list_before
= string_free_list
;
2131 for (i
= 0; i
< STRING_BLOCK_SIZE
; ++i
)
2133 struct Lisp_String
*s
= b
->strings
+ i
;
2137 /* String was not on free-list before. */
2138 if (STRING_MARKED_P (s
))
2140 /* String is live; unmark it and its intervals. */
2143 if (!NULL_INTERVAL_P (s
->intervals
))
2144 UNMARK_BALANCE_INTERVALS (s
->intervals
);
2147 total_string_size
+= STRING_BYTES (s
);
2151 /* String is dead. Put it on the free-list. */
2152 struct sdata
*data
= SDATA_OF_STRING (s
);
2154 /* Save the size of S in its sdata so that we know
2155 how large that is. Reset the sdata's string
2156 back-pointer so that we know it's free. */
2157 #ifdef GC_CHECK_STRING_BYTES
2158 if (GC_STRING_BYTES (s
) != SDATA_NBYTES (data
))
2161 data
->u
.nbytes
= GC_STRING_BYTES (s
);
2163 data
->string
= NULL
;
2165 /* Reset the strings's `data' member so that we
2169 /* Put the string on the free-list. */
2170 NEXT_FREE_LISP_STRING (s
) = string_free_list
;
2171 string_free_list
= s
;
2177 /* S was on the free-list before. Put it there again. */
2178 NEXT_FREE_LISP_STRING (s
) = string_free_list
;
2179 string_free_list
= s
;
2184 /* Free blocks that contain free Lisp_Strings only, except
2185 the first two of them. */
2186 if (nfree
== STRING_BLOCK_SIZE
2187 && total_free_strings
> STRING_BLOCK_SIZE
)
2190 string_free_list
= free_list_before
;
2194 total_free_strings
+= nfree
;
2195 b
->next
= live_blocks
;
2200 check_string_free_list ();
2202 string_blocks
= live_blocks
;
2203 free_large_strings ();
2204 compact_small_strings ();
2206 check_string_free_list ();
2210 /* Free dead large strings. */
2213 free_large_strings (void)
2215 struct sblock
*b
, *next
;
2216 struct sblock
*live_blocks
= NULL
;
2218 for (b
= large_sblocks
; b
; b
= next
)
2222 if (b
->first_data
.string
== NULL
)
2226 b
->next
= live_blocks
;
2231 large_sblocks
= live_blocks
;
2235 /* Compact data of small strings. Free sblocks that don't contain
2236 data of live strings after compaction. */
2239 compact_small_strings (void)
2241 struct sblock
*b
, *tb
, *next
;
2242 struct sdata
*from
, *to
, *end
, *tb_end
;
2243 struct sdata
*to_end
, *from_end
;
2245 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2246 to, and TB_END is the end of TB. */
2248 tb_end
= (struct sdata
*) ((char *) tb
+ SBLOCK_SIZE
);
2249 to
= &tb
->first_data
;
2251 /* Step through the blocks from the oldest to the youngest. We
2252 expect that old blocks will stabilize over time, so that less
2253 copying will happen this way. */
2254 for (b
= oldest_sblock
; b
; b
= b
->next
)
2257 xassert ((char *) end
<= (char *) b
+ SBLOCK_SIZE
);
2259 for (from
= &b
->first_data
; from
< end
; from
= from_end
)
2261 /* Compute the next FROM here because copying below may
2262 overwrite data we need to compute it. */
2265 #ifdef GC_CHECK_STRING_BYTES
2266 /* Check that the string size recorded in the string is the
2267 same as the one recorded in the sdata structure. */
2269 && GC_STRING_BYTES (from
->string
) != SDATA_NBYTES (from
))
2271 #endif /* GC_CHECK_STRING_BYTES */
2274 nbytes
= GC_STRING_BYTES (from
->string
);
2276 nbytes
= SDATA_NBYTES (from
);
2278 if (nbytes
> LARGE_STRING_BYTES
)
2281 nbytes
= SDATA_SIZE (nbytes
);
2282 from_end
= (struct sdata
*) ((char *) from
+ nbytes
+ GC_STRING_EXTRA
);
2284 #ifdef GC_CHECK_STRING_OVERRUN
2285 if (memcmp (string_overrun_cookie
,
2286 (char *) from_end
- GC_STRING_OVERRUN_COOKIE_SIZE
,
2287 GC_STRING_OVERRUN_COOKIE_SIZE
))
2291 /* FROM->string non-null means it's alive. Copy its data. */
2294 /* If TB is full, proceed with the next sblock. */
2295 to_end
= (struct sdata
*) ((char *) to
+ nbytes
+ GC_STRING_EXTRA
);
2296 if (to_end
> tb_end
)
2300 tb_end
= (struct sdata
*) ((char *) tb
+ SBLOCK_SIZE
);
2301 to
= &tb
->first_data
;
2302 to_end
= (struct sdata
*) ((char *) to
+ nbytes
+ GC_STRING_EXTRA
);
2305 /* Copy, and update the string's `data' pointer. */
2308 xassert (tb
!= b
|| to
< from
);
2309 memmove (to
, from
, nbytes
+ GC_STRING_EXTRA
);
2310 to
->string
->data
= SDATA_DATA (to
);
2313 /* Advance past the sdata we copied to. */
2319 /* The rest of the sblocks following TB don't contain live data, so
2320 we can free them. */
2321 for (b
= tb
->next
; b
; b
= next
)
2329 current_sblock
= tb
;
2333 string_overflow (void)
2335 error ("Maximum string size exceeded");
2338 DEFUN ("make-string", Fmake_string
, Smake_string
, 2, 2, 0,
2339 doc
: /* Return a newly created string of length LENGTH, with INIT in each element.
2340 LENGTH must be an integer.
2341 INIT must be an integer that represents a character. */)
2342 (Lisp_Object length
, Lisp_Object init
)
2344 register Lisp_Object val
;
2345 register unsigned char *p
, *end
;
2349 CHECK_NATNUM (length
);
2350 CHECK_CHARACTER (init
);
2352 c
= XFASTINT (init
);
2353 if (ASCII_CHAR_P (c
))
2355 nbytes
= XINT (length
);
2356 val
= make_uninit_string (nbytes
);
2358 end
= p
+ SCHARS (val
);
2364 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
2365 int len
= CHAR_STRING (c
, str
);
2366 EMACS_INT string_len
= XINT (length
);
2368 if (string_len
> STRING_BYTES_MAX
/ len
)
2370 nbytes
= len
* string_len
;
2371 val
= make_uninit_multibyte_string (string_len
, nbytes
);
2376 memcpy (p
, str
, len
);
2386 DEFUN ("make-bool-vector", Fmake_bool_vector
, Smake_bool_vector
, 2, 2, 0,
2387 doc
: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2388 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2389 (Lisp_Object length
, Lisp_Object init
)
2391 register Lisp_Object val
;
2392 struct Lisp_Bool_Vector
*p
;
2393 EMACS_INT length_in_chars
, length_in_elts
;
2396 CHECK_NATNUM (length
);
2398 bits_per_value
= sizeof (EMACS_INT
) * BOOL_VECTOR_BITS_PER_CHAR
;
2400 length_in_elts
= (XFASTINT (length
) + bits_per_value
- 1) / bits_per_value
;
2401 length_in_chars
= ((XFASTINT (length
) + BOOL_VECTOR_BITS_PER_CHAR
- 1)
2402 / BOOL_VECTOR_BITS_PER_CHAR
);
2404 /* We must allocate one more elements than LENGTH_IN_ELTS for the
2405 slot `size' of the struct Lisp_Bool_Vector. */
2406 val
= Fmake_vector (make_number (length_in_elts
+ 1), Qnil
);
2408 /* No Lisp_Object to trace in there. */
2409 XSETPVECTYPESIZE (XVECTOR (val
), PVEC_BOOL_VECTOR
, 0);
2411 p
= XBOOL_VECTOR (val
);
2412 p
->size
= XFASTINT (length
);
2414 if (length_in_chars
)
2416 memset (p
->data
, ! NILP (init
) ? -1 : 0, length_in_chars
);
2418 /* Clear any extraneous bits in the last byte. */
2419 p
->data
[length_in_chars
- 1]
2420 &= (1 << (XINT (length
) % BOOL_VECTOR_BITS_PER_CHAR
)) - 1;
2427 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2428 of characters from the contents. This string may be unibyte or
2429 multibyte, depending on the contents. */
2432 make_string (const char *contents
, EMACS_INT nbytes
)
2434 register Lisp_Object val
;
2435 EMACS_INT nchars
, multibyte_nbytes
;
2437 parse_str_as_multibyte ((const unsigned char *) contents
, nbytes
,
2438 &nchars
, &multibyte_nbytes
);
2439 if (nbytes
== nchars
|| nbytes
!= multibyte_nbytes
)
2440 /* CONTENTS contains no multibyte sequences or contains an invalid
2441 multibyte sequence. We must make unibyte string. */
2442 val
= make_unibyte_string (contents
, nbytes
);
2444 val
= make_multibyte_string (contents
, nchars
, nbytes
);
2449 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
2452 make_unibyte_string (const char *contents
, EMACS_INT length
)
2454 register Lisp_Object val
;
2455 val
= make_uninit_string (length
);
2456 memcpy (SDATA (val
), contents
, length
);
2461 /* Make a multibyte string from NCHARS characters occupying NBYTES
2462 bytes at CONTENTS. */
2465 make_multibyte_string (const char *contents
,
2466 EMACS_INT nchars
, EMACS_INT nbytes
)
2468 register Lisp_Object val
;
2469 val
= make_uninit_multibyte_string (nchars
, nbytes
);
2470 memcpy (SDATA (val
), contents
, nbytes
);
2475 /* Make a string from NCHARS characters occupying NBYTES bytes at
2476 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2479 make_string_from_bytes (const char *contents
,
2480 EMACS_INT nchars
, EMACS_INT nbytes
)
2482 register Lisp_Object val
;
2483 val
= make_uninit_multibyte_string (nchars
, nbytes
);
2484 memcpy (SDATA (val
), contents
, nbytes
);
2485 if (SBYTES (val
) == SCHARS (val
))
2486 STRING_SET_UNIBYTE (val
);
2491 /* Make a string from NCHARS characters occupying NBYTES bytes at
2492 CONTENTS. The argument MULTIBYTE controls whether to label the
2493 string as multibyte. If NCHARS is negative, it counts the number of
2494 characters by itself. */
2497 make_specified_string (const char *contents
,
2498 EMACS_INT nchars
, EMACS_INT nbytes
, int multibyte
)
2500 register Lisp_Object val
;
2505 nchars
= multibyte_chars_in_text ((const unsigned char *) contents
,
2510 val
= make_uninit_multibyte_string (nchars
, nbytes
);
2511 memcpy (SDATA (val
), contents
, nbytes
);
2513 STRING_SET_UNIBYTE (val
);
2518 /* Make a string from the data at STR, treating it as multibyte if the
2522 build_string (const char *str
)
2524 return make_string (str
, strlen (str
));
2528 /* Return an unibyte Lisp_String set up to hold LENGTH characters
2529 occupying LENGTH bytes. */
2532 make_uninit_string (EMACS_INT length
)
2537 return empty_unibyte_string
;
2538 val
= make_uninit_multibyte_string (length
, length
);
2539 STRING_SET_UNIBYTE (val
);
2544 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2545 which occupy NBYTES bytes. */
2548 make_uninit_multibyte_string (EMACS_INT nchars
, EMACS_INT nbytes
)
2551 struct Lisp_String
*s
;
2556 return empty_multibyte_string
;
2558 s
= allocate_string ();
2559 allocate_string_data (s
, nchars
, nbytes
);
2560 XSETSTRING (string
, s
);
2561 string_chars_consed
+= nbytes
;
2567 /***********************************************************************
2569 ***********************************************************************/
2571 /* We store float cells inside of float_blocks, allocating a new
2572 float_block with malloc whenever necessary. Float cells reclaimed
2573 by GC are put on a free list to be reallocated before allocating
2574 any new float cells from the latest float_block. */
2576 #define FLOAT_BLOCK_SIZE \
2577 (((BLOCK_BYTES - sizeof (struct float_block *) \
2578 /* The compiler might add padding at the end. */ \
2579 - (sizeof (struct Lisp_Float) - sizeof (int))) * CHAR_BIT) \
2580 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2582 #define GETMARKBIT(block,n) \
2583 (((block)->gcmarkbits[(n) / (sizeof (int) * CHAR_BIT)] \
2584 >> ((n) % (sizeof (int) * CHAR_BIT))) \
2587 #define SETMARKBIT(block,n) \
2588 (block)->gcmarkbits[(n) / (sizeof (int) * CHAR_BIT)] \
2589 |= 1 << ((n) % (sizeof (int) * CHAR_BIT))
2591 #define UNSETMARKBIT(block,n) \
2592 (block)->gcmarkbits[(n) / (sizeof (int) * CHAR_BIT)] \
2593 &= ~(1 << ((n) % (sizeof (int) * CHAR_BIT)))
2595 #define FLOAT_BLOCK(fptr) \
2596 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2598 #define FLOAT_INDEX(fptr) \
2599 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2603 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2604 struct Lisp_Float floats
[FLOAT_BLOCK_SIZE
];
2605 int gcmarkbits
[1 + FLOAT_BLOCK_SIZE
/ (sizeof (int) * CHAR_BIT
)];
2606 struct float_block
*next
;
2609 #define FLOAT_MARKED_P(fptr) \
2610 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2612 #define FLOAT_MARK(fptr) \
2613 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2615 #define FLOAT_UNMARK(fptr) \
2616 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2618 /* Current float_block. */
2620 static struct float_block
*float_block
;
2622 /* Index of first unused Lisp_Float in the current float_block. */
2624 static int float_block_index
;
2626 /* Free-list of Lisp_Floats. */
2628 static struct Lisp_Float
*float_free_list
;
2631 /* Initialize float allocation. */
2637 float_block_index
= FLOAT_BLOCK_SIZE
; /* Force alloc of new float_block. */
2638 float_free_list
= 0;
2642 /* Return a new float object with value FLOAT_VALUE. */
2645 make_float (double float_value
)
2647 register Lisp_Object val
;
2649 /* eassert (!handling_signal); */
2653 if (float_free_list
)
2655 /* We use the data field for chaining the free list
2656 so that we won't use the same field that has the mark bit. */
2657 XSETFLOAT (val
, float_free_list
);
2658 float_free_list
= float_free_list
->u
.chain
;
2662 if (float_block_index
== FLOAT_BLOCK_SIZE
)
2664 register struct float_block
*new;
2666 new = (struct float_block
*) lisp_align_malloc (sizeof *new,
2668 new->next
= float_block
;
2669 memset (new->gcmarkbits
, 0, sizeof new->gcmarkbits
);
2671 float_block_index
= 0;
2673 XSETFLOAT (val
, &float_block
->floats
[float_block_index
]);
2674 float_block_index
++;
2677 MALLOC_UNBLOCK_INPUT
;
2679 XFLOAT_INIT (val
, float_value
);
2680 eassert (!FLOAT_MARKED_P (XFLOAT (val
)));
2681 consing_since_gc
+= sizeof (struct Lisp_Float
);
2688 /***********************************************************************
2690 ***********************************************************************/
2692 /* We store cons cells inside of cons_blocks, allocating a new
2693 cons_block with malloc whenever necessary. Cons cells reclaimed by
2694 GC are put on a free list to be reallocated before allocating
2695 any new cons cells from the latest cons_block. */
2697 #define CONS_BLOCK_SIZE \
2698 (((BLOCK_BYTES - sizeof (struct cons_block *)) * CHAR_BIT) \
2699 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2701 #define CONS_BLOCK(fptr) \
2702 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2704 #define CONS_INDEX(fptr) \
2705 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2709 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2710 struct Lisp_Cons conses
[CONS_BLOCK_SIZE
];
2711 int gcmarkbits
[1 + CONS_BLOCK_SIZE
/ (sizeof (int) * CHAR_BIT
)];
2712 struct cons_block
*next
;
2715 #define CONS_MARKED_P(fptr) \
2716 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2718 #define CONS_MARK(fptr) \
2719 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2721 #define CONS_UNMARK(fptr) \
2722 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2724 /* Current cons_block. */
2726 static struct cons_block
*cons_block
;
2728 /* Index of first unused Lisp_Cons in the current block. */
2730 static int cons_block_index
;
2732 /* Free-list of Lisp_Cons structures. */
2734 static struct Lisp_Cons
*cons_free_list
;
2737 /* Initialize cons allocation. */
2743 cons_block_index
= CONS_BLOCK_SIZE
; /* Force alloc of new cons_block. */
2748 /* Explicitly free a cons cell by putting it on the free-list. */
2751 free_cons (struct Lisp_Cons
*ptr
)
2753 ptr
->u
.chain
= cons_free_list
;
2757 cons_free_list
= ptr
;
2760 DEFUN ("cons", Fcons
, Scons
, 2, 2, 0,
2761 doc
: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2762 (Lisp_Object car
, Lisp_Object cdr
)
2764 register Lisp_Object val
;
2766 /* eassert (!handling_signal); */
2772 /* We use the cdr for chaining the free list
2773 so that we won't use the same field that has the mark bit. */
2774 XSETCONS (val
, cons_free_list
);
2775 cons_free_list
= cons_free_list
->u
.chain
;
2779 if (cons_block_index
== CONS_BLOCK_SIZE
)
2781 register struct cons_block
*new;
2782 new = (struct cons_block
*) lisp_align_malloc (sizeof *new,
2784 memset (new->gcmarkbits
, 0, sizeof new->gcmarkbits
);
2785 new->next
= cons_block
;
2787 cons_block_index
= 0;
2789 XSETCONS (val
, &cons_block
->conses
[cons_block_index
]);
2793 MALLOC_UNBLOCK_INPUT
;
2797 eassert (!CONS_MARKED_P (XCONS (val
)));
2798 consing_since_gc
+= sizeof (struct Lisp_Cons
);
2799 cons_cells_consed
++;
2803 #ifdef GC_CHECK_CONS_LIST
2804 /* Get an error now if there's any junk in the cons free list. */
2806 check_cons_list (void)
2808 struct Lisp_Cons
*tail
= cons_free_list
;
2811 tail
= tail
->u
.chain
;
2815 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2818 list1 (Lisp_Object arg1
)
2820 return Fcons (arg1
, Qnil
);
2824 list2 (Lisp_Object arg1
, Lisp_Object arg2
)
2826 return Fcons (arg1
, Fcons (arg2
, Qnil
));
2831 list3 (Lisp_Object arg1
, Lisp_Object arg2
, Lisp_Object arg3
)
2833 return Fcons (arg1
, Fcons (arg2
, Fcons (arg3
, Qnil
)));
2838 list4 (Lisp_Object arg1
, Lisp_Object arg2
, Lisp_Object arg3
, Lisp_Object arg4
)
2840 return Fcons (arg1
, Fcons (arg2
, Fcons (arg3
, Fcons (arg4
, Qnil
))));
2845 list5 (Lisp_Object arg1
, Lisp_Object arg2
, Lisp_Object arg3
, Lisp_Object arg4
, Lisp_Object arg5
)
2847 return Fcons (arg1
, Fcons (arg2
, Fcons (arg3
, Fcons (arg4
,
2848 Fcons (arg5
, Qnil
)))));
2852 DEFUN ("list", Flist
, Slist
, 0, MANY
, 0,
2853 doc
: /* Return a newly created list with specified arguments as elements.
2854 Any number of arguments, even zero arguments, are allowed.
2855 usage: (list &rest OBJECTS) */)
2856 (ptrdiff_t nargs
, Lisp_Object
*args
)
2858 register Lisp_Object val
;
2864 val
= Fcons (args
[nargs
], val
);
2870 DEFUN ("make-list", Fmake_list
, Smake_list
, 2, 2, 0,
2871 doc
: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2872 (register Lisp_Object length
, Lisp_Object init
)
2874 register Lisp_Object val
;
2875 register EMACS_INT size
;
2877 CHECK_NATNUM (length
);
2878 size
= XFASTINT (length
);
2883 val
= Fcons (init
, val
);
2888 val
= Fcons (init
, val
);
2893 val
= Fcons (init
, val
);
2898 val
= Fcons (init
, val
);
2903 val
= Fcons (init
, val
);
2918 /***********************************************************************
2920 ***********************************************************************/
2922 /* Singly-linked list of all vectors. */
2924 static struct Lisp_Vector
*all_vectors
;
2926 /* Handy constants for vectorlike objects. */
2929 header_size
= offsetof (struct Lisp_Vector
, contents
),
2930 word_size
= sizeof (Lisp_Object
)
2933 /* Value is a pointer to a newly allocated Lisp_Vector structure
2934 with room for LEN Lisp_Objects. */
2936 static struct Lisp_Vector
*
2937 allocate_vectorlike (EMACS_INT len
)
2939 struct Lisp_Vector
*p
;
2944 #ifdef DOUG_LEA_MALLOC
2945 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2946 because mapped region contents are not preserved in
2948 mallopt (M_MMAP_MAX
, 0);
2951 /* This gets triggered by code which I haven't bothered to fix. --Stef */
2952 /* eassert (!handling_signal); */
2954 nbytes
= header_size
+ len
* word_size
;
2955 p
= (struct Lisp_Vector
*) lisp_malloc (nbytes
, MEM_TYPE_VECTORLIKE
);
2957 #ifdef DOUG_LEA_MALLOC
2958 /* Back to a reasonable maximum of mmap'ed areas. */
2959 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
);
2962 consing_since_gc
+= nbytes
;
2963 vector_cells_consed
+= len
;
2965 p
->header
.next
.vector
= all_vectors
;
2968 MALLOC_UNBLOCK_INPUT
;
2974 /* Allocate a vector with LEN slots. */
2976 struct Lisp_Vector
*
2977 allocate_vector (EMACS_INT len
)
2979 struct Lisp_Vector
*v
;
2980 ptrdiff_t nbytes_max
= min (PTRDIFF_MAX
, SIZE_MAX
);
2982 if (min ((nbytes_max
- header_size
) / word_size
, MOST_POSITIVE_FIXNUM
) < len
)
2983 memory_full (SIZE_MAX
);
2984 v
= allocate_vectorlike (len
);
2985 v
->header
.size
= len
;
2990 /* Allocate other vector-like structures. */
2992 struct Lisp_Vector
*
2993 allocate_pseudovector (int memlen
, int lisplen
, EMACS_INT tag
)
2995 struct Lisp_Vector
*v
= allocate_vectorlike (memlen
);
2998 /* Only the first lisplen slots will be traced normally by the GC. */
2999 for (i
= 0; i
< lisplen
; ++i
)
3000 v
->contents
[i
] = Qnil
;
3002 XSETPVECTYPESIZE (v
, tag
, lisplen
);
3006 struct Lisp_Hash_Table
*
3007 allocate_hash_table (void)
3009 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table
, count
, PVEC_HASH_TABLE
);
3014 allocate_window (void)
3016 return ALLOCATE_PSEUDOVECTOR (struct window
, current_matrix
, PVEC_WINDOW
);
3021 allocate_terminal (void)
3023 struct terminal
*t
= ALLOCATE_PSEUDOVECTOR (struct terminal
,
3024 next_terminal
, PVEC_TERMINAL
);
3025 /* Zero out the non-GC'd fields. FIXME: This should be made unnecessary. */
3026 memset (&t
->next_terminal
, 0,
3027 (char*) (t
+ 1) - (char*) &t
->next_terminal
);
3033 allocate_frame (void)
3035 struct frame
*f
= ALLOCATE_PSEUDOVECTOR (struct frame
,
3036 face_cache
, PVEC_FRAME
);
3037 /* Zero out the non-GC'd fields. FIXME: This should be made unnecessary. */
3038 memset (&f
->face_cache
, 0,
3039 (char *) (f
+ 1) - (char *) &f
->face_cache
);
3044 struct Lisp_Process
*
3045 allocate_process (void)
3047 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Process
, pid
, PVEC_PROCESS
);
3051 DEFUN ("make-vector", Fmake_vector
, Smake_vector
, 2, 2, 0,
3052 doc
: /* Return a newly created vector of length LENGTH, with each element being INIT.
3053 See also the function `vector'. */)
3054 (register Lisp_Object length
, Lisp_Object init
)
3057 register EMACS_INT sizei
;
3058 register EMACS_INT i
;
3059 register struct Lisp_Vector
*p
;
3061 CHECK_NATNUM (length
);
3062 sizei
= XFASTINT (length
);
3064 p
= allocate_vector (sizei
);
3065 for (i
= 0; i
< sizei
; i
++)
3066 p
->contents
[i
] = init
;
3068 XSETVECTOR (vector
, p
);
3073 DEFUN ("vector", Fvector
, Svector
, 0, MANY
, 0,
3074 doc
: /* Return a newly created vector with specified arguments as elements.
3075 Any number of arguments, even zero arguments, are allowed.
3076 usage: (vector &rest OBJECTS) */)
3077 (ptrdiff_t nargs
, Lisp_Object
*args
)
3079 register Lisp_Object len
, val
;
3081 register struct Lisp_Vector
*p
;
3083 XSETFASTINT (len
, nargs
);
3084 val
= Fmake_vector (len
, Qnil
);
3086 for (i
= 0; i
< nargs
; i
++)
3087 p
->contents
[i
] = args
[i
];
3092 DEFUN ("make-byte-code", Fmake_byte_code
, Smake_byte_code
, 4, MANY
, 0,
3093 doc
: /* Create a byte-code object with specified arguments as elements.
3094 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3095 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3096 and (optional) INTERACTIVE-SPEC.
3097 The first four arguments are required; at most six have any
3099 The ARGLIST can be either like the one of `lambda', in which case the arguments
3100 will be dynamically bound before executing the byte code, or it can be an
3101 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3102 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3103 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3104 argument to catch the left-over arguments. If such an integer is used, the
3105 arguments will not be dynamically bound but will be instead pushed on the
3106 stack before executing the byte-code.
3107 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3108 (ptrdiff_t nargs
, Lisp_Object
*args
)
3110 register Lisp_Object len
, val
;
3112 register struct Lisp_Vector
*p
;
3114 XSETFASTINT (len
, nargs
);
3115 if (!NILP (Vpurify_flag
))
3116 val
= make_pure_vector (nargs
);
3118 val
= Fmake_vector (len
, Qnil
);
3120 if (nargs
> 1 && STRINGP (args
[1]) && STRING_MULTIBYTE (args
[1]))
3121 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3122 earlier because they produced a raw 8-bit string for byte-code
3123 and now such a byte-code string is loaded as multibyte while
3124 raw 8-bit characters converted to multibyte form. Thus, now we
3125 must convert them back to the original unibyte form. */
3126 args
[1] = Fstring_as_unibyte (args
[1]);
3129 for (i
= 0; i
< nargs
; i
++)
3131 if (!NILP (Vpurify_flag
))
3132 args
[i
] = Fpurecopy (args
[i
]);
3133 p
->contents
[i
] = args
[i
];
3135 XSETPVECTYPE (p
, PVEC_COMPILED
);
3136 XSETCOMPILED (val
, p
);
3142 /***********************************************************************
3144 ***********************************************************************/
3146 /* Like struct Lisp_Symbol, but padded so that the size is a multiple
3147 of the required alignment if LSB tags are used. */
3149 union aligned_Lisp_Symbol
3151 struct Lisp_Symbol s
;
3153 unsigned char c
[(sizeof (struct Lisp_Symbol
) + (1 << GCTYPEBITS
) - 1)
3154 & -(1 << GCTYPEBITS
)];
3158 /* Each symbol_block is just under 1020 bytes long, since malloc
3159 really allocates in units of powers of two and uses 4 bytes for its
3162 #define SYMBOL_BLOCK_SIZE \
3163 ((1020 - sizeof (struct symbol_block *)) / sizeof (union aligned_Lisp_Symbol))
3167 /* Place `symbols' first, to preserve alignment. */
3168 union aligned_Lisp_Symbol symbols
[SYMBOL_BLOCK_SIZE
];
3169 struct symbol_block
*next
;
3172 /* Current symbol block and index of first unused Lisp_Symbol
3175 static struct symbol_block
*symbol_block
;
3176 static int symbol_block_index
;
3178 /* List of free symbols. */
3180 static struct Lisp_Symbol
*symbol_free_list
;
3183 /* Initialize symbol allocation. */
3188 symbol_block
= NULL
;
3189 symbol_block_index
= SYMBOL_BLOCK_SIZE
;
3190 symbol_free_list
= 0;
3194 DEFUN ("make-symbol", Fmake_symbol
, Smake_symbol
, 1, 1, 0,
3195 doc
: /* Return a newly allocated uninterned symbol whose name is NAME.
3196 Its value and function definition are void, and its property list is nil. */)
3199 register Lisp_Object val
;
3200 register struct Lisp_Symbol
*p
;
3202 CHECK_STRING (name
);
3204 /* eassert (!handling_signal); */
3208 if (symbol_free_list
)
3210 XSETSYMBOL (val
, symbol_free_list
);
3211 symbol_free_list
= symbol_free_list
->next
;
3215 if (symbol_block_index
== SYMBOL_BLOCK_SIZE
)
3217 struct symbol_block
*new;
3218 new = (struct symbol_block
*) lisp_malloc (sizeof *new,
3220 new->next
= symbol_block
;
3222 symbol_block_index
= 0;
3224 XSETSYMBOL (val
, &symbol_block
->symbols
[symbol_block_index
].s
);
3225 symbol_block_index
++;
3228 MALLOC_UNBLOCK_INPUT
;
3233 p
->redirect
= SYMBOL_PLAINVAL
;
3234 SET_SYMBOL_VAL (p
, Qunbound
);
3235 p
->function
= Qunbound
;
3238 p
->interned
= SYMBOL_UNINTERNED
;
3240 p
->declared_special
= 0;
3241 consing_since_gc
+= sizeof (struct Lisp_Symbol
);
3248 /***********************************************************************
3249 Marker (Misc) Allocation
3250 ***********************************************************************/
3252 /* Like union Lisp_Misc, but padded so that its size is a multiple of
3253 the required alignment when LSB tags are used. */
3255 union aligned_Lisp_Misc
3259 unsigned char c
[(sizeof (union Lisp_Misc
) + (1 << GCTYPEBITS
) - 1)
3260 & -(1 << GCTYPEBITS
)];
3264 /* Allocation of markers and other objects that share that structure.
3265 Works like allocation of conses. */
3267 #define MARKER_BLOCK_SIZE \
3268 ((1020 - sizeof (struct marker_block *)) / sizeof (union aligned_Lisp_Misc))
3272 /* Place `markers' first, to preserve alignment. */
3273 union aligned_Lisp_Misc markers
[MARKER_BLOCK_SIZE
];
3274 struct marker_block
*next
;
3277 static struct marker_block
*marker_block
;
3278 static int marker_block_index
;
3280 static union Lisp_Misc
*marker_free_list
;
3285 marker_block
= NULL
;
3286 marker_block_index
= MARKER_BLOCK_SIZE
;
3287 marker_free_list
= 0;
3290 /* Return a newly allocated Lisp_Misc object, with no substructure. */
3293 allocate_misc (void)
3297 /* eassert (!handling_signal); */
3301 if (marker_free_list
)
3303 XSETMISC (val
, marker_free_list
);
3304 marker_free_list
= marker_free_list
->u_free
.chain
;
3308 if (marker_block_index
== MARKER_BLOCK_SIZE
)
3310 struct marker_block
*new;
3311 new = (struct marker_block
*) lisp_malloc (sizeof *new,
3313 new->next
= marker_block
;
3315 marker_block_index
= 0;
3316 total_free_markers
+= MARKER_BLOCK_SIZE
;
3318 XSETMISC (val
, &marker_block
->markers
[marker_block_index
].m
);
3319 marker_block_index
++;
3322 MALLOC_UNBLOCK_INPUT
;
3324 --total_free_markers
;
3325 consing_since_gc
+= sizeof (union Lisp_Misc
);
3326 misc_objects_consed
++;
3327 XMISCANY (val
)->gcmarkbit
= 0;
3331 /* Free a Lisp_Misc object */
3334 free_misc (Lisp_Object misc
)
3336 XMISCTYPE (misc
) = Lisp_Misc_Free
;
3337 XMISC (misc
)->u_free
.chain
= marker_free_list
;
3338 marker_free_list
= XMISC (misc
);
3340 total_free_markers
++;
3343 /* Return a Lisp_Misc_Save_Value object containing POINTER and
3344 INTEGER. This is used to package C values to call record_unwind_protect.
3345 The unwind function can get the C values back using XSAVE_VALUE. */
3348 make_save_value (void *pointer
, ptrdiff_t integer
)
3350 register Lisp_Object val
;
3351 register struct Lisp_Save_Value
*p
;
3353 val
= allocate_misc ();
3354 XMISCTYPE (val
) = Lisp_Misc_Save_Value
;
3355 p
= XSAVE_VALUE (val
);
3356 p
->pointer
= pointer
;
3357 p
->integer
= integer
;
3362 DEFUN ("make-marker", Fmake_marker
, Smake_marker
, 0, 0, 0,
3363 doc
: /* Return a newly allocated marker which does not point at any place. */)
3366 register Lisp_Object val
;
3367 register struct Lisp_Marker
*p
;
3369 val
= allocate_misc ();
3370 XMISCTYPE (val
) = Lisp_Misc_Marker
;
3376 p
->insertion_type
= 0;
3380 /* Put MARKER back on the free list after using it temporarily. */
3383 free_marker (Lisp_Object marker
)
3385 unchain_marker (XMARKER (marker
));
3390 /* Return a newly created vector or string with specified arguments as
3391 elements. If all the arguments are characters that can fit
3392 in a string of events, make a string; otherwise, make a vector.
3394 Any number of arguments, even zero arguments, are allowed. */
3397 make_event_array (register int nargs
, Lisp_Object
*args
)
3401 for (i
= 0; i
< nargs
; i
++)
3402 /* The things that fit in a string
3403 are characters that are in 0...127,
3404 after discarding the meta bit and all the bits above it. */
3405 if (!INTEGERP (args
[i
])
3406 || (XINT (args
[i
]) & ~(-CHAR_META
)) >= 0200)
3407 return Fvector (nargs
, args
);
3409 /* Since the loop exited, we know that all the things in it are
3410 characters, so we can make a string. */
3414 result
= Fmake_string (make_number (nargs
), make_number (0));
3415 for (i
= 0; i
< nargs
; i
++)
3417 SSET (result
, i
, XINT (args
[i
]));
3418 /* Move the meta bit to the right place for a string char. */
3419 if (XINT (args
[i
]) & CHAR_META
)
3420 SSET (result
, i
, SREF (result
, i
) | 0x80);
3429 /************************************************************************
3430 Memory Full Handling
3431 ************************************************************************/
3434 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
3435 there may have been size_t overflow so that malloc was never
3436 called, or perhaps malloc was invoked successfully but the
3437 resulting pointer had problems fitting into a tagged EMACS_INT. In
3438 either case this counts as memory being full even though malloc did
3442 memory_full (size_t nbytes
)
3444 /* Do not go into hysterics merely because a large request failed. */
3445 int enough_free_memory
= 0;
3446 if (SPARE_MEMORY
< nbytes
)
3451 p
= malloc (SPARE_MEMORY
);
3455 enough_free_memory
= 1;
3457 MALLOC_UNBLOCK_INPUT
;
3460 if (! enough_free_memory
)
3466 memory_full_cons_threshold
= sizeof (struct cons_block
);
3468 /* The first time we get here, free the spare memory. */
3469 for (i
= 0; i
< sizeof (spare_memory
) / sizeof (char *); i
++)
3470 if (spare_memory
[i
])
3473 free (spare_memory
[i
]);
3474 else if (i
>= 1 && i
<= 4)
3475 lisp_align_free (spare_memory
[i
]);
3477 lisp_free (spare_memory
[i
]);
3478 spare_memory
[i
] = 0;
3481 /* Record the space now used. When it decreases substantially,
3482 we can refill the memory reserve. */
3483 #if !defined SYSTEM_MALLOC && !defined SYNC_INPUT
3484 bytes_used_when_full
= BYTES_USED
;
3488 /* This used to call error, but if we've run out of memory, we could
3489 get infinite recursion trying to build the string. */
3490 xsignal (Qnil
, Vmemory_signal_data
);
3493 /* If we released our reserve (due to running out of memory),
3494 and we have a fair amount free once again,
3495 try to set aside another reserve in case we run out once more.
3497 This is called when a relocatable block is freed in ralloc.c,
3498 and also directly from this file, in case we're not using ralloc.c. */
3501 refill_memory_reserve (void)
3503 #ifndef SYSTEM_MALLOC
3504 if (spare_memory
[0] == 0)
3505 spare_memory
[0] = (char *) malloc (SPARE_MEMORY
);
3506 if (spare_memory
[1] == 0)
3507 spare_memory
[1] = (char *) lisp_align_malloc (sizeof (struct cons_block
),
3509 if (spare_memory
[2] == 0)
3510 spare_memory
[2] = (char *) lisp_align_malloc (sizeof (struct cons_block
),
3512 if (spare_memory
[3] == 0)
3513 spare_memory
[3] = (char *) lisp_align_malloc (sizeof (struct cons_block
),
3515 if (spare_memory
[4] == 0)
3516 spare_memory
[4] = (char *) lisp_align_malloc (sizeof (struct cons_block
),
3518 if (spare_memory
[5] == 0)
3519 spare_memory
[5] = (char *) lisp_malloc (sizeof (struct string_block
),
3521 if (spare_memory
[6] == 0)
3522 spare_memory
[6] = (char *) lisp_malloc (sizeof (struct string_block
),
3524 if (spare_memory
[0] && spare_memory
[1] && spare_memory
[5])
3525 Vmemory_full
= Qnil
;
3529 /************************************************************************
3531 ************************************************************************/
3533 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
3535 /* Conservative C stack marking requires a method to identify possibly
3536 live Lisp objects given a pointer value. We do this by keeping
3537 track of blocks of Lisp data that are allocated in a red-black tree
3538 (see also the comment of mem_node which is the type of nodes in
3539 that tree). Function lisp_malloc adds information for an allocated
3540 block to the red-black tree with calls to mem_insert, and function
3541 lisp_free removes it with mem_delete. Functions live_string_p etc
3542 call mem_find to lookup information about a given pointer in the
3543 tree, and use that to determine if the pointer points to a Lisp
3546 /* Initialize this part of alloc.c. */
3551 mem_z
.left
= mem_z
.right
= MEM_NIL
;
3552 mem_z
.parent
= NULL
;
3553 mem_z
.color
= MEM_BLACK
;
3554 mem_z
.start
= mem_z
.end
= NULL
;
3559 /* Value is a pointer to the mem_node containing START. Value is
3560 MEM_NIL if there is no node in the tree containing START. */
3562 static inline struct mem_node
*
3563 mem_find (void *start
)
3567 if (start
< min_heap_address
|| start
> max_heap_address
)
3570 /* Make the search always successful to speed up the loop below. */
3571 mem_z
.start
= start
;
3572 mem_z
.end
= (char *) start
+ 1;
3575 while (start
< p
->start
|| start
>= p
->end
)
3576 p
= start
< p
->start
? p
->left
: p
->right
;
3581 #ifdef NEED_MEM_INSERT
3583 /* Insert a new node into the tree for a block of memory with start
3584 address START, end address END, and type TYPE. Value is a
3585 pointer to the node that was inserted. */
3587 static struct mem_node
*
3588 mem_insert (void *start
, void *end
, enum mem_type type
)
3590 struct mem_node
*c
, *parent
, *x
;
3592 if (min_heap_address
== NULL
|| start
< min_heap_address
)
3593 min_heap_address
= start
;
3594 if (max_heap_address
== NULL
|| end
> max_heap_address
)
3595 max_heap_address
= end
;
3597 /* See where in the tree a node for START belongs. In this
3598 particular application, it shouldn't happen that a node is already
3599 present. For debugging purposes, let's check that. */
3603 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
3605 while (c
!= MEM_NIL
)
3607 if (start
>= c
->start
&& start
< c
->end
)
3610 c
= start
< c
->start
? c
->left
: c
->right
;
3613 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3615 while (c
!= MEM_NIL
)
3618 c
= start
< c
->start
? c
->left
: c
->right
;
3621 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3623 /* Create a new node. */
3624 #ifdef GC_MALLOC_CHECK
3625 x
= (struct mem_node
*) _malloc_internal (sizeof *x
);
3629 x
= (struct mem_node
*) xmalloc (sizeof *x
);
3635 x
->left
= x
->right
= MEM_NIL
;
3638 /* Insert it as child of PARENT or install it as root. */
3641 if (start
< parent
->start
)
3649 /* Re-establish red-black tree properties. */
3650 mem_insert_fixup (x
);
3656 /* Re-establish the red-black properties of the tree, and thereby
3657 balance the tree, after node X has been inserted; X is always red. */
3660 mem_insert_fixup (struct mem_node
*x
)
3662 while (x
!= mem_root
&& x
->parent
->color
== MEM_RED
)
3664 /* X is red and its parent is red. This is a violation of
3665 red-black tree property #3. */
3667 if (x
->parent
== x
->parent
->parent
->left
)
3669 /* We're on the left side of our grandparent, and Y is our
3671 struct mem_node
*y
= x
->parent
->parent
->right
;
3673 if (y
->color
== MEM_RED
)
3675 /* Uncle and parent are red but should be black because
3676 X is red. Change the colors accordingly and proceed
3677 with the grandparent. */
3678 x
->parent
->color
= MEM_BLACK
;
3679 y
->color
= MEM_BLACK
;
3680 x
->parent
->parent
->color
= MEM_RED
;
3681 x
= x
->parent
->parent
;
3685 /* Parent and uncle have different colors; parent is
3686 red, uncle is black. */
3687 if (x
== x
->parent
->right
)
3690 mem_rotate_left (x
);
3693 x
->parent
->color
= MEM_BLACK
;
3694 x
->parent
->parent
->color
= MEM_RED
;
3695 mem_rotate_right (x
->parent
->parent
);
3700 /* This is the symmetrical case of above. */
3701 struct mem_node
*y
= x
->parent
->parent
->left
;
3703 if (y
->color
== MEM_RED
)
3705 x
->parent
->color
= MEM_BLACK
;
3706 y
->color
= MEM_BLACK
;
3707 x
->parent
->parent
->color
= MEM_RED
;
3708 x
= x
->parent
->parent
;
3712 if (x
== x
->parent
->left
)
3715 mem_rotate_right (x
);
3718 x
->parent
->color
= MEM_BLACK
;
3719 x
->parent
->parent
->color
= MEM_RED
;
3720 mem_rotate_left (x
->parent
->parent
);
3725 /* The root may have been changed to red due to the algorithm. Set
3726 it to black so that property #5 is satisfied. */
3727 mem_root
->color
= MEM_BLACK
;
3730 #endif /* NEED_MEM_INSERT */
3740 mem_rotate_left (struct mem_node
*x
)
3744 /* Turn y's left sub-tree into x's right sub-tree. */
3747 if (y
->left
!= MEM_NIL
)
3748 y
->left
->parent
= x
;
3750 /* Y's parent was x's parent. */
3752 y
->parent
= x
->parent
;
3754 /* Get the parent to point to y instead of x. */
3757 if (x
== x
->parent
->left
)
3758 x
->parent
->left
= y
;
3760 x
->parent
->right
= y
;
3765 /* Put x on y's left. */
3779 mem_rotate_right (struct mem_node
*x
)
3781 struct mem_node
*y
= x
->left
;
3784 if (y
->right
!= MEM_NIL
)
3785 y
->right
->parent
= x
;
3788 y
->parent
= x
->parent
;
3791 if (x
== x
->parent
->right
)
3792 x
->parent
->right
= y
;
3794 x
->parent
->left
= y
;
3805 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
3808 mem_delete (struct mem_node
*z
)
3810 struct mem_node
*x
, *y
;
3812 if (!z
|| z
== MEM_NIL
)
3815 if (z
->left
== MEM_NIL
|| z
->right
== MEM_NIL
)
3820 while (y
->left
!= MEM_NIL
)
3824 if (y
->left
!= MEM_NIL
)
3829 x
->parent
= y
->parent
;
3832 if (y
== y
->parent
->left
)
3833 y
->parent
->left
= x
;
3835 y
->parent
->right
= x
;
3842 z
->start
= y
->start
;
3847 if (y
->color
== MEM_BLACK
)
3848 mem_delete_fixup (x
);
3850 #ifdef GC_MALLOC_CHECK
3858 /* Re-establish the red-black properties of the tree, after a
3862 mem_delete_fixup (struct mem_node
*x
)
3864 while (x
!= mem_root
&& x
->color
== MEM_BLACK
)
3866 if (x
== x
->parent
->left
)
3868 struct mem_node
*w
= x
->parent
->right
;
3870 if (w
->color
== MEM_RED
)
3872 w
->color
= MEM_BLACK
;
3873 x
->parent
->color
= MEM_RED
;
3874 mem_rotate_left (x
->parent
);
3875 w
= x
->parent
->right
;
3878 if (w
->left
->color
== MEM_BLACK
&& w
->right
->color
== MEM_BLACK
)
3885 if (w
->right
->color
== MEM_BLACK
)
3887 w
->left
->color
= MEM_BLACK
;
3889 mem_rotate_right (w
);
3890 w
= x
->parent
->right
;
3892 w
->color
= x
->parent
->color
;
3893 x
->parent
->color
= MEM_BLACK
;
3894 w
->right
->color
= MEM_BLACK
;
3895 mem_rotate_left (x
->parent
);
3901 struct mem_node
*w
= x
->parent
->left
;
3903 if (w
->color
== MEM_RED
)
3905 w
->color
= MEM_BLACK
;
3906 x
->parent
->color
= MEM_RED
;
3907 mem_rotate_right (x
->parent
);
3908 w
= x
->parent
->left
;
3911 if (w
->right
->color
== MEM_BLACK
&& w
->left
->color
== MEM_BLACK
)
3918 if (w
->left
->color
== MEM_BLACK
)
3920 w
->right
->color
= MEM_BLACK
;
3922 mem_rotate_left (w
);
3923 w
= x
->parent
->left
;
3926 w
->color
= x
->parent
->color
;
3927 x
->parent
->color
= MEM_BLACK
;
3928 w
->left
->color
= MEM_BLACK
;
3929 mem_rotate_right (x
->parent
);
3935 x
->color
= MEM_BLACK
;
3939 /* Value is non-zero if P is a pointer to a live Lisp string on
3940 the heap. M is a pointer to the mem_block for P. */
3943 live_string_p (struct mem_node
*m
, void *p
)
3945 if (m
->type
== MEM_TYPE_STRING
)
3947 struct string_block
*b
= (struct string_block
*) m
->start
;
3948 ptrdiff_t offset
= (char *) p
- (char *) &b
->strings
[0];
3950 /* P must point to the start of a Lisp_String structure, and it
3951 must not be on the free-list. */
3953 && offset
% sizeof b
->strings
[0] == 0
3954 && offset
< (STRING_BLOCK_SIZE
* sizeof b
->strings
[0])
3955 && ((struct Lisp_String
*) p
)->data
!= NULL
);
3962 /* Value is non-zero if P is a pointer to a live Lisp cons on
3963 the heap. M is a pointer to the mem_block for P. */
3966 live_cons_p (struct mem_node
*m
, void *p
)
3968 if (m
->type
== MEM_TYPE_CONS
)
3970 struct cons_block
*b
= (struct cons_block
*) m
->start
;
3971 ptrdiff_t offset
= (char *) p
- (char *) &b
->conses
[0];
3973 /* P must point to the start of a Lisp_Cons, not be
3974 one of the unused cells in the current cons block,
3975 and not be on the free-list. */
3977 && offset
% sizeof b
->conses
[0] == 0
3978 && offset
< (CONS_BLOCK_SIZE
* sizeof b
->conses
[0])
3980 || offset
/ sizeof b
->conses
[0] < cons_block_index
)
3981 && !EQ (((struct Lisp_Cons
*) p
)->car
, Vdead
));
3988 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3989 the heap. M is a pointer to the mem_block for P. */
3992 live_symbol_p (struct mem_node
*m
, void *p
)
3994 if (m
->type
== MEM_TYPE_SYMBOL
)
3996 struct symbol_block
*b
= (struct symbol_block
*) m
->start
;
3997 ptrdiff_t offset
= (char *) p
- (char *) &b
->symbols
[0];
3999 /* P must point to the start of a Lisp_Symbol, not be
4000 one of the unused cells in the current symbol block,
4001 and not be on the free-list. */
4003 && offset
% sizeof b
->symbols
[0] == 0
4004 && offset
< (SYMBOL_BLOCK_SIZE
* sizeof b
->symbols
[0])
4005 && (b
!= symbol_block
4006 || offset
/ sizeof b
->symbols
[0] < symbol_block_index
)
4007 && !EQ (((struct Lisp_Symbol
*) p
)->function
, Vdead
));
4014 /* Value is non-zero if P is a pointer to a live Lisp float on
4015 the heap. M is a pointer to the mem_block for P. */
4018 live_float_p (struct mem_node
*m
, void *p
)
4020 if (m
->type
== MEM_TYPE_FLOAT
)
4022 struct float_block
*b
= (struct float_block
*) m
->start
;
4023 ptrdiff_t offset
= (char *) p
- (char *) &b
->floats
[0];
4025 /* P must point to the start of a Lisp_Float and not be
4026 one of the unused cells in the current float block. */
4028 && offset
% sizeof b
->floats
[0] == 0
4029 && offset
< (FLOAT_BLOCK_SIZE
* sizeof b
->floats
[0])
4030 && (b
!= float_block
4031 || offset
/ sizeof b
->floats
[0] < float_block_index
));
4038 /* Value is non-zero if P is a pointer to a live Lisp Misc on
4039 the heap. M is a pointer to the mem_block for P. */
4042 live_misc_p (struct mem_node
*m
, void *p
)
4044 if (m
->type
== MEM_TYPE_MISC
)
4046 struct marker_block
*b
= (struct marker_block
*) m
->start
;
4047 ptrdiff_t offset
= (char *) p
- (char *) &b
->markers
[0];
4049 /* P must point to the start of a Lisp_Misc, not be
4050 one of the unused cells in the current misc block,
4051 and not be on the free-list. */
4053 && offset
% sizeof b
->markers
[0] == 0
4054 && offset
< (MARKER_BLOCK_SIZE
* sizeof b
->markers
[0])
4055 && (b
!= marker_block
4056 || offset
/ sizeof b
->markers
[0] < marker_block_index
)
4057 && ((union Lisp_Misc
*) p
)->u_any
.type
!= Lisp_Misc_Free
);
4064 /* Value is non-zero if P is a pointer to a live vector-like object.
4065 M is a pointer to the mem_block for P. */
4068 live_vector_p (struct mem_node
*m
, void *p
)
4070 return (p
== m
->start
&& m
->type
== MEM_TYPE_VECTORLIKE
);
4074 /* Value is non-zero if P is a pointer to a live buffer. M is a
4075 pointer to the mem_block for P. */
4078 live_buffer_p (struct mem_node
*m
, void *p
)
4080 /* P must point to the start of the block, and the buffer
4081 must not have been killed. */
4082 return (m
->type
== MEM_TYPE_BUFFER
4084 && !NILP (((struct buffer
*) p
)->BUFFER_INTERNAL_FIELD (name
)));
4087 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
4091 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4093 /* Array of objects that are kept alive because the C stack contains
4094 a pattern that looks like a reference to them . */
4096 #define MAX_ZOMBIES 10
4097 static Lisp_Object zombies
[MAX_ZOMBIES
];
4099 /* Number of zombie objects. */
4101 static EMACS_INT nzombies
;
4103 /* Number of garbage collections. */
4105 static EMACS_INT ngcs
;
4107 /* Average percentage of zombies per collection. */
4109 static double avg_zombies
;
4111 /* Max. number of live and zombie objects. */
4113 static EMACS_INT max_live
, max_zombies
;
4115 /* Average number of live objects per GC. */
4117 static double avg_live
;
4119 DEFUN ("gc-status", Fgc_status
, Sgc_status
, 0, 0, "",
4120 doc
: /* Show information about live and zombie objects. */)
4123 Lisp_Object args
[8], zombie_list
= Qnil
;
4125 for (i
= 0; i
< min (MAX_ZOMBIES
, nzombies
); i
++)
4126 zombie_list
= Fcons (zombies
[i
], zombie_list
);
4127 args
[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
4128 args
[1] = make_number (ngcs
);
4129 args
[2] = make_float (avg_live
);
4130 args
[3] = make_float (avg_zombies
);
4131 args
[4] = make_float (avg_zombies
/ avg_live
/ 100);
4132 args
[5] = make_number (max_live
);
4133 args
[6] = make_number (max_zombies
);
4134 args
[7] = zombie_list
;
4135 return Fmessage (8, args
);
4138 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4141 /* Mark OBJ if we can prove it's a Lisp_Object. */
4144 mark_maybe_object (Lisp_Object obj
)
4152 po
= (void *) XPNTR (obj
);
4159 switch (XTYPE (obj
))
4162 mark_p
= (live_string_p (m
, po
)
4163 && !STRING_MARKED_P ((struct Lisp_String
*) po
));
4167 mark_p
= (live_cons_p (m
, po
) && !CONS_MARKED_P (XCONS (obj
)));
4171 mark_p
= (live_symbol_p (m
, po
) && !XSYMBOL (obj
)->gcmarkbit
);
4175 mark_p
= (live_float_p (m
, po
) && !FLOAT_MARKED_P (XFLOAT (obj
)));
4178 case Lisp_Vectorlike
:
4179 /* Note: can't check BUFFERP before we know it's a
4180 buffer because checking that dereferences the pointer
4181 PO which might point anywhere. */
4182 if (live_vector_p (m
, po
))
4183 mark_p
= !SUBRP (obj
) && !VECTOR_MARKED_P (XVECTOR (obj
));
4184 else if (live_buffer_p (m
, po
))
4185 mark_p
= BUFFERP (obj
) && !VECTOR_MARKED_P (XBUFFER (obj
));
4189 mark_p
= (live_misc_p (m
, po
) && !XMISCANY (obj
)->gcmarkbit
);
4198 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4199 if (nzombies
< MAX_ZOMBIES
)
4200 zombies
[nzombies
] = obj
;
4209 /* If P points to Lisp data, mark that as live if it isn't already
4213 mark_maybe_pointer (void *p
)
4217 /* Quickly rule out some values which can't point to Lisp data. */
4220 8 /* USE_LSB_TAG needs Lisp data to be aligned on multiples of 8. */
4222 2 /* We assume that Lisp data is aligned on even addresses. */
4230 Lisp_Object obj
= Qnil
;
4234 case MEM_TYPE_NON_LISP
:
4235 /* Nothing to do; not a pointer to Lisp memory. */
4238 case MEM_TYPE_BUFFER
:
4239 if (live_buffer_p (m
, p
) && !VECTOR_MARKED_P ((struct buffer
*)p
))
4240 XSETVECTOR (obj
, p
);
4244 if (live_cons_p (m
, p
) && !CONS_MARKED_P ((struct Lisp_Cons
*) p
))
4248 case MEM_TYPE_STRING
:
4249 if (live_string_p (m
, p
)
4250 && !STRING_MARKED_P ((struct Lisp_String
*) p
))
4251 XSETSTRING (obj
, p
);
4255 if (live_misc_p (m
, p
) && !((struct Lisp_Free
*) p
)->gcmarkbit
)
4259 case MEM_TYPE_SYMBOL
:
4260 if (live_symbol_p (m
, p
) && !((struct Lisp_Symbol
*) p
)->gcmarkbit
)
4261 XSETSYMBOL (obj
, p
);
4264 case MEM_TYPE_FLOAT
:
4265 if (live_float_p (m
, p
) && !FLOAT_MARKED_P (p
))
4269 case MEM_TYPE_VECTORLIKE
:
4270 if (live_vector_p (m
, p
))
4273 XSETVECTOR (tem
, p
);
4274 if (!SUBRP (tem
) && !VECTOR_MARKED_P (XVECTOR (tem
)))
4289 /* Alignment of pointer values. Use offsetof, as it sometimes returns
4290 a smaller alignment than GCC's __alignof__ and mark_memory might
4291 miss objects if __alignof__ were used. */
4292 #define GC_POINTER_ALIGNMENT offsetof (struct {char a; void *b;}, b)
4294 /* Define POINTERS_MIGHT_HIDE_IN_OBJECTS to 1 if marking via C pointers does
4295 not suffice, which is the typical case. A host where a Lisp_Object is
4296 wider than a pointer might allocate a Lisp_Object in non-adjacent halves.
4297 If USE_LSB_TAG, the bottom half is not a valid pointer, but it should
4298 suffice to widen it to to a Lisp_Object and check it that way. */
4299 #if defined USE_LSB_TAG || UINTPTR_MAX >> VALBITS != 0
4300 # if !defined USE_LSB_TAG && UINTPTR_MAX >> VALBITS >> GCTYPEBITS != 0
4301 /* If tag bits straddle pointer-word boundaries, neither mark_maybe_pointer
4302 nor mark_maybe_object can follow the pointers. This should not occur on
4303 any practical porting target. */
4304 # error "MSB type bits straddle pointer-word boundaries"
4306 /* Marking via C pointers does not suffice, because Lisp_Objects contain
4307 pointer words that hold pointers ORed with type bits. */
4308 # define POINTERS_MIGHT_HIDE_IN_OBJECTS 1
4310 /* Marking via C pointers suffices, because Lisp_Objects contain pointer
4311 words that hold unmodified pointers. */
4312 # define POINTERS_MIGHT_HIDE_IN_OBJECTS 0
4315 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4316 or END+OFFSET..START. */
4319 mark_memory (void *start
, void *end
)
4324 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4328 /* Make START the pointer to the start of the memory region,
4329 if it isn't already. */
4337 /* Mark Lisp data pointed to. This is necessary because, in some
4338 situations, the C compiler optimizes Lisp objects away, so that
4339 only a pointer to them remains. Example:
4341 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4344 Lisp_Object obj = build_string ("test");
4345 struct Lisp_String *s = XSTRING (obj);
4346 Fgarbage_collect ();
4347 fprintf (stderr, "test `%s'\n", s->data);
4351 Here, `obj' isn't really used, and the compiler optimizes it
4352 away. The only reference to the life string is through the
4355 for (pp
= start
; (void *) pp
< end
; pp
++)
4356 for (i
= 0; i
< sizeof *pp
; i
+= GC_POINTER_ALIGNMENT
)
4358 void *p
= *(void **) ((char *) pp
+ i
);
4359 mark_maybe_pointer (p
);
4360 if (POINTERS_MIGHT_HIDE_IN_OBJECTS
)
4361 mark_maybe_object (widen_to_Lisp_Object (p
));
4365 /* setjmp will work with GCC unless NON_SAVING_SETJMP is defined in
4366 the GCC system configuration. In gcc 3.2, the only systems for
4367 which this is so are i386-sco5 non-ELF, i386-sysv3 (maybe included
4368 by others?) and ns32k-pc532-min. */
4370 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4372 static int setjmp_tested_p
, longjmps_done
;
4374 #define SETJMP_WILL_LIKELY_WORK "\
4376 Emacs garbage collector has been changed to use conservative stack\n\
4377 marking. Emacs has determined that the method it uses to do the\n\
4378 marking will likely work on your system, but this isn't sure.\n\
4380 If you are a system-programmer, or can get the help of a local wizard\n\
4381 who is, please take a look at the function mark_stack in alloc.c, and\n\
4382 verify that the methods used are appropriate for your system.\n\
4384 Please mail the result to <emacs-devel@gnu.org>.\n\
4387 #define SETJMP_WILL_NOT_WORK "\
4389 Emacs garbage collector has been changed to use conservative stack\n\
4390 marking. Emacs has determined that the default method it uses to do the\n\
4391 marking will not work on your system. We will need a system-dependent\n\
4392 solution for your system.\n\
4394 Please take a look at the function mark_stack in alloc.c, and\n\
4395 try to find a way to make it work on your system.\n\
4397 Note that you may get false negatives, depending on the compiler.\n\
4398 In particular, you need to use -O with GCC for this test.\n\
4400 Please mail the result to <emacs-devel@gnu.org>.\n\
4404 /* Perform a quick check if it looks like setjmp saves registers in a
4405 jmp_buf. Print a message to stderr saying so. When this test
4406 succeeds, this is _not_ a proof that setjmp is sufficient for
4407 conservative stack marking. Only the sources or a disassembly
4418 /* Arrange for X to be put in a register. */
4424 if (longjmps_done
== 1)
4426 /* Came here after the longjmp at the end of the function.
4428 If x == 1, the longjmp has restored the register to its
4429 value before the setjmp, and we can hope that setjmp
4430 saves all such registers in the jmp_buf, although that
4433 For other values of X, either something really strange is
4434 taking place, or the setjmp just didn't save the register. */
4437 fprintf (stderr
, SETJMP_WILL_LIKELY_WORK
);
4440 fprintf (stderr
, SETJMP_WILL_NOT_WORK
);
4447 if (longjmps_done
== 1)
4451 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4454 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4456 /* Abort if anything GCPRO'd doesn't survive the GC. */
4464 for (p
= gcprolist
; p
; p
= p
->next
)
4465 for (i
= 0; i
< p
->nvars
; ++i
)
4466 if (!survives_gc_p (p
->var
[i
]))
4467 /* FIXME: It's not necessarily a bug. It might just be that the
4468 GCPRO is unnecessary or should release the object sooner. */
4472 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4479 fprintf (stderr
, "\nZombies kept alive = %"pI
"d:\n", nzombies
);
4480 for (i
= 0; i
< min (MAX_ZOMBIES
, nzombies
); ++i
)
4482 fprintf (stderr
, " %d = ", i
);
4483 debug_print (zombies
[i
]);
4487 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4490 /* Mark live Lisp objects on the C stack.
4492 There are several system-dependent problems to consider when
4493 porting this to new architectures:
4497 We have to mark Lisp objects in CPU registers that can hold local
4498 variables or are used to pass parameters.
4500 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4501 something that either saves relevant registers on the stack, or
4502 calls mark_maybe_object passing it each register's contents.
4504 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4505 implementation assumes that calling setjmp saves registers we need
4506 to see in a jmp_buf which itself lies on the stack. This doesn't
4507 have to be true! It must be verified for each system, possibly
4508 by taking a look at the source code of setjmp.
4510 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4511 can use it as a machine independent method to store all registers
4512 to the stack. In this case the macros described in the previous
4513 two paragraphs are not used.
4517 Architectures differ in the way their processor stack is organized.
4518 For example, the stack might look like this
4521 | Lisp_Object | size = 4
4523 | something else | size = 2
4525 | Lisp_Object | size = 4
4529 In such a case, not every Lisp_Object will be aligned equally. To
4530 find all Lisp_Object on the stack it won't be sufficient to walk
4531 the stack in steps of 4 bytes. Instead, two passes will be
4532 necessary, one starting at the start of the stack, and a second
4533 pass starting at the start of the stack + 2. Likewise, if the
4534 minimal alignment of Lisp_Objects on the stack is 1, four passes
4535 would be necessary, each one starting with one byte more offset
4536 from the stack start. */
4543 #ifdef HAVE___BUILTIN_UNWIND_INIT
4544 /* Force callee-saved registers and register windows onto the stack.
4545 This is the preferred method if available, obviating the need for
4546 machine dependent methods. */
4547 __builtin_unwind_init ();
4549 #else /* not HAVE___BUILTIN_UNWIND_INIT */
4550 #ifndef GC_SAVE_REGISTERS_ON_STACK
4551 /* jmp_buf may not be aligned enough on darwin-ppc64 */
4552 union aligned_jmpbuf
{
4556 volatile int stack_grows_down_p
= (char *) &j
> (char *) stack_base
;
4558 /* This trick flushes the register windows so that all the state of
4559 the process is contained in the stack. */
4560 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
4561 needed on ia64 too. See mach_dep.c, where it also says inline
4562 assembler doesn't work with relevant proprietary compilers. */
4564 #if defined (__sparc64__) && defined (__FreeBSD__)
4565 /* FreeBSD does not have a ta 3 handler. */
4572 /* Save registers that we need to see on the stack. We need to see
4573 registers used to hold register variables and registers used to
4575 #ifdef GC_SAVE_REGISTERS_ON_STACK
4576 GC_SAVE_REGISTERS_ON_STACK (end
);
4577 #else /* not GC_SAVE_REGISTERS_ON_STACK */
4579 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
4580 setjmp will definitely work, test it
4581 and print a message with the result
4583 if (!setjmp_tested_p
)
4585 setjmp_tested_p
= 1;
4588 #endif /* GC_SETJMP_WORKS */
4591 end
= stack_grows_down_p
? (char *) &j
+ sizeof j
: (char *) &j
;
4592 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
4593 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
4595 /* This assumes that the stack is a contiguous region in memory. If
4596 that's not the case, something has to be done here to iterate
4597 over the stack segments. */
4598 mark_memory (stack_base
, end
);
4600 /* Allow for marking a secondary stack, like the register stack on the
4602 #ifdef GC_MARK_SECONDARY_STACK
4603 GC_MARK_SECONDARY_STACK ();
4606 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4611 #endif /* GC_MARK_STACK != 0 */
4614 /* Determine whether it is safe to access memory at address P. */
4616 valid_pointer_p (void *p
)
4619 return w32_valid_pointer_p (p
, 16);
4623 /* Obviously, we cannot just access it (we would SEGV trying), so we
4624 trick the o/s to tell us whether p is a valid pointer.
4625 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4626 not validate p in that case. */
4630 int valid
= (emacs_write (fd
[1], (char *) p
, 16) == 16);
4631 emacs_close (fd
[1]);
4632 emacs_close (fd
[0]);
4640 /* Return 1 if OBJ is a valid lisp object.
4641 Return 0 if OBJ is NOT a valid lisp object.
4642 Return -1 if we cannot validate OBJ.
4643 This function can be quite slow,
4644 so it should only be used in code for manual debugging. */
4647 valid_lisp_object_p (Lisp_Object obj
)
4657 p
= (void *) XPNTR (obj
);
4658 if (PURE_POINTER_P (p
))
4662 return valid_pointer_p (p
);
4669 int valid
= valid_pointer_p (p
);
4681 case MEM_TYPE_NON_LISP
:
4684 case MEM_TYPE_BUFFER
:
4685 return live_buffer_p (m
, p
);
4688 return live_cons_p (m
, p
);
4690 case MEM_TYPE_STRING
:
4691 return live_string_p (m
, p
);
4694 return live_misc_p (m
, p
);
4696 case MEM_TYPE_SYMBOL
:
4697 return live_symbol_p (m
, p
);
4699 case MEM_TYPE_FLOAT
:
4700 return live_float_p (m
, p
);
4702 case MEM_TYPE_VECTORLIKE
:
4703 return live_vector_p (m
, p
);
4716 /***********************************************************************
4717 Pure Storage Management
4718 ***********************************************************************/
4720 /* Allocate room for SIZE bytes from pure Lisp storage and return a
4721 pointer to it. TYPE is the Lisp type for which the memory is
4722 allocated. TYPE < 0 means it's not used for a Lisp object. */
4724 static POINTER_TYPE
*
4725 pure_alloc (size_t size
, int type
)
4727 POINTER_TYPE
*result
;
4729 size_t alignment
= (1 << GCTYPEBITS
);
4731 size_t alignment
= sizeof (EMACS_INT
);
4733 /* Give Lisp_Floats an extra alignment. */
4734 if (type
== Lisp_Float
)
4736 #if defined __GNUC__ && __GNUC__ >= 2
4737 alignment
= __alignof (struct Lisp_Float
);
4739 alignment
= sizeof (struct Lisp_Float
);
4747 /* Allocate space for a Lisp object from the beginning of the free
4748 space with taking account of alignment. */
4749 result
= ALIGN (purebeg
+ pure_bytes_used_lisp
, alignment
);
4750 pure_bytes_used_lisp
= ((char *)result
- (char *)purebeg
) + size
;
4754 /* Allocate space for a non-Lisp object from the end of the free
4756 pure_bytes_used_non_lisp
+= size
;
4757 result
= purebeg
+ pure_size
- pure_bytes_used_non_lisp
;
4759 pure_bytes_used
= pure_bytes_used_lisp
+ pure_bytes_used_non_lisp
;
4761 if (pure_bytes_used
<= pure_size
)
4764 /* Don't allocate a large amount here,
4765 because it might get mmap'd and then its address
4766 might not be usable. */
4767 purebeg
= (char *) xmalloc (10000);
4769 pure_bytes_used_before_overflow
+= pure_bytes_used
- size
;
4770 pure_bytes_used
= 0;
4771 pure_bytes_used_lisp
= pure_bytes_used_non_lisp
= 0;
4776 /* Print a warning if PURESIZE is too small. */
4779 check_pure_size (void)
4781 if (pure_bytes_used_before_overflow
)
4782 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI
"d"
4784 pure_bytes_used
+ pure_bytes_used_before_overflow
);
4788 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
4789 the non-Lisp data pool of the pure storage, and return its start
4790 address. Return NULL if not found. */
4793 find_string_data_in_pure (const char *data
, EMACS_INT nbytes
)
4796 EMACS_INT skip
, bm_skip
[256], last_char_skip
, infinity
, start
, start_max
;
4797 const unsigned char *p
;
4800 if (pure_bytes_used_non_lisp
< nbytes
+ 1)
4803 /* Set up the Boyer-Moore table. */
4805 for (i
= 0; i
< 256; i
++)
4808 p
= (const unsigned char *) data
;
4810 bm_skip
[*p
++] = skip
;
4812 last_char_skip
= bm_skip
['\0'];
4814 non_lisp_beg
= purebeg
+ pure_size
- pure_bytes_used_non_lisp
;
4815 start_max
= pure_bytes_used_non_lisp
- (nbytes
+ 1);
4817 /* See the comments in the function `boyer_moore' (search.c) for the
4818 use of `infinity'. */
4819 infinity
= pure_bytes_used_non_lisp
+ 1;
4820 bm_skip
['\0'] = infinity
;
4822 p
= (const unsigned char *) non_lisp_beg
+ nbytes
;
4826 /* Check the last character (== '\0'). */
4829 start
+= bm_skip
[*(p
+ start
)];
4831 while (start
<= start_max
);
4833 if (start
< infinity
)
4834 /* Couldn't find the last character. */
4837 /* No less than `infinity' means we could find the last
4838 character at `p[start - infinity]'. */
4841 /* Check the remaining characters. */
4842 if (memcmp (data
, non_lisp_beg
+ start
, nbytes
) == 0)
4844 return non_lisp_beg
+ start
;
4846 start
+= last_char_skip
;
4848 while (start
<= start_max
);
4854 /* Return a string allocated in pure space. DATA is a buffer holding
4855 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
4856 non-zero means make the result string multibyte.
4858 Must get an error if pure storage is full, since if it cannot hold
4859 a large string it may be able to hold conses that point to that
4860 string; then the string is not protected from gc. */
4863 make_pure_string (const char *data
,
4864 EMACS_INT nchars
, EMACS_INT nbytes
, int multibyte
)
4867 struct Lisp_String
*s
;
4869 s
= (struct Lisp_String
*) pure_alloc (sizeof *s
, Lisp_String
);
4870 s
->data
= (unsigned char *) find_string_data_in_pure (data
, nbytes
);
4871 if (s
->data
== NULL
)
4873 s
->data
= (unsigned char *) pure_alloc (nbytes
+ 1, -1);
4874 memcpy (s
->data
, data
, nbytes
);
4875 s
->data
[nbytes
] = '\0';
4878 s
->size_byte
= multibyte
? nbytes
: -1;
4879 s
->intervals
= NULL_INTERVAL
;
4880 XSETSTRING (string
, s
);
4884 /* Return a string a string allocated in pure space. Do not allocate
4885 the string data, just point to DATA. */
4888 make_pure_c_string (const char *data
)
4891 struct Lisp_String
*s
;
4892 EMACS_INT nchars
= strlen (data
);
4894 s
= (struct Lisp_String
*) pure_alloc (sizeof *s
, Lisp_String
);
4897 s
->data
= (unsigned char *) data
;
4898 s
->intervals
= NULL_INTERVAL
;
4899 XSETSTRING (string
, s
);
4903 /* Return a cons allocated from pure space. Give it pure copies
4904 of CAR as car and CDR as cdr. */
4907 pure_cons (Lisp_Object car
, Lisp_Object cdr
)
4909 register Lisp_Object
new;
4910 struct Lisp_Cons
*p
;
4912 p
= (struct Lisp_Cons
*) pure_alloc (sizeof *p
, Lisp_Cons
);
4914 XSETCAR (new, Fpurecopy (car
));
4915 XSETCDR (new, Fpurecopy (cdr
));
4920 /* Value is a float object with value NUM allocated from pure space. */
4923 make_pure_float (double num
)
4925 register Lisp_Object
new;
4926 struct Lisp_Float
*p
;
4928 p
= (struct Lisp_Float
*) pure_alloc (sizeof *p
, Lisp_Float
);
4930 XFLOAT_INIT (new, num
);
4935 /* Return a vector with room for LEN Lisp_Objects allocated from
4939 make_pure_vector (EMACS_INT len
)
4942 struct Lisp_Vector
*p
;
4943 size_t size
= (offsetof (struct Lisp_Vector
, contents
)
4944 + len
* sizeof (Lisp_Object
));
4946 p
= (struct Lisp_Vector
*) pure_alloc (size
, Lisp_Vectorlike
);
4947 XSETVECTOR (new, p
);
4948 XVECTOR (new)->header
.size
= len
;
4953 DEFUN ("purecopy", Fpurecopy
, Spurecopy
, 1, 1, 0,
4954 doc
: /* Make a copy of object OBJ in pure storage.
4955 Recursively copies contents of vectors and cons cells.
4956 Does not copy symbols. Copies strings without text properties. */)
4957 (register Lisp_Object obj
)
4959 if (NILP (Vpurify_flag
))
4962 if (PURE_POINTER_P (XPNTR (obj
)))
4965 if (HASH_TABLE_P (Vpurify_flag
)) /* Hash consing. */
4967 Lisp_Object tmp
= Fgethash (obj
, Vpurify_flag
, Qnil
);
4973 obj
= pure_cons (XCAR (obj
), XCDR (obj
));
4974 else if (FLOATP (obj
))
4975 obj
= make_pure_float (XFLOAT_DATA (obj
));
4976 else if (STRINGP (obj
))
4977 obj
= make_pure_string (SSDATA (obj
), SCHARS (obj
),
4979 STRING_MULTIBYTE (obj
));
4980 else if (COMPILEDP (obj
) || VECTORP (obj
))
4982 register struct Lisp_Vector
*vec
;
4983 register EMACS_INT i
;
4987 if (size
& PSEUDOVECTOR_FLAG
)
4988 size
&= PSEUDOVECTOR_SIZE_MASK
;
4989 vec
= XVECTOR (make_pure_vector (size
));
4990 for (i
= 0; i
< size
; i
++)
4991 vec
->contents
[i
] = Fpurecopy (XVECTOR (obj
)->contents
[i
]);
4992 if (COMPILEDP (obj
))
4994 XSETPVECTYPE (vec
, PVEC_COMPILED
);
4995 XSETCOMPILED (obj
, vec
);
4998 XSETVECTOR (obj
, vec
);
5000 else if (MARKERP (obj
))
5001 error ("Attempt to copy a marker to pure storage");
5003 /* Not purified, don't hash-cons. */
5006 if (HASH_TABLE_P (Vpurify_flag
)) /* Hash consing. */
5007 Fputhash (obj
, obj
, Vpurify_flag
);
5014 /***********************************************************************
5016 ***********************************************************************/
5018 /* Put an entry in staticvec, pointing at the variable with address
5022 staticpro (Lisp_Object
*varaddress
)
5024 staticvec
[staticidx
++] = varaddress
;
5025 if (staticidx
>= NSTATICS
)
5030 /***********************************************************************
5032 ***********************************************************************/
5034 /* Temporarily prevent garbage collection. */
5037 inhibit_garbage_collection (void)
5039 int count
= SPECPDL_INDEX ();
5041 specbind (Qgc_cons_threshold
, make_number (MOST_POSITIVE_FIXNUM
));
5046 DEFUN ("garbage-collect", Fgarbage_collect
, Sgarbage_collect
, 0, 0, "",
5047 doc
: /* Reclaim storage for Lisp objects no longer needed.
5048 Garbage collection happens automatically if you cons more than
5049 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5050 `garbage-collect' normally returns a list with info on amount of space in use:
5051 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
5052 (USED-MISCS . FREE-MISCS) USED-STRING-CHARS USED-VECTOR-SLOTS
5053 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)
5054 (USED-STRINGS . FREE-STRINGS))
5055 However, if there was overflow in pure space, `garbage-collect'
5056 returns nil, because real GC can't be done.
5057 See Info node `(elisp)Garbage Collection'. */)
5060 register struct specbinding
*bind
;
5061 char stack_top_variable
;
5064 Lisp_Object total
[8];
5065 int count
= SPECPDL_INDEX ();
5066 EMACS_TIME t1
, t2
, t3
;
5071 /* Can't GC if pure storage overflowed because we can't determine
5072 if something is a pure object or not. */
5073 if (pure_bytes_used_before_overflow
)
5078 /* Don't keep undo information around forever.
5079 Do this early on, so it is no problem if the user quits. */
5081 register struct buffer
*nextb
= all_buffers
;
5085 /* If a buffer's undo list is Qt, that means that undo is
5086 turned off in that buffer. Calling truncate_undo_list on
5087 Qt tends to return NULL, which effectively turns undo back on.
5088 So don't call truncate_undo_list if undo_list is Qt. */
5089 if (! NILP (nextb
->BUFFER_INTERNAL_FIELD (name
)) && ! EQ (nextb
->BUFFER_INTERNAL_FIELD (undo_list
), Qt
))
5090 truncate_undo_list (nextb
);
5092 /* Shrink buffer gaps, but skip indirect and dead buffers. */
5093 if (nextb
->base_buffer
== 0 && !NILP (nextb
->BUFFER_INTERNAL_FIELD (name
))
5094 && ! nextb
->text
->inhibit_shrinking
)
5096 /* If a buffer's gap size is more than 10% of the buffer
5097 size, or larger than 2000 bytes, then shrink it
5098 accordingly. Keep a minimum size of 20 bytes. */
5099 int size
= min (2000, max (20, (nextb
->text
->z_byte
/ 10)));
5101 if (nextb
->text
->gap_size
> size
)
5103 struct buffer
*save_current
= current_buffer
;
5104 current_buffer
= nextb
;
5105 make_gap (-(nextb
->text
->gap_size
- size
));
5106 current_buffer
= save_current
;
5110 nextb
= nextb
->header
.next
.buffer
;
5114 EMACS_GET_TIME (t1
);
5116 /* In case user calls debug_print during GC,
5117 don't let that cause a recursive GC. */
5118 consing_since_gc
= 0;
5120 /* Save what's currently displayed in the echo area. */
5121 message_p
= push_message ();
5122 record_unwind_protect (pop_message_unwind
, Qnil
);
5124 /* Save a copy of the contents of the stack, for debugging. */
5125 #if MAX_SAVE_STACK > 0
5126 if (NILP (Vpurify_flag
))
5129 ptrdiff_t stack_size
;
5130 if (&stack_top_variable
< stack_bottom
)
5132 stack
= &stack_top_variable
;
5133 stack_size
= stack_bottom
- &stack_top_variable
;
5137 stack
= stack_bottom
;
5138 stack_size
= &stack_top_variable
- stack_bottom
;
5140 if (stack_size
<= MAX_SAVE_STACK
)
5142 if (stack_copy_size
< stack_size
)
5144 stack_copy
= (char *) xrealloc (stack_copy
, stack_size
);
5145 stack_copy_size
= stack_size
;
5147 memcpy (stack_copy
, stack
, stack_size
);
5150 #endif /* MAX_SAVE_STACK > 0 */
5152 if (garbage_collection_messages
)
5153 message1_nolog ("Garbage collecting...");
5157 shrink_regexp_cache ();
5161 /* clear_marks (); */
5163 /* Mark all the special slots that serve as the roots of accessibility. */
5165 for (i
= 0; i
< staticidx
; i
++)
5166 mark_object (*staticvec
[i
]);
5168 for (bind
= specpdl
; bind
!= specpdl_ptr
; bind
++)
5170 mark_object (bind
->symbol
);
5171 mark_object (bind
->old_value
);
5179 extern void xg_mark_data (void);
5184 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
5185 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
5189 register struct gcpro
*tail
;
5190 for (tail
= gcprolist
; tail
; tail
= tail
->next
)
5191 for (i
= 0; i
< tail
->nvars
; i
++)
5192 mark_object (tail
->var
[i
]);
5196 struct catchtag
*catch;
5197 struct handler
*handler
;
5199 for (catch = catchlist
; catch; catch = catch->next
)
5201 mark_object (catch->tag
);
5202 mark_object (catch->val
);
5204 for (handler
= handlerlist
; handler
; handler
= handler
->next
)
5206 mark_object (handler
->handler
);
5207 mark_object (handler
->var
);
5213 #ifdef HAVE_WINDOW_SYSTEM
5214 mark_fringe_data ();
5217 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5221 /* Everything is now marked, except for the things that require special
5222 finalization, i.e. the undo_list.
5223 Look thru every buffer's undo list
5224 for elements that update markers that were not marked,
5227 register struct buffer
*nextb
= all_buffers
;
5231 /* If a buffer's undo list is Qt, that means that undo is
5232 turned off in that buffer. Calling truncate_undo_list on
5233 Qt tends to return NULL, which effectively turns undo back on.
5234 So don't call truncate_undo_list if undo_list is Qt. */
5235 if (! EQ (nextb
->BUFFER_INTERNAL_FIELD (undo_list
), Qt
))
5237 Lisp_Object tail
, prev
;
5238 tail
= nextb
->BUFFER_INTERNAL_FIELD (undo_list
);
5240 while (CONSP (tail
))
5242 if (CONSP (XCAR (tail
))
5243 && MARKERP (XCAR (XCAR (tail
)))
5244 && !XMARKER (XCAR (XCAR (tail
)))->gcmarkbit
)
5247 nextb
->BUFFER_INTERNAL_FIELD (undo_list
) = tail
= XCDR (tail
);
5251 XSETCDR (prev
, tail
);
5261 /* Now that we have stripped the elements that need not be in the
5262 undo_list any more, we can finally mark the list. */
5263 mark_object (nextb
->BUFFER_INTERNAL_FIELD (undo_list
));
5265 nextb
= nextb
->header
.next
.buffer
;
5271 /* Clear the mark bits that we set in certain root slots. */
5273 unmark_byte_stack ();
5274 VECTOR_UNMARK (&buffer_defaults
);
5275 VECTOR_UNMARK (&buffer_local_symbols
);
5277 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
5285 /* clear_marks (); */
5288 consing_since_gc
= 0;
5289 if (gc_cons_threshold
< 10000)
5290 gc_cons_threshold
= 10000;
5292 gc_relative_threshold
= 0;
5293 if (FLOATP (Vgc_cons_percentage
))
5294 { /* Set gc_cons_combined_threshold. */
5297 tot
+= total_conses
* sizeof (struct Lisp_Cons
);
5298 tot
+= total_symbols
* sizeof (struct Lisp_Symbol
);
5299 tot
+= total_markers
* sizeof (union Lisp_Misc
);
5300 tot
+= total_string_size
;
5301 tot
+= total_vector_size
* sizeof (Lisp_Object
);
5302 tot
+= total_floats
* sizeof (struct Lisp_Float
);
5303 tot
+= total_intervals
* sizeof (struct interval
);
5304 tot
+= total_strings
* sizeof (struct Lisp_String
);
5306 tot
*= XFLOAT_DATA (Vgc_cons_percentage
);
5309 if (tot
< TYPE_MAXIMUM (EMACS_INT
))
5310 gc_relative_threshold
= tot
;
5312 gc_relative_threshold
= TYPE_MAXIMUM (EMACS_INT
);
5316 if (garbage_collection_messages
)
5318 if (message_p
|| minibuf_level
> 0)
5321 message1_nolog ("Garbage collecting...done");
5324 unbind_to (count
, Qnil
);
5326 total
[0] = Fcons (make_number (total_conses
),
5327 make_number (total_free_conses
));
5328 total
[1] = Fcons (make_number (total_symbols
),
5329 make_number (total_free_symbols
));
5330 total
[2] = Fcons (make_number (total_markers
),
5331 make_number (total_free_markers
));
5332 total
[3] = make_number (total_string_size
);
5333 total
[4] = make_number (total_vector_size
);
5334 total
[5] = Fcons (make_number (total_floats
),
5335 make_number (total_free_floats
));
5336 total
[6] = Fcons (make_number (total_intervals
),
5337 make_number (total_free_intervals
));
5338 total
[7] = Fcons (make_number (total_strings
),
5339 make_number (total_free_strings
));
5341 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5343 /* Compute average percentage of zombies. */
5346 for (i
= 0; i
< 7; ++i
)
5347 if (CONSP (total
[i
]))
5348 nlive
+= XFASTINT (XCAR (total
[i
]));
5350 avg_live
= (avg_live
* ngcs
+ nlive
) / (ngcs
+ 1);
5351 max_live
= max (nlive
, max_live
);
5352 avg_zombies
= (avg_zombies
* ngcs
+ nzombies
) / (ngcs
+ 1);
5353 max_zombies
= max (nzombies
, max_zombies
);
5358 if (!NILP (Vpost_gc_hook
))
5360 int gc_count
= inhibit_garbage_collection ();
5361 safe_run_hooks (Qpost_gc_hook
);
5362 unbind_to (gc_count
, Qnil
);
5365 /* Accumulate statistics. */
5366 EMACS_GET_TIME (t2
);
5367 EMACS_SUB_TIME (t3
, t2
, t1
);
5368 if (FLOATP (Vgc_elapsed
))
5369 Vgc_elapsed
= make_float (XFLOAT_DATA (Vgc_elapsed
) +
5371 EMACS_USECS (t3
) * 1.0e-6);
5374 return Flist (sizeof total
/ sizeof *total
, total
);
5378 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5379 only interesting objects referenced from glyphs are strings. */
5382 mark_glyph_matrix (struct glyph_matrix
*matrix
)
5384 struct glyph_row
*row
= matrix
->rows
;
5385 struct glyph_row
*end
= row
+ matrix
->nrows
;
5387 for (; row
< end
; ++row
)
5391 for (area
= LEFT_MARGIN_AREA
; area
< LAST_AREA
; ++area
)
5393 struct glyph
*glyph
= row
->glyphs
[area
];
5394 struct glyph
*end_glyph
= glyph
+ row
->used
[area
];
5396 for (; glyph
< end_glyph
; ++glyph
)
5397 if (STRINGP (glyph
->object
)
5398 && !STRING_MARKED_P (XSTRING (glyph
->object
)))
5399 mark_object (glyph
->object
);
5405 /* Mark Lisp faces in the face cache C. */
5408 mark_face_cache (struct face_cache
*c
)
5413 for (i
= 0; i
< c
->used
; ++i
)
5415 struct face
*face
= FACE_FROM_ID (c
->f
, i
);
5419 for (j
= 0; j
< LFACE_VECTOR_SIZE
; ++j
)
5420 mark_object (face
->lface
[j
]);
5428 /* Mark reference to a Lisp_Object.
5429 If the object referred to has not been seen yet, recursively mark
5430 all the references contained in it. */
5432 #define LAST_MARKED_SIZE 500
5433 static Lisp_Object last_marked
[LAST_MARKED_SIZE
];
5434 static int last_marked_index
;
5436 /* For debugging--call abort when we cdr down this many
5437 links of a list, in mark_object. In debugging,
5438 the call to abort will hit a breakpoint.
5439 Normally this is zero and the check never goes off. */
5440 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE
;
5443 mark_vectorlike (struct Lisp_Vector
*ptr
)
5445 EMACS_INT size
= ptr
->header
.size
;
5448 eassert (!VECTOR_MARKED_P (ptr
));
5449 VECTOR_MARK (ptr
); /* Else mark it */
5450 if (size
& PSEUDOVECTOR_FLAG
)
5451 size
&= PSEUDOVECTOR_SIZE_MASK
;
5453 /* Note that this size is not the memory-footprint size, but only
5454 the number of Lisp_Object fields that we should trace.
5455 The distinction is used e.g. by Lisp_Process which places extra
5456 non-Lisp_Object fields at the end of the structure. */
5457 for (i
= 0; i
< size
; i
++) /* and then mark its elements */
5458 mark_object (ptr
->contents
[i
]);
5461 /* Like mark_vectorlike but optimized for char-tables (and
5462 sub-char-tables) assuming that the contents are mostly integers or
5466 mark_char_table (struct Lisp_Vector
*ptr
)
5468 int size
= ptr
->header
.size
& PSEUDOVECTOR_SIZE_MASK
;
5471 eassert (!VECTOR_MARKED_P (ptr
));
5473 for (i
= 0; i
< size
; i
++)
5475 Lisp_Object val
= ptr
->contents
[i
];
5477 if (INTEGERP (val
) || (SYMBOLP (val
) && XSYMBOL (val
)->gcmarkbit
))
5479 if (SUB_CHAR_TABLE_P (val
))
5481 if (! VECTOR_MARKED_P (XVECTOR (val
)))
5482 mark_char_table (XVECTOR (val
));
5490 mark_object (Lisp_Object arg
)
5492 register Lisp_Object obj
= arg
;
5493 #ifdef GC_CHECK_MARKED_OBJECTS
5497 ptrdiff_t cdr_count
= 0;
5501 if (PURE_POINTER_P (XPNTR (obj
)))
5504 last_marked
[last_marked_index
++] = obj
;
5505 if (last_marked_index
== LAST_MARKED_SIZE
)
5506 last_marked_index
= 0;
5508 /* Perform some sanity checks on the objects marked here. Abort if
5509 we encounter an object we know is bogus. This increases GC time
5510 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
5511 #ifdef GC_CHECK_MARKED_OBJECTS
5513 po
= (void *) XPNTR (obj
);
5515 /* Check that the object pointed to by PO is known to be a Lisp
5516 structure allocated from the heap. */
5517 #define CHECK_ALLOCATED() \
5519 m = mem_find (po); \
5524 /* Check that the object pointed to by PO is live, using predicate
5526 #define CHECK_LIVE(LIVEP) \
5528 if (!LIVEP (m, po)) \
5532 /* Check both of the above conditions. */
5533 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
5535 CHECK_ALLOCATED (); \
5536 CHECK_LIVE (LIVEP); \
5539 #else /* not GC_CHECK_MARKED_OBJECTS */
5541 #define CHECK_LIVE(LIVEP) (void) 0
5542 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
5544 #endif /* not GC_CHECK_MARKED_OBJECTS */
5546 switch (SWITCH_ENUM_CAST (XTYPE (obj
)))
5550 register struct Lisp_String
*ptr
= XSTRING (obj
);
5551 if (STRING_MARKED_P (ptr
))
5553 CHECK_ALLOCATED_AND_LIVE (live_string_p
);
5554 MARK_INTERVAL_TREE (ptr
->intervals
);
5556 #ifdef GC_CHECK_STRING_BYTES
5557 /* Check that the string size recorded in the string is the
5558 same as the one recorded in the sdata structure. */
5559 CHECK_STRING_BYTES (ptr
);
5560 #endif /* GC_CHECK_STRING_BYTES */
5564 case Lisp_Vectorlike
:
5565 if (VECTOR_MARKED_P (XVECTOR (obj
)))
5567 #ifdef GC_CHECK_MARKED_OBJECTS
5569 if (m
== MEM_NIL
&& !SUBRP (obj
)
5570 && po
!= &buffer_defaults
5571 && po
!= &buffer_local_symbols
)
5573 #endif /* GC_CHECK_MARKED_OBJECTS */
5577 #ifdef GC_CHECK_MARKED_OBJECTS
5578 if (po
!= &buffer_defaults
&& po
!= &buffer_local_symbols
)
5581 for (b
= all_buffers
; b
&& b
!= po
; b
= b
->header
.next
.buffer
)
5586 #endif /* GC_CHECK_MARKED_OBJECTS */
5589 else if (SUBRP (obj
))
5591 else if (COMPILEDP (obj
))
5592 /* We could treat this just like a vector, but it is better to
5593 save the COMPILED_CONSTANTS element for last and avoid
5596 register struct Lisp_Vector
*ptr
= XVECTOR (obj
);
5597 int size
= ptr
->header
.size
& PSEUDOVECTOR_SIZE_MASK
;
5600 CHECK_LIVE (live_vector_p
);
5601 VECTOR_MARK (ptr
); /* Else mark it */
5602 for (i
= 0; i
< size
; i
++) /* and then mark its elements */
5604 if (i
!= COMPILED_CONSTANTS
)
5605 mark_object (ptr
->contents
[i
]);
5607 obj
= ptr
->contents
[COMPILED_CONSTANTS
];
5610 else if (FRAMEP (obj
))
5612 register struct frame
*ptr
= XFRAME (obj
);
5613 mark_vectorlike (XVECTOR (obj
));
5614 mark_face_cache (ptr
->face_cache
);
5616 else if (WINDOWP (obj
))
5618 register struct Lisp_Vector
*ptr
= XVECTOR (obj
);
5619 struct window
*w
= XWINDOW (obj
);
5620 mark_vectorlike (ptr
);
5621 /* Mark glyphs for leaf windows. Marking window matrices is
5622 sufficient because frame matrices use the same glyph
5624 if (NILP (w
->hchild
)
5626 && w
->current_matrix
)
5628 mark_glyph_matrix (w
->current_matrix
);
5629 mark_glyph_matrix (w
->desired_matrix
);
5632 else if (HASH_TABLE_P (obj
))
5634 struct Lisp_Hash_Table
*h
= XHASH_TABLE (obj
);
5635 mark_vectorlike ((struct Lisp_Vector
*)h
);
5636 /* If hash table is not weak, mark all keys and values.
5637 For weak tables, mark only the vector. */
5639 mark_object (h
->key_and_value
);
5641 VECTOR_MARK (XVECTOR (h
->key_and_value
));
5643 else if (CHAR_TABLE_P (obj
))
5644 mark_char_table (XVECTOR (obj
));
5646 mark_vectorlike (XVECTOR (obj
));
5651 register struct Lisp_Symbol
*ptr
= XSYMBOL (obj
);
5652 struct Lisp_Symbol
*ptrx
;
5656 CHECK_ALLOCATED_AND_LIVE (live_symbol_p
);
5658 mark_object (ptr
->function
);
5659 mark_object (ptr
->plist
);
5660 switch (ptr
->redirect
)
5662 case SYMBOL_PLAINVAL
: mark_object (SYMBOL_VAL (ptr
)); break;
5663 case SYMBOL_VARALIAS
:
5666 XSETSYMBOL (tem
, SYMBOL_ALIAS (ptr
));
5670 case SYMBOL_LOCALIZED
:
5672 struct Lisp_Buffer_Local_Value
*blv
= SYMBOL_BLV (ptr
);
5673 /* If the value is forwarded to a buffer or keyboard field,
5674 these are marked when we see the corresponding object.
5675 And if it's forwarded to a C variable, either it's not
5676 a Lisp_Object var, or it's staticpro'd already. */
5677 mark_object (blv
->where
);
5678 mark_object (blv
->valcell
);
5679 mark_object (blv
->defcell
);
5682 case SYMBOL_FORWARDED
:
5683 /* If the value is forwarded to a buffer or keyboard field,
5684 these are marked when we see the corresponding object.
5685 And if it's forwarded to a C variable, either it's not
5686 a Lisp_Object var, or it's staticpro'd already. */
5690 if (!PURE_POINTER_P (XSTRING (ptr
->xname
)))
5691 MARK_STRING (XSTRING (ptr
->xname
));
5692 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr
->xname
));
5697 ptrx
= ptr
; /* Use of ptrx avoids compiler bug on Sun */
5698 XSETSYMBOL (obj
, ptrx
);
5705 CHECK_ALLOCATED_AND_LIVE (live_misc_p
);
5706 if (XMISCANY (obj
)->gcmarkbit
)
5708 XMISCANY (obj
)->gcmarkbit
= 1;
5710 switch (XMISCTYPE (obj
))
5713 case Lisp_Misc_Marker
:
5714 /* DO NOT mark thru the marker's chain.
5715 The buffer's markers chain does not preserve markers from gc;
5716 instead, markers are removed from the chain when freed by gc. */
5719 case Lisp_Misc_Save_Value
:
5722 register struct Lisp_Save_Value
*ptr
= XSAVE_VALUE (obj
);
5723 /* If DOGC is set, POINTER is the address of a memory
5724 area containing INTEGER potential Lisp_Objects. */
5727 Lisp_Object
*p
= (Lisp_Object
*) ptr
->pointer
;
5729 for (nelt
= ptr
->integer
; nelt
> 0; nelt
--, p
++)
5730 mark_maybe_object (*p
);
5736 case Lisp_Misc_Overlay
:
5738 struct Lisp_Overlay
*ptr
= XOVERLAY (obj
);
5739 mark_object (ptr
->start
);
5740 mark_object (ptr
->end
);
5741 mark_object (ptr
->plist
);
5744 XSETMISC (obj
, ptr
->next
);
5757 register struct Lisp_Cons
*ptr
= XCONS (obj
);
5758 if (CONS_MARKED_P (ptr
))
5760 CHECK_ALLOCATED_AND_LIVE (live_cons_p
);
5762 /* If the cdr is nil, avoid recursion for the car. */
5763 if (EQ (ptr
->u
.cdr
, Qnil
))
5769 mark_object (ptr
->car
);
5772 if (cdr_count
== mark_object_loop_halt
)
5778 CHECK_ALLOCATED_AND_LIVE (live_float_p
);
5779 FLOAT_MARK (XFLOAT (obj
));
5790 #undef CHECK_ALLOCATED
5791 #undef CHECK_ALLOCATED_AND_LIVE
5794 /* Mark the pointers in a buffer structure. */
5797 mark_buffer (Lisp_Object buf
)
5799 register struct buffer
*buffer
= XBUFFER (buf
);
5800 register Lisp_Object
*ptr
, tmp
;
5801 Lisp_Object base_buffer
;
5803 eassert (!VECTOR_MARKED_P (buffer
));
5804 VECTOR_MARK (buffer
);
5806 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer
));
5808 /* For now, we just don't mark the undo_list. It's done later in
5809 a special way just before the sweep phase, and after stripping
5810 some of its elements that are not needed any more. */
5812 if (buffer
->overlays_before
)
5814 XSETMISC (tmp
, buffer
->overlays_before
);
5817 if (buffer
->overlays_after
)
5819 XSETMISC (tmp
, buffer
->overlays_after
);
5823 /* buffer-local Lisp variables start at `undo_list',
5824 tho only the ones from `name' on are GC'd normally. */
5825 for (ptr
= &buffer
->BUFFER_INTERNAL_FIELD (name
);
5826 ptr
<= &PER_BUFFER_VALUE (buffer
,
5827 PER_BUFFER_VAR_OFFSET (LAST_FIELD_PER_BUFFER
));
5831 /* If this is an indirect buffer, mark its base buffer. */
5832 if (buffer
->base_buffer
&& !VECTOR_MARKED_P (buffer
->base_buffer
))
5834 XSETBUFFER (base_buffer
, buffer
->base_buffer
);
5835 mark_buffer (base_buffer
);
5839 /* Mark the Lisp pointers in the terminal objects.
5840 Called by the Fgarbage_collector. */
5843 mark_terminals (void)
5846 for (t
= terminal_list
; t
; t
= t
->next_terminal
)
5848 eassert (t
->name
!= NULL
);
5849 #ifdef HAVE_WINDOW_SYSTEM
5850 /* If a terminal object is reachable from a stacpro'ed object,
5851 it might have been marked already. Make sure the image cache
5853 mark_image_cache (t
->image_cache
);
5854 #endif /* HAVE_WINDOW_SYSTEM */
5855 if (!VECTOR_MARKED_P (t
))
5856 mark_vectorlike ((struct Lisp_Vector
*)t
);
5862 /* Value is non-zero if OBJ will survive the current GC because it's
5863 either marked or does not need to be marked to survive. */
5866 survives_gc_p (Lisp_Object obj
)
5870 switch (XTYPE (obj
))
5877 survives_p
= XSYMBOL (obj
)->gcmarkbit
;
5881 survives_p
= XMISCANY (obj
)->gcmarkbit
;
5885 survives_p
= STRING_MARKED_P (XSTRING (obj
));
5888 case Lisp_Vectorlike
:
5889 survives_p
= SUBRP (obj
) || VECTOR_MARKED_P (XVECTOR (obj
));
5893 survives_p
= CONS_MARKED_P (XCONS (obj
));
5897 survives_p
= FLOAT_MARKED_P (XFLOAT (obj
));
5904 return survives_p
|| PURE_POINTER_P ((void *) XPNTR (obj
));
5909 /* Sweep: find all structures not marked, and free them. */
5914 /* Remove or mark entries in weak hash tables.
5915 This must be done before any object is unmarked. */
5916 sweep_weak_hash_tables ();
5919 #ifdef GC_CHECK_STRING_BYTES
5920 if (!noninteractive
)
5921 check_string_bytes (1);
5924 /* Put all unmarked conses on free list */
5926 register struct cons_block
*cblk
;
5927 struct cons_block
**cprev
= &cons_block
;
5928 register int lim
= cons_block_index
;
5929 EMACS_INT num_free
= 0, num_used
= 0;
5933 for (cblk
= cons_block
; cblk
; cblk
= *cprev
)
5937 int ilim
= (lim
+ BITS_PER_INT
- 1) / BITS_PER_INT
;
5939 /* Scan the mark bits an int at a time. */
5940 for (i
= 0; i
< ilim
; i
++)
5942 if (cblk
->gcmarkbits
[i
] == -1)
5944 /* Fast path - all cons cells for this int are marked. */
5945 cblk
->gcmarkbits
[i
] = 0;
5946 num_used
+= BITS_PER_INT
;
5950 /* Some cons cells for this int are not marked.
5951 Find which ones, and free them. */
5952 int start
, pos
, stop
;
5954 start
= i
* BITS_PER_INT
;
5956 if (stop
> BITS_PER_INT
)
5957 stop
= BITS_PER_INT
;
5960 for (pos
= start
; pos
< stop
; pos
++)
5962 if (!CONS_MARKED_P (&cblk
->conses
[pos
]))
5965 cblk
->conses
[pos
].u
.chain
= cons_free_list
;
5966 cons_free_list
= &cblk
->conses
[pos
];
5968 cons_free_list
->car
= Vdead
;
5974 CONS_UNMARK (&cblk
->conses
[pos
]);
5980 lim
= CONS_BLOCK_SIZE
;
5981 /* If this block contains only free conses and we have already
5982 seen more than two blocks worth of free conses then deallocate
5984 if (this_free
== CONS_BLOCK_SIZE
&& num_free
> CONS_BLOCK_SIZE
)
5986 *cprev
= cblk
->next
;
5987 /* Unhook from the free list. */
5988 cons_free_list
= cblk
->conses
[0].u
.chain
;
5989 lisp_align_free (cblk
);
5993 num_free
+= this_free
;
5994 cprev
= &cblk
->next
;
5997 total_conses
= num_used
;
5998 total_free_conses
= num_free
;
6001 /* Put all unmarked floats on free list */
6003 register struct float_block
*fblk
;
6004 struct float_block
**fprev
= &float_block
;
6005 register int lim
= float_block_index
;
6006 EMACS_INT num_free
= 0, num_used
= 0;
6008 float_free_list
= 0;
6010 for (fblk
= float_block
; fblk
; fblk
= *fprev
)
6014 for (i
= 0; i
< lim
; i
++)
6015 if (!FLOAT_MARKED_P (&fblk
->floats
[i
]))
6018 fblk
->floats
[i
].u
.chain
= float_free_list
;
6019 float_free_list
= &fblk
->floats
[i
];
6024 FLOAT_UNMARK (&fblk
->floats
[i
]);
6026 lim
= FLOAT_BLOCK_SIZE
;
6027 /* If this block contains only free floats and we have already
6028 seen more than two blocks worth of free floats then deallocate
6030 if (this_free
== FLOAT_BLOCK_SIZE
&& num_free
> FLOAT_BLOCK_SIZE
)
6032 *fprev
= fblk
->next
;
6033 /* Unhook from the free list. */
6034 float_free_list
= fblk
->floats
[0].u
.chain
;
6035 lisp_align_free (fblk
);
6039 num_free
+= this_free
;
6040 fprev
= &fblk
->next
;
6043 total_floats
= num_used
;
6044 total_free_floats
= num_free
;
6047 /* Put all unmarked intervals on free list */
6049 register struct interval_block
*iblk
;
6050 struct interval_block
**iprev
= &interval_block
;
6051 register int lim
= interval_block_index
;
6052 EMACS_INT num_free
= 0, num_used
= 0;
6054 interval_free_list
= 0;
6056 for (iblk
= interval_block
; iblk
; iblk
= *iprev
)
6061 for (i
= 0; i
< lim
; i
++)
6063 if (!iblk
->intervals
[i
].gcmarkbit
)
6065 SET_INTERVAL_PARENT (&iblk
->intervals
[i
], interval_free_list
);
6066 interval_free_list
= &iblk
->intervals
[i
];
6072 iblk
->intervals
[i
].gcmarkbit
= 0;
6075 lim
= INTERVAL_BLOCK_SIZE
;
6076 /* If this block contains only free intervals and we have already
6077 seen more than two blocks worth of free intervals then
6078 deallocate this block. */
6079 if (this_free
== INTERVAL_BLOCK_SIZE
&& num_free
> INTERVAL_BLOCK_SIZE
)
6081 *iprev
= iblk
->next
;
6082 /* Unhook from the free list. */
6083 interval_free_list
= INTERVAL_PARENT (&iblk
->intervals
[0]);
6088 num_free
+= this_free
;
6089 iprev
= &iblk
->next
;
6092 total_intervals
= num_used
;
6093 total_free_intervals
= num_free
;
6096 /* Put all unmarked symbols on free list */
6098 register struct symbol_block
*sblk
;
6099 struct symbol_block
**sprev
= &symbol_block
;
6100 register int lim
= symbol_block_index
;
6101 EMACS_INT num_free
= 0, num_used
= 0;
6103 symbol_free_list
= NULL
;
6105 for (sblk
= symbol_block
; sblk
; sblk
= *sprev
)
6108 union aligned_Lisp_Symbol
*sym
= sblk
->symbols
;
6109 union aligned_Lisp_Symbol
*end
= sym
+ lim
;
6111 for (; sym
< end
; ++sym
)
6113 /* Check if the symbol was created during loadup. In such a case
6114 it might be pointed to by pure bytecode which we don't trace,
6115 so we conservatively assume that it is live. */
6116 int pure_p
= PURE_POINTER_P (XSTRING (sym
->s
.xname
));
6118 if (!sym
->s
.gcmarkbit
&& !pure_p
)
6120 if (sym
->s
.redirect
== SYMBOL_LOCALIZED
)
6121 xfree (SYMBOL_BLV (&sym
->s
));
6122 sym
->s
.next
= symbol_free_list
;
6123 symbol_free_list
= &sym
->s
;
6125 symbol_free_list
->function
= Vdead
;
6133 UNMARK_STRING (XSTRING (sym
->s
.xname
));
6134 sym
->s
.gcmarkbit
= 0;
6138 lim
= SYMBOL_BLOCK_SIZE
;
6139 /* If this block contains only free symbols and we have already
6140 seen more than two blocks worth of free symbols then deallocate
6142 if (this_free
== SYMBOL_BLOCK_SIZE
&& num_free
> SYMBOL_BLOCK_SIZE
)
6144 *sprev
= sblk
->next
;
6145 /* Unhook from the free list. */
6146 symbol_free_list
= sblk
->symbols
[0].s
.next
;
6151 num_free
+= this_free
;
6152 sprev
= &sblk
->next
;
6155 total_symbols
= num_used
;
6156 total_free_symbols
= num_free
;
6159 /* Put all unmarked misc's on free list.
6160 For a marker, first unchain it from the buffer it points into. */
6162 register struct marker_block
*mblk
;
6163 struct marker_block
**mprev
= &marker_block
;
6164 register int lim
= marker_block_index
;
6165 EMACS_INT num_free
= 0, num_used
= 0;
6167 marker_free_list
= 0;
6169 for (mblk
= marker_block
; mblk
; mblk
= *mprev
)
6174 for (i
= 0; i
< lim
; i
++)
6176 if (!mblk
->markers
[i
].m
.u_any
.gcmarkbit
)
6178 if (mblk
->markers
[i
].m
.u_any
.type
== Lisp_Misc_Marker
)
6179 unchain_marker (&mblk
->markers
[i
].m
.u_marker
);
6180 /* Set the type of the freed object to Lisp_Misc_Free.
6181 We could leave the type alone, since nobody checks it,
6182 but this might catch bugs faster. */
6183 mblk
->markers
[i
].m
.u_marker
.type
= Lisp_Misc_Free
;
6184 mblk
->markers
[i
].m
.u_free
.chain
= marker_free_list
;
6185 marker_free_list
= &mblk
->markers
[i
].m
;
6191 mblk
->markers
[i
].m
.u_any
.gcmarkbit
= 0;
6194 lim
= MARKER_BLOCK_SIZE
;
6195 /* If this block contains only free markers and we have already
6196 seen more than two blocks worth of free markers then deallocate
6198 if (this_free
== MARKER_BLOCK_SIZE
&& num_free
> MARKER_BLOCK_SIZE
)
6200 *mprev
= mblk
->next
;
6201 /* Unhook from the free list. */
6202 marker_free_list
= mblk
->markers
[0].m
.u_free
.chain
;
6207 num_free
+= this_free
;
6208 mprev
= &mblk
->next
;
6212 total_markers
= num_used
;
6213 total_free_markers
= num_free
;
6216 /* Free all unmarked buffers */
6218 register struct buffer
*buffer
= all_buffers
, *prev
= 0, *next
;
6221 if (!VECTOR_MARKED_P (buffer
))
6224 prev
->header
.next
= buffer
->header
.next
;
6226 all_buffers
= buffer
->header
.next
.buffer
;
6227 next
= buffer
->header
.next
.buffer
;
6233 VECTOR_UNMARK (buffer
);
6234 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer
));
6235 prev
= buffer
, buffer
= buffer
->header
.next
.buffer
;
6239 /* Free all unmarked vectors */
6241 register struct Lisp_Vector
*vector
= all_vectors
, *prev
= 0, *next
;
6242 total_vector_size
= 0;
6245 if (!VECTOR_MARKED_P (vector
))
6248 prev
->header
.next
= vector
->header
.next
;
6250 all_vectors
= vector
->header
.next
.vector
;
6251 next
= vector
->header
.next
.vector
;
6258 VECTOR_UNMARK (vector
);
6259 if (vector
->header
.size
& PSEUDOVECTOR_FLAG
)
6260 total_vector_size
+= PSEUDOVECTOR_SIZE_MASK
& vector
->header
.size
;
6262 total_vector_size
+= vector
->header
.size
;
6263 prev
= vector
, vector
= vector
->header
.next
.vector
;
6267 #ifdef GC_CHECK_STRING_BYTES
6268 if (!noninteractive
)
6269 check_string_bytes (1);
6276 /* Debugging aids. */
6278 DEFUN ("memory-limit", Fmemory_limit
, Smemory_limit
, 0, 0, 0,
6279 doc
: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6280 This may be helpful in debugging Emacs's memory usage.
6281 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6286 XSETINT (end
, (intptr_t) (char *) sbrk (0) / 1024);
6291 DEFUN ("memory-use-counts", Fmemory_use_counts
, Smemory_use_counts
, 0, 0, 0,
6292 doc
: /* Return a list of counters that measure how much consing there has been.
6293 Each of these counters increments for a certain kind of object.
6294 The counters wrap around from the largest positive integer to zero.
6295 Garbage collection does not decrease them.
6296 The elements of the value are as follows:
6297 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6298 All are in units of 1 = one object consed
6299 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6301 MISCS include overlays, markers, and some internal types.
6302 Frames, windows, buffers, and subprocesses count as vectors
6303 (but the contents of a buffer's text do not count here). */)
6306 Lisp_Object consed
[8];
6308 consed
[0] = make_number (min (MOST_POSITIVE_FIXNUM
, cons_cells_consed
));
6309 consed
[1] = make_number (min (MOST_POSITIVE_FIXNUM
, floats_consed
));
6310 consed
[2] = make_number (min (MOST_POSITIVE_FIXNUM
, vector_cells_consed
));
6311 consed
[3] = make_number (min (MOST_POSITIVE_FIXNUM
, symbols_consed
));
6312 consed
[4] = make_number (min (MOST_POSITIVE_FIXNUM
, string_chars_consed
));
6313 consed
[5] = make_number (min (MOST_POSITIVE_FIXNUM
, misc_objects_consed
));
6314 consed
[6] = make_number (min (MOST_POSITIVE_FIXNUM
, intervals_consed
));
6315 consed
[7] = make_number (min (MOST_POSITIVE_FIXNUM
, strings_consed
));
6317 return Flist (8, consed
);
6320 /* Find at most FIND_MAX symbols which have OBJ as their value or
6321 function. This is used in gdbinit's `xwhichsymbols' command. */
6324 which_symbols (Lisp_Object obj
, EMACS_INT find_max
)
6326 struct symbol_block
*sblk
;
6327 int gc_count
= inhibit_garbage_collection ();
6328 Lisp_Object found
= Qnil
;
6332 for (sblk
= symbol_block
; sblk
; sblk
= sblk
->next
)
6334 union aligned_Lisp_Symbol
*aligned_sym
= sblk
->symbols
;
6337 for (bn
= 0; bn
< SYMBOL_BLOCK_SIZE
; bn
++, aligned_sym
++)
6339 struct Lisp_Symbol
*sym
= &aligned_sym
->s
;
6343 if (sblk
== symbol_block
&& bn
>= symbol_block_index
)
6346 XSETSYMBOL (tem
, sym
);
6347 val
= find_symbol_value (tem
);
6349 || EQ (sym
->function
, obj
)
6350 || (!NILP (sym
->function
)
6351 && COMPILEDP (sym
->function
)
6352 && EQ (AREF (sym
->function
, COMPILED_BYTECODE
), obj
))
6355 && EQ (AREF (val
, COMPILED_BYTECODE
), obj
)))
6357 found
= Fcons (tem
, found
);
6358 if (--find_max
== 0)
6366 unbind_to (gc_count
, Qnil
);
6370 #ifdef ENABLE_CHECKING
6371 int suppress_checking
;
6374 die (const char *msg
, const char *file
, int line
)
6376 fprintf (stderr
, "\r\n%s:%d: Emacs fatal error: %s\r\n",
6382 /* Initialization */
6385 init_alloc_once (void)
6387 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
6389 pure_size
= PURESIZE
;
6390 pure_bytes_used
= 0;
6391 pure_bytes_used_lisp
= pure_bytes_used_non_lisp
= 0;
6392 pure_bytes_used_before_overflow
= 0;
6394 /* Initialize the list of free aligned blocks. */
6397 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
6399 Vdead
= make_pure_string ("DEAD", 4, 4, 0);
6403 ignore_warnings
= 1;
6404 #ifdef DOUG_LEA_MALLOC
6405 mallopt (M_TRIM_THRESHOLD
, 128*1024); /* trim threshold */
6406 mallopt (M_MMAP_THRESHOLD
, 64*1024); /* mmap threshold */
6407 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
); /* max. number of mmap'ed areas */
6415 init_weak_hash_tables ();
6418 malloc_hysteresis
= 32;
6420 malloc_hysteresis
= 0;
6423 refill_memory_reserve ();
6425 ignore_warnings
= 0;
6427 byte_stack_list
= 0;
6429 consing_since_gc
= 0;
6430 gc_cons_threshold
= 100000 * sizeof (Lisp_Object
);
6431 gc_relative_threshold
= 0;
6438 byte_stack_list
= 0;
6440 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
6441 setjmp_tested_p
= longjmps_done
= 0;
6444 Vgc_elapsed
= make_float (0.0);
6449 syms_of_alloc (void)
6451 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold
,
6452 doc
: /* Number of bytes of consing between garbage collections.
6453 Garbage collection can happen automatically once this many bytes have been
6454 allocated since the last garbage collection. All data types count.
6456 Garbage collection happens automatically only when `eval' is called.
6458 By binding this temporarily to a large number, you can effectively
6459 prevent garbage collection during a part of the program.
6460 See also `gc-cons-percentage'. */);
6462 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage
,
6463 doc
: /* Portion of the heap used for allocation.
6464 Garbage collection can happen automatically once this portion of the heap
6465 has been allocated since the last garbage collection.
6466 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
6467 Vgc_cons_percentage
= make_float (0.1);
6469 DEFVAR_INT ("pure-bytes-used", pure_bytes_used
,
6470 doc
: /* Number of bytes of shareable Lisp data allocated so far. */);
6472 DEFVAR_INT ("cons-cells-consed", cons_cells_consed
,
6473 doc
: /* Number of cons cells that have been consed so far. */);
6475 DEFVAR_INT ("floats-consed", floats_consed
,
6476 doc
: /* Number of floats that have been consed so far. */);
6478 DEFVAR_INT ("vector-cells-consed", vector_cells_consed
,
6479 doc
: /* Number of vector cells that have been consed so far. */);
6481 DEFVAR_INT ("symbols-consed", symbols_consed
,
6482 doc
: /* Number of symbols that have been consed so far. */);
6484 DEFVAR_INT ("string-chars-consed", string_chars_consed
,
6485 doc
: /* Number of string characters that have been consed so far. */);
6487 DEFVAR_INT ("misc-objects-consed", misc_objects_consed
,
6488 doc
: /* Number of miscellaneous objects that have been consed so far.
6489 These include markers and overlays, plus certain objects not visible
6492 DEFVAR_INT ("intervals-consed", intervals_consed
,
6493 doc
: /* Number of intervals that have been consed so far. */);
6495 DEFVAR_INT ("strings-consed", strings_consed
,
6496 doc
: /* Number of strings that have been consed so far. */);
6498 DEFVAR_LISP ("purify-flag", Vpurify_flag
,
6499 doc
: /* Non-nil means loading Lisp code in order to dump an executable.
6500 This means that certain objects should be allocated in shared (pure) space.
6501 It can also be set to a hash-table, in which case this table is used to
6502 do hash-consing of the objects allocated to pure space. */);
6504 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages
,
6505 doc
: /* Non-nil means display messages at start and end of garbage collection. */);
6506 garbage_collection_messages
= 0;
6508 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook
,
6509 doc
: /* Hook run after garbage collection has finished. */);
6510 Vpost_gc_hook
= Qnil
;
6511 DEFSYM (Qpost_gc_hook
, "post-gc-hook");
6513 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data
,
6514 doc
: /* Precomputed `signal' argument for memory-full error. */);
6515 /* We build this in advance because if we wait until we need it, we might
6516 not be able to allocate the memory to hold it. */
6518 = pure_cons (Qerror
,
6519 pure_cons (make_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"), Qnil
));
6521 DEFVAR_LISP ("memory-full", Vmemory_full
,
6522 doc
: /* Non-nil means Emacs cannot get much more Lisp memory. */);
6523 Vmemory_full
= Qnil
;
6525 DEFSYM (Qgc_cons_threshold
, "gc-cons-threshold");
6526 DEFSYM (Qchar_table_extra_slots
, "char-table-extra-slots");
6528 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed
,
6529 doc
: /* Accumulated time elapsed in garbage collections.
6530 The time is in seconds as a floating point value. */);
6531 DEFVAR_INT ("gcs-done", gcs_done
,
6532 doc
: /* Accumulated number of garbage collections done. */);
6537 defsubr (&Smake_byte_code
);
6538 defsubr (&Smake_list
);
6539 defsubr (&Smake_vector
);
6540 defsubr (&Smake_string
);
6541 defsubr (&Smake_bool_vector
);
6542 defsubr (&Smake_symbol
);
6543 defsubr (&Smake_marker
);
6544 defsubr (&Spurecopy
);
6545 defsubr (&Sgarbage_collect
);
6546 defsubr (&Smemory_limit
);
6547 defsubr (&Smemory_use_counts
);
6549 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
6550 defsubr (&Sgc_status
);