1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
2 Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2011
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <limits.h> /* For CHAR_BIT. */
31 #ifdef HAVE_GTK_AND_PTHREAD
35 /* This file is part of the core Lisp implementation, and thus must
36 deal with the real data structures. If the Lisp implementation is
37 replaced, this file likely will not be used. */
39 #undef HIDE_LISP_IMPLEMENTATION
42 #include "intervals.h"
48 #include "blockinput.h"
49 #include "character.h"
50 #include "syssignal.h"
51 #include "termhooks.h" /* For struct terminal. */
54 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
55 memory. Can do this only if using gmalloc.c. */
57 #if defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC
58 #undef GC_MALLOC_CHECK
63 extern POINTER_TYPE
*sbrk ();
72 #ifdef DOUG_LEA_MALLOC
75 /* malloc.h #defines this as size_t, at least in glibc2. */
76 #ifndef __malloc_size_t
77 #define __malloc_size_t int
80 /* Specify maximum number of areas to mmap. It would be nice to use a
81 value that explicitly means "no limit". */
83 #define MMAP_MAX_AREAS 100000000
85 #else /* not DOUG_LEA_MALLOC */
87 /* The following come from gmalloc.c. */
89 #define __malloc_size_t size_t
90 extern __malloc_size_t _bytes_used
;
91 extern __malloc_size_t __malloc_extra_blocks
;
93 #endif /* not DOUG_LEA_MALLOC */
95 #if ! defined SYSTEM_MALLOC && ! defined SYNC_INPUT
96 #ifdef HAVE_GTK_AND_PTHREAD
98 /* When GTK uses the file chooser dialog, different backends can be loaded
99 dynamically. One such a backend is the Gnome VFS backend that gets loaded
100 if you run Gnome. That backend creates several threads and also allocates
103 If Emacs sets malloc hooks (! SYSTEM_MALLOC) and the emacs_blocked_*
104 functions below are called from malloc, there is a chance that one
105 of these threads preempts the Emacs main thread and the hook variables
106 end up in an inconsistent state. So we have a mutex to prevent that (note
107 that the backend handles concurrent access to malloc within its own threads
108 but Emacs code running in the main thread is not included in that control).
110 When UNBLOCK_INPUT is called, reinvoke_input_signal may be called. If this
111 happens in one of the backend threads we will have two threads that tries
112 to run Emacs code at once, and the code is not prepared for that.
113 To prevent that, we only call BLOCK/UNBLOCK from the main thread. */
115 static pthread_mutex_t alloc_mutex
;
117 #define BLOCK_INPUT_ALLOC \
120 if (pthread_equal (pthread_self (), main_thread)) \
122 pthread_mutex_lock (&alloc_mutex); \
125 #define UNBLOCK_INPUT_ALLOC \
128 pthread_mutex_unlock (&alloc_mutex); \
129 if (pthread_equal (pthread_self (), main_thread)) \
134 #else /* ! defined HAVE_GTK_AND_PTHREAD */
136 #define BLOCK_INPUT_ALLOC BLOCK_INPUT
137 #define UNBLOCK_INPUT_ALLOC UNBLOCK_INPUT
139 #endif /* ! defined HAVE_GTK_AND_PTHREAD */
140 #endif /* ! defined SYSTEM_MALLOC && ! defined SYNC_INPUT */
142 /* Value of _bytes_used, when spare_memory was freed. */
144 static __malloc_size_t bytes_used_when_full
;
146 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
147 to a struct Lisp_String. */
149 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
150 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
151 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
153 #define VECTOR_MARK(V) ((V)->size |= ARRAY_MARK_FLAG)
154 #define VECTOR_UNMARK(V) ((V)->size &= ~ARRAY_MARK_FLAG)
155 #define VECTOR_MARKED_P(V) (((V)->size & ARRAY_MARK_FLAG) != 0)
157 /* Value is the number of bytes of S, a pointer to a struct Lisp_String.
158 Be careful during GC, because S->size contains the mark bit for
161 #define GC_STRING_BYTES(S) (STRING_BYTES (S))
163 /* Global variables. */
164 struct emacs_globals globals
;
166 /* Number of bytes of consing done since the last gc. */
168 int consing_since_gc
;
170 /* Similar minimum, computed from Vgc_cons_percentage. */
172 EMACS_INT gc_relative_threshold
;
174 /* Minimum number of bytes of consing since GC before next GC,
175 when memory is full. */
177 EMACS_INT memory_full_cons_threshold
;
179 /* Nonzero during GC. */
183 /* Nonzero means abort if try to GC.
184 This is for code which is written on the assumption that
185 no GC will happen, so as to verify that assumption. */
189 /* Number of live and free conses etc. */
191 static int total_conses
, total_markers
, total_symbols
, total_vector_size
;
192 static int total_free_conses
, total_free_markers
, total_free_symbols
;
193 static int total_free_floats
, total_floats
;
195 /* Points to memory space allocated as "spare", to be freed if we run
196 out of memory. We keep one large block, four cons-blocks, and
197 two string blocks. */
199 static char *spare_memory
[7];
201 /* Amount of spare memory to keep in large reserve block. */
203 #define SPARE_MEMORY (1 << 14)
205 /* Number of extra blocks malloc should get when it needs more core. */
207 static int malloc_hysteresis
;
209 /* Initialize it to a nonzero value to force it into data space
210 (rather than bss space). That way unexec will remap it into text
211 space (pure), on some systems. We have not implemented the
212 remapping on more recent systems because this is less important
213 nowadays than in the days of small memories and timesharing. */
215 EMACS_INT pure
[(PURESIZE
+ sizeof (EMACS_INT
) - 1) / sizeof (EMACS_INT
)] = {1,};
216 #define PUREBEG (char *) pure
218 /* Pointer to the pure area, and its size. */
220 static char *purebeg
;
221 static size_t pure_size
;
223 /* Number of bytes of pure storage used before pure storage overflowed.
224 If this is non-zero, this implies that an overflow occurred. */
226 static size_t pure_bytes_used_before_overflow
;
228 /* Value is non-zero if P points into pure space. */
230 #define PURE_POINTER_P(P) \
231 (((PNTR_COMPARISON_TYPE) (P) \
232 < (PNTR_COMPARISON_TYPE) ((char *) purebeg + pure_size)) \
233 && ((PNTR_COMPARISON_TYPE) (P) \
234 >= (PNTR_COMPARISON_TYPE) purebeg))
236 /* Index in pure at which next pure Lisp object will be allocated.. */
238 static EMACS_INT pure_bytes_used_lisp
;
240 /* Number of bytes allocated for non-Lisp objects in pure storage. */
242 static EMACS_INT pure_bytes_used_non_lisp
;
244 /* If nonzero, this is a warning delivered by malloc and not yet
247 const char *pending_malloc_warning
;
249 /* Maximum amount of C stack to save when a GC happens. */
251 #ifndef MAX_SAVE_STACK
252 #define MAX_SAVE_STACK 16000
255 /* Buffer in which we save a copy of the C stack at each GC. */
257 static char *stack_copy
;
258 static int stack_copy_size
;
260 /* Non-zero means ignore malloc warnings. Set during initialization.
261 Currently not used. */
263 static int ignore_warnings
;
265 Lisp_Object Qgc_cons_threshold
, Qchar_table_extra_slots
;
267 /* Hook run after GC has finished. */
269 Lisp_Object Qpost_gc_hook
;
271 static void mark_buffer (Lisp_Object
);
272 static void mark_terminals (void);
273 static void gc_sweep (void);
274 static void mark_glyph_matrix (struct glyph_matrix
*);
275 static void mark_face_cache (struct face_cache
*);
277 static struct Lisp_String
*allocate_string (void);
278 static void compact_small_strings (void);
279 static void free_large_strings (void);
280 static void sweep_strings (void);
282 extern int message_enable_multibyte
;
284 /* When scanning the C stack for live Lisp objects, Emacs keeps track
285 of what memory allocated via lisp_malloc is intended for what
286 purpose. This enumeration specifies the type of memory. */
297 /* We used to keep separate mem_types for subtypes of vectors such as
298 process, hash_table, frame, terminal, and window, but we never made
299 use of the distinction, so it only caused source-code complexity
300 and runtime slowdown. Minor but pointless. */
304 static POINTER_TYPE
*lisp_align_malloc (size_t, enum mem_type
);
305 static POINTER_TYPE
*lisp_malloc (size_t, enum mem_type
);
308 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
310 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
311 #include <stdio.h> /* For fprintf. */
314 /* A unique object in pure space used to make some Lisp objects
315 on free lists recognizable in O(1). */
317 static Lisp_Object Vdead
;
319 #ifdef GC_MALLOC_CHECK
321 enum mem_type allocated_mem_type
;
322 static int dont_register_blocks
;
324 #endif /* GC_MALLOC_CHECK */
326 /* A node in the red-black tree describing allocated memory containing
327 Lisp data. Each such block is recorded with its start and end
328 address when it is allocated, and removed from the tree when it
331 A red-black tree is a balanced binary tree with the following
334 1. Every node is either red or black.
335 2. Every leaf is black.
336 3. If a node is red, then both of its children are black.
337 4. Every simple path from a node to a descendant leaf contains
338 the same number of black nodes.
339 5. The root is always black.
341 When nodes are inserted into the tree, or deleted from the tree,
342 the tree is "fixed" so that these properties are always true.
344 A red-black tree with N internal nodes has height at most 2
345 log(N+1). Searches, insertions and deletions are done in O(log N).
346 Please see a text book about data structures for a detailed
347 description of red-black trees. Any book worth its salt should
352 /* Children of this node. These pointers are never NULL. When there
353 is no child, the value is MEM_NIL, which points to a dummy node. */
354 struct mem_node
*left
, *right
;
356 /* The parent of this node. In the root node, this is NULL. */
357 struct mem_node
*parent
;
359 /* Start and end of allocated region. */
363 enum {MEM_BLACK
, MEM_RED
} color
;
369 /* Base address of stack. Set in main. */
371 Lisp_Object
*stack_base
;
373 /* Root of the tree describing allocated Lisp memory. */
375 static struct mem_node
*mem_root
;
377 /* Lowest and highest known address in the heap. */
379 static void *min_heap_address
, *max_heap_address
;
381 /* Sentinel node of the tree. */
383 static struct mem_node mem_z
;
384 #define MEM_NIL &mem_z
386 static struct Lisp_Vector
*allocate_vectorlike (EMACS_INT
);
387 static void lisp_free (POINTER_TYPE
*);
388 static void mark_stack (void);
389 static int live_vector_p (struct mem_node
*, void *);
390 static int live_buffer_p (struct mem_node
*, void *);
391 static int live_string_p (struct mem_node
*, void *);
392 static int live_cons_p (struct mem_node
*, void *);
393 static int live_symbol_p (struct mem_node
*, void *);
394 static int live_float_p (struct mem_node
*, void *);
395 static int live_misc_p (struct mem_node
*, void *);
396 static void mark_maybe_object (Lisp_Object
);
397 static void mark_memory (void *, void *, int);
398 static void mem_init (void);
399 static struct mem_node
*mem_insert (void *, void *, enum mem_type
);
400 static void mem_insert_fixup (struct mem_node
*);
401 static void mem_rotate_left (struct mem_node
*);
402 static void mem_rotate_right (struct mem_node
*);
403 static void mem_delete (struct mem_node
*);
404 static void mem_delete_fixup (struct mem_node
*);
405 static INLINE
struct mem_node
*mem_find (void *);
408 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
409 static void check_gcpros (void);
412 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
414 /* Recording what needs to be marked for gc. */
416 struct gcpro
*gcprolist
;
418 /* Addresses of staticpro'd variables. Initialize it to a nonzero
419 value; otherwise some compilers put it into BSS. */
421 #define NSTATICS 0x640
422 static Lisp_Object
*staticvec
[NSTATICS
] = {&Vpurify_flag
};
424 /* Index of next unused slot in staticvec. */
426 static int staticidx
= 0;
428 static POINTER_TYPE
*pure_alloc (size_t, int);
431 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
432 ALIGNMENT must be a power of 2. */
434 #define ALIGN(ptr, ALIGNMENT) \
435 ((POINTER_TYPE *) ((((EMACS_UINT)(ptr)) + (ALIGNMENT) - 1) \
436 & ~((ALIGNMENT) - 1)))
440 /************************************************************************
442 ************************************************************************/
444 /* Function malloc calls this if it finds we are near exhausting storage. */
447 malloc_warning (const char *str
)
449 pending_malloc_warning
= str
;
453 /* Display an already-pending malloc warning. */
456 display_malloc_warning (void)
458 call3 (intern ("display-warning"),
460 build_string (pending_malloc_warning
),
461 intern ("emergency"));
462 pending_malloc_warning
= 0;
466 #ifdef DOUG_LEA_MALLOC
467 # define BYTES_USED (mallinfo ().uordblks)
469 # define BYTES_USED _bytes_used
472 /* Called if we can't allocate relocatable space for a buffer. */
475 buffer_memory_full (void)
477 /* If buffers use the relocating allocator, no need to free
478 spare_memory, because we may have plenty of malloc space left
479 that we could get, and if we don't, the malloc that fails will
480 itself cause spare_memory to be freed. If buffers don't use the
481 relocating allocator, treat this like any other failing
488 /* This used to call error, but if we've run out of memory, we could
489 get infinite recursion trying to build the string. */
490 xsignal (Qnil
, Vmemory_signal_data
);
494 #ifdef XMALLOC_OVERRUN_CHECK
496 /* Check for overrun in malloc'ed buffers by wrapping a 16 byte header
497 and a 16 byte trailer around each block.
499 The header consists of 12 fixed bytes + a 4 byte integer contaning the
500 original block size, while the trailer consists of 16 fixed bytes.
502 The header is used to detect whether this block has been allocated
503 through these functions -- as it seems that some low-level libc
504 functions may bypass the malloc hooks.
508 #define XMALLOC_OVERRUN_CHECK_SIZE 16
510 static char xmalloc_overrun_check_header
[XMALLOC_OVERRUN_CHECK_SIZE
-4] =
511 { 0x9a, 0x9b, 0xae, 0xaf,
512 0xbf, 0xbe, 0xce, 0xcf,
513 0xea, 0xeb, 0xec, 0xed };
515 static char xmalloc_overrun_check_trailer
[XMALLOC_OVERRUN_CHECK_SIZE
] =
516 { 0xaa, 0xab, 0xac, 0xad,
517 0xba, 0xbb, 0xbc, 0xbd,
518 0xca, 0xcb, 0xcc, 0xcd,
519 0xda, 0xdb, 0xdc, 0xdd };
521 /* Macros to insert and extract the block size in the header. */
523 #define XMALLOC_PUT_SIZE(ptr, size) \
524 (ptr[-1] = (size & 0xff), \
525 ptr[-2] = ((size >> 8) & 0xff), \
526 ptr[-3] = ((size >> 16) & 0xff), \
527 ptr[-4] = ((size >> 24) & 0xff))
529 #define XMALLOC_GET_SIZE(ptr) \
530 (size_t)((unsigned)(ptr[-1]) | \
531 ((unsigned)(ptr[-2]) << 8) | \
532 ((unsigned)(ptr[-3]) << 16) | \
533 ((unsigned)(ptr[-4]) << 24))
536 /* The call depth in overrun_check functions. For example, this might happen:
538 overrun_check_malloc()
539 -> malloc -> (via hook)_-> emacs_blocked_malloc
540 -> overrun_check_malloc
541 call malloc (hooks are NULL, so real malloc is called).
542 malloc returns 10000.
543 add overhead, return 10016.
544 <- (back in overrun_check_malloc)
545 add overhead again, return 10032
546 xmalloc returns 10032.
551 overrun_check_free(10032)
553 free(10016) <- crash, because 10000 is the original pointer. */
555 static int check_depth
;
557 /* Like malloc, but wraps allocated block with header and trailer. */
560 overrun_check_malloc (size
)
563 register unsigned char *val
;
564 size_t overhead
= ++check_depth
== 1 ? XMALLOC_OVERRUN_CHECK_SIZE
*2 : 0;
566 val
= (unsigned char *) malloc (size
+ overhead
);
567 if (val
&& check_depth
== 1)
569 memcpy (val
, xmalloc_overrun_check_header
,
570 XMALLOC_OVERRUN_CHECK_SIZE
- 4);
571 val
+= XMALLOC_OVERRUN_CHECK_SIZE
;
572 XMALLOC_PUT_SIZE(val
, size
);
573 memcpy (val
+ size
, xmalloc_overrun_check_trailer
,
574 XMALLOC_OVERRUN_CHECK_SIZE
);
577 return (POINTER_TYPE
*)val
;
581 /* Like realloc, but checks old block for overrun, and wraps new block
582 with header and trailer. */
585 overrun_check_realloc (block
, size
)
589 register unsigned char *val
= (unsigned char *)block
;
590 size_t overhead
= ++check_depth
== 1 ? XMALLOC_OVERRUN_CHECK_SIZE
*2 : 0;
594 && memcmp (xmalloc_overrun_check_header
,
595 val
- XMALLOC_OVERRUN_CHECK_SIZE
,
596 XMALLOC_OVERRUN_CHECK_SIZE
- 4) == 0)
598 size_t osize
= XMALLOC_GET_SIZE (val
);
599 if (memcmp (xmalloc_overrun_check_trailer
, val
+ osize
,
600 XMALLOC_OVERRUN_CHECK_SIZE
))
602 memset (val
+ osize
, 0, XMALLOC_OVERRUN_CHECK_SIZE
);
603 val
-= XMALLOC_OVERRUN_CHECK_SIZE
;
604 memset (val
, 0, XMALLOC_OVERRUN_CHECK_SIZE
);
607 val
= (unsigned char *) realloc ((POINTER_TYPE
*)val
, size
+ overhead
);
609 if (val
&& check_depth
== 1)
611 memcpy (val
, xmalloc_overrun_check_header
,
612 XMALLOC_OVERRUN_CHECK_SIZE
- 4);
613 val
+= XMALLOC_OVERRUN_CHECK_SIZE
;
614 XMALLOC_PUT_SIZE(val
, size
);
615 memcpy (val
+ size
, xmalloc_overrun_check_trailer
,
616 XMALLOC_OVERRUN_CHECK_SIZE
);
619 return (POINTER_TYPE
*)val
;
622 /* Like free, but checks block for overrun. */
625 overrun_check_free (block
)
628 unsigned char *val
= (unsigned char *)block
;
633 && memcmp (xmalloc_overrun_check_header
,
634 val
- XMALLOC_OVERRUN_CHECK_SIZE
,
635 XMALLOC_OVERRUN_CHECK_SIZE
- 4) == 0)
637 size_t osize
= XMALLOC_GET_SIZE (val
);
638 if (memcmp (xmalloc_overrun_check_trailer
, val
+ osize
,
639 XMALLOC_OVERRUN_CHECK_SIZE
))
641 #ifdef XMALLOC_CLEAR_FREE_MEMORY
642 val
-= XMALLOC_OVERRUN_CHECK_SIZE
;
643 memset (val
, 0xff, osize
+ XMALLOC_OVERRUN_CHECK_SIZE
*2);
645 memset (val
+ osize
, 0, XMALLOC_OVERRUN_CHECK_SIZE
);
646 val
-= XMALLOC_OVERRUN_CHECK_SIZE
;
647 memset (val
, 0, XMALLOC_OVERRUN_CHECK_SIZE
);
658 #define malloc overrun_check_malloc
659 #define realloc overrun_check_realloc
660 #define free overrun_check_free
664 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
665 there's no need to block input around malloc. */
666 #define MALLOC_BLOCK_INPUT ((void)0)
667 #define MALLOC_UNBLOCK_INPUT ((void)0)
669 #define MALLOC_BLOCK_INPUT BLOCK_INPUT
670 #define MALLOC_UNBLOCK_INPUT UNBLOCK_INPUT
673 /* Like malloc but check for no memory and block interrupt input.. */
676 xmalloc (size_t size
)
678 register POINTER_TYPE
*val
;
681 val
= (POINTER_TYPE
*) malloc (size
);
682 MALLOC_UNBLOCK_INPUT
;
690 /* Like realloc but check for no memory and block interrupt input.. */
693 xrealloc (POINTER_TYPE
*block
, size_t size
)
695 register POINTER_TYPE
*val
;
698 /* We must call malloc explicitly when BLOCK is 0, since some
699 reallocs don't do this. */
701 val
= (POINTER_TYPE
*) malloc (size
);
703 val
= (POINTER_TYPE
*) realloc (block
, size
);
704 MALLOC_UNBLOCK_INPUT
;
706 if (!val
&& size
) memory_full ();
711 /* Like free but block interrupt input. */
714 xfree (POINTER_TYPE
*block
)
720 MALLOC_UNBLOCK_INPUT
;
721 /* We don't call refill_memory_reserve here
722 because that duplicates doing so in emacs_blocked_free
723 and the criterion should go there. */
727 /* Like strdup, but uses xmalloc. */
730 xstrdup (const char *s
)
732 size_t len
= strlen (s
) + 1;
733 char *p
= (char *) xmalloc (len
);
739 /* Unwind for SAFE_ALLOCA */
742 safe_alloca_unwind (Lisp_Object arg
)
744 register struct Lisp_Save_Value
*p
= XSAVE_VALUE (arg
);
754 /* Like malloc but used for allocating Lisp data. NBYTES is the
755 number of bytes to allocate, TYPE describes the intended use of the
756 allcated memory block (for strings, for conses, ...). */
759 static void *lisp_malloc_loser
;
762 static POINTER_TYPE
*
763 lisp_malloc (size_t nbytes
, enum mem_type type
)
769 #ifdef GC_MALLOC_CHECK
770 allocated_mem_type
= type
;
773 val
= (void *) malloc (nbytes
);
776 /* If the memory just allocated cannot be addressed thru a Lisp
777 object's pointer, and it needs to be,
778 that's equivalent to running out of memory. */
779 if (val
&& type
!= MEM_TYPE_NON_LISP
)
782 XSETCONS (tem
, (char *) val
+ nbytes
- 1);
783 if ((char *) XCONS (tem
) != (char *) val
+ nbytes
- 1)
785 lisp_malloc_loser
= val
;
792 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
793 if (val
&& type
!= MEM_TYPE_NON_LISP
)
794 mem_insert (val
, (char *) val
+ nbytes
, type
);
797 MALLOC_UNBLOCK_INPUT
;
803 /* Free BLOCK. This must be called to free memory allocated with a
804 call to lisp_malloc. */
807 lisp_free (POINTER_TYPE
*block
)
811 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
812 mem_delete (mem_find (block
));
814 MALLOC_UNBLOCK_INPUT
;
817 /* Allocation of aligned blocks of memory to store Lisp data. */
818 /* The entry point is lisp_align_malloc which returns blocks of at most */
819 /* BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
821 /* Use posix_memalloc if the system has it and we're using the system's
822 malloc (because our gmalloc.c routines don't have posix_memalign although
823 its memalloc could be used). */
824 #if defined (HAVE_POSIX_MEMALIGN) && defined (SYSTEM_MALLOC)
825 #define USE_POSIX_MEMALIGN 1
828 /* BLOCK_ALIGN has to be a power of 2. */
829 #define BLOCK_ALIGN (1 << 10)
831 /* Padding to leave at the end of a malloc'd block. This is to give
832 malloc a chance to minimize the amount of memory wasted to alignment.
833 It should be tuned to the particular malloc library used.
834 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
835 posix_memalign on the other hand would ideally prefer a value of 4
836 because otherwise, there's 1020 bytes wasted between each ablocks.
837 In Emacs, testing shows that those 1020 can most of the time be
838 efficiently used by malloc to place other objects, so a value of 0 can
839 still preferable unless you have a lot of aligned blocks and virtually
841 #define BLOCK_PADDING 0
842 #define BLOCK_BYTES \
843 (BLOCK_ALIGN - sizeof (struct ablock *) - BLOCK_PADDING)
845 /* Internal data structures and constants. */
847 #define ABLOCKS_SIZE 16
849 /* An aligned block of memory. */
854 char payload
[BLOCK_BYTES
];
855 struct ablock
*next_free
;
857 /* `abase' is the aligned base of the ablocks. */
858 /* It is overloaded to hold the virtual `busy' field that counts
859 the number of used ablock in the parent ablocks.
860 The first ablock has the `busy' field, the others have the `abase'
861 field. To tell the difference, we assume that pointers will have
862 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
863 is used to tell whether the real base of the parent ablocks is `abase'
864 (if not, the word before the first ablock holds a pointer to the
866 struct ablocks
*abase
;
867 /* The padding of all but the last ablock is unused. The padding of
868 the last ablock in an ablocks is not allocated. */
870 char padding
[BLOCK_PADDING
];
874 /* A bunch of consecutive aligned blocks. */
877 struct ablock blocks
[ABLOCKS_SIZE
];
880 /* Size of the block requested from malloc or memalign. */
881 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
883 #define ABLOCK_ABASE(block) \
884 (((unsigned long) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
885 ? (struct ablocks *)(block) \
888 /* Virtual `busy' field. */
889 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
891 /* Pointer to the (not necessarily aligned) malloc block. */
892 #ifdef USE_POSIX_MEMALIGN
893 #define ABLOCKS_BASE(abase) (abase)
895 #define ABLOCKS_BASE(abase) \
896 (1 & (long) ABLOCKS_BUSY (abase) ? abase : ((void**)abase)[-1])
899 /* The list of free ablock. */
900 static struct ablock
*free_ablock
;
902 /* Allocate an aligned block of nbytes.
903 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
904 smaller or equal to BLOCK_BYTES. */
905 static POINTER_TYPE
*
906 lisp_align_malloc (size_t nbytes
, enum mem_type type
)
909 struct ablocks
*abase
;
911 eassert (nbytes
<= BLOCK_BYTES
);
915 #ifdef GC_MALLOC_CHECK
916 allocated_mem_type
= type
;
922 EMACS_INT aligned
; /* int gets warning casting to 64-bit pointer. */
924 #ifdef DOUG_LEA_MALLOC
925 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
926 because mapped region contents are not preserved in
928 mallopt (M_MMAP_MAX
, 0);
931 #ifdef USE_POSIX_MEMALIGN
933 int err
= posix_memalign (&base
, BLOCK_ALIGN
, ABLOCKS_BYTES
);
939 base
= malloc (ABLOCKS_BYTES
);
940 abase
= ALIGN (base
, BLOCK_ALIGN
);
945 MALLOC_UNBLOCK_INPUT
;
949 aligned
= (base
== abase
);
951 ((void**)abase
)[-1] = base
;
953 #ifdef DOUG_LEA_MALLOC
954 /* Back to a reasonable maximum of mmap'ed areas. */
955 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
);
959 /* If the memory just allocated cannot be addressed thru a Lisp
960 object's pointer, and it needs to be, that's equivalent to
961 running out of memory. */
962 if (type
!= MEM_TYPE_NON_LISP
)
965 char *end
= (char *) base
+ ABLOCKS_BYTES
- 1;
967 if ((char *) XCONS (tem
) != end
)
969 lisp_malloc_loser
= base
;
971 MALLOC_UNBLOCK_INPUT
;
977 /* Initialize the blocks and put them on the free list.
978 Is `base' was not properly aligned, we can't use the last block. */
979 for (i
= 0; i
< (aligned
? ABLOCKS_SIZE
: ABLOCKS_SIZE
- 1); i
++)
981 abase
->blocks
[i
].abase
= abase
;
982 abase
->blocks
[i
].x
.next_free
= free_ablock
;
983 free_ablock
= &abase
->blocks
[i
];
985 ABLOCKS_BUSY (abase
) = (struct ablocks
*) (long) aligned
;
987 eassert (0 == ((EMACS_UINT
)abase
) % BLOCK_ALIGN
);
988 eassert (ABLOCK_ABASE (&abase
->blocks
[3]) == abase
); /* 3 is arbitrary */
989 eassert (ABLOCK_ABASE (&abase
->blocks
[0]) == abase
);
990 eassert (ABLOCKS_BASE (abase
) == base
);
991 eassert (aligned
== (long) ABLOCKS_BUSY (abase
));
994 abase
= ABLOCK_ABASE (free_ablock
);
995 ABLOCKS_BUSY (abase
) = (struct ablocks
*) (2 + (long) ABLOCKS_BUSY (abase
));
997 free_ablock
= free_ablock
->x
.next_free
;
999 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1000 if (val
&& type
!= MEM_TYPE_NON_LISP
)
1001 mem_insert (val
, (char *) val
+ nbytes
, type
);
1004 MALLOC_UNBLOCK_INPUT
;
1008 eassert (0 == ((EMACS_UINT
)val
) % BLOCK_ALIGN
);
1013 lisp_align_free (POINTER_TYPE
*block
)
1015 struct ablock
*ablock
= block
;
1016 struct ablocks
*abase
= ABLOCK_ABASE (ablock
);
1019 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1020 mem_delete (mem_find (block
));
1022 /* Put on free list. */
1023 ablock
->x
.next_free
= free_ablock
;
1024 free_ablock
= ablock
;
1025 /* Update busy count. */
1026 ABLOCKS_BUSY (abase
) = (struct ablocks
*) (-2 + (long) ABLOCKS_BUSY (abase
));
1028 if (2 > (long) ABLOCKS_BUSY (abase
))
1029 { /* All the blocks are free. */
1030 int i
= 0, aligned
= (long) ABLOCKS_BUSY (abase
);
1031 struct ablock
**tem
= &free_ablock
;
1032 struct ablock
*atop
= &abase
->blocks
[aligned
? ABLOCKS_SIZE
: ABLOCKS_SIZE
- 1];
1036 if (*tem
>= (struct ablock
*) abase
&& *tem
< atop
)
1039 *tem
= (*tem
)->x
.next_free
;
1042 tem
= &(*tem
)->x
.next_free
;
1044 eassert ((aligned
& 1) == aligned
);
1045 eassert (i
== (aligned
? ABLOCKS_SIZE
: ABLOCKS_SIZE
- 1));
1046 #ifdef USE_POSIX_MEMALIGN
1047 eassert ((unsigned long)ABLOCKS_BASE (abase
) % BLOCK_ALIGN
== 0);
1049 free (ABLOCKS_BASE (abase
));
1051 MALLOC_UNBLOCK_INPUT
;
1054 /* Return a new buffer structure allocated from the heap with
1055 a call to lisp_malloc. */
1058 allocate_buffer (void)
1061 = (struct buffer
*) lisp_malloc (sizeof (struct buffer
),
1063 b
->size
= sizeof (struct buffer
) / sizeof (EMACS_INT
);
1064 XSETPVECTYPE (b
, PVEC_BUFFER
);
1069 #ifndef SYSTEM_MALLOC
1071 /* Arranging to disable input signals while we're in malloc.
1073 This only works with GNU malloc. To help out systems which can't
1074 use GNU malloc, all the calls to malloc, realloc, and free
1075 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
1076 pair; unfortunately, we have no idea what C library functions
1077 might call malloc, so we can't really protect them unless you're
1078 using GNU malloc. Fortunately, most of the major operating systems
1079 can use GNU malloc. */
1082 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
1083 there's no need to block input around malloc. */
1085 #ifndef DOUG_LEA_MALLOC
1086 extern void * (*__malloc_hook
) (size_t, const void *);
1087 extern void * (*__realloc_hook
) (void *, size_t, const void *);
1088 extern void (*__free_hook
) (void *, const void *);
1089 /* Else declared in malloc.h, perhaps with an extra arg. */
1090 #endif /* DOUG_LEA_MALLOC */
1091 static void * (*old_malloc_hook
) (size_t, const void *);
1092 static void * (*old_realloc_hook
) (void *, size_t, const void*);
1093 static void (*old_free_hook
) (void*, const void*);
1095 static __malloc_size_t bytes_used_when_reconsidered
;
1097 /* This function is used as the hook for free to call. */
1100 emacs_blocked_free (void *ptr
, const void *ptr2
)
1104 #ifdef GC_MALLOC_CHECK
1110 if (m
== MEM_NIL
|| m
->start
!= ptr
)
1113 "Freeing `%p' which wasn't allocated with malloc\n", ptr
);
1118 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
1122 #endif /* GC_MALLOC_CHECK */
1124 __free_hook
= old_free_hook
;
1127 /* If we released our reserve (due to running out of memory),
1128 and we have a fair amount free once again,
1129 try to set aside another reserve in case we run out once more. */
1130 if (! NILP (Vmemory_full
)
1131 /* Verify there is enough space that even with the malloc
1132 hysteresis this call won't run out again.
1133 The code here is correct as long as SPARE_MEMORY
1134 is substantially larger than the block size malloc uses. */
1135 && (bytes_used_when_full
1136 > ((bytes_used_when_reconsidered
= BYTES_USED
)
1137 + max (malloc_hysteresis
, 4) * SPARE_MEMORY
)))
1138 refill_memory_reserve ();
1140 __free_hook
= emacs_blocked_free
;
1141 UNBLOCK_INPUT_ALLOC
;
1145 /* This function is the malloc hook that Emacs uses. */
1148 emacs_blocked_malloc (size_t size
, const void *ptr
)
1153 __malloc_hook
= old_malloc_hook
;
1154 #ifdef DOUG_LEA_MALLOC
1155 /* Segfaults on my system. --lorentey */
1156 /* mallopt (M_TOP_PAD, malloc_hysteresis * 4096); */
1158 __malloc_extra_blocks
= malloc_hysteresis
;
1161 value
= (void *) malloc (size
);
1163 #ifdef GC_MALLOC_CHECK
1165 struct mem_node
*m
= mem_find (value
);
1168 fprintf (stderr
, "Malloc returned %p which is already in use\n",
1170 fprintf (stderr
, "Region in use is %p...%p, %u bytes, type %d\n",
1171 m
->start
, m
->end
, (char *) m
->end
- (char *) m
->start
,
1176 if (!dont_register_blocks
)
1178 mem_insert (value
, (char *) value
+ max (1, size
), allocated_mem_type
);
1179 allocated_mem_type
= MEM_TYPE_NON_LISP
;
1182 #endif /* GC_MALLOC_CHECK */
1184 __malloc_hook
= emacs_blocked_malloc
;
1185 UNBLOCK_INPUT_ALLOC
;
1187 /* fprintf (stderr, "%p malloc\n", value); */
1192 /* This function is the realloc hook that Emacs uses. */
1195 emacs_blocked_realloc (void *ptr
, size_t size
, const void *ptr2
)
1200 __realloc_hook
= old_realloc_hook
;
1202 #ifdef GC_MALLOC_CHECK
1205 struct mem_node
*m
= mem_find (ptr
);
1206 if (m
== MEM_NIL
|| m
->start
!= ptr
)
1209 "Realloc of %p which wasn't allocated with malloc\n",
1217 /* fprintf (stderr, "%p -> realloc\n", ptr); */
1219 /* Prevent malloc from registering blocks. */
1220 dont_register_blocks
= 1;
1221 #endif /* GC_MALLOC_CHECK */
1223 value
= (void *) realloc (ptr
, size
);
1225 #ifdef GC_MALLOC_CHECK
1226 dont_register_blocks
= 0;
1229 struct mem_node
*m
= mem_find (value
);
1232 fprintf (stderr
, "Realloc returns memory that is already in use\n");
1236 /* Can't handle zero size regions in the red-black tree. */
1237 mem_insert (value
, (char *) value
+ max (size
, 1), MEM_TYPE_NON_LISP
);
1240 /* fprintf (stderr, "%p <- realloc\n", value); */
1241 #endif /* GC_MALLOC_CHECK */
1243 __realloc_hook
= emacs_blocked_realloc
;
1244 UNBLOCK_INPUT_ALLOC
;
1250 #ifdef HAVE_GTK_AND_PTHREAD
1251 /* Called from Fdump_emacs so that when the dumped Emacs starts, it has a
1252 normal malloc. Some thread implementations need this as they call
1253 malloc before main. The pthread_self call in BLOCK_INPUT_ALLOC then
1254 calls malloc because it is the first call, and we have an endless loop. */
1257 reset_malloc_hooks ()
1259 __free_hook
= old_free_hook
;
1260 __malloc_hook
= old_malloc_hook
;
1261 __realloc_hook
= old_realloc_hook
;
1263 #endif /* HAVE_GTK_AND_PTHREAD */
1266 /* Called from main to set up malloc to use our hooks. */
1269 uninterrupt_malloc (void)
1271 #ifdef HAVE_GTK_AND_PTHREAD
1272 #ifdef DOUG_LEA_MALLOC
1273 pthread_mutexattr_t attr
;
1275 /* GLIBC has a faster way to do this, but lets keep it portable.
1276 This is according to the Single UNIX Specification. */
1277 pthread_mutexattr_init (&attr
);
1278 pthread_mutexattr_settype (&attr
, PTHREAD_MUTEX_RECURSIVE
);
1279 pthread_mutex_init (&alloc_mutex
, &attr
);
1280 #else /* !DOUG_LEA_MALLOC */
1281 /* Some systems such as Solaris 2.6 don't have a recursive mutex,
1282 and the bundled gmalloc.c doesn't require it. */
1283 pthread_mutex_init (&alloc_mutex
, NULL
);
1284 #endif /* !DOUG_LEA_MALLOC */
1285 #endif /* HAVE_GTK_AND_PTHREAD */
1287 if (__free_hook
!= emacs_blocked_free
)
1288 old_free_hook
= __free_hook
;
1289 __free_hook
= emacs_blocked_free
;
1291 if (__malloc_hook
!= emacs_blocked_malloc
)
1292 old_malloc_hook
= __malloc_hook
;
1293 __malloc_hook
= emacs_blocked_malloc
;
1295 if (__realloc_hook
!= emacs_blocked_realloc
)
1296 old_realloc_hook
= __realloc_hook
;
1297 __realloc_hook
= emacs_blocked_realloc
;
1300 #endif /* not SYNC_INPUT */
1301 #endif /* not SYSTEM_MALLOC */
1305 /***********************************************************************
1307 ***********************************************************************/
1309 /* Number of intervals allocated in an interval_block structure.
1310 The 1020 is 1024 minus malloc overhead. */
1312 #define INTERVAL_BLOCK_SIZE \
1313 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1315 /* Intervals are allocated in chunks in form of an interval_block
1318 struct interval_block
1320 /* Place `intervals' first, to preserve alignment. */
1321 struct interval intervals
[INTERVAL_BLOCK_SIZE
];
1322 struct interval_block
*next
;
1325 /* Current interval block. Its `next' pointer points to older
1328 static struct interval_block
*interval_block
;
1330 /* Index in interval_block above of the next unused interval
1333 static int interval_block_index
;
1335 /* Number of free and live intervals. */
1337 static int total_free_intervals
, total_intervals
;
1339 /* List of free intervals. */
1341 INTERVAL interval_free_list
;
1343 /* Total number of interval blocks now in use. */
1345 static int n_interval_blocks
;
1348 /* Initialize interval allocation. */
1351 init_intervals (void)
1353 interval_block
= NULL
;
1354 interval_block_index
= INTERVAL_BLOCK_SIZE
;
1355 interval_free_list
= 0;
1356 n_interval_blocks
= 0;
1360 /* Return a new interval. */
1363 make_interval (void)
1367 /* eassert (!handling_signal); */
1371 if (interval_free_list
)
1373 val
= interval_free_list
;
1374 interval_free_list
= INTERVAL_PARENT (interval_free_list
);
1378 if (interval_block_index
== INTERVAL_BLOCK_SIZE
)
1380 register struct interval_block
*newi
;
1382 newi
= (struct interval_block
*) lisp_malloc (sizeof *newi
,
1385 newi
->next
= interval_block
;
1386 interval_block
= newi
;
1387 interval_block_index
= 0;
1388 n_interval_blocks
++;
1390 val
= &interval_block
->intervals
[interval_block_index
++];
1393 MALLOC_UNBLOCK_INPUT
;
1395 consing_since_gc
+= sizeof (struct interval
);
1397 RESET_INTERVAL (val
);
1403 /* Mark Lisp objects in interval I. */
1406 mark_interval (register INTERVAL i
, Lisp_Object dummy
)
1408 eassert (!i
->gcmarkbit
); /* Intervals are never shared. */
1410 mark_object (i
->plist
);
1414 /* Mark the interval tree rooted in TREE. Don't call this directly;
1415 use the macro MARK_INTERVAL_TREE instead. */
1418 mark_interval_tree (register INTERVAL tree
)
1420 /* No need to test if this tree has been marked already; this
1421 function is always called through the MARK_INTERVAL_TREE macro,
1422 which takes care of that. */
1424 traverse_intervals_noorder (tree
, mark_interval
, Qnil
);
1428 /* Mark the interval tree rooted in I. */
1430 #define MARK_INTERVAL_TREE(i) \
1432 if (!NULL_INTERVAL_P (i) && !i->gcmarkbit) \
1433 mark_interval_tree (i); \
1437 #define UNMARK_BALANCE_INTERVALS(i) \
1439 if (! NULL_INTERVAL_P (i)) \
1440 (i) = balance_intervals (i); \
1444 /* Number support. If USE_LISP_UNION_TYPE is in effect, we
1445 can't create number objects in macros. */
1448 make_number (EMACS_INT n
)
1452 obj
.s
.type
= Lisp_Int
;
1457 /***********************************************************************
1459 ***********************************************************************/
1461 /* Lisp_Strings are allocated in string_block structures. When a new
1462 string_block is allocated, all the Lisp_Strings it contains are
1463 added to a free-list string_free_list. When a new Lisp_String is
1464 needed, it is taken from that list. During the sweep phase of GC,
1465 string_blocks that are entirely free are freed, except two which
1468 String data is allocated from sblock structures. Strings larger
1469 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1470 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1472 Sblocks consist internally of sdata structures, one for each
1473 Lisp_String. The sdata structure points to the Lisp_String it
1474 belongs to. The Lisp_String points back to the `u.data' member of
1475 its sdata structure.
1477 When a Lisp_String is freed during GC, it is put back on
1478 string_free_list, and its `data' member and its sdata's `string'
1479 pointer is set to null. The size of the string is recorded in the
1480 `u.nbytes' member of the sdata. So, sdata structures that are no
1481 longer used, can be easily recognized, and it's easy to compact the
1482 sblocks of small strings which we do in compact_small_strings. */
1484 /* Size in bytes of an sblock structure used for small strings. This
1485 is 8192 minus malloc overhead. */
1487 #define SBLOCK_SIZE 8188
1489 /* Strings larger than this are considered large strings. String data
1490 for large strings is allocated from individual sblocks. */
1492 #define LARGE_STRING_BYTES 1024
1494 /* Structure describing string memory sub-allocated from an sblock.
1495 This is where the contents of Lisp strings are stored. */
1499 /* Back-pointer to the string this sdata belongs to. If null, this
1500 structure is free, and the NBYTES member of the union below
1501 contains the string's byte size (the same value that STRING_BYTES
1502 would return if STRING were non-null). If non-null, STRING_BYTES
1503 (STRING) is the size of the data, and DATA contains the string's
1505 struct Lisp_String
*string
;
1507 #ifdef GC_CHECK_STRING_BYTES
1510 unsigned char data
[1];
1512 #define SDATA_NBYTES(S) (S)->nbytes
1513 #define SDATA_DATA(S) (S)->data
1515 #else /* not GC_CHECK_STRING_BYTES */
1519 /* When STRING in non-null. */
1520 unsigned char data
[1];
1522 /* When STRING is null. */
1527 #define SDATA_NBYTES(S) (S)->u.nbytes
1528 #define SDATA_DATA(S) (S)->u.data
1530 #endif /* not GC_CHECK_STRING_BYTES */
1534 /* Structure describing a block of memory which is sub-allocated to
1535 obtain string data memory for strings. Blocks for small strings
1536 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1537 as large as needed. */
1542 struct sblock
*next
;
1544 /* Pointer to the next free sdata block. This points past the end
1545 of the sblock if there isn't any space left in this block. */
1546 struct sdata
*next_free
;
1548 /* Start of data. */
1549 struct sdata first_data
;
1552 /* Number of Lisp strings in a string_block structure. The 1020 is
1553 1024 minus malloc overhead. */
1555 #define STRING_BLOCK_SIZE \
1556 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1558 /* Structure describing a block from which Lisp_String structures
1563 /* Place `strings' first, to preserve alignment. */
1564 struct Lisp_String strings
[STRING_BLOCK_SIZE
];
1565 struct string_block
*next
;
1568 /* Head and tail of the list of sblock structures holding Lisp string
1569 data. We always allocate from current_sblock. The NEXT pointers
1570 in the sblock structures go from oldest_sblock to current_sblock. */
1572 static struct sblock
*oldest_sblock
, *current_sblock
;
1574 /* List of sblocks for large strings. */
1576 static struct sblock
*large_sblocks
;
1578 /* List of string_block structures, and how many there are. */
1580 static struct string_block
*string_blocks
;
1581 static int n_string_blocks
;
1583 /* Free-list of Lisp_Strings. */
1585 static struct Lisp_String
*string_free_list
;
1587 /* Number of live and free Lisp_Strings. */
1589 static int total_strings
, total_free_strings
;
1591 /* Number of bytes used by live strings. */
1593 static EMACS_INT total_string_size
;
1595 /* Given a pointer to a Lisp_String S which is on the free-list
1596 string_free_list, return a pointer to its successor in the
1599 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1601 /* Return a pointer to the sdata structure belonging to Lisp string S.
1602 S must be live, i.e. S->data must not be null. S->data is actually
1603 a pointer to the `u.data' member of its sdata structure; the
1604 structure starts at a constant offset in front of that. */
1606 #ifdef GC_CHECK_STRING_BYTES
1608 #define SDATA_OF_STRING(S) \
1609 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *) \
1610 - sizeof (EMACS_INT)))
1612 #else /* not GC_CHECK_STRING_BYTES */
1614 #define SDATA_OF_STRING(S) \
1615 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))
1617 #endif /* not GC_CHECK_STRING_BYTES */
1620 #ifdef GC_CHECK_STRING_OVERRUN
1622 /* We check for overrun in string data blocks by appending a small
1623 "cookie" after each allocated string data block, and check for the
1624 presence of this cookie during GC. */
1626 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1627 static char string_overrun_cookie
[GC_STRING_OVERRUN_COOKIE_SIZE
] =
1628 { 0xde, 0xad, 0xbe, 0xef };
1631 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1634 /* Value is the size of an sdata structure large enough to hold NBYTES
1635 bytes of string data. The value returned includes a terminating
1636 NUL byte, the size of the sdata structure, and padding. */
1638 #ifdef GC_CHECK_STRING_BYTES
1640 #define SDATA_SIZE(NBYTES) \
1641 ((sizeof (struct Lisp_String *) \
1643 + sizeof (EMACS_INT) \
1644 + sizeof (EMACS_INT) - 1) \
1645 & ~(sizeof (EMACS_INT) - 1))
1647 #else /* not GC_CHECK_STRING_BYTES */
1649 #define SDATA_SIZE(NBYTES) \
1650 ((sizeof (struct Lisp_String *) \
1652 + sizeof (EMACS_INT) - 1) \
1653 & ~(sizeof (EMACS_INT) - 1))
1655 #endif /* not GC_CHECK_STRING_BYTES */
1657 /* Extra bytes to allocate for each string. */
1659 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1661 /* Initialize string allocation. Called from init_alloc_once. */
1666 total_strings
= total_free_strings
= total_string_size
= 0;
1667 oldest_sblock
= current_sblock
= large_sblocks
= NULL
;
1668 string_blocks
= NULL
;
1669 n_string_blocks
= 0;
1670 string_free_list
= NULL
;
1671 empty_unibyte_string
= make_pure_string ("", 0, 0, 0);
1672 empty_multibyte_string
= make_pure_string ("", 0, 0, 1);
1676 #ifdef GC_CHECK_STRING_BYTES
1678 static int check_string_bytes_count
;
1680 static void check_string_bytes (int);
1681 static void check_sblock (struct sblock
*);
1683 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1686 /* Like GC_STRING_BYTES, but with debugging check. */
1689 string_bytes (struct Lisp_String
*s
)
1692 (s
->size_byte
< 0 ? s
->size
& ~ARRAY_MARK_FLAG
: s
->size_byte
);
1694 if (!PURE_POINTER_P (s
)
1696 && nbytes
!= SDATA_NBYTES (SDATA_OF_STRING (s
)))
1701 /* Check validity of Lisp strings' string_bytes member in B. */
1707 struct sdata
*from
, *end
, *from_end
;
1711 for (from
= &b
->first_data
; from
< end
; from
= from_end
)
1713 /* Compute the next FROM here because copying below may
1714 overwrite data we need to compute it. */
1717 /* Check that the string size recorded in the string is the
1718 same as the one recorded in the sdata structure. */
1720 CHECK_STRING_BYTES (from
->string
);
1723 nbytes
= GC_STRING_BYTES (from
->string
);
1725 nbytes
= SDATA_NBYTES (from
);
1727 nbytes
= SDATA_SIZE (nbytes
);
1728 from_end
= (struct sdata
*) ((char *) from
+ nbytes
+ GC_STRING_EXTRA
);
1733 /* Check validity of Lisp strings' string_bytes member. ALL_P
1734 non-zero means check all strings, otherwise check only most
1735 recently allocated strings. Used for hunting a bug. */
1738 check_string_bytes (all_p
)
1745 for (b
= large_sblocks
; b
; b
= b
->next
)
1747 struct Lisp_String
*s
= b
->first_data
.string
;
1749 CHECK_STRING_BYTES (s
);
1752 for (b
= oldest_sblock
; b
; b
= b
->next
)
1756 check_sblock (current_sblock
);
1759 #endif /* GC_CHECK_STRING_BYTES */
1761 #ifdef GC_CHECK_STRING_FREE_LIST
1763 /* Walk through the string free list looking for bogus next pointers.
1764 This may catch buffer overrun from a previous string. */
1767 check_string_free_list ()
1769 struct Lisp_String
*s
;
1771 /* Pop a Lisp_String off the free-list. */
1772 s
= string_free_list
;
1775 if ((unsigned long)s
< 1024)
1777 s
= NEXT_FREE_LISP_STRING (s
);
1781 #define check_string_free_list()
1784 /* Return a new Lisp_String. */
1786 static struct Lisp_String
*
1787 allocate_string (void)
1789 struct Lisp_String
*s
;
1791 /* eassert (!handling_signal); */
1795 /* If the free-list is empty, allocate a new string_block, and
1796 add all the Lisp_Strings in it to the free-list. */
1797 if (string_free_list
== NULL
)
1799 struct string_block
*b
;
1802 b
= (struct string_block
*) lisp_malloc (sizeof *b
, MEM_TYPE_STRING
);
1803 memset (b
, 0, sizeof *b
);
1804 b
->next
= string_blocks
;
1808 for (i
= STRING_BLOCK_SIZE
- 1; i
>= 0; --i
)
1811 NEXT_FREE_LISP_STRING (s
) = string_free_list
;
1812 string_free_list
= s
;
1815 total_free_strings
+= STRING_BLOCK_SIZE
;
1818 check_string_free_list ();
1820 /* Pop a Lisp_String off the free-list. */
1821 s
= string_free_list
;
1822 string_free_list
= NEXT_FREE_LISP_STRING (s
);
1824 MALLOC_UNBLOCK_INPUT
;
1826 /* Probably not strictly necessary, but play it safe. */
1827 memset (s
, 0, sizeof *s
);
1829 --total_free_strings
;
1832 consing_since_gc
+= sizeof *s
;
1834 #ifdef GC_CHECK_STRING_BYTES
1835 if (!noninteractive
)
1837 if (++check_string_bytes_count
== 200)
1839 check_string_bytes_count
= 0;
1840 check_string_bytes (1);
1843 check_string_bytes (0);
1845 #endif /* GC_CHECK_STRING_BYTES */
1851 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1852 plus a NUL byte at the end. Allocate an sdata structure for S, and
1853 set S->data to its `u.data' member. Store a NUL byte at the end of
1854 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1855 S->data if it was initially non-null. */
1858 allocate_string_data (struct Lisp_String
*s
,
1859 EMACS_INT nchars
, EMACS_INT nbytes
)
1861 struct sdata
*data
, *old_data
;
1863 EMACS_INT needed
, old_nbytes
;
1865 /* Determine the number of bytes needed to store NBYTES bytes
1867 needed
= SDATA_SIZE (nbytes
);
1868 old_data
= s
->data
? SDATA_OF_STRING (s
) : NULL
;
1869 old_nbytes
= GC_STRING_BYTES (s
);
1873 if (nbytes
> LARGE_STRING_BYTES
)
1875 size_t size
= sizeof *b
- sizeof (struct sdata
) + needed
;
1877 #ifdef DOUG_LEA_MALLOC
1878 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1879 because mapped region contents are not preserved in
1882 In case you think of allowing it in a dumped Emacs at the
1883 cost of not being able to re-dump, there's another reason:
1884 mmap'ed data typically have an address towards the top of the
1885 address space, which won't fit into an EMACS_INT (at least on
1886 32-bit systems with the current tagging scheme). --fx */
1887 mallopt (M_MMAP_MAX
, 0);
1890 b
= (struct sblock
*) lisp_malloc (size
+ GC_STRING_EXTRA
, MEM_TYPE_NON_LISP
);
1892 #ifdef DOUG_LEA_MALLOC
1893 /* Back to a reasonable maximum of mmap'ed areas. */
1894 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
);
1897 b
->next_free
= &b
->first_data
;
1898 b
->first_data
.string
= NULL
;
1899 b
->next
= large_sblocks
;
1902 else if (current_sblock
== NULL
1903 || (((char *) current_sblock
+ SBLOCK_SIZE
1904 - (char *) current_sblock
->next_free
)
1905 < (needed
+ GC_STRING_EXTRA
)))
1907 /* Not enough room in the current sblock. */
1908 b
= (struct sblock
*) lisp_malloc (SBLOCK_SIZE
, MEM_TYPE_NON_LISP
);
1909 b
->next_free
= &b
->first_data
;
1910 b
->first_data
.string
= NULL
;
1914 current_sblock
->next
= b
;
1922 data
= b
->next_free
;
1923 b
->next_free
= (struct sdata
*) ((char *) data
+ needed
+ GC_STRING_EXTRA
);
1925 MALLOC_UNBLOCK_INPUT
;
1928 s
->data
= SDATA_DATA (data
);
1929 #ifdef GC_CHECK_STRING_BYTES
1930 SDATA_NBYTES (data
) = nbytes
;
1933 s
->size_byte
= nbytes
;
1934 s
->data
[nbytes
] = '\0';
1935 #ifdef GC_CHECK_STRING_OVERRUN
1936 memcpy (data
+ needed
, string_overrun_cookie
, GC_STRING_OVERRUN_COOKIE_SIZE
);
1939 /* If S had already data assigned, mark that as free by setting its
1940 string back-pointer to null, and recording the size of the data
1944 SDATA_NBYTES (old_data
) = old_nbytes
;
1945 old_data
->string
= NULL
;
1948 consing_since_gc
+= needed
;
1952 /* Sweep and compact strings. */
1955 sweep_strings (void)
1957 struct string_block
*b
, *next
;
1958 struct string_block
*live_blocks
= NULL
;
1960 string_free_list
= NULL
;
1961 total_strings
= total_free_strings
= 0;
1962 total_string_size
= 0;
1964 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1965 for (b
= string_blocks
; b
; b
= next
)
1968 struct Lisp_String
*free_list_before
= string_free_list
;
1972 for (i
= 0; i
< STRING_BLOCK_SIZE
; ++i
)
1974 struct Lisp_String
*s
= b
->strings
+ i
;
1978 /* String was not on free-list before. */
1979 if (STRING_MARKED_P (s
))
1981 /* String is live; unmark it and its intervals. */
1984 if (!NULL_INTERVAL_P (s
->intervals
))
1985 UNMARK_BALANCE_INTERVALS (s
->intervals
);
1988 total_string_size
+= STRING_BYTES (s
);
1992 /* String is dead. Put it on the free-list. */
1993 struct sdata
*data
= SDATA_OF_STRING (s
);
1995 /* Save the size of S in its sdata so that we know
1996 how large that is. Reset the sdata's string
1997 back-pointer so that we know it's free. */
1998 #ifdef GC_CHECK_STRING_BYTES
1999 if (GC_STRING_BYTES (s
) != SDATA_NBYTES (data
))
2002 data
->u
.nbytes
= GC_STRING_BYTES (s
);
2004 data
->string
= NULL
;
2006 /* Reset the strings's `data' member so that we
2010 /* Put the string on the free-list. */
2011 NEXT_FREE_LISP_STRING (s
) = string_free_list
;
2012 string_free_list
= s
;
2018 /* S was on the free-list before. Put it there again. */
2019 NEXT_FREE_LISP_STRING (s
) = string_free_list
;
2020 string_free_list
= s
;
2025 /* Free blocks that contain free Lisp_Strings only, except
2026 the first two of them. */
2027 if (nfree
== STRING_BLOCK_SIZE
2028 && total_free_strings
> STRING_BLOCK_SIZE
)
2032 string_free_list
= free_list_before
;
2036 total_free_strings
+= nfree
;
2037 b
->next
= live_blocks
;
2042 check_string_free_list ();
2044 string_blocks
= live_blocks
;
2045 free_large_strings ();
2046 compact_small_strings ();
2048 check_string_free_list ();
2052 /* Free dead large strings. */
2055 free_large_strings (void)
2057 struct sblock
*b
, *next
;
2058 struct sblock
*live_blocks
= NULL
;
2060 for (b
= large_sblocks
; b
; b
= next
)
2064 if (b
->first_data
.string
== NULL
)
2068 b
->next
= live_blocks
;
2073 large_sblocks
= live_blocks
;
2077 /* Compact data of small strings. Free sblocks that don't contain
2078 data of live strings after compaction. */
2081 compact_small_strings (void)
2083 struct sblock
*b
, *tb
, *next
;
2084 struct sdata
*from
, *to
, *end
, *tb_end
;
2085 struct sdata
*to_end
, *from_end
;
2087 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2088 to, and TB_END is the end of TB. */
2090 tb_end
= (struct sdata
*) ((char *) tb
+ SBLOCK_SIZE
);
2091 to
= &tb
->first_data
;
2093 /* Step through the blocks from the oldest to the youngest. We
2094 expect that old blocks will stabilize over time, so that less
2095 copying will happen this way. */
2096 for (b
= oldest_sblock
; b
; b
= b
->next
)
2099 xassert ((char *) end
<= (char *) b
+ SBLOCK_SIZE
);
2101 for (from
= &b
->first_data
; from
< end
; from
= from_end
)
2103 /* Compute the next FROM here because copying below may
2104 overwrite data we need to compute it. */
2107 #ifdef GC_CHECK_STRING_BYTES
2108 /* Check that the string size recorded in the string is the
2109 same as the one recorded in the sdata structure. */
2111 && GC_STRING_BYTES (from
->string
) != SDATA_NBYTES (from
))
2113 #endif /* GC_CHECK_STRING_BYTES */
2116 nbytes
= GC_STRING_BYTES (from
->string
);
2118 nbytes
= SDATA_NBYTES (from
);
2120 if (nbytes
> LARGE_STRING_BYTES
)
2123 nbytes
= SDATA_SIZE (nbytes
);
2124 from_end
= (struct sdata
*) ((char *) from
+ nbytes
+ GC_STRING_EXTRA
);
2126 #ifdef GC_CHECK_STRING_OVERRUN
2127 if (memcmp (string_overrun_cookie
,
2128 (char *) from_end
- GC_STRING_OVERRUN_COOKIE_SIZE
,
2129 GC_STRING_OVERRUN_COOKIE_SIZE
))
2133 /* FROM->string non-null means it's alive. Copy its data. */
2136 /* If TB is full, proceed with the next sblock. */
2137 to_end
= (struct sdata
*) ((char *) to
+ nbytes
+ GC_STRING_EXTRA
);
2138 if (to_end
> tb_end
)
2142 tb_end
= (struct sdata
*) ((char *) tb
+ SBLOCK_SIZE
);
2143 to
= &tb
->first_data
;
2144 to_end
= (struct sdata
*) ((char *) to
+ nbytes
+ GC_STRING_EXTRA
);
2147 /* Copy, and update the string's `data' pointer. */
2150 xassert (tb
!= b
|| to
<= from
);
2151 memmove (to
, from
, nbytes
+ GC_STRING_EXTRA
);
2152 to
->string
->data
= SDATA_DATA (to
);
2155 /* Advance past the sdata we copied to. */
2161 /* The rest of the sblocks following TB don't contain live data, so
2162 we can free them. */
2163 for (b
= tb
->next
; b
; b
= next
)
2171 current_sblock
= tb
;
2175 DEFUN ("make-string", Fmake_string
, Smake_string
, 2, 2, 0,
2176 doc
: /* Return a newly created string of length LENGTH, with INIT in each element.
2177 LENGTH must be an integer.
2178 INIT must be an integer that represents a character. */)
2179 (Lisp_Object length
, Lisp_Object init
)
2181 register Lisp_Object val
;
2182 register unsigned char *p
, *end
;
2186 CHECK_NATNUM (length
);
2187 CHECK_NUMBER (init
);
2190 if (ASCII_CHAR_P (c
))
2192 nbytes
= XINT (length
);
2193 val
= make_uninit_string (nbytes
);
2195 end
= p
+ SCHARS (val
);
2201 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
2202 int len
= CHAR_STRING (c
, str
);
2203 EMACS_INT string_len
= XINT (length
);
2205 if (string_len
> MOST_POSITIVE_FIXNUM
/ len
)
2206 error ("Maximum string size exceeded");
2207 nbytes
= len
* string_len
;
2208 val
= make_uninit_multibyte_string (string_len
, nbytes
);
2213 memcpy (p
, str
, len
);
2223 DEFUN ("make-bool-vector", Fmake_bool_vector
, Smake_bool_vector
, 2, 2, 0,
2224 doc
: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2225 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2226 (Lisp_Object length
, Lisp_Object init
)
2228 register Lisp_Object val
;
2229 struct Lisp_Bool_Vector
*p
;
2231 EMACS_INT length_in_chars
, length_in_elts
;
2234 CHECK_NATNUM (length
);
2236 bits_per_value
= sizeof (EMACS_INT
) * BOOL_VECTOR_BITS_PER_CHAR
;
2238 length_in_elts
= (XFASTINT (length
) + bits_per_value
- 1) / bits_per_value
;
2239 length_in_chars
= ((XFASTINT (length
) + BOOL_VECTOR_BITS_PER_CHAR
- 1)
2240 / BOOL_VECTOR_BITS_PER_CHAR
);
2242 /* We must allocate one more elements than LENGTH_IN_ELTS for the
2243 slot `size' of the struct Lisp_Bool_Vector. */
2244 val
= Fmake_vector (make_number (length_in_elts
+ 1), Qnil
);
2246 /* Get rid of any bits that would cause confusion. */
2247 XVECTOR (val
)->size
= 0; /* No Lisp_Object to trace in there. */
2248 /* Use XVECTOR (val) rather than `p' because p->size is not TRT. */
2249 XSETPVECTYPE (XVECTOR (val
), PVEC_BOOL_VECTOR
);
2251 p
= XBOOL_VECTOR (val
);
2252 p
->size
= XFASTINT (length
);
2254 real_init
= (NILP (init
) ? 0 : -1);
2255 for (i
= 0; i
< length_in_chars
; i
++)
2256 p
->data
[i
] = real_init
;
2258 /* Clear the extraneous bits in the last byte. */
2259 if (XINT (length
) != length_in_chars
* BOOL_VECTOR_BITS_PER_CHAR
)
2260 p
->data
[length_in_chars
- 1]
2261 &= (1 << (XINT (length
) % BOOL_VECTOR_BITS_PER_CHAR
)) - 1;
2267 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2268 of characters from the contents. This string may be unibyte or
2269 multibyte, depending on the contents. */
2272 make_string (const char *contents
, EMACS_INT nbytes
)
2274 register Lisp_Object val
;
2275 EMACS_INT nchars
, multibyte_nbytes
;
2277 parse_str_as_multibyte ((const unsigned char *) contents
, nbytes
,
2278 &nchars
, &multibyte_nbytes
);
2279 if (nbytes
== nchars
|| nbytes
!= multibyte_nbytes
)
2280 /* CONTENTS contains no multibyte sequences or contains an invalid
2281 multibyte sequence. We must make unibyte string. */
2282 val
= make_unibyte_string (contents
, nbytes
);
2284 val
= make_multibyte_string (contents
, nchars
, nbytes
);
2289 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
2292 make_unibyte_string (const char *contents
, EMACS_INT length
)
2294 register Lisp_Object val
;
2295 val
= make_uninit_string (length
);
2296 memcpy (SDATA (val
), contents
, length
);
2301 /* Make a multibyte string from NCHARS characters occupying NBYTES
2302 bytes at CONTENTS. */
2305 make_multibyte_string (const char *contents
,
2306 EMACS_INT nchars
, EMACS_INT nbytes
)
2308 register Lisp_Object val
;
2309 val
= make_uninit_multibyte_string (nchars
, nbytes
);
2310 memcpy (SDATA (val
), contents
, nbytes
);
2315 /* Make a string from NCHARS characters occupying NBYTES bytes at
2316 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2319 make_string_from_bytes (const char *contents
,
2320 EMACS_INT nchars
, EMACS_INT nbytes
)
2322 register Lisp_Object val
;
2323 val
= make_uninit_multibyte_string (nchars
, nbytes
);
2324 memcpy (SDATA (val
), contents
, nbytes
);
2325 if (SBYTES (val
) == SCHARS (val
))
2326 STRING_SET_UNIBYTE (val
);
2331 /* Make a string from NCHARS characters occupying NBYTES bytes at
2332 CONTENTS. The argument MULTIBYTE controls whether to label the
2333 string as multibyte. If NCHARS is negative, it counts the number of
2334 characters by itself. */
2337 make_specified_string (const char *contents
,
2338 EMACS_INT nchars
, EMACS_INT nbytes
, int multibyte
)
2340 register Lisp_Object val
;
2345 nchars
= multibyte_chars_in_text ((const unsigned char *) contents
,
2350 val
= make_uninit_multibyte_string (nchars
, nbytes
);
2351 memcpy (SDATA (val
), contents
, nbytes
);
2353 STRING_SET_UNIBYTE (val
);
2358 /* Make a string from the data at STR, treating it as multibyte if the
2362 build_string (const char *str
)
2364 return make_string (str
, strlen (str
));
2368 /* Return an unibyte Lisp_String set up to hold LENGTH characters
2369 occupying LENGTH bytes. */
2372 make_uninit_string (EMACS_INT length
)
2377 return empty_unibyte_string
;
2378 val
= make_uninit_multibyte_string (length
, length
);
2379 STRING_SET_UNIBYTE (val
);
2384 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2385 which occupy NBYTES bytes. */
2388 make_uninit_multibyte_string (EMACS_INT nchars
, EMACS_INT nbytes
)
2391 struct Lisp_String
*s
;
2396 return empty_multibyte_string
;
2398 s
= allocate_string ();
2399 allocate_string_data (s
, nchars
, nbytes
);
2400 XSETSTRING (string
, s
);
2401 string_chars_consed
+= nbytes
;
2407 /***********************************************************************
2409 ***********************************************************************/
2411 /* We store float cells inside of float_blocks, allocating a new
2412 float_block with malloc whenever necessary. Float cells reclaimed
2413 by GC are put on a free list to be reallocated before allocating
2414 any new float cells from the latest float_block. */
2416 #define FLOAT_BLOCK_SIZE \
2417 (((BLOCK_BYTES - sizeof (struct float_block *) \
2418 /* The compiler might add padding at the end. */ \
2419 - (sizeof (struct Lisp_Float) - sizeof (int))) * CHAR_BIT) \
2420 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2422 #define GETMARKBIT(block,n) \
2423 (((block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2424 >> ((n) % (sizeof(int) * CHAR_BIT))) \
2427 #define SETMARKBIT(block,n) \
2428 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2429 |= 1 << ((n) % (sizeof(int) * CHAR_BIT))
2431 #define UNSETMARKBIT(block,n) \
2432 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2433 &= ~(1 << ((n) % (sizeof(int) * CHAR_BIT)))
2435 #define FLOAT_BLOCK(fptr) \
2436 ((struct float_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
2438 #define FLOAT_INDEX(fptr) \
2439 ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2443 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2444 struct Lisp_Float floats
[FLOAT_BLOCK_SIZE
];
2445 int gcmarkbits
[1 + FLOAT_BLOCK_SIZE
/ (sizeof(int) * CHAR_BIT
)];
2446 struct float_block
*next
;
2449 #define FLOAT_MARKED_P(fptr) \
2450 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2452 #define FLOAT_MARK(fptr) \
2453 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2455 #define FLOAT_UNMARK(fptr) \
2456 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2458 /* Current float_block. */
2460 struct float_block
*float_block
;
2462 /* Index of first unused Lisp_Float in the current float_block. */
2464 int float_block_index
;
2466 /* Total number of float blocks now in use. */
2470 /* Free-list of Lisp_Floats. */
2472 struct Lisp_Float
*float_free_list
;
2475 /* Initialize float allocation. */
2481 float_block_index
= FLOAT_BLOCK_SIZE
; /* Force alloc of new float_block. */
2482 float_free_list
= 0;
2487 /* Return a new float object with value FLOAT_VALUE. */
2490 make_float (double float_value
)
2492 register Lisp_Object val
;
2494 /* eassert (!handling_signal); */
2498 if (float_free_list
)
2500 /* We use the data field for chaining the free list
2501 so that we won't use the same field that has the mark bit. */
2502 XSETFLOAT (val
, float_free_list
);
2503 float_free_list
= float_free_list
->u
.chain
;
2507 if (float_block_index
== FLOAT_BLOCK_SIZE
)
2509 register struct float_block
*new;
2511 new = (struct float_block
*) lisp_align_malloc (sizeof *new,
2513 new->next
= float_block
;
2514 memset (new->gcmarkbits
, 0, sizeof new->gcmarkbits
);
2516 float_block_index
= 0;
2519 XSETFLOAT (val
, &float_block
->floats
[float_block_index
]);
2520 float_block_index
++;
2523 MALLOC_UNBLOCK_INPUT
;
2525 XFLOAT_INIT (val
, float_value
);
2526 eassert (!FLOAT_MARKED_P (XFLOAT (val
)));
2527 consing_since_gc
+= sizeof (struct Lisp_Float
);
2534 /***********************************************************************
2536 ***********************************************************************/
2538 /* We store cons cells inside of cons_blocks, allocating a new
2539 cons_block with malloc whenever necessary. Cons cells reclaimed by
2540 GC are put on a free list to be reallocated before allocating
2541 any new cons cells from the latest cons_block. */
2543 #define CONS_BLOCK_SIZE \
2544 (((BLOCK_BYTES - sizeof (struct cons_block *)) * CHAR_BIT) \
2545 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2547 #define CONS_BLOCK(fptr) \
2548 ((struct cons_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
2550 #define CONS_INDEX(fptr) \
2551 ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2555 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2556 struct Lisp_Cons conses
[CONS_BLOCK_SIZE
];
2557 int gcmarkbits
[1 + CONS_BLOCK_SIZE
/ (sizeof(int) * CHAR_BIT
)];
2558 struct cons_block
*next
;
2561 #define CONS_MARKED_P(fptr) \
2562 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2564 #define CONS_MARK(fptr) \
2565 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2567 #define CONS_UNMARK(fptr) \
2568 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2570 /* Current cons_block. */
2572 struct cons_block
*cons_block
;
2574 /* Index of first unused Lisp_Cons in the current block. */
2576 int cons_block_index
;
2578 /* Free-list of Lisp_Cons structures. */
2580 struct Lisp_Cons
*cons_free_list
;
2582 /* Total number of cons blocks now in use. */
2584 static int n_cons_blocks
;
2587 /* Initialize cons allocation. */
2593 cons_block_index
= CONS_BLOCK_SIZE
; /* Force alloc of new cons_block. */
2599 /* Explicitly free a cons cell by putting it on the free-list. */
2602 free_cons (struct Lisp_Cons
*ptr
)
2604 ptr
->u
.chain
= cons_free_list
;
2608 cons_free_list
= ptr
;
2611 DEFUN ("cons", Fcons
, Scons
, 2, 2, 0,
2612 doc
: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2613 (Lisp_Object car
, Lisp_Object cdr
)
2615 register Lisp_Object val
;
2617 /* eassert (!handling_signal); */
2623 /* We use the cdr for chaining the free list
2624 so that we won't use the same field that has the mark bit. */
2625 XSETCONS (val
, cons_free_list
);
2626 cons_free_list
= cons_free_list
->u
.chain
;
2630 if (cons_block_index
== CONS_BLOCK_SIZE
)
2632 register struct cons_block
*new;
2633 new = (struct cons_block
*) lisp_align_malloc (sizeof *new,
2635 memset (new->gcmarkbits
, 0, sizeof new->gcmarkbits
);
2636 new->next
= cons_block
;
2638 cons_block_index
= 0;
2641 XSETCONS (val
, &cons_block
->conses
[cons_block_index
]);
2645 MALLOC_UNBLOCK_INPUT
;
2649 eassert (!CONS_MARKED_P (XCONS (val
)));
2650 consing_since_gc
+= sizeof (struct Lisp_Cons
);
2651 cons_cells_consed
++;
2655 #ifdef GC_CHECK_CONS_LIST
2656 /* Get an error now if there's any junk in the cons free list. */
2658 check_cons_list (void)
2660 struct Lisp_Cons
*tail
= cons_free_list
;
2663 tail
= tail
->u
.chain
;
2667 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2670 list1 (Lisp_Object arg1
)
2672 return Fcons (arg1
, Qnil
);
2676 list2 (Lisp_Object arg1
, Lisp_Object arg2
)
2678 return Fcons (arg1
, Fcons (arg2
, Qnil
));
2683 list3 (Lisp_Object arg1
, Lisp_Object arg2
, Lisp_Object arg3
)
2685 return Fcons (arg1
, Fcons (arg2
, Fcons (arg3
, Qnil
)));
2690 list4 (Lisp_Object arg1
, Lisp_Object arg2
, Lisp_Object arg3
, Lisp_Object arg4
)
2692 return Fcons (arg1
, Fcons (arg2
, Fcons (arg3
, Fcons (arg4
, Qnil
))));
2697 list5 (Lisp_Object arg1
, Lisp_Object arg2
, Lisp_Object arg3
, Lisp_Object arg4
, Lisp_Object arg5
)
2699 return Fcons (arg1
, Fcons (arg2
, Fcons (arg3
, Fcons (arg4
,
2700 Fcons (arg5
, Qnil
)))));
2704 DEFUN ("list", Flist
, Slist
, 0, MANY
, 0,
2705 doc
: /* Return a newly created list with specified arguments as elements.
2706 Any number of arguments, even zero arguments, are allowed.
2707 usage: (list &rest OBJECTS) */)
2708 (int nargs
, register Lisp_Object
*args
)
2710 register Lisp_Object val
;
2716 val
= Fcons (args
[nargs
], val
);
2722 DEFUN ("make-list", Fmake_list
, Smake_list
, 2, 2, 0,
2723 doc
: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2724 (register Lisp_Object length
, Lisp_Object init
)
2726 register Lisp_Object val
;
2727 register EMACS_INT size
;
2729 CHECK_NATNUM (length
);
2730 size
= XFASTINT (length
);
2735 val
= Fcons (init
, val
);
2740 val
= Fcons (init
, val
);
2745 val
= Fcons (init
, val
);
2750 val
= Fcons (init
, val
);
2755 val
= Fcons (init
, val
);
2770 /***********************************************************************
2772 ***********************************************************************/
2774 /* Singly-linked list of all vectors. */
2776 static struct Lisp_Vector
*all_vectors
;
2778 /* Total number of vector-like objects now in use. */
2780 static int n_vectors
;
2783 /* Value is a pointer to a newly allocated Lisp_Vector structure
2784 with room for LEN Lisp_Objects. */
2786 static struct Lisp_Vector
*
2787 allocate_vectorlike (EMACS_INT len
)
2789 struct Lisp_Vector
*p
;
2794 #ifdef DOUG_LEA_MALLOC
2795 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2796 because mapped region contents are not preserved in
2798 mallopt (M_MMAP_MAX
, 0);
2801 /* This gets triggered by code which I haven't bothered to fix. --Stef */
2802 /* eassert (!handling_signal); */
2804 nbytes
= sizeof *p
+ (len
- 1) * sizeof p
->contents
[0];
2805 p
= (struct Lisp_Vector
*) lisp_malloc (nbytes
, MEM_TYPE_VECTORLIKE
);
2807 #ifdef DOUG_LEA_MALLOC
2808 /* Back to a reasonable maximum of mmap'ed areas. */
2809 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
);
2812 consing_since_gc
+= nbytes
;
2813 vector_cells_consed
+= len
;
2815 p
->next
= all_vectors
;
2818 MALLOC_UNBLOCK_INPUT
;
2825 /* Allocate a vector with NSLOTS slots. */
2827 struct Lisp_Vector
*
2828 allocate_vector (EMACS_INT nslots
)
2830 struct Lisp_Vector
*v
= allocate_vectorlike (nslots
);
2836 /* Allocate other vector-like structures. */
2838 struct Lisp_Vector
*
2839 allocate_pseudovector (int memlen
, int lisplen
, EMACS_INT tag
)
2841 struct Lisp_Vector
*v
= allocate_vectorlike (memlen
);
2844 /* Only the first lisplen slots will be traced normally by the GC. */
2846 for (i
= 0; i
< lisplen
; ++i
)
2847 v
->contents
[i
] = Qnil
;
2849 XSETPVECTYPE (v
, tag
); /* Add the appropriate tag. */
2853 struct Lisp_Hash_Table
*
2854 allocate_hash_table (void)
2856 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table
, count
, PVEC_HASH_TABLE
);
2861 allocate_window (void)
2863 return ALLOCATE_PSEUDOVECTOR(struct window
, current_matrix
, PVEC_WINDOW
);
2868 allocate_terminal (void)
2870 struct terminal
*t
= ALLOCATE_PSEUDOVECTOR (struct terminal
,
2871 next_terminal
, PVEC_TERMINAL
);
2872 /* Zero out the non-GC'd fields. FIXME: This should be made unnecessary. */
2873 memset (&t
->next_terminal
, 0,
2874 (char*) (t
+ 1) - (char*) &t
->next_terminal
);
2880 allocate_frame (void)
2882 struct frame
*f
= ALLOCATE_PSEUDOVECTOR (struct frame
,
2883 face_cache
, PVEC_FRAME
);
2884 /* Zero out the non-GC'd fields. FIXME: This should be made unnecessary. */
2885 memset (&f
->face_cache
, 0,
2886 (char *) (f
+ 1) - (char *) &f
->face_cache
);
2891 struct Lisp_Process
*
2892 allocate_process (void)
2894 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Process
, pid
, PVEC_PROCESS
);
2898 DEFUN ("make-vector", Fmake_vector
, Smake_vector
, 2, 2, 0,
2899 doc
: /* Return a newly created vector of length LENGTH, with each element being INIT.
2900 See also the function `vector'. */)
2901 (register Lisp_Object length
, Lisp_Object init
)
2904 register EMACS_INT sizei
;
2905 register EMACS_INT i
;
2906 register struct Lisp_Vector
*p
;
2908 CHECK_NATNUM (length
);
2909 sizei
= XFASTINT (length
);
2911 p
= allocate_vector (sizei
);
2912 for (i
= 0; i
< sizei
; i
++)
2913 p
->contents
[i
] = init
;
2915 XSETVECTOR (vector
, p
);
2920 DEFUN ("vector", Fvector
, Svector
, 0, MANY
, 0,
2921 doc
: /* Return a newly created vector with specified arguments as elements.
2922 Any number of arguments, even zero arguments, are allowed.
2923 usage: (vector &rest OBJECTS) */)
2924 (register int nargs
, Lisp_Object
*args
)
2926 register Lisp_Object len
, val
;
2928 register struct Lisp_Vector
*p
;
2930 XSETFASTINT (len
, nargs
);
2931 val
= Fmake_vector (len
, Qnil
);
2933 for (i
= 0; i
< nargs
; i
++)
2934 p
->contents
[i
] = args
[i
];
2939 DEFUN ("make-byte-code", Fmake_byte_code
, Smake_byte_code
, 4, MANY
, 0,
2940 doc
: /* Create a byte-code object with specified arguments as elements.
2941 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
2942 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
2943 and (optional) INTERACTIVE-SPEC.
2944 The first four arguments are required; at most six have any
2946 The ARGLIST can be either like the one of `lambda', in which case the arguments
2947 will be dynamically bound before executing the byte code, or it can be an
2948 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
2949 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
2950 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
2951 argument to catch the left-over arguments. If such an integer is used, the
2952 arguments will not be dynamically bound but will be instead pushed on the
2953 stack before executing the byte-code.
2954 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
2955 (register int nargs
, Lisp_Object
*args
)
2957 register Lisp_Object len
, val
;
2959 register struct Lisp_Vector
*p
;
2961 XSETFASTINT (len
, nargs
);
2962 if (!NILP (Vpurify_flag
))
2963 val
= make_pure_vector ((EMACS_INT
) nargs
);
2965 val
= Fmake_vector (len
, Qnil
);
2967 if (nargs
> 1 && STRINGP (args
[1]) && STRING_MULTIBYTE (args
[1]))
2968 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
2969 earlier because they produced a raw 8-bit string for byte-code
2970 and now such a byte-code string is loaded as multibyte while
2971 raw 8-bit characters converted to multibyte form. Thus, now we
2972 must convert them back to the original unibyte form. */
2973 args
[1] = Fstring_as_unibyte (args
[1]);
2976 for (i
= 0; i
< nargs
; i
++)
2978 if (!NILP (Vpurify_flag
))
2979 args
[i
] = Fpurecopy (args
[i
]);
2980 p
->contents
[i
] = args
[i
];
2982 XSETPVECTYPE (p
, PVEC_COMPILED
);
2983 XSETCOMPILED (val
, p
);
2989 /***********************************************************************
2991 ***********************************************************************/
2993 /* Each symbol_block is just under 1020 bytes long, since malloc
2994 really allocates in units of powers of two and uses 4 bytes for its
2997 #define SYMBOL_BLOCK_SIZE \
2998 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
3002 /* Place `symbols' first, to preserve alignment. */
3003 struct Lisp_Symbol symbols
[SYMBOL_BLOCK_SIZE
];
3004 struct symbol_block
*next
;
3007 /* Current symbol block and index of first unused Lisp_Symbol
3010 static struct symbol_block
*symbol_block
;
3011 static int symbol_block_index
;
3013 /* List of free symbols. */
3015 static struct Lisp_Symbol
*symbol_free_list
;
3017 /* Total number of symbol blocks now in use. */
3019 static int n_symbol_blocks
;
3022 /* Initialize symbol allocation. */
3027 symbol_block
= NULL
;
3028 symbol_block_index
= SYMBOL_BLOCK_SIZE
;
3029 symbol_free_list
= 0;
3030 n_symbol_blocks
= 0;
3034 DEFUN ("make-symbol", Fmake_symbol
, Smake_symbol
, 1, 1, 0,
3035 doc
: /* Return a newly allocated uninterned symbol whose name is NAME.
3036 Its value and function definition are void, and its property list is nil. */)
3039 register Lisp_Object val
;
3040 register struct Lisp_Symbol
*p
;
3042 CHECK_STRING (name
);
3044 /* eassert (!handling_signal); */
3048 if (symbol_free_list
)
3050 XSETSYMBOL (val
, symbol_free_list
);
3051 symbol_free_list
= symbol_free_list
->next
;
3055 if (symbol_block_index
== SYMBOL_BLOCK_SIZE
)
3057 struct symbol_block
*new;
3058 new = (struct symbol_block
*) lisp_malloc (sizeof *new,
3060 new->next
= symbol_block
;
3062 symbol_block_index
= 0;
3065 XSETSYMBOL (val
, &symbol_block
->symbols
[symbol_block_index
]);
3066 symbol_block_index
++;
3069 MALLOC_UNBLOCK_INPUT
;
3074 p
->redirect
= SYMBOL_PLAINVAL
;
3075 SET_SYMBOL_VAL (p
, Qunbound
);
3076 p
->function
= Qunbound
;
3079 p
->interned
= SYMBOL_UNINTERNED
;
3081 p
->declared_special
= 0;
3082 consing_since_gc
+= sizeof (struct Lisp_Symbol
);
3089 /***********************************************************************
3090 Marker (Misc) Allocation
3091 ***********************************************************************/
3093 /* Allocation of markers and other objects that share that structure.
3094 Works like allocation of conses. */
3096 #define MARKER_BLOCK_SIZE \
3097 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
3101 /* Place `markers' first, to preserve alignment. */
3102 union Lisp_Misc markers
[MARKER_BLOCK_SIZE
];
3103 struct marker_block
*next
;
3106 static struct marker_block
*marker_block
;
3107 static int marker_block_index
;
3109 static union Lisp_Misc
*marker_free_list
;
3111 /* Total number of marker blocks now in use. */
3113 static int n_marker_blocks
;
3118 marker_block
= NULL
;
3119 marker_block_index
= MARKER_BLOCK_SIZE
;
3120 marker_free_list
= 0;
3121 n_marker_blocks
= 0;
3124 /* Return a newly allocated Lisp_Misc object, with no substructure. */
3127 allocate_misc (void)
3131 /* eassert (!handling_signal); */
3135 if (marker_free_list
)
3137 XSETMISC (val
, marker_free_list
);
3138 marker_free_list
= marker_free_list
->u_free
.chain
;
3142 if (marker_block_index
== MARKER_BLOCK_SIZE
)
3144 struct marker_block
*new;
3145 new = (struct marker_block
*) lisp_malloc (sizeof *new,
3147 new->next
= marker_block
;
3149 marker_block_index
= 0;
3151 total_free_markers
+= MARKER_BLOCK_SIZE
;
3153 XSETMISC (val
, &marker_block
->markers
[marker_block_index
]);
3154 marker_block_index
++;
3157 MALLOC_UNBLOCK_INPUT
;
3159 --total_free_markers
;
3160 consing_since_gc
+= sizeof (union Lisp_Misc
);
3161 misc_objects_consed
++;
3162 XMISCANY (val
)->gcmarkbit
= 0;
3166 /* Free a Lisp_Misc object */
3169 free_misc (Lisp_Object misc
)
3171 XMISCTYPE (misc
) = Lisp_Misc_Free
;
3172 XMISC (misc
)->u_free
.chain
= marker_free_list
;
3173 marker_free_list
= XMISC (misc
);
3175 total_free_markers
++;
3178 /* Return a Lisp_Misc_Save_Value object containing POINTER and
3179 INTEGER. This is used to package C values to call record_unwind_protect.
3180 The unwind function can get the C values back using XSAVE_VALUE. */
3183 make_save_value (void *pointer
, int integer
)
3185 register Lisp_Object val
;
3186 register struct Lisp_Save_Value
*p
;
3188 val
= allocate_misc ();
3189 XMISCTYPE (val
) = Lisp_Misc_Save_Value
;
3190 p
= XSAVE_VALUE (val
);
3191 p
->pointer
= pointer
;
3192 p
->integer
= integer
;
3197 DEFUN ("make-marker", Fmake_marker
, Smake_marker
, 0, 0, 0,
3198 doc
: /* Return a newly allocated marker which does not point at any place. */)
3201 register Lisp_Object val
;
3202 register struct Lisp_Marker
*p
;
3204 val
= allocate_misc ();
3205 XMISCTYPE (val
) = Lisp_Misc_Marker
;
3211 p
->insertion_type
= 0;
3215 /* Put MARKER back on the free list after using it temporarily. */
3218 free_marker (Lisp_Object marker
)
3220 unchain_marker (XMARKER (marker
));
3225 /* Return a newly created vector or string with specified arguments as
3226 elements. If all the arguments are characters that can fit
3227 in a string of events, make a string; otherwise, make a vector.
3229 Any number of arguments, even zero arguments, are allowed. */
3232 make_event_array (register int nargs
, Lisp_Object
*args
)
3236 for (i
= 0; i
< nargs
; i
++)
3237 /* The things that fit in a string
3238 are characters that are in 0...127,
3239 after discarding the meta bit and all the bits above it. */
3240 if (!INTEGERP (args
[i
])
3241 || (XUINT (args
[i
]) & ~(-CHAR_META
)) >= 0200)
3242 return Fvector (nargs
, args
);
3244 /* Since the loop exited, we know that all the things in it are
3245 characters, so we can make a string. */
3249 result
= Fmake_string (make_number (nargs
), make_number (0));
3250 for (i
= 0; i
< nargs
; i
++)
3252 SSET (result
, i
, XINT (args
[i
]));
3253 /* Move the meta bit to the right place for a string char. */
3254 if (XINT (args
[i
]) & CHAR_META
)
3255 SSET (result
, i
, SREF (result
, i
) | 0x80);
3264 /************************************************************************
3265 Memory Full Handling
3266 ************************************************************************/
3269 /* Called if malloc returns zero. */
3278 memory_full_cons_threshold
= sizeof (struct cons_block
);
3280 /* The first time we get here, free the spare memory. */
3281 for (i
= 0; i
< sizeof (spare_memory
) / sizeof (char *); i
++)
3282 if (spare_memory
[i
])
3285 free (spare_memory
[i
]);
3286 else if (i
>= 1 && i
<= 4)
3287 lisp_align_free (spare_memory
[i
]);
3289 lisp_free (spare_memory
[i
]);
3290 spare_memory
[i
] = 0;
3293 /* Record the space now used. When it decreases substantially,
3294 we can refill the memory reserve. */
3295 #ifndef SYSTEM_MALLOC
3296 bytes_used_when_full
= BYTES_USED
;
3299 /* This used to call error, but if we've run out of memory, we could
3300 get infinite recursion trying to build the string. */
3301 xsignal (Qnil
, Vmemory_signal_data
);
3304 /* If we released our reserve (due to running out of memory),
3305 and we have a fair amount free once again,
3306 try to set aside another reserve in case we run out once more.
3308 This is called when a relocatable block is freed in ralloc.c,
3309 and also directly from this file, in case we're not using ralloc.c. */
3312 refill_memory_reserve (void)
3314 #ifndef SYSTEM_MALLOC
3315 if (spare_memory
[0] == 0)
3316 spare_memory
[0] = (char *) malloc ((size_t) SPARE_MEMORY
);
3317 if (spare_memory
[1] == 0)
3318 spare_memory
[1] = (char *) lisp_align_malloc (sizeof (struct cons_block
),
3320 if (spare_memory
[2] == 0)
3321 spare_memory
[2] = (char *) lisp_align_malloc (sizeof (struct cons_block
),
3323 if (spare_memory
[3] == 0)
3324 spare_memory
[3] = (char *) lisp_align_malloc (sizeof (struct cons_block
),
3326 if (spare_memory
[4] == 0)
3327 spare_memory
[4] = (char *) lisp_align_malloc (sizeof (struct cons_block
),
3329 if (spare_memory
[5] == 0)
3330 spare_memory
[5] = (char *) lisp_malloc (sizeof (struct string_block
),
3332 if (spare_memory
[6] == 0)
3333 spare_memory
[6] = (char *) lisp_malloc (sizeof (struct string_block
),
3335 if (spare_memory
[0] && spare_memory
[1] && spare_memory
[5])
3336 Vmemory_full
= Qnil
;
3340 /************************************************************************
3342 ************************************************************************/
3344 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
3346 /* Conservative C stack marking requires a method to identify possibly
3347 live Lisp objects given a pointer value. We do this by keeping
3348 track of blocks of Lisp data that are allocated in a red-black tree
3349 (see also the comment of mem_node which is the type of nodes in
3350 that tree). Function lisp_malloc adds information for an allocated
3351 block to the red-black tree with calls to mem_insert, and function
3352 lisp_free removes it with mem_delete. Functions live_string_p etc
3353 call mem_find to lookup information about a given pointer in the
3354 tree, and use that to determine if the pointer points to a Lisp
3357 /* Initialize this part of alloc.c. */
3362 mem_z
.left
= mem_z
.right
= MEM_NIL
;
3363 mem_z
.parent
= NULL
;
3364 mem_z
.color
= MEM_BLACK
;
3365 mem_z
.start
= mem_z
.end
= NULL
;
3370 /* Value is a pointer to the mem_node containing START. Value is
3371 MEM_NIL if there is no node in the tree containing START. */
3373 static INLINE
struct mem_node
*
3374 mem_find (void *start
)
3378 if (start
< min_heap_address
|| start
> max_heap_address
)
3381 /* Make the search always successful to speed up the loop below. */
3382 mem_z
.start
= start
;
3383 mem_z
.end
= (char *) start
+ 1;
3386 while (start
< p
->start
|| start
>= p
->end
)
3387 p
= start
< p
->start
? p
->left
: p
->right
;
3392 /* Insert a new node into the tree for a block of memory with start
3393 address START, end address END, and type TYPE. Value is a
3394 pointer to the node that was inserted. */
3396 static struct mem_node
*
3397 mem_insert (void *start
, void *end
, enum mem_type type
)
3399 struct mem_node
*c
, *parent
, *x
;
3401 if (min_heap_address
== NULL
|| start
< min_heap_address
)
3402 min_heap_address
= start
;
3403 if (max_heap_address
== NULL
|| end
> max_heap_address
)
3404 max_heap_address
= end
;
3406 /* See where in the tree a node for START belongs. In this
3407 particular application, it shouldn't happen that a node is already
3408 present. For debugging purposes, let's check that. */
3412 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
3414 while (c
!= MEM_NIL
)
3416 if (start
>= c
->start
&& start
< c
->end
)
3419 c
= start
< c
->start
? c
->left
: c
->right
;
3422 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3424 while (c
!= MEM_NIL
)
3427 c
= start
< c
->start
? c
->left
: c
->right
;
3430 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3432 /* Create a new node. */
3433 #ifdef GC_MALLOC_CHECK
3434 x
= (struct mem_node
*) _malloc_internal (sizeof *x
);
3438 x
= (struct mem_node
*) xmalloc (sizeof *x
);
3444 x
->left
= x
->right
= MEM_NIL
;
3447 /* Insert it as child of PARENT or install it as root. */
3450 if (start
< parent
->start
)
3458 /* Re-establish red-black tree properties. */
3459 mem_insert_fixup (x
);
3465 /* Re-establish the red-black properties of the tree, and thereby
3466 balance the tree, after node X has been inserted; X is always red. */
3469 mem_insert_fixup (struct mem_node
*x
)
3471 while (x
!= mem_root
&& x
->parent
->color
== MEM_RED
)
3473 /* X is red and its parent is red. This is a violation of
3474 red-black tree property #3. */
3476 if (x
->parent
== x
->parent
->parent
->left
)
3478 /* We're on the left side of our grandparent, and Y is our
3480 struct mem_node
*y
= x
->parent
->parent
->right
;
3482 if (y
->color
== MEM_RED
)
3484 /* Uncle and parent are red but should be black because
3485 X is red. Change the colors accordingly and proceed
3486 with the grandparent. */
3487 x
->parent
->color
= MEM_BLACK
;
3488 y
->color
= MEM_BLACK
;
3489 x
->parent
->parent
->color
= MEM_RED
;
3490 x
= x
->parent
->parent
;
3494 /* Parent and uncle have different colors; parent is
3495 red, uncle is black. */
3496 if (x
== x
->parent
->right
)
3499 mem_rotate_left (x
);
3502 x
->parent
->color
= MEM_BLACK
;
3503 x
->parent
->parent
->color
= MEM_RED
;
3504 mem_rotate_right (x
->parent
->parent
);
3509 /* This is the symmetrical case of above. */
3510 struct mem_node
*y
= x
->parent
->parent
->left
;
3512 if (y
->color
== MEM_RED
)
3514 x
->parent
->color
= MEM_BLACK
;
3515 y
->color
= MEM_BLACK
;
3516 x
->parent
->parent
->color
= MEM_RED
;
3517 x
= x
->parent
->parent
;
3521 if (x
== x
->parent
->left
)
3524 mem_rotate_right (x
);
3527 x
->parent
->color
= MEM_BLACK
;
3528 x
->parent
->parent
->color
= MEM_RED
;
3529 mem_rotate_left (x
->parent
->parent
);
3534 /* The root may have been changed to red due to the algorithm. Set
3535 it to black so that property #5 is satisfied. */
3536 mem_root
->color
= MEM_BLACK
;
3547 mem_rotate_left (struct mem_node
*x
)
3551 /* Turn y's left sub-tree into x's right sub-tree. */
3554 if (y
->left
!= MEM_NIL
)
3555 y
->left
->parent
= x
;
3557 /* Y's parent was x's parent. */
3559 y
->parent
= x
->parent
;
3561 /* Get the parent to point to y instead of x. */
3564 if (x
== x
->parent
->left
)
3565 x
->parent
->left
= y
;
3567 x
->parent
->right
= y
;
3572 /* Put x on y's left. */
3586 mem_rotate_right (struct mem_node
*x
)
3588 struct mem_node
*y
= x
->left
;
3591 if (y
->right
!= MEM_NIL
)
3592 y
->right
->parent
= x
;
3595 y
->parent
= x
->parent
;
3598 if (x
== x
->parent
->right
)
3599 x
->parent
->right
= y
;
3601 x
->parent
->left
= y
;
3612 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
3615 mem_delete (struct mem_node
*z
)
3617 struct mem_node
*x
, *y
;
3619 if (!z
|| z
== MEM_NIL
)
3622 if (z
->left
== MEM_NIL
|| z
->right
== MEM_NIL
)
3627 while (y
->left
!= MEM_NIL
)
3631 if (y
->left
!= MEM_NIL
)
3636 x
->parent
= y
->parent
;
3639 if (y
== y
->parent
->left
)
3640 y
->parent
->left
= x
;
3642 y
->parent
->right
= x
;
3649 z
->start
= y
->start
;
3654 if (y
->color
== MEM_BLACK
)
3655 mem_delete_fixup (x
);
3657 #ifdef GC_MALLOC_CHECK
3665 /* Re-establish the red-black properties of the tree, after a
3669 mem_delete_fixup (struct mem_node
*x
)
3671 while (x
!= mem_root
&& x
->color
== MEM_BLACK
)
3673 if (x
== x
->parent
->left
)
3675 struct mem_node
*w
= x
->parent
->right
;
3677 if (w
->color
== MEM_RED
)
3679 w
->color
= MEM_BLACK
;
3680 x
->parent
->color
= MEM_RED
;
3681 mem_rotate_left (x
->parent
);
3682 w
= x
->parent
->right
;
3685 if (w
->left
->color
== MEM_BLACK
&& w
->right
->color
== MEM_BLACK
)
3692 if (w
->right
->color
== MEM_BLACK
)
3694 w
->left
->color
= MEM_BLACK
;
3696 mem_rotate_right (w
);
3697 w
= x
->parent
->right
;
3699 w
->color
= x
->parent
->color
;
3700 x
->parent
->color
= MEM_BLACK
;
3701 w
->right
->color
= MEM_BLACK
;
3702 mem_rotate_left (x
->parent
);
3708 struct mem_node
*w
= x
->parent
->left
;
3710 if (w
->color
== MEM_RED
)
3712 w
->color
= MEM_BLACK
;
3713 x
->parent
->color
= MEM_RED
;
3714 mem_rotate_right (x
->parent
);
3715 w
= x
->parent
->left
;
3718 if (w
->right
->color
== MEM_BLACK
&& w
->left
->color
== MEM_BLACK
)
3725 if (w
->left
->color
== MEM_BLACK
)
3727 w
->right
->color
= MEM_BLACK
;
3729 mem_rotate_left (w
);
3730 w
= x
->parent
->left
;
3733 w
->color
= x
->parent
->color
;
3734 x
->parent
->color
= MEM_BLACK
;
3735 w
->left
->color
= MEM_BLACK
;
3736 mem_rotate_right (x
->parent
);
3742 x
->color
= MEM_BLACK
;
3746 /* Value is non-zero if P is a pointer to a live Lisp string on
3747 the heap. M is a pointer to the mem_block for P. */
3750 live_string_p (struct mem_node
*m
, void *p
)
3752 if (m
->type
== MEM_TYPE_STRING
)
3754 struct string_block
*b
= (struct string_block
*) m
->start
;
3755 ptrdiff_t offset
= (char *) p
- (char *) &b
->strings
[0];
3757 /* P must point to the start of a Lisp_String structure, and it
3758 must not be on the free-list. */
3760 && offset
% sizeof b
->strings
[0] == 0
3761 && offset
< (STRING_BLOCK_SIZE
* sizeof b
->strings
[0])
3762 && ((struct Lisp_String
*) p
)->data
!= NULL
);
3769 /* Value is non-zero if P is a pointer to a live Lisp cons on
3770 the heap. M is a pointer to the mem_block for P. */
3773 live_cons_p (struct mem_node
*m
, void *p
)
3775 if (m
->type
== MEM_TYPE_CONS
)
3777 struct cons_block
*b
= (struct cons_block
*) m
->start
;
3778 ptrdiff_t offset
= (char *) p
- (char *) &b
->conses
[0];
3780 /* P must point to the start of a Lisp_Cons, not be
3781 one of the unused cells in the current cons block,
3782 and not be on the free-list. */
3784 && offset
% sizeof b
->conses
[0] == 0
3785 && offset
< (CONS_BLOCK_SIZE
* sizeof b
->conses
[0])
3787 || offset
/ sizeof b
->conses
[0] < cons_block_index
)
3788 && !EQ (((struct Lisp_Cons
*) p
)->car
, Vdead
));
3795 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3796 the heap. M is a pointer to the mem_block for P. */
3799 live_symbol_p (struct mem_node
*m
, void *p
)
3801 if (m
->type
== MEM_TYPE_SYMBOL
)
3803 struct symbol_block
*b
= (struct symbol_block
*) m
->start
;
3804 ptrdiff_t offset
= (char *) p
- (char *) &b
->symbols
[0];
3806 /* P must point to the start of a Lisp_Symbol, not be
3807 one of the unused cells in the current symbol block,
3808 and not be on the free-list. */
3810 && offset
% sizeof b
->symbols
[0] == 0
3811 && offset
< (SYMBOL_BLOCK_SIZE
* sizeof b
->symbols
[0])
3812 && (b
!= symbol_block
3813 || offset
/ sizeof b
->symbols
[0] < symbol_block_index
)
3814 && !EQ (((struct Lisp_Symbol
*) p
)->function
, Vdead
));
3821 /* Value is non-zero if P is a pointer to a live Lisp float on
3822 the heap. M is a pointer to the mem_block for P. */
3825 live_float_p (struct mem_node
*m
, void *p
)
3827 if (m
->type
== MEM_TYPE_FLOAT
)
3829 struct float_block
*b
= (struct float_block
*) m
->start
;
3830 ptrdiff_t offset
= (char *) p
- (char *) &b
->floats
[0];
3832 /* P must point to the start of a Lisp_Float and not be
3833 one of the unused cells in the current float block. */
3835 && offset
% sizeof b
->floats
[0] == 0
3836 && offset
< (FLOAT_BLOCK_SIZE
* sizeof b
->floats
[0])
3837 && (b
!= float_block
3838 || offset
/ sizeof b
->floats
[0] < float_block_index
));
3845 /* Value is non-zero if P is a pointer to a live Lisp Misc on
3846 the heap. M is a pointer to the mem_block for P. */
3849 live_misc_p (struct mem_node
*m
, void *p
)
3851 if (m
->type
== MEM_TYPE_MISC
)
3853 struct marker_block
*b
= (struct marker_block
*) m
->start
;
3854 ptrdiff_t offset
= (char *) p
- (char *) &b
->markers
[0];
3856 /* P must point to the start of a Lisp_Misc, not be
3857 one of the unused cells in the current misc block,
3858 and not be on the free-list. */
3860 && offset
% sizeof b
->markers
[0] == 0
3861 && offset
< (MARKER_BLOCK_SIZE
* sizeof b
->markers
[0])
3862 && (b
!= marker_block
3863 || offset
/ sizeof b
->markers
[0] < marker_block_index
)
3864 && ((union Lisp_Misc
*) p
)->u_any
.type
!= Lisp_Misc_Free
);
3871 /* Value is non-zero if P is a pointer to a live vector-like object.
3872 M is a pointer to the mem_block for P. */
3875 live_vector_p (struct mem_node
*m
, void *p
)
3877 return (p
== m
->start
&& m
->type
== MEM_TYPE_VECTORLIKE
);
3881 /* Value is non-zero if P is a pointer to a live buffer. M is a
3882 pointer to the mem_block for P. */
3885 live_buffer_p (struct mem_node
*m
, void *p
)
3887 /* P must point to the start of the block, and the buffer
3888 must not have been killed. */
3889 return (m
->type
== MEM_TYPE_BUFFER
3891 && !NILP (((struct buffer
*) p
)->BUFFER_INTERNAL_FIELD (name
)));
3894 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
3898 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3900 /* Array of objects that are kept alive because the C stack contains
3901 a pattern that looks like a reference to them . */
3903 #define MAX_ZOMBIES 10
3904 static Lisp_Object zombies
[MAX_ZOMBIES
];
3906 /* Number of zombie objects. */
3908 static int nzombies
;
3910 /* Number of garbage collections. */
3914 /* Average percentage of zombies per collection. */
3916 static double avg_zombies
;
3918 /* Max. number of live and zombie objects. */
3920 static int max_live
, max_zombies
;
3922 /* Average number of live objects per GC. */
3924 static double avg_live
;
3926 DEFUN ("gc-status", Fgc_status
, Sgc_status
, 0, 0, "",
3927 doc
: /* Show information about live and zombie objects. */)
3930 Lisp_Object args
[8], zombie_list
= Qnil
;
3932 for (i
= 0; i
< nzombies
; i
++)
3933 zombie_list
= Fcons (zombies
[i
], zombie_list
);
3934 args
[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
3935 args
[1] = make_number (ngcs
);
3936 args
[2] = make_float (avg_live
);
3937 args
[3] = make_float (avg_zombies
);
3938 args
[4] = make_float (avg_zombies
/ avg_live
/ 100);
3939 args
[5] = make_number (max_live
);
3940 args
[6] = make_number (max_zombies
);
3941 args
[7] = zombie_list
;
3942 return Fmessage (8, args
);
3945 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3948 /* Mark OBJ if we can prove it's a Lisp_Object. */
3951 mark_maybe_object (Lisp_Object obj
)
3959 po
= (void *) XPNTR (obj
);
3966 switch (XTYPE (obj
))
3969 mark_p
= (live_string_p (m
, po
)
3970 && !STRING_MARKED_P ((struct Lisp_String
*) po
));
3974 mark_p
= (live_cons_p (m
, po
) && !CONS_MARKED_P (XCONS (obj
)));
3978 mark_p
= (live_symbol_p (m
, po
) && !XSYMBOL (obj
)->gcmarkbit
);
3982 mark_p
= (live_float_p (m
, po
) && !FLOAT_MARKED_P (XFLOAT (obj
)));
3985 case Lisp_Vectorlike
:
3986 /* Note: can't check BUFFERP before we know it's a
3987 buffer because checking that dereferences the pointer
3988 PO which might point anywhere. */
3989 if (live_vector_p (m
, po
))
3990 mark_p
= !SUBRP (obj
) && !VECTOR_MARKED_P (XVECTOR (obj
));
3991 else if (live_buffer_p (m
, po
))
3992 mark_p
= BUFFERP (obj
) && !VECTOR_MARKED_P (XBUFFER (obj
));
3996 mark_p
= (live_misc_p (m
, po
) && !XMISCANY (obj
)->gcmarkbit
);
4005 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4006 if (nzombies
< MAX_ZOMBIES
)
4007 zombies
[nzombies
] = obj
;
4016 /* If P points to Lisp data, mark that as live if it isn't already
4020 mark_maybe_pointer (void *p
)
4024 /* Quickly rule out some values which can't point to Lisp data. */
4027 8 /* USE_LSB_TAG needs Lisp data to be aligned on multiples of 8. */
4029 2 /* We assume that Lisp data is aligned on even addresses. */
4037 Lisp_Object obj
= Qnil
;
4041 case MEM_TYPE_NON_LISP
:
4042 /* Nothing to do; not a pointer to Lisp memory. */
4045 case MEM_TYPE_BUFFER
:
4046 if (live_buffer_p (m
, p
) && !VECTOR_MARKED_P((struct buffer
*)p
))
4047 XSETVECTOR (obj
, p
);
4051 if (live_cons_p (m
, p
) && !CONS_MARKED_P ((struct Lisp_Cons
*) p
))
4055 case MEM_TYPE_STRING
:
4056 if (live_string_p (m
, p
)
4057 && !STRING_MARKED_P ((struct Lisp_String
*) p
))
4058 XSETSTRING (obj
, p
);
4062 if (live_misc_p (m
, p
) && !((struct Lisp_Free
*) p
)->gcmarkbit
)
4066 case MEM_TYPE_SYMBOL
:
4067 if (live_symbol_p (m
, p
) && !((struct Lisp_Symbol
*) p
)->gcmarkbit
)
4068 XSETSYMBOL (obj
, p
);
4071 case MEM_TYPE_FLOAT
:
4072 if (live_float_p (m
, p
) && !FLOAT_MARKED_P (p
))
4076 case MEM_TYPE_VECTORLIKE
:
4077 if (live_vector_p (m
, p
))
4080 XSETVECTOR (tem
, p
);
4081 if (!SUBRP (tem
) && !VECTOR_MARKED_P (XVECTOR (tem
)))
4096 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4097 or END+OFFSET..START. */
4100 mark_memory (void *start
, void *end
, int offset
)
4105 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4109 /* Make START the pointer to the start of the memory region,
4110 if it isn't already. */
4118 /* Mark Lisp_Objects. */
4119 for (p
= (Lisp_Object
*) ((char *) start
+ offset
); (void *) p
< end
; ++p
)
4120 mark_maybe_object (*p
);
4122 /* Mark Lisp data pointed to. This is necessary because, in some
4123 situations, the C compiler optimizes Lisp objects away, so that
4124 only a pointer to them remains. Example:
4126 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4129 Lisp_Object obj = build_string ("test");
4130 struct Lisp_String *s = XSTRING (obj);
4131 Fgarbage_collect ();
4132 fprintf (stderr, "test `%s'\n", s->data);
4136 Here, `obj' isn't really used, and the compiler optimizes it
4137 away. The only reference to the life string is through the
4140 for (pp
= (void **) ((char *) start
+ offset
); (void *) pp
< end
; ++pp
)
4141 mark_maybe_pointer (*pp
);
4144 /* setjmp will work with GCC unless NON_SAVING_SETJMP is defined in
4145 the GCC system configuration. In gcc 3.2, the only systems for
4146 which this is so are i386-sco5 non-ELF, i386-sysv3 (maybe included
4147 by others?) and ns32k-pc532-min. */
4149 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4151 static int setjmp_tested_p
, longjmps_done
;
4153 #define SETJMP_WILL_LIKELY_WORK "\
4155 Emacs garbage collector has been changed to use conservative stack\n\
4156 marking. Emacs has determined that the method it uses to do the\n\
4157 marking will likely work on your system, but this isn't sure.\n\
4159 If you are a system-programmer, or can get the help of a local wizard\n\
4160 who is, please take a look at the function mark_stack in alloc.c, and\n\
4161 verify that the methods used are appropriate for your system.\n\
4163 Please mail the result to <emacs-devel@gnu.org>.\n\
4166 #define SETJMP_WILL_NOT_WORK "\
4168 Emacs garbage collector has been changed to use conservative stack\n\
4169 marking. Emacs has determined that the default method it uses to do the\n\
4170 marking will not work on your system. We will need a system-dependent\n\
4171 solution for your system.\n\
4173 Please take a look at the function mark_stack in alloc.c, and\n\
4174 try to find a way to make it work on your system.\n\
4176 Note that you may get false negatives, depending on the compiler.\n\
4177 In particular, you need to use -O with GCC for this test.\n\
4179 Please mail the result to <emacs-devel@gnu.org>.\n\
4183 /* Perform a quick check if it looks like setjmp saves registers in a
4184 jmp_buf. Print a message to stderr saying so. When this test
4185 succeeds, this is _not_ a proof that setjmp is sufficient for
4186 conservative stack marking. Only the sources or a disassembly
4197 /* Arrange for X to be put in a register. */
4203 if (longjmps_done
== 1)
4205 /* Came here after the longjmp at the end of the function.
4207 If x == 1, the longjmp has restored the register to its
4208 value before the setjmp, and we can hope that setjmp
4209 saves all such registers in the jmp_buf, although that
4212 For other values of X, either something really strange is
4213 taking place, or the setjmp just didn't save the register. */
4216 fprintf (stderr
, SETJMP_WILL_LIKELY_WORK
);
4219 fprintf (stderr
, SETJMP_WILL_NOT_WORK
);
4226 if (longjmps_done
== 1)
4230 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4233 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4235 /* Abort if anything GCPRO'd doesn't survive the GC. */
4243 for (p
= gcprolist
; p
; p
= p
->next
)
4244 for (i
= 0; i
< p
->nvars
; ++i
)
4245 if (!survives_gc_p (p
->var
[i
]))
4246 /* FIXME: It's not necessarily a bug. It might just be that the
4247 GCPRO is unnecessary or should release the object sooner. */
4251 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4258 fprintf (stderr
, "\nZombies kept alive = %d:\n", nzombies
);
4259 for (i
= 0; i
< min (MAX_ZOMBIES
, nzombies
); ++i
)
4261 fprintf (stderr
, " %d = ", i
);
4262 debug_print (zombies
[i
]);
4266 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4269 /* Mark live Lisp objects on the C stack.
4271 There are several system-dependent problems to consider when
4272 porting this to new architectures:
4276 We have to mark Lisp objects in CPU registers that can hold local
4277 variables or are used to pass parameters.
4279 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4280 something that either saves relevant registers on the stack, or
4281 calls mark_maybe_object passing it each register's contents.
4283 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4284 implementation assumes that calling setjmp saves registers we need
4285 to see in a jmp_buf which itself lies on the stack. This doesn't
4286 have to be true! It must be verified for each system, possibly
4287 by taking a look at the source code of setjmp.
4289 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4290 can use it as a machine independent method to store all registers
4291 to the stack. In this case the macros described in the previous
4292 two paragraphs are not used.
4296 Architectures differ in the way their processor stack is organized.
4297 For example, the stack might look like this
4300 | Lisp_Object | size = 4
4302 | something else | size = 2
4304 | Lisp_Object | size = 4
4308 In such a case, not every Lisp_Object will be aligned equally. To
4309 find all Lisp_Object on the stack it won't be sufficient to walk
4310 the stack in steps of 4 bytes. Instead, two passes will be
4311 necessary, one starting at the start of the stack, and a second
4312 pass starting at the start of the stack + 2. Likewise, if the
4313 minimal alignment of Lisp_Objects on the stack is 1, four passes
4314 would be necessary, each one starting with one byte more offset
4315 from the stack start.
4317 The current code assumes by default that Lisp_Objects are aligned
4318 equally on the stack. */
4326 #ifdef HAVE___BUILTIN_UNWIND_INIT
4327 /* Force callee-saved registers and register windows onto the stack.
4328 This is the preferred method if available, obviating the need for
4329 machine dependent methods. */
4330 __builtin_unwind_init ();
4332 #else /* not HAVE___BUILTIN_UNWIND_INIT */
4333 #ifndef GC_SAVE_REGISTERS_ON_STACK
4334 /* jmp_buf may not be aligned enough on darwin-ppc64 */
4335 union aligned_jmpbuf
{
4339 volatile int stack_grows_down_p
= (char *) &j
> (char *) stack_base
;
4341 /* This trick flushes the register windows so that all the state of
4342 the process is contained in the stack. */
4343 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
4344 needed on ia64 too. See mach_dep.c, where it also says inline
4345 assembler doesn't work with relevant proprietary compilers. */
4347 #if defined (__sparc64__) && defined (__FreeBSD__)
4348 /* FreeBSD does not have a ta 3 handler. */
4355 /* Save registers that we need to see on the stack. We need to see
4356 registers used to hold register variables and registers used to
4358 #ifdef GC_SAVE_REGISTERS_ON_STACK
4359 GC_SAVE_REGISTERS_ON_STACK (end
);
4360 #else /* not GC_SAVE_REGISTERS_ON_STACK */
4362 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
4363 setjmp will definitely work, test it
4364 and print a message with the result
4366 if (!setjmp_tested_p
)
4368 setjmp_tested_p
= 1;
4371 #endif /* GC_SETJMP_WORKS */
4374 end
= stack_grows_down_p
? (char *) &j
+ sizeof j
: (char *) &j
;
4375 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
4376 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
4378 /* This assumes that the stack is a contiguous region in memory. If
4379 that's not the case, something has to be done here to iterate
4380 over the stack segments. */
4381 #ifndef GC_LISP_OBJECT_ALIGNMENT
4383 #define GC_LISP_OBJECT_ALIGNMENT __alignof__ (Lisp_Object)
4385 #define GC_LISP_OBJECT_ALIGNMENT sizeof (Lisp_Object)
4388 for (i
= 0; i
< sizeof (Lisp_Object
); i
+= GC_LISP_OBJECT_ALIGNMENT
)
4389 mark_memory (stack_base
, end
, i
);
4390 /* Allow for marking a secondary stack, like the register stack on the
4392 #ifdef GC_MARK_SECONDARY_STACK
4393 GC_MARK_SECONDARY_STACK ();
4396 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4401 #endif /* GC_MARK_STACK != 0 */
4404 /* Determine whether it is safe to access memory at address P. */
4406 valid_pointer_p (void *p
)
4409 return w32_valid_pointer_p (p
, 16);
4413 /* Obviously, we cannot just access it (we would SEGV trying), so we
4414 trick the o/s to tell us whether p is a valid pointer.
4415 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4416 not validate p in that case. */
4418 if ((fd
= emacs_open ("__Valid__Lisp__Object__", O_CREAT
| O_WRONLY
| O_TRUNC
, 0666)) >= 0)
4420 int valid
= (emacs_write (fd
, (char *)p
, 16) == 16);
4422 unlink ("__Valid__Lisp__Object__");
4430 /* Return 1 if OBJ is a valid lisp object.
4431 Return 0 if OBJ is NOT a valid lisp object.
4432 Return -1 if we cannot validate OBJ.
4433 This function can be quite slow,
4434 so it should only be used in code for manual debugging. */
4437 valid_lisp_object_p (Lisp_Object obj
)
4447 p
= (void *) XPNTR (obj
);
4448 if (PURE_POINTER_P (p
))
4452 return valid_pointer_p (p
);
4459 int valid
= valid_pointer_p (p
);
4471 case MEM_TYPE_NON_LISP
:
4474 case MEM_TYPE_BUFFER
:
4475 return live_buffer_p (m
, p
);
4478 return live_cons_p (m
, p
);
4480 case MEM_TYPE_STRING
:
4481 return live_string_p (m
, p
);
4484 return live_misc_p (m
, p
);
4486 case MEM_TYPE_SYMBOL
:
4487 return live_symbol_p (m
, p
);
4489 case MEM_TYPE_FLOAT
:
4490 return live_float_p (m
, p
);
4492 case MEM_TYPE_VECTORLIKE
:
4493 return live_vector_p (m
, p
);
4506 /***********************************************************************
4507 Pure Storage Management
4508 ***********************************************************************/
4510 /* Allocate room for SIZE bytes from pure Lisp storage and return a
4511 pointer to it. TYPE is the Lisp type for which the memory is
4512 allocated. TYPE < 0 means it's not used for a Lisp object. */
4514 static POINTER_TYPE
*
4515 pure_alloc (size_t size
, int type
)
4517 POINTER_TYPE
*result
;
4519 size_t alignment
= (1 << GCTYPEBITS
);
4521 size_t alignment
= sizeof (EMACS_INT
);
4523 /* Give Lisp_Floats an extra alignment. */
4524 if (type
== Lisp_Float
)
4526 #if defined __GNUC__ && __GNUC__ >= 2
4527 alignment
= __alignof (struct Lisp_Float
);
4529 alignment
= sizeof (struct Lisp_Float
);
4537 /* Allocate space for a Lisp object from the beginning of the free
4538 space with taking account of alignment. */
4539 result
= ALIGN (purebeg
+ pure_bytes_used_lisp
, alignment
);
4540 pure_bytes_used_lisp
= ((char *)result
- (char *)purebeg
) + size
;
4544 /* Allocate space for a non-Lisp object from the end of the free
4546 pure_bytes_used_non_lisp
+= size
;
4547 result
= purebeg
+ pure_size
- pure_bytes_used_non_lisp
;
4549 pure_bytes_used
= pure_bytes_used_lisp
+ pure_bytes_used_non_lisp
;
4551 if (pure_bytes_used
<= pure_size
)
4554 /* Don't allocate a large amount here,
4555 because it might get mmap'd and then its address
4556 might not be usable. */
4557 purebeg
= (char *) xmalloc (10000);
4559 pure_bytes_used_before_overflow
+= pure_bytes_used
- size
;
4560 pure_bytes_used
= 0;
4561 pure_bytes_used_lisp
= pure_bytes_used_non_lisp
= 0;
4566 /* Print a warning if PURESIZE is too small. */
4569 check_pure_size (void)
4571 if (pure_bytes_used_before_overflow
)
4572 message ("emacs:0:Pure Lisp storage overflow (approx. %d bytes needed)",
4573 (int) (pure_bytes_used
+ pure_bytes_used_before_overflow
));
4577 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
4578 the non-Lisp data pool of the pure storage, and return its start
4579 address. Return NULL if not found. */
4582 find_string_data_in_pure (const char *data
, EMACS_INT nbytes
)
4585 EMACS_INT skip
, bm_skip
[256], last_char_skip
, infinity
, start
, start_max
;
4586 const unsigned char *p
;
4589 if (pure_bytes_used_non_lisp
< nbytes
+ 1)
4592 /* Set up the Boyer-Moore table. */
4594 for (i
= 0; i
< 256; i
++)
4597 p
= (const unsigned char *) data
;
4599 bm_skip
[*p
++] = skip
;
4601 last_char_skip
= bm_skip
['\0'];
4603 non_lisp_beg
= purebeg
+ pure_size
- pure_bytes_used_non_lisp
;
4604 start_max
= pure_bytes_used_non_lisp
- (nbytes
+ 1);
4606 /* See the comments in the function `boyer_moore' (search.c) for the
4607 use of `infinity'. */
4608 infinity
= pure_bytes_used_non_lisp
+ 1;
4609 bm_skip
['\0'] = infinity
;
4611 p
= (const unsigned char *) non_lisp_beg
+ nbytes
;
4615 /* Check the last character (== '\0'). */
4618 start
+= bm_skip
[*(p
+ start
)];
4620 while (start
<= start_max
);
4622 if (start
< infinity
)
4623 /* Couldn't find the last character. */
4626 /* No less than `infinity' means we could find the last
4627 character at `p[start - infinity]'. */
4630 /* Check the remaining characters. */
4631 if (memcmp (data
, non_lisp_beg
+ start
, nbytes
) == 0)
4633 return non_lisp_beg
+ start
;
4635 start
+= last_char_skip
;
4637 while (start
<= start_max
);
4643 /* Return a string allocated in pure space. DATA is a buffer holding
4644 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
4645 non-zero means make the result string multibyte.
4647 Must get an error if pure storage is full, since if it cannot hold
4648 a large string it may be able to hold conses that point to that
4649 string; then the string is not protected from gc. */
4652 make_pure_string (const char *data
,
4653 EMACS_INT nchars
, EMACS_INT nbytes
, int multibyte
)
4656 struct Lisp_String
*s
;
4658 s
= (struct Lisp_String
*) pure_alloc (sizeof *s
, Lisp_String
);
4659 s
->data
= (unsigned char *) find_string_data_in_pure (data
, nbytes
);
4660 if (s
->data
== NULL
)
4662 s
->data
= (unsigned char *) pure_alloc (nbytes
+ 1, -1);
4663 memcpy (s
->data
, data
, nbytes
);
4664 s
->data
[nbytes
] = '\0';
4667 s
->size_byte
= multibyte
? nbytes
: -1;
4668 s
->intervals
= NULL_INTERVAL
;
4669 XSETSTRING (string
, s
);
4673 /* Return a string a string allocated in pure space. Do not allocate
4674 the string data, just point to DATA. */
4677 make_pure_c_string (const char *data
)
4680 struct Lisp_String
*s
;
4681 EMACS_INT nchars
= strlen (data
);
4683 s
= (struct Lisp_String
*) pure_alloc (sizeof *s
, Lisp_String
);
4686 s
->data
= (unsigned char *) data
;
4687 s
->intervals
= NULL_INTERVAL
;
4688 XSETSTRING (string
, s
);
4692 /* Return a cons allocated from pure space. Give it pure copies
4693 of CAR as car and CDR as cdr. */
4696 pure_cons (Lisp_Object car
, Lisp_Object cdr
)
4698 register Lisp_Object
new;
4699 struct Lisp_Cons
*p
;
4701 p
= (struct Lisp_Cons
*) pure_alloc (sizeof *p
, Lisp_Cons
);
4703 XSETCAR (new, Fpurecopy (car
));
4704 XSETCDR (new, Fpurecopy (cdr
));
4709 /* Value is a float object with value NUM allocated from pure space. */
4712 make_pure_float (double num
)
4714 register Lisp_Object
new;
4715 struct Lisp_Float
*p
;
4717 p
= (struct Lisp_Float
*) pure_alloc (sizeof *p
, Lisp_Float
);
4719 XFLOAT_INIT (new, num
);
4724 /* Return a vector with room for LEN Lisp_Objects allocated from
4728 make_pure_vector (EMACS_INT len
)
4731 struct Lisp_Vector
*p
;
4732 size_t size
= sizeof *p
+ (len
- 1) * sizeof (Lisp_Object
);
4734 p
= (struct Lisp_Vector
*) pure_alloc (size
, Lisp_Vectorlike
);
4735 XSETVECTOR (new, p
);
4736 XVECTOR (new)->size
= len
;
4741 DEFUN ("purecopy", Fpurecopy
, Spurecopy
, 1, 1, 0,
4742 doc
: /* Make a copy of object OBJ in pure storage.
4743 Recursively copies contents of vectors and cons cells.
4744 Does not copy symbols. Copies strings without text properties. */)
4745 (register Lisp_Object obj
)
4747 if (NILP (Vpurify_flag
))
4750 if (PURE_POINTER_P (XPNTR (obj
)))
4753 if (HASH_TABLE_P (Vpurify_flag
)) /* Hash consing. */
4755 Lisp_Object tmp
= Fgethash (obj
, Vpurify_flag
, Qnil
);
4761 obj
= pure_cons (XCAR (obj
), XCDR (obj
));
4762 else if (FLOATP (obj
))
4763 obj
= make_pure_float (XFLOAT_DATA (obj
));
4764 else if (STRINGP (obj
))
4765 obj
= make_pure_string (SSDATA (obj
), SCHARS (obj
),
4767 STRING_MULTIBYTE (obj
));
4768 else if (COMPILEDP (obj
) || VECTORP (obj
))
4770 register struct Lisp_Vector
*vec
;
4771 register EMACS_INT i
;
4774 size
= XVECTOR (obj
)->size
;
4775 if (size
& PSEUDOVECTOR_FLAG
)
4776 size
&= PSEUDOVECTOR_SIZE_MASK
;
4777 vec
= XVECTOR (make_pure_vector (size
));
4778 for (i
= 0; i
< size
; i
++)
4779 vec
->contents
[i
] = Fpurecopy (XVECTOR (obj
)->contents
[i
]);
4780 if (COMPILEDP (obj
))
4782 XSETPVECTYPE (vec
, PVEC_COMPILED
);
4783 XSETCOMPILED (obj
, vec
);
4786 XSETVECTOR (obj
, vec
);
4788 else if (MARKERP (obj
))
4789 error ("Attempt to copy a marker to pure storage");
4791 /* Not purified, don't hash-cons. */
4794 if (HASH_TABLE_P (Vpurify_flag
)) /* Hash consing. */
4795 Fputhash (obj
, obj
, Vpurify_flag
);
4802 /***********************************************************************
4804 ***********************************************************************/
4806 /* Put an entry in staticvec, pointing at the variable with address
4810 staticpro (Lisp_Object
*varaddress
)
4812 staticvec
[staticidx
++] = varaddress
;
4813 if (staticidx
>= NSTATICS
)
4818 /***********************************************************************
4820 ***********************************************************************/
4822 /* Temporarily prevent garbage collection. */
4825 inhibit_garbage_collection (void)
4827 int count
= SPECPDL_INDEX ();
4828 int nbits
= min (VALBITS
, BITS_PER_INT
);
4830 specbind (Qgc_cons_threshold
, make_number (((EMACS_INT
) 1 << (nbits
- 1)) - 1));
4835 DEFUN ("garbage-collect", Fgarbage_collect
, Sgarbage_collect
, 0, 0, "",
4836 doc
: /* Reclaim storage for Lisp objects no longer needed.
4837 Garbage collection happens automatically if you cons more than
4838 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
4839 `garbage-collect' normally returns a list with info on amount of space in use:
4840 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
4841 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
4842 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)
4843 (USED-STRINGS . FREE-STRINGS))
4844 However, if there was overflow in pure space, `garbage-collect'
4845 returns nil, because real GC can't be done. */)
4848 register struct specbinding
*bind
;
4849 char stack_top_variable
;
4852 Lisp_Object total
[8];
4853 int count
= SPECPDL_INDEX ();
4854 EMACS_TIME t1
, t2
, t3
;
4859 /* Can't GC if pure storage overflowed because we can't determine
4860 if something is a pure object or not. */
4861 if (pure_bytes_used_before_overflow
)
4866 /* Don't keep undo information around forever.
4867 Do this early on, so it is no problem if the user quits. */
4869 register struct buffer
*nextb
= all_buffers
;
4873 /* If a buffer's undo list is Qt, that means that undo is
4874 turned off in that buffer. Calling truncate_undo_list on
4875 Qt tends to return NULL, which effectively turns undo back on.
4876 So don't call truncate_undo_list if undo_list is Qt. */
4877 if (! NILP (nextb
->BUFFER_INTERNAL_FIELD (name
)) && ! EQ (nextb
->BUFFER_INTERNAL_FIELD (undo_list
), Qt
))
4878 truncate_undo_list (nextb
);
4880 /* Shrink buffer gaps, but skip indirect and dead buffers. */
4881 if (nextb
->base_buffer
== 0 && !NILP (nextb
->BUFFER_INTERNAL_FIELD (name
))
4882 && ! nextb
->text
->inhibit_shrinking
)
4884 /* If a buffer's gap size is more than 10% of the buffer
4885 size, or larger than 2000 bytes, then shrink it
4886 accordingly. Keep a minimum size of 20 bytes. */
4887 int size
= min (2000, max (20, (nextb
->text
->z_byte
/ 10)));
4889 if (nextb
->text
->gap_size
> size
)
4891 struct buffer
*save_current
= current_buffer
;
4892 current_buffer
= nextb
;
4893 make_gap (-(nextb
->text
->gap_size
- size
));
4894 current_buffer
= save_current
;
4898 nextb
= nextb
->next
;
4902 EMACS_GET_TIME (t1
);
4904 /* In case user calls debug_print during GC,
4905 don't let that cause a recursive GC. */
4906 consing_since_gc
= 0;
4908 /* Save what's currently displayed in the echo area. */
4909 message_p
= push_message ();
4910 record_unwind_protect (pop_message_unwind
, Qnil
);
4912 /* Save a copy of the contents of the stack, for debugging. */
4913 #if MAX_SAVE_STACK > 0
4914 if (NILP (Vpurify_flag
))
4916 i
= &stack_top_variable
- stack_bottom
;
4918 if (i
< MAX_SAVE_STACK
)
4920 if (stack_copy
== 0)
4921 stack_copy
= (char *) xmalloc (stack_copy_size
= i
);
4922 else if (stack_copy_size
< i
)
4923 stack_copy
= (char *) xrealloc (stack_copy
, (stack_copy_size
= i
));
4926 if ((EMACS_INT
) (&stack_top_variable
- stack_bottom
) > 0)
4927 memcpy (stack_copy
, stack_bottom
, i
);
4929 memcpy (stack_copy
, &stack_top_variable
, i
);
4933 #endif /* MAX_SAVE_STACK > 0 */
4935 if (garbage_collection_messages
)
4936 message1_nolog ("Garbage collecting...");
4940 shrink_regexp_cache ();
4944 /* clear_marks (); */
4946 /* Mark all the special slots that serve as the roots of accessibility. */
4948 for (i
= 0; i
< staticidx
; i
++)
4949 mark_object (*staticvec
[i
]);
4951 for (bind
= specpdl
; bind
!= specpdl_ptr
; bind
++)
4953 mark_object (bind
->symbol
);
4954 mark_object (bind
->old_value
);
4962 extern void xg_mark_data (void);
4967 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
4968 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
4972 register struct gcpro
*tail
;
4973 for (tail
= gcprolist
; tail
; tail
= tail
->next
)
4974 for (i
= 0; i
< tail
->nvars
; i
++)
4975 mark_object (tail
->var
[i
]);
4979 struct catchtag
*catch;
4980 struct handler
*handler
;
4982 for (catch = catchlist
; catch; catch = catch->next
)
4984 mark_object (catch->tag
);
4985 mark_object (catch->val
);
4987 for (handler
= handlerlist
; handler
; handler
= handler
->next
)
4989 mark_object (handler
->handler
);
4990 mark_object (handler
->var
);
4996 #ifdef HAVE_WINDOW_SYSTEM
4997 mark_fringe_data ();
5000 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5004 /* Everything is now marked, except for the things that require special
5005 finalization, i.e. the undo_list.
5006 Look thru every buffer's undo list
5007 for elements that update markers that were not marked,
5010 register struct buffer
*nextb
= all_buffers
;
5014 /* If a buffer's undo list is Qt, that means that undo is
5015 turned off in that buffer. Calling truncate_undo_list on
5016 Qt tends to return NULL, which effectively turns undo back on.
5017 So don't call truncate_undo_list if undo_list is Qt. */
5018 if (! EQ (nextb
->BUFFER_INTERNAL_FIELD (undo_list
), Qt
))
5020 Lisp_Object tail
, prev
;
5021 tail
= nextb
->BUFFER_INTERNAL_FIELD (undo_list
);
5023 while (CONSP (tail
))
5025 if (CONSP (XCAR (tail
))
5026 && MARKERP (XCAR (XCAR (tail
)))
5027 && !XMARKER (XCAR (XCAR (tail
)))->gcmarkbit
)
5030 nextb
->BUFFER_INTERNAL_FIELD (undo_list
) = tail
= XCDR (tail
);
5034 XSETCDR (prev
, tail
);
5044 /* Now that we have stripped the elements that need not be in the
5045 undo_list any more, we can finally mark the list. */
5046 mark_object (nextb
->BUFFER_INTERNAL_FIELD (undo_list
));
5048 nextb
= nextb
->next
;
5054 /* Clear the mark bits that we set in certain root slots. */
5056 unmark_byte_stack ();
5057 VECTOR_UNMARK (&buffer_defaults
);
5058 VECTOR_UNMARK (&buffer_local_symbols
);
5060 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
5068 /* clear_marks (); */
5071 consing_since_gc
= 0;
5072 if (gc_cons_threshold
< 10000)
5073 gc_cons_threshold
= 10000;
5075 if (FLOATP (Vgc_cons_percentage
))
5076 { /* Set gc_cons_combined_threshold. */
5079 tot
+= total_conses
* sizeof (struct Lisp_Cons
);
5080 tot
+= total_symbols
* sizeof (struct Lisp_Symbol
);
5081 tot
+= total_markers
* sizeof (union Lisp_Misc
);
5082 tot
+= total_string_size
;
5083 tot
+= total_vector_size
* sizeof (Lisp_Object
);
5084 tot
+= total_floats
* sizeof (struct Lisp_Float
);
5085 tot
+= total_intervals
* sizeof (struct interval
);
5086 tot
+= total_strings
* sizeof (struct Lisp_String
);
5088 gc_relative_threshold
= tot
* XFLOAT_DATA (Vgc_cons_percentage
);
5091 gc_relative_threshold
= 0;
5093 if (garbage_collection_messages
)
5095 if (message_p
|| minibuf_level
> 0)
5098 message1_nolog ("Garbage collecting...done");
5101 unbind_to (count
, Qnil
);
5103 total
[0] = Fcons (make_number (total_conses
),
5104 make_number (total_free_conses
));
5105 total
[1] = Fcons (make_number (total_symbols
),
5106 make_number (total_free_symbols
));
5107 total
[2] = Fcons (make_number (total_markers
),
5108 make_number (total_free_markers
));
5109 total
[3] = make_number (total_string_size
);
5110 total
[4] = make_number (total_vector_size
);
5111 total
[5] = Fcons (make_number (total_floats
),
5112 make_number (total_free_floats
));
5113 total
[6] = Fcons (make_number (total_intervals
),
5114 make_number (total_free_intervals
));
5115 total
[7] = Fcons (make_number (total_strings
),
5116 make_number (total_free_strings
));
5118 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5120 /* Compute average percentage of zombies. */
5123 for (i
= 0; i
< 7; ++i
)
5124 if (CONSP (total
[i
]))
5125 nlive
+= XFASTINT (XCAR (total
[i
]));
5127 avg_live
= (avg_live
* ngcs
+ nlive
) / (ngcs
+ 1);
5128 max_live
= max (nlive
, max_live
);
5129 avg_zombies
= (avg_zombies
* ngcs
+ nzombies
) / (ngcs
+ 1);
5130 max_zombies
= max (nzombies
, max_zombies
);
5135 if (!NILP (Vpost_gc_hook
))
5137 int gc_count
= inhibit_garbage_collection ();
5138 safe_run_hooks (Qpost_gc_hook
);
5139 unbind_to (gc_count
, Qnil
);
5142 /* Accumulate statistics. */
5143 EMACS_GET_TIME (t2
);
5144 EMACS_SUB_TIME (t3
, t2
, t1
);
5145 if (FLOATP (Vgc_elapsed
))
5146 Vgc_elapsed
= make_float (XFLOAT_DATA (Vgc_elapsed
) +
5148 EMACS_USECS (t3
) * 1.0e-6);
5151 return Flist (sizeof total
/ sizeof *total
, total
);
5155 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5156 only interesting objects referenced from glyphs are strings. */
5159 mark_glyph_matrix (struct glyph_matrix
*matrix
)
5161 struct glyph_row
*row
= matrix
->rows
;
5162 struct glyph_row
*end
= row
+ matrix
->nrows
;
5164 for (; row
< end
; ++row
)
5168 for (area
= LEFT_MARGIN_AREA
; area
< LAST_AREA
; ++area
)
5170 struct glyph
*glyph
= row
->glyphs
[area
];
5171 struct glyph
*end_glyph
= glyph
+ row
->used
[area
];
5173 for (; glyph
< end_glyph
; ++glyph
)
5174 if (STRINGP (glyph
->object
)
5175 && !STRING_MARKED_P (XSTRING (glyph
->object
)))
5176 mark_object (glyph
->object
);
5182 /* Mark Lisp faces in the face cache C. */
5185 mark_face_cache (struct face_cache
*c
)
5190 for (i
= 0; i
< c
->used
; ++i
)
5192 struct face
*face
= FACE_FROM_ID (c
->f
, i
);
5196 for (j
= 0; j
< LFACE_VECTOR_SIZE
; ++j
)
5197 mark_object (face
->lface
[j
]);
5205 /* Mark reference to a Lisp_Object.
5206 If the object referred to has not been seen yet, recursively mark
5207 all the references contained in it. */
5209 #define LAST_MARKED_SIZE 500
5210 static Lisp_Object last_marked
[LAST_MARKED_SIZE
];
5211 int last_marked_index
;
5213 /* For debugging--call abort when we cdr down this many
5214 links of a list, in mark_object. In debugging,
5215 the call to abort will hit a breakpoint.
5216 Normally this is zero and the check never goes off. */
5217 static int mark_object_loop_halt
;
5220 mark_vectorlike (struct Lisp_Vector
*ptr
)
5222 register EMACS_UINT size
= ptr
->size
;
5223 register EMACS_UINT i
;
5225 eassert (!VECTOR_MARKED_P (ptr
));
5226 VECTOR_MARK (ptr
); /* Else mark it */
5227 if (size
& PSEUDOVECTOR_FLAG
)
5228 size
&= PSEUDOVECTOR_SIZE_MASK
;
5230 /* Note that this size is not the memory-footprint size, but only
5231 the number of Lisp_Object fields that we should trace.
5232 The distinction is used e.g. by Lisp_Process which places extra
5233 non-Lisp_Object fields at the end of the structure. */
5234 for (i
= 0; i
< size
; i
++) /* and then mark its elements */
5235 mark_object (ptr
->contents
[i
]);
5238 /* Like mark_vectorlike but optimized for char-tables (and
5239 sub-char-tables) assuming that the contents are mostly integers or
5243 mark_char_table (struct Lisp_Vector
*ptr
)
5245 register EMACS_UINT size
= ptr
->size
& PSEUDOVECTOR_SIZE_MASK
;
5246 register EMACS_UINT i
;
5248 eassert (!VECTOR_MARKED_P (ptr
));
5250 for (i
= 0; i
< size
; i
++)
5252 Lisp_Object val
= ptr
->contents
[i
];
5254 if (INTEGERP (val
) || (SYMBOLP (val
) && XSYMBOL (val
)->gcmarkbit
))
5256 if (SUB_CHAR_TABLE_P (val
))
5258 if (! VECTOR_MARKED_P (XVECTOR (val
)))
5259 mark_char_table (XVECTOR (val
));
5267 mark_object (Lisp_Object arg
)
5269 register Lisp_Object obj
= arg
;
5270 #ifdef GC_CHECK_MARKED_OBJECTS
5278 if (PURE_POINTER_P (XPNTR (obj
)))
5281 last_marked
[last_marked_index
++] = obj
;
5282 if (last_marked_index
== LAST_MARKED_SIZE
)
5283 last_marked_index
= 0;
5285 /* Perform some sanity checks on the objects marked here. Abort if
5286 we encounter an object we know is bogus. This increases GC time
5287 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
5288 #ifdef GC_CHECK_MARKED_OBJECTS
5290 po
= (void *) XPNTR (obj
);
5292 /* Check that the object pointed to by PO is known to be a Lisp
5293 structure allocated from the heap. */
5294 #define CHECK_ALLOCATED() \
5296 m = mem_find (po); \
5301 /* Check that the object pointed to by PO is live, using predicate
5303 #define CHECK_LIVE(LIVEP) \
5305 if (!LIVEP (m, po)) \
5309 /* Check both of the above conditions. */
5310 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
5312 CHECK_ALLOCATED (); \
5313 CHECK_LIVE (LIVEP); \
5316 #else /* not GC_CHECK_MARKED_OBJECTS */
5318 #define CHECK_LIVE(LIVEP) (void) 0
5319 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
5321 #endif /* not GC_CHECK_MARKED_OBJECTS */
5323 switch (SWITCH_ENUM_CAST (XTYPE (obj
)))
5327 register struct Lisp_String
*ptr
= XSTRING (obj
);
5328 if (STRING_MARKED_P (ptr
))
5330 CHECK_ALLOCATED_AND_LIVE (live_string_p
);
5331 MARK_INTERVAL_TREE (ptr
->intervals
);
5333 #ifdef GC_CHECK_STRING_BYTES
5334 /* Check that the string size recorded in the string is the
5335 same as the one recorded in the sdata structure. */
5336 CHECK_STRING_BYTES (ptr
);
5337 #endif /* GC_CHECK_STRING_BYTES */
5341 case Lisp_Vectorlike
:
5342 if (VECTOR_MARKED_P (XVECTOR (obj
)))
5344 #ifdef GC_CHECK_MARKED_OBJECTS
5346 if (m
== MEM_NIL
&& !SUBRP (obj
)
5347 && po
!= &buffer_defaults
5348 && po
!= &buffer_local_symbols
)
5350 #endif /* GC_CHECK_MARKED_OBJECTS */
5354 #ifdef GC_CHECK_MARKED_OBJECTS
5355 if (po
!= &buffer_defaults
&& po
!= &buffer_local_symbols
)
5358 for (b
= all_buffers
; b
&& b
!= po
; b
= b
->next
)
5363 #endif /* GC_CHECK_MARKED_OBJECTS */
5366 else if (SUBRP (obj
))
5368 else if (COMPILEDP (obj
))
5369 /* We could treat this just like a vector, but it is better to
5370 save the COMPILED_CONSTANTS element for last and avoid
5373 register struct Lisp_Vector
*ptr
= XVECTOR (obj
);
5374 register EMACS_UINT size
= ptr
->size
;
5375 register EMACS_UINT i
;
5377 CHECK_LIVE (live_vector_p
);
5378 VECTOR_MARK (ptr
); /* Else mark it */
5379 size
&= PSEUDOVECTOR_SIZE_MASK
;
5380 for (i
= 0; i
< size
; i
++) /* and then mark its elements */
5382 if (i
!= COMPILED_CONSTANTS
)
5383 mark_object (ptr
->contents
[i
]);
5385 obj
= ptr
->contents
[COMPILED_CONSTANTS
];
5388 else if (FRAMEP (obj
))
5390 register struct frame
*ptr
= XFRAME (obj
);
5391 mark_vectorlike (XVECTOR (obj
));
5392 mark_face_cache (ptr
->face_cache
);
5394 else if (WINDOWP (obj
))
5396 register struct Lisp_Vector
*ptr
= XVECTOR (obj
);
5397 struct window
*w
= XWINDOW (obj
);
5398 mark_vectorlike (ptr
);
5399 /* Mark glyphs for leaf windows. Marking window matrices is
5400 sufficient because frame matrices use the same glyph
5402 if (NILP (w
->hchild
)
5404 && w
->current_matrix
)
5406 mark_glyph_matrix (w
->current_matrix
);
5407 mark_glyph_matrix (w
->desired_matrix
);
5410 else if (HASH_TABLE_P (obj
))
5412 struct Lisp_Hash_Table
*h
= XHASH_TABLE (obj
);
5413 mark_vectorlike ((struct Lisp_Vector
*)h
);
5414 /* If hash table is not weak, mark all keys and values.
5415 For weak tables, mark only the vector. */
5417 mark_object (h
->key_and_value
);
5419 VECTOR_MARK (XVECTOR (h
->key_and_value
));
5421 else if (CHAR_TABLE_P (obj
))
5422 mark_char_table (XVECTOR (obj
));
5424 mark_vectorlike (XVECTOR (obj
));
5429 register struct Lisp_Symbol
*ptr
= XSYMBOL (obj
);
5430 struct Lisp_Symbol
*ptrx
;
5434 CHECK_ALLOCATED_AND_LIVE (live_symbol_p
);
5436 mark_object (ptr
->function
);
5437 mark_object (ptr
->plist
);
5438 switch (ptr
->redirect
)
5440 case SYMBOL_PLAINVAL
: mark_object (SYMBOL_VAL (ptr
)); break;
5441 case SYMBOL_VARALIAS
:
5444 XSETSYMBOL (tem
, SYMBOL_ALIAS (ptr
));
5448 case SYMBOL_LOCALIZED
:
5450 struct Lisp_Buffer_Local_Value
*blv
= SYMBOL_BLV (ptr
);
5451 /* If the value is forwarded to a buffer or keyboard field,
5452 these are marked when we see the corresponding object.
5453 And if it's forwarded to a C variable, either it's not
5454 a Lisp_Object var, or it's staticpro'd already. */
5455 mark_object (blv
->where
);
5456 mark_object (blv
->valcell
);
5457 mark_object (blv
->defcell
);
5460 case SYMBOL_FORWARDED
:
5461 /* If the value is forwarded to a buffer or keyboard field,
5462 these are marked when we see the corresponding object.
5463 And if it's forwarded to a C variable, either it's not
5464 a Lisp_Object var, or it's staticpro'd already. */
5468 if (!PURE_POINTER_P (XSTRING (ptr
->xname
)))
5469 MARK_STRING (XSTRING (ptr
->xname
));
5470 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr
->xname
));
5475 ptrx
= ptr
; /* Use of ptrx avoids compiler bug on Sun */
5476 XSETSYMBOL (obj
, ptrx
);
5483 CHECK_ALLOCATED_AND_LIVE (live_misc_p
);
5484 if (XMISCANY (obj
)->gcmarkbit
)
5486 XMISCANY (obj
)->gcmarkbit
= 1;
5488 switch (XMISCTYPE (obj
))
5491 case Lisp_Misc_Marker
:
5492 /* DO NOT mark thru the marker's chain.
5493 The buffer's markers chain does not preserve markers from gc;
5494 instead, markers are removed from the chain when freed by gc. */
5497 case Lisp_Misc_Save_Value
:
5500 register struct Lisp_Save_Value
*ptr
= XSAVE_VALUE (obj
);
5501 /* If DOGC is set, POINTER is the address of a memory
5502 area containing INTEGER potential Lisp_Objects. */
5505 Lisp_Object
*p
= (Lisp_Object
*) ptr
->pointer
;
5507 for (nelt
= ptr
->integer
; nelt
> 0; nelt
--, p
++)
5508 mark_maybe_object (*p
);
5514 case Lisp_Misc_Overlay
:
5516 struct Lisp_Overlay
*ptr
= XOVERLAY (obj
);
5517 mark_object (ptr
->start
);
5518 mark_object (ptr
->end
);
5519 mark_object (ptr
->plist
);
5522 XSETMISC (obj
, ptr
->next
);
5535 register struct Lisp_Cons
*ptr
= XCONS (obj
);
5536 if (CONS_MARKED_P (ptr
))
5538 CHECK_ALLOCATED_AND_LIVE (live_cons_p
);
5540 /* If the cdr is nil, avoid recursion for the car. */
5541 if (EQ (ptr
->u
.cdr
, Qnil
))
5547 mark_object (ptr
->car
);
5550 if (cdr_count
== mark_object_loop_halt
)
5556 CHECK_ALLOCATED_AND_LIVE (live_float_p
);
5557 FLOAT_MARK (XFLOAT (obj
));
5568 #undef CHECK_ALLOCATED
5569 #undef CHECK_ALLOCATED_AND_LIVE
5572 /* Mark the pointers in a buffer structure. */
5575 mark_buffer (Lisp_Object buf
)
5577 register struct buffer
*buffer
= XBUFFER (buf
);
5578 register Lisp_Object
*ptr
, tmp
;
5579 Lisp_Object base_buffer
;
5581 eassert (!VECTOR_MARKED_P (buffer
));
5582 VECTOR_MARK (buffer
);
5584 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer
));
5586 /* For now, we just don't mark the undo_list. It's done later in
5587 a special way just before the sweep phase, and after stripping
5588 some of its elements that are not needed any more. */
5590 if (buffer
->overlays_before
)
5592 XSETMISC (tmp
, buffer
->overlays_before
);
5595 if (buffer
->overlays_after
)
5597 XSETMISC (tmp
, buffer
->overlays_after
);
5601 /* buffer-local Lisp variables start at `undo_list',
5602 tho only the ones from `name' on are GC'd normally. */
5603 for (ptr
= &buffer
->BUFFER_INTERNAL_FIELD (name
);
5604 (char *)ptr
< (char *)buffer
+ sizeof (struct buffer
);
5608 /* If this is an indirect buffer, mark its base buffer. */
5609 if (buffer
->base_buffer
&& !VECTOR_MARKED_P (buffer
->base_buffer
))
5611 XSETBUFFER (base_buffer
, buffer
->base_buffer
);
5612 mark_buffer (base_buffer
);
5616 /* Mark the Lisp pointers in the terminal objects.
5617 Called by the Fgarbage_collector. */
5620 mark_terminals (void)
5623 for (t
= terminal_list
; t
; t
= t
->next_terminal
)
5625 eassert (t
->name
!= NULL
);
5626 #ifdef HAVE_WINDOW_SYSTEM
5627 /* If a terminal object is reachable from a stacpro'ed object,
5628 it might have been marked already. Make sure the image cache
5630 mark_image_cache (t
->image_cache
);
5631 #endif /* HAVE_WINDOW_SYSTEM */
5632 if (!VECTOR_MARKED_P (t
))
5633 mark_vectorlike ((struct Lisp_Vector
*)t
);
5639 /* Value is non-zero if OBJ will survive the current GC because it's
5640 either marked or does not need to be marked to survive. */
5643 survives_gc_p (Lisp_Object obj
)
5647 switch (XTYPE (obj
))
5654 survives_p
= XSYMBOL (obj
)->gcmarkbit
;
5658 survives_p
= XMISCANY (obj
)->gcmarkbit
;
5662 survives_p
= STRING_MARKED_P (XSTRING (obj
));
5665 case Lisp_Vectorlike
:
5666 survives_p
= SUBRP (obj
) || VECTOR_MARKED_P (XVECTOR (obj
));
5670 survives_p
= CONS_MARKED_P (XCONS (obj
));
5674 survives_p
= FLOAT_MARKED_P (XFLOAT (obj
));
5681 return survives_p
|| PURE_POINTER_P ((void *) XPNTR (obj
));
5686 /* Sweep: find all structures not marked, and free them. */
5691 /* Remove or mark entries in weak hash tables.
5692 This must be done before any object is unmarked. */
5693 sweep_weak_hash_tables ();
5696 #ifdef GC_CHECK_STRING_BYTES
5697 if (!noninteractive
)
5698 check_string_bytes (1);
5701 /* Put all unmarked conses on free list */
5703 register struct cons_block
*cblk
;
5704 struct cons_block
**cprev
= &cons_block
;
5705 register int lim
= cons_block_index
;
5706 register int num_free
= 0, num_used
= 0;
5710 for (cblk
= cons_block
; cblk
; cblk
= *cprev
)
5714 int ilim
= (lim
+ BITS_PER_INT
- 1) / BITS_PER_INT
;
5716 /* Scan the mark bits an int at a time. */
5717 for (i
= 0; i
<= ilim
; i
++)
5719 if (cblk
->gcmarkbits
[i
] == -1)
5721 /* Fast path - all cons cells for this int are marked. */
5722 cblk
->gcmarkbits
[i
] = 0;
5723 num_used
+= BITS_PER_INT
;
5727 /* Some cons cells for this int are not marked.
5728 Find which ones, and free them. */
5729 int start
, pos
, stop
;
5731 start
= i
* BITS_PER_INT
;
5733 if (stop
> BITS_PER_INT
)
5734 stop
= BITS_PER_INT
;
5737 for (pos
= start
; pos
< stop
; pos
++)
5739 if (!CONS_MARKED_P (&cblk
->conses
[pos
]))
5742 cblk
->conses
[pos
].u
.chain
= cons_free_list
;
5743 cons_free_list
= &cblk
->conses
[pos
];
5745 cons_free_list
->car
= Vdead
;
5751 CONS_UNMARK (&cblk
->conses
[pos
]);
5757 lim
= CONS_BLOCK_SIZE
;
5758 /* If this block contains only free conses and we have already
5759 seen more than two blocks worth of free conses then deallocate
5761 if (this_free
== CONS_BLOCK_SIZE
&& num_free
> CONS_BLOCK_SIZE
)
5763 *cprev
= cblk
->next
;
5764 /* Unhook from the free list. */
5765 cons_free_list
= cblk
->conses
[0].u
.chain
;
5766 lisp_align_free (cblk
);
5771 num_free
+= this_free
;
5772 cprev
= &cblk
->next
;
5775 total_conses
= num_used
;
5776 total_free_conses
= num_free
;
5779 /* Put all unmarked floats on free list */
5781 register struct float_block
*fblk
;
5782 struct float_block
**fprev
= &float_block
;
5783 register int lim
= float_block_index
;
5784 register int num_free
= 0, num_used
= 0;
5786 float_free_list
= 0;
5788 for (fblk
= float_block
; fblk
; fblk
= *fprev
)
5792 for (i
= 0; i
< lim
; i
++)
5793 if (!FLOAT_MARKED_P (&fblk
->floats
[i
]))
5796 fblk
->floats
[i
].u
.chain
= float_free_list
;
5797 float_free_list
= &fblk
->floats
[i
];
5802 FLOAT_UNMARK (&fblk
->floats
[i
]);
5804 lim
= FLOAT_BLOCK_SIZE
;
5805 /* If this block contains only free floats and we have already
5806 seen more than two blocks worth of free floats then deallocate
5808 if (this_free
== FLOAT_BLOCK_SIZE
&& num_free
> FLOAT_BLOCK_SIZE
)
5810 *fprev
= fblk
->next
;
5811 /* Unhook from the free list. */
5812 float_free_list
= fblk
->floats
[0].u
.chain
;
5813 lisp_align_free (fblk
);
5818 num_free
+= this_free
;
5819 fprev
= &fblk
->next
;
5822 total_floats
= num_used
;
5823 total_free_floats
= num_free
;
5826 /* Put all unmarked intervals on free list */
5828 register struct interval_block
*iblk
;
5829 struct interval_block
**iprev
= &interval_block
;
5830 register int lim
= interval_block_index
;
5831 register int num_free
= 0, num_used
= 0;
5833 interval_free_list
= 0;
5835 for (iblk
= interval_block
; iblk
; iblk
= *iprev
)
5840 for (i
= 0; i
< lim
; i
++)
5842 if (!iblk
->intervals
[i
].gcmarkbit
)
5844 SET_INTERVAL_PARENT (&iblk
->intervals
[i
], interval_free_list
);
5845 interval_free_list
= &iblk
->intervals
[i
];
5851 iblk
->intervals
[i
].gcmarkbit
= 0;
5854 lim
= INTERVAL_BLOCK_SIZE
;
5855 /* If this block contains only free intervals and we have already
5856 seen more than two blocks worth of free intervals then
5857 deallocate this block. */
5858 if (this_free
== INTERVAL_BLOCK_SIZE
&& num_free
> INTERVAL_BLOCK_SIZE
)
5860 *iprev
= iblk
->next
;
5861 /* Unhook from the free list. */
5862 interval_free_list
= INTERVAL_PARENT (&iblk
->intervals
[0]);
5864 n_interval_blocks
--;
5868 num_free
+= this_free
;
5869 iprev
= &iblk
->next
;
5872 total_intervals
= num_used
;
5873 total_free_intervals
= num_free
;
5876 /* Put all unmarked symbols on free list */
5878 register struct symbol_block
*sblk
;
5879 struct symbol_block
**sprev
= &symbol_block
;
5880 register int lim
= symbol_block_index
;
5881 register int num_free
= 0, num_used
= 0;
5883 symbol_free_list
= NULL
;
5885 for (sblk
= symbol_block
; sblk
; sblk
= *sprev
)
5888 struct Lisp_Symbol
*sym
= sblk
->symbols
;
5889 struct Lisp_Symbol
*end
= sym
+ lim
;
5891 for (; sym
< end
; ++sym
)
5893 /* Check if the symbol was created during loadup. In such a case
5894 it might be pointed to by pure bytecode which we don't trace,
5895 so we conservatively assume that it is live. */
5896 int pure_p
= PURE_POINTER_P (XSTRING (sym
->xname
));
5898 if (!sym
->gcmarkbit
&& !pure_p
)
5900 if (sym
->redirect
== SYMBOL_LOCALIZED
)
5901 xfree (SYMBOL_BLV (sym
));
5902 sym
->next
= symbol_free_list
;
5903 symbol_free_list
= sym
;
5905 symbol_free_list
->function
= Vdead
;
5913 UNMARK_STRING (XSTRING (sym
->xname
));
5918 lim
= SYMBOL_BLOCK_SIZE
;
5919 /* If this block contains only free symbols and we have already
5920 seen more than two blocks worth of free symbols then deallocate
5922 if (this_free
== SYMBOL_BLOCK_SIZE
&& num_free
> SYMBOL_BLOCK_SIZE
)
5924 *sprev
= sblk
->next
;
5925 /* Unhook from the free list. */
5926 symbol_free_list
= sblk
->symbols
[0].next
;
5932 num_free
+= this_free
;
5933 sprev
= &sblk
->next
;
5936 total_symbols
= num_used
;
5937 total_free_symbols
= num_free
;
5940 /* Put all unmarked misc's on free list.
5941 For a marker, first unchain it from the buffer it points into. */
5943 register struct marker_block
*mblk
;
5944 struct marker_block
**mprev
= &marker_block
;
5945 register int lim
= marker_block_index
;
5946 register int num_free
= 0, num_used
= 0;
5948 marker_free_list
= 0;
5950 for (mblk
= marker_block
; mblk
; mblk
= *mprev
)
5955 for (i
= 0; i
< lim
; i
++)
5957 if (!mblk
->markers
[i
].u_any
.gcmarkbit
)
5959 if (mblk
->markers
[i
].u_any
.type
== Lisp_Misc_Marker
)
5960 unchain_marker (&mblk
->markers
[i
].u_marker
);
5961 /* Set the type of the freed object to Lisp_Misc_Free.
5962 We could leave the type alone, since nobody checks it,
5963 but this might catch bugs faster. */
5964 mblk
->markers
[i
].u_marker
.type
= Lisp_Misc_Free
;
5965 mblk
->markers
[i
].u_free
.chain
= marker_free_list
;
5966 marker_free_list
= &mblk
->markers
[i
];
5972 mblk
->markers
[i
].u_any
.gcmarkbit
= 0;
5975 lim
= MARKER_BLOCK_SIZE
;
5976 /* If this block contains only free markers and we have already
5977 seen more than two blocks worth of free markers then deallocate
5979 if (this_free
== MARKER_BLOCK_SIZE
&& num_free
> MARKER_BLOCK_SIZE
)
5981 *mprev
= mblk
->next
;
5982 /* Unhook from the free list. */
5983 marker_free_list
= mblk
->markers
[0].u_free
.chain
;
5989 num_free
+= this_free
;
5990 mprev
= &mblk
->next
;
5994 total_markers
= num_used
;
5995 total_free_markers
= num_free
;
5998 /* Free all unmarked buffers */
6000 register struct buffer
*buffer
= all_buffers
, *prev
= 0, *next
;
6003 if (!VECTOR_MARKED_P (buffer
))
6006 prev
->next
= buffer
->next
;
6008 all_buffers
= buffer
->next
;
6009 next
= buffer
->next
;
6015 VECTOR_UNMARK (buffer
);
6016 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer
));
6017 prev
= buffer
, buffer
= buffer
->next
;
6021 /* Free all unmarked vectors */
6023 register struct Lisp_Vector
*vector
= all_vectors
, *prev
= 0, *next
;
6024 total_vector_size
= 0;
6027 if (!VECTOR_MARKED_P (vector
))
6030 prev
->next
= vector
->next
;
6032 all_vectors
= vector
->next
;
6033 next
= vector
->next
;
6041 VECTOR_UNMARK (vector
);
6042 if (vector
->size
& PSEUDOVECTOR_FLAG
)
6043 total_vector_size
+= (PSEUDOVECTOR_SIZE_MASK
& vector
->size
);
6045 total_vector_size
+= vector
->size
;
6046 prev
= vector
, vector
= vector
->next
;
6050 #ifdef GC_CHECK_STRING_BYTES
6051 if (!noninteractive
)
6052 check_string_bytes (1);
6059 /* Debugging aids. */
6061 DEFUN ("memory-limit", Fmemory_limit
, Smemory_limit
, 0, 0, 0,
6062 doc
: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6063 This may be helpful in debugging Emacs's memory usage.
6064 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6069 XSETINT (end
, (EMACS_INT
) (char *) sbrk (0) / 1024);
6074 DEFUN ("memory-use-counts", Fmemory_use_counts
, Smemory_use_counts
, 0, 0, 0,
6075 doc
: /* Return a list of counters that measure how much consing there has been.
6076 Each of these counters increments for a certain kind of object.
6077 The counters wrap around from the largest positive integer to zero.
6078 Garbage collection does not decrease them.
6079 The elements of the value are as follows:
6080 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6081 All are in units of 1 = one object consed
6082 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6084 MISCS include overlays, markers, and some internal types.
6085 Frames, windows, buffers, and subprocesses count as vectors
6086 (but the contents of a buffer's text do not count here). */)
6089 Lisp_Object consed
[8];
6091 consed
[0] = make_number (min (MOST_POSITIVE_FIXNUM
, cons_cells_consed
));
6092 consed
[1] = make_number (min (MOST_POSITIVE_FIXNUM
, floats_consed
));
6093 consed
[2] = make_number (min (MOST_POSITIVE_FIXNUM
, vector_cells_consed
));
6094 consed
[3] = make_number (min (MOST_POSITIVE_FIXNUM
, symbols_consed
));
6095 consed
[4] = make_number (min (MOST_POSITIVE_FIXNUM
, string_chars_consed
));
6096 consed
[5] = make_number (min (MOST_POSITIVE_FIXNUM
, misc_objects_consed
));
6097 consed
[6] = make_number (min (MOST_POSITIVE_FIXNUM
, intervals_consed
));
6098 consed
[7] = make_number (min (MOST_POSITIVE_FIXNUM
, strings_consed
));
6100 return Flist (8, consed
);
6103 int suppress_checking
;
6106 die (const char *msg
, const char *file
, int line
)
6108 fprintf (stderr
, "\r\n%s:%d: Emacs fatal error: %s\r\n",
6113 /* Initialization */
6116 init_alloc_once (void)
6118 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
6120 pure_size
= PURESIZE
;
6121 pure_bytes_used
= 0;
6122 pure_bytes_used_lisp
= pure_bytes_used_non_lisp
= 0;
6123 pure_bytes_used_before_overflow
= 0;
6125 /* Initialize the list of free aligned blocks. */
6128 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
6130 Vdead
= make_pure_string ("DEAD", 4, 4, 0);
6134 ignore_warnings
= 1;
6135 #ifdef DOUG_LEA_MALLOC
6136 mallopt (M_TRIM_THRESHOLD
, 128*1024); /* trim threshold */
6137 mallopt (M_MMAP_THRESHOLD
, 64*1024); /* mmap threshold */
6138 mallopt (M_MMAP_MAX
, MMAP_MAX_AREAS
); /* max. number of mmap'ed areas */
6146 init_weak_hash_tables ();
6149 malloc_hysteresis
= 32;
6151 malloc_hysteresis
= 0;
6154 refill_memory_reserve ();
6156 ignore_warnings
= 0;
6158 byte_stack_list
= 0;
6160 consing_since_gc
= 0;
6161 gc_cons_threshold
= 100000 * sizeof (Lisp_Object
);
6162 gc_relative_threshold
= 0;
6169 byte_stack_list
= 0;
6171 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
6172 setjmp_tested_p
= longjmps_done
= 0;
6175 Vgc_elapsed
= make_float (0.0);
6180 syms_of_alloc (void)
6182 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold
,
6183 doc
: /* *Number of bytes of consing between garbage collections.
6184 Garbage collection can happen automatically once this many bytes have been
6185 allocated since the last garbage collection. All data types count.
6187 Garbage collection happens automatically only when `eval' is called.
6189 By binding this temporarily to a large number, you can effectively
6190 prevent garbage collection during a part of the program.
6191 See also `gc-cons-percentage'. */);
6193 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage
,
6194 doc
: /* *Portion of the heap used for allocation.
6195 Garbage collection can happen automatically once this portion of the heap
6196 has been allocated since the last garbage collection.
6197 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
6198 Vgc_cons_percentage
= make_float (0.1);
6200 DEFVAR_INT ("pure-bytes-used", pure_bytes_used
,
6201 doc
: /* Number of bytes of sharable Lisp data allocated so far. */);
6203 DEFVAR_INT ("cons-cells-consed", cons_cells_consed
,
6204 doc
: /* Number of cons cells that have been consed so far. */);
6206 DEFVAR_INT ("floats-consed", floats_consed
,
6207 doc
: /* Number of floats that have been consed so far. */);
6209 DEFVAR_INT ("vector-cells-consed", vector_cells_consed
,
6210 doc
: /* Number of vector cells that have been consed so far. */);
6212 DEFVAR_INT ("symbols-consed", symbols_consed
,
6213 doc
: /* Number of symbols that have been consed so far. */);
6215 DEFVAR_INT ("string-chars-consed", string_chars_consed
,
6216 doc
: /* Number of string characters that have been consed so far. */);
6218 DEFVAR_INT ("misc-objects-consed", misc_objects_consed
,
6219 doc
: /* Number of miscellaneous objects that have been consed so far. */);
6221 DEFVAR_INT ("intervals-consed", intervals_consed
,
6222 doc
: /* Number of intervals that have been consed so far. */);
6224 DEFVAR_INT ("strings-consed", strings_consed
,
6225 doc
: /* Number of strings that have been consed so far. */);
6227 DEFVAR_LISP ("purify-flag", Vpurify_flag
,
6228 doc
: /* Non-nil means loading Lisp code in order to dump an executable.
6229 This means that certain objects should be allocated in shared (pure) space.
6230 It can also be set to a hash-table, in which case this table is used to
6231 do hash-consing of the objects allocated to pure space. */);
6233 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages
,
6234 doc
: /* Non-nil means display messages at start and end of garbage collection. */);
6235 garbage_collection_messages
= 0;
6237 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook
,
6238 doc
: /* Hook run after garbage collection has finished. */);
6239 Vpost_gc_hook
= Qnil
;
6240 Qpost_gc_hook
= intern_c_string ("post-gc-hook");
6241 staticpro (&Qpost_gc_hook
);
6243 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data
,
6244 doc
: /* Precomputed `signal' argument for memory-full error. */);
6245 /* We build this in advance because if we wait until we need it, we might
6246 not be able to allocate the memory to hold it. */
6248 = pure_cons (Qerror
,
6249 pure_cons (make_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"), Qnil
));
6251 DEFVAR_LISP ("memory-full", Vmemory_full
,
6252 doc
: /* Non-nil means Emacs cannot get much more Lisp memory. */);
6253 Vmemory_full
= Qnil
;
6255 staticpro (&Qgc_cons_threshold
);
6256 Qgc_cons_threshold
= intern_c_string ("gc-cons-threshold");
6258 staticpro (&Qchar_table_extra_slots
);
6259 Qchar_table_extra_slots
= intern_c_string ("char-table-extra-slots");
6261 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed
,
6262 doc
: /* Accumulated time elapsed in garbage collections.
6263 The time is in seconds as a floating point value. */);
6264 DEFVAR_INT ("gcs-done", gcs_done
,
6265 doc
: /* Accumulated number of garbage collections done. */);
6270 defsubr (&Smake_byte_code
);
6271 defsubr (&Smake_list
);
6272 defsubr (&Smake_vector
);
6273 defsubr (&Smake_string
);
6274 defsubr (&Smake_bool_vector
);
6275 defsubr (&Smake_symbol
);
6276 defsubr (&Smake_marker
);
6277 defsubr (&Spurecopy
);
6278 defsubr (&Sgarbage_collect
);
6279 defsubr (&Smemory_limit
);
6280 defsubr (&Smemory_use_counts
);
6282 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
6283 defsubr (&Sgc_status
);