(survives_gc_p): Simplify.
[emacs.git] / src / alloc.c
blob886c489e21f1d9d571f11387d339daefc16f057a
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
2 Copyright (C) 1985, 86, 88, 93, 94, 95, 97, 98, 1999, 2000, 2001, 2002, 2003
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 #include <config.h>
23 #include <stdio.h>
25 #ifdef ALLOC_DEBUG
26 #undef INLINE
27 #endif
29 /* Note that this declares bzero on OSF/1. How dumb. */
31 #include <signal.h>
33 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
34 memory. Can do this only if using gmalloc.c. */
36 #if defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC
37 #undef GC_MALLOC_CHECK
38 #endif
40 /* This file is part of the core Lisp implementation, and thus must
41 deal with the real data structures. If the Lisp implementation is
42 replaced, this file likely will not be used. */
44 #undef HIDE_LISP_IMPLEMENTATION
45 #include "lisp.h"
46 #include "process.h"
47 #include "intervals.h"
48 #include "puresize.h"
49 #include "buffer.h"
50 #include "window.h"
51 #include "keyboard.h"
52 #include "frame.h"
53 #include "blockinput.h"
54 #include "charset.h"
55 #include "syssignal.h"
56 #include <setjmp.h>
58 #ifdef HAVE_UNISTD_H
59 #include <unistd.h>
60 #else
61 extern POINTER_TYPE *sbrk ();
62 #endif
64 #ifdef DOUG_LEA_MALLOC
66 #include <malloc.h>
67 /* malloc.h #defines this as size_t, at least in glibc2. */
68 #ifndef __malloc_size_t
69 #define __malloc_size_t int
70 #endif
72 /* Specify maximum number of areas to mmap. It would be nice to use a
73 value that explicitly means "no limit". */
75 #define MMAP_MAX_AREAS 100000000
77 #else /* not DOUG_LEA_MALLOC */
79 /* The following come from gmalloc.c. */
81 #define __malloc_size_t size_t
82 extern __malloc_size_t _bytes_used;
83 extern __malloc_size_t __malloc_extra_blocks;
85 #endif /* not DOUG_LEA_MALLOC */
87 /* Value of _bytes_used, when spare_memory was freed. */
89 static __malloc_size_t bytes_used_when_full;
91 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
92 to a struct Lisp_String. */
94 #define MARK_STRING(S) ((S)->size |= MARKBIT)
95 #define UNMARK_STRING(S) ((S)->size &= ~MARKBIT)
96 #define STRING_MARKED_P(S) ((S)->size & MARKBIT)
98 /* Value is the number of bytes/chars of S, a pointer to a struct
99 Lisp_String. This must be used instead of STRING_BYTES (S) or
100 S->size during GC, because S->size contains the mark bit for
101 strings. */
103 #define GC_STRING_BYTES(S) (STRING_BYTES (S) & ~MARKBIT)
104 #define GC_STRING_CHARS(S) ((S)->size & ~MARKBIT)
106 /* Number of bytes of consing done since the last gc. */
108 int consing_since_gc;
110 /* Count the amount of consing of various sorts of space. */
112 EMACS_INT cons_cells_consed;
113 EMACS_INT floats_consed;
114 EMACS_INT vector_cells_consed;
115 EMACS_INT symbols_consed;
116 EMACS_INT string_chars_consed;
117 EMACS_INT misc_objects_consed;
118 EMACS_INT intervals_consed;
119 EMACS_INT strings_consed;
121 /* Number of bytes of consing since GC before another GC should be done. */
123 EMACS_INT gc_cons_threshold;
125 /* Nonzero during GC. */
127 int gc_in_progress;
129 /* Nonzero means abort if try to GC.
130 This is for code which is written on the assumption that
131 no GC will happen, so as to verify that assumption. */
133 int abort_on_gc;
135 /* Nonzero means display messages at beginning and end of GC. */
137 int garbage_collection_messages;
139 #ifndef VIRT_ADDR_VARIES
140 extern
141 #endif /* VIRT_ADDR_VARIES */
142 int malloc_sbrk_used;
144 #ifndef VIRT_ADDR_VARIES
145 extern
146 #endif /* VIRT_ADDR_VARIES */
147 int malloc_sbrk_unused;
149 /* Two limits controlling how much undo information to keep. */
151 EMACS_INT undo_limit;
152 EMACS_INT undo_strong_limit;
154 /* Number of live and free conses etc. */
156 static int total_conses, total_markers, total_symbols, total_vector_size;
157 static int total_free_conses, total_free_markers, total_free_symbols;
158 static int total_free_floats, total_floats;
160 /* Points to memory space allocated as "spare", to be freed if we run
161 out of memory. */
163 static char *spare_memory;
165 /* Amount of spare memory to keep in reserve. */
167 #define SPARE_MEMORY (1 << 14)
169 /* Number of extra blocks malloc should get when it needs more core. */
171 static int malloc_hysteresis;
173 /* Non-nil means defun should do purecopy on the function definition. */
175 Lisp_Object Vpurify_flag;
177 /* Non-nil means we are handling a memory-full error. */
179 Lisp_Object Vmemory_full;
181 #ifndef HAVE_SHM
183 /* Force it into data space! */
185 EMACS_INT pure[PURESIZE / sizeof (EMACS_INT)] = {0,};
186 #define PUREBEG (char *) pure
188 #else /* HAVE_SHM */
190 #define pure PURE_SEG_BITS /* Use shared memory segment */
191 #define PUREBEG (char *)PURE_SEG_BITS
193 #endif /* HAVE_SHM */
195 /* Pointer to the pure area, and its size. */
197 static char *purebeg;
198 static size_t pure_size;
200 /* Number of bytes of pure storage used before pure storage overflowed.
201 If this is non-zero, this implies that an overflow occurred. */
203 static size_t pure_bytes_used_before_overflow;
205 /* Value is non-zero if P points into pure space. */
207 #define PURE_POINTER_P(P) \
208 (((PNTR_COMPARISON_TYPE) (P) \
209 < (PNTR_COMPARISON_TYPE) ((char *) purebeg + pure_size)) \
210 && ((PNTR_COMPARISON_TYPE) (P) \
211 >= (PNTR_COMPARISON_TYPE) purebeg))
213 /* Index in pure at which next pure object will be allocated.. */
215 EMACS_INT pure_bytes_used;
217 /* If nonzero, this is a warning delivered by malloc and not yet
218 displayed. */
220 char *pending_malloc_warning;
222 /* Pre-computed signal argument for use when memory is exhausted. */
224 Lisp_Object Vmemory_signal_data;
226 /* Maximum amount of C stack to save when a GC happens. */
228 #ifndef MAX_SAVE_STACK
229 #define MAX_SAVE_STACK 16000
230 #endif
232 /* Buffer in which we save a copy of the C stack at each GC. */
234 char *stack_copy;
235 int stack_copy_size;
237 /* Non-zero means ignore malloc warnings. Set during initialization.
238 Currently not used. */
240 int ignore_warnings;
242 Lisp_Object Qgc_cons_threshold, Qchar_table_extra_slots;
244 /* Hook run after GC has finished. */
246 Lisp_Object Vpost_gc_hook, Qpost_gc_hook;
248 Lisp_Object Vgc_elapsed; /* accumulated elapsed time in GC */
249 EMACS_INT gcs_done; /* accumulated GCs */
251 static void mark_buffer P_ ((Lisp_Object));
252 extern void mark_kboards P_ ((void));
253 static void gc_sweep P_ ((void));
254 static void mark_glyph_matrix P_ ((struct glyph_matrix *));
255 static void mark_face_cache P_ ((struct face_cache *));
257 #ifdef HAVE_WINDOW_SYSTEM
258 static void mark_image P_ ((struct image *));
259 static void mark_image_cache P_ ((struct frame *));
260 #endif /* HAVE_WINDOW_SYSTEM */
262 static struct Lisp_String *allocate_string P_ ((void));
263 static void compact_small_strings P_ ((void));
264 static void free_large_strings P_ ((void));
265 static void sweep_strings P_ ((void));
267 extern int message_enable_multibyte;
269 /* When scanning the C stack for live Lisp objects, Emacs keeps track
270 of what memory allocated via lisp_malloc is intended for what
271 purpose. This enumeration specifies the type of memory. */
273 enum mem_type
275 MEM_TYPE_NON_LISP,
276 MEM_TYPE_BUFFER,
277 MEM_TYPE_CONS,
278 MEM_TYPE_STRING,
279 MEM_TYPE_MISC,
280 MEM_TYPE_SYMBOL,
281 MEM_TYPE_FLOAT,
282 /* Keep the following vector-like types together, with
283 MEM_TYPE_WINDOW being the last, and MEM_TYPE_VECTOR the
284 first. Or change the code of live_vector_p, for instance. */
285 MEM_TYPE_VECTOR,
286 MEM_TYPE_PROCESS,
287 MEM_TYPE_HASH_TABLE,
288 MEM_TYPE_FRAME,
289 MEM_TYPE_WINDOW
292 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
294 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
295 #include <stdio.h> /* For fprintf. */
296 #endif
298 /* A unique object in pure space used to make some Lisp objects
299 on free lists recognizable in O(1). */
301 Lisp_Object Vdead;
303 #ifdef GC_MALLOC_CHECK
305 enum mem_type allocated_mem_type;
306 int dont_register_blocks;
308 #endif /* GC_MALLOC_CHECK */
310 /* A node in the red-black tree describing allocated memory containing
311 Lisp data. Each such block is recorded with its start and end
312 address when it is allocated, and removed from the tree when it
313 is freed.
315 A red-black tree is a balanced binary tree with the following
316 properties:
318 1. Every node is either red or black.
319 2. Every leaf is black.
320 3. If a node is red, then both of its children are black.
321 4. Every simple path from a node to a descendant leaf contains
322 the same number of black nodes.
323 5. The root is always black.
325 When nodes are inserted into the tree, or deleted from the tree,
326 the tree is "fixed" so that these properties are always true.
328 A red-black tree with N internal nodes has height at most 2
329 log(N+1). Searches, insertions and deletions are done in O(log N).
330 Please see a text book about data structures for a detailed
331 description of red-black trees. Any book worth its salt should
332 describe them. */
334 struct mem_node
336 /* Children of this node. These pointers are never NULL. When there
337 is no child, the value is MEM_NIL, which points to a dummy node. */
338 struct mem_node *left, *right;
340 /* The parent of this node. In the root node, this is NULL. */
341 struct mem_node *parent;
343 /* Start and end of allocated region. */
344 void *start, *end;
346 /* Node color. */
347 enum {MEM_BLACK, MEM_RED} color;
349 /* Memory type. */
350 enum mem_type type;
353 /* Base address of stack. Set in main. */
355 Lisp_Object *stack_base;
357 /* Root of the tree describing allocated Lisp memory. */
359 static struct mem_node *mem_root;
361 /* Lowest and highest known address in the heap. */
363 static void *min_heap_address, *max_heap_address;
365 /* Sentinel node of the tree. */
367 static struct mem_node mem_z;
368 #define MEM_NIL &mem_z
370 static POINTER_TYPE *lisp_malloc P_ ((size_t, enum mem_type));
371 static struct Lisp_Vector *allocate_vectorlike P_ ((EMACS_INT, enum mem_type));
372 static void lisp_free P_ ((POINTER_TYPE *));
373 static void mark_stack P_ ((void));
374 static int live_vector_p P_ ((struct mem_node *, void *));
375 static int live_buffer_p P_ ((struct mem_node *, void *));
376 static int live_string_p P_ ((struct mem_node *, void *));
377 static int live_cons_p P_ ((struct mem_node *, void *));
378 static int live_symbol_p P_ ((struct mem_node *, void *));
379 static int live_float_p P_ ((struct mem_node *, void *));
380 static int live_misc_p P_ ((struct mem_node *, void *));
381 static void mark_maybe_object P_ ((Lisp_Object));
382 static void mark_memory P_ ((void *, void *));
383 static void mem_init P_ ((void));
384 static struct mem_node *mem_insert P_ ((void *, void *, enum mem_type));
385 static void mem_insert_fixup P_ ((struct mem_node *));
386 static void mem_rotate_left P_ ((struct mem_node *));
387 static void mem_rotate_right P_ ((struct mem_node *));
388 static void mem_delete P_ ((struct mem_node *));
389 static void mem_delete_fixup P_ ((struct mem_node *));
390 static INLINE struct mem_node *mem_find P_ ((void *));
392 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
393 static void check_gcpros P_ ((void));
394 #endif
396 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
398 /* Recording what needs to be marked for gc. */
400 struct gcpro *gcprolist;
402 /* Addresses of staticpro'd variables. */
404 #define NSTATICS 1280
405 Lisp_Object *staticvec[NSTATICS] = {0};
407 /* Index of next unused slot in staticvec. */
409 int staticidx = 0;
411 static POINTER_TYPE *pure_alloc P_ ((size_t, int));
414 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
415 ALIGNMENT must be a power of 2. */
417 #define ALIGN(SZ, ALIGNMENT) \
418 (((SZ) + (ALIGNMENT) - 1) & ~((ALIGNMENT) - 1))
422 /************************************************************************
423 Malloc
424 ************************************************************************/
426 /* Function malloc calls this if it finds we are near exhausting storage. */
428 void
429 malloc_warning (str)
430 char *str;
432 pending_malloc_warning = str;
436 /* Display an already-pending malloc warning. */
438 void
439 display_malloc_warning ()
441 call3 (intern ("display-warning"),
442 intern ("alloc"),
443 build_string (pending_malloc_warning),
444 intern ("emergency"));
445 pending_malloc_warning = 0;
449 #ifdef DOUG_LEA_MALLOC
450 # define BYTES_USED (mallinfo ().arena)
451 #else
452 # define BYTES_USED _bytes_used
453 #endif
456 /* Called if malloc returns zero. */
458 void
459 memory_full ()
461 Vmemory_full = Qt;
463 #ifndef SYSTEM_MALLOC
464 bytes_used_when_full = BYTES_USED;
465 #endif
467 /* The first time we get here, free the spare memory. */
468 if (spare_memory)
470 free (spare_memory);
471 spare_memory = 0;
474 /* This used to call error, but if we've run out of memory, we could
475 get infinite recursion trying to build the string. */
476 while (1)
477 Fsignal (Qnil, Vmemory_signal_data);
481 /* Called if we can't allocate relocatable space for a buffer. */
483 void
484 buffer_memory_full ()
486 /* If buffers use the relocating allocator, no need to free
487 spare_memory, because we may have plenty of malloc space left
488 that we could get, and if we don't, the malloc that fails will
489 itself cause spare_memory to be freed. If buffers don't use the
490 relocating allocator, treat this like any other failing
491 malloc. */
493 #ifndef REL_ALLOC
494 memory_full ();
495 #endif
497 Vmemory_full = Qt;
499 /* This used to call error, but if we've run out of memory, we could
500 get infinite recursion trying to build the string. */
501 while (1)
502 Fsignal (Qnil, Vmemory_signal_data);
506 /* Like malloc but check for no memory and block interrupt input.. */
508 POINTER_TYPE *
509 xmalloc (size)
510 size_t size;
512 register POINTER_TYPE *val;
514 BLOCK_INPUT;
515 val = (POINTER_TYPE *) malloc (size);
516 UNBLOCK_INPUT;
518 if (!val && size)
519 memory_full ();
520 return val;
524 /* Like realloc but check for no memory and block interrupt input.. */
526 POINTER_TYPE *
527 xrealloc (block, size)
528 POINTER_TYPE *block;
529 size_t size;
531 register POINTER_TYPE *val;
533 BLOCK_INPUT;
534 /* We must call malloc explicitly when BLOCK is 0, since some
535 reallocs don't do this. */
536 if (! block)
537 val = (POINTER_TYPE *) malloc (size);
538 else
539 val = (POINTER_TYPE *) realloc (block, size);
540 UNBLOCK_INPUT;
542 if (!val && size) memory_full ();
543 return val;
547 /* Like free but block interrupt input.. */
549 void
550 xfree (block)
551 POINTER_TYPE *block;
553 BLOCK_INPUT;
554 free (block);
555 UNBLOCK_INPUT;
559 /* Like strdup, but uses xmalloc. */
561 char *
562 xstrdup (s)
563 const char *s;
565 size_t len = strlen (s) + 1;
566 char *p = (char *) xmalloc (len);
567 bcopy (s, p, len);
568 return p;
572 /* Like malloc but used for allocating Lisp data. NBYTES is the
573 number of bytes to allocate, TYPE describes the intended use of the
574 allcated memory block (for strings, for conses, ...). */
576 static void *lisp_malloc_loser;
578 static POINTER_TYPE *
579 lisp_malloc (nbytes, type)
580 size_t nbytes;
581 enum mem_type type;
583 register void *val;
585 BLOCK_INPUT;
587 #ifdef GC_MALLOC_CHECK
588 allocated_mem_type = type;
589 #endif
591 val = (void *) malloc (nbytes);
593 /* If the memory just allocated cannot be addressed thru a Lisp
594 object's pointer, and it needs to be,
595 that's equivalent to running out of memory. */
596 if (val && type != MEM_TYPE_NON_LISP)
598 Lisp_Object tem;
599 XSETCONS (tem, (char *) val + nbytes - 1);
600 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
602 lisp_malloc_loser = val;
603 free (val);
604 val = 0;
608 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
609 if (val && type != MEM_TYPE_NON_LISP)
610 mem_insert (val, (char *) val + nbytes, type);
611 #endif
613 UNBLOCK_INPUT;
614 if (!val && nbytes)
615 memory_full ();
616 return val;
620 /* Return a new buffer structure allocated from the heap with
621 a call to lisp_malloc. */
623 struct buffer *
624 allocate_buffer ()
626 struct buffer *b
627 = (struct buffer *) lisp_malloc (sizeof (struct buffer),
628 MEM_TYPE_BUFFER);
629 return b;
633 /* Free BLOCK. This must be called to free memory allocated with a
634 call to lisp_malloc. */
636 static void
637 lisp_free (block)
638 POINTER_TYPE *block;
640 BLOCK_INPUT;
641 free (block);
642 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
643 mem_delete (mem_find (block));
644 #endif
645 UNBLOCK_INPUT;
649 /* Arranging to disable input signals while we're in malloc.
651 This only works with GNU malloc. To help out systems which can't
652 use GNU malloc, all the calls to malloc, realloc, and free
653 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
654 pairs; unfortunately, we have no idea what C library functions
655 might call malloc, so we can't really protect them unless you're
656 using GNU malloc. Fortunately, most of the major operating systems
657 can use GNU malloc. */
659 #ifndef SYSTEM_MALLOC
660 #ifndef DOUG_LEA_MALLOC
661 extern void * (*__malloc_hook) P_ ((size_t));
662 extern void * (*__realloc_hook) P_ ((void *, size_t));
663 extern void (*__free_hook) P_ ((void *));
664 /* Else declared in malloc.h, perhaps with an extra arg. */
665 #endif /* DOUG_LEA_MALLOC */
666 static void * (*old_malloc_hook) ();
667 static void * (*old_realloc_hook) ();
668 static void (*old_free_hook) ();
670 /* This function is used as the hook for free to call. */
672 static void
673 emacs_blocked_free (ptr)
674 void *ptr;
676 BLOCK_INPUT;
678 #ifdef GC_MALLOC_CHECK
679 if (ptr)
681 struct mem_node *m;
683 m = mem_find (ptr);
684 if (m == MEM_NIL || m->start != ptr)
686 fprintf (stderr,
687 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
688 abort ();
690 else
692 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
693 mem_delete (m);
696 #endif /* GC_MALLOC_CHECK */
698 __free_hook = old_free_hook;
699 free (ptr);
701 /* If we released our reserve (due to running out of memory),
702 and we have a fair amount free once again,
703 try to set aside another reserve in case we run out once more. */
704 if (spare_memory == 0
705 /* Verify there is enough space that even with the malloc
706 hysteresis this call won't run out again.
707 The code here is correct as long as SPARE_MEMORY
708 is substantially larger than the block size malloc uses. */
709 && (bytes_used_when_full
710 > BYTES_USED + max (malloc_hysteresis, 4) * SPARE_MEMORY))
711 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
713 __free_hook = emacs_blocked_free;
714 UNBLOCK_INPUT;
718 /* If we released our reserve (due to running out of memory),
719 and we have a fair amount free once again,
720 try to set aside another reserve in case we run out once more.
722 This is called when a relocatable block is freed in ralloc.c. */
724 void
725 refill_memory_reserve ()
727 if (spare_memory == 0)
728 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
732 /* This function is the malloc hook that Emacs uses. */
734 static void *
735 emacs_blocked_malloc (size)
736 size_t size;
738 void *value;
740 BLOCK_INPUT;
741 __malloc_hook = old_malloc_hook;
742 #ifdef DOUG_LEA_MALLOC
743 mallopt (M_TOP_PAD, malloc_hysteresis * 4096);
744 #else
745 __malloc_extra_blocks = malloc_hysteresis;
746 #endif
748 value = (void *) malloc (size);
750 #ifdef GC_MALLOC_CHECK
752 struct mem_node *m = mem_find (value);
753 if (m != MEM_NIL)
755 fprintf (stderr, "Malloc returned %p which is already in use\n",
756 value);
757 fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
758 m->start, m->end, (char *) m->end - (char *) m->start,
759 m->type);
760 abort ();
763 if (!dont_register_blocks)
765 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
766 allocated_mem_type = MEM_TYPE_NON_LISP;
769 #endif /* GC_MALLOC_CHECK */
771 __malloc_hook = emacs_blocked_malloc;
772 UNBLOCK_INPUT;
774 /* fprintf (stderr, "%p malloc\n", value); */
775 return value;
779 /* This function is the realloc hook that Emacs uses. */
781 static void *
782 emacs_blocked_realloc (ptr, size)
783 void *ptr;
784 size_t size;
786 void *value;
788 BLOCK_INPUT;
789 __realloc_hook = old_realloc_hook;
791 #ifdef GC_MALLOC_CHECK
792 if (ptr)
794 struct mem_node *m = mem_find (ptr);
795 if (m == MEM_NIL || m->start != ptr)
797 fprintf (stderr,
798 "Realloc of %p which wasn't allocated with malloc\n",
799 ptr);
800 abort ();
803 mem_delete (m);
806 /* fprintf (stderr, "%p -> realloc\n", ptr); */
808 /* Prevent malloc from registering blocks. */
809 dont_register_blocks = 1;
810 #endif /* GC_MALLOC_CHECK */
812 value = (void *) realloc (ptr, size);
814 #ifdef GC_MALLOC_CHECK
815 dont_register_blocks = 0;
818 struct mem_node *m = mem_find (value);
819 if (m != MEM_NIL)
821 fprintf (stderr, "Realloc returns memory that is already in use\n");
822 abort ();
825 /* Can't handle zero size regions in the red-black tree. */
826 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
829 /* fprintf (stderr, "%p <- realloc\n", value); */
830 #endif /* GC_MALLOC_CHECK */
832 __realloc_hook = emacs_blocked_realloc;
833 UNBLOCK_INPUT;
835 return value;
839 /* Called from main to set up malloc to use our hooks. */
841 void
842 uninterrupt_malloc ()
844 if (__free_hook != emacs_blocked_free)
845 old_free_hook = __free_hook;
846 __free_hook = emacs_blocked_free;
848 if (__malloc_hook != emacs_blocked_malloc)
849 old_malloc_hook = __malloc_hook;
850 __malloc_hook = emacs_blocked_malloc;
852 if (__realloc_hook != emacs_blocked_realloc)
853 old_realloc_hook = __realloc_hook;
854 __realloc_hook = emacs_blocked_realloc;
857 #endif /* not SYSTEM_MALLOC */
861 /***********************************************************************
862 Interval Allocation
863 ***********************************************************************/
865 /* Number of intervals allocated in an interval_block structure.
866 The 1020 is 1024 minus malloc overhead. */
868 #define INTERVAL_BLOCK_SIZE \
869 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
871 /* Intervals are allocated in chunks in form of an interval_block
872 structure. */
874 struct interval_block
876 struct interval_block *next;
877 struct interval intervals[INTERVAL_BLOCK_SIZE];
880 /* Current interval block. Its `next' pointer points to older
881 blocks. */
883 struct interval_block *interval_block;
885 /* Index in interval_block above of the next unused interval
886 structure. */
888 static int interval_block_index;
890 /* Number of free and live intervals. */
892 static int total_free_intervals, total_intervals;
894 /* List of free intervals. */
896 INTERVAL interval_free_list;
898 /* Total number of interval blocks now in use. */
900 int n_interval_blocks;
903 /* Initialize interval allocation. */
905 static void
906 init_intervals ()
908 interval_block
909 = (struct interval_block *) lisp_malloc (sizeof *interval_block,
910 MEM_TYPE_NON_LISP);
911 interval_block->next = 0;
912 bzero ((char *) interval_block->intervals, sizeof interval_block->intervals);
913 interval_block_index = 0;
914 interval_free_list = 0;
915 n_interval_blocks = 1;
919 /* Return a new interval. */
921 INTERVAL
922 make_interval ()
924 INTERVAL val;
926 if (interval_free_list)
928 val = interval_free_list;
929 interval_free_list = INTERVAL_PARENT (interval_free_list);
931 else
933 if (interval_block_index == INTERVAL_BLOCK_SIZE)
935 register struct interval_block *newi;
937 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
938 MEM_TYPE_NON_LISP);
940 newi->next = interval_block;
941 interval_block = newi;
942 interval_block_index = 0;
943 n_interval_blocks++;
945 val = &interval_block->intervals[interval_block_index++];
947 consing_since_gc += sizeof (struct interval);
948 intervals_consed++;
949 RESET_INTERVAL (val);
950 val->gcmarkbit = 0;
951 return val;
955 /* Mark Lisp objects in interval I. */
957 static void
958 mark_interval (i, dummy)
959 register INTERVAL i;
960 Lisp_Object dummy;
962 eassert (!i->gcmarkbit); /* Intervals are never shared. */
963 i->gcmarkbit = 1;
964 mark_object (&i->plist);
968 /* Mark the interval tree rooted in TREE. Don't call this directly;
969 use the macro MARK_INTERVAL_TREE instead. */
971 static void
972 mark_interval_tree (tree)
973 register INTERVAL tree;
975 /* No need to test if this tree has been marked already; this
976 function is always called through the MARK_INTERVAL_TREE macro,
977 which takes care of that. */
979 traverse_intervals_noorder (tree, mark_interval, Qnil);
983 /* Mark the interval tree rooted in I. */
985 #define MARK_INTERVAL_TREE(i) \
986 do { \
987 if (!NULL_INTERVAL_P (i) && !i->gcmarkbit) \
988 mark_interval_tree (i); \
989 } while (0)
992 #define UNMARK_BALANCE_INTERVALS(i) \
993 do { \
994 if (! NULL_INTERVAL_P (i)) \
995 (i) = balance_intervals (i); \
996 } while (0)
999 /* Number support. If NO_UNION_TYPE isn't in effect, we
1000 can't create number objects in macros. */
1001 #ifndef make_number
1002 Lisp_Object
1003 make_number (n)
1004 int n;
1006 Lisp_Object obj;
1007 obj.s.val = n;
1008 obj.s.type = Lisp_Int;
1009 return obj;
1011 #endif
1013 /***********************************************************************
1014 String Allocation
1015 ***********************************************************************/
1017 /* Lisp_Strings are allocated in string_block structures. When a new
1018 string_block is allocated, all the Lisp_Strings it contains are
1019 added to a free-list string_free_list. When a new Lisp_String is
1020 needed, it is taken from that list. During the sweep phase of GC,
1021 string_blocks that are entirely free are freed, except two which
1022 we keep.
1024 String data is allocated from sblock structures. Strings larger
1025 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1026 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1028 Sblocks consist internally of sdata structures, one for each
1029 Lisp_String. The sdata structure points to the Lisp_String it
1030 belongs to. The Lisp_String points back to the `u.data' member of
1031 its sdata structure.
1033 When a Lisp_String is freed during GC, it is put back on
1034 string_free_list, and its `data' member and its sdata's `string'
1035 pointer is set to null. The size of the string is recorded in the
1036 `u.nbytes' member of the sdata. So, sdata structures that are no
1037 longer used, can be easily recognized, and it's easy to compact the
1038 sblocks of small strings which we do in compact_small_strings. */
1040 /* Size in bytes of an sblock structure used for small strings. This
1041 is 8192 minus malloc overhead. */
1043 #define SBLOCK_SIZE 8188
1045 /* Strings larger than this are considered large strings. String data
1046 for large strings is allocated from individual sblocks. */
1048 #define LARGE_STRING_BYTES 1024
1050 /* Structure describing string memory sub-allocated from an sblock.
1051 This is where the contents of Lisp strings are stored. */
1053 struct sdata
1055 /* Back-pointer to the string this sdata belongs to. If null, this
1056 structure is free, and the NBYTES member of the union below
1057 contains the string's byte size (the same value that STRING_BYTES
1058 would return if STRING were non-null). If non-null, STRING_BYTES
1059 (STRING) is the size of the data, and DATA contains the string's
1060 contents. */
1061 struct Lisp_String *string;
1063 #ifdef GC_CHECK_STRING_BYTES
1065 EMACS_INT nbytes;
1066 unsigned char data[1];
1068 #define SDATA_NBYTES(S) (S)->nbytes
1069 #define SDATA_DATA(S) (S)->data
1071 #else /* not GC_CHECK_STRING_BYTES */
1073 union
1075 /* When STRING in non-null. */
1076 unsigned char data[1];
1078 /* When STRING is null. */
1079 EMACS_INT nbytes;
1080 } u;
1083 #define SDATA_NBYTES(S) (S)->u.nbytes
1084 #define SDATA_DATA(S) (S)->u.data
1086 #endif /* not GC_CHECK_STRING_BYTES */
1090 /* Structure describing a block of memory which is sub-allocated to
1091 obtain string data memory for strings. Blocks for small strings
1092 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1093 as large as needed. */
1095 struct sblock
1097 /* Next in list. */
1098 struct sblock *next;
1100 /* Pointer to the next free sdata block. This points past the end
1101 of the sblock if there isn't any space left in this block. */
1102 struct sdata *next_free;
1104 /* Start of data. */
1105 struct sdata first_data;
1108 /* Number of Lisp strings in a string_block structure. The 1020 is
1109 1024 minus malloc overhead. */
1111 #define STRINGS_IN_STRING_BLOCK \
1112 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1114 /* Structure describing a block from which Lisp_String structures
1115 are allocated. */
1117 struct string_block
1119 struct string_block *next;
1120 struct Lisp_String strings[STRINGS_IN_STRING_BLOCK];
1123 /* Head and tail of the list of sblock structures holding Lisp string
1124 data. We always allocate from current_sblock. The NEXT pointers
1125 in the sblock structures go from oldest_sblock to current_sblock. */
1127 static struct sblock *oldest_sblock, *current_sblock;
1129 /* List of sblocks for large strings. */
1131 static struct sblock *large_sblocks;
1133 /* List of string_block structures, and how many there are. */
1135 static struct string_block *string_blocks;
1136 static int n_string_blocks;
1138 /* Free-list of Lisp_Strings. */
1140 static struct Lisp_String *string_free_list;
1142 /* Number of live and free Lisp_Strings. */
1144 static int total_strings, total_free_strings;
1146 /* Number of bytes used by live strings. */
1148 static int total_string_size;
1150 /* Given a pointer to a Lisp_String S which is on the free-list
1151 string_free_list, return a pointer to its successor in the
1152 free-list. */
1154 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1156 /* Return a pointer to the sdata structure belonging to Lisp string S.
1157 S must be live, i.e. S->data must not be null. S->data is actually
1158 a pointer to the `u.data' member of its sdata structure; the
1159 structure starts at a constant offset in front of that. */
1161 #ifdef GC_CHECK_STRING_BYTES
1163 #define SDATA_OF_STRING(S) \
1164 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *) \
1165 - sizeof (EMACS_INT)))
1167 #else /* not GC_CHECK_STRING_BYTES */
1169 #define SDATA_OF_STRING(S) \
1170 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))
1172 #endif /* not GC_CHECK_STRING_BYTES */
1174 /* Value is the size of an sdata structure large enough to hold NBYTES
1175 bytes of string data. The value returned includes a terminating
1176 NUL byte, the size of the sdata structure, and padding. */
1178 #ifdef GC_CHECK_STRING_BYTES
1180 #define SDATA_SIZE(NBYTES) \
1181 ((sizeof (struct Lisp_String *) \
1182 + (NBYTES) + 1 \
1183 + sizeof (EMACS_INT) \
1184 + sizeof (EMACS_INT) - 1) \
1185 & ~(sizeof (EMACS_INT) - 1))
1187 #else /* not GC_CHECK_STRING_BYTES */
1189 #define SDATA_SIZE(NBYTES) \
1190 ((sizeof (struct Lisp_String *) \
1191 + (NBYTES) + 1 \
1192 + sizeof (EMACS_INT) - 1) \
1193 & ~(sizeof (EMACS_INT) - 1))
1195 #endif /* not GC_CHECK_STRING_BYTES */
1197 /* Initialize string allocation. Called from init_alloc_once. */
1199 void
1200 init_strings ()
1202 total_strings = total_free_strings = total_string_size = 0;
1203 oldest_sblock = current_sblock = large_sblocks = NULL;
1204 string_blocks = NULL;
1205 n_string_blocks = 0;
1206 string_free_list = NULL;
1210 #ifdef GC_CHECK_STRING_BYTES
1212 static int check_string_bytes_count;
1214 void check_string_bytes P_ ((int));
1215 void check_sblock P_ ((struct sblock *));
1217 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1220 /* Like GC_STRING_BYTES, but with debugging check. */
1223 string_bytes (s)
1224 struct Lisp_String *s;
1226 int nbytes = (s->size_byte < 0 ? s->size : s->size_byte) & ~MARKBIT;
1227 if (!PURE_POINTER_P (s)
1228 && s->data
1229 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1230 abort ();
1231 return nbytes;
1234 /* Check validity of Lisp strings' string_bytes member in B. */
1236 void
1237 check_sblock (b)
1238 struct sblock *b;
1240 struct sdata *from, *end, *from_end;
1242 end = b->next_free;
1244 for (from = &b->first_data; from < end; from = from_end)
1246 /* Compute the next FROM here because copying below may
1247 overwrite data we need to compute it. */
1248 int nbytes;
1250 /* Check that the string size recorded in the string is the
1251 same as the one recorded in the sdata structure. */
1252 if (from->string)
1253 CHECK_STRING_BYTES (from->string);
1255 if (from->string)
1256 nbytes = GC_STRING_BYTES (from->string);
1257 else
1258 nbytes = SDATA_NBYTES (from);
1260 nbytes = SDATA_SIZE (nbytes);
1261 from_end = (struct sdata *) ((char *) from + nbytes);
1266 /* Check validity of Lisp strings' string_bytes member. ALL_P
1267 non-zero means check all strings, otherwise check only most
1268 recently allocated strings. Used for hunting a bug. */
1270 void
1271 check_string_bytes (all_p)
1272 int all_p;
1274 if (all_p)
1276 struct sblock *b;
1278 for (b = large_sblocks; b; b = b->next)
1280 struct Lisp_String *s = b->first_data.string;
1281 if (s)
1282 CHECK_STRING_BYTES (s);
1285 for (b = oldest_sblock; b; b = b->next)
1286 check_sblock (b);
1288 else
1289 check_sblock (current_sblock);
1292 #endif /* GC_CHECK_STRING_BYTES */
1295 /* Return a new Lisp_String. */
1297 static struct Lisp_String *
1298 allocate_string ()
1300 struct Lisp_String *s;
1302 /* If the free-list is empty, allocate a new string_block, and
1303 add all the Lisp_Strings in it to the free-list. */
1304 if (string_free_list == NULL)
1306 struct string_block *b;
1307 int i;
1309 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1310 bzero (b, sizeof *b);
1311 b->next = string_blocks;
1312 string_blocks = b;
1313 ++n_string_blocks;
1315 for (i = STRINGS_IN_STRING_BLOCK - 1; i >= 0; --i)
1317 s = b->strings + i;
1318 NEXT_FREE_LISP_STRING (s) = string_free_list;
1319 string_free_list = s;
1322 total_free_strings += STRINGS_IN_STRING_BLOCK;
1325 /* Pop a Lisp_String off the free-list. */
1326 s = string_free_list;
1327 string_free_list = NEXT_FREE_LISP_STRING (s);
1329 /* Probably not strictly necessary, but play it safe. */
1330 bzero (s, sizeof *s);
1332 --total_free_strings;
1333 ++total_strings;
1334 ++strings_consed;
1335 consing_since_gc += sizeof *s;
1337 #ifdef GC_CHECK_STRING_BYTES
1338 if (!noninteractive
1339 #ifdef MAC_OS8
1340 && current_sblock
1341 #endif
1344 if (++check_string_bytes_count == 200)
1346 check_string_bytes_count = 0;
1347 check_string_bytes (1);
1349 else
1350 check_string_bytes (0);
1352 #endif /* GC_CHECK_STRING_BYTES */
1354 return s;
1358 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1359 plus a NUL byte at the end. Allocate an sdata structure for S, and
1360 set S->data to its `u.data' member. Store a NUL byte at the end of
1361 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1362 S->data if it was initially non-null. */
1364 void
1365 allocate_string_data (s, nchars, nbytes)
1366 struct Lisp_String *s;
1367 int nchars, nbytes;
1369 struct sdata *data, *old_data;
1370 struct sblock *b;
1371 int needed, old_nbytes;
1373 /* Determine the number of bytes needed to store NBYTES bytes
1374 of string data. */
1375 needed = SDATA_SIZE (nbytes);
1377 if (nbytes > LARGE_STRING_BYTES)
1379 size_t size = sizeof *b - sizeof (struct sdata) + needed;
1381 #ifdef DOUG_LEA_MALLOC
1382 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1383 because mapped region contents are not preserved in
1384 a dumped Emacs.
1386 In case you think of allowing it in a dumped Emacs at the
1387 cost of not being able to re-dump, there's another reason:
1388 mmap'ed data typically have an address towards the top of the
1389 address space, which won't fit into an EMACS_INT (at least on
1390 32-bit systems with the current tagging scheme). --fx */
1391 mallopt (M_MMAP_MAX, 0);
1392 #endif
1394 b = (struct sblock *) lisp_malloc (size, MEM_TYPE_NON_LISP);
1396 #ifdef DOUG_LEA_MALLOC
1397 /* Back to a reasonable maximum of mmap'ed areas. */
1398 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1399 #endif
1401 b->next_free = &b->first_data;
1402 b->first_data.string = NULL;
1403 b->next = large_sblocks;
1404 large_sblocks = b;
1406 else if (current_sblock == NULL
1407 || (((char *) current_sblock + SBLOCK_SIZE
1408 - (char *) current_sblock->next_free)
1409 < needed))
1411 /* Not enough room in the current sblock. */
1412 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1413 b->next_free = &b->first_data;
1414 b->first_data.string = NULL;
1415 b->next = NULL;
1417 if (current_sblock)
1418 current_sblock->next = b;
1419 else
1420 oldest_sblock = b;
1421 current_sblock = b;
1423 else
1424 b = current_sblock;
1426 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1427 old_nbytes = GC_STRING_BYTES (s);
1429 data = b->next_free;
1430 data->string = s;
1431 s->data = SDATA_DATA (data);
1432 #ifdef GC_CHECK_STRING_BYTES
1433 SDATA_NBYTES (data) = nbytes;
1434 #endif
1435 s->size = nchars;
1436 s->size_byte = nbytes;
1437 s->data[nbytes] = '\0';
1438 b->next_free = (struct sdata *) ((char *) data + needed);
1440 /* If S had already data assigned, mark that as free by setting its
1441 string back-pointer to null, and recording the size of the data
1442 in it. */
1443 if (old_data)
1445 SDATA_NBYTES (old_data) = old_nbytes;
1446 old_data->string = NULL;
1449 consing_since_gc += needed;
1453 /* Sweep and compact strings. */
1455 static void
1456 sweep_strings ()
1458 struct string_block *b, *next;
1459 struct string_block *live_blocks = NULL;
1461 string_free_list = NULL;
1462 total_strings = total_free_strings = 0;
1463 total_string_size = 0;
1465 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1466 for (b = string_blocks; b; b = next)
1468 int i, nfree = 0;
1469 struct Lisp_String *free_list_before = string_free_list;
1471 next = b->next;
1473 for (i = 0; i < STRINGS_IN_STRING_BLOCK; ++i)
1475 struct Lisp_String *s = b->strings + i;
1477 if (s->data)
1479 /* String was not on free-list before. */
1480 if (STRING_MARKED_P (s))
1482 /* String is live; unmark it and its intervals. */
1483 UNMARK_STRING (s);
1485 if (!NULL_INTERVAL_P (s->intervals))
1486 UNMARK_BALANCE_INTERVALS (s->intervals);
1488 ++total_strings;
1489 total_string_size += STRING_BYTES (s);
1491 else
1493 /* String is dead. Put it on the free-list. */
1494 struct sdata *data = SDATA_OF_STRING (s);
1496 /* Save the size of S in its sdata so that we know
1497 how large that is. Reset the sdata's string
1498 back-pointer so that we know it's free. */
1499 #ifdef GC_CHECK_STRING_BYTES
1500 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
1501 abort ();
1502 #else
1503 data->u.nbytes = GC_STRING_BYTES (s);
1504 #endif
1505 data->string = NULL;
1507 /* Reset the strings's `data' member so that we
1508 know it's free. */
1509 s->data = NULL;
1511 /* Put the string on the free-list. */
1512 NEXT_FREE_LISP_STRING (s) = string_free_list;
1513 string_free_list = s;
1514 ++nfree;
1517 else
1519 /* S was on the free-list before. Put it there again. */
1520 NEXT_FREE_LISP_STRING (s) = string_free_list;
1521 string_free_list = s;
1522 ++nfree;
1526 /* Free blocks that contain free Lisp_Strings only, except
1527 the first two of them. */
1528 if (nfree == STRINGS_IN_STRING_BLOCK
1529 && total_free_strings > STRINGS_IN_STRING_BLOCK)
1531 lisp_free (b);
1532 --n_string_blocks;
1533 string_free_list = free_list_before;
1535 else
1537 total_free_strings += nfree;
1538 b->next = live_blocks;
1539 live_blocks = b;
1543 string_blocks = live_blocks;
1544 free_large_strings ();
1545 compact_small_strings ();
1549 /* Free dead large strings. */
1551 static void
1552 free_large_strings ()
1554 struct sblock *b, *next;
1555 struct sblock *live_blocks = NULL;
1557 for (b = large_sblocks; b; b = next)
1559 next = b->next;
1561 if (b->first_data.string == NULL)
1562 lisp_free (b);
1563 else
1565 b->next = live_blocks;
1566 live_blocks = b;
1570 large_sblocks = live_blocks;
1574 /* Compact data of small strings. Free sblocks that don't contain
1575 data of live strings after compaction. */
1577 static void
1578 compact_small_strings ()
1580 struct sblock *b, *tb, *next;
1581 struct sdata *from, *to, *end, *tb_end;
1582 struct sdata *to_end, *from_end;
1584 /* TB is the sblock we copy to, TO is the sdata within TB we copy
1585 to, and TB_END is the end of TB. */
1586 tb = oldest_sblock;
1587 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1588 to = &tb->first_data;
1590 /* Step through the blocks from the oldest to the youngest. We
1591 expect that old blocks will stabilize over time, so that less
1592 copying will happen this way. */
1593 for (b = oldest_sblock; b; b = b->next)
1595 end = b->next_free;
1596 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
1598 for (from = &b->first_data; from < end; from = from_end)
1600 /* Compute the next FROM here because copying below may
1601 overwrite data we need to compute it. */
1602 int nbytes;
1604 #ifdef GC_CHECK_STRING_BYTES
1605 /* Check that the string size recorded in the string is the
1606 same as the one recorded in the sdata structure. */
1607 if (from->string
1608 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
1609 abort ();
1610 #endif /* GC_CHECK_STRING_BYTES */
1612 if (from->string)
1613 nbytes = GC_STRING_BYTES (from->string);
1614 else
1615 nbytes = SDATA_NBYTES (from);
1617 nbytes = SDATA_SIZE (nbytes);
1618 from_end = (struct sdata *) ((char *) from + nbytes);
1620 /* FROM->string non-null means it's alive. Copy its data. */
1621 if (from->string)
1623 /* If TB is full, proceed with the next sblock. */
1624 to_end = (struct sdata *) ((char *) to + nbytes);
1625 if (to_end > tb_end)
1627 tb->next_free = to;
1628 tb = tb->next;
1629 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1630 to = &tb->first_data;
1631 to_end = (struct sdata *) ((char *) to + nbytes);
1634 /* Copy, and update the string's `data' pointer. */
1635 if (from != to)
1637 xassert (tb != b || to <= from);
1638 safe_bcopy ((char *) from, (char *) to, nbytes);
1639 to->string->data = SDATA_DATA (to);
1642 /* Advance past the sdata we copied to. */
1643 to = to_end;
1648 /* The rest of the sblocks following TB don't contain live data, so
1649 we can free them. */
1650 for (b = tb->next; b; b = next)
1652 next = b->next;
1653 lisp_free (b);
1656 tb->next_free = to;
1657 tb->next = NULL;
1658 current_sblock = tb;
1662 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
1663 doc: /* Return a newly created string of length LENGTH, with each element being INIT.
1664 Both LENGTH and INIT must be numbers. */)
1665 (length, init)
1666 Lisp_Object length, init;
1668 register Lisp_Object val;
1669 register unsigned char *p, *end;
1670 int c, nbytes;
1672 CHECK_NATNUM (length);
1673 CHECK_NUMBER (init);
1675 c = XINT (init);
1676 if (SINGLE_BYTE_CHAR_P (c))
1678 nbytes = XINT (length);
1679 val = make_uninit_string (nbytes);
1680 p = SDATA (val);
1681 end = p + SCHARS (val);
1682 while (p != end)
1683 *p++ = c;
1685 else
1687 unsigned char str[MAX_MULTIBYTE_LENGTH];
1688 int len = CHAR_STRING (c, str);
1690 nbytes = len * XINT (length);
1691 val = make_uninit_multibyte_string (XINT (length), nbytes);
1692 p = SDATA (val);
1693 end = p + nbytes;
1694 while (p != end)
1696 bcopy (str, p, len);
1697 p += len;
1701 *p = 0;
1702 return val;
1706 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
1707 doc: /* Return a new bool-vector of length LENGTH, using INIT for as each element.
1708 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
1709 (length, init)
1710 Lisp_Object length, init;
1712 register Lisp_Object val;
1713 struct Lisp_Bool_Vector *p;
1714 int real_init, i;
1715 int length_in_chars, length_in_elts, bits_per_value;
1717 CHECK_NATNUM (length);
1719 bits_per_value = sizeof (EMACS_INT) * BITS_PER_CHAR;
1721 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
1722 length_in_chars = ((XFASTINT (length) + BITS_PER_CHAR - 1) / BITS_PER_CHAR);
1724 /* We must allocate one more elements than LENGTH_IN_ELTS for the
1725 slot `size' of the struct Lisp_Bool_Vector. */
1726 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
1727 p = XBOOL_VECTOR (val);
1729 /* Get rid of any bits that would cause confusion. */
1730 p->vector_size = 0;
1731 XSETBOOL_VECTOR (val, p);
1732 p->size = XFASTINT (length);
1734 real_init = (NILP (init) ? 0 : -1);
1735 for (i = 0; i < length_in_chars ; i++)
1736 p->data[i] = real_init;
1738 /* Clear the extraneous bits in the last byte. */
1739 if (XINT (length) != length_in_chars * BITS_PER_CHAR)
1740 XBOOL_VECTOR (val)->data[length_in_chars - 1]
1741 &= (1 << (XINT (length) % BITS_PER_CHAR)) - 1;
1743 return val;
1747 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
1748 of characters from the contents. This string may be unibyte or
1749 multibyte, depending on the contents. */
1751 Lisp_Object
1752 make_string (contents, nbytes)
1753 const char *contents;
1754 int nbytes;
1756 register Lisp_Object val;
1757 int nchars, multibyte_nbytes;
1759 parse_str_as_multibyte (contents, nbytes, &nchars, &multibyte_nbytes);
1760 if (nbytes == nchars || nbytes != multibyte_nbytes)
1761 /* CONTENTS contains no multibyte sequences or contains an invalid
1762 multibyte sequence. We must make unibyte string. */
1763 val = make_unibyte_string (contents, nbytes);
1764 else
1765 val = make_multibyte_string (contents, nchars, nbytes);
1766 return val;
1770 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
1772 Lisp_Object
1773 make_unibyte_string (contents, length)
1774 const char *contents;
1775 int length;
1777 register Lisp_Object val;
1778 val = make_uninit_string (length);
1779 bcopy (contents, SDATA (val), length);
1780 STRING_SET_UNIBYTE (val);
1781 return val;
1785 /* Make a multibyte string from NCHARS characters occupying NBYTES
1786 bytes at CONTENTS. */
1788 Lisp_Object
1789 make_multibyte_string (contents, nchars, nbytes)
1790 const char *contents;
1791 int nchars, nbytes;
1793 register Lisp_Object val;
1794 val = make_uninit_multibyte_string (nchars, nbytes);
1795 bcopy (contents, SDATA (val), nbytes);
1796 return val;
1800 /* Make a string from NCHARS characters occupying NBYTES bytes at
1801 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
1803 Lisp_Object
1804 make_string_from_bytes (contents, nchars, nbytes)
1805 const char *contents;
1806 int nchars, nbytes;
1808 register Lisp_Object val;
1809 val = make_uninit_multibyte_string (nchars, nbytes);
1810 bcopy (contents, SDATA (val), nbytes);
1811 if (SBYTES (val) == SCHARS (val))
1812 STRING_SET_UNIBYTE (val);
1813 return val;
1817 /* Make a string from NCHARS characters occupying NBYTES bytes at
1818 CONTENTS. The argument MULTIBYTE controls whether to label the
1819 string as multibyte. If NCHARS is negative, it counts the number of
1820 characters by itself. */
1822 Lisp_Object
1823 make_specified_string (contents, nchars, nbytes, multibyte)
1824 const char *contents;
1825 int nchars, nbytes;
1826 int multibyte;
1828 register Lisp_Object val;
1830 if (nchars < 0)
1832 if (multibyte)
1833 nchars = multibyte_chars_in_text (contents, nbytes);
1834 else
1835 nchars = nbytes;
1837 val = make_uninit_multibyte_string (nchars, nbytes);
1838 bcopy (contents, SDATA (val), nbytes);
1839 if (!multibyte)
1840 STRING_SET_UNIBYTE (val);
1841 return val;
1845 /* Make a string from the data at STR, treating it as multibyte if the
1846 data warrants. */
1848 Lisp_Object
1849 build_string (str)
1850 const char *str;
1852 return make_string (str, strlen (str));
1856 /* Return an unibyte Lisp_String set up to hold LENGTH characters
1857 occupying LENGTH bytes. */
1859 Lisp_Object
1860 make_uninit_string (length)
1861 int length;
1863 Lisp_Object val;
1864 val = make_uninit_multibyte_string (length, length);
1865 STRING_SET_UNIBYTE (val);
1866 return val;
1870 /* Return a multibyte Lisp_String set up to hold NCHARS characters
1871 which occupy NBYTES bytes. */
1873 Lisp_Object
1874 make_uninit_multibyte_string (nchars, nbytes)
1875 int nchars, nbytes;
1877 Lisp_Object string;
1878 struct Lisp_String *s;
1880 if (nchars < 0)
1881 abort ();
1883 s = allocate_string ();
1884 allocate_string_data (s, nchars, nbytes);
1885 XSETSTRING (string, s);
1886 string_chars_consed += nbytes;
1887 return string;
1892 /***********************************************************************
1893 Float Allocation
1894 ***********************************************************************/
1896 /* We store float cells inside of float_blocks, allocating a new
1897 float_block with malloc whenever necessary. Float cells reclaimed
1898 by GC are put on a free list to be reallocated before allocating
1899 any new float cells from the latest float_block.
1901 Each float_block is just under 1020 bytes long, since malloc really
1902 allocates in units of powers of two and uses 4 bytes for its own
1903 overhead. */
1905 #define FLOAT_BLOCK_SIZE \
1906 ((1020 - sizeof (struct float_block *)) / sizeof (struct Lisp_Float))
1908 struct float_block
1910 struct float_block *next;
1911 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
1914 /* Current float_block. */
1916 struct float_block *float_block;
1918 /* Index of first unused Lisp_Float in the current float_block. */
1920 int float_block_index;
1922 /* Total number of float blocks now in use. */
1924 int n_float_blocks;
1926 /* Free-list of Lisp_Floats. */
1928 struct Lisp_Float *float_free_list;
1931 /* Initialize float allocation. */
1933 void
1934 init_float ()
1936 float_block = (struct float_block *) lisp_malloc (sizeof *float_block,
1937 MEM_TYPE_FLOAT);
1938 float_block->next = 0;
1939 bzero ((char *) float_block->floats, sizeof float_block->floats);
1940 float_block_index = 0;
1941 float_free_list = 0;
1942 n_float_blocks = 1;
1946 /* Explicitly free a float cell by putting it on the free-list. */
1948 void
1949 free_float (ptr)
1950 struct Lisp_Float *ptr;
1952 *(struct Lisp_Float **)&ptr->data = float_free_list;
1953 #if GC_MARK_STACK
1954 ptr->type = Vdead;
1955 #endif
1956 float_free_list = ptr;
1960 /* Return a new float object with value FLOAT_VALUE. */
1962 Lisp_Object
1963 make_float (float_value)
1964 double float_value;
1966 register Lisp_Object val;
1968 if (float_free_list)
1970 /* We use the data field for chaining the free list
1971 so that we won't use the same field that has the mark bit. */
1972 XSETFLOAT (val, float_free_list);
1973 float_free_list = *(struct Lisp_Float **)&float_free_list->data;
1975 else
1977 if (float_block_index == FLOAT_BLOCK_SIZE)
1979 register struct float_block *new;
1981 new = (struct float_block *) lisp_malloc (sizeof *new,
1982 MEM_TYPE_FLOAT);
1983 new->next = float_block;
1984 float_block = new;
1985 float_block_index = 0;
1986 n_float_blocks++;
1988 XSETFLOAT (val, &float_block->floats[float_block_index++]);
1991 XFLOAT_DATA (val) = float_value;
1992 XSETFASTINT (XFLOAT (val)->type, 0); /* bug chasing -wsr */
1993 consing_since_gc += sizeof (struct Lisp_Float);
1994 floats_consed++;
1995 return val;
2000 /***********************************************************************
2001 Cons Allocation
2002 ***********************************************************************/
2004 /* We store cons cells inside of cons_blocks, allocating a new
2005 cons_block with malloc whenever necessary. Cons cells reclaimed by
2006 GC are put on a free list to be reallocated before allocating
2007 any new cons cells from the latest cons_block.
2009 Each cons_block is just under 1020 bytes long,
2010 since malloc really allocates in units of powers of two
2011 and uses 4 bytes for its own overhead. */
2013 #define CONS_BLOCK_SIZE \
2014 ((1020 - sizeof (struct cons_block *)) / sizeof (struct Lisp_Cons))
2016 struct cons_block
2018 struct cons_block *next;
2019 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2022 /* Current cons_block. */
2024 struct cons_block *cons_block;
2026 /* Index of first unused Lisp_Cons in the current block. */
2028 int cons_block_index;
2030 /* Free-list of Lisp_Cons structures. */
2032 struct Lisp_Cons *cons_free_list;
2034 /* Total number of cons blocks now in use. */
2036 int n_cons_blocks;
2039 /* Initialize cons allocation. */
2041 void
2042 init_cons ()
2044 cons_block = (struct cons_block *) lisp_malloc (sizeof *cons_block,
2045 MEM_TYPE_CONS);
2046 cons_block->next = 0;
2047 bzero ((char *) cons_block->conses, sizeof cons_block->conses);
2048 cons_block_index = 0;
2049 cons_free_list = 0;
2050 n_cons_blocks = 1;
2054 /* Explicitly free a cons cell by putting it on the free-list. */
2056 void
2057 free_cons (ptr)
2058 struct Lisp_Cons *ptr;
2060 *(struct Lisp_Cons **)&ptr->cdr = cons_free_list;
2061 #if GC_MARK_STACK
2062 ptr->car = Vdead;
2063 #endif
2064 cons_free_list = ptr;
2068 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2069 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2070 (car, cdr)
2071 Lisp_Object car, cdr;
2073 register Lisp_Object val;
2075 if (cons_free_list)
2077 /* We use the cdr for chaining the free list
2078 so that we won't use the same field that has the mark bit. */
2079 XSETCONS (val, cons_free_list);
2080 cons_free_list = *(struct Lisp_Cons **)&cons_free_list->cdr;
2082 else
2084 if (cons_block_index == CONS_BLOCK_SIZE)
2086 register struct cons_block *new;
2087 new = (struct cons_block *) lisp_malloc (sizeof *new,
2088 MEM_TYPE_CONS);
2089 new->next = cons_block;
2090 cons_block = new;
2091 cons_block_index = 0;
2092 n_cons_blocks++;
2094 XSETCONS (val, &cons_block->conses[cons_block_index++]);
2097 XSETCAR (val, car);
2098 XSETCDR (val, cdr);
2099 consing_since_gc += sizeof (struct Lisp_Cons);
2100 cons_cells_consed++;
2101 return val;
2105 /* Make a list of 2, 3, 4 or 5 specified objects. */
2107 Lisp_Object
2108 list2 (arg1, arg2)
2109 Lisp_Object arg1, arg2;
2111 return Fcons (arg1, Fcons (arg2, Qnil));
2115 Lisp_Object
2116 list3 (arg1, arg2, arg3)
2117 Lisp_Object arg1, arg2, arg3;
2119 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2123 Lisp_Object
2124 list4 (arg1, arg2, arg3, arg4)
2125 Lisp_Object arg1, arg2, arg3, arg4;
2127 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2131 Lisp_Object
2132 list5 (arg1, arg2, arg3, arg4, arg5)
2133 Lisp_Object arg1, arg2, arg3, arg4, arg5;
2135 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2136 Fcons (arg5, Qnil)))));
2140 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2141 doc: /* Return a newly created list with specified arguments as elements.
2142 Any number of arguments, even zero arguments, are allowed.
2143 usage: (list &rest OBJECTS) */)
2144 (nargs, args)
2145 int nargs;
2146 register Lisp_Object *args;
2148 register Lisp_Object val;
2149 val = Qnil;
2151 while (nargs > 0)
2153 nargs--;
2154 val = Fcons (args[nargs], val);
2156 return val;
2160 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2161 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2162 (length, init)
2163 register Lisp_Object length, init;
2165 register Lisp_Object val;
2166 register int size;
2168 CHECK_NATNUM (length);
2169 size = XFASTINT (length);
2171 val = Qnil;
2172 while (size > 0)
2174 val = Fcons (init, val);
2175 --size;
2177 if (size > 0)
2179 val = Fcons (init, val);
2180 --size;
2182 if (size > 0)
2184 val = Fcons (init, val);
2185 --size;
2187 if (size > 0)
2189 val = Fcons (init, val);
2190 --size;
2192 if (size > 0)
2194 val = Fcons (init, val);
2195 --size;
2201 QUIT;
2204 return val;
2209 /***********************************************************************
2210 Vector Allocation
2211 ***********************************************************************/
2213 /* Singly-linked list of all vectors. */
2215 struct Lisp_Vector *all_vectors;
2217 /* Total number of vector-like objects now in use. */
2219 int n_vectors;
2222 /* Value is a pointer to a newly allocated Lisp_Vector structure
2223 with room for LEN Lisp_Objects. */
2225 static struct Lisp_Vector *
2226 allocate_vectorlike (len, type)
2227 EMACS_INT len;
2228 enum mem_type type;
2230 struct Lisp_Vector *p;
2231 size_t nbytes;
2233 #ifdef DOUG_LEA_MALLOC
2234 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2235 because mapped region contents are not preserved in
2236 a dumped Emacs. */
2237 mallopt (M_MMAP_MAX, 0);
2238 #endif
2240 nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
2241 p = (struct Lisp_Vector *) lisp_malloc (nbytes, type);
2243 #ifdef DOUG_LEA_MALLOC
2244 /* Back to a reasonable maximum of mmap'ed areas. */
2245 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2246 #endif
2248 consing_since_gc += nbytes;
2249 vector_cells_consed += len;
2251 p->next = all_vectors;
2252 all_vectors = p;
2253 ++n_vectors;
2254 return p;
2258 /* Allocate a vector with NSLOTS slots. */
2260 struct Lisp_Vector *
2261 allocate_vector (nslots)
2262 EMACS_INT nslots;
2264 struct Lisp_Vector *v = allocate_vectorlike (nslots, MEM_TYPE_VECTOR);
2265 v->size = nslots;
2266 return v;
2270 /* Allocate other vector-like structures. */
2272 struct Lisp_Hash_Table *
2273 allocate_hash_table ()
2275 EMACS_INT len = VECSIZE (struct Lisp_Hash_Table);
2276 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_HASH_TABLE);
2277 EMACS_INT i;
2279 v->size = len;
2280 for (i = 0; i < len; ++i)
2281 v->contents[i] = Qnil;
2283 return (struct Lisp_Hash_Table *) v;
2287 struct window *
2288 allocate_window ()
2290 EMACS_INT len = VECSIZE (struct window);
2291 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_WINDOW);
2292 EMACS_INT i;
2294 for (i = 0; i < len; ++i)
2295 v->contents[i] = Qnil;
2296 v->size = len;
2298 return (struct window *) v;
2302 struct frame *
2303 allocate_frame ()
2305 EMACS_INT len = VECSIZE (struct frame);
2306 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_FRAME);
2307 EMACS_INT i;
2309 for (i = 0; i < len; ++i)
2310 v->contents[i] = make_number (0);
2311 v->size = len;
2312 return (struct frame *) v;
2316 struct Lisp_Process *
2317 allocate_process ()
2319 EMACS_INT len = VECSIZE (struct Lisp_Process);
2320 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_PROCESS);
2321 EMACS_INT i;
2323 for (i = 0; i < len; ++i)
2324 v->contents[i] = Qnil;
2325 v->size = len;
2327 return (struct Lisp_Process *) v;
2331 struct Lisp_Vector *
2332 allocate_other_vector (len)
2333 EMACS_INT len;
2335 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_VECTOR);
2336 EMACS_INT i;
2338 for (i = 0; i < len; ++i)
2339 v->contents[i] = Qnil;
2340 v->size = len;
2342 return v;
2346 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
2347 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
2348 See also the function `vector'. */)
2349 (length, init)
2350 register Lisp_Object length, init;
2352 Lisp_Object vector;
2353 register EMACS_INT sizei;
2354 register int index;
2355 register struct Lisp_Vector *p;
2357 CHECK_NATNUM (length);
2358 sizei = XFASTINT (length);
2360 p = allocate_vector (sizei);
2361 for (index = 0; index < sizei; index++)
2362 p->contents[index] = init;
2364 XSETVECTOR (vector, p);
2365 return vector;
2369 DEFUN ("make-char-table", Fmake_char_table, Smake_char_table, 1, 2, 0,
2370 doc: /* Return a newly created char-table, with purpose PURPOSE.
2371 Each element is initialized to INIT, which defaults to nil.
2372 PURPOSE should be a symbol which has a `char-table-extra-slots' property.
2373 The property's value should be an integer between 0 and 10. */)
2374 (purpose, init)
2375 register Lisp_Object purpose, init;
2377 Lisp_Object vector;
2378 Lisp_Object n;
2379 CHECK_SYMBOL (purpose);
2380 n = Fget (purpose, Qchar_table_extra_slots);
2381 CHECK_NUMBER (n);
2382 if (XINT (n) < 0 || XINT (n) > 10)
2383 args_out_of_range (n, Qnil);
2384 /* Add 2 to the size for the defalt and parent slots. */
2385 vector = Fmake_vector (make_number (CHAR_TABLE_STANDARD_SLOTS + XINT (n)),
2386 init);
2387 XCHAR_TABLE (vector)->top = Qt;
2388 XCHAR_TABLE (vector)->parent = Qnil;
2389 XCHAR_TABLE (vector)->purpose = purpose;
2390 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
2391 return vector;
2395 /* Return a newly created sub char table with default value DEFALT.
2396 Since a sub char table does not appear as a top level Emacs Lisp
2397 object, we don't need a Lisp interface to make it. */
2399 Lisp_Object
2400 make_sub_char_table (defalt)
2401 Lisp_Object defalt;
2403 Lisp_Object vector
2404 = Fmake_vector (make_number (SUB_CHAR_TABLE_STANDARD_SLOTS), Qnil);
2405 XCHAR_TABLE (vector)->top = Qnil;
2406 XCHAR_TABLE (vector)->defalt = defalt;
2407 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
2408 return vector;
2412 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
2413 doc: /* Return a newly created vector with specified arguments as elements.
2414 Any number of arguments, even zero arguments, are allowed.
2415 usage: (vector &rest OBJECTS) */)
2416 (nargs, args)
2417 register int nargs;
2418 Lisp_Object *args;
2420 register Lisp_Object len, val;
2421 register int index;
2422 register struct Lisp_Vector *p;
2424 XSETFASTINT (len, nargs);
2425 val = Fmake_vector (len, Qnil);
2426 p = XVECTOR (val);
2427 for (index = 0; index < nargs; index++)
2428 p->contents[index] = args[index];
2429 return val;
2433 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
2434 doc: /* Create a byte-code object with specified arguments as elements.
2435 The arguments should be the arglist, bytecode-string, constant vector,
2436 stack size, (optional) doc string, and (optional) interactive spec.
2437 The first four arguments are required; at most six have any
2438 significance.
2439 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
2440 (nargs, args)
2441 register int nargs;
2442 Lisp_Object *args;
2444 register Lisp_Object len, val;
2445 register int index;
2446 register struct Lisp_Vector *p;
2448 XSETFASTINT (len, nargs);
2449 if (!NILP (Vpurify_flag))
2450 val = make_pure_vector ((EMACS_INT) nargs);
2451 else
2452 val = Fmake_vector (len, Qnil);
2454 if (STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
2455 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
2456 earlier because they produced a raw 8-bit string for byte-code
2457 and now such a byte-code string is loaded as multibyte while
2458 raw 8-bit characters converted to multibyte form. Thus, now we
2459 must convert them back to the original unibyte form. */
2460 args[1] = Fstring_as_unibyte (args[1]);
2462 p = XVECTOR (val);
2463 for (index = 0; index < nargs; index++)
2465 if (!NILP (Vpurify_flag))
2466 args[index] = Fpurecopy (args[index]);
2467 p->contents[index] = args[index];
2469 XSETCOMPILED (val, p);
2470 return val;
2475 /***********************************************************************
2476 Symbol Allocation
2477 ***********************************************************************/
2479 /* Each symbol_block is just under 1020 bytes long, since malloc
2480 really allocates in units of powers of two and uses 4 bytes for its
2481 own overhead. */
2483 #define SYMBOL_BLOCK_SIZE \
2484 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
2486 struct symbol_block
2488 struct symbol_block *next;
2489 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
2492 /* Current symbol block and index of first unused Lisp_Symbol
2493 structure in it. */
2495 struct symbol_block *symbol_block;
2496 int symbol_block_index;
2498 /* List of free symbols. */
2500 struct Lisp_Symbol *symbol_free_list;
2502 /* Total number of symbol blocks now in use. */
2504 int n_symbol_blocks;
2507 /* Initialize symbol allocation. */
2509 void
2510 init_symbol ()
2512 symbol_block = (struct symbol_block *) lisp_malloc (sizeof *symbol_block,
2513 MEM_TYPE_SYMBOL);
2514 symbol_block->next = 0;
2515 bzero ((char *) symbol_block->symbols, sizeof symbol_block->symbols);
2516 symbol_block_index = 0;
2517 symbol_free_list = 0;
2518 n_symbol_blocks = 1;
2522 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
2523 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
2524 Its value and function definition are void, and its property list is nil. */)
2525 (name)
2526 Lisp_Object name;
2528 register Lisp_Object val;
2529 register struct Lisp_Symbol *p;
2531 CHECK_STRING (name);
2533 if (symbol_free_list)
2535 XSETSYMBOL (val, symbol_free_list);
2536 symbol_free_list = *(struct Lisp_Symbol **)&symbol_free_list->value;
2538 else
2540 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
2542 struct symbol_block *new;
2543 new = (struct symbol_block *) lisp_malloc (sizeof *new,
2544 MEM_TYPE_SYMBOL);
2545 new->next = symbol_block;
2546 symbol_block = new;
2547 symbol_block_index = 0;
2548 n_symbol_blocks++;
2550 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index++]);
2553 p = XSYMBOL (val);
2554 p->xname = name;
2555 p->plist = Qnil;
2556 p->value = Qunbound;
2557 p->function = Qunbound;
2558 p->next = NULL;
2559 p->gcmarkbit = 0;
2560 p->interned = SYMBOL_UNINTERNED;
2561 p->constant = 0;
2562 p->indirect_variable = 0;
2563 consing_since_gc += sizeof (struct Lisp_Symbol);
2564 symbols_consed++;
2565 return val;
2570 /***********************************************************************
2571 Marker (Misc) Allocation
2572 ***********************************************************************/
2574 /* Allocation of markers and other objects that share that structure.
2575 Works like allocation of conses. */
2577 #define MARKER_BLOCK_SIZE \
2578 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
2580 struct marker_block
2582 struct marker_block *next;
2583 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
2586 struct marker_block *marker_block;
2587 int marker_block_index;
2589 union Lisp_Misc *marker_free_list;
2591 /* Total number of marker blocks now in use. */
2593 int n_marker_blocks;
2595 void
2596 init_marker ()
2598 marker_block = (struct marker_block *) lisp_malloc (sizeof *marker_block,
2599 MEM_TYPE_MISC);
2600 marker_block->next = 0;
2601 bzero ((char *) marker_block->markers, sizeof marker_block->markers);
2602 marker_block_index = 0;
2603 marker_free_list = 0;
2604 n_marker_blocks = 1;
2607 /* Return a newly allocated Lisp_Misc object, with no substructure. */
2609 Lisp_Object
2610 allocate_misc ()
2612 Lisp_Object val;
2614 if (marker_free_list)
2616 XSETMISC (val, marker_free_list);
2617 marker_free_list = marker_free_list->u_free.chain;
2619 else
2621 if (marker_block_index == MARKER_BLOCK_SIZE)
2623 struct marker_block *new;
2624 new = (struct marker_block *) lisp_malloc (sizeof *new,
2625 MEM_TYPE_MISC);
2626 new->next = marker_block;
2627 marker_block = new;
2628 marker_block_index = 0;
2629 n_marker_blocks++;
2631 XSETMISC (val, &marker_block->markers[marker_block_index++]);
2634 consing_since_gc += sizeof (union Lisp_Misc);
2635 misc_objects_consed++;
2636 XMARKER (val)->gcmarkbit = 0;
2637 return val;
2640 /* Return a Lisp_Misc_Save_Value object containing POINTER and
2641 INTEGER. This is used to package C values to call record_unwind_protect.
2642 The unwind function can get the C values back using XSAVE_VALUE. */
2644 Lisp_Object
2645 make_save_value (pointer, integer)
2646 void *pointer;
2647 int integer;
2649 register Lisp_Object val;
2650 register struct Lisp_Save_Value *p;
2652 val = allocate_misc ();
2653 XMISCTYPE (val) = Lisp_Misc_Save_Value;
2654 p = XSAVE_VALUE (val);
2655 p->pointer = pointer;
2656 p->integer = integer;
2657 return val;
2660 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
2661 doc: /* Return a newly allocated marker which does not point at any place. */)
2664 register Lisp_Object val;
2665 register struct Lisp_Marker *p;
2667 val = allocate_misc ();
2668 XMISCTYPE (val) = Lisp_Misc_Marker;
2669 p = XMARKER (val);
2670 p->buffer = 0;
2671 p->bytepos = 0;
2672 p->charpos = 0;
2673 p->next = NULL;
2674 p->insertion_type = 0;
2675 return val;
2678 /* Put MARKER back on the free list after using it temporarily. */
2680 void
2681 free_marker (marker)
2682 Lisp_Object marker;
2684 unchain_marker (XMARKER (marker));
2686 XMISC (marker)->u_marker.type = Lisp_Misc_Free;
2687 XMISC (marker)->u_free.chain = marker_free_list;
2688 marker_free_list = XMISC (marker);
2690 total_free_markers++;
2694 /* Return a newly created vector or string with specified arguments as
2695 elements. If all the arguments are characters that can fit
2696 in a string of events, make a string; otherwise, make a vector.
2698 Any number of arguments, even zero arguments, are allowed. */
2700 Lisp_Object
2701 make_event_array (nargs, args)
2702 register int nargs;
2703 Lisp_Object *args;
2705 int i;
2707 for (i = 0; i < nargs; i++)
2708 /* The things that fit in a string
2709 are characters that are in 0...127,
2710 after discarding the meta bit and all the bits above it. */
2711 if (!INTEGERP (args[i])
2712 || (XUINT (args[i]) & ~(-CHAR_META)) >= 0200)
2713 return Fvector (nargs, args);
2715 /* Since the loop exited, we know that all the things in it are
2716 characters, so we can make a string. */
2718 Lisp_Object result;
2720 result = Fmake_string (make_number (nargs), make_number (0));
2721 for (i = 0; i < nargs; i++)
2723 SSET (result, i, XINT (args[i]));
2724 /* Move the meta bit to the right place for a string char. */
2725 if (XINT (args[i]) & CHAR_META)
2726 SSET (result, i, SREF (result, i) | 0x80);
2729 return result;
2735 /************************************************************************
2736 C Stack Marking
2737 ************************************************************************/
2739 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
2741 /* Conservative C stack marking requires a method to identify possibly
2742 live Lisp objects given a pointer value. We do this by keeping
2743 track of blocks of Lisp data that are allocated in a red-black tree
2744 (see also the comment of mem_node which is the type of nodes in
2745 that tree). Function lisp_malloc adds information for an allocated
2746 block to the red-black tree with calls to mem_insert, and function
2747 lisp_free removes it with mem_delete. Functions live_string_p etc
2748 call mem_find to lookup information about a given pointer in the
2749 tree, and use that to determine if the pointer points to a Lisp
2750 object or not. */
2752 /* Initialize this part of alloc.c. */
2754 static void
2755 mem_init ()
2757 mem_z.left = mem_z.right = MEM_NIL;
2758 mem_z.parent = NULL;
2759 mem_z.color = MEM_BLACK;
2760 mem_z.start = mem_z.end = NULL;
2761 mem_root = MEM_NIL;
2765 /* Value is a pointer to the mem_node containing START. Value is
2766 MEM_NIL if there is no node in the tree containing START. */
2768 static INLINE struct mem_node *
2769 mem_find (start)
2770 void *start;
2772 struct mem_node *p;
2774 if (start < min_heap_address || start > max_heap_address)
2775 return MEM_NIL;
2777 /* Make the search always successful to speed up the loop below. */
2778 mem_z.start = start;
2779 mem_z.end = (char *) start + 1;
2781 p = mem_root;
2782 while (start < p->start || start >= p->end)
2783 p = start < p->start ? p->left : p->right;
2784 return p;
2788 /* Insert a new node into the tree for a block of memory with start
2789 address START, end address END, and type TYPE. Value is a
2790 pointer to the node that was inserted. */
2792 static struct mem_node *
2793 mem_insert (start, end, type)
2794 void *start, *end;
2795 enum mem_type type;
2797 struct mem_node *c, *parent, *x;
2799 if (start < min_heap_address)
2800 min_heap_address = start;
2801 if (end > max_heap_address)
2802 max_heap_address = end;
2804 /* See where in the tree a node for START belongs. In this
2805 particular application, it shouldn't happen that a node is already
2806 present. For debugging purposes, let's check that. */
2807 c = mem_root;
2808 parent = NULL;
2810 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
2812 while (c != MEM_NIL)
2814 if (start >= c->start && start < c->end)
2815 abort ();
2816 parent = c;
2817 c = start < c->start ? c->left : c->right;
2820 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2822 while (c != MEM_NIL)
2824 parent = c;
2825 c = start < c->start ? c->left : c->right;
2828 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2830 /* Create a new node. */
2831 #ifdef GC_MALLOC_CHECK
2832 x = (struct mem_node *) _malloc_internal (sizeof *x);
2833 if (x == NULL)
2834 abort ();
2835 #else
2836 x = (struct mem_node *) xmalloc (sizeof *x);
2837 #endif
2838 x->start = start;
2839 x->end = end;
2840 x->type = type;
2841 x->parent = parent;
2842 x->left = x->right = MEM_NIL;
2843 x->color = MEM_RED;
2845 /* Insert it as child of PARENT or install it as root. */
2846 if (parent)
2848 if (start < parent->start)
2849 parent->left = x;
2850 else
2851 parent->right = x;
2853 else
2854 mem_root = x;
2856 /* Re-establish red-black tree properties. */
2857 mem_insert_fixup (x);
2859 return x;
2863 /* Re-establish the red-black properties of the tree, and thereby
2864 balance the tree, after node X has been inserted; X is always red. */
2866 static void
2867 mem_insert_fixup (x)
2868 struct mem_node *x;
2870 while (x != mem_root && x->parent->color == MEM_RED)
2872 /* X is red and its parent is red. This is a violation of
2873 red-black tree property #3. */
2875 if (x->parent == x->parent->parent->left)
2877 /* We're on the left side of our grandparent, and Y is our
2878 "uncle". */
2879 struct mem_node *y = x->parent->parent->right;
2881 if (y->color == MEM_RED)
2883 /* Uncle and parent are red but should be black because
2884 X is red. Change the colors accordingly and proceed
2885 with the grandparent. */
2886 x->parent->color = MEM_BLACK;
2887 y->color = MEM_BLACK;
2888 x->parent->parent->color = MEM_RED;
2889 x = x->parent->parent;
2891 else
2893 /* Parent and uncle have different colors; parent is
2894 red, uncle is black. */
2895 if (x == x->parent->right)
2897 x = x->parent;
2898 mem_rotate_left (x);
2901 x->parent->color = MEM_BLACK;
2902 x->parent->parent->color = MEM_RED;
2903 mem_rotate_right (x->parent->parent);
2906 else
2908 /* This is the symmetrical case of above. */
2909 struct mem_node *y = x->parent->parent->left;
2911 if (y->color == MEM_RED)
2913 x->parent->color = MEM_BLACK;
2914 y->color = MEM_BLACK;
2915 x->parent->parent->color = MEM_RED;
2916 x = x->parent->parent;
2918 else
2920 if (x == x->parent->left)
2922 x = x->parent;
2923 mem_rotate_right (x);
2926 x->parent->color = MEM_BLACK;
2927 x->parent->parent->color = MEM_RED;
2928 mem_rotate_left (x->parent->parent);
2933 /* The root may have been changed to red due to the algorithm. Set
2934 it to black so that property #5 is satisfied. */
2935 mem_root->color = MEM_BLACK;
2939 /* (x) (y)
2940 / \ / \
2941 a (y) ===> (x) c
2942 / \ / \
2943 b c a b */
2945 static void
2946 mem_rotate_left (x)
2947 struct mem_node *x;
2949 struct mem_node *y;
2951 /* Turn y's left sub-tree into x's right sub-tree. */
2952 y = x->right;
2953 x->right = y->left;
2954 if (y->left != MEM_NIL)
2955 y->left->parent = x;
2957 /* Y's parent was x's parent. */
2958 if (y != MEM_NIL)
2959 y->parent = x->parent;
2961 /* Get the parent to point to y instead of x. */
2962 if (x->parent)
2964 if (x == x->parent->left)
2965 x->parent->left = y;
2966 else
2967 x->parent->right = y;
2969 else
2970 mem_root = y;
2972 /* Put x on y's left. */
2973 y->left = x;
2974 if (x != MEM_NIL)
2975 x->parent = y;
2979 /* (x) (Y)
2980 / \ / \
2981 (y) c ===> a (x)
2982 / \ / \
2983 a b b c */
2985 static void
2986 mem_rotate_right (x)
2987 struct mem_node *x;
2989 struct mem_node *y = x->left;
2991 x->left = y->right;
2992 if (y->right != MEM_NIL)
2993 y->right->parent = x;
2995 if (y != MEM_NIL)
2996 y->parent = x->parent;
2997 if (x->parent)
2999 if (x == x->parent->right)
3000 x->parent->right = y;
3001 else
3002 x->parent->left = y;
3004 else
3005 mem_root = y;
3007 y->right = x;
3008 if (x != MEM_NIL)
3009 x->parent = y;
3013 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
3015 static void
3016 mem_delete (z)
3017 struct mem_node *z;
3019 struct mem_node *x, *y;
3021 if (!z || z == MEM_NIL)
3022 return;
3024 if (z->left == MEM_NIL || z->right == MEM_NIL)
3025 y = z;
3026 else
3028 y = z->right;
3029 while (y->left != MEM_NIL)
3030 y = y->left;
3033 if (y->left != MEM_NIL)
3034 x = y->left;
3035 else
3036 x = y->right;
3038 x->parent = y->parent;
3039 if (y->parent)
3041 if (y == y->parent->left)
3042 y->parent->left = x;
3043 else
3044 y->parent->right = x;
3046 else
3047 mem_root = x;
3049 if (y != z)
3051 z->start = y->start;
3052 z->end = y->end;
3053 z->type = y->type;
3056 if (y->color == MEM_BLACK)
3057 mem_delete_fixup (x);
3059 #ifdef GC_MALLOC_CHECK
3060 _free_internal (y);
3061 #else
3062 xfree (y);
3063 #endif
3067 /* Re-establish the red-black properties of the tree, after a
3068 deletion. */
3070 static void
3071 mem_delete_fixup (x)
3072 struct mem_node *x;
3074 while (x != mem_root && x->color == MEM_BLACK)
3076 if (x == x->parent->left)
3078 struct mem_node *w = x->parent->right;
3080 if (w->color == MEM_RED)
3082 w->color = MEM_BLACK;
3083 x->parent->color = MEM_RED;
3084 mem_rotate_left (x->parent);
3085 w = x->parent->right;
3088 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
3090 w->color = MEM_RED;
3091 x = x->parent;
3093 else
3095 if (w->right->color == MEM_BLACK)
3097 w->left->color = MEM_BLACK;
3098 w->color = MEM_RED;
3099 mem_rotate_right (w);
3100 w = x->parent->right;
3102 w->color = x->parent->color;
3103 x->parent->color = MEM_BLACK;
3104 w->right->color = MEM_BLACK;
3105 mem_rotate_left (x->parent);
3106 x = mem_root;
3109 else
3111 struct mem_node *w = x->parent->left;
3113 if (w->color == MEM_RED)
3115 w->color = MEM_BLACK;
3116 x->parent->color = MEM_RED;
3117 mem_rotate_right (x->parent);
3118 w = x->parent->left;
3121 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
3123 w->color = MEM_RED;
3124 x = x->parent;
3126 else
3128 if (w->left->color == MEM_BLACK)
3130 w->right->color = MEM_BLACK;
3131 w->color = MEM_RED;
3132 mem_rotate_left (w);
3133 w = x->parent->left;
3136 w->color = x->parent->color;
3137 x->parent->color = MEM_BLACK;
3138 w->left->color = MEM_BLACK;
3139 mem_rotate_right (x->parent);
3140 x = mem_root;
3145 x->color = MEM_BLACK;
3149 /* Value is non-zero if P is a pointer to a live Lisp string on
3150 the heap. M is a pointer to the mem_block for P. */
3152 static INLINE int
3153 live_string_p (m, p)
3154 struct mem_node *m;
3155 void *p;
3157 if (m->type == MEM_TYPE_STRING)
3159 struct string_block *b = (struct string_block *) m->start;
3160 int offset = (char *) p - (char *) &b->strings[0];
3162 /* P must point to the start of a Lisp_String structure, and it
3163 must not be on the free-list. */
3164 return (offset >= 0
3165 && offset % sizeof b->strings[0] == 0
3166 && ((struct Lisp_String *) p)->data != NULL);
3168 else
3169 return 0;
3173 /* Value is non-zero if P is a pointer to a live Lisp cons on
3174 the heap. M is a pointer to the mem_block for P. */
3176 static INLINE int
3177 live_cons_p (m, p)
3178 struct mem_node *m;
3179 void *p;
3181 if (m->type == MEM_TYPE_CONS)
3183 struct cons_block *b = (struct cons_block *) m->start;
3184 int offset = (char *) p - (char *) &b->conses[0];
3186 /* P must point to the start of a Lisp_Cons, not be
3187 one of the unused cells in the current cons block,
3188 and not be on the free-list. */
3189 return (offset >= 0
3190 && offset % sizeof b->conses[0] == 0
3191 && (b != cons_block
3192 || offset / sizeof b->conses[0] < cons_block_index)
3193 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
3195 else
3196 return 0;
3200 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3201 the heap. M is a pointer to the mem_block for P. */
3203 static INLINE int
3204 live_symbol_p (m, p)
3205 struct mem_node *m;
3206 void *p;
3208 if (m->type == MEM_TYPE_SYMBOL)
3210 struct symbol_block *b = (struct symbol_block *) m->start;
3211 int offset = (char *) p - (char *) &b->symbols[0];
3213 /* P must point to the start of a Lisp_Symbol, not be
3214 one of the unused cells in the current symbol block,
3215 and not be on the free-list. */
3216 return (offset >= 0
3217 && offset % sizeof b->symbols[0] == 0
3218 && (b != symbol_block
3219 || offset / sizeof b->symbols[0] < symbol_block_index)
3220 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
3222 else
3223 return 0;
3227 /* Value is non-zero if P is a pointer to a live Lisp float on
3228 the heap. M is a pointer to the mem_block for P. */
3230 static INLINE int
3231 live_float_p (m, p)
3232 struct mem_node *m;
3233 void *p;
3235 if (m->type == MEM_TYPE_FLOAT)
3237 struct float_block *b = (struct float_block *) m->start;
3238 int offset = (char *) p - (char *) &b->floats[0];
3240 /* P must point to the start of a Lisp_Float, not be
3241 one of the unused cells in the current float block,
3242 and not be on the free-list. */
3243 return (offset >= 0
3244 && offset % sizeof b->floats[0] == 0
3245 && (b != float_block
3246 || offset / sizeof b->floats[0] < float_block_index)
3247 && !EQ (((struct Lisp_Float *) p)->type, Vdead));
3249 else
3250 return 0;
3254 /* Value is non-zero if P is a pointer to a live Lisp Misc on
3255 the heap. M is a pointer to the mem_block for P. */
3257 static INLINE int
3258 live_misc_p (m, p)
3259 struct mem_node *m;
3260 void *p;
3262 if (m->type == MEM_TYPE_MISC)
3264 struct marker_block *b = (struct marker_block *) m->start;
3265 int offset = (char *) p - (char *) &b->markers[0];
3267 /* P must point to the start of a Lisp_Misc, not be
3268 one of the unused cells in the current misc block,
3269 and not be on the free-list. */
3270 return (offset >= 0
3271 && offset % sizeof b->markers[0] == 0
3272 && (b != marker_block
3273 || offset / sizeof b->markers[0] < marker_block_index)
3274 && ((union Lisp_Misc *) p)->u_marker.type != Lisp_Misc_Free);
3276 else
3277 return 0;
3281 /* Value is non-zero if P is a pointer to a live vector-like object.
3282 M is a pointer to the mem_block for P. */
3284 static INLINE int
3285 live_vector_p (m, p)
3286 struct mem_node *m;
3287 void *p;
3289 return (p == m->start
3290 && m->type >= MEM_TYPE_VECTOR
3291 && m->type <= MEM_TYPE_WINDOW);
3295 /* Value is non-zero if P is a pointer to a live buffer. M is a
3296 pointer to the mem_block for P. */
3298 static INLINE int
3299 live_buffer_p (m, p)
3300 struct mem_node *m;
3301 void *p;
3303 /* P must point to the start of the block, and the buffer
3304 must not have been killed. */
3305 return (m->type == MEM_TYPE_BUFFER
3306 && p == m->start
3307 && !NILP (((struct buffer *) p)->name));
3310 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
3312 #if GC_MARK_STACK
3314 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3316 /* Array of objects that are kept alive because the C stack contains
3317 a pattern that looks like a reference to them . */
3319 #define MAX_ZOMBIES 10
3320 static Lisp_Object zombies[MAX_ZOMBIES];
3322 /* Number of zombie objects. */
3324 static int nzombies;
3326 /* Number of garbage collections. */
3328 static int ngcs;
3330 /* Average percentage of zombies per collection. */
3332 static double avg_zombies;
3334 /* Max. number of live and zombie objects. */
3336 static int max_live, max_zombies;
3338 /* Average number of live objects per GC. */
3340 static double avg_live;
3342 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
3343 doc: /* Show information about live and zombie objects. */)
3346 Lisp_Object args[8], zombie_list = Qnil;
3347 int i;
3348 for (i = 0; i < nzombies; i++)
3349 zombie_list = Fcons (zombies[i], zombie_list);
3350 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
3351 args[1] = make_number (ngcs);
3352 args[2] = make_float (avg_live);
3353 args[3] = make_float (avg_zombies);
3354 args[4] = make_float (avg_zombies / avg_live / 100);
3355 args[5] = make_number (max_live);
3356 args[6] = make_number (max_zombies);
3357 args[7] = zombie_list;
3358 return Fmessage (8, args);
3361 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3364 /* Mark OBJ if we can prove it's a Lisp_Object. */
3366 static INLINE void
3367 mark_maybe_object (obj)
3368 Lisp_Object obj;
3370 void *po = (void *) XPNTR (obj);
3371 struct mem_node *m = mem_find (po);
3373 if (m != MEM_NIL)
3375 int mark_p = 0;
3377 switch (XGCTYPE (obj))
3379 case Lisp_String:
3380 mark_p = (live_string_p (m, po)
3381 && !STRING_MARKED_P ((struct Lisp_String *) po));
3382 break;
3384 case Lisp_Cons:
3385 mark_p = (live_cons_p (m, po)
3386 && !XMARKBIT (XCONS (obj)->car));
3387 break;
3389 case Lisp_Symbol:
3390 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
3391 break;
3393 case Lisp_Float:
3394 mark_p = (live_float_p (m, po)
3395 && !XMARKBIT (XFLOAT (obj)->type));
3396 break;
3398 case Lisp_Vectorlike:
3399 /* Note: can't check GC_BUFFERP before we know it's a
3400 buffer because checking that dereferences the pointer
3401 PO which might point anywhere. */
3402 if (live_vector_p (m, po))
3403 mark_p = (!GC_SUBRP (obj)
3404 && !(XVECTOR (obj)->size & ARRAY_MARK_FLAG));
3405 else if (live_buffer_p (m, po))
3406 mark_p = GC_BUFFERP (obj) && !XMARKBIT (XBUFFER (obj)->name);
3407 break;
3409 case Lisp_Misc:
3410 mark_p = (live_misc_p (m, po) && !XMARKER (obj)->gcmarkbit);
3411 break;
3413 case Lisp_Int:
3414 case Lisp_Type_Limit:
3415 break;
3418 if (mark_p)
3420 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3421 if (nzombies < MAX_ZOMBIES)
3422 zombies[nzombies] = obj;
3423 ++nzombies;
3424 #endif
3425 mark_object (&obj);
3431 /* If P points to Lisp data, mark that as live if it isn't already
3432 marked. */
3434 static INLINE void
3435 mark_maybe_pointer (p)
3436 void *p;
3438 struct mem_node *m;
3440 /* Quickly rule out some values which can't point to Lisp data. We
3441 assume that Lisp data is aligned on even addresses. */
3442 if ((EMACS_INT) p & 1)
3443 return;
3445 m = mem_find (p);
3446 if (m != MEM_NIL)
3448 Lisp_Object obj = Qnil;
3450 switch (m->type)
3452 case MEM_TYPE_NON_LISP:
3453 /* Nothing to do; not a pointer to Lisp memory. */
3454 break;
3456 case MEM_TYPE_BUFFER:
3457 if (live_buffer_p (m, p)
3458 && !XMARKBIT (((struct buffer *) p)->name))
3459 XSETVECTOR (obj, p);
3460 break;
3462 case MEM_TYPE_CONS:
3463 if (live_cons_p (m, p)
3464 && !XMARKBIT (((struct Lisp_Cons *) p)->car))
3465 XSETCONS (obj, p);
3466 break;
3468 case MEM_TYPE_STRING:
3469 if (live_string_p (m, p)
3470 && !STRING_MARKED_P ((struct Lisp_String *) p))
3471 XSETSTRING (obj, p);
3472 break;
3474 case MEM_TYPE_MISC:
3475 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
3476 XSETMISC (obj, p);
3477 break;
3479 case MEM_TYPE_SYMBOL:
3480 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
3481 XSETSYMBOL (obj, p);
3482 break;
3484 case MEM_TYPE_FLOAT:
3485 if (live_float_p (m, p)
3486 && !XMARKBIT (((struct Lisp_Float *) p)->type))
3487 XSETFLOAT (obj, p);
3488 break;
3490 case MEM_TYPE_VECTOR:
3491 case MEM_TYPE_PROCESS:
3492 case MEM_TYPE_HASH_TABLE:
3493 case MEM_TYPE_FRAME:
3494 case MEM_TYPE_WINDOW:
3495 if (live_vector_p (m, p))
3497 Lisp_Object tem;
3498 XSETVECTOR (tem, p);
3499 if (!GC_SUBRP (tem)
3500 && !(XVECTOR (tem)->size & ARRAY_MARK_FLAG))
3501 obj = tem;
3503 break;
3505 default:
3506 abort ();
3509 if (!GC_NILP (obj))
3510 mark_object (&obj);
3515 /* Mark Lisp objects referenced from the address range START..END. */
3517 static void
3518 mark_memory (start, end)
3519 void *start, *end;
3521 Lisp_Object *p;
3522 void **pp;
3524 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3525 nzombies = 0;
3526 #endif
3528 /* Make START the pointer to the start of the memory region,
3529 if it isn't already. */
3530 if (end < start)
3532 void *tem = start;
3533 start = end;
3534 end = tem;
3537 /* Mark Lisp_Objects. */
3538 for (p = (Lisp_Object *) start; (void *) p < end; ++p)
3539 mark_maybe_object (*p);
3541 /* Mark Lisp data pointed to. This is necessary because, in some
3542 situations, the C compiler optimizes Lisp objects away, so that
3543 only a pointer to them remains. Example:
3545 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
3548 Lisp_Object obj = build_string ("test");
3549 struct Lisp_String *s = XSTRING (obj);
3550 Fgarbage_collect ();
3551 fprintf (stderr, "test `%s'\n", s->data);
3552 return Qnil;
3555 Here, `obj' isn't really used, and the compiler optimizes it
3556 away. The only reference to the life string is through the
3557 pointer `s'. */
3559 for (pp = (void **) start; (void *) pp < end; ++pp)
3560 mark_maybe_pointer (*pp);
3563 /* setjmp will work with GCC unless NON_SAVING_SETJMP is defined in
3564 the GCC system configuration. In gcc 3.2, the only systems for
3565 which this is so are i386-sco5 non-ELF, i386-sysv3 (maybe included
3566 by others?) and ns32k-pc532-min. */
3568 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
3570 static int setjmp_tested_p, longjmps_done;
3572 #define SETJMP_WILL_LIKELY_WORK "\
3574 Emacs garbage collector has been changed to use conservative stack\n\
3575 marking. Emacs has determined that the method it uses to do the\n\
3576 marking will likely work on your system, but this isn't sure.\n\
3578 If you are a system-programmer, or can get the help of a local wizard\n\
3579 who is, please take a look at the function mark_stack in alloc.c, and\n\
3580 verify that the methods used are appropriate for your system.\n\
3582 Please mail the result to <emacs-devel@gnu.org>.\n\
3585 #define SETJMP_WILL_NOT_WORK "\
3587 Emacs garbage collector has been changed to use conservative stack\n\
3588 marking. Emacs has determined that the default method it uses to do the\n\
3589 marking will not work on your system. We will need a system-dependent\n\
3590 solution for your system.\n\
3592 Please take a look at the function mark_stack in alloc.c, and\n\
3593 try to find a way to make it work on your system.\n\
3595 Note that you may get false negatives, depending on the compiler.\n\
3596 In particular, you need to use -O with GCC for this test.\n\
3598 Please mail the result to <emacs-devel@gnu.org>.\n\
3602 /* Perform a quick check if it looks like setjmp saves registers in a
3603 jmp_buf. Print a message to stderr saying so. When this test
3604 succeeds, this is _not_ a proof that setjmp is sufficient for
3605 conservative stack marking. Only the sources or a disassembly
3606 can prove that. */
3608 static void
3609 test_setjmp ()
3611 char buf[10];
3612 register int x;
3613 jmp_buf jbuf;
3614 int result = 0;
3616 /* Arrange for X to be put in a register. */
3617 sprintf (buf, "1");
3618 x = strlen (buf);
3619 x = 2 * x - 1;
3621 setjmp (jbuf);
3622 if (longjmps_done == 1)
3624 /* Came here after the longjmp at the end of the function.
3626 If x == 1, the longjmp has restored the register to its
3627 value before the setjmp, and we can hope that setjmp
3628 saves all such registers in the jmp_buf, although that
3629 isn't sure.
3631 For other values of X, either something really strange is
3632 taking place, or the setjmp just didn't save the register. */
3634 if (x == 1)
3635 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
3636 else
3638 fprintf (stderr, SETJMP_WILL_NOT_WORK);
3639 exit (1);
3643 ++longjmps_done;
3644 x = 2;
3645 if (longjmps_done == 1)
3646 longjmp (jbuf, 1);
3649 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
3652 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
3654 /* Abort if anything GCPRO'd doesn't survive the GC. */
3656 static void
3657 check_gcpros ()
3659 struct gcpro *p;
3660 int i;
3662 for (p = gcprolist; p; p = p->next)
3663 for (i = 0; i < p->nvars; ++i)
3664 if (!survives_gc_p (p->var[i]))
3665 /* FIXME: It's not necessarily a bug. It might just be that the
3666 GCPRO is unnecessary or should release the object sooner. */
3667 abort ();
3670 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3672 static void
3673 dump_zombies ()
3675 int i;
3677 fprintf (stderr, "\nZombies kept alive = %d:\n", nzombies);
3678 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
3680 fprintf (stderr, " %d = ", i);
3681 debug_print (zombies[i]);
3685 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3688 /* Mark live Lisp objects on the C stack.
3690 There are several system-dependent problems to consider when
3691 porting this to new architectures:
3693 Processor Registers
3695 We have to mark Lisp objects in CPU registers that can hold local
3696 variables or are used to pass parameters.
3698 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
3699 something that either saves relevant registers on the stack, or
3700 calls mark_maybe_object passing it each register's contents.
3702 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
3703 implementation assumes that calling setjmp saves registers we need
3704 to see in a jmp_buf which itself lies on the stack. This doesn't
3705 have to be true! It must be verified for each system, possibly
3706 by taking a look at the source code of setjmp.
3708 Stack Layout
3710 Architectures differ in the way their processor stack is organized.
3711 For example, the stack might look like this
3713 +----------------+
3714 | Lisp_Object | size = 4
3715 +----------------+
3716 | something else | size = 2
3717 +----------------+
3718 | Lisp_Object | size = 4
3719 +----------------+
3720 | ... |
3722 In such a case, not every Lisp_Object will be aligned equally. To
3723 find all Lisp_Object on the stack it won't be sufficient to walk
3724 the stack in steps of 4 bytes. Instead, two passes will be
3725 necessary, one starting at the start of the stack, and a second
3726 pass starting at the start of the stack + 2. Likewise, if the
3727 minimal alignment of Lisp_Objects on the stack is 1, four passes
3728 would be necessary, each one starting with one byte more offset
3729 from the stack start.
3731 The current code assumes by default that Lisp_Objects are aligned
3732 equally on the stack. */
3734 static void
3735 mark_stack ()
3737 int i;
3738 jmp_buf j;
3739 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
3740 void *end;
3742 /* This trick flushes the register windows so that all the state of
3743 the process is contained in the stack. */
3744 /* Fixme: Code in the Boehm GC sugests flushing (with `flushrs') is
3745 needed on ia64 too. See mach_dep.c, where it also says inline
3746 assembler doesn't work with relevant proprietary compilers. */
3747 #ifdef sparc
3748 asm ("ta 3");
3749 #endif
3751 /* Save registers that we need to see on the stack. We need to see
3752 registers used to hold register variables and registers used to
3753 pass parameters. */
3754 #ifdef GC_SAVE_REGISTERS_ON_STACK
3755 GC_SAVE_REGISTERS_ON_STACK (end);
3756 #else /* not GC_SAVE_REGISTERS_ON_STACK */
3758 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
3759 setjmp will definitely work, test it
3760 and print a message with the result
3761 of the test. */
3762 if (!setjmp_tested_p)
3764 setjmp_tested_p = 1;
3765 test_setjmp ();
3767 #endif /* GC_SETJMP_WORKS */
3769 setjmp (j);
3770 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
3771 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
3773 /* This assumes that the stack is a contiguous region in memory. If
3774 that's not the case, something has to be done here to iterate
3775 over the stack segments. */
3776 #ifndef GC_LISP_OBJECT_ALIGNMENT
3777 #ifdef __GNUC__
3778 #define GC_LISP_OBJECT_ALIGNMENT __alignof__ (Lisp_Object)
3779 #else
3780 #define GC_LISP_OBJECT_ALIGNMENT sizeof (Lisp_Object)
3781 #endif
3782 #endif
3783 for (i = 0; i < sizeof (Lisp_Object); i += GC_LISP_OBJECT_ALIGNMENT)
3784 mark_memory ((char *) stack_base + i, end);
3786 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
3787 check_gcpros ();
3788 #endif
3792 #endif /* GC_MARK_STACK != 0 */
3796 /***********************************************************************
3797 Pure Storage Management
3798 ***********************************************************************/
3800 /* Allocate room for SIZE bytes from pure Lisp storage and return a
3801 pointer to it. TYPE is the Lisp type for which the memory is
3802 allocated. TYPE < 0 means it's not used for a Lisp object.
3804 If store_pure_type_info is set and TYPE is >= 0, the type of
3805 the allocated object is recorded in pure_types. */
3807 static POINTER_TYPE *
3808 pure_alloc (size, type)
3809 size_t size;
3810 int type;
3812 POINTER_TYPE *result;
3813 size_t alignment = sizeof (EMACS_INT);
3815 /* Give Lisp_Floats an extra alignment. */
3816 if (type == Lisp_Float)
3818 #if defined __GNUC__ && __GNUC__ >= 2
3819 alignment = __alignof (struct Lisp_Float);
3820 #else
3821 alignment = sizeof (struct Lisp_Float);
3822 #endif
3825 again:
3826 result = (POINTER_TYPE *) ALIGN ((EMACS_UINT)purebeg + pure_bytes_used, alignment);
3827 pure_bytes_used = ((char *)result - (char *)purebeg) + size;
3829 if (pure_bytes_used <= pure_size)
3830 return result;
3832 /* Don't allocate a large amount here,
3833 because it might get mmap'd and then its address
3834 might not be usable. */
3835 purebeg = (char *) xmalloc (10000);
3836 pure_size = 10000;
3837 pure_bytes_used_before_overflow += pure_bytes_used - size;
3838 pure_bytes_used = 0;
3839 goto again;
3843 /* Print a warning if PURESIZE is too small. */
3845 void
3846 check_pure_size ()
3848 if (pure_bytes_used_before_overflow)
3849 message ("Pure Lisp storage overflow (approx. %d bytes needed)",
3850 (int) (pure_bytes_used + pure_bytes_used_before_overflow));
3854 /* Return a string allocated in pure space. DATA is a buffer holding
3855 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
3856 non-zero means make the result string multibyte.
3858 Must get an error if pure storage is full, since if it cannot hold
3859 a large string it may be able to hold conses that point to that
3860 string; then the string is not protected from gc. */
3862 Lisp_Object
3863 make_pure_string (data, nchars, nbytes, multibyte)
3864 char *data;
3865 int nchars, nbytes;
3866 int multibyte;
3868 Lisp_Object string;
3869 struct Lisp_String *s;
3871 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
3872 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
3873 s->size = nchars;
3874 s->size_byte = multibyte ? nbytes : -1;
3875 bcopy (data, s->data, nbytes);
3876 s->data[nbytes] = '\0';
3877 s->intervals = NULL_INTERVAL;
3878 XSETSTRING (string, s);
3879 return string;
3883 /* Return a cons allocated from pure space. Give it pure copies
3884 of CAR as car and CDR as cdr. */
3886 Lisp_Object
3887 pure_cons (car, cdr)
3888 Lisp_Object car, cdr;
3890 register Lisp_Object new;
3891 struct Lisp_Cons *p;
3893 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
3894 XSETCONS (new, p);
3895 XSETCAR (new, Fpurecopy (car));
3896 XSETCDR (new, Fpurecopy (cdr));
3897 return new;
3901 /* Value is a float object with value NUM allocated from pure space. */
3903 Lisp_Object
3904 make_pure_float (num)
3905 double num;
3907 register Lisp_Object new;
3908 struct Lisp_Float *p;
3910 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
3911 XSETFLOAT (new, p);
3912 XFLOAT_DATA (new) = num;
3913 return new;
3917 /* Return a vector with room for LEN Lisp_Objects allocated from
3918 pure space. */
3920 Lisp_Object
3921 make_pure_vector (len)
3922 EMACS_INT len;
3924 Lisp_Object new;
3925 struct Lisp_Vector *p;
3926 size_t size = sizeof *p + (len - 1) * sizeof (Lisp_Object);
3928 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
3929 XSETVECTOR (new, p);
3930 XVECTOR (new)->size = len;
3931 return new;
3935 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
3936 doc: /* Make a copy of OBJECT in pure storage.
3937 Recursively copies contents of vectors and cons cells.
3938 Does not copy symbols. Copies strings without text properties. */)
3939 (obj)
3940 register Lisp_Object obj;
3942 if (NILP (Vpurify_flag))
3943 return obj;
3945 if (PURE_POINTER_P (XPNTR (obj)))
3946 return obj;
3948 if (CONSP (obj))
3949 return pure_cons (XCAR (obj), XCDR (obj));
3950 else if (FLOATP (obj))
3951 return make_pure_float (XFLOAT_DATA (obj));
3952 else if (STRINGP (obj))
3953 return make_pure_string (SDATA (obj), SCHARS (obj),
3954 SBYTES (obj),
3955 STRING_MULTIBYTE (obj));
3956 else if (COMPILEDP (obj) || VECTORP (obj))
3958 register struct Lisp_Vector *vec;
3959 register int i, size;
3961 size = XVECTOR (obj)->size;
3962 if (size & PSEUDOVECTOR_FLAG)
3963 size &= PSEUDOVECTOR_SIZE_MASK;
3964 vec = XVECTOR (make_pure_vector ((EMACS_INT) size));
3965 for (i = 0; i < size; i++)
3966 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
3967 if (COMPILEDP (obj))
3968 XSETCOMPILED (obj, vec);
3969 else
3970 XSETVECTOR (obj, vec);
3971 return obj;
3973 else if (MARKERP (obj))
3974 error ("Attempt to copy a marker to pure storage");
3976 return obj;
3981 /***********************************************************************
3982 Protection from GC
3983 ***********************************************************************/
3985 /* Put an entry in staticvec, pointing at the variable with address
3986 VARADDRESS. */
3988 void
3989 staticpro (varaddress)
3990 Lisp_Object *varaddress;
3992 staticvec[staticidx++] = varaddress;
3993 if (staticidx >= NSTATICS)
3994 abort ();
3997 struct catchtag
3999 Lisp_Object tag;
4000 Lisp_Object val;
4001 struct catchtag *next;
4004 struct backtrace
4006 struct backtrace *next;
4007 Lisp_Object *function;
4008 Lisp_Object *args; /* Points to vector of args. */
4009 int nargs; /* Length of vector. */
4010 /* If nargs is UNEVALLED, args points to slot holding list of
4011 unevalled args. */
4012 char evalargs;
4017 /***********************************************************************
4018 Protection from GC
4019 ***********************************************************************/
4021 /* Temporarily prevent garbage collection. */
4024 inhibit_garbage_collection ()
4026 int count = SPECPDL_INDEX ();
4027 int nbits = min (VALBITS, BITS_PER_INT);
4029 specbind (Qgc_cons_threshold, make_number (((EMACS_INT) 1 << (nbits - 1)) - 1));
4030 return count;
4034 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
4035 doc: /* Reclaim storage for Lisp objects no longer needed.
4036 Returns info on amount of space in use:
4037 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
4038 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
4039 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)
4040 (USED-STRINGS . FREE-STRINGS))
4041 Garbage collection happens automatically if you cons more than
4042 `gc-cons-threshold' bytes of Lisp data since previous garbage collection. */)
4045 register struct specbinding *bind;
4046 struct catchtag *catch;
4047 struct handler *handler;
4048 register struct backtrace *backlist;
4049 char stack_top_variable;
4050 register int i;
4051 int message_p;
4052 Lisp_Object total[8];
4053 int count = SPECPDL_INDEX ();
4054 EMACS_TIME t1, t2, t3;
4056 if (abort_on_gc)
4057 abort ();
4059 EMACS_GET_TIME (t1);
4061 /* Can't GC if pure storage overflowed because we can't determine
4062 if something is a pure object or not. */
4063 if (pure_bytes_used_before_overflow)
4064 return Qnil;
4066 /* In case user calls debug_print during GC,
4067 don't let that cause a recursive GC. */
4068 consing_since_gc = 0;
4070 /* Save what's currently displayed in the echo area. */
4071 message_p = push_message ();
4072 record_unwind_protect (pop_message_unwind, Qnil);
4074 /* Save a copy of the contents of the stack, for debugging. */
4075 #if MAX_SAVE_STACK > 0
4076 if (NILP (Vpurify_flag))
4078 i = &stack_top_variable - stack_bottom;
4079 if (i < 0) i = -i;
4080 if (i < MAX_SAVE_STACK)
4082 if (stack_copy == 0)
4083 stack_copy = (char *) xmalloc (stack_copy_size = i);
4084 else if (stack_copy_size < i)
4085 stack_copy = (char *) xrealloc (stack_copy, (stack_copy_size = i));
4086 if (stack_copy)
4088 if ((EMACS_INT) (&stack_top_variable - stack_bottom) > 0)
4089 bcopy (stack_bottom, stack_copy, i);
4090 else
4091 bcopy (&stack_top_variable, stack_copy, i);
4095 #endif /* MAX_SAVE_STACK > 0 */
4097 if (garbage_collection_messages)
4098 message1_nolog ("Garbage collecting...");
4100 BLOCK_INPUT;
4102 shrink_regexp_cache ();
4104 /* Don't keep undo information around forever. */
4106 register struct buffer *nextb = all_buffers;
4108 while (nextb)
4110 /* If a buffer's undo list is Qt, that means that undo is
4111 turned off in that buffer. Calling truncate_undo_list on
4112 Qt tends to return NULL, which effectively turns undo back on.
4113 So don't call truncate_undo_list if undo_list is Qt. */
4114 if (! EQ (nextb->undo_list, Qt))
4115 nextb->undo_list
4116 = truncate_undo_list (nextb->undo_list, undo_limit,
4117 undo_strong_limit);
4119 /* Shrink buffer gaps, but skip indirect and dead buffers. */
4120 if (nextb->base_buffer == 0 && !NILP (nextb->name))
4122 /* If a buffer's gap size is more than 10% of the buffer
4123 size, or larger than 2000 bytes, then shrink it
4124 accordingly. Keep a minimum size of 20 bytes. */
4125 int size = min (2000, max (20, (nextb->text->z_byte / 10)));
4127 if (nextb->text->gap_size > size)
4129 struct buffer *save_current = current_buffer;
4130 current_buffer = nextb;
4131 make_gap (-(nextb->text->gap_size - size));
4132 current_buffer = save_current;
4136 nextb = nextb->next;
4140 gc_in_progress = 1;
4142 /* clear_marks (); */
4144 /* Mark all the special slots that serve as the roots of accessibility.
4146 Usually the special slots to mark are contained in particular structures.
4147 Then we know no slot is marked twice because the structures don't overlap.
4148 In some cases, the structures point to the slots to be marked.
4149 For these, we use MARKBIT to avoid double marking of the slot. */
4151 for (i = 0; i < staticidx; i++)
4152 mark_object (staticvec[i]);
4154 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
4155 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
4156 mark_stack ();
4157 #else
4159 register struct gcpro *tail;
4160 for (tail = gcprolist; tail; tail = tail->next)
4161 for (i = 0; i < tail->nvars; i++)
4162 if (!XMARKBIT (tail->var[i]))
4164 /* Explicit casting prevents compiler warning about
4165 discarding the `volatile' qualifier. */
4166 mark_object ((Lisp_Object *)&tail->var[i]);
4167 XMARK (tail->var[i]);
4170 #endif
4172 mark_byte_stack ();
4173 for (bind = specpdl; bind != specpdl_ptr; bind++)
4175 /* These casts avoid a warning for discarding `volatile'. */
4176 mark_object ((Lisp_Object *) &bind->symbol);
4177 mark_object ((Lisp_Object *) &bind->old_value);
4179 for (catch = catchlist; catch; catch = catch->next)
4181 mark_object (&catch->tag);
4182 mark_object (&catch->val);
4184 for (handler = handlerlist; handler; handler = handler->next)
4186 mark_object (&handler->handler);
4187 mark_object (&handler->var);
4189 for (backlist = backtrace_list; backlist; backlist = backlist->next)
4191 if (!XMARKBIT (*backlist->function))
4193 mark_object (backlist->function);
4194 XMARK (*backlist->function);
4196 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
4197 i = 0;
4198 else
4199 i = backlist->nargs - 1;
4200 for (; i >= 0; i--)
4201 if (!XMARKBIT (backlist->args[i]))
4203 mark_object (&backlist->args[i]);
4204 XMARK (backlist->args[i]);
4207 mark_kboards ();
4209 /* Look thru every buffer's undo list
4210 for elements that update markers that were not marked,
4211 and delete them. */
4213 register struct buffer *nextb = all_buffers;
4215 while (nextb)
4217 /* If a buffer's undo list is Qt, that means that undo is
4218 turned off in that buffer. Calling truncate_undo_list on
4219 Qt tends to return NULL, which effectively turns undo back on.
4220 So don't call truncate_undo_list if undo_list is Qt. */
4221 if (! EQ (nextb->undo_list, Qt))
4223 Lisp_Object tail, prev;
4224 tail = nextb->undo_list;
4225 prev = Qnil;
4226 while (CONSP (tail))
4228 if (GC_CONSP (XCAR (tail))
4229 && GC_MARKERP (XCAR (XCAR (tail)))
4230 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
4232 if (NILP (prev))
4233 nextb->undo_list = tail = XCDR (tail);
4234 else
4236 tail = XCDR (tail);
4237 XSETCDR (prev, tail);
4240 else
4242 prev = tail;
4243 tail = XCDR (tail);
4248 nextb = nextb->next;
4252 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4253 mark_stack ();
4254 #endif
4256 #ifdef USE_GTK
4258 extern void xg_mark_data ();
4259 xg_mark_data ();
4261 #endif
4263 gc_sweep ();
4265 /* Clear the mark bits that we set in certain root slots. */
4267 #if (GC_MARK_STACK == GC_USE_GCPROS_AS_BEFORE \
4268 || GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES)
4270 register struct gcpro *tail;
4272 for (tail = gcprolist; tail; tail = tail->next)
4273 for (i = 0; i < tail->nvars; i++)
4274 XUNMARK (tail->var[i]);
4276 #endif
4278 unmark_byte_stack ();
4279 for (backlist = backtrace_list; backlist; backlist = backlist->next)
4281 XUNMARK (*backlist->function);
4282 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
4283 i = 0;
4284 else
4285 i = backlist->nargs - 1;
4286 for (; i >= 0; i--)
4287 XUNMARK (backlist->args[i]);
4289 XUNMARK (buffer_defaults.name);
4290 XUNMARK (buffer_local_symbols.name);
4292 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
4293 dump_zombies ();
4294 #endif
4296 UNBLOCK_INPUT;
4298 /* clear_marks (); */
4299 gc_in_progress = 0;
4301 consing_since_gc = 0;
4302 if (gc_cons_threshold < 10000)
4303 gc_cons_threshold = 10000;
4305 if (garbage_collection_messages)
4307 if (message_p || minibuf_level > 0)
4308 restore_message ();
4309 else
4310 message1_nolog ("Garbage collecting...done");
4313 unbind_to (count, Qnil);
4315 total[0] = Fcons (make_number (total_conses),
4316 make_number (total_free_conses));
4317 total[1] = Fcons (make_number (total_symbols),
4318 make_number (total_free_symbols));
4319 total[2] = Fcons (make_number (total_markers),
4320 make_number (total_free_markers));
4321 total[3] = make_number (total_string_size);
4322 total[4] = make_number (total_vector_size);
4323 total[5] = Fcons (make_number (total_floats),
4324 make_number (total_free_floats));
4325 total[6] = Fcons (make_number (total_intervals),
4326 make_number (total_free_intervals));
4327 total[7] = Fcons (make_number (total_strings),
4328 make_number (total_free_strings));
4330 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4332 /* Compute average percentage of zombies. */
4333 double nlive = 0;
4335 for (i = 0; i < 7; ++i)
4336 if (CONSP (total[i]))
4337 nlive += XFASTINT (XCAR (total[i]));
4339 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
4340 max_live = max (nlive, max_live);
4341 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
4342 max_zombies = max (nzombies, max_zombies);
4343 ++ngcs;
4345 #endif
4347 if (!NILP (Vpost_gc_hook))
4349 int count = inhibit_garbage_collection ();
4350 safe_run_hooks (Qpost_gc_hook);
4351 unbind_to (count, Qnil);
4354 /* Accumulate statistics. */
4355 EMACS_GET_TIME (t2);
4356 EMACS_SUB_TIME (t3, t2, t1);
4357 if (FLOATP (Vgc_elapsed))
4358 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed) +
4359 EMACS_SECS (t3) +
4360 EMACS_USECS (t3) * 1.0e-6);
4361 gcs_done++;
4363 return Flist (sizeof total / sizeof *total, total);
4367 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
4368 only interesting objects referenced from glyphs are strings. */
4370 static void
4371 mark_glyph_matrix (matrix)
4372 struct glyph_matrix *matrix;
4374 struct glyph_row *row = matrix->rows;
4375 struct glyph_row *end = row + matrix->nrows;
4377 for (; row < end; ++row)
4378 if (row->enabled_p)
4380 int area;
4381 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
4383 struct glyph *glyph = row->glyphs[area];
4384 struct glyph *end_glyph = glyph + row->used[area];
4386 for (; glyph < end_glyph; ++glyph)
4387 if (GC_STRINGP (glyph->object)
4388 && !STRING_MARKED_P (XSTRING (glyph->object)))
4389 mark_object (&glyph->object);
4395 /* Mark Lisp faces in the face cache C. */
4397 static void
4398 mark_face_cache (c)
4399 struct face_cache *c;
4401 if (c)
4403 int i, j;
4404 for (i = 0; i < c->used; ++i)
4406 struct face *face = FACE_FROM_ID (c->f, i);
4408 if (face)
4410 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
4411 mark_object (&face->lface[j]);
4418 #ifdef HAVE_WINDOW_SYSTEM
4420 /* Mark Lisp objects in image IMG. */
4422 static void
4423 mark_image (img)
4424 struct image *img;
4426 mark_object (&img->spec);
4428 if (!NILP (img->data.lisp_val))
4429 mark_object (&img->data.lisp_val);
4433 /* Mark Lisp objects in image cache of frame F. It's done this way so
4434 that we don't have to include xterm.h here. */
4436 static void
4437 mark_image_cache (f)
4438 struct frame *f;
4440 forall_images_in_image_cache (f, mark_image);
4443 #endif /* HAVE_X_WINDOWS */
4447 /* Mark reference to a Lisp_Object.
4448 If the object referred to has not been seen yet, recursively mark
4449 all the references contained in it. */
4451 #define LAST_MARKED_SIZE 500
4452 Lisp_Object *last_marked[LAST_MARKED_SIZE];
4453 int last_marked_index;
4455 /* For debugging--call abort when we cdr down this many
4456 links of a list, in mark_object. In debugging,
4457 the call to abort will hit a breakpoint.
4458 Normally this is zero and the check never goes off. */
4459 int mark_object_loop_halt;
4461 void
4462 mark_object (argptr)
4463 Lisp_Object *argptr;
4465 Lisp_Object *objptr = argptr;
4466 register Lisp_Object obj;
4467 #ifdef GC_CHECK_MARKED_OBJECTS
4468 void *po;
4469 struct mem_node *m;
4470 #endif
4471 int cdr_count = 0;
4473 loop:
4474 obj = *objptr;
4475 loop2:
4476 XUNMARK (obj);
4478 if (PURE_POINTER_P (XPNTR (obj)))
4479 return;
4481 last_marked[last_marked_index++] = objptr;
4482 if (last_marked_index == LAST_MARKED_SIZE)
4483 last_marked_index = 0;
4485 /* Perform some sanity checks on the objects marked here. Abort if
4486 we encounter an object we know is bogus. This increases GC time
4487 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
4488 #ifdef GC_CHECK_MARKED_OBJECTS
4490 po = (void *) XPNTR (obj);
4492 /* Check that the object pointed to by PO is known to be a Lisp
4493 structure allocated from the heap. */
4494 #define CHECK_ALLOCATED() \
4495 do { \
4496 m = mem_find (po); \
4497 if (m == MEM_NIL) \
4498 abort (); \
4499 } while (0)
4501 /* Check that the object pointed to by PO is live, using predicate
4502 function LIVEP. */
4503 #define CHECK_LIVE(LIVEP) \
4504 do { \
4505 if (!LIVEP (m, po)) \
4506 abort (); \
4507 } while (0)
4509 /* Check both of the above conditions. */
4510 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
4511 do { \
4512 CHECK_ALLOCATED (); \
4513 CHECK_LIVE (LIVEP); \
4514 } while (0) \
4516 #else /* not GC_CHECK_MARKED_OBJECTS */
4518 #define CHECK_ALLOCATED() (void) 0
4519 #define CHECK_LIVE(LIVEP) (void) 0
4520 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
4522 #endif /* not GC_CHECK_MARKED_OBJECTS */
4524 switch (SWITCH_ENUM_CAST (XGCTYPE (obj)))
4526 case Lisp_String:
4528 register struct Lisp_String *ptr = XSTRING (obj);
4529 CHECK_ALLOCATED_AND_LIVE (live_string_p);
4530 MARK_INTERVAL_TREE (ptr->intervals);
4531 MARK_STRING (ptr);
4532 #ifdef GC_CHECK_STRING_BYTES
4533 /* Check that the string size recorded in the string is the
4534 same as the one recorded in the sdata structure. */
4535 CHECK_STRING_BYTES (ptr);
4536 #endif /* GC_CHECK_STRING_BYTES */
4538 break;
4540 case Lisp_Vectorlike:
4541 #ifdef GC_CHECK_MARKED_OBJECTS
4542 m = mem_find (po);
4543 if (m == MEM_NIL && !GC_SUBRP (obj)
4544 && po != &buffer_defaults
4545 && po != &buffer_local_symbols)
4546 abort ();
4547 #endif /* GC_CHECK_MARKED_OBJECTS */
4549 if (GC_BUFFERP (obj))
4551 if (!XMARKBIT (XBUFFER (obj)->name))
4553 #ifdef GC_CHECK_MARKED_OBJECTS
4554 if (po != &buffer_defaults && po != &buffer_local_symbols)
4556 struct buffer *b;
4557 for (b = all_buffers; b && b != po; b = b->next)
4559 if (b == NULL)
4560 abort ();
4562 #endif /* GC_CHECK_MARKED_OBJECTS */
4563 mark_buffer (obj);
4566 else if (GC_SUBRP (obj))
4567 break;
4568 else if (GC_COMPILEDP (obj))
4569 /* We could treat this just like a vector, but it is better to
4570 save the COMPILED_CONSTANTS element for last and avoid
4571 recursion there. */
4573 register struct Lisp_Vector *ptr = XVECTOR (obj);
4574 register EMACS_INT size = ptr->size;
4575 register int i;
4577 if (size & ARRAY_MARK_FLAG)
4578 break; /* Already marked */
4580 CHECK_LIVE (live_vector_p);
4581 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4582 size &= PSEUDOVECTOR_SIZE_MASK;
4583 for (i = 0; i < size; i++) /* and then mark its elements */
4585 if (i != COMPILED_CONSTANTS)
4586 mark_object (&ptr->contents[i]);
4588 /* This cast should be unnecessary, but some Mips compiler complains
4589 (MIPS-ABI + SysVR4, DC/OSx, etc). */
4590 objptr = (Lisp_Object *) &ptr->contents[COMPILED_CONSTANTS];
4591 goto loop;
4593 else if (GC_FRAMEP (obj))
4595 register struct frame *ptr = XFRAME (obj);
4596 register EMACS_INT size = ptr->size;
4598 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
4599 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4601 CHECK_LIVE (live_vector_p);
4602 mark_object (&ptr->name);
4603 mark_object (&ptr->icon_name);
4604 mark_object (&ptr->title);
4605 mark_object (&ptr->focus_frame);
4606 mark_object (&ptr->selected_window);
4607 mark_object (&ptr->minibuffer_window);
4608 mark_object (&ptr->param_alist);
4609 mark_object (&ptr->scroll_bars);
4610 mark_object (&ptr->condemned_scroll_bars);
4611 mark_object (&ptr->menu_bar_items);
4612 mark_object (&ptr->face_alist);
4613 mark_object (&ptr->menu_bar_vector);
4614 mark_object (&ptr->buffer_predicate);
4615 mark_object (&ptr->buffer_list);
4616 mark_object (&ptr->menu_bar_window);
4617 mark_object (&ptr->tool_bar_window);
4618 mark_face_cache (ptr->face_cache);
4619 #ifdef HAVE_WINDOW_SYSTEM
4620 mark_image_cache (ptr);
4621 mark_object (&ptr->tool_bar_items);
4622 mark_object (&ptr->desired_tool_bar_string);
4623 mark_object (&ptr->current_tool_bar_string);
4624 #endif /* HAVE_WINDOW_SYSTEM */
4626 else if (GC_BOOL_VECTOR_P (obj))
4628 register struct Lisp_Vector *ptr = XVECTOR (obj);
4630 if (ptr->size & ARRAY_MARK_FLAG)
4631 break; /* Already marked */
4632 CHECK_LIVE (live_vector_p);
4633 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4635 else if (GC_WINDOWP (obj))
4637 register struct Lisp_Vector *ptr = XVECTOR (obj);
4638 struct window *w = XWINDOW (obj);
4639 register EMACS_INT size = ptr->size;
4640 register int i;
4642 /* Stop if already marked. */
4643 if (size & ARRAY_MARK_FLAG)
4644 break;
4646 /* Mark it. */
4647 CHECK_LIVE (live_vector_p);
4648 ptr->size |= ARRAY_MARK_FLAG;
4650 /* There is no Lisp data above The member CURRENT_MATRIX in
4651 struct WINDOW. Stop marking when that slot is reached. */
4652 for (i = 0;
4653 (char *) &ptr->contents[i] < (char *) &w->current_matrix;
4654 i++)
4655 mark_object (&ptr->contents[i]);
4657 /* Mark glyphs for leaf windows. Marking window matrices is
4658 sufficient because frame matrices use the same glyph
4659 memory. */
4660 if (NILP (w->hchild)
4661 && NILP (w->vchild)
4662 && w->current_matrix)
4664 mark_glyph_matrix (w->current_matrix);
4665 mark_glyph_matrix (w->desired_matrix);
4668 else if (GC_HASH_TABLE_P (obj))
4670 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
4671 EMACS_INT size = h->size;
4673 /* Stop if already marked. */
4674 if (size & ARRAY_MARK_FLAG)
4675 break;
4677 /* Mark it. */
4678 CHECK_LIVE (live_vector_p);
4679 h->size |= ARRAY_MARK_FLAG;
4681 /* Mark contents. */
4682 /* Do not mark next_free or next_weak.
4683 Being in the next_weak chain
4684 should not keep the hash table alive.
4685 No need to mark `count' since it is an integer. */
4686 mark_object (&h->test);
4687 mark_object (&h->weak);
4688 mark_object (&h->rehash_size);
4689 mark_object (&h->rehash_threshold);
4690 mark_object (&h->hash);
4691 mark_object (&h->next);
4692 mark_object (&h->index);
4693 mark_object (&h->user_hash_function);
4694 mark_object (&h->user_cmp_function);
4696 /* If hash table is not weak, mark all keys and values.
4697 For weak tables, mark only the vector. */
4698 if (GC_NILP (h->weak))
4699 mark_object (&h->key_and_value);
4700 else
4701 XVECTOR (h->key_and_value)->size |= ARRAY_MARK_FLAG;
4704 else
4706 register struct Lisp_Vector *ptr = XVECTOR (obj);
4707 register EMACS_INT size = ptr->size;
4708 register int i;
4710 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
4711 CHECK_LIVE (live_vector_p);
4712 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4713 if (size & PSEUDOVECTOR_FLAG)
4714 size &= PSEUDOVECTOR_SIZE_MASK;
4716 for (i = 0; i < size; i++) /* and then mark its elements */
4717 mark_object (&ptr->contents[i]);
4719 break;
4721 case Lisp_Symbol:
4723 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
4724 struct Lisp_Symbol *ptrx;
4726 if (ptr->gcmarkbit) break;
4727 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
4728 ptr->gcmarkbit = 1;
4729 mark_object ((Lisp_Object *) &ptr->value);
4730 mark_object (&ptr->function);
4731 mark_object (&ptr->plist);
4733 if (!PURE_POINTER_P (XSTRING (ptr->xname)))
4734 MARK_STRING (XSTRING (ptr->xname));
4735 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr->xname));
4737 /* Note that we do not mark the obarray of the symbol.
4738 It is safe not to do so because nothing accesses that
4739 slot except to check whether it is nil. */
4740 ptr = ptr->next;
4741 if (ptr)
4743 /* For the benefit of the last_marked log. */
4744 objptr = (Lisp_Object *)&XSYMBOL (obj)->next;
4745 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
4746 XSETSYMBOL (obj, ptrx);
4747 /* We can't goto loop here because *objptr doesn't contain an
4748 actual Lisp_Object with valid datatype field. */
4749 goto loop2;
4752 break;
4754 case Lisp_Misc:
4755 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
4756 if (XMARKER (obj)->gcmarkbit)
4757 break;
4758 XMARKER (obj)->gcmarkbit = 1;
4759 switch (XMISCTYPE (obj))
4761 case Lisp_Misc_Buffer_Local_Value:
4762 case Lisp_Misc_Some_Buffer_Local_Value:
4764 register struct Lisp_Buffer_Local_Value *ptr
4765 = XBUFFER_LOCAL_VALUE (obj);
4766 /* If the cdr is nil, avoid recursion for the car. */
4767 if (EQ (ptr->cdr, Qnil))
4769 objptr = &ptr->realvalue;
4770 goto loop;
4772 mark_object (&ptr->realvalue);
4773 mark_object (&ptr->buffer);
4774 mark_object (&ptr->frame);
4775 objptr = &ptr->cdr;
4776 goto loop;
4779 case Lisp_Misc_Marker:
4780 /* DO NOT mark thru the marker's chain.
4781 The buffer's markers chain does not preserve markers from gc;
4782 instead, markers are removed from the chain when freed by gc. */
4783 case Lisp_Misc_Intfwd:
4784 case Lisp_Misc_Boolfwd:
4785 case Lisp_Misc_Objfwd:
4786 case Lisp_Misc_Buffer_Objfwd:
4787 case Lisp_Misc_Kboard_Objfwd:
4788 /* Don't bother with Lisp_Buffer_Objfwd,
4789 since all markable slots in current buffer marked anyway. */
4790 /* Don't need to do Lisp_Objfwd, since the places they point
4791 are protected with staticpro. */
4792 break;
4794 case Lisp_Misc_Overlay:
4796 struct Lisp_Overlay *ptr = XOVERLAY (obj);
4797 mark_object (&ptr->start);
4798 mark_object (&ptr->end);
4799 objptr = &ptr->plist;
4800 goto loop;
4802 break;
4804 default:
4805 abort ();
4807 break;
4809 case Lisp_Cons:
4811 register struct Lisp_Cons *ptr = XCONS (obj);
4812 if (XMARKBIT (ptr->car)) break;
4813 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
4814 XMARK (ptr->car);
4815 /* If the cdr is nil, avoid recursion for the car. */
4816 if (EQ (ptr->cdr, Qnil))
4818 objptr = &ptr->car;
4819 cdr_count = 0;
4820 goto loop;
4822 mark_object (&ptr->car);
4823 objptr = &ptr->cdr;
4824 cdr_count++;
4825 if (cdr_count == mark_object_loop_halt)
4826 abort ();
4827 goto loop;
4830 case Lisp_Float:
4831 CHECK_ALLOCATED_AND_LIVE (live_float_p);
4832 XMARK (XFLOAT (obj)->type);
4833 break;
4835 case Lisp_Int:
4836 break;
4838 default:
4839 abort ();
4842 #undef CHECK_LIVE
4843 #undef CHECK_ALLOCATED
4844 #undef CHECK_ALLOCATED_AND_LIVE
4847 /* Mark the pointers in a buffer structure. */
4849 static void
4850 mark_buffer (buf)
4851 Lisp_Object buf;
4853 register struct buffer *buffer = XBUFFER (buf);
4854 register Lisp_Object *ptr;
4855 Lisp_Object base_buffer;
4857 /* This is the buffer's markbit */
4858 mark_object (&buffer->name);
4859 XMARK (buffer->name);
4861 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
4863 if (CONSP (buffer->undo_list))
4865 Lisp_Object tail;
4866 tail = buffer->undo_list;
4868 /* We mark the undo list specially because
4869 its pointers to markers should be weak. */
4871 while (CONSP (tail))
4873 register struct Lisp_Cons *ptr = XCONS (tail);
4875 if (XMARKBIT (ptr->car))
4876 break;
4877 XMARK (ptr->car);
4878 if (GC_CONSP (ptr->car)
4879 && ! XMARKBIT (XCAR (ptr->car))
4880 && GC_MARKERP (XCAR (ptr->car)))
4882 XMARK (XCAR_AS_LVALUE (ptr->car));
4883 mark_object (&XCDR_AS_LVALUE (ptr->car));
4885 else
4886 mark_object (&ptr->car);
4888 if (CONSP (ptr->cdr))
4889 tail = ptr->cdr;
4890 else
4891 break;
4894 mark_object (&XCDR_AS_LVALUE (tail));
4896 else
4897 mark_object (&buffer->undo_list);
4899 for (ptr = &buffer->name + 1;
4900 (char *)ptr < (char *)buffer + sizeof (struct buffer);
4901 ptr++)
4902 mark_object (ptr);
4904 /* If this is an indirect buffer, mark its base buffer. */
4905 if (buffer->base_buffer && !XMARKBIT (buffer->base_buffer->name))
4907 XSETBUFFER (base_buffer, buffer->base_buffer);
4908 mark_buffer (base_buffer);
4913 /* Value is non-zero if OBJ will survive the current GC because it's
4914 either marked or does not need to be marked to survive. */
4917 survives_gc_p (obj)
4918 Lisp_Object obj;
4920 int survives_p;
4922 switch (XGCTYPE (obj))
4924 case Lisp_Int:
4925 survives_p = 1;
4926 break;
4928 case Lisp_Symbol:
4929 survives_p = XSYMBOL (obj)->gcmarkbit;
4930 break;
4932 case Lisp_Misc:
4933 survives_p = XMARKER (obj)->gcmarkbit;
4934 break;
4936 case Lisp_String:
4938 struct Lisp_String *s = XSTRING (obj);
4939 survives_p = STRING_MARKED_P (s);
4941 break;
4943 case Lisp_Vectorlike:
4944 if (GC_BUFFERP (obj))
4945 survives_p = XMARKBIT (XBUFFER (obj)->name);
4946 else if (GC_SUBRP (obj))
4947 survives_p = 1;
4948 else
4949 survives_p = XVECTOR (obj)->size & ARRAY_MARK_FLAG;
4950 break;
4952 case Lisp_Cons:
4953 survives_p = XMARKBIT (XCAR (obj));
4954 break;
4956 case Lisp_Float:
4957 survives_p = XMARKBIT (XFLOAT (obj)->type);
4958 break;
4960 default:
4961 abort ();
4964 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
4969 /* Sweep: find all structures not marked, and free them. */
4971 static void
4972 gc_sweep ()
4974 /* Remove or mark entries in weak hash tables.
4975 This must be done before any object is unmarked. */
4976 sweep_weak_hash_tables ();
4978 sweep_strings ();
4979 #ifdef GC_CHECK_STRING_BYTES
4980 if (!noninteractive)
4981 check_string_bytes (1);
4982 #endif
4984 /* Put all unmarked conses on free list */
4986 register struct cons_block *cblk;
4987 struct cons_block **cprev = &cons_block;
4988 register int lim = cons_block_index;
4989 register int num_free = 0, num_used = 0;
4991 cons_free_list = 0;
4993 for (cblk = cons_block; cblk; cblk = *cprev)
4995 register int i;
4996 int this_free = 0;
4997 for (i = 0; i < lim; i++)
4998 if (!XMARKBIT (cblk->conses[i].car))
5000 this_free++;
5001 *(struct Lisp_Cons **)&cblk->conses[i].cdr = cons_free_list;
5002 cons_free_list = &cblk->conses[i];
5003 #if GC_MARK_STACK
5004 cons_free_list->car = Vdead;
5005 #endif
5007 else
5009 num_used++;
5010 XUNMARK (cblk->conses[i].car);
5012 lim = CONS_BLOCK_SIZE;
5013 /* If this block contains only free conses and we have already
5014 seen more than two blocks worth of free conses then deallocate
5015 this block. */
5016 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
5018 *cprev = cblk->next;
5019 /* Unhook from the free list. */
5020 cons_free_list = *(struct Lisp_Cons **) &cblk->conses[0].cdr;
5021 lisp_free (cblk);
5022 n_cons_blocks--;
5024 else
5026 num_free += this_free;
5027 cprev = &cblk->next;
5030 total_conses = num_used;
5031 total_free_conses = num_free;
5034 /* Put all unmarked floats on free list */
5036 register struct float_block *fblk;
5037 struct float_block **fprev = &float_block;
5038 register int lim = float_block_index;
5039 register int num_free = 0, num_used = 0;
5041 float_free_list = 0;
5043 for (fblk = float_block; fblk; fblk = *fprev)
5045 register int i;
5046 int this_free = 0;
5047 for (i = 0; i < lim; i++)
5048 if (!XMARKBIT (fblk->floats[i].type))
5050 this_free++;
5051 *(struct Lisp_Float **)&fblk->floats[i].data = float_free_list;
5052 float_free_list = &fblk->floats[i];
5053 #if GC_MARK_STACK
5054 float_free_list->type = Vdead;
5055 #endif
5057 else
5059 num_used++;
5060 XUNMARK (fblk->floats[i].type);
5062 lim = FLOAT_BLOCK_SIZE;
5063 /* If this block contains only free floats and we have already
5064 seen more than two blocks worth of free floats then deallocate
5065 this block. */
5066 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
5068 *fprev = fblk->next;
5069 /* Unhook from the free list. */
5070 float_free_list = *(struct Lisp_Float **) &fblk->floats[0].data;
5071 lisp_free (fblk);
5072 n_float_blocks--;
5074 else
5076 num_free += this_free;
5077 fprev = &fblk->next;
5080 total_floats = num_used;
5081 total_free_floats = num_free;
5084 /* Put all unmarked intervals on free list */
5086 register struct interval_block *iblk;
5087 struct interval_block **iprev = &interval_block;
5088 register int lim = interval_block_index;
5089 register int num_free = 0, num_used = 0;
5091 interval_free_list = 0;
5093 for (iblk = interval_block; iblk; iblk = *iprev)
5095 register int i;
5096 int this_free = 0;
5098 for (i = 0; i < lim; i++)
5100 if (!iblk->intervals[i].gcmarkbit)
5102 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
5103 interval_free_list = &iblk->intervals[i];
5104 this_free++;
5106 else
5108 num_used++;
5109 iblk->intervals[i].gcmarkbit = 0;
5112 lim = INTERVAL_BLOCK_SIZE;
5113 /* If this block contains only free intervals and we have already
5114 seen more than two blocks worth of free intervals then
5115 deallocate this block. */
5116 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
5118 *iprev = iblk->next;
5119 /* Unhook from the free list. */
5120 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
5121 lisp_free (iblk);
5122 n_interval_blocks--;
5124 else
5126 num_free += this_free;
5127 iprev = &iblk->next;
5130 total_intervals = num_used;
5131 total_free_intervals = num_free;
5134 /* Put all unmarked symbols on free list */
5136 register struct symbol_block *sblk;
5137 struct symbol_block **sprev = &symbol_block;
5138 register int lim = symbol_block_index;
5139 register int num_free = 0, num_used = 0;
5141 symbol_free_list = NULL;
5143 for (sblk = symbol_block; sblk; sblk = *sprev)
5145 int this_free = 0;
5146 struct Lisp_Symbol *sym = sblk->symbols;
5147 struct Lisp_Symbol *end = sym + lim;
5149 for (; sym < end; ++sym)
5151 /* Check if the symbol was created during loadup. In such a case
5152 it might be pointed to by pure bytecode which we don't trace,
5153 so we conservatively assume that it is live. */
5154 int pure_p = PURE_POINTER_P (XSTRING (sym->xname));
5156 if (!sym->gcmarkbit && !pure_p)
5158 *(struct Lisp_Symbol **) &sym->value = symbol_free_list;
5159 symbol_free_list = sym;
5160 #if GC_MARK_STACK
5161 symbol_free_list->function = Vdead;
5162 #endif
5163 ++this_free;
5165 else
5167 ++num_used;
5168 if (!pure_p)
5169 UNMARK_STRING (XSTRING (sym->xname));
5170 sym->gcmarkbit = 0;
5174 lim = SYMBOL_BLOCK_SIZE;
5175 /* If this block contains only free symbols and we have already
5176 seen more than two blocks worth of free symbols then deallocate
5177 this block. */
5178 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
5180 *sprev = sblk->next;
5181 /* Unhook from the free list. */
5182 symbol_free_list = *(struct Lisp_Symbol **)&sblk->symbols[0].value;
5183 lisp_free (sblk);
5184 n_symbol_blocks--;
5186 else
5188 num_free += this_free;
5189 sprev = &sblk->next;
5192 total_symbols = num_used;
5193 total_free_symbols = num_free;
5196 /* Put all unmarked misc's on free list.
5197 For a marker, first unchain it from the buffer it points into. */
5199 register struct marker_block *mblk;
5200 struct marker_block **mprev = &marker_block;
5201 register int lim = marker_block_index;
5202 register int num_free = 0, num_used = 0;
5204 marker_free_list = 0;
5206 for (mblk = marker_block; mblk; mblk = *mprev)
5208 register int i;
5209 int this_free = 0;
5211 for (i = 0; i < lim; i++)
5213 if (!mblk->markers[i].u_marker.gcmarkbit)
5215 Lisp_Object tem;
5216 if (mblk->markers[i].u_marker.type == Lisp_Misc_Marker)
5217 unchain_marker (&mblk->markers[i].u_marker);
5218 /* Set the type of the freed object to Lisp_Misc_Free.
5219 We could leave the type alone, since nobody checks it,
5220 but this might catch bugs faster. */
5221 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
5222 mblk->markers[i].u_free.chain = marker_free_list;
5223 marker_free_list = &mblk->markers[i];
5224 this_free++;
5226 else
5228 num_used++;
5229 mblk->markers[i].u_marker.gcmarkbit = 0;
5232 lim = MARKER_BLOCK_SIZE;
5233 /* If this block contains only free markers and we have already
5234 seen more than two blocks worth of free markers then deallocate
5235 this block. */
5236 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
5238 *mprev = mblk->next;
5239 /* Unhook from the free list. */
5240 marker_free_list = mblk->markers[0].u_free.chain;
5241 lisp_free (mblk);
5242 n_marker_blocks--;
5244 else
5246 num_free += this_free;
5247 mprev = &mblk->next;
5251 total_markers = num_used;
5252 total_free_markers = num_free;
5255 /* Free all unmarked buffers */
5257 register struct buffer *buffer = all_buffers, *prev = 0, *next;
5259 while (buffer)
5260 if (!XMARKBIT (buffer->name))
5262 if (prev)
5263 prev->next = buffer->next;
5264 else
5265 all_buffers = buffer->next;
5266 next = buffer->next;
5267 lisp_free (buffer);
5268 buffer = next;
5270 else
5272 XUNMARK (buffer->name);
5273 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
5274 prev = buffer, buffer = buffer->next;
5278 /* Free all unmarked vectors */
5280 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
5281 total_vector_size = 0;
5283 while (vector)
5284 if (!(vector->size & ARRAY_MARK_FLAG))
5286 if (prev)
5287 prev->next = vector->next;
5288 else
5289 all_vectors = vector->next;
5290 next = vector->next;
5291 lisp_free (vector);
5292 n_vectors--;
5293 vector = next;
5296 else
5298 vector->size &= ~ARRAY_MARK_FLAG;
5299 if (vector->size & PSEUDOVECTOR_FLAG)
5300 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
5301 else
5302 total_vector_size += vector->size;
5303 prev = vector, vector = vector->next;
5307 #ifdef GC_CHECK_STRING_BYTES
5308 if (!noninteractive)
5309 check_string_bytes (1);
5310 #endif
5316 /* Debugging aids. */
5318 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
5319 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
5320 This may be helpful in debugging Emacs's memory usage.
5321 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
5324 Lisp_Object end;
5326 XSETINT (end, (EMACS_INT) sbrk (0) / 1024);
5328 return end;
5331 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
5332 doc: /* Return a list of counters that measure how much consing there has been.
5333 Each of these counters increments for a certain kind of object.
5334 The counters wrap around from the largest positive integer to zero.
5335 Garbage collection does not decrease them.
5336 The elements of the value are as follows:
5337 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
5338 All are in units of 1 = one object consed
5339 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
5340 objects consed.
5341 MISCS include overlays, markers, and some internal types.
5342 Frames, windows, buffers, and subprocesses count as vectors
5343 (but the contents of a buffer's text do not count here). */)
5346 Lisp_Object consed[8];
5348 consed[0] = make_number (min (MOST_POSITIVE_FIXNUM, cons_cells_consed));
5349 consed[1] = make_number (min (MOST_POSITIVE_FIXNUM, floats_consed));
5350 consed[2] = make_number (min (MOST_POSITIVE_FIXNUM, vector_cells_consed));
5351 consed[3] = make_number (min (MOST_POSITIVE_FIXNUM, symbols_consed));
5352 consed[4] = make_number (min (MOST_POSITIVE_FIXNUM, string_chars_consed));
5353 consed[5] = make_number (min (MOST_POSITIVE_FIXNUM, misc_objects_consed));
5354 consed[6] = make_number (min (MOST_POSITIVE_FIXNUM, intervals_consed));
5355 consed[7] = make_number (min (MOST_POSITIVE_FIXNUM, strings_consed));
5357 return Flist (8, consed);
5360 int suppress_checking;
5361 void
5362 die (msg, file, line)
5363 const char *msg;
5364 const char *file;
5365 int line;
5367 fprintf (stderr, "\r\nEmacs fatal error: %s:%d: %s\r\n",
5368 file, line, msg);
5369 abort ();
5372 /* Initialization */
5374 void
5375 init_alloc_once ()
5377 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
5378 purebeg = PUREBEG;
5379 pure_size = PURESIZE;
5380 pure_bytes_used = 0;
5381 pure_bytes_used_before_overflow = 0;
5383 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
5384 mem_init ();
5385 Vdead = make_pure_string ("DEAD", 4, 4, 0);
5386 #endif
5388 all_vectors = 0;
5389 ignore_warnings = 1;
5390 #ifdef DOUG_LEA_MALLOC
5391 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
5392 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
5393 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
5394 #endif
5395 init_strings ();
5396 init_cons ();
5397 init_symbol ();
5398 init_marker ();
5399 init_float ();
5400 init_intervals ();
5402 #ifdef REL_ALLOC
5403 malloc_hysteresis = 32;
5404 #else
5405 malloc_hysteresis = 0;
5406 #endif
5408 spare_memory = (char *) malloc (SPARE_MEMORY);
5410 ignore_warnings = 0;
5411 gcprolist = 0;
5412 byte_stack_list = 0;
5413 staticidx = 0;
5414 consing_since_gc = 0;
5415 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
5416 #ifdef VIRT_ADDR_VARIES
5417 malloc_sbrk_unused = 1<<22; /* A large number */
5418 malloc_sbrk_used = 100000; /* as reasonable as any number */
5419 #endif /* VIRT_ADDR_VARIES */
5422 void
5423 init_alloc ()
5425 gcprolist = 0;
5426 byte_stack_list = 0;
5427 #if GC_MARK_STACK
5428 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
5429 setjmp_tested_p = longjmps_done = 0;
5430 #endif
5431 #endif
5432 Vgc_elapsed = make_float (0.0);
5433 gcs_done = 0;
5436 void
5437 syms_of_alloc ()
5439 DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold,
5440 doc: /* *Number of bytes of consing between garbage collections.
5441 Garbage collection can happen automatically once this many bytes have been
5442 allocated since the last garbage collection. All data types count.
5444 Garbage collection happens automatically only when `eval' is called.
5446 By binding this temporarily to a large number, you can effectively
5447 prevent garbage collection during a part of the program. */);
5449 DEFVAR_INT ("pure-bytes-used", &pure_bytes_used,
5450 doc: /* Number of bytes of sharable Lisp data allocated so far. */);
5452 DEFVAR_INT ("cons-cells-consed", &cons_cells_consed,
5453 doc: /* Number of cons cells that have been consed so far. */);
5455 DEFVAR_INT ("floats-consed", &floats_consed,
5456 doc: /* Number of floats that have been consed so far. */);
5458 DEFVAR_INT ("vector-cells-consed", &vector_cells_consed,
5459 doc: /* Number of vector cells that have been consed so far. */);
5461 DEFVAR_INT ("symbols-consed", &symbols_consed,
5462 doc: /* Number of symbols that have been consed so far. */);
5464 DEFVAR_INT ("string-chars-consed", &string_chars_consed,
5465 doc: /* Number of string characters that have been consed so far. */);
5467 DEFVAR_INT ("misc-objects-consed", &misc_objects_consed,
5468 doc: /* Number of miscellaneous objects that have been consed so far. */);
5470 DEFVAR_INT ("intervals-consed", &intervals_consed,
5471 doc: /* Number of intervals that have been consed so far. */);
5473 DEFVAR_INT ("strings-consed", &strings_consed,
5474 doc: /* Number of strings that have been consed so far. */);
5476 DEFVAR_LISP ("purify-flag", &Vpurify_flag,
5477 doc: /* Non-nil means loading Lisp code in order to dump an executable.
5478 This means that certain objects should be allocated in shared (pure) space. */);
5480 DEFVAR_INT ("undo-limit", &undo_limit,
5481 doc: /* Keep no more undo information once it exceeds this size.
5482 This limit is applied when garbage collection happens.
5483 The size is counted as the number of bytes occupied,
5484 which includes both saved text and other data. */);
5485 undo_limit = 20000;
5487 DEFVAR_INT ("undo-strong-limit", &undo_strong_limit,
5488 doc: /* Don't keep more than this much size of undo information.
5489 A command which pushes past this size is itself forgotten.
5490 This limit is applied when garbage collection happens.
5491 The size is counted as the number of bytes occupied,
5492 which includes both saved text and other data. */);
5493 undo_strong_limit = 30000;
5495 DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
5496 doc: /* Non-nil means display messages at start and end of garbage collection. */);
5497 garbage_collection_messages = 0;
5499 DEFVAR_LISP ("post-gc-hook", &Vpost_gc_hook,
5500 doc: /* Hook run after garbage collection has finished. */);
5501 Vpost_gc_hook = Qnil;
5502 Qpost_gc_hook = intern ("post-gc-hook");
5503 staticpro (&Qpost_gc_hook);
5505 DEFVAR_LISP ("memory-signal-data", &Vmemory_signal_data,
5506 doc: /* Precomputed `signal' argument for memory-full error. */);
5507 /* We build this in advance because if we wait until we need it, we might
5508 not be able to allocate the memory to hold it. */
5509 Vmemory_signal_data
5510 = list2 (Qerror,
5511 build_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
5513 DEFVAR_LISP ("memory-full", &Vmemory_full,
5514 doc: /* Non-nil means we are handling a memory-full error. */);
5515 Vmemory_full = Qnil;
5517 staticpro (&Qgc_cons_threshold);
5518 Qgc_cons_threshold = intern ("gc-cons-threshold");
5520 staticpro (&Qchar_table_extra_slots);
5521 Qchar_table_extra_slots = intern ("char-table-extra-slots");
5523 DEFVAR_LISP ("gc-elapsed", &Vgc_elapsed,
5524 doc: /* Accumulated time elapsed in garbage collections.
5525 The time is in seconds as a floating point value.
5526 Programs may reset this to get statistics in a specific period. */);
5527 DEFVAR_INT ("gcs-done", &gcs_done,
5528 doc: /* Accumulated number of garbage collections done.
5529 Programs may reset this to get statistics in a specific period. */);
5531 defsubr (&Scons);
5532 defsubr (&Slist);
5533 defsubr (&Svector);
5534 defsubr (&Smake_byte_code);
5535 defsubr (&Smake_list);
5536 defsubr (&Smake_vector);
5537 defsubr (&Smake_char_table);
5538 defsubr (&Smake_string);
5539 defsubr (&Smake_bool_vector);
5540 defsubr (&Smake_symbol);
5541 defsubr (&Smake_marker);
5542 defsubr (&Spurecopy);
5543 defsubr (&Sgarbage_collect);
5544 defsubr (&Smemory_limit);
5545 defsubr (&Smemory_use_counts);
5547 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5548 defsubr (&Sgc_status);
5549 #endif