Try to use "gpg2" if "gpg" isn't available.
[emacs.git] / src / alloc.c
blobfa39c1ee5dcba16d3777bb6cf4ef953ac5ecae11
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
2 Copyright (C) 1985, 1986, 1988, 1993, 1994, 1995, 1997, 1998, 1999,
3 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
22 #include <stdio.h>
23 #include <limits.h> /* For CHAR_BIT. */
24 #include <setjmp.h>
26 #ifdef ALLOC_DEBUG
27 #undef INLINE
28 #endif
30 #include <signal.h>
32 #ifdef HAVE_GTK_AND_PTHREAD
33 #include <pthread.h>
34 #endif
36 /* This file is part of the core Lisp implementation, and thus must
37 deal with the real data structures. If the Lisp implementation is
38 replaced, this file likely will not be used. */
40 #undef HIDE_LISP_IMPLEMENTATION
41 #include "lisp.h"
42 #include "process.h"
43 #include "intervals.h"
44 #include "puresize.h"
45 #include "buffer.h"
46 #include "window.h"
47 #include "keyboard.h"
48 #include "frame.h"
49 #include "blockinput.h"
50 #include "character.h"
51 #include "syssignal.h"
52 #include "termhooks.h" /* For struct terminal. */
53 #include <setjmp.h>
55 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
56 memory. Can do this only if using gmalloc.c. */
58 #if defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC
59 #undef GC_MALLOC_CHECK
60 #endif
62 #ifdef HAVE_UNISTD_H
63 #include <unistd.h>
64 #else
65 extern POINTER_TYPE *sbrk ();
66 #endif
68 #include <fcntl.h>
70 #ifdef WINDOWSNT
71 #include "w32.h"
72 #endif
74 #ifdef DOUG_LEA_MALLOC
76 #include <malloc.h>
77 /* malloc.h #defines this as size_t, at least in glibc2. */
78 #ifndef __malloc_size_t
79 #define __malloc_size_t int
80 #endif
82 /* Specify maximum number of areas to mmap. It would be nice to use a
83 value that explicitly means "no limit". */
85 #define MMAP_MAX_AREAS 100000000
87 #else /* not DOUG_LEA_MALLOC */
89 /* The following come from gmalloc.c. */
91 #define __malloc_size_t size_t
92 extern __malloc_size_t _bytes_used;
93 extern __malloc_size_t __malloc_extra_blocks;
95 #endif /* not DOUG_LEA_MALLOC */
97 #if ! defined (SYSTEM_MALLOC) && defined (HAVE_GTK_AND_PTHREAD)
99 /* When GTK uses the file chooser dialog, different backends can be loaded
100 dynamically. One such a backend is the Gnome VFS backend that gets loaded
101 if you run Gnome. That backend creates several threads and also allocates
102 memory with malloc.
104 If Emacs sets malloc hooks (! SYSTEM_MALLOC) and the emacs_blocked_*
105 functions below are called from malloc, there is a chance that one
106 of these threads preempts the Emacs main thread and the hook variables
107 end up in an inconsistent state. So we have a mutex to prevent that (note
108 that the backend handles concurrent access to malloc within its own threads
109 but Emacs code running in the main thread is not included in that control).
111 When UNBLOCK_INPUT is called, reinvoke_input_signal may be called. If this
112 happens in one of the backend threads we will have two threads that tries
113 to run Emacs code at once, and the code is not prepared for that.
114 To prevent that, we only call BLOCK/UNBLOCK from the main thread. */
116 static pthread_mutex_t alloc_mutex;
118 #define BLOCK_INPUT_ALLOC \
119 do \
121 if (pthread_equal (pthread_self (), main_thread)) \
122 BLOCK_INPUT; \
123 pthread_mutex_lock (&alloc_mutex); \
125 while (0)
126 #define UNBLOCK_INPUT_ALLOC \
127 do \
129 pthread_mutex_unlock (&alloc_mutex); \
130 if (pthread_equal (pthread_self (), main_thread)) \
131 UNBLOCK_INPUT; \
133 while (0)
135 #else /* SYSTEM_MALLOC || not HAVE_GTK_AND_PTHREAD */
137 #define BLOCK_INPUT_ALLOC BLOCK_INPUT
138 #define UNBLOCK_INPUT_ALLOC UNBLOCK_INPUT
140 #endif /* SYSTEM_MALLOC || not HAVE_GTK_AND_PTHREAD */
142 /* Value of _bytes_used, when spare_memory was freed. */
144 static __malloc_size_t bytes_used_when_full;
146 static __malloc_size_t bytes_used_when_reconsidered;
148 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
149 to a struct Lisp_String. */
151 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
152 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
153 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
155 #define VECTOR_MARK(V) ((V)->size |= ARRAY_MARK_FLAG)
156 #define VECTOR_UNMARK(V) ((V)->size &= ~ARRAY_MARK_FLAG)
157 #define VECTOR_MARKED_P(V) (((V)->size & ARRAY_MARK_FLAG) != 0)
159 /* Value is the number of bytes/chars of S, a pointer to a struct
160 Lisp_String. This must be used instead of STRING_BYTES (S) or
161 S->size during GC, because S->size contains the mark bit for
162 strings. */
164 #define GC_STRING_BYTES(S) (STRING_BYTES (S))
165 #define GC_STRING_CHARS(S) ((S)->size & ~ARRAY_MARK_FLAG)
167 /* Number of bytes of consing done since the last gc. */
169 int consing_since_gc;
171 /* Count the amount of consing of various sorts of space. */
173 EMACS_INT cons_cells_consed;
174 EMACS_INT floats_consed;
175 EMACS_INT vector_cells_consed;
176 EMACS_INT symbols_consed;
177 EMACS_INT string_chars_consed;
178 EMACS_INT misc_objects_consed;
179 EMACS_INT intervals_consed;
180 EMACS_INT strings_consed;
182 /* Minimum number of bytes of consing since GC before next GC. */
184 EMACS_INT gc_cons_threshold;
186 /* Similar minimum, computed from Vgc_cons_percentage. */
188 EMACS_INT gc_relative_threshold;
190 static Lisp_Object Vgc_cons_percentage;
192 /* Minimum number of bytes of consing since GC before next GC,
193 when memory is full. */
195 EMACS_INT memory_full_cons_threshold;
197 /* Nonzero during GC. */
199 int gc_in_progress;
201 /* Nonzero means abort if try to GC.
202 This is for code which is written on the assumption that
203 no GC will happen, so as to verify that assumption. */
205 int abort_on_gc;
207 /* Nonzero means display messages at beginning and end of GC. */
209 int garbage_collection_messages;
211 /* Number of live and free conses etc. */
213 static int total_conses, total_markers, total_symbols, total_vector_size;
214 static int total_free_conses, total_free_markers, total_free_symbols;
215 static int total_free_floats, total_floats;
217 /* Points to memory space allocated as "spare", to be freed if we run
218 out of memory. We keep one large block, four cons-blocks, and
219 two string blocks. */
221 static char *spare_memory[7];
223 /* Amount of spare memory to keep in large reserve block. */
225 #define SPARE_MEMORY (1 << 14)
227 /* Number of extra blocks malloc should get when it needs more core. */
229 static int malloc_hysteresis;
231 /* Non-nil means defun should do purecopy on the function definition. */
233 Lisp_Object Vpurify_flag;
235 /* Non-nil means we are handling a memory-full error. */
237 Lisp_Object Vmemory_full;
239 /* Initialize it to a nonzero value to force it into data space
240 (rather than bss space). That way unexec will remap it into text
241 space (pure), on some systems. We have not implemented the
242 remapping on more recent systems because this is less important
243 nowadays than in the days of small memories and timesharing. */
245 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
246 #define PUREBEG (char *) pure
248 /* Pointer to the pure area, and its size. */
250 static char *purebeg;
251 static size_t pure_size;
253 /* Number of bytes of pure storage used before pure storage overflowed.
254 If this is non-zero, this implies that an overflow occurred. */
256 static size_t pure_bytes_used_before_overflow;
258 /* Value is non-zero if P points into pure space. */
260 #define PURE_POINTER_P(P) \
261 (((PNTR_COMPARISON_TYPE) (P) \
262 < (PNTR_COMPARISON_TYPE) ((char *) purebeg + pure_size)) \
263 && ((PNTR_COMPARISON_TYPE) (P) \
264 >= (PNTR_COMPARISON_TYPE) purebeg))
266 /* Total number of bytes allocated in pure storage. */
268 EMACS_INT pure_bytes_used;
270 /* Index in pure at which next pure Lisp object will be allocated.. */
272 static EMACS_INT pure_bytes_used_lisp;
274 /* Number of bytes allocated for non-Lisp objects in pure storage. */
276 static EMACS_INT pure_bytes_used_non_lisp;
278 /* If nonzero, this is a warning delivered by malloc and not yet
279 displayed. */
281 const char *pending_malloc_warning;
283 /* Pre-computed signal argument for use when memory is exhausted. */
285 Lisp_Object Vmemory_signal_data;
287 /* Maximum amount of C stack to save when a GC happens. */
289 #ifndef MAX_SAVE_STACK
290 #define MAX_SAVE_STACK 16000
291 #endif
293 /* Buffer in which we save a copy of the C stack at each GC. */
295 static char *stack_copy;
296 static int stack_copy_size;
298 /* Non-zero means ignore malloc warnings. Set during initialization.
299 Currently not used. */
301 static int ignore_warnings;
303 Lisp_Object Qgc_cons_threshold, Qchar_table_extra_slots;
305 /* Hook run after GC has finished. */
307 Lisp_Object Vpost_gc_hook, Qpost_gc_hook;
309 Lisp_Object Vgc_elapsed; /* accumulated elapsed time in GC */
310 EMACS_INT gcs_done; /* accumulated GCs */
312 static void mark_buffer (Lisp_Object);
313 static void mark_terminals (void);
314 extern void mark_kboards (void);
315 extern void mark_ttys (void);
316 extern void mark_backtrace (void);
317 static void gc_sweep (void);
318 static void mark_glyph_matrix (struct glyph_matrix *);
319 static void mark_face_cache (struct face_cache *);
321 #ifdef HAVE_WINDOW_SYSTEM
322 extern void mark_fringe_data (void);
323 #endif /* HAVE_WINDOW_SYSTEM */
325 static struct Lisp_String *allocate_string (void);
326 static void compact_small_strings (void);
327 static void free_large_strings (void);
328 static void sweep_strings (void);
330 extern int message_enable_multibyte;
332 /* When scanning the C stack for live Lisp objects, Emacs keeps track
333 of what memory allocated via lisp_malloc is intended for what
334 purpose. This enumeration specifies the type of memory. */
336 enum mem_type
338 MEM_TYPE_NON_LISP,
339 MEM_TYPE_BUFFER,
340 MEM_TYPE_CONS,
341 MEM_TYPE_STRING,
342 MEM_TYPE_MISC,
343 MEM_TYPE_SYMBOL,
344 MEM_TYPE_FLOAT,
345 /* We used to keep separate mem_types for subtypes of vectors such as
346 process, hash_table, frame, terminal, and window, but we never made
347 use of the distinction, so it only caused source-code complexity
348 and runtime slowdown. Minor but pointless. */
349 MEM_TYPE_VECTORLIKE
352 static POINTER_TYPE *lisp_align_malloc (size_t, enum mem_type);
353 static POINTER_TYPE *lisp_malloc (size_t, enum mem_type);
354 void refill_memory_reserve (void);
357 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
359 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
360 #include <stdio.h> /* For fprintf. */
361 #endif
363 /* A unique object in pure space used to make some Lisp objects
364 on free lists recognizable in O(1). */
366 static Lisp_Object Vdead;
368 #ifdef GC_MALLOC_CHECK
370 enum mem_type allocated_mem_type;
371 static int dont_register_blocks;
373 #endif /* GC_MALLOC_CHECK */
375 /* A node in the red-black tree describing allocated memory containing
376 Lisp data. Each such block is recorded with its start and end
377 address when it is allocated, and removed from the tree when it
378 is freed.
380 A red-black tree is a balanced binary tree with the following
381 properties:
383 1. Every node is either red or black.
384 2. Every leaf is black.
385 3. If a node is red, then both of its children are black.
386 4. Every simple path from a node to a descendant leaf contains
387 the same number of black nodes.
388 5. The root is always black.
390 When nodes are inserted into the tree, or deleted from the tree,
391 the tree is "fixed" so that these properties are always true.
393 A red-black tree with N internal nodes has height at most 2
394 log(N+1). Searches, insertions and deletions are done in O(log N).
395 Please see a text book about data structures for a detailed
396 description of red-black trees. Any book worth its salt should
397 describe them. */
399 struct mem_node
401 /* Children of this node. These pointers are never NULL. When there
402 is no child, the value is MEM_NIL, which points to a dummy node. */
403 struct mem_node *left, *right;
405 /* The parent of this node. In the root node, this is NULL. */
406 struct mem_node *parent;
408 /* Start and end of allocated region. */
409 void *start, *end;
411 /* Node color. */
412 enum {MEM_BLACK, MEM_RED} color;
414 /* Memory type. */
415 enum mem_type type;
418 /* Base address of stack. Set in main. */
420 Lisp_Object *stack_base;
422 /* Root of the tree describing allocated Lisp memory. */
424 static struct mem_node *mem_root;
426 /* Lowest and highest known address in the heap. */
428 static void *min_heap_address, *max_heap_address;
430 /* Sentinel node of the tree. */
432 static struct mem_node mem_z;
433 #define MEM_NIL &mem_z
435 static struct Lisp_Vector *allocate_vectorlike (EMACS_INT);
436 static void lisp_free (POINTER_TYPE *);
437 static void mark_stack (void);
438 static int live_vector_p (struct mem_node *, void *);
439 static int live_buffer_p (struct mem_node *, void *);
440 static int live_string_p (struct mem_node *, void *);
441 static int live_cons_p (struct mem_node *, void *);
442 static int live_symbol_p (struct mem_node *, void *);
443 static int live_float_p (struct mem_node *, void *);
444 static int live_misc_p (struct mem_node *, void *);
445 static void mark_maybe_object (Lisp_Object);
446 static void mark_memory (void *, void *, int);
447 static void mem_init (void);
448 static struct mem_node *mem_insert (void *, void *, enum mem_type);
449 static void mem_insert_fixup (struct mem_node *);
450 static void mem_rotate_left (struct mem_node *);
451 static void mem_rotate_right (struct mem_node *);
452 static void mem_delete (struct mem_node *);
453 static void mem_delete_fixup (struct mem_node *);
454 static INLINE struct mem_node *mem_find (void *);
457 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
458 static void check_gcpros (void);
459 #endif
461 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
463 /* Recording what needs to be marked for gc. */
465 struct gcpro *gcprolist;
467 /* Addresses of staticpro'd variables. Initialize it to a nonzero
468 value; otherwise some compilers put it into BSS. */
470 #define NSTATICS 0x640
471 static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
473 /* Index of next unused slot in staticvec. */
475 static int staticidx = 0;
477 static POINTER_TYPE *pure_alloc (size_t, int);
480 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
481 ALIGNMENT must be a power of 2. */
483 #define ALIGN(ptr, ALIGNMENT) \
484 ((POINTER_TYPE *) ((((EMACS_UINT)(ptr)) + (ALIGNMENT) - 1) \
485 & ~((ALIGNMENT) - 1)))
489 /************************************************************************
490 Malloc
491 ************************************************************************/
493 /* Function malloc calls this if it finds we are near exhausting storage. */
495 void
496 malloc_warning (const char *str)
498 pending_malloc_warning = str;
502 /* Display an already-pending malloc warning. */
504 void
505 display_malloc_warning (void)
507 call3 (intern ("display-warning"),
508 intern ("alloc"),
509 build_string (pending_malloc_warning),
510 intern ("emergency"));
511 pending_malloc_warning = 0;
515 #ifdef DOUG_LEA_MALLOC
516 # define BYTES_USED (mallinfo ().uordblks)
517 #else
518 # define BYTES_USED _bytes_used
519 #endif
521 /* Called if we can't allocate relocatable space for a buffer. */
523 void
524 buffer_memory_full (void)
526 /* If buffers use the relocating allocator, no need to free
527 spare_memory, because we may have plenty of malloc space left
528 that we could get, and if we don't, the malloc that fails will
529 itself cause spare_memory to be freed. If buffers don't use the
530 relocating allocator, treat this like any other failing
531 malloc. */
533 #ifndef REL_ALLOC
534 memory_full ();
535 #endif
537 /* This used to call error, but if we've run out of memory, we could
538 get infinite recursion trying to build the string. */
539 xsignal (Qnil, Vmemory_signal_data);
543 #ifdef XMALLOC_OVERRUN_CHECK
545 /* Check for overrun in malloc'ed buffers by wrapping a 16 byte header
546 and a 16 byte trailer around each block.
548 The header consists of 12 fixed bytes + a 4 byte integer contaning the
549 original block size, while the trailer consists of 16 fixed bytes.
551 The header is used to detect whether this block has been allocated
552 through these functions -- as it seems that some low-level libc
553 functions may bypass the malloc hooks.
557 #define XMALLOC_OVERRUN_CHECK_SIZE 16
559 static char xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE-4] =
560 { 0x9a, 0x9b, 0xae, 0xaf,
561 0xbf, 0xbe, 0xce, 0xcf,
562 0xea, 0xeb, 0xec, 0xed };
564 static char xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
565 { 0xaa, 0xab, 0xac, 0xad,
566 0xba, 0xbb, 0xbc, 0xbd,
567 0xca, 0xcb, 0xcc, 0xcd,
568 0xda, 0xdb, 0xdc, 0xdd };
570 /* Macros to insert and extract the block size in the header. */
572 #define XMALLOC_PUT_SIZE(ptr, size) \
573 (ptr[-1] = (size & 0xff), \
574 ptr[-2] = ((size >> 8) & 0xff), \
575 ptr[-3] = ((size >> 16) & 0xff), \
576 ptr[-4] = ((size >> 24) & 0xff))
578 #define XMALLOC_GET_SIZE(ptr) \
579 (size_t)((unsigned)(ptr[-1]) | \
580 ((unsigned)(ptr[-2]) << 8) | \
581 ((unsigned)(ptr[-3]) << 16) | \
582 ((unsigned)(ptr[-4]) << 24))
585 /* The call depth in overrun_check functions. For example, this might happen:
586 xmalloc()
587 overrun_check_malloc()
588 -> malloc -> (via hook)_-> emacs_blocked_malloc
589 -> overrun_check_malloc
590 call malloc (hooks are NULL, so real malloc is called).
591 malloc returns 10000.
592 add overhead, return 10016.
593 <- (back in overrun_check_malloc)
594 add overhead again, return 10032
595 xmalloc returns 10032.
597 (time passes).
599 xfree(10032)
600 overrun_check_free(10032)
601 decrease overhed
602 free(10016) <- crash, because 10000 is the original pointer. */
604 static int check_depth;
606 /* Like malloc, but wraps allocated block with header and trailer. */
608 POINTER_TYPE *
609 overrun_check_malloc (size)
610 size_t size;
612 register unsigned char *val;
613 size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
615 val = (unsigned char *) malloc (size + overhead);
616 if (val && check_depth == 1)
618 memcpy (val, xmalloc_overrun_check_header,
619 XMALLOC_OVERRUN_CHECK_SIZE - 4);
620 val += XMALLOC_OVERRUN_CHECK_SIZE;
621 XMALLOC_PUT_SIZE(val, size);
622 memcpy (val + size, xmalloc_overrun_check_trailer,
623 XMALLOC_OVERRUN_CHECK_SIZE);
625 --check_depth;
626 return (POINTER_TYPE *)val;
630 /* Like realloc, but checks old block for overrun, and wraps new block
631 with header and trailer. */
633 POINTER_TYPE *
634 overrun_check_realloc (block, size)
635 POINTER_TYPE *block;
636 size_t size;
638 register unsigned char *val = (unsigned char *)block;
639 size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
641 if (val
642 && check_depth == 1
643 && memcmp (xmalloc_overrun_check_header,
644 val - XMALLOC_OVERRUN_CHECK_SIZE,
645 XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
647 size_t osize = XMALLOC_GET_SIZE (val);
648 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
649 XMALLOC_OVERRUN_CHECK_SIZE))
650 abort ();
651 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
652 val -= XMALLOC_OVERRUN_CHECK_SIZE;
653 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE);
656 val = (unsigned char *) realloc ((POINTER_TYPE *)val, size + overhead);
658 if (val && check_depth == 1)
660 memcpy (val, xmalloc_overrun_check_header,
661 XMALLOC_OVERRUN_CHECK_SIZE - 4);
662 val += XMALLOC_OVERRUN_CHECK_SIZE;
663 XMALLOC_PUT_SIZE(val, size);
664 memcpy (val + size, xmalloc_overrun_check_trailer,
665 XMALLOC_OVERRUN_CHECK_SIZE);
667 --check_depth;
668 return (POINTER_TYPE *)val;
671 /* Like free, but checks block for overrun. */
673 void
674 overrun_check_free (block)
675 POINTER_TYPE *block;
677 unsigned char *val = (unsigned char *)block;
679 ++check_depth;
680 if (val
681 && check_depth == 1
682 && memcmp (xmalloc_overrun_check_header,
683 val - XMALLOC_OVERRUN_CHECK_SIZE,
684 XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
686 size_t osize = XMALLOC_GET_SIZE (val);
687 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
688 XMALLOC_OVERRUN_CHECK_SIZE))
689 abort ();
690 #ifdef XMALLOC_CLEAR_FREE_MEMORY
691 val -= XMALLOC_OVERRUN_CHECK_SIZE;
692 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_SIZE*2);
693 #else
694 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
695 val -= XMALLOC_OVERRUN_CHECK_SIZE;
696 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE);
697 #endif
700 free (val);
701 --check_depth;
704 #undef malloc
705 #undef realloc
706 #undef free
707 #define malloc overrun_check_malloc
708 #define realloc overrun_check_realloc
709 #define free overrun_check_free
710 #endif
712 #ifdef SYNC_INPUT
713 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
714 there's no need to block input around malloc. */
715 #define MALLOC_BLOCK_INPUT ((void)0)
716 #define MALLOC_UNBLOCK_INPUT ((void)0)
717 #else
718 #define MALLOC_BLOCK_INPUT BLOCK_INPUT
719 #define MALLOC_UNBLOCK_INPUT UNBLOCK_INPUT
720 #endif
722 /* Like malloc but check for no memory and block interrupt input.. */
724 POINTER_TYPE *
725 xmalloc (size_t size)
727 register POINTER_TYPE *val;
729 MALLOC_BLOCK_INPUT;
730 val = (POINTER_TYPE *) malloc (size);
731 MALLOC_UNBLOCK_INPUT;
733 if (!val && size)
734 memory_full ();
735 return val;
739 /* Like realloc but check for no memory and block interrupt input.. */
741 POINTER_TYPE *
742 xrealloc (POINTER_TYPE *block, size_t size)
744 register POINTER_TYPE *val;
746 MALLOC_BLOCK_INPUT;
747 /* We must call malloc explicitly when BLOCK is 0, since some
748 reallocs don't do this. */
749 if (! block)
750 val = (POINTER_TYPE *) malloc (size);
751 else
752 val = (POINTER_TYPE *) realloc (block, size);
753 MALLOC_UNBLOCK_INPUT;
755 if (!val && size) memory_full ();
756 return val;
760 /* Like free but block interrupt input. */
762 void
763 xfree (POINTER_TYPE *block)
765 if (!block)
766 return;
767 MALLOC_BLOCK_INPUT;
768 free (block);
769 MALLOC_UNBLOCK_INPUT;
770 /* We don't call refill_memory_reserve here
771 because that duplicates doing so in emacs_blocked_free
772 and the criterion should go there. */
776 /* Like strdup, but uses xmalloc. */
778 char *
779 xstrdup (const char *s)
781 size_t len = strlen (s) + 1;
782 char *p = (char *) xmalloc (len);
783 memcpy (p, s, len);
784 return p;
788 /* Unwind for SAFE_ALLOCA */
790 Lisp_Object
791 safe_alloca_unwind (Lisp_Object arg)
793 register struct Lisp_Save_Value *p = XSAVE_VALUE (arg);
795 p->dogc = 0;
796 xfree (p->pointer);
797 p->pointer = 0;
798 free_misc (arg);
799 return Qnil;
803 /* Like malloc but used for allocating Lisp data. NBYTES is the
804 number of bytes to allocate, TYPE describes the intended use of the
805 allcated memory block (for strings, for conses, ...). */
807 #ifndef USE_LSB_TAG
808 static void *lisp_malloc_loser;
809 #endif
811 static POINTER_TYPE *
812 lisp_malloc (size_t nbytes, enum mem_type type)
814 register void *val;
816 MALLOC_BLOCK_INPUT;
818 #ifdef GC_MALLOC_CHECK
819 allocated_mem_type = type;
820 #endif
822 val = (void *) malloc (nbytes);
824 #ifndef USE_LSB_TAG
825 /* If the memory just allocated cannot be addressed thru a Lisp
826 object's pointer, and it needs to be,
827 that's equivalent to running out of memory. */
828 if (val && type != MEM_TYPE_NON_LISP)
830 Lisp_Object tem;
831 XSETCONS (tem, (char *) val + nbytes - 1);
832 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
834 lisp_malloc_loser = val;
835 free (val);
836 val = 0;
839 #endif
841 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
842 if (val && type != MEM_TYPE_NON_LISP)
843 mem_insert (val, (char *) val + nbytes, type);
844 #endif
846 MALLOC_UNBLOCK_INPUT;
847 if (!val && nbytes)
848 memory_full ();
849 return val;
852 /* Free BLOCK. This must be called to free memory allocated with a
853 call to lisp_malloc. */
855 static void
856 lisp_free (POINTER_TYPE *block)
858 MALLOC_BLOCK_INPUT;
859 free (block);
860 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
861 mem_delete (mem_find (block));
862 #endif
863 MALLOC_UNBLOCK_INPUT;
866 /* Allocation of aligned blocks of memory to store Lisp data. */
867 /* The entry point is lisp_align_malloc which returns blocks of at most */
868 /* BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
870 /* Use posix_memalloc if the system has it and we're using the system's
871 malloc (because our gmalloc.c routines don't have posix_memalign although
872 its memalloc could be used). */
873 #if defined (HAVE_POSIX_MEMALIGN) && defined (SYSTEM_MALLOC)
874 #define USE_POSIX_MEMALIGN 1
875 #endif
877 /* BLOCK_ALIGN has to be a power of 2. */
878 #define BLOCK_ALIGN (1 << 10)
880 /* Padding to leave at the end of a malloc'd block. This is to give
881 malloc a chance to minimize the amount of memory wasted to alignment.
882 It should be tuned to the particular malloc library used.
883 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
884 posix_memalign on the other hand would ideally prefer a value of 4
885 because otherwise, there's 1020 bytes wasted between each ablocks.
886 In Emacs, testing shows that those 1020 can most of the time be
887 efficiently used by malloc to place other objects, so a value of 0 can
888 still preferable unless you have a lot of aligned blocks and virtually
889 nothing else. */
890 #define BLOCK_PADDING 0
891 #define BLOCK_BYTES \
892 (BLOCK_ALIGN - sizeof (struct ablock *) - BLOCK_PADDING)
894 /* Internal data structures and constants. */
896 #define ABLOCKS_SIZE 16
898 /* An aligned block of memory. */
899 struct ablock
901 union
903 char payload[BLOCK_BYTES];
904 struct ablock *next_free;
905 } x;
906 /* `abase' is the aligned base of the ablocks. */
907 /* It is overloaded to hold the virtual `busy' field that counts
908 the number of used ablock in the parent ablocks.
909 The first ablock has the `busy' field, the others have the `abase'
910 field. To tell the difference, we assume that pointers will have
911 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
912 is used to tell whether the real base of the parent ablocks is `abase'
913 (if not, the word before the first ablock holds a pointer to the
914 real base). */
915 struct ablocks *abase;
916 /* The padding of all but the last ablock is unused. The padding of
917 the last ablock in an ablocks is not allocated. */
918 #if BLOCK_PADDING
919 char padding[BLOCK_PADDING];
920 #endif
923 /* A bunch of consecutive aligned blocks. */
924 struct ablocks
926 struct ablock blocks[ABLOCKS_SIZE];
929 /* Size of the block requested from malloc or memalign. */
930 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
932 #define ABLOCK_ABASE(block) \
933 (((unsigned long) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
934 ? (struct ablocks *)(block) \
935 : (block)->abase)
937 /* Virtual `busy' field. */
938 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
940 /* Pointer to the (not necessarily aligned) malloc block. */
941 #ifdef USE_POSIX_MEMALIGN
942 #define ABLOCKS_BASE(abase) (abase)
943 #else
944 #define ABLOCKS_BASE(abase) \
945 (1 & (long) ABLOCKS_BUSY (abase) ? abase : ((void**)abase)[-1])
946 #endif
948 /* The list of free ablock. */
949 static struct ablock *free_ablock;
951 /* Allocate an aligned block of nbytes.
952 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
953 smaller or equal to BLOCK_BYTES. */
954 static POINTER_TYPE *
955 lisp_align_malloc (size_t nbytes, enum mem_type type)
957 void *base, *val;
958 struct ablocks *abase;
960 eassert (nbytes <= BLOCK_BYTES);
962 MALLOC_BLOCK_INPUT;
964 #ifdef GC_MALLOC_CHECK
965 allocated_mem_type = type;
966 #endif
968 if (!free_ablock)
970 int i;
971 EMACS_INT aligned; /* int gets warning casting to 64-bit pointer. */
973 #ifdef DOUG_LEA_MALLOC
974 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
975 because mapped region contents are not preserved in
976 a dumped Emacs. */
977 mallopt (M_MMAP_MAX, 0);
978 #endif
980 #ifdef USE_POSIX_MEMALIGN
982 int err = posix_memalign (&base, BLOCK_ALIGN, ABLOCKS_BYTES);
983 if (err)
984 base = NULL;
985 abase = base;
987 #else
988 base = malloc (ABLOCKS_BYTES);
989 abase = ALIGN (base, BLOCK_ALIGN);
990 #endif
992 if (base == 0)
994 MALLOC_UNBLOCK_INPUT;
995 memory_full ();
998 aligned = (base == abase);
999 if (!aligned)
1000 ((void**)abase)[-1] = base;
1002 #ifdef DOUG_LEA_MALLOC
1003 /* Back to a reasonable maximum of mmap'ed areas. */
1004 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1005 #endif
1007 #ifndef USE_LSB_TAG
1008 /* If the memory just allocated cannot be addressed thru a Lisp
1009 object's pointer, and it needs to be, that's equivalent to
1010 running out of memory. */
1011 if (type != MEM_TYPE_NON_LISP)
1013 Lisp_Object tem;
1014 char *end = (char *) base + ABLOCKS_BYTES - 1;
1015 XSETCONS (tem, end);
1016 if ((char *) XCONS (tem) != end)
1018 lisp_malloc_loser = base;
1019 free (base);
1020 MALLOC_UNBLOCK_INPUT;
1021 memory_full ();
1024 #endif
1026 /* Initialize the blocks and put them on the free list.
1027 Is `base' was not properly aligned, we can't use the last block. */
1028 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1030 abase->blocks[i].abase = abase;
1031 abase->blocks[i].x.next_free = free_ablock;
1032 free_ablock = &abase->blocks[i];
1034 ABLOCKS_BUSY (abase) = (struct ablocks *) (long) aligned;
1036 eassert (0 == ((EMACS_UINT)abase) % BLOCK_ALIGN);
1037 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1038 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1039 eassert (ABLOCKS_BASE (abase) == base);
1040 eassert (aligned == (long) ABLOCKS_BUSY (abase));
1043 abase = ABLOCK_ABASE (free_ablock);
1044 ABLOCKS_BUSY (abase) = (struct ablocks *) (2 + (long) ABLOCKS_BUSY (abase));
1045 val = free_ablock;
1046 free_ablock = free_ablock->x.next_free;
1048 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1049 if (val && type != MEM_TYPE_NON_LISP)
1050 mem_insert (val, (char *) val + nbytes, type);
1051 #endif
1053 MALLOC_UNBLOCK_INPUT;
1054 if (!val && nbytes)
1055 memory_full ();
1057 eassert (0 == ((EMACS_UINT)val) % BLOCK_ALIGN);
1058 return val;
1061 static void
1062 lisp_align_free (POINTER_TYPE *block)
1064 struct ablock *ablock = block;
1065 struct ablocks *abase = ABLOCK_ABASE (ablock);
1067 MALLOC_BLOCK_INPUT;
1068 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1069 mem_delete (mem_find (block));
1070 #endif
1071 /* Put on free list. */
1072 ablock->x.next_free = free_ablock;
1073 free_ablock = ablock;
1074 /* Update busy count. */
1075 ABLOCKS_BUSY (abase) = (struct ablocks *) (-2 + (long) ABLOCKS_BUSY (abase));
1077 if (2 > (long) ABLOCKS_BUSY (abase))
1078 { /* All the blocks are free. */
1079 int i = 0, aligned = (long) ABLOCKS_BUSY (abase);
1080 struct ablock **tem = &free_ablock;
1081 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1083 while (*tem)
1085 if (*tem >= (struct ablock *) abase && *tem < atop)
1087 i++;
1088 *tem = (*tem)->x.next_free;
1090 else
1091 tem = &(*tem)->x.next_free;
1093 eassert ((aligned & 1) == aligned);
1094 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1095 #ifdef USE_POSIX_MEMALIGN
1096 eassert ((unsigned long)ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1097 #endif
1098 free (ABLOCKS_BASE (abase));
1100 MALLOC_UNBLOCK_INPUT;
1103 /* Return a new buffer structure allocated from the heap with
1104 a call to lisp_malloc. */
1106 struct buffer *
1107 allocate_buffer (void)
1109 struct buffer *b
1110 = (struct buffer *) lisp_malloc (sizeof (struct buffer),
1111 MEM_TYPE_BUFFER);
1112 b->size = sizeof (struct buffer) / sizeof (EMACS_INT);
1113 XSETPVECTYPE (b, PVEC_BUFFER);
1114 return b;
1118 #ifndef SYSTEM_MALLOC
1120 /* Arranging to disable input signals while we're in malloc.
1122 This only works with GNU malloc. To help out systems which can't
1123 use GNU malloc, all the calls to malloc, realloc, and free
1124 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
1125 pair; unfortunately, we have no idea what C library functions
1126 might call malloc, so we can't really protect them unless you're
1127 using GNU malloc. Fortunately, most of the major operating systems
1128 can use GNU malloc. */
1130 #ifndef SYNC_INPUT
1131 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
1132 there's no need to block input around malloc. */
1134 #ifndef DOUG_LEA_MALLOC
1135 extern void * (*__malloc_hook) (size_t, const void *);
1136 extern void * (*__realloc_hook) (void *, size_t, const void *);
1137 extern void (*__free_hook) (void *, const void *);
1138 /* Else declared in malloc.h, perhaps with an extra arg. */
1139 #endif /* DOUG_LEA_MALLOC */
1140 static void * (*old_malloc_hook) (size_t, const void *);
1141 static void * (*old_realloc_hook) (void *, size_t, const void*);
1142 static void (*old_free_hook) (void*, const void*);
1144 /* This function is used as the hook for free to call. */
1146 static void
1147 emacs_blocked_free (void *ptr, const void *ptr2)
1149 BLOCK_INPUT_ALLOC;
1151 #ifdef GC_MALLOC_CHECK
1152 if (ptr)
1154 struct mem_node *m;
1156 m = mem_find (ptr);
1157 if (m == MEM_NIL || m->start != ptr)
1159 fprintf (stderr,
1160 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
1161 abort ();
1163 else
1165 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
1166 mem_delete (m);
1169 #endif /* GC_MALLOC_CHECK */
1171 __free_hook = old_free_hook;
1172 free (ptr);
1174 /* If we released our reserve (due to running out of memory),
1175 and we have a fair amount free once again,
1176 try to set aside another reserve in case we run out once more. */
1177 if (! NILP (Vmemory_full)
1178 /* Verify there is enough space that even with the malloc
1179 hysteresis this call won't run out again.
1180 The code here is correct as long as SPARE_MEMORY
1181 is substantially larger than the block size malloc uses. */
1182 && (bytes_used_when_full
1183 > ((bytes_used_when_reconsidered = BYTES_USED)
1184 + max (malloc_hysteresis, 4) * SPARE_MEMORY)))
1185 refill_memory_reserve ();
1187 __free_hook = emacs_blocked_free;
1188 UNBLOCK_INPUT_ALLOC;
1192 /* This function is the malloc hook that Emacs uses. */
1194 static void *
1195 emacs_blocked_malloc (size_t size, const void *ptr)
1197 void *value;
1199 BLOCK_INPUT_ALLOC;
1200 __malloc_hook = old_malloc_hook;
1201 #ifdef DOUG_LEA_MALLOC
1202 /* Segfaults on my system. --lorentey */
1203 /* mallopt (M_TOP_PAD, malloc_hysteresis * 4096); */
1204 #else
1205 __malloc_extra_blocks = malloc_hysteresis;
1206 #endif
1208 value = (void *) malloc (size);
1210 #ifdef GC_MALLOC_CHECK
1212 struct mem_node *m = mem_find (value);
1213 if (m != MEM_NIL)
1215 fprintf (stderr, "Malloc returned %p which is already in use\n",
1216 value);
1217 fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
1218 m->start, m->end, (char *) m->end - (char *) m->start,
1219 m->type);
1220 abort ();
1223 if (!dont_register_blocks)
1225 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
1226 allocated_mem_type = MEM_TYPE_NON_LISP;
1229 #endif /* GC_MALLOC_CHECK */
1231 __malloc_hook = emacs_blocked_malloc;
1232 UNBLOCK_INPUT_ALLOC;
1234 /* fprintf (stderr, "%p malloc\n", value); */
1235 return value;
1239 /* This function is the realloc hook that Emacs uses. */
1241 static void *
1242 emacs_blocked_realloc (void *ptr, size_t size, const void *ptr2)
1244 void *value;
1246 BLOCK_INPUT_ALLOC;
1247 __realloc_hook = old_realloc_hook;
1249 #ifdef GC_MALLOC_CHECK
1250 if (ptr)
1252 struct mem_node *m = mem_find (ptr);
1253 if (m == MEM_NIL || m->start != ptr)
1255 fprintf (stderr,
1256 "Realloc of %p which wasn't allocated with malloc\n",
1257 ptr);
1258 abort ();
1261 mem_delete (m);
1264 /* fprintf (stderr, "%p -> realloc\n", ptr); */
1266 /* Prevent malloc from registering blocks. */
1267 dont_register_blocks = 1;
1268 #endif /* GC_MALLOC_CHECK */
1270 value = (void *) realloc (ptr, size);
1272 #ifdef GC_MALLOC_CHECK
1273 dont_register_blocks = 0;
1276 struct mem_node *m = mem_find (value);
1277 if (m != MEM_NIL)
1279 fprintf (stderr, "Realloc returns memory that is already in use\n");
1280 abort ();
1283 /* Can't handle zero size regions in the red-black tree. */
1284 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
1287 /* fprintf (stderr, "%p <- realloc\n", value); */
1288 #endif /* GC_MALLOC_CHECK */
1290 __realloc_hook = emacs_blocked_realloc;
1291 UNBLOCK_INPUT_ALLOC;
1293 return value;
1297 #ifdef HAVE_GTK_AND_PTHREAD
1298 /* Called from Fdump_emacs so that when the dumped Emacs starts, it has a
1299 normal malloc. Some thread implementations need this as they call
1300 malloc before main. The pthread_self call in BLOCK_INPUT_ALLOC then
1301 calls malloc because it is the first call, and we have an endless loop. */
1303 void
1304 reset_malloc_hooks ()
1306 __free_hook = old_free_hook;
1307 __malloc_hook = old_malloc_hook;
1308 __realloc_hook = old_realloc_hook;
1310 #endif /* HAVE_GTK_AND_PTHREAD */
1313 /* Called from main to set up malloc to use our hooks. */
1315 void
1316 uninterrupt_malloc (void)
1318 #ifdef HAVE_GTK_AND_PTHREAD
1319 #ifdef DOUG_LEA_MALLOC
1320 pthread_mutexattr_t attr;
1322 /* GLIBC has a faster way to do this, but lets keep it portable.
1323 This is according to the Single UNIX Specification. */
1324 pthread_mutexattr_init (&attr);
1325 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1326 pthread_mutex_init (&alloc_mutex, &attr);
1327 #else /* !DOUG_LEA_MALLOC */
1328 /* Some systems such as Solaris 2.6 don't have a recursive mutex,
1329 and the bundled gmalloc.c doesn't require it. */
1330 pthread_mutex_init (&alloc_mutex, NULL);
1331 #endif /* !DOUG_LEA_MALLOC */
1332 #endif /* HAVE_GTK_AND_PTHREAD */
1334 if (__free_hook != emacs_blocked_free)
1335 old_free_hook = __free_hook;
1336 __free_hook = emacs_blocked_free;
1338 if (__malloc_hook != emacs_blocked_malloc)
1339 old_malloc_hook = __malloc_hook;
1340 __malloc_hook = emacs_blocked_malloc;
1342 if (__realloc_hook != emacs_blocked_realloc)
1343 old_realloc_hook = __realloc_hook;
1344 __realloc_hook = emacs_blocked_realloc;
1347 #endif /* not SYNC_INPUT */
1348 #endif /* not SYSTEM_MALLOC */
1352 /***********************************************************************
1353 Interval Allocation
1354 ***********************************************************************/
1356 /* Number of intervals allocated in an interval_block structure.
1357 The 1020 is 1024 minus malloc overhead. */
1359 #define INTERVAL_BLOCK_SIZE \
1360 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1362 /* Intervals are allocated in chunks in form of an interval_block
1363 structure. */
1365 struct interval_block
1367 /* Place `intervals' first, to preserve alignment. */
1368 struct interval intervals[INTERVAL_BLOCK_SIZE];
1369 struct interval_block *next;
1372 /* Current interval block. Its `next' pointer points to older
1373 blocks. */
1375 static struct interval_block *interval_block;
1377 /* Index in interval_block above of the next unused interval
1378 structure. */
1380 static int interval_block_index;
1382 /* Number of free and live intervals. */
1384 static int total_free_intervals, total_intervals;
1386 /* List of free intervals. */
1388 INTERVAL interval_free_list;
1390 /* Total number of interval blocks now in use. */
1392 static int n_interval_blocks;
1395 /* Initialize interval allocation. */
1397 static void
1398 init_intervals (void)
1400 interval_block = NULL;
1401 interval_block_index = INTERVAL_BLOCK_SIZE;
1402 interval_free_list = 0;
1403 n_interval_blocks = 0;
1407 /* Return a new interval. */
1409 INTERVAL
1410 make_interval (void)
1412 INTERVAL val;
1414 /* eassert (!handling_signal); */
1416 MALLOC_BLOCK_INPUT;
1418 if (interval_free_list)
1420 val = interval_free_list;
1421 interval_free_list = INTERVAL_PARENT (interval_free_list);
1423 else
1425 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1427 register struct interval_block *newi;
1429 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
1430 MEM_TYPE_NON_LISP);
1432 newi->next = interval_block;
1433 interval_block = newi;
1434 interval_block_index = 0;
1435 n_interval_blocks++;
1437 val = &interval_block->intervals[interval_block_index++];
1440 MALLOC_UNBLOCK_INPUT;
1442 consing_since_gc += sizeof (struct interval);
1443 intervals_consed++;
1444 RESET_INTERVAL (val);
1445 val->gcmarkbit = 0;
1446 return val;
1450 /* Mark Lisp objects in interval I. */
1452 static void
1453 mark_interval (register INTERVAL i, Lisp_Object dummy)
1455 eassert (!i->gcmarkbit); /* Intervals are never shared. */
1456 i->gcmarkbit = 1;
1457 mark_object (i->plist);
1461 /* Mark the interval tree rooted in TREE. Don't call this directly;
1462 use the macro MARK_INTERVAL_TREE instead. */
1464 static void
1465 mark_interval_tree (register INTERVAL tree)
1467 /* No need to test if this tree has been marked already; this
1468 function is always called through the MARK_INTERVAL_TREE macro,
1469 which takes care of that. */
1471 traverse_intervals_noorder (tree, mark_interval, Qnil);
1475 /* Mark the interval tree rooted in I. */
1477 #define MARK_INTERVAL_TREE(i) \
1478 do { \
1479 if (!NULL_INTERVAL_P (i) && !i->gcmarkbit) \
1480 mark_interval_tree (i); \
1481 } while (0)
1484 #define UNMARK_BALANCE_INTERVALS(i) \
1485 do { \
1486 if (! NULL_INTERVAL_P (i)) \
1487 (i) = balance_intervals (i); \
1488 } while (0)
1491 /* Number support. If USE_LISP_UNION_TYPE is in effect, we
1492 can't create number objects in macros. */
1493 #ifndef make_number
1494 Lisp_Object
1495 make_number (n)
1496 EMACS_INT n;
1498 Lisp_Object obj;
1499 obj.s.val = n;
1500 obj.s.type = Lisp_Int;
1501 return obj;
1503 #endif
1505 /***********************************************************************
1506 String Allocation
1507 ***********************************************************************/
1509 /* Lisp_Strings are allocated in string_block structures. When a new
1510 string_block is allocated, all the Lisp_Strings it contains are
1511 added to a free-list string_free_list. When a new Lisp_String is
1512 needed, it is taken from that list. During the sweep phase of GC,
1513 string_blocks that are entirely free are freed, except two which
1514 we keep.
1516 String data is allocated from sblock structures. Strings larger
1517 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1518 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1520 Sblocks consist internally of sdata structures, one for each
1521 Lisp_String. The sdata structure points to the Lisp_String it
1522 belongs to. The Lisp_String points back to the `u.data' member of
1523 its sdata structure.
1525 When a Lisp_String is freed during GC, it is put back on
1526 string_free_list, and its `data' member and its sdata's `string'
1527 pointer is set to null. The size of the string is recorded in the
1528 `u.nbytes' member of the sdata. So, sdata structures that are no
1529 longer used, can be easily recognized, and it's easy to compact the
1530 sblocks of small strings which we do in compact_small_strings. */
1532 /* Size in bytes of an sblock structure used for small strings. This
1533 is 8192 minus malloc overhead. */
1535 #define SBLOCK_SIZE 8188
1537 /* Strings larger than this are considered large strings. String data
1538 for large strings is allocated from individual sblocks. */
1540 #define LARGE_STRING_BYTES 1024
1542 /* Structure describing string memory sub-allocated from an sblock.
1543 This is where the contents of Lisp strings are stored. */
1545 struct sdata
1547 /* Back-pointer to the string this sdata belongs to. If null, this
1548 structure is free, and the NBYTES member of the union below
1549 contains the string's byte size (the same value that STRING_BYTES
1550 would return if STRING were non-null). If non-null, STRING_BYTES
1551 (STRING) is the size of the data, and DATA contains the string's
1552 contents. */
1553 struct Lisp_String *string;
1555 #ifdef GC_CHECK_STRING_BYTES
1557 EMACS_INT nbytes;
1558 unsigned char data[1];
1560 #define SDATA_NBYTES(S) (S)->nbytes
1561 #define SDATA_DATA(S) (S)->data
1563 #else /* not GC_CHECK_STRING_BYTES */
1565 union
1567 /* When STRING in non-null. */
1568 unsigned char data[1];
1570 /* When STRING is null. */
1571 EMACS_INT nbytes;
1572 } u;
1575 #define SDATA_NBYTES(S) (S)->u.nbytes
1576 #define SDATA_DATA(S) (S)->u.data
1578 #endif /* not GC_CHECK_STRING_BYTES */
1582 /* Structure describing a block of memory which is sub-allocated to
1583 obtain string data memory for strings. Blocks for small strings
1584 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1585 as large as needed. */
1587 struct sblock
1589 /* Next in list. */
1590 struct sblock *next;
1592 /* Pointer to the next free sdata block. This points past the end
1593 of the sblock if there isn't any space left in this block. */
1594 struct sdata *next_free;
1596 /* Start of data. */
1597 struct sdata first_data;
1600 /* Number of Lisp strings in a string_block structure. The 1020 is
1601 1024 minus malloc overhead. */
1603 #define STRING_BLOCK_SIZE \
1604 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1606 /* Structure describing a block from which Lisp_String structures
1607 are allocated. */
1609 struct string_block
1611 /* Place `strings' first, to preserve alignment. */
1612 struct Lisp_String strings[STRING_BLOCK_SIZE];
1613 struct string_block *next;
1616 /* Head and tail of the list of sblock structures holding Lisp string
1617 data. We always allocate from current_sblock. The NEXT pointers
1618 in the sblock structures go from oldest_sblock to current_sblock. */
1620 static struct sblock *oldest_sblock, *current_sblock;
1622 /* List of sblocks for large strings. */
1624 static struct sblock *large_sblocks;
1626 /* List of string_block structures, and how many there are. */
1628 static struct string_block *string_blocks;
1629 static int n_string_blocks;
1631 /* Free-list of Lisp_Strings. */
1633 static struct Lisp_String *string_free_list;
1635 /* Number of live and free Lisp_Strings. */
1637 static int total_strings, total_free_strings;
1639 /* Number of bytes used by live strings. */
1641 static EMACS_INT total_string_size;
1643 /* Given a pointer to a Lisp_String S which is on the free-list
1644 string_free_list, return a pointer to its successor in the
1645 free-list. */
1647 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1649 /* Return a pointer to the sdata structure belonging to Lisp string S.
1650 S must be live, i.e. S->data must not be null. S->data is actually
1651 a pointer to the `u.data' member of its sdata structure; the
1652 structure starts at a constant offset in front of that. */
1654 #ifdef GC_CHECK_STRING_BYTES
1656 #define SDATA_OF_STRING(S) \
1657 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *) \
1658 - sizeof (EMACS_INT)))
1660 #else /* not GC_CHECK_STRING_BYTES */
1662 #define SDATA_OF_STRING(S) \
1663 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))
1665 #endif /* not GC_CHECK_STRING_BYTES */
1668 #ifdef GC_CHECK_STRING_OVERRUN
1670 /* We check for overrun in string data blocks by appending a small
1671 "cookie" after each allocated string data block, and check for the
1672 presence of this cookie during GC. */
1674 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1675 static char string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1676 { 0xde, 0xad, 0xbe, 0xef };
1678 #else
1679 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1680 #endif
1682 /* Value is the size of an sdata structure large enough to hold NBYTES
1683 bytes of string data. The value returned includes a terminating
1684 NUL byte, the size of the sdata structure, and padding. */
1686 #ifdef GC_CHECK_STRING_BYTES
1688 #define SDATA_SIZE(NBYTES) \
1689 ((sizeof (struct Lisp_String *) \
1690 + (NBYTES) + 1 \
1691 + sizeof (EMACS_INT) \
1692 + sizeof (EMACS_INT) - 1) \
1693 & ~(sizeof (EMACS_INT) - 1))
1695 #else /* not GC_CHECK_STRING_BYTES */
1697 #define SDATA_SIZE(NBYTES) \
1698 ((sizeof (struct Lisp_String *) \
1699 + (NBYTES) + 1 \
1700 + sizeof (EMACS_INT) - 1) \
1701 & ~(sizeof (EMACS_INT) - 1))
1703 #endif /* not GC_CHECK_STRING_BYTES */
1705 /* Extra bytes to allocate for each string. */
1707 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1709 /* Initialize string allocation. Called from init_alloc_once. */
1711 static void
1712 init_strings (void)
1714 total_strings = total_free_strings = total_string_size = 0;
1715 oldest_sblock = current_sblock = large_sblocks = NULL;
1716 string_blocks = NULL;
1717 n_string_blocks = 0;
1718 string_free_list = NULL;
1719 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1720 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1724 #ifdef GC_CHECK_STRING_BYTES
1726 static int check_string_bytes_count;
1728 static void check_string_bytes (int);
1729 static void check_sblock (struct sblock *);
1731 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1734 /* Like GC_STRING_BYTES, but with debugging check. */
1736 EMACS_INT
1737 string_bytes (struct Lisp_String *s)
1739 EMACS_INT nbytes =
1740 (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1742 if (!PURE_POINTER_P (s)
1743 && s->data
1744 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1745 abort ();
1746 return nbytes;
1749 /* Check validity of Lisp strings' string_bytes member in B. */
1751 static void
1752 check_sblock (b)
1753 struct sblock *b;
1755 struct sdata *from, *end, *from_end;
1757 end = b->next_free;
1759 for (from = &b->first_data; from < end; from = from_end)
1761 /* Compute the next FROM here because copying below may
1762 overwrite data we need to compute it. */
1763 EMACS_INT nbytes;
1765 /* Check that the string size recorded in the string is the
1766 same as the one recorded in the sdata structure. */
1767 if (from->string)
1768 CHECK_STRING_BYTES (from->string);
1770 if (from->string)
1771 nbytes = GC_STRING_BYTES (from->string);
1772 else
1773 nbytes = SDATA_NBYTES (from);
1775 nbytes = SDATA_SIZE (nbytes);
1776 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1781 /* Check validity of Lisp strings' string_bytes member. ALL_P
1782 non-zero means check all strings, otherwise check only most
1783 recently allocated strings. Used for hunting a bug. */
1785 static void
1786 check_string_bytes (all_p)
1787 int all_p;
1789 if (all_p)
1791 struct sblock *b;
1793 for (b = large_sblocks; b; b = b->next)
1795 struct Lisp_String *s = b->first_data.string;
1796 if (s)
1797 CHECK_STRING_BYTES (s);
1800 for (b = oldest_sblock; b; b = b->next)
1801 check_sblock (b);
1803 else
1804 check_sblock (current_sblock);
1807 #endif /* GC_CHECK_STRING_BYTES */
1809 #ifdef GC_CHECK_STRING_FREE_LIST
1811 /* Walk through the string free list looking for bogus next pointers.
1812 This may catch buffer overrun from a previous string. */
1814 static void
1815 check_string_free_list ()
1817 struct Lisp_String *s;
1819 /* Pop a Lisp_String off the free-list. */
1820 s = string_free_list;
1821 while (s != NULL)
1823 if ((unsigned long)s < 1024)
1824 abort();
1825 s = NEXT_FREE_LISP_STRING (s);
1828 #else
1829 #define check_string_free_list()
1830 #endif
1832 /* Return a new Lisp_String. */
1834 static struct Lisp_String *
1835 allocate_string (void)
1837 struct Lisp_String *s;
1839 /* eassert (!handling_signal); */
1841 MALLOC_BLOCK_INPUT;
1843 /* If the free-list is empty, allocate a new string_block, and
1844 add all the Lisp_Strings in it to the free-list. */
1845 if (string_free_list == NULL)
1847 struct string_block *b;
1848 int i;
1850 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1851 memset (b, 0, sizeof *b);
1852 b->next = string_blocks;
1853 string_blocks = b;
1854 ++n_string_blocks;
1856 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1858 s = b->strings + i;
1859 NEXT_FREE_LISP_STRING (s) = string_free_list;
1860 string_free_list = s;
1863 total_free_strings += STRING_BLOCK_SIZE;
1866 check_string_free_list ();
1868 /* Pop a Lisp_String off the free-list. */
1869 s = string_free_list;
1870 string_free_list = NEXT_FREE_LISP_STRING (s);
1872 MALLOC_UNBLOCK_INPUT;
1874 /* Probably not strictly necessary, but play it safe. */
1875 memset (s, 0, sizeof *s);
1877 --total_free_strings;
1878 ++total_strings;
1879 ++strings_consed;
1880 consing_since_gc += sizeof *s;
1882 #ifdef GC_CHECK_STRING_BYTES
1883 if (!noninteractive)
1885 if (++check_string_bytes_count == 200)
1887 check_string_bytes_count = 0;
1888 check_string_bytes (1);
1890 else
1891 check_string_bytes (0);
1893 #endif /* GC_CHECK_STRING_BYTES */
1895 return s;
1899 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1900 plus a NUL byte at the end. Allocate an sdata structure for S, and
1901 set S->data to its `u.data' member. Store a NUL byte at the end of
1902 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1903 S->data if it was initially non-null. */
1905 void
1906 allocate_string_data (struct Lisp_String *s,
1907 EMACS_INT nchars, EMACS_INT nbytes)
1909 struct sdata *data, *old_data;
1910 struct sblock *b;
1911 EMACS_INT needed, old_nbytes;
1913 /* Determine the number of bytes needed to store NBYTES bytes
1914 of string data. */
1915 needed = SDATA_SIZE (nbytes);
1916 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1917 old_nbytes = GC_STRING_BYTES (s);
1919 MALLOC_BLOCK_INPUT;
1921 if (nbytes > LARGE_STRING_BYTES)
1923 size_t size = sizeof *b - sizeof (struct sdata) + needed;
1925 #ifdef DOUG_LEA_MALLOC
1926 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1927 because mapped region contents are not preserved in
1928 a dumped Emacs.
1930 In case you think of allowing it in a dumped Emacs at the
1931 cost of not being able to re-dump, there's another reason:
1932 mmap'ed data typically have an address towards the top of the
1933 address space, which won't fit into an EMACS_INT (at least on
1934 32-bit systems with the current tagging scheme). --fx */
1935 mallopt (M_MMAP_MAX, 0);
1936 #endif
1938 b = (struct sblock *) lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
1940 #ifdef DOUG_LEA_MALLOC
1941 /* Back to a reasonable maximum of mmap'ed areas. */
1942 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1943 #endif
1945 b->next_free = &b->first_data;
1946 b->first_data.string = NULL;
1947 b->next = large_sblocks;
1948 large_sblocks = b;
1950 else if (current_sblock == NULL
1951 || (((char *) current_sblock + SBLOCK_SIZE
1952 - (char *) current_sblock->next_free)
1953 < (needed + GC_STRING_EXTRA)))
1955 /* Not enough room in the current sblock. */
1956 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1957 b->next_free = &b->first_data;
1958 b->first_data.string = NULL;
1959 b->next = NULL;
1961 if (current_sblock)
1962 current_sblock->next = b;
1963 else
1964 oldest_sblock = b;
1965 current_sblock = b;
1967 else
1968 b = current_sblock;
1970 data = b->next_free;
1971 b->next_free = (struct sdata *) ((char *) data + needed + GC_STRING_EXTRA);
1973 MALLOC_UNBLOCK_INPUT;
1975 data->string = s;
1976 s->data = SDATA_DATA (data);
1977 #ifdef GC_CHECK_STRING_BYTES
1978 SDATA_NBYTES (data) = nbytes;
1979 #endif
1980 s->size = nchars;
1981 s->size_byte = nbytes;
1982 s->data[nbytes] = '\0';
1983 #ifdef GC_CHECK_STRING_OVERRUN
1984 memcpy (data + needed, string_overrun_cookie, GC_STRING_OVERRUN_COOKIE_SIZE);
1985 #endif
1987 /* If S had already data assigned, mark that as free by setting its
1988 string back-pointer to null, and recording the size of the data
1989 in it. */
1990 if (old_data)
1992 SDATA_NBYTES (old_data) = old_nbytes;
1993 old_data->string = NULL;
1996 consing_since_gc += needed;
2000 /* Sweep and compact strings. */
2002 static void
2003 sweep_strings (void)
2005 struct string_block *b, *next;
2006 struct string_block *live_blocks = NULL;
2008 string_free_list = NULL;
2009 total_strings = total_free_strings = 0;
2010 total_string_size = 0;
2012 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
2013 for (b = string_blocks; b; b = next)
2015 int i, nfree = 0;
2016 struct Lisp_String *free_list_before = string_free_list;
2018 next = b->next;
2020 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
2022 struct Lisp_String *s = b->strings + i;
2024 if (s->data)
2026 /* String was not on free-list before. */
2027 if (STRING_MARKED_P (s))
2029 /* String is live; unmark it and its intervals. */
2030 UNMARK_STRING (s);
2032 if (!NULL_INTERVAL_P (s->intervals))
2033 UNMARK_BALANCE_INTERVALS (s->intervals);
2035 ++total_strings;
2036 total_string_size += STRING_BYTES (s);
2038 else
2040 /* String is dead. Put it on the free-list. */
2041 struct sdata *data = SDATA_OF_STRING (s);
2043 /* Save the size of S in its sdata so that we know
2044 how large that is. Reset the sdata's string
2045 back-pointer so that we know it's free. */
2046 #ifdef GC_CHECK_STRING_BYTES
2047 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
2048 abort ();
2049 #else
2050 data->u.nbytes = GC_STRING_BYTES (s);
2051 #endif
2052 data->string = NULL;
2054 /* Reset the strings's `data' member so that we
2055 know it's free. */
2056 s->data = NULL;
2058 /* Put the string on the free-list. */
2059 NEXT_FREE_LISP_STRING (s) = string_free_list;
2060 string_free_list = s;
2061 ++nfree;
2064 else
2066 /* S was on the free-list before. Put it there again. */
2067 NEXT_FREE_LISP_STRING (s) = string_free_list;
2068 string_free_list = s;
2069 ++nfree;
2073 /* Free blocks that contain free Lisp_Strings only, except
2074 the first two of them. */
2075 if (nfree == STRING_BLOCK_SIZE
2076 && total_free_strings > STRING_BLOCK_SIZE)
2078 lisp_free (b);
2079 --n_string_blocks;
2080 string_free_list = free_list_before;
2082 else
2084 total_free_strings += nfree;
2085 b->next = live_blocks;
2086 live_blocks = b;
2090 check_string_free_list ();
2092 string_blocks = live_blocks;
2093 free_large_strings ();
2094 compact_small_strings ();
2096 check_string_free_list ();
2100 /* Free dead large strings. */
2102 static void
2103 free_large_strings (void)
2105 struct sblock *b, *next;
2106 struct sblock *live_blocks = NULL;
2108 for (b = large_sblocks; b; b = next)
2110 next = b->next;
2112 if (b->first_data.string == NULL)
2113 lisp_free (b);
2114 else
2116 b->next = live_blocks;
2117 live_blocks = b;
2121 large_sblocks = live_blocks;
2125 /* Compact data of small strings. Free sblocks that don't contain
2126 data of live strings after compaction. */
2128 static void
2129 compact_small_strings (void)
2131 struct sblock *b, *tb, *next;
2132 struct sdata *from, *to, *end, *tb_end;
2133 struct sdata *to_end, *from_end;
2135 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2136 to, and TB_END is the end of TB. */
2137 tb = oldest_sblock;
2138 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2139 to = &tb->first_data;
2141 /* Step through the blocks from the oldest to the youngest. We
2142 expect that old blocks will stabilize over time, so that less
2143 copying will happen this way. */
2144 for (b = oldest_sblock; b; b = b->next)
2146 end = b->next_free;
2147 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2149 for (from = &b->first_data; from < end; from = from_end)
2151 /* Compute the next FROM here because copying below may
2152 overwrite data we need to compute it. */
2153 EMACS_INT nbytes;
2155 #ifdef GC_CHECK_STRING_BYTES
2156 /* Check that the string size recorded in the string is the
2157 same as the one recorded in the sdata structure. */
2158 if (from->string
2159 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
2160 abort ();
2161 #endif /* GC_CHECK_STRING_BYTES */
2163 if (from->string)
2164 nbytes = GC_STRING_BYTES (from->string);
2165 else
2166 nbytes = SDATA_NBYTES (from);
2168 if (nbytes > LARGE_STRING_BYTES)
2169 abort ();
2171 nbytes = SDATA_SIZE (nbytes);
2172 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
2174 #ifdef GC_CHECK_STRING_OVERRUN
2175 if (memcmp (string_overrun_cookie,
2176 (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
2177 GC_STRING_OVERRUN_COOKIE_SIZE))
2178 abort ();
2179 #endif
2181 /* FROM->string non-null means it's alive. Copy its data. */
2182 if (from->string)
2184 /* If TB is full, proceed with the next sblock. */
2185 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2186 if (to_end > tb_end)
2188 tb->next_free = to;
2189 tb = tb->next;
2190 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2191 to = &tb->first_data;
2192 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2195 /* Copy, and update the string's `data' pointer. */
2196 if (from != to)
2198 xassert (tb != b || to <= from);
2199 memmove (to, from, nbytes + GC_STRING_EXTRA);
2200 to->string->data = SDATA_DATA (to);
2203 /* Advance past the sdata we copied to. */
2204 to = to_end;
2209 /* The rest of the sblocks following TB don't contain live data, so
2210 we can free them. */
2211 for (b = tb->next; b; b = next)
2213 next = b->next;
2214 lisp_free (b);
2217 tb->next_free = to;
2218 tb->next = NULL;
2219 current_sblock = tb;
2223 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2224 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2225 LENGTH must be an integer.
2226 INIT must be an integer that represents a character. */)
2227 (Lisp_Object length, Lisp_Object init)
2229 register Lisp_Object val;
2230 register unsigned char *p, *end;
2231 int c;
2232 EMACS_INT nbytes;
2234 CHECK_NATNUM (length);
2235 CHECK_NUMBER (init);
2237 c = XINT (init);
2238 if (ASCII_CHAR_P (c))
2240 nbytes = XINT (length);
2241 val = make_uninit_string (nbytes);
2242 p = SDATA (val);
2243 end = p + SCHARS (val);
2244 while (p != end)
2245 *p++ = c;
2247 else
2249 unsigned char str[MAX_MULTIBYTE_LENGTH];
2250 int len = CHAR_STRING (c, str);
2251 EMACS_INT string_len = XINT (length);
2253 if (string_len > MOST_POSITIVE_FIXNUM / len)
2254 error ("Maximum string size exceeded");
2255 nbytes = len * string_len;
2256 val = make_uninit_multibyte_string (string_len, nbytes);
2257 p = SDATA (val);
2258 end = p + nbytes;
2259 while (p != end)
2261 memcpy (p, str, len);
2262 p += len;
2266 *p = 0;
2267 return val;
2271 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2272 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2273 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2274 (Lisp_Object length, Lisp_Object init)
2276 register Lisp_Object val;
2277 struct Lisp_Bool_Vector *p;
2278 int real_init, i;
2279 EMACS_INT length_in_chars, length_in_elts;
2280 int bits_per_value;
2282 CHECK_NATNUM (length);
2284 bits_per_value = sizeof (EMACS_INT) * BOOL_VECTOR_BITS_PER_CHAR;
2286 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
2287 length_in_chars = ((XFASTINT (length) + BOOL_VECTOR_BITS_PER_CHAR - 1)
2288 / BOOL_VECTOR_BITS_PER_CHAR);
2290 /* We must allocate one more elements than LENGTH_IN_ELTS for the
2291 slot `size' of the struct Lisp_Bool_Vector. */
2292 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
2294 /* Get rid of any bits that would cause confusion. */
2295 XVECTOR (val)->size = 0; /* No Lisp_Object to trace in there. */
2296 /* Use XVECTOR (val) rather than `p' because p->size is not TRT. */
2297 XSETPVECTYPE (XVECTOR (val), PVEC_BOOL_VECTOR);
2299 p = XBOOL_VECTOR (val);
2300 p->size = XFASTINT (length);
2302 real_init = (NILP (init) ? 0 : -1);
2303 for (i = 0; i < length_in_chars ; i++)
2304 p->data[i] = real_init;
2306 /* Clear the extraneous bits in the last byte. */
2307 if (XINT (length) != length_in_chars * BOOL_VECTOR_BITS_PER_CHAR)
2308 p->data[length_in_chars - 1]
2309 &= (1 << (XINT (length) % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2311 return val;
2315 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2316 of characters from the contents. This string may be unibyte or
2317 multibyte, depending on the contents. */
2319 Lisp_Object
2320 make_string (const char *contents, EMACS_INT nbytes)
2322 register Lisp_Object val;
2323 EMACS_INT nchars, multibyte_nbytes;
2325 parse_str_as_multibyte (contents, nbytes, &nchars, &multibyte_nbytes);
2326 if (nbytes == nchars || nbytes != multibyte_nbytes)
2327 /* CONTENTS contains no multibyte sequences or contains an invalid
2328 multibyte sequence. We must make unibyte string. */
2329 val = make_unibyte_string (contents, nbytes);
2330 else
2331 val = make_multibyte_string (contents, nchars, nbytes);
2332 return val;
2336 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
2338 Lisp_Object
2339 make_unibyte_string (const char *contents, EMACS_INT length)
2341 register Lisp_Object val;
2342 val = make_uninit_string (length);
2343 memcpy (SDATA (val), contents, length);
2344 STRING_SET_UNIBYTE (val);
2345 return val;
2349 /* Make a multibyte string from NCHARS characters occupying NBYTES
2350 bytes at CONTENTS. */
2352 Lisp_Object
2353 make_multibyte_string (const char *contents,
2354 EMACS_INT nchars, EMACS_INT nbytes)
2356 register Lisp_Object val;
2357 val = make_uninit_multibyte_string (nchars, nbytes);
2358 memcpy (SDATA (val), contents, nbytes);
2359 return val;
2363 /* Make a string from NCHARS characters occupying NBYTES bytes at
2364 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2366 Lisp_Object
2367 make_string_from_bytes (const char *contents,
2368 EMACS_INT nchars, EMACS_INT nbytes)
2370 register Lisp_Object val;
2371 val = make_uninit_multibyte_string (nchars, nbytes);
2372 memcpy (SDATA (val), contents, nbytes);
2373 if (SBYTES (val) == SCHARS (val))
2374 STRING_SET_UNIBYTE (val);
2375 return val;
2379 /* Make a string from NCHARS characters occupying NBYTES bytes at
2380 CONTENTS. The argument MULTIBYTE controls whether to label the
2381 string as multibyte. If NCHARS is negative, it counts the number of
2382 characters by itself. */
2384 Lisp_Object
2385 make_specified_string (const char *contents,
2386 EMACS_INT nchars, EMACS_INT nbytes, int multibyte)
2388 register Lisp_Object val;
2390 if (nchars < 0)
2392 if (multibyte)
2393 nchars = multibyte_chars_in_text (contents, nbytes);
2394 else
2395 nchars = nbytes;
2397 val = make_uninit_multibyte_string (nchars, nbytes);
2398 memcpy (SDATA (val), contents, nbytes);
2399 if (!multibyte)
2400 STRING_SET_UNIBYTE (val);
2401 return val;
2405 /* Make a string from the data at STR, treating it as multibyte if the
2406 data warrants. */
2408 Lisp_Object
2409 build_string (const char *str)
2411 return make_string (str, strlen (str));
2415 /* Return an unibyte Lisp_String set up to hold LENGTH characters
2416 occupying LENGTH bytes. */
2418 Lisp_Object
2419 make_uninit_string (EMACS_INT length)
2421 Lisp_Object val;
2423 if (!length)
2424 return empty_unibyte_string;
2425 val = make_uninit_multibyte_string (length, length);
2426 STRING_SET_UNIBYTE (val);
2427 return val;
2431 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2432 which occupy NBYTES bytes. */
2434 Lisp_Object
2435 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2437 Lisp_Object string;
2438 struct Lisp_String *s;
2440 if (nchars < 0)
2441 abort ();
2442 if (!nbytes)
2443 return empty_multibyte_string;
2445 s = allocate_string ();
2446 allocate_string_data (s, nchars, nbytes);
2447 XSETSTRING (string, s);
2448 string_chars_consed += nbytes;
2449 return string;
2454 /***********************************************************************
2455 Float Allocation
2456 ***********************************************************************/
2458 /* We store float cells inside of float_blocks, allocating a new
2459 float_block with malloc whenever necessary. Float cells reclaimed
2460 by GC are put on a free list to be reallocated before allocating
2461 any new float cells from the latest float_block. */
2463 #define FLOAT_BLOCK_SIZE \
2464 (((BLOCK_BYTES - sizeof (struct float_block *) \
2465 /* The compiler might add padding at the end. */ \
2466 - (sizeof (struct Lisp_Float) - sizeof (int))) * CHAR_BIT) \
2467 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2469 #define GETMARKBIT(block,n) \
2470 (((block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2471 >> ((n) % (sizeof(int) * CHAR_BIT))) \
2472 & 1)
2474 #define SETMARKBIT(block,n) \
2475 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2476 |= 1 << ((n) % (sizeof(int) * CHAR_BIT))
2478 #define UNSETMARKBIT(block,n) \
2479 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2480 &= ~(1 << ((n) % (sizeof(int) * CHAR_BIT)))
2482 #define FLOAT_BLOCK(fptr) \
2483 ((struct float_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
2485 #define FLOAT_INDEX(fptr) \
2486 ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2488 struct float_block
2490 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2491 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2492 int gcmarkbits[1 + FLOAT_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
2493 struct float_block *next;
2496 #define FLOAT_MARKED_P(fptr) \
2497 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2499 #define FLOAT_MARK(fptr) \
2500 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2502 #define FLOAT_UNMARK(fptr) \
2503 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2505 /* Current float_block. */
2507 struct float_block *float_block;
2509 /* Index of first unused Lisp_Float in the current float_block. */
2511 int float_block_index;
2513 /* Total number of float blocks now in use. */
2515 int n_float_blocks;
2517 /* Free-list of Lisp_Floats. */
2519 struct Lisp_Float *float_free_list;
2522 /* Initialize float allocation. */
2524 static void
2525 init_float (void)
2527 float_block = NULL;
2528 float_block_index = FLOAT_BLOCK_SIZE; /* Force alloc of new float_block. */
2529 float_free_list = 0;
2530 n_float_blocks = 0;
2534 /* Return a new float object with value FLOAT_VALUE. */
2536 Lisp_Object
2537 make_float (double float_value)
2539 register Lisp_Object val;
2541 /* eassert (!handling_signal); */
2543 MALLOC_BLOCK_INPUT;
2545 if (float_free_list)
2547 /* We use the data field for chaining the free list
2548 so that we won't use the same field that has the mark bit. */
2549 XSETFLOAT (val, float_free_list);
2550 float_free_list = float_free_list->u.chain;
2552 else
2554 if (float_block_index == FLOAT_BLOCK_SIZE)
2556 register struct float_block *new;
2558 new = (struct float_block *) lisp_align_malloc (sizeof *new,
2559 MEM_TYPE_FLOAT);
2560 new->next = float_block;
2561 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2562 float_block = new;
2563 float_block_index = 0;
2564 n_float_blocks++;
2566 XSETFLOAT (val, &float_block->floats[float_block_index]);
2567 float_block_index++;
2570 MALLOC_UNBLOCK_INPUT;
2572 XFLOAT_INIT (val, float_value);
2573 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2574 consing_since_gc += sizeof (struct Lisp_Float);
2575 floats_consed++;
2576 return val;
2581 /***********************************************************************
2582 Cons Allocation
2583 ***********************************************************************/
2585 /* We store cons cells inside of cons_blocks, allocating a new
2586 cons_block with malloc whenever necessary. Cons cells reclaimed by
2587 GC are put on a free list to be reallocated before allocating
2588 any new cons cells from the latest cons_block. */
2590 #define CONS_BLOCK_SIZE \
2591 (((BLOCK_BYTES - sizeof (struct cons_block *)) * CHAR_BIT) \
2592 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2594 #define CONS_BLOCK(fptr) \
2595 ((struct cons_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
2597 #define CONS_INDEX(fptr) \
2598 ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2600 struct cons_block
2602 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2603 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2604 int gcmarkbits[1 + CONS_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
2605 struct cons_block *next;
2608 #define CONS_MARKED_P(fptr) \
2609 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2611 #define CONS_MARK(fptr) \
2612 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2614 #define CONS_UNMARK(fptr) \
2615 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2617 /* Current cons_block. */
2619 struct cons_block *cons_block;
2621 /* Index of first unused Lisp_Cons in the current block. */
2623 int cons_block_index;
2625 /* Free-list of Lisp_Cons structures. */
2627 struct Lisp_Cons *cons_free_list;
2629 /* Total number of cons blocks now in use. */
2631 static int n_cons_blocks;
2634 /* Initialize cons allocation. */
2636 static void
2637 init_cons (void)
2639 cons_block = NULL;
2640 cons_block_index = CONS_BLOCK_SIZE; /* Force alloc of new cons_block. */
2641 cons_free_list = 0;
2642 n_cons_blocks = 0;
2646 /* Explicitly free a cons cell by putting it on the free-list. */
2648 void
2649 free_cons (struct Lisp_Cons *ptr)
2651 ptr->u.chain = cons_free_list;
2652 #if GC_MARK_STACK
2653 ptr->car = Vdead;
2654 #endif
2655 cons_free_list = ptr;
2658 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2659 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2660 (Lisp_Object car, Lisp_Object cdr)
2662 register Lisp_Object val;
2664 /* eassert (!handling_signal); */
2666 MALLOC_BLOCK_INPUT;
2668 if (cons_free_list)
2670 /* We use the cdr for chaining the free list
2671 so that we won't use the same field that has the mark bit. */
2672 XSETCONS (val, cons_free_list);
2673 cons_free_list = cons_free_list->u.chain;
2675 else
2677 if (cons_block_index == CONS_BLOCK_SIZE)
2679 register struct cons_block *new;
2680 new = (struct cons_block *) lisp_align_malloc (sizeof *new,
2681 MEM_TYPE_CONS);
2682 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2683 new->next = cons_block;
2684 cons_block = new;
2685 cons_block_index = 0;
2686 n_cons_blocks++;
2688 XSETCONS (val, &cons_block->conses[cons_block_index]);
2689 cons_block_index++;
2692 MALLOC_UNBLOCK_INPUT;
2694 XSETCAR (val, car);
2695 XSETCDR (val, cdr);
2696 eassert (!CONS_MARKED_P (XCONS (val)));
2697 consing_since_gc += sizeof (struct Lisp_Cons);
2698 cons_cells_consed++;
2699 return val;
2702 /* Get an error now if there's any junk in the cons free list. */
2703 void
2704 check_cons_list (void)
2706 #ifdef GC_CHECK_CONS_LIST
2707 struct Lisp_Cons *tail = cons_free_list;
2709 while (tail)
2710 tail = tail->u.chain;
2711 #endif
2714 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2716 Lisp_Object
2717 list1 (Lisp_Object arg1)
2719 return Fcons (arg1, Qnil);
2722 Lisp_Object
2723 list2 (Lisp_Object arg1, Lisp_Object arg2)
2725 return Fcons (arg1, Fcons (arg2, Qnil));
2729 Lisp_Object
2730 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2732 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2736 Lisp_Object
2737 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2739 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2743 Lisp_Object
2744 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2746 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2747 Fcons (arg5, Qnil)))));
2751 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2752 doc: /* Return a newly created list with specified arguments as elements.
2753 Any number of arguments, even zero arguments, are allowed.
2754 usage: (list &rest OBJECTS) */)
2755 (int nargs, register Lisp_Object *args)
2757 register Lisp_Object val;
2758 val = Qnil;
2760 while (nargs > 0)
2762 nargs--;
2763 val = Fcons (args[nargs], val);
2765 return val;
2769 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2770 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2771 (register Lisp_Object length, Lisp_Object init)
2773 register Lisp_Object val;
2774 register EMACS_INT size;
2776 CHECK_NATNUM (length);
2777 size = XFASTINT (length);
2779 val = Qnil;
2780 while (size > 0)
2782 val = Fcons (init, val);
2783 --size;
2785 if (size > 0)
2787 val = Fcons (init, val);
2788 --size;
2790 if (size > 0)
2792 val = Fcons (init, val);
2793 --size;
2795 if (size > 0)
2797 val = Fcons (init, val);
2798 --size;
2800 if (size > 0)
2802 val = Fcons (init, val);
2803 --size;
2809 QUIT;
2812 return val;
2817 /***********************************************************************
2818 Vector Allocation
2819 ***********************************************************************/
2821 /* Singly-linked list of all vectors. */
2823 static struct Lisp_Vector *all_vectors;
2825 /* Total number of vector-like objects now in use. */
2827 static int n_vectors;
2830 /* Value is a pointer to a newly allocated Lisp_Vector structure
2831 with room for LEN Lisp_Objects. */
2833 static struct Lisp_Vector *
2834 allocate_vectorlike (EMACS_INT len)
2836 struct Lisp_Vector *p;
2837 size_t nbytes;
2839 MALLOC_BLOCK_INPUT;
2841 #ifdef DOUG_LEA_MALLOC
2842 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2843 because mapped region contents are not preserved in
2844 a dumped Emacs. */
2845 mallopt (M_MMAP_MAX, 0);
2846 #endif
2848 /* This gets triggered by code which I haven't bothered to fix. --Stef */
2849 /* eassert (!handling_signal); */
2851 nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
2852 p = (struct Lisp_Vector *) lisp_malloc (nbytes, MEM_TYPE_VECTORLIKE);
2854 #ifdef DOUG_LEA_MALLOC
2855 /* Back to a reasonable maximum of mmap'ed areas. */
2856 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2857 #endif
2859 consing_since_gc += nbytes;
2860 vector_cells_consed += len;
2862 p->next = all_vectors;
2863 all_vectors = p;
2865 MALLOC_UNBLOCK_INPUT;
2867 ++n_vectors;
2868 return p;
2872 /* Allocate a vector with NSLOTS slots. */
2874 struct Lisp_Vector *
2875 allocate_vector (EMACS_INT nslots)
2877 struct Lisp_Vector *v = allocate_vectorlike (nslots);
2878 v->size = nslots;
2879 return v;
2883 /* Allocate other vector-like structures. */
2885 struct Lisp_Vector *
2886 allocate_pseudovector (int memlen, int lisplen, EMACS_INT tag)
2888 struct Lisp_Vector *v = allocate_vectorlike (memlen);
2889 EMACS_INT i;
2891 /* Only the first lisplen slots will be traced normally by the GC. */
2892 v->size = lisplen;
2893 for (i = 0; i < lisplen; ++i)
2894 v->contents[i] = Qnil;
2896 XSETPVECTYPE (v, tag); /* Add the appropriate tag. */
2897 return v;
2900 struct Lisp_Hash_Table *
2901 allocate_hash_table (void)
2903 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table, count, PVEC_HASH_TABLE);
2907 struct window *
2908 allocate_window (void)
2910 return ALLOCATE_PSEUDOVECTOR(struct window, current_matrix, PVEC_WINDOW);
2914 struct terminal *
2915 allocate_terminal (void)
2917 struct terminal *t = ALLOCATE_PSEUDOVECTOR (struct terminal,
2918 next_terminal, PVEC_TERMINAL);
2919 /* Zero out the non-GC'd fields. FIXME: This should be made unnecessary. */
2920 memset (&t->next_terminal, 0,
2921 (char*) (t + 1) - (char*) &t->next_terminal);
2923 return t;
2926 struct frame *
2927 allocate_frame (void)
2929 struct frame *f = ALLOCATE_PSEUDOVECTOR (struct frame,
2930 face_cache, PVEC_FRAME);
2931 /* Zero out the non-GC'd fields. FIXME: This should be made unnecessary. */
2932 memset (&f->face_cache, 0,
2933 (char *) (f + 1) - (char *) &f->face_cache);
2934 return f;
2938 struct Lisp_Process *
2939 allocate_process (void)
2941 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
2945 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
2946 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
2947 See also the function `vector'. */)
2948 (register Lisp_Object length, Lisp_Object init)
2950 Lisp_Object vector;
2951 register EMACS_INT sizei;
2952 register EMACS_INT index;
2953 register struct Lisp_Vector *p;
2955 CHECK_NATNUM (length);
2956 sizei = XFASTINT (length);
2958 p = allocate_vector (sizei);
2959 for (index = 0; index < sizei; index++)
2960 p->contents[index] = init;
2962 XSETVECTOR (vector, p);
2963 return vector;
2967 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
2968 doc: /* Return a newly created vector with specified arguments as elements.
2969 Any number of arguments, even zero arguments, are allowed.
2970 usage: (vector &rest OBJECTS) */)
2971 (register int nargs, Lisp_Object *args)
2973 register Lisp_Object len, val;
2974 register int index;
2975 register struct Lisp_Vector *p;
2977 XSETFASTINT (len, nargs);
2978 val = Fmake_vector (len, Qnil);
2979 p = XVECTOR (val);
2980 for (index = 0; index < nargs; index++)
2981 p->contents[index] = args[index];
2982 return val;
2986 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
2987 doc: /* Create a byte-code object with specified arguments as elements.
2988 The arguments should be the arglist, bytecode-string, constant vector,
2989 stack size, (optional) doc string, and (optional) interactive spec.
2990 The first four arguments are required; at most six have any
2991 significance.
2992 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
2993 (register int nargs, Lisp_Object *args)
2995 register Lisp_Object len, val;
2996 register int index;
2997 register struct Lisp_Vector *p;
2999 XSETFASTINT (len, nargs);
3000 if (!NILP (Vpurify_flag))
3001 val = make_pure_vector ((EMACS_INT) nargs);
3002 else
3003 val = Fmake_vector (len, Qnil);
3005 if (nargs > 1 && STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
3006 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3007 earlier because they produced a raw 8-bit string for byte-code
3008 and now such a byte-code string is loaded as multibyte while
3009 raw 8-bit characters converted to multibyte form. Thus, now we
3010 must convert them back to the original unibyte form. */
3011 args[1] = Fstring_as_unibyte (args[1]);
3013 p = XVECTOR (val);
3014 for (index = 0; index < nargs; index++)
3016 if (!NILP (Vpurify_flag))
3017 args[index] = Fpurecopy (args[index]);
3018 p->contents[index] = args[index];
3020 XSETPVECTYPE (p, PVEC_COMPILED);
3021 XSETCOMPILED (val, p);
3022 return val;
3027 /***********************************************************************
3028 Symbol Allocation
3029 ***********************************************************************/
3031 /* Each symbol_block is just under 1020 bytes long, since malloc
3032 really allocates in units of powers of two and uses 4 bytes for its
3033 own overhead. */
3035 #define SYMBOL_BLOCK_SIZE \
3036 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
3038 struct symbol_block
3040 /* Place `symbols' first, to preserve alignment. */
3041 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3042 struct symbol_block *next;
3045 /* Current symbol block and index of first unused Lisp_Symbol
3046 structure in it. */
3048 static struct symbol_block *symbol_block;
3049 static int symbol_block_index;
3051 /* List of free symbols. */
3053 static struct Lisp_Symbol *symbol_free_list;
3055 /* Total number of symbol blocks now in use. */
3057 static int n_symbol_blocks;
3060 /* Initialize symbol allocation. */
3062 static void
3063 init_symbol (void)
3065 symbol_block = NULL;
3066 symbol_block_index = SYMBOL_BLOCK_SIZE;
3067 symbol_free_list = 0;
3068 n_symbol_blocks = 0;
3072 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3073 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3074 Its value and function definition are void, and its property list is nil. */)
3075 (Lisp_Object name)
3077 register Lisp_Object val;
3078 register struct Lisp_Symbol *p;
3080 CHECK_STRING (name);
3082 /* eassert (!handling_signal); */
3084 MALLOC_BLOCK_INPUT;
3086 if (symbol_free_list)
3088 XSETSYMBOL (val, symbol_free_list);
3089 symbol_free_list = symbol_free_list->next;
3091 else
3093 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3095 struct symbol_block *new;
3096 new = (struct symbol_block *) lisp_malloc (sizeof *new,
3097 MEM_TYPE_SYMBOL);
3098 new->next = symbol_block;
3099 symbol_block = new;
3100 symbol_block_index = 0;
3101 n_symbol_blocks++;
3103 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index]);
3104 symbol_block_index++;
3107 MALLOC_UNBLOCK_INPUT;
3109 p = XSYMBOL (val);
3110 p->xname = name;
3111 p->plist = Qnil;
3112 p->redirect = SYMBOL_PLAINVAL;
3113 SET_SYMBOL_VAL (p, Qunbound);
3114 p->function = Qunbound;
3115 p->next = NULL;
3116 p->gcmarkbit = 0;
3117 p->interned = SYMBOL_UNINTERNED;
3118 p->constant = 0;
3119 consing_since_gc += sizeof (struct Lisp_Symbol);
3120 symbols_consed++;
3121 return val;
3126 /***********************************************************************
3127 Marker (Misc) Allocation
3128 ***********************************************************************/
3130 /* Allocation of markers and other objects that share that structure.
3131 Works like allocation of conses. */
3133 #define MARKER_BLOCK_SIZE \
3134 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
3136 struct marker_block
3138 /* Place `markers' first, to preserve alignment. */
3139 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
3140 struct marker_block *next;
3143 static struct marker_block *marker_block;
3144 static int marker_block_index;
3146 static union Lisp_Misc *marker_free_list;
3148 /* Total number of marker blocks now in use. */
3150 static int n_marker_blocks;
3152 static void
3153 init_marker (void)
3155 marker_block = NULL;
3156 marker_block_index = MARKER_BLOCK_SIZE;
3157 marker_free_list = 0;
3158 n_marker_blocks = 0;
3161 /* Return a newly allocated Lisp_Misc object, with no substructure. */
3163 Lisp_Object
3164 allocate_misc (void)
3166 Lisp_Object val;
3168 /* eassert (!handling_signal); */
3170 MALLOC_BLOCK_INPUT;
3172 if (marker_free_list)
3174 XSETMISC (val, marker_free_list);
3175 marker_free_list = marker_free_list->u_free.chain;
3177 else
3179 if (marker_block_index == MARKER_BLOCK_SIZE)
3181 struct marker_block *new;
3182 new = (struct marker_block *) lisp_malloc (sizeof *new,
3183 MEM_TYPE_MISC);
3184 new->next = marker_block;
3185 marker_block = new;
3186 marker_block_index = 0;
3187 n_marker_blocks++;
3188 total_free_markers += MARKER_BLOCK_SIZE;
3190 XSETMISC (val, &marker_block->markers[marker_block_index]);
3191 marker_block_index++;
3194 MALLOC_UNBLOCK_INPUT;
3196 --total_free_markers;
3197 consing_since_gc += sizeof (union Lisp_Misc);
3198 misc_objects_consed++;
3199 XMISCANY (val)->gcmarkbit = 0;
3200 return val;
3203 /* Free a Lisp_Misc object */
3205 void
3206 free_misc (Lisp_Object misc)
3208 XMISCTYPE (misc) = Lisp_Misc_Free;
3209 XMISC (misc)->u_free.chain = marker_free_list;
3210 marker_free_list = XMISC (misc);
3212 total_free_markers++;
3215 /* Return a Lisp_Misc_Save_Value object containing POINTER and
3216 INTEGER. This is used to package C values to call record_unwind_protect.
3217 The unwind function can get the C values back using XSAVE_VALUE. */
3219 Lisp_Object
3220 make_save_value (void *pointer, int integer)
3222 register Lisp_Object val;
3223 register struct Lisp_Save_Value *p;
3225 val = allocate_misc ();
3226 XMISCTYPE (val) = Lisp_Misc_Save_Value;
3227 p = XSAVE_VALUE (val);
3228 p->pointer = pointer;
3229 p->integer = integer;
3230 p->dogc = 0;
3231 return val;
3234 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3235 doc: /* Return a newly allocated marker which does not point at any place. */)
3236 (void)
3238 register Lisp_Object val;
3239 register struct Lisp_Marker *p;
3241 val = allocate_misc ();
3242 XMISCTYPE (val) = Lisp_Misc_Marker;
3243 p = XMARKER (val);
3244 p->buffer = 0;
3245 p->bytepos = 0;
3246 p->charpos = 0;
3247 p->next = NULL;
3248 p->insertion_type = 0;
3249 return val;
3252 /* Put MARKER back on the free list after using it temporarily. */
3254 void
3255 free_marker (Lisp_Object marker)
3257 unchain_marker (XMARKER (marker));
3258 free_misc (marker);
3262 /* Return a newly created vector or string with specified arguments as
3263 elements. If all the arguments are characters that can fit
3264 in a string of events, make a string; otherwise, make a vector.
3266 Any number of arguments, even zero arguments, are allowed. */
3268 Lisp_Object
3269 make_event_array (register int nargs, Lisp_Object *args)
3271 int i;
3273 for (i = 0; i < nargs; i++)
3274 /* The things that fit in a string
3275 are characters that are in 0...127,
3276 after discarding the meta bit and all the bits above it. */
3277 if (!INTEGERP (args[i])
3278 || (XUINT (args[i]) & ~(-CHAR_META)) >= 0200)
3279 return Fvector (nargs, args);
3281 /* Since the loop exited, we know that all the things in it are
3282 characters, so we can make a string. */
3284 Lisp_Object result;
3286 result = Fmake_string (make_number (nargs), make_number (0));
3287 for (i = 0; i < nargs; i++)
3289 SSET (result, i, XINT (args[i]));
3290 /* Move the meta bit to the right place for a string char. */
3291 if (XINT (args[i]) & CHAR_META)
3292 SSET (result, i, SREF (result, i) | 0x80);
3295 return result;
3301 /************************************************************************
3302 Memory Full Handling
3303 ************************************************************************/
3306 /* Called if malloc returns zero. */
3308 void
3309 memory_full (void)
3311 int i;
3313 Vmemory_full = Qt;
3315 memory_full_cons_threshold = sizeof (struct cons_block);
3317 /* The first time we get here, free the spare memory. */
3318 for (i = 0; i < sizeof (spare_memory) / sizeof (char *); i++)
3319 if (spare_memory[i])
3321 if (i == 0)
3322 free (spare_memory[i]);
3323 else if (i >= 1 && i <= 4)
3324 lisp_align_free (spare_memory[i]);
3325 else
3326 lisp_free (spare_memory[i]);
3327 spare_memory[i] = 0;
3330 /* Record the space now used. When it decreases substantially,
3331 we can refill the memory reserve. */
3332 #ifndef SYSTEM_MALLOC
3333 bytes_used_when_full = BYTES_USED;
3334 #endif
3336 /* This used to call error, but if we've run out of memory, we could
3337 get infinite recursion trying to build the string. */
3338 xsignal (Qnil, Vmemory_signal_data);
3341 /* If we released our reserve (due to running out of memory),
3342 and we have a fair amount free once again,
3343 try to set aside another reserve in case we run out once more.
3345 This is called when a relocatable block is freed in ralloc.c,
3346 and also directly from this file, in case we're not using ralloc.c. */
3348 void
3349 refill_memory_reserve (void)
3351 #ifndef SYSTEM_MALLOC
3352 if (spare_memory[0] == 0)
3353 spare_memory[0] = (char *) malloc ((size_t) SPARE_MEMORY);
3354 if (spare_memory[1] == 0)
3355 spare_memory[1] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3356 MEM_TYPE_CONS);
3357 if (spare_memory[2] == 0)
3358 spare_memory[2] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3359 MEM_TYPE_CONS);
3360 if (spare_memory[3] == 0)
3361 spare_memory[3] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3362 MEM_TYPE_CONS);
3363 if (spare_memory[4] == 0)
3364 spare_memory[4] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3365 MEM_TYPE_CONS);
3366 if (spare_memory[5] == 0)
3367 spare_memory[5] = (char *) lisp_malloc (sizeof (struct string_block),
3368 MEM_TYPE_STRING);
3369 if (spare_memory[6] == 0)
3370 spare_memory[6] = (char *) lisp_malloc (sizeof (struct string_block),
3371 MEM_TYPE_STRING);
3372 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
3373 Vmemory_full = Qnil;
3374 #endif
3377 /************************************************************************
3378 C Stack Marking
3379 ************************************************************************/
3381 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
3383 /* Conservative C stack marking requires a method to identify possibly
3384 live Lisp objects given a pointer value. We do this by keeping
3385 track of blocks of Lisp data that are allocated in a red-black tree
3386 (see also the comment of mem_node which is the type of nodes in
3387 that tree). Function lisp_malloc adds information for an allocated
3388 block to the red-black tree with calls to mem_insert, and function
3389 lisp_free removes it with mem_delete. Functions live_string_p etc
3390 call mem_find to lookup information about a given pointer in the
3391 tree, and use that to determine if the pointer points to a Lisp
3392 object or not. */
3394 /* Initialize this part of alloc.c. */
3396 static void
3397 mem_init (void)
3399 mem_z.left = mem_z.right = MEM_NIL;
3400 mem_z.parent = NULL;
3401 mem_z.color = MEM_BLACK;
3402 mem_z.start = mem_z.end = NULL;
3403 mem_root = MEM_NIL;
3407 /* Value is a pointer to the mem_node containing START. Value is
3408 MEM_NIL if there is no node in the tree containing START. */
3410 static INLINE struct mem_node *
3411 mem_find (void *start)
3413 struct mem_node *p;
3415 if (start < min_heap_address || start > max_heap_address)
3416 return MEM_NIL;
3418 /* Make the search always successful to speed up the loop below. */
3419 mem_z.start = start;
3420 mem_z.end = (char *) start + 1;
3422 p = mem_root;
3423 while (start < p->start || start >= p->end)
3424 p = start < p->start ? p->left : p->right;
3425 return p;
3429 /* Insert a new node into the tree for a block of memory with start
3430 address START, end address END, and type TYPE. Value is a
3431 pointer to the node that was inserted. */
3433 static struct mem_node *
3434 mem_insert (void *start, void *end, enum mem_type type)
3436 struct mem_node *c, *parent, *x;
3438 if (min_heap_address == NULL || start < min_heap_address)
3439 min_heap_address = start;
3440 if (max_heap_address == NULL || end > max_heap_address)
3441 max_heap_address = end;
3443 /* See where in the tree a node for START belongs. In this
3444 particular application, it shouldn't happen that a node is already
3445 present. For debugging purposes, let's check that. */
3446 c = mem_root;
3447 parent = NULL;
3449 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
3451 while (c != MEM_NIL)
3453 if (start >= c->start && start < c->end)
3454 abort ();
3455 parent = c;
3456 c = start < c->start ? c->left : c->right;
3459 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3461 while (c != MEM_NIL)
3463 parent = c;
3464 c = start < c->start ? c->left : c->right;
3467 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3469 /* Create a new node. */
3470 #ifdef GC_MALLOC_CHECK
3471 x = (struct mem_node *) _malloc_internal (sizeof *x);
3472 if (x == NULL)
3473 abort ();
3474 #else
3475 x = (struct mem_node *) xmalloc (sizeof *x);
3476 #endif
3477 x->start = start;
3478 x->end = end;
3479 x->type = type;
3480 x->parent = parent;
3481 x->left = x->right = MEM_NIL;
3482 x->color = MEM_RED;
3484 /* Insert it as child of PARENT or install it as root. */
3485 if (parent)
3487 if (start < parent->start)
3488 parent->left = x;
3489 else
3490 parent->right = x;
3492 else
3493 mem_root = x;
3495 /* Re-establish red-black tree properties. */
3496 mem_insert_fixup (x);
3498 return x;
3502 /* Re-establish the red-black properties of the tree, and thereby
3503 balance the tree, after node X has been inserted; X is always red. */
3505 static void
3506 mem_insert_fixup (struct mem_node *x)
3508 while (x != mem_root && x->parent->color == MEM_RED)
3510 /* X is red and its parent is red. This is a violation of
3511 red-black tree property #3. */
3513 if (x->parent == x->parent->parent->left)
3515 /* We're on the left side of our grandparent, and Y is our
3516 "uncle". */
3517 struct mem_node *y = x->parent->parent->right;
3519 if (y->color == MEM_RED)
3521 /* Uncle and parent are red but should be black because
3522 X is red. Change the colors accordingly and proceed
3523 with the grandparent. */
3524 x->parent->color = MEM_BLACK;
3525 y->color = MEM_BLACK;
3526 x->parent->parent->color = MEM_RED;
3527 x = x->parent->parent;
3529 else
3531 /* Parent and uncle have different colors; parent is
3532 red, uncle is black. */
3533 if (x == x->parent->right)
3535 x = x->parent;
3536 mem_rotate_left (x);
3539 x->parent->color = MEM_BLACK;
3540 x->parent->parent->color = MEM_RED;
3541 mem_rotate_right (x->parent->parent);
3544 else
3546 /* This is the symmetrical case of above. */
3547 struct mem_node *y = x->parent->parent->left;
3549 if (y->color == MEM_RED)
3551 x->parent->color = MEM_BLACK;
3552 y->color = MEM_BLACK;
3553 x->parent->parent->color = MEM_RED;
3554 x = x->parent->parent;
3556 else
3558 if (x == x->parent->left)
3560 x = x->parent;
3561 mem_rotate_right (x);
3564 x->parent->color = MEM_BLACK;
3565 x->parent->parent->color = MEM_RED;
3566 mem_rotate_left (x->parent->parent);
3571 /* The root may have been changed to red due to the algorithm. Set
3572 it to black so that property #5 is satisfied. */
3573 mem_root->color = MEM_BLACK;
3577 /* (x) (y)
3578 / \ / \
3579 a (y) ===> (x) c
3580 / \ / \
3581 b c a b */
3583 static void
3584 mem_rotate_left (struct mem_node *x)
3586 struct mem_node *y;
3588 /* Turn y's left sub-tree into x's right sub-tree. */
3589 y = x->right;
3590 x->right = y->left;
3591 if (y->left != MEM_NIL)
3592 y->left->parent = x;
3594 /* Y's parent was x's parent. */
3595 if (y != MEM_NIL)
3596 y->parent = x->parent;
3598 /* Get the parent to point to y instead of x. */
3599 if (x->parent)
3601 if (x == x->parent->left)
3602 x->parent->left = y;
3603 else
3604 x->parent->right = y;
3606 else
3607 mem_root = y;
3609 /* Put x on y's left. */
3610 y->left = x;
3611 if (x != MEM_NIL)
3612 x->parent = y;
3616 /* (x) (Y)
3617 / \ / \
3618 (y) c ===> a (x)
3619 / \ / \
3620 a b b c */
3622 static void
3623 mem_rotate_right (struct mem_node *x)
3625 struct mem_node *y = x->left;
3627 x->left = y->right;
3628 if (y->right != MEM_NIL)
3629 y->right->parent = x;
3631 if (y != MEM_NIL)
3632 y->parent = x->parent;
3633 if (x->parent)
3635 if (x == x->parent->right)
3636 x->parent->right = y;
3637 else
3638 x->parent->left = y;
3640 else
3641 mem_root = y;
3643 y->right = x;
3644 if (x != MEM_NIL)
3645 x->parent = y;
3649 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
3651 static void
3652 mem_delete (struct mem_node *z)
3654 struct mem_node *x, *y;
3656 if (!z || z == MEM_NIL)
3657 return;
3659 if (z->left == MEM_NIL || z->right == MEM_NIL)
3660 y = z;
3661 else
3663 y = z->right;
3664 while (y->left != MEM_NIL)
3665 y = y->left;
3668 if (y->left != MEM_NIL)
3669 x = y->left;
3670 else
3671 x = y->right;
3673 x->parent = y->parent;
3674 if (y->parent)
3676 if (y == y->parent->left)
3677 y->parent->left = x;
3678 else
3679 y->parent->right = x;
3681 else
3682 mem_root = x;
3684 if (y != z)
3686 z->start = y->start;
3687 z->end = y->end;
3688 z->type = y->type;
3691 if (y->color == MEM_BLACK)
3692 mem_delete_fixup (x);
3694 #ifdef GC_MALLOC_CHECK
3695 _free_internal (y);
3696 #else
3697 xfree (y);
3698 #endif
3702 /* Re-establish the red-black properties of the tree, after a
3703 deletion. */
3705 static void
3706 mem_delete_fixup (struct mem_node *x)
3708 while (x != mem_root && x->color == MEM_BLACK)
3710 if (x == x->parent->left)
3712 struct mem_node *w = x->parent->right;
3714 if (w->color == MEM_RED)
3716 w->color = MEM_BLACK;
3717 x->parent->color = MEM_RED;
3718 mem_rotate_left (x->parent);
3719 w = x->parent->right;
3722 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
3724 w->color = MEM_RED;
3725 x = x->parent;
3727 else
3729 if (w->right->color == MEM_BLACK)
3731 w->left->color = MEM_BLACK;
3732 w->color = MEM_RED;
3733 mem_rotate_right (w);
3734 w = x->parent->right;
3736 w->color = x->parent->color;
3737 x->parent->color = MEM_BLACK;
3738 w->right->color = MEM_BLACK;
3739 mem_rotate_left (x->parent);
3740 x = mem_root;
3743 else
3745 struct mem_node *w = x->parent->left;
3747 if (w->color == MEM_RED)
3749 w->color = MEM_BLACK;
3750 x->parent->color = MEM_RED;
3751 mem_rotate_right (x->parent);
3752 w = x->parent->left;
3755 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
3757 w->color = MEM_RED;
3758 x = x->parent;
3760 else
3762 if (w->left->color == MEM_BLACK)
3764 w->right->color = MEM_BLACK;
3765 w->color = MEM_RED;
3766 mem_rotate_left (w);
3767 w = x->parent->left;
3770 w->color = x->parent->color;
3771 x->parent->color = MEM_BLACK;
3772 w->left->color = MEM_BLACK;
3773 mem_rotate_right (x->parent);
3774 x = mem_root;
3779 x->color = MEM_BLACK;
3783 /* Value is non-zero if P is a pointer to a live Lisp string on
3784 the heap. M is a pointer to the mem_block for P. */
3786 static INLINE int
3787 live_string_p (struct mem_node *m, void *p)
3789 if (m->type == MEM_TYPE_STRING)
3791 struct string_block *b = (struct string_block *) m->start;
3792 ptrdiff_t offset = (char *) p - (char *) &b->strings[0];
3794 /* P must point to the start of a Lisp_String structure, and it
3795 must not be on the free-list. */
3796 return (offset >= 0
3797 && offset % sizeof b->strings[0] == 0
3798 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
3799 && ((struct Lisp_String *) p)->data != NULL);
3801 else
3802 return 0;
3806 /* Value is non-zero if P is a pointer to a live Lisp cons on
3807 the heap. M is a pointer to the mem_block for P. */
3809 static INLINE int
3810 live_cons_p (struct mem_node *m, void *p)
3812 if (m->type == MEM_TYPE_CONS)
3814 struct cons_block *b = (struct cons_block *) m->start;
3815 ptrdiff_t offset = (char *) p - (char *) &b->conses[0];
3817 /* P must point to the start of a Lisp_Cons, not be
3818 one of the unused cells in the current cons block,
3819 and not be on the free-list. */
3820 return (offset >= 0
3821 && offset % sizeof b->conses[0] == 0
3822 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
3823 && (b != cons_block
3824 || offset / sizeof b->conses[0] < cons_block_index)
3825 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
3827 else
3828 return 0;
3832 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3833 the heap. M is a pointer to the mem_block for P. */
3835 static INLINE int
3836 live_symbol_p (struct mem_node *m, void *p)
3838 if (m->type == MEM_TYPE_SYMBOL)
3840 struct symbol_block *b = (struct symbol_block *) m->start;
3841 ptrdiff_t offset = (char *) p - (char *) &b->symbols[0];
3843 /* P must point to the start of a Lisp_Symbol, not be
3844 one of the unused cells in the current symbol block,
3845 and not be on the free-list. */
3846 return (offset >= 0
3847 && offset % sizeof b->symbols[0] == 0
3848 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
3849 && (b != symbol_block
3850 || offset / sizeof b->symbols[0] < symbol_block_index)
3851 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
3853 else
3854 return 0;
3858 /* Value is non-zero if P is a pointer to a live Lisp float on
3859 the heap. M is a pointer to the mem_block for P. */
3861 static INLINE int
3862 live_float_p (struct mem_node *m, void *p)
3864 if (m->type == MEM_TYPE_FLOAT)
3866 struct float_block *b = (struct float_block *) m->start;
3867 ptrdiff_t offset = (char *) p - (char *) &b->floats[0];
3869 /* P must point to the start of a Lisp_Float and not be
3870 one of the unused cells in the current float block. */
3871 return (offset >= 0
3872 && offset % sizeof b->floats[0] == 0
3873 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
3874 && (b != float_block
3875 || offset / sizeof b->floats[0] < float_block_index));
3877 else
3878 return 0;
3882 /* Value is non-zero if P is a pointer to a live Lisp Misc on
3883 the heap. M is a pointer to the mem_block for P. */
3885 static INLINE int
3886 live_misc_p (struct mem_node *m, void *p)
3888 if (m->type == MEM_TYPE_MISC)
3890 struct marker_block *b = (struct marker_block *) m->start;
3891 ptrdiff_t offset = (char *) p - (char *) &b->markers[0];
3893 /* P must point to the start of a Lisp_Misc, not be
3894 one of the unused cells in the current misc block,
3895 and not be on the free-list. */
3896 return (offset >= 0
3897 && offset % sizeof b->markers[0] == 0
3898 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
3899 && (b != marker_block
3900 || offset / sizeof b->markers[0] < marker_block_index)
3901 && ((union Lisp_Misc *) p)->u_any.type != Lisp_Misc_Free);
3903 else
3904 return 0;
3908 /* Value is non-zero if P is a pointer to a live vector-like object.
3909 M is a pointer to the mem_block for P. */
3911 static INLINE int
3912 live_vector_p (struct mem_node *m, void *p)
3914 return (p == m->start && m->type == MEM_TYPE_VECTORLIKE);
3918 /* Value is non-zero if P is a pointer to a live buffer. M is a
3919 pointer to the mem_block for P. */
3921 static INLINE int
3922 live_buffer_p (struct mem_node *m, void *p)
3924 /* P must point to the start of the block, and the buffer
3925 must not have been killed. */
3926 return (m->type == MEM_TYPE_BUFFER
3927 && p == m->start
3928 && !NILP (((struct buffer *) p)->name));
3931 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
3933 #if GC_MARK_STACK
3935 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3937 /* Array of objects that are kept alive because the C stack contains
3938 a pattern that looks like a reference to them . */
3940 #define MAX_ZOMBIES 10
3941 static Lisp_Object zombies[MAX_ZOMBIES];
3943 /* Number of zombie objects. */
3945 static int nzombies;
3947 /* Number of garbage collections. */
3949 static int ngcs;
3951 /* Average percentage of zombies per collection. */
3953 static double avg_zombies;
3955 /* Max. number of live and zombie objects. */
3957 static int max_live, max_zombies;
3959 /* Average number of live objects per GC. */
3961 static double avg_live;
3963 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
3964 doc: /* Show information about live and zombie objects. */)
3965 (void)
3967 Lisp_Object args[8], zombie_list = Qnil;
3968 int i;
3969 for (i = 0; i < nzombies; i++)
3970 zombie_list = Fcons (zombies[i], zombie_list);
3971 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
3972 args[1] = make_number (ngcs);
3973 args[2] = make_float (avg_live);
3974 args[3] = make_float (avg_zombies);
3975 args[4] = make_float (avg_zombies / avg_live / 100);
3976 args[5] = make_number (max_live);
3977 args[6] = make_number (max_zombies);
3978 args[7] = zombie_list;
3979 return Fmessage (8, args);
3982 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3985 /* Mark OBJ if we can prove it's a Lisp_Object. */
3987 static INLINE void
3988 mark_maybe_object (Lisp_Object obj)
3990 void *po = (void *) XPNTR (obj);
3991 struct mem_node *m = mem_find (po);
3993 if (m != MEM_NIL)
3995 int mark_p = 0;
3997 switch (XTYPE (obj))
3999 case Lisp_String:
4000 mark_p = (live_string_p (m, po)
4001 && !STRING_MARKED_P ((struct Lisp_String *) po));
4002 break;
4004 case Lisp_Cons:
4005 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4006 break;
4008 case Lisp_Symbol:
4009 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4010 break;
4012 case Lisp_Float:
4013 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4014 break;
4016 case Lisp_Vectorlike:
4017 /* Note: can't check BUFFERP before we know it's a
4018 buffer because checking that dereferences the pointer
4019 PO which might point anywhere. */
4020 if (live_vector_p (m, po))
4021 mark_p = !SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4022 else if (live_buffer_p (m, po))
4023 mark_p = BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4024 break;
4026 case Lisp_Misc:
4027 mark_p = (live_misc_p (m, po) && !XMISCANY (obj)->gcmarkbit);
4028 break;
4030 default:
4031 break;
4034 if (mark_p)
4036 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4037 if (nzombies < MAX_ZOMBIES)
4038 zombies[nzombies] = obj;
4039 ++nzombies;
4040 #endif
4041 mark_object (obj);
4047 /* If P points to Lisp data, mark that as live if it isn't already
4048 marked. */
4050 static INLINE void
4051 mark_maybe_pointer (void *p)
4053 struct mem_node *m;
4055 /* Quickly rule out some values which can't point to Lisp data. */
4056 if ((EMACS_INT) p %
4057 #ifdef USE_LSB_TAG
4058 8 /* USE_LSB_TAG needs Lisp data to be aligned on multiples of 8. */
4059 #else
4060 2 /* We assume that Lisp data is aligned on even addresses. */
4061 #endif
4063 return;
4065 m = mem_find (p);
4066 if (m != MEM_NIL)
4068 Lisp_Object obj = Qnil;
4070 switch (m->type)
4072 case MEM_TYPE_NON_LISP:
4073 /* Nothing to do; not a pointer to Lisp memory. */
4074 break;
4076 case MEM_TYPE_BUFFER:
4077 if (live_buffer_p (m, p) && !VECTOR_MARKED_P((struct buffer *)p))
4078 XSETVECTOR (obj, p);
4079 break;
4081 case MEM_TYPE_CONS:
4082 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4083 XSETCONS (obj, p);
4084 break;
4086 case MEM_TYPE_STRING:
4087 if (live_string_p (m, p)
4088 && !STRING_MARKED_P ((struct Lisp_String *) p))
4089 XSETSTRING (obj, p);
4090 break;
4092 case MEM_TYPE_MISC:
4093 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4094 XSETMISC (obj, p);
4095 break;
4097 case MEM_TYPE_SYMBOL:
4098 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4099 XSETSYMBOL (obj, p);
4100 break;
4102 case MEM_TYPE_FLOAT:
4103 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4104 XSETFLOAT (obj, p);
4105 break;
4107 case MEM_TYPE_VECTORLIKE:
4108 if (live_vector_p (m, p))
4110 Lisp_Object tem;
4111 XSETVECTOR (tem, p);
4112 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4113 obj = tem;
4115 break;
4117 default:
4118 abort ();
4121 if (!NILP (obj))
4122 mark_object (obj);
4127 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4128 or END+OFFSET..START. */
4130 static void
4131 mark_memory (void *start, void *end, int offset)
4133 Lisp_Object *p;
4134 void **pp;
4136 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4137 nzombies = 0;
4138 #endif
4140 /* Make START the pointer to the start of the memory region,
4141 if it isn't already. */
4142 if (end < start)
4144 void *tem = start;
4145 start = end;
4146 end = tem;
4149 /* Mark Lisp_Objects. */
4150 for (p = (Lisp_Object *) ((char *) start + offset); (void *) p < end; ++p)
4151 mark_maybe_object (*p);
4153 /* Mark Lisp data pointed to. This is necessary because, in some
4154 situations, the C compiler optimizes Lisp objects away, so that
4155 only a pointer to them remains. Example:
4157 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4160 Lisp_Object obj = build_string ("test");
4161 struct Lisp_String *s = XSTRING (obj);
4162 Fgarbage_collect ();
4163 fprintf (stderr, "test `%s'\n", s->data);
4164 return Qnil;
4167 Here, `obj' isn't really used, and the compiler optimizes it
4168 away. The only reference to the life string is through the
4169 pointer `s'. */
4171 for (pp = (void **) ((char *) start + offset); (void *) pp < end; ++pp)
4172 mark_maybe_pointer (*pp);
4175 /* setjmp will work with GCC unless NON_SAVING_SETJMP is defined in
4176 the GCC system configuration. In gcc 3.2, the only systems for
4177 which this is so are i386-sco5 non-ELF, i386-sysv3 (maybe included
4178 by others?) and ns32k-pc532-min. */
4180 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4182 static int setjmp_tested_p, longjmps_done;
4184 #define SETJMP_WILL_LIKELY_WORK "\
4186 Emacs garbage collector has been changed to use conservative stack\n\
4187 marking. Emacs has determined that the method it uses to do the\n\
4188 marking will likely work on your system, but this isn't sure.\n\
4190 If you are a system-programmer, or can get the help of a local wizard\n\
4191 who is, please take a look at the function mark_stack in alloc.c, and\n\
4192 verify that the methods used are appropriate for your system.\n\
4194 Please mail the result to <emacs-devel@gnu.org>.\n\
4197 #define SETJMP_WILL_NOT_WORK "\
4199 Emacs garbage collector has been changed to use conservative stack\n\
4200 marking. Emacs has determined that the default method it uses to do the\n\
4201 marking will not work on your system. We will need a system-dependent\n\
4202 solution for your system.\n\
4204 Please take a look at the function mark_stack in alloc.c, and\n\
4205 try to find a way to make it work on your system.\n\
4207 Note that you may get false negatives, depending on the compiler.\n\
4208 In particular, you need to use -O with GCC for this test.\n\
4210 Please mail the result to <emacs-devel@gnu.org>.\n\
4214 /* Perform a quick check if it looks like setjmp saves registers in a
4215 jmp_buf. Print a message to stderr saying so. When this test
4216 succeeds, this is _not_ a proof that setjmp is sufficient for
4217 conservative stack marking. Only the sources or a disassembly
4218 can prove that. */
4220 static void
4221 test_setjmp ()
4223 char buf[10];
4224 register int x;
4225 jmp_buf jbuf;
4226 int result = 0;
4228 /* Arrange for X to be put in a register. */
4229 sprintf (buf, "1");
4230 x = strlen (buf);
4231 x = 2 * x - 1;
4233 setjmp (jbuf);
4234 if (longjmps_done == 1)
4236 /* Came here after the longjmp at the end of the function.
4238 If x == 1, the longjmp has restored the register to its
4239 value before the setjmp, and we can hope that setjmp
4240 saves all such registers in the jmp_buf, although that
4241 isn't sure.
4243 For other values of X, either something really strange is
4244 taking place, or the setjmp just didn't save the register. */
4246 if (x == 1)
4247 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4248 else
4250 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4251 exit (1);
4255 ++longjmps_done;
4256 x = 2;
4257 if (longjmps_done == 1)
4258 longjmp (jbuf, 1);
4261 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4264 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4266 /* Abort if anything GCPRO'd doesn't survive the GC. */
4268 static void
4269 check_gcpros ()
4271 struct gcpro *p;
4272 int i;
4274 for (p = gcprolist; p; p = p->next)
4275 for (i = 0; i < p->nvars; ++i)
4276 if (!survives_gc_p (p->var[i]))
4277 /* FIXME: It's not necessarily a bug. It might just be that the
4278 GCPRO is unnecessary or should release the object sooner. */
4279 abort ();
4282 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4284 static void
4285 dump_zombies ()
4287 int i;
4289 fprintf (stderr, "\nZombies kept alive = %d:\n", nzombies);
4290 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
4292 fprintf (stderr, " %d = ", i);
4293 debug_print (zombies[i]);
4297 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4300 /* Mark live Lisp objects on the C stack.
4302 There are several system-dependent problems to consider when
4303 porting this to new architectures:
4305 Processor Registers
4307 We have to mark Lisp objects in CPU registers that can hold local
4308 variables or are used to pass parameters.
4310 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4311 something that either saves relevant registers on the stack, or
4312 calls mark_maybe_object passing it each register's contents.
4314 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4315 implementation assumes that calling setjmp saves registers we need
4316 to see in a jmp_buf which itself lies on the stack. This doesn't
4317 have to be true! It must be verified for each system, possibly
4318 by taking a look at the source code of setjmp.
4320 Stack Layout
4322 Architectures differ in the way their processor stack is organized.
4323 For example, the stack might look like this
4325 +----------------+
4326 | Lisp_Object | size = 4
4327 +----------------+
4328 | something else | size = 2
4329 +----------------+
4330 | Lisp_Object | size = 4
4331 +----------------+
4332 | ... |
4334 In such a case, not every Lisp_Object will be aligned equally. To
4335 find all Lisp_Object on the stack it won't be sufficient to walk
4336 the stack in steps of 4 bytes. Instead, two passes will be
4337 necessary, one starting at the start of the stack, and a second
4338 pass starting at the start of the stack + 2. Likewise, if the
4339 minimal alignment of Lisp_Objects on the stack is 1, four passes
4340 would be necessary, each one starting with one byte more offset
4341 from the stack start.
4343 The current code assumes by default that Lisp_Objects are aligned
4344 equally on the stack. */
4346 static void
4347 mark_stack (void)
4349 int i;
4350 /* jmp_buf may not be aligned enough on darwin-ppc64 */
4351 union aligned_jmpbuf {
4352 Lisp_Object o;
4353 jmp_buf j;
4354 } j;
4355 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
4356 void *end;
4358 /* This trick flushes the register windows so that all the state of
4359 the process is contained in the stack. */
4360 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
4361 needed on ia64 too. See mach_dep.c, where it also says inline
4362 assembler doesn't work with relevant proprietary compilers. */
4363 #ifdef __sparc__
4364 #if defined (__sparc64__) && defined (__FreeBSD__)
4365 /* FreeBSD does not have a ta 3 handler. */
4366 asm ("flushw");
4367 #else
4368 asm ("ta 3");
4369 #endif
4370 #endif
4372 /* Save registers that we need to see on the stack. We need to see
4373 registers used to hold register variables and registers used to
4374 pass parameters. */
4375 #ifdef GC_SAVE_REGISTERS_ON_STACK
4376 GC_SAVE_REGISTERS_ON_STACK (end);
4377 #else /* not GC_SAVE_REGISTERS_ON_STACK */
4379 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
4380 setjmp will definitely work, test it
4381 and print a message with the result
4382 of the test. */
4383 if (!setjmp_tested_p)
4385 setjmp_tested_p = 1;
4386 test_setjmp ();
4388 #endif /* GC_SETJMP_WORKS */
4390 setjmp (j.j);
4391 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
4392 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
4394 /* This assumes that the stack is a contiguous region in memory. If
4395 that's not the case, something has to be done here to iterate
4396 over the stack segments. */
4397 #ifndef GC_LISP_OBJECT_ALIGNMENT
4398 #ifdef __GNUC__
4399 #define GC_LISP_OBJECT_ALIGNMENT __alignof__ (Lisp_Object)
4400 #else
4401 #define GC_LISP_OBJECT_ALIGNMENT sizeof (Lisp_Object)
4402 #endif
4403 #endif
4404 for (i = 0; i < sizeof (Lisp_Object); i += GC_LISP_OBJECT_ALIGNMENT)
4405 mark_memory (stack_base, end, i);
4406 /* Allow for marking a secondary stack, like the register stack on the
4407 ia64. */
4408 #ifdef GC_MARK_SECONDARY_STACK
4409 GC_MARK_SECONDARY_STACK ();
4410 #endif
4412 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4413 check_gcpros ();
4414 #endif
4417 #endif /* GC_MARK_STACK != 0 */
4420 /* Determine whether it is safe to access memory at address P. */
4421 static int
4422 valid_pointer_p (void *p)
4424 #ifdef WINDOWSNT
4425 return w32_valid_pointer_p (p, 16);
4426 #else
4427 int fd;
4429 /* Obviously, we cannot just access it (we would SEGV trying), so we
4430 trick the o/s to tell us whether p is a valid pointer.
4431 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4432 not validate p in that case. */
4434 if ((fd = emacs_open ("__Valid__Lisp__Object__", O_CREAT | O_WRONLY | O_TRUNC, 0666)) >= 0)
4436 int valid = (emacs_write (fd, (char *)p, 16) == 16);
4437 emacs_close (fd);
4438 unlink ("__Valid__Lisp__Object__");
4439 return valid;
4442 return -1;
4443 #endif
4446 /* Return 1 if OBJ is a valid lisp object.
4447 Return 0 if OBJ is NOT a valid lisp object.
4448 Return -1 if we cannot validate OBJ.
4449 This function can be quite slow,
4450 so it should only be used in code for manual debugging. */
4453 valid_lisp_object_p (Lisp_Object obj)
4455 void *p;
4456 #if GC_MARK_STACK
4457 struct mem_node *m;
4458 #endif
4460 if (INTEGERP (obj))
4461 return 1;
4463 p = (void *) XPNTR (obj);
4464 if (PURE_POINTER_P (p))
4465 return 1;
4467 #if !GC_MARK_STACK
4468 return valid_pointer_p (p);
4469 #else
4471 m = mem_find (p);
4473 if (m == MEM_NIL)
4475 int valid = valid_pointer_p (p);
4476 if (valid <= 0)
4477 return valid;
4479 if (SUBRP (obj))
4480 return 1;
4482 return 0;
4485 switch (m->type)
4487 case MEM_TYPE_NON_LISP:
4488 return 0;
4490 case MEM_TYPE_BUFFER:
4491 return live_buffer_p (m, p);
4493 case MEM_TYPE_CONS:
4494 return live_cons_p (m, p);
4496 case MEM_TYPE_STRING:
4497 return live_string_p (m, p);
4499 case MEM_TYPE_MISC:
4500 return live_misc_p (m, p);
4502 case MEM_TYPE_SYMBOL:
4503 return live_symbol_p (m, p);
4505 case MEM_TYPE_FLOAT:
4506 return live_float_p (m, p);
4508 case MEM_TYPE_VECTORLIKE:
4509 return live_vector_p (m, p);
4511 default:
4512 break;
4515 return 0;
4516 #endif
4522 /***********************************************************************
4523 Pure Storage Management
4524 ***********************************************************************/
4526 /* Allocate room for SIZE bytes from pure Lisp storage and return a
4527 pointer to it. TYPE is the Lisp type for which the memory is
4528 allocated. TYPE < 0 means it's not used for a Lisp object. */
4530 static POINTER_TYPE *
4531 pure_alloc (size_t size, int type)
4533 POINTER_TYPE *result;
4534 #ifdef USE_LSB_TAG
4535 size_t alignment = (1 << GCTYPEBITS);
4536 #else
4537 size_t alignment = sizeof (EMACS_INT);
4539 /* Give Lisp_Floats an extra alignment. */
4540 if (type == Lisp_Float)
4542 #if defined __GNUC__ && __GNUC__ >= 2
4543 alignment = __alignof (struct Lisp_Float);
4544 #else
4545 alignment = sizeof (struct Lisp_Float);
4546 #endif
4548 #endif
4550 again:
4551 if (type >= 0)
4553 /* Allocate space for a Lisp object from the beginning of the free
4554 space with taking account of alignment. */
4555 result = ALIGN (purebeg + pure_bytes_used_lisp, alignment);
4556 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
4558 else
4560 /* Allocate space for a non-Lisp object from the end of the free
4561 space. */
4562 pure_bytes_used_non_lisp += size;
4563 result = purebeg + pure_size - pure_bytes_used_non_lisp;
4565 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
4567 if (pure_bytes_used <= pure_size)
4568 return result;
4570 /* Don't allocate a large amount here,
4571 because it might get mmap'd and then its address
4572 might not be usable. */
4573 purebeg = (char *) xmalloc (10000);
4574 pure_size = 10000;
4575 pure_bytes_used_before_overflow += pure_bytes_used - size;
4576 pure_bytes_used = 0;
4577 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
4578 goto again;
4582 /* Print a warning if PURESIZE is too small. */
4584 void
4585 check_pure_size (void)
4587 if (pure_bytes_used_before_overflow)
4588 message ("emacs:0:Pure Lisp storage overflow (approx. %d bytes needed)",
4589 (int) (pure_bytes_used + pure_bytes_used_before_overflow));
4593 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
4594 the non-Lisp data pool of the pure storage, and return its start
4595 address. Return NULL if not found. */
4597 static char *
4598 find_string_data_in_pure (const char *data, EMACS_INT nbytes)
4600 int i;
4601 EMACS_INT skip, bm_skip[256], last_char_skip, infinity, start, start_max;
4602 const unsigned char *p;
4603 char *non_lisp_beg;
4605 if (pure_bytes_used_non_lisp < nbytes + 1)
4606 return NULL;
4608 /* Set up the Boyer-Moore table. */
4609 skip = nbytes + 1;
4610 for (i = 0; i < 256; i++)
4611 bm_skip[i] = skip;
4613 p = (const unsigned char *) data;
4614 while (--skip > 0)
4615 bm_skip[*p++] = skip;
4617 last_char_skip = bm_skip['\0'];
4619 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
4620 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
4622 /* See the comments in the function `boyer_moore' (search.c) for the
4623 use of `infinity'. */
4624 infinity = pure_bytes_used_non_lisp + 1;
4625 bm_skip['\0'] = infinity;
4627 p = (const unsigned char *) non_lisp_beg + nbytes;
4628 start = 0;
4631 /* Check the last character (== '\0'). */
4634 start += bm_skip[*(p + start)];
4636 while (start <= start_max);
4638 if (start < infinity)
4639 /* Couldn't find the last character. */
4640 return NULL;
4642 /* No less than `infinity' means we could find the last
4643 character at `p[start - infinity]'. */
4644 start -= infinity;
4646 /* Check the remaining characters. */
4647 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
4648 /* Found. */
4649 return non_lisp_beg + start;
4651 start += last_char_skip;
4653 while (start <= start_max);
4655 return NULL;
4659 /* Return a string allocated in pure space. DATA is a buffer holding
4660 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
4661 non-zero means make the result string multibyte.
4663 Must get an error if pure storage is full, since if it cannot hold
4664 a large string it may be able to hold conses that point to that
4665 string; then the string is not protected from gc. */
4667 Lisp_Object
4668 make_pure_string (const char *data,
4669 EMACS_INT nchars, EMACS_INT nbytes, int multibyte)
4671 Lisp_Object string;
4672 struct Lisp_String *s;
4674 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
4675 s->data = find_string_data_in_pure (data, nbytes);
4676 if (s->data == NULL)
4678 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
4679 memcpy (s->data, data, nbytes);
4680 s->data[nbytes] = '\0';
4682 s->size = nchars;
4683 s->size_byte = multibyte ? nbytes : -1;
4684 s->intervals = NULL_INTERVAL;
4685 XSETSTRING (string, s);
4686 return string;
4689 /* Return a string a string allocated in pure space. Do not allocate
4690 the string data, just point to DATA. */
4692 Lisp_Object
4693 make_pure_c_string (const char *data)
4695 Lisp_Object string;
4696 struct Lisp_String *s;
4697 EMACS_INT nchars = strlen (data);
4699 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
4700 s->size = nchars;
4701 s->size_byte = -1;
4702 s->data = (unsigned char *) data;
4703 s->intervals = NULL_INTERVAL;
4704 XSETSTRING (string, s);
4705 return string;
4708 /* Return a cons allocated from pure space. Give it pure copies
4709 of CAR as car and CDR as cdr. */
4711 Lisp_Object
4712 pure_cons (Lisp_Object car, Lisp_Object cdr)
4714 register Lisp_Object new;
4715 struct Lisp_Cons *p;
4717 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
4718 XSETCONS (new, p);
4719 XSETCAR (new, Fpurecopy (car));
4720 XSETCDR (new, Fpurecopy (cdr));
4721 return new;
4725 /* Value is a float object with value NUM allocated from pure space. */
4727 static Lisp_Object
4728 make_pure_float (double num)
4730 register Lisp_Object new;
4731 struct Lisp_Float *p;
4733 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
4734 XSETFLOAT (new, p);
4735 XFLOAT_INIT (new, num);
4736 return new;
4740 /* Return a vector with room for LEN Lisp_Objects allocated from
4741 pure space. */
4743 Lisp_Object
4744 make_pure_vector (EMACS_INT len)
4746 Lisp_Object new;
4747 struct Lisp_Vector *p;
4748 size_t size = sizeof *p + (len - 1) * sizeof (Lisp_Object);
4750 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
4751 XSETVECTOR (new, p);
4752 XVECTOR (new)->size = len;
4753 return new;
4757 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
4758 doc: /* Make a copy of object OBJ in pure storage.
4759 Recursively copies contents of vectors and cons cells.
4760 Does not copy symbols. Copies strings without text properties. */)
4761 (register Lisp_Object obj)
4763 if (NILP (Vpurify_flag))
4764 return obj;
4766 if (PURE_POINTER_P (XPNTR (obj)))
4767 return obj;
4769 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
4771 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
4772 if (!NILP (tmp))
4773 return tmp;
4776 if (CONSP (obj))
4777 obj = pure_cons (XCAR (obj), XCDR (obj));
4778 else if (FLOATP (obj))
4779 obj = make_pure_float (XFLOAT_DATA (obj));
4780 else if (STRINGP (obj))
4781 obj = make_pure_string (SDATA (obj), SCHARS (obj),
4782 SBYTES (obj),
4783 STRING_MULTIBYTE (obj));
4784 else if (COMPILEDP (obj) || VECTORP (obj))
4786 register struct Lisp_Vector *vec;
4787 register EMACS_INT i;
4788 EMACS_INT size;
4790 size = XVECTOR (obj)->size;
4791 if (size & PSEUDOVECTOR_FLAG)
4792 size &= PSEUDOVECTOR_SIZE_MASK;
4793 vec = XVECTOR (make_pure_vector (size));
4794 for (i = 0; i < size; i++)
4795 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
4796 if (COMPILEDP (obj))
4798 XSETPVECTYPE (vec, PVEC_COMPILED);
4799 XSETCOMPILED (obj, vec);
4801 else
4802 XSETVECTOR (obj, vec);
4804 else if (MARKERP (obj))
4805 error ("Attempt to copy a marker to pure storage");
4806 else
4807 /* Not purified, don't hash-cons. */
4808 return obj;
4810 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
4811 Fputhash (obj, obj, Vpurify_flag);
4813 return obj;
4818 /***********************************************************************
4819 Protection from GC
4820 ***********************************************************************/
4822 /* Put an entry in staticvec, pointing at the variable with address
4823 VARADDRESS. */
4825 void
4826 staticpro (Lisp_Object *varaddress)
4828 staticvec[staticidx++] = varaddress;
4829 if (staticidx >= NSTATICS)
4830 abort ();
4834 /***********************************************************************
4835 Protection from GC
4836 ***********************************************************************/
4838 /* Temporarily prevent garbage collection. */
4841 inhibit_garbage_collection (void)
4843 int count = SPECPDL_INDEX ();
4844 int nbits = min (VALBITS, BITS_PER_INT);
4846 specbind (Qgc_cons_threshold, make_number (((EMACS_INT) 1 << (nbits - 1)) - 1));
4847 return count;
4851 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
4852 doc: /* Reclaim storage for Lisp objects no longer needed.
4853 Garbage collection happens automatically if you cons more than
4854 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
4855 `garbage-collect' normally returns a list with info on amount of space in use:
4856 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
4857 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
4858 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)
4859 (USED-STRINGS . FREE-STRINGS))
4860 However, if there was overflow in pure space, `garbage-collect'
4861 returns nil, because real GC can't be done. */)
4862 (void)
4864 register struct specbinding *bind;
4865 struct catchtag *catch;
4866 struct handler *handler;
4867 char stack_top_variable;
4868 register int i;
4869 int message_p;
4870 Lisp_Object total[8];
4871 int count = SPECPDL_INDEX ();
4872 EMACS_TIME t1, t2, t3;
4874 if (abort_on_gc)
4875 abort ();
4877 /* Can't GC if pure storage overflowed because we can't determine
4878 if something is a pure object or not. */
4879 if (pure_bytes_used_before_overflow)
4880 return Qnil;
4882 CHECK_CONS_LIST ();
4884 /* Don't keep undo information around forever.
4885 Do this early on, so it is no problem if the user quits. */
4887 register struct buffer *nextb = all_buffers;
4889 while (nextb)
4891 /* If a buffer's undo list is Qt, that means that undo is
4892 turned off in that buffer. Calling truncate_undo_list on
4893 Qt tends to return NULL, which effectively turns undo back on.
4894 So don't call truncate_undo_list if undo_list is Qt. */
4895 if (! NILP (nextb->name) && ! EQ (nextb->undo_list, Qt))
4896 truncate_undo_list (nextb);
4898 /* Shrink buffer gaps, but skip indirect and dead buffers. */
4899 if (nextb->base_buffer == 0 && !NILP (nextb->name)
4900 && ! nextb->text->inhibit_shrinking)
4902 /* If a buffer's gap size is more than 10% of the buffer
4903 size, or larger than 2000 bytes, then shrink it
4904 accordingly. Keep a minimum size of 20 bytes. */
4905 int size = min (2000, max (20, (nextb->text->z_byte / 10)));
4907 if (nextb->text->gap_size > size)
4909 struct buffer *save_current = current_buffer;
4910 current_buffer = nextb;
4911 make_gap (-(nextb->text->gap_size - size));
4912 current_buffer = save_current;
4916 nextb = nextb->next;
4920 EMACS_GET_TIME (t1);
4922 /* In case user calls debug_print during GC,
4923 don't let that cause a recursive GC. */
4924 consing_since_gc = 0;
4926 /* Save what's currently displayed in the echo area. */
4927 message_p = push_message ();
4928 record_unwind_protect (pop_message_unwind, Qnil);
4930 /* Save a copy of the contents of the stack, for debugging. */
4931 #if MAX_SAVE_STACK > 0
4932 if (NILP (Vpurify_flag))
4934 i = &stack_top_variable - stack_bottom;
4935 if (i < 0) i = -i;
4936 if (i < MAX_SAVE_STACK)
4938 if (stack_copy == 0)
4939 stack_copy = (char *) xmalloc (stack_copy_size = i);
4940 else if (stack_copy_size < i)
4941 stack_copy = (char *) xrealloc (stack_copy, (stack_copy_size = i));
4942 if (stack_copy)
4944 if ((EMACS_INT) (&stack_top_variable - stack_bottom) > 0)
4945 memcpy (stack_copy, stack_bottom, i);
4946 else
4947 memcpy (stack_copy, &stack_top_variable, i);
4951 #endif /* MAX_SAVE_STACK > 0 */
4953 if (garbage_collection_messages)
4954 message1_nolog ("Garbage collecting...");
4956 BLOCK_INPUT;
4958 shrink_regexp_cache ();
4960 gc_in_progress = 1;
4962 /* clear_marks (); */
4964 /* Mark all the special slots that serve as the roots of accessibility. */
4966 for (i = 0; i < staticidx; i++)
4967 mark_object (*staticvec[i]);
4969 for (bind = specpdl; bind != specpdl_ptr; bind++)
4971 mark_object (bind->symbol);
4972 mark_object (bind->old_value);
4974 mark_terminals ();
4975 mark_kboards ();
4976 mark_ttys ();
4978 #ifdef USE_GTK
4980 extern void xg_mark_data (void);
4981 xg_mark_data ();
4983 #endif
4985 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
4986 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
4987 mark_stack ();
4988 #else
4990 register struct gcpro *tail;
4991 for (tail = gcprolist; tail; tail = tail->next)
4992 for (i = 0; i < tail->nvars; i++)
4993 mark_object (tail->var[i]);
4995 #endif
4997 mark_byte_stack ();
4998 for (catch = catchlist; catch; catch = catch->next)
5000 mark_object (catch->tag);
5001 mark_object (catch->val);
5003 for (handler = handlerlist; handler; handler = handler->next)
5005 mark_object (handler->handler);
5006 mark_object (handler->var);
5008 mark_backtrace ();
5010 #ifdef HAVE_WINDOW_SYSTEM
5011 mark_fringe_data ();
5012 #endif
5014 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5015 mark_stack ();
5016 #endif
5018 /* Everything is now marked, except for the things that require special
5019 finalization, i.e. the undo_list.
5020 Look thru every buffer's undo list
5021 for elements that update markers that were not marked,
5022 and delete them. */
5024 register struct buffer *nextb = all_buffers;
5026 while (nextb)
5028 /* If a buffer's undo list is Qt, that means that undo is
5029 turned off in that buffer. Calling truncate_undo_list on
5030 Qt tends to return NULL, which effectively turns undo back on.
5031 So don't call truncate_undo_list if undo_list is Qt. */
5032 if (! EQ (nextb->undo_list, Qt))
5034 Lisp_Object tail, prev;
5035 tail = nextb->undo_list;
5036 prev = Qnil;
5037 while (CONSP (tail))
5039 if (CONSP (XCAR (tail))
5040 && MARKERP (XCAR (XCAR (tail)))
5041 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5043 if (NILP (prev))
5044 nextb->undo_list = tail = XCDR (tail);
5045 else
5047 tail = XCDR (tail);
5048 XSETCDR (prev, tail);
5051 else
5053 prev = tail;
5054 tail = XCDR (tail);
5058 /* Now that we have stripped the elements that need not be in the
5059 undo_list any more, we can finally mark the list. */
5060 mark_object (nextb->undo_list);
5062 nextb = nextb->next;
5066 gc_sweep ();
5068 /* Clear the mark bits that we set in certain root slots. */
5070 unmark_byte_stack ();
5071 VECTOR_UNMARK (&buffer_defaults);
5072 VECTOR_UNMARK (&buffer_local_symbols);
5074 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
5075 dump_zombies ();
5076 #endif
5078 UNBLOCK_INPUT;
5080 CHECK_CONS_LIST ();
5082 /* clear_marks (); */
5083 gc_in_progress = 0;
5085 consing_since_gc = 0;
5086 if (gc_cons_threshold < 10000)
5087 gc_cons_threshold = 10000;
5089 if (FLOATP (Vgc_cons_percentage))
5090 { /* Set gc_cons_combined_threshold. */
5091 EMACS_INT total = 0;
5093 total += total_conses * sizeof (struct Lisp_Cons);
5094 total += total_symbols * sizeof (struct Lisp_Symbol);
5095 total += total_markers * sizeof (union Lisp_Misc);
5096 total += total_string_size;
5097 total += total_vector_size * sizeof (Lisp_Object);
5098 total += total_floats * sizeof (struct Lisp_Float);
5099 total += total_intervals * sizeof (struct interval);
5100 total += total_strings * sizeof (struct Lisp_String);
5102 gc_relative_threshold = total * XFLOAT_DATA (Vgc_cons_percentage);
5104 else
5105 gc_relative_threshold = 0;
5107 if (garbage_collection_messages)
5109 if (message_p || minibuf_level > 0)
5110 restore_message ();
5111 else
5112 message1_nolog ("Garbage collecting...done");
5115 unbind_to (count, Qnil);
5117 total[0] = Fcons (make_number (total_conses),
5118 make_number (total_free_conses));
5119 total[1] = Fcons (make_number (total_symbols),
5120 make_number (total_free_symbols));
5121 total[2] = Fcons (make_number (total_markers),
5122 make_number (total_free_markers));
5123 total[3] = make_number (total_string_size);
5124 total[4] = make_number (total_vector_size);
5125 total[5] = Fcons (make_number (total_floats),
5126 make_number (total_free_floats));
5127 total[6] = Fcons (make_number (total_intervals),
5128 make_number (total_free_intervals));
5129 total[7] = Fcons (make_number (total_strings),
5130 make_number (total_free_strings));
5132 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5134 /* Compute average percentage of zombies. */
5135 double nlive = 0;
5137 for (i = 0; i < 7; ++i)
5138 if (CONSP (total[i]))
5139 nlive += XFASTINT (XCAR (total[i]));
5141 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
5142 max_live = max (nlive, max_live);
5143 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
5144 max_zombies = max (nzombies, max_zombies);
5145 ++ngcs;
5147 #endif
5149 if (!NILP (Vpost_gc_hook))
5151 int count = inhibit_garbage_collection ();
5152 safe_run_hooks (Qpost_gc_hook);
5153 unbind_to (count, Qnil);
5156 /* Accumulate statistics. */
5157 EMACS_GET_TIME (t2);
5158 EMACS_SUB_TIME (t3, t2, t1);
5159 if (FLOATP (Vgc_elapsed))
5160 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed) +
5161 EMACS_SECS (t3) +
5162 EMACS_USECS (t3) * 1.0e-6);
5163 gcs_done++;
5165 return Flist (sizeof total / sizeof *total, total);
5169 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5170 only interesting objects referenced from glyphs are strings. */
5172 static void
5173 mark_glyph_matrix (struct glyph_matrix *matrix)
5175 struct glyph_row *row = matrix->rows;
5176 struct glyph_row *end = row + matrix->nrows;
5178 for (; row < end; ++row)
5179 if (row->enabled_p)
5181 int area;
5182 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
5184 struct glyph *glyph = row->glyphs[area];
5185 struct glyph *end_glyph = glyph + row->used[area];
5187 for (; glyph < end_glyph; ++glyph)
5188 if (STRINGP (glyph->object)
5189 && !STRING_MARKED_P (XSTRING (glyph->object)))
5190 mark_object (glyph->object);
5196 /* Mark Lisp faces in the face cache C. */
5198 static void
5199 mark_face_cache (struct face_cache *c)
5201 if (c)
5203 int i, j;
5204 for (i = 0; i < c->used; ++i)
5206 struct face *face = FACE_FROM_ID (c->f, i);
5208 if (face)
5210 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
5211 mark_object (face->lface[j]);
5219 /* Mark reference to a Lisp_Object.
5220 If the object referred to has not been seen yet, recursively mark
5221 all the references contained in it. */
5223 #define LAST_MARKED_SIZE 500
5224 static Lisp_Object last_marked[LAST_MARKED_SIZE];
5225 int last_marked_index;
5227 /* For debugging--call abort when we cdr down this many
5228 links of a list, in mark_object. In debugging,
5229 the call to abort will hit a breakpoint.
5230 Normally this is zero and the check never goes off. */
5231 static int mark_object_loop_halt;
5233 static void
5234 mark_vectorlike (struct Lisp_Vector *ptr)
5236 register EMACS_UINT size = ptr->size;
5237 register EMACS_UINT i;
5239 eassert (!VECTOR_MARKED_P (ptr));
5240 VECTOR_MARK (ptr); /* Else mark it */
5241 if (size & PSEUDOVECTOR_FLAG)
5242 size &= PSEUDOVECTOR_SIZE_MASK;
5244 /* Note that this size is not the memory-footprint size, but only
5245 the number of Lisp_Object fields that we should trace.
5246 The distinction is used e.g. by Lisp_Process which places extra
5247 non-Lisp_Object fields at the end of the structure. */
5248 for (i = 0; i < size; i++) /* and then mark its elements */
5249 mark_object (ptr->contents[i]);
5252 /* Like mark_vectorlike but optimized for char-tables (and
5253 sub-char-tables) assuming that the contents are mostly integers or
5254 symbols. */
5256 static void
5257 mark_char_table (struct Lisp_Vector *ptr)
5259 register EMACS_UINT size = ptr->size & PSEUDOVECTOR_SIZE_MASK;
5260 register EMACS_UINT i;
5262 eassert (!VECTOR_MARKED_P (ptr));
5263 VECTOR_MARK (ptr);
5264 for (i = 0; i < size; i++)
5266 Lisp_Object val = ptr->contents[i];
5268 if (INTEGERP (val) || SYMBOLP (val) && XSYMBOL (val)->gcmarkbit)
5269 continue;
5270 if (SUB_CHAR_TABLE_P (val))
5272 if (! VECTOR_MARKED_P (XVECTOR (val)))
5273 mark_char_table (XVECTOR (val));
5275 else
5276 mark_object (val);
5280 void
5281 mark_object (Lisp_Object arg)
5283 register Lisp_Object obj = arg;
5284 #ifdef GC_CHECK_MARKED_OBJECTS
5285 void *po;
5286 struct mem_node *m;
5287 #endif
5288 int cdr_count = 0;
5290 loop:
5292 if (PURE_POINTER_P (XPNTR (obj)))
5293 return;
5295 last_marked[last_marked_index++] = obj;
5296 if (last_marked_index == LAST_MARKED_SIZE)
5297 last_marked_index = 0;
5299 /* Perform some sanity checks on the objects marked here. Abort if
5300 we encounter an object we know is bogus. This increases GC time
5301 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
5302 #ifdef GC_CHECK_MARKED_OBJECTS
5304 po = (void *) XPNTR (obj);
5306 /* Check that the object pointed to by PO is known to be a Lisp
5307 structure allocated from the heap. */
5308 #define CHECK_ALLOCATED() \
5309 do { \
5310 m = mem_find (po); \
5311 if (m == MEM_NIL) \
5312 abort (); \
5313 } while (0)
5315 /* Check that the object pointed to by PO is live, using predicate
5316 function LIVEP. */
5317 #define CHECK_LIVE(LIVEP) \
5318 do { \
5319 if (!LIVEP (m, po)) \
5320 abort (); \
5321 } while (0)
5323 /* Check both of the above conditions. */
5324 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
5325 do { \
5326 CHECK_ALLOCATED (); \
5327 CHECK_LIVE (LIVEP); \
5328 } while (0) \
5330 #else /* not GC_CHECK_MARKED_OBJECTS */
5332 #define CHECK_ALLOCATED() (void) 0
5333 #define CHECK_LIVE(LIVEP) (void) 0
5334 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
5336 #endif /* not GC_CHECK_MARKED_OBJECTS */
5338 switch (SWITCH_ENUM_CAST (XTYPE (obj)))
5340 case Lisp_String:
5342 register struct Lisp_String *ptr = XSTRING (obj);
5343 if (STRING_MARKED_P (ptr))
5344 break;
5345 CHECK_ALLOCATED_AND_LIVE (live_string_p);
5346 MARK_INTERVAL_TREE (ptr->intervals);
5347 MARK_STRING (ptr);
5348 #ifdef GC_CHECK_STRING_BYTES
5349 /* Check that the string size recorded in the string is the
5350 same as the one recorded in the sdata structure. */
5351 CHECK_STRING_BYTES (ptr);
5352 #endif /* GC_CHECK_STRING_BYTES */
5354 break;
5356 case Lisp_Vectorlike:
5357 if (VECTOR_MARKED_P (XVECTOR (obj)))
5358 break;
5359 #ifdef GC_CHECK_MARKED_OBJECTS
5360 m = mem_find (po);
5361 if (m == MEM_NIL && !SUBRP (obj)
5362 && po != &buffer_defaults
5363 && po != &buffer_local_symbols)
5364 abort ();
5365 #endif /* GC_CHECK_MARKED_OBJECTS */
5367 if (BUFFERP (obj))
5369 #ifdef GC_CHECK_MARKED_OBJECTS
5370 if (po != &buffer_defaults && po != &buffer_local_symbols)
5372 struct buffer *b;
5373 for (b = all_buffers; b && b != po; b = b->next)
5375 if (b == NULL)
5376 abort ();
5378 #endif /* GC_CHECK_MARKED_OBJECTS */
5379 mark_buffer (obj);
5381 else if (SUBRP (obj))
5382 break;
5383 else if (COMPILEDP (obj))
5384 /* We could treat this just like a vector, but it is better to
5385 save the COMPILED_CONSTANTS element for last and avoid
5386 recursion there. */
5388 register struct Lisp_Vector *ptr = XVECTOR (obj);
5389 register EMACS_UINT size = ptr->size;
5390 register EMACS_UINT i;
5392 CHECK_LIVE (live_vector_p);
5393 VECTOR_MARK (ptr); /* Else mark it */
5394 size &= PSEUDOVECTOR_SIZE_MASK;
5395 for (i = 0; i < size; i++) /* and then mark its elements */
5397 if (i != COMPILED_CONSTANTS)
5398 mark_object (ptr->contents[i]);
5400 obj = ptr->contents[COMPILED_CONSTANTS];
5401 goto loop;
5403 else if (FRAMEP (obj))
5405 register struct frame *ptr = XFRAME (obj);
5406 mark_vectorlike (XVECTOR (obj));
5407 mark_face_cache (ptr->face_cache);
5409 else if (WINDOWP (obj))
5411 register struct Lisp_Vector *ptr = XVECTOR (obj);
5412 struct window *w = XWINDOW (obj);
5413 mark_vectorlike (ptr);
5414 /* Mark glyphs for leaf windows. Marking window matrices is
5415 sufficient because frame matrices use the same glyph
5416 memory. */
5417 if (NILP (w->hchild)
5418 && NILP (w->vchild)
5419 && w->current_matrix)
5421 mark_glyph_matrix (w->current_matrix);
5422 mark_glyph_matrix (w->desired_matrix);
5425 else if (HASH_TABLE_P (obj))
5427 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
5428 mark_vectorlike ((struct Lisp_Vector *)h);
5429 /* If hash table is not weak, mark all keys and values.
5430 For weak tables, mark only the vector. */
5431 if (NILP (h->weak))
5432 mark_object (h->key_and_value);
5433 else
5434 VECTOR_MARK (XVECTOR (h->key_and_value));
5436 else if (CHAR_TABLE_P (obj))
5437 mark_char_table (XVECTOR (obj));
5438 else
5439 mark_vectorlike (XVECTOR (obj));
5440 break;
5442 case Lisp_Symbol:
5444 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
5445 struct Lisp_Symbol *ptrx;
5447 if (ptr->gcmarkbit)
5448 break;
5449 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
5450 ptr->gcmarkbit = 1;
5451 mark_object (ptr->function);
5452 mark_object (ptr->plist);
5453 switch (ptr->redirect)
5455 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
5456 case SYMBOL_VARALIAS:
5458 Lisp_Object tem;
5459 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
5460 mark_object (tem);
5461 break;
5463 case SYMBOL_LOCALIZED:
5465 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
5466 /* If the value is forwarded to a buffer or keyboard field,
5467 these are marked when we see the corresponding object.
5468 And if it's forwarded to a C variable, either it's not
5469 a Lisp_Object var, or it's staticpro'd already. */
5470 mark_object (blv->where);
5471 mark_object (blv->valcell);
5472 mark_object (blv->defcell);
5473 break;
5475 case SYMBOL_FORWARDED:
5476 /* If the value is forwarded to a buffer or keyboard field,
5477 these are marked when we see the corresponding object.
5478 And if it's forwarded to a C variable, either it's not
5479 a Lisp_Object var, or it's staticpro'd already. */
5480 break;
5481 default: abort ();
5483 if (!PURE_POINTER_P (XSTRING (ptr->xname)))
5484 MARK_STRING (XSTRING (ptr->xname));
5485 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr->xname));
5487 ptr = ptr->next;
5488 if (ptr)
5490 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
5491 XSETSYMBOL (obj, ptrx);
5492 goto loop;
5495 break;
5497 case Lisp_Misc:
5498 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
5499 if (XMISCANY (obj)->gcmarkbit)
5500 break;
5501 XMISCANY (obj)->gcmarkbit = 1;
5503 switch (XMISCTYPE (obj))
5506 case Lisp_Misc_Marker:
5507 /* DO NOT mark thru the marker's chain.
5508 The buffer's markers chain does not preserve markers from gc;
5509 instead, markers are removed from the chain when freed by gc. */
5510 break;
5512 case Lisp_Misc_Save_Value:
5513 #if GC_MARK_STACK
5515 register struct Lisp_Save_Value *ptr = XSAVE_VALUE (obj);
5516 /* If DOGC is set, POINTER is the address of a memory
5517 area containing INTEGER potential Lisp_Objects. */
5518 if (ptr->dogc)
5520 Lisp_Object *p = (Lisp_Object *) ptr->pointer;
5521 int nelt;
5522 for (nelt = ptr->integer; nelt > 0; nelt--, p++)
5523 mark_maybe_object (*p);
5526 #endif
5527 break;
5529 case Lisp_Misc_Overlay:
5531 struct Lisp_Overlay *ptr = XOVERLAY (obj);
5532 mark_object (ptr->start);
5533 mark_object (ptr->end);
5534 mark_object (ptr->plist);
5535 if (ptr->next)
5537 XSETMISC (obj, ptr->next);
5538 goto loop;
5541 break;
5543 default:
5544 abort ();
5546 break;
5548 case Lisp_Cons:
5550 register struct Lisp_Cons *ptr = XCONS (obj);
5551 if (CONS_MARKED_P (ptr))
5552 break;
5553 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
5554 CONS_MARK (ptr);
5555 /* If the cdr is nil, avoid recursion for the car. */
5556 if (EQ (ptr->u.cdr, Qnil))
5558 obj = ptr->car;
5559 cdr_count = 0;
5560 goto loop;
5562 mark_object (ptr->car);
5563 obj = ptr->u.cdr;
5564 cdr_count++;
5565 if (cdr_count == mark_object_loop_halt)
5566 abort ();
5567 goto loop;
5570 case Lisp_Float:
5571 CHECK_ALLOCATED_AND_LIVE (live_float_p);
5572 FLOAT_MARK (XFLOAT (obj));
5573 break;
5575 case_Lisp_Int:
5576 break;
5578 default:
5579 abort ();
5582 #undef CHECK_LIVE
5583 #undef CHECK_ALLOCATED
5584 #undef CHECK_ALLOCATED_AND_LIVE
5587 /* Mark the pointers in a buffer structure. */
5589 static void
5590 mark_buffer (Lisp_Object buf)
5592 register struct buffer *buffer = XBUFFER (buf);
5593 register Lisp_Object *ptr, tmp;
5594 Lisp_Object base_buffer;
5596 eassert (!VECTOR_MARKED_P (buffer));
5597 VECTOR_MARK (buffer);
5599 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
5601 /* For now, we just don't mark the undo_list. It's done later in
5602 a special way just before the sweep phase, and after stripping
5603 some of its elements that are not needed any more. */
5605 if (buffer->overlays_before)
5607 XSETMISC (tmp, buffer->overlays_before);
5608 mark_object (tmp);
5610 if (buffer->overlays_after)
5612 XSETMISC (tmp, buffer->overlays_after);
5613 mark_object (tmp);
5616 /* buffer-local Lisp variables start at `undo_list',
5617 tho only the ones from `name' on are GC'd normally. */
5618 for (ptr = &buffer->name;
5619 (char *)ptr < (char *)buffer + sizeof (struct buffer);
5620 ptr++)
5621 mark_object (*ptr);
5623 /* If this is an indirect buffer, mark its base buffer. */
5624 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5626 XSETBUFFER (base_buffer, buffer->base_buffer);
5627 mark_buffer (base_buffer);
5631 /* Mark the Lisp pointers in the terminal objects.
5632 Called by the Fgarbage_collector. */
5634 static void
5635 mark_terminals (void)
5637 struct terminal *t;
5638 for (t = terminal_list; t; t = t->next_terminal)
5640 eassert (t->name != NULL);
5641 if (!VECTOR_MARKED_P (t))
5643 #ifdef HAVE_WINDOW_SYSTEM
5644 mark_image_cache (t->image_cache);
5645 #endif /* HAVE_WINDOW_SYSTEM */
5646 mark_vectorlike ((struct Lisp_Vector *)t);
5653 /* Value is non-zero if OBJ will survive the current GC because it's
5654 either marked or does not need to be marked to survive. */
5657 survives_gc_p (Lisp_Object obj)
5659 int survives_p;
5661 switch (XTYPE (obj))
5663 case_Lisp_Int:
5664 survives_p = 1;
5665 break;
5667 case Lisp_Symbol:
5668 survives_p = XSYMBOL (obj)->gcmarkbit;
5669 break;
5671 case Lisp_Misc:
5672 survives_p = XMISCANY (obj)->gcmarkbit;
5673 break;
5675 case Lisp_String:
5676 survives_p = STRING_MARKED_P (XSTRING (obj));
5677 break;
5679 case Lisp_Vectorlike:
5680 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
5681 break;
5683 case Lisp_Cons:
5684 survives_p = CONS_MARKED_P (XCONS (obj));
5685 break;
5687 case Lisp_Float:
5688 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
5689 break;
5691 default:
5692 abort ();
5695 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
5700 /* Sweep: find all structures not marked, and free them. */
5702 static void
5703 gc_sweep (void)
5705 /* Remove or mark entries in weak hash tables.
5706 This must be done before any object is unmarked. */
5707 sweep_weak_hash_tables ();
5709 sweep_strings ();
5710 #ifdef GC_CHECK_STRING_BYTES
5711 if (!noninteractive)
5712 check_string_bytes (1);
5713 #endif
5715 /* Put all unmarked conses on free list */
5717 register struct cons_block *cblk;
5718 struct cons_block **cprev = &cons_block;
5719 register int lim = cons_block_index;
5720 register int num_free = 0, num_used = 0;
5722 cons_free_list = 0;
5724 for (cblk = cons_block; cblk; cblk = *cprev)
5726 register int i = 0;
5727 int this_free = 0;
5728 int ilim = (lim + BITS_PER_INT - 1) / BITS_PER_INT;
5730 /* Scan the mark bits an int at a time. */
5731 for (i = 0; i <= ilim; i++)
5733 if (cblk->gcmarkbits[i] == -1)
5735 /* Fast path - all cons cells for this int are marked. */
5736 cblk->gcmarkbits[i] = 0;
5737 num_used += BITS_PER_INT;
5739 else
5741 /* Some cons cells for this int are not marked.
5742 Find which ones, and free them. */
5743 int start, pos, stop;
5745 start = i * BITS_PER_INT;
5746 stop = lim - start;
5747 if (stop > BITS_PER_INT)
5748 stop = BITS_PER_INT;
5749 stop += start;
5751 for (pos = start; pos < stop; pos++)
5753 if (!CONS_MARKED_P (&cblk->conses[pos]))
5755 this_free++;
5756 cblk->conses[pos].u.chain = cons_free_list;
5757 cons_free_list = &cblk->conses[pos];
5758 #if GC_MARK_STACK
5759 cons_free_list->car = Vdead;
5760 #endif
5762 else
5764 num_used++;
5765 CONS_UNMARK (&cblk->conses[pos]);
5771 lim = CONS_BLOCK_SIZE;
5772 /* If this block contains only free conses and we have already
5773 seen more than two blocks worth of free conses then deallocate
5774 this block. */
5775 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
5777 *cprev = cblk->next;
5778 /* Unhook from the free list. */
5779 cons_free_list = cblk->conses[0].u.chain;
5780 lisp_align_free (cblk);
5781 n_cons_blocks--;
5783 else
5785 num_free += this_free;
5786 cprev = &cblk->next;
5789 total_conses = num_used;
5790 total_free_conses = num_free;
5793 /* Put all unmarked floats on free list */
5795 register struct float_block *fblk;
5796 struct float_block **fprev = &float_block;
5797 register int lim = float_block_index;
5798 register int num_free = 0, num_used = 0;
5800 float_free_list = 0;
5802 for (fblk = float_block; fblk; fblk = *fprev)
5804 register int i;
5805 int this_free = 0;
5806 for (i = 0; i < lim; i++)
5807 if (!FLOAT_MARKED_P (&fblk->floats[i]))
5809 this_free++;
5810 fblk->floats[i].u.chain = float_free_list;
5811 float_free_list = &fblk->floats[i];
5813 else
5815 num_used++;
5816 FLOAT_UNMARK (&fblk->floats[i]);
5818 lim = FLOAT_BLOCK_SIZE;
5819 /* If this block contains only free floats and we have already
5820 seen more than two blocks worth of free floats then deallocate
5821 this block. */
5822 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
5824 *fprev = fblk->next;
5825 /* Unhook from the free list. */
5826 float_free_list = fblk->floats[0].u.chain;
5827 lisp_align_free (fblk);
5828 n_float_blocks--;
5830 else
5832 num_free += this_free;
5833 fprev = &fblk->next;
5836 total_floats = num_used;
5837 total_free_floats = num_free;
5840 /* Put all unmarked intervals on free list */
5842 register struct interval_block *iblk;
5843 struct interval_block **iprev = &interval_block;
5844 register int lim = interval_block_index;
5845 register int num_free = 0, num_used = 0;
5847 interval_free_list = 0;
5849 for (iblk = interval_block; iblk; iblk = *iprev)
5851 register int i;
5852 int this_free = 0;
5854 for (i = 0; i < lim; i++)
5856 if (!iblk->intervals[i].gcmarkbit)
5858 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
5859 interval_free_list = &iblk->intervals[i];
5860 this_free++;
5862 else
5864 num_used++;
5865 iblk->intervals[i].gcmarkbit = 0;
5868 lim = INTERVAL_BLOCK_SIZE;
5869 /* If this block contains only free intervals and we have already
5870 seen more than two blocks worth of free intervals then
5871 deallocate this block. */
5872 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
5874 *iprev = iblk->next;
5875 /* Unhook from the free list. */
5876 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
5877 lisp_free (iblk);
5878 n_interval_blocks--;
5880 else
5882 num_free += this_free;
5883 iprev = &iblk->next;
5886 total_intervals = num_used;
5887 total_free_intervals = num_free;
5890 /* Put all unmarked symbols on free list */
5892 register struct symbol_block *sblk;
5893 struct symbol_block **sprev = &symbol_block;
5894 register int lim = symbol_block_index;
5895 register int num_free = 0, num_used = 0;
5897 symbol_free_list = NULL;
5899 for (sblk = symbol_block; sblk; sblk = *sprev)
5901 int this_free = 0;
5902 struct Lisp_Symbol *sym = sblk->symbols;
5903 struct Lisp_Symbol *end = sym + lim;
5905 for (; sym < end; ++sym)
5907 /* Check if the symbol was created during loadup. In such a case
5908 it might be pointed to by pure bytecode which we don't trace,
5909 so we conservatively assume that it is live. */
5910 int pure_p = PURE_POINTER_P (XSTRING (sym->xname));
5912 if (!sym->gcmarkbit && !pure_p)
5914 if (sym->redirect == SYMBOL_LOCALIZED)
5915 xfree (SYMBOL_BLV (sym));
5916 sym->next = symbol_free_list;
5917 symbol_free_list = sym;
5918 #if GC_MARK_STACK
5919 symbol_free_list->function = Vdead;
5920 #endif
5921 ++this_free;
5923 else
5925 ++num_used;
5926 if (!pure_p)
5927 UNMARK_STRING (XSTRING (sym->xname));
5928 sym->gcmarkbit = 0;
5932 lim = SYMBOL_BLOCK_SIZE;
5933 /* If this block contains only free symbols and we have already
5934 seen more than two blocks worth of free symbols then deallocate
5935 this block. */
5936 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
5938 *sprev = sblk->next;
5939 /* Unhook from the free list. */
5940 symbol_free_list = sblk->symbols[0].next;
5941 lisp_free (sblk);
5942 n_symbol_blocks--;
5944 else
5946 num_free += this_free;
5947 sprev = &sblk->next;
5950 total_symbols = num_used;
5951 total_free_symbols = num_free;
5954 /* Put all unmarked misc's on free list.
5955 For a marker, first unchain it from the buffer it points into. */
5957 register struct marker_block *mblk;
5958 struct marker_block **mprev = &marker_block;
5959 register int lim = marker_block_index;
5960 register int num_free = 0, num_used = 0;
5962 marker_free_list = 0;
5964 for (mblk = marker_block; mblk; mblk = *mprev)
5966 register int i;
5967 int this_free = 0;
5969 for (i = 0; i < lim; i++)
5971 if (!mblk->markers[i].u_any.gcmarkbit)
5973 if (mblk->markers[i].u_any.type == Lisp_Misc_Marker)
5974 unchain_marker (&mblk->markers[i].u_marker);
5975 /* Set the type of the freed object to Lisp_Misc_Free.
5976 We could leave the type alone, since nobody checks it,
5977 but this might catch bugs faster. */
5978 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
5979 mblk->markers[i].u_free.chain = marker_free_list;
5980 marker_free_list = &mblk->markers[i];
5981 this_free++;
5983 else
5985 num_used++;
5986 mblk->markers[i].u_any.gcmarkbit = 0;
5989 lim = MARKER_BLOCK_SIZE;
5990 /* If this block contains only free markers and we have already
5991 seen more than two blocks worth of free markers then deallocate
5992 this block. */
5993 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
5995 *mprev = mblk->next;
5996 /* Unhook from the free list. */
5997 marker_free_list = mblk->markers[0].u_free.chain;
5998 lisp_free (mblk);
5999 n_marker_blocks--;
6001 else
6003 num_free += this_free;
6004 mprev = &mblk->next;
6008 total_markers = num_used;
6009 total_free_markers = num_free;
6012 /* Free all unmarked buffers */
6014 register struct buffer *buffer = all_buffers, *prev = 0, *next;
6016 while (buffer)
6017 if (!VECTOR_MARKED_P (buffer))
6019 if (prev)
6020 prev->next = buffer->next;
6021 else
6022 all_buffers = buffer->next;
6023 next = buffer->next;
6024 lisp_free (buffer);
6025 buffer = next;
6027 else
6029 VECTOR_UNMARK (buffer);
6030 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
6031 prev = buffer, buffer = buffer->next;
6035 /* Free all unmarked vectors */
6037 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
6038 total_vector_size = 0;
6040 while (vector)
6041 if (!VECTOR_MARKED_P (vector))
6043 if (prev)
6044 prev->next = vector->next;
6045 else
6046 all_vectors = vector->next;
6047 next = vector->next;
6048 lisp_free (vector);
6049 n_vectors--;
6050 vector = next;
6053 else
6055 VECTOR_UNMARK (vector);
6056 if (vector->size & PSEUDOVECTOR_FLAG)
6057 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
6058 else
6059 total_vector_size += vector->size;
6060 prev = vector, vector = vector->next;
6064 #ifdef GC_CHECK_STRING_BYTES
6065 if (!noninteractive)
6066 check_string_bytes (1);
6067 #endif
6073 /* Debugging aids. */
6075 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
6076 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6077 This may be helpful in debugging Emacs's memory usage.
6078 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6079 (void)
6081 Lisp_Object end;
6083 XSETINT (end, (EMACS_INT) sbrk (0) / 1024);
6085 return end;
6088 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
6089 doc: /* Return a list of counters that measure how much consing there has been.
6090 Each of these counters increments for a certain kind of object.
6091 The counters wrap around from the largest positive integer to zero.
6092 Garbage collection does not decrease them.
6093 The elements of the value are as follows:
6094 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6095 All are in units of 1 = one object consed
6096 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6097 objects consed.
6098 MISCS include overlays, markers, and some internal types.
6099 Frames, windows, buffers, and subprocesses count as vectors
6100 (but the contents of a buffer's text do not count here). */)
6101 (void)
6103 Lisp_Object consed[8];
6105 consed[0] = make_number (min (MOST_POSITIVE_FIXNUM, cons_cells_consed));
6106 consed[1] = make_number (min (MOST_POSITIVE_FIXNUM, floats_consed));
6107 consed[2] = make_number (min (MOST_POSITIVE_FIXNUM, vector_cells_consed));
6108 consed[3] = make_number (min (MOST_POSITIVE_FIXNUM, symbols_consed));
6109 consed[4] = make_number (min (MOST_POSITIVE_FIXNUM, string_chars_consed));
6110 consed[5] = make_number (min (MOST_POSITIVE_FIXNUM, misc_objects_consed));
6111 consed[6] = make_number (min (MOST_POSITIVE_FIXNUM, intervals_consed));
6112 consed[7] = make_number (min (MOST_POSITIVE_FIXNUM, strings_consed));
6114 return Flist (8, consed);
6117 int suppress_checking;
6119 void
6120 die (const char *msg, const char *file, int line)
6122 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: %s\r\n",
6123 file, line, msg);
6124 abort ();
6127 /* Initialization */
6129 void
6130 init_alloc_once (void)
6132 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
6133 purebeg = PUREBEG;
6134 pure_size = PURESIZE;
6135 pure_bytes_used = 0;
6136 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
6137 pure_bytes_used_before_overflow = 0;
6139 /* Initialize the list of free aligned blocks. */
6140 free_ablock = NULL;
6142 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
6143 mem_init ();
6144 Vdead = make_pure_string ("DEAD", 4, 4, 0);
6145 #endif
6147 all_vectors = 0;
6148 ignore_warnings = 1;
6149 #ifdef DOUG_LEA_MALLOC
6150 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
6151 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
6152 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
6153 #endif
6154 init_strings ();
6155 init_cons ();
6156 init_symbol ();
6157 init_marker ();
6158 init_float ();
6159 init_intervals ();
6160 init_weak_hash_tables ();
6162 #ifdef REL_ALLOC
6163 malloc_hysteresis = 32;
6164 #else
6165 malloc_hysteresis = 0;
6166 #endif
6168 refill_memory_reserve ();
6170 ignore_warnings = 0;
6171 gcprolist = 0;
6172 byte_stack_list = 0;
6173 staticidx = 0;
6174 consing_since_gc = 0;
6175 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
6176 gc_relative_threshold = 0;
6179 void
6180 init_alloc (void)
6182 gcprolist = 0;
6183 byte_stack_list = 0;
6184 #if GC_MARK_STACK
6185 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
6186 setjmp_tested_p = longjmps_done = 0;
6187 #endif
6188 #endif
6189 Vgc_elapsed = make_float (0.0);
6190 gcs_done = 0;
6193 void
6194 syms_of_alloc (void)
6196 DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold,
6197 doc: /* *Number of bytes of consing between garbage collections.
6198 Garbage collection can happen automatically once this many bytes have been
6199 allocated since the last garbage collection. All data types count.
6201 Garbage collection happens automatically only when `eval' is called.
6203 By binding this temporarily to a large number, you can effectively
6204 prevent garbage collection during a part of the program.
6205 See also `gc-cons-percentage'. */);
6207 DEFVAR_LISP ("gc-cons-percentage", &Vgc_cons_percentage,
6208 doc: /* *Portion of the heap used for allocation.
6209 Garbage collection can happen automatically once this portion of the heap
6210 has been allocated since the last garbage collection.
6211 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
6212 Vgc_cons_percentage = make_float (0.1);
6214 DEFVAR_INT ("pure-bytes-used", &pure_bytes_used,
6215 doc: /* Number of bytes of sharable Lisp data allocated so far. */);
6217 DEFVAR_INT ("cons-cells-consed", &cons_cells_consed,
6218 doc: /* Number of cons cells that have been consed so far. */);
6220 DEFVAR_INT ("floats-consed", &floats_consed,
6221 doc: /* Number of floats that have been consed so far. */);
6223 DEFVAR_INT ("vector-cells-consed", &vector_cells_consed,
6224 doc: /* Number of vector cells that have been consed so far. */);
6226 DEFVAR_INT ("symbols-consed", &symbols_consed,
6227 doc: /* Number of symbols that have been consed so far. */);
6229 DEFVAR_INT ("string-chars-consed", &string_chars_consed,
6230 doc: /* Number of string characters that have been consed so far. */);
6232 DEFVAR_INT ("misc-objects-consed", &misc_objects_consed,
6233 doc: /* Number of miscellaneous objects that have been consed so far. */);
6235 DEFVAR_INT ("intervals-consed", &intervals_consed,
6236 doc: /* Number of intervals that have been consed so far. */);
6238 DEFVAR_INT ("strings-consed", &strings_consed,
6239 doc: /* Number of strings that have been consed so far. */);
6241 DEFVAR_LISP ("purify-flag", &Vpurify_flag,
6242 doc: /* Non-nil means loading Lisp code in order to dump an executable.
6243 This means that certain objects should be allocated in shared (pure) space.
6244 It can also be set to a hash-table, in which case this table is used to
6245 do hash-consing of the objects allocated to pure space. */);
6247 DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
6248 doc: /* Non-nil means display messages at start and end of garbage collection. */);
6249 garbage_collection_messages = 0;
6251 DEFVAR_LISP ("post-gc-hook", &Vpost_gc_hook,
6252 doc: /* Hook run after garbage collection has finished. */);
6253 Vpost_gc_hook = Qnil;
6254 Qpost_gc_hook = intern_c_string ("post-gc-hook");
6255 staticpro (&Qpost_gc_hook);
6257 DEFVAR_LISP ("memory-signal-data", &Vmemory_signal_data,
6258 doc: /* Precomputed `signal' argument for memory-full error. */);
6259 /* We build this in advance because if we wait until we need it, we might
6260 not be able to allocate the memory to hold it. */
6261 Vmemory_signal_data
6262 = pure_cons (Qerror,
6263 pure_cons (make_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"), Qnil));
6265 DEFVAR_LISP ("memory-full", &Vmemory_full,
6266 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
6267 Vmemory_full = Qnil;
6269 staticpro (&Qgc_cons_threshold);
6270 Qgc_cons_threshold = intern_c_string ("gc-cons-threshold");
6272 staticpro (&Qchar_table_extra_slots);
6273 Qchar_table_extra_slots = intern_c_string ("char-table-extra-slots");
6275 DEFVAR_LISP ("gc-elapsed", &Vgc_elapsed,
6276 doc: /* Accumulated time elapsed in garbage collections.
6277 The time is in seconds as a floating point value. */);
6278 DEFVAR_INT ("gcs-done", &gcs_done,
6279 doc: /* Accumulated number of garbage collections done. */);
6281 defsubr (&Scons);
6282 defsubr (&Slist);
6283 defsubr (&Svector);
6284 defsubr (&Smake_byte_code);
6285 defsubr (&Smake_list);
6286 defsubr (&Smake_vector);
6287 defsubr (&Smake_string);
6288 defsubr (&Smake_bool_vector);
6289 defsubr (&Smake_symbol);
6290 defsubr (&Smake_marker);
6291 defsubr (&Spurecopy);
6292 defsubr (&Sgarbage_collect);
6293 defsubr (&Smemory_limit);
6294 defsubr (&Smemory_use_counts);
6296 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
6297 defsubr (&Sgc_status);
6298 #endif
6301 /* arch-tag: 6695ca10-e3c5-4c2c-8bc3-ed26a7dda857
6302 (do not change this comment) */