(mail-specify-envelope-from, mail-envelope-from): Doc fix.
[emacs.git] / src / alloc.c
blob8dfeb25edf466e40c3f00b44aa8b722d1e0ba205
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 #define VECTOR_MARK(V) ((V)->size |= ARRAY_MARK_FLAG)
99 #define VECTOR_UNMARK(V) ((V)->size &= ~ARRAY_MARK_FLAG)
100 #define VECTOR_MARKED_P(V) ((V)->size & ARRAY_MARK_FLAG)
102 /* Value is the number of bytes/chars of S, a pointer to a struct
103 Lisp_String. This must be used instead of STRING_BYTES (S) or
104 S->size during GC, because S->size contains the mark bit for
105 strings. */
107 #define GC_STRING_BYTES(S) (STRING_BYTES (S))
108 #define GC_STRING_CHARS(S) ((S)->size & ~MARKBIT)
110 /* Number of bytes of consing done since the last gc. */
112 int consing_since_gc;
114 /* Count the amount of consing of various sorts of space. */
116 EMACS_INT cons_cells_consed;
117 EMACS_INT floats_consed;
118 EMACS_INT vector_cells_consed;
119 EMACS_INT symbols_consed;
120 EMACS_INT string_chars_consed;
121 EMACS_INT misc_objects_consed;
122 EMACS_INT intervals_consed;
123 EMACS_INT strings_consed;
125 /* Number of bytes of consing since GC before another GC should be done. */
127 EMACS_INT gc_cons_threshold;
129 /* Nonzero during GC. */
131 int gc_in_progress;
133 /* Nonzero means abort if try to GC.
134 This is for code which is written on the assumption that
135 no GC will happen, so as to verify that assumption. */
137 int abort_on_gc;
139 /* Nonzero means display messages at beginning and end of GC. */
141 int garbage_collection_messages;
143 #ifndef VIRT_ADDR_VARIES
144 extern
145 #endif /* VIRT_ADDR_VARIES */
146 int malloc_sbrk_used;
148 #ifndef VIRT_ADDR_VARIES
149 extern
150 #endif /* VIRT_ADDR_VARIES */
151 int malloc_sbrk_unused;
153 /* Two limits controlling how much undo information to keep. */
155 EMACS_INT undo_limit;
156 EMACS_INT undo_strong_limit;
158 /* Number of live and free conses etc. */
160 static int total_conses, total_markers, total_symbols, total_vector_size;
161 static int total_free_conses, total_free_markers, total_free_symbols;
162 static int total_free_floats, total_floats;
164 /* Points to memory space allocated as "spare", to be freed if we run
165 out of memory. */
167 static char *spare_memory;
169 /* Amount of spare memory to keep in reserve. */
171 #define SPARE_MEMORY (1 << 14)
173 /* Number of extra blocks malloc should get when it needs more core. */
175 static int malloc_hysteresis;
177 /* Non-nil means defun should do purecopy on the function definition. */
179 Lisp_Object Vpurify_flag;
181 /* Non-nil means we are handling a memory-full error. */
183 Lisp_Object Vmemory_full;
185 #ifndef HAVE_SHM
187 /* Force it into data space! */
189 EMACS_INT pure[PURESIZE / sizeof (EMACS_INT)] = {0,};
190 #define PUREBEG (char *) pure
192 #else /* HAVE_SHM */
194 #define pure PURE_SEG_BITS /* Use shared memory segment */
195 #define PUREBEG (char *)PURE_SEG_BITS
197 #endif /* HAVE_SHM */
199 /* Pointer to the pure area, and its size. */
201 static char *purebeg;
202 static size_t pure_size;
204 /* Number of bytes of pure storage used before pure storage overflowed.
205 If this is non-zero, this implies that an overflow occurred. */
207 static size_t pure_bytes_used_before_overflow;
209 /* Value is non-zero if P points into pure space. */
211 #define PURE_POINTER_P(P) \
212 (((PNTR_COMPARISON_TYPE) (P) \
213 < (PNTR_COMPARISON_TYPE) ((char *) purebeg + pure_size)) \
214 && ((PNTR_COMPARISON_TYPE) (P) \
215 >= (PNTR_COMPARISON_TYPE) purebeg))
217 /* Index in pure at which next pure object will be allocated.. */
219 EMACS_INT pure_bytes_used;
221 /* If nonzero, this is a warning delivered by malloc and not yet
222 displayed. */
224 char *pending_malloc_warning;
226 /* Pre-computed signal argument for use when memory is exhausted. */
228 Lisp_Object Vmemory_signal_data;
230 /* Maximum amount of C stack to save when a GC happens. */
232 #ifndef MAX_SAVE_STACK
233 #define MAX_SAVE_STACK 16000
234 #endif
236 /* Buffer in which we save a copy of the C stack at each GC. */
238 char *stack_copy;
239 int stack_copy_size;
241 /* Non-zero means ignore malloc warnings. Set during initialization.
242 Currently not used. */
244 int ignore_warnings;
246 Lisp_Object Qgc_cons_threshold, Qchar_table_extra_slots;
248 /* Hook run after GC has finished. */
250 Lisp_Object Vpost_gc_hook, Qpost_gc_hook;
252 Lisp_Object Vgc_elapsed; /* accumulated elapsed time in GC */
253 EMACS_INT gcs_done; /* accumulated GCs */
255 static void mark_buffer P_ ((Lisp_Object));
256 extern void mark_kboards P_ ((void));
257 static void gc_sweep P_ ((void));
258 static void mark_glyph_matrix P_ ((struct glyph_matrix *));
259 static void mark_face_cache P_ ((struct face_cache *));
261 #ifdef HAVE_WINDOW_SYSTEM
262 static void mark_image P_ ((struct image *));
263 static void mark_image_cache P_ ((struct frame *));
264 #endif /* HAVE_WINDOW_SYSTEM */
266 static struct Lisp_String *allocate_string P_ ((void));
267 static void compact_small_strings P_ ((void));
268 static void free_large_strings P_ ((void));
269 static void sweep_strings P_ ((void));
271 extern int message_enable_multibyte;
273 /* When scanning the C stack for live Lisp objects, Emacs keeps track
274 of what memory allocated via lisp_malloc is intended for what
275 purpose. This enumeration specifies the type of memory. */
277 enum mem_type
279 MEM_TYPE_NON_LISP,
280 MEM_TYPE_BUFFER,
281 MEM_TYPE_CONS,
282 MEM_TYPE_STRING,
283 MEM_TYPE_MISC,
284 MEM_TYPE_SYMBOL,
285 MEM_TYPE_FLOAT,
286 /* Keep the following vector-like types together, with
287 MEM_TYPE_WINDOW being the last, and MEM_TYPE_VECTOR the
288 first. Or change the code of live_vector_p, for instance. */
289 MEM_TYPE_VECTOR,
290 MEM_TYPE_PROCESS,
291 MEM_TYPE_HASH_TABLE,
292 MEM_TYPE_FRAME,
293 MEM_TYPE_WINDOW
296 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
298 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
299 #include <stdio.h> /* For fprintf. */
300 #endif
302 /* A unique object in pure space used to make some Lisp objects
303 on free lists recognizable in O(1). */
305 Lisp_Object Vdead;
307 #ifdef GC_MALLOC_CHECK
309 enum mem_type allocated_mem_type;
310 int dont_register_blocks;
312 #endif /* GC_MALLOC_CHECK */
314 /* A node in the red-black tree describing allocated memory containing
315 Lisp data. Each such block is recorded with its start and end
316 address when it is allocated, and removed from the tree when it
317 is freed.
319 A red-black tree is a balanced binary tree with the following
320 properties:
322 1. Every node is either red or black.
323 2. Every leaf is black.
324 3. If a node is red, then both of its children are black.
325 4. Every simple path from a node to a descendant leaf contains
326 the same number of black nodes.
327 5. The root is always black.
329 When nodes are inserted into the tree, or deleted from the tree,
330 the tree is "fixed" so that these properties are always true.
332 A red-black tree with N internal nodes has height at most 2
333 log(N+1). Searches, insertions and deletions are done in O(log N).
334 Please see a text book about data structures for a detailed
335 description of red-black trees. Any book worth its salt should
336 describe them. */
338 struct mem_node
340 /* Children of this node. These pointers are never NULL. When there
341 is no child, the value is MEM_NIL, which points to a dummy node. */
342 struct mem_node *left, *right;
344 /* The parent of this node. In the root node, this is NULL. */
345 struct mem_node *parent;
347 /* Start and end of allocated region. */
348 void *start, *end;
350 /* Node color. */
351 enum {MEM_BLACK, MEM_RED} color;
353 /* Memory type. */
354 enum mem_type type;
357 /* Base address of stack. Set in main. */
359 Lisp_Object *stack_base;
361 /* Root of the tree describing allocated Lisp memory. */
363 static struct mem_node *mem_root;
365 /* Lowest and highest known address in the heap. */
367 static void *min_heap_address, *max_heap_address;
369 /* Sentinel node of the tree. */
371 static struct mem_node mem_z;
372 #define MEM_NIL &mem_z
374 static POINTER_TYPE *lisp_malloc P_ ((size_t, enum mem_type));
375 static struct Lisp_Vector *allocate_vectorlike P_ ((EMACS_INT, enum mem_type));
376 static void lisp_free P_ ((POINTER_TYPE *));
377 static void mark_stack P_ ((void));
378 static int live_vector_p P_ ((struct mem_node *, void *));
379 static int live_buffer_p P_ ((struct mem_node *, void *));
380 static int live_string_p P_ ((struct mem_node *, void *));
381 static int live_cons_p P_ ((struct mem_node *, void *));
382 static int live_symbol_p P_ ((struct mem_node *, void *));
383 static int live_float_p P_ ((struct mem_node *, void *));
384 static int live_misc_p P_ ((struct mem_node *, void *));
385 static void mark_maybe_object P_ ((Lisp_Object));
386 static void mark_memory P_ ((void *, void *));
387 static void mem_init P_ ((void));
388 static struct mem_node *mem_insert P_ ((void *, void *, enum mem_type));
389 static void mem_insert_fixup P_ ((struct mem_node *));
390 static void mem_rotate_left P_ ((struct mem_node *));
391 static void mem_rotate_right P_ ((struct mem_node *));
392 static void mem_delete P_ ((struct mem_node *));
393 static void mem_delete_fixup P_ ((struct mem_node *));
394 static INLINE struct mem_node *mem_find P_ ((void *));
396 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
397 static void check_gcpros P_ ((void));
398 #endif
400 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
402 /* Recording what needs to be marked for gc. */
404 struct gcpro *gcprolist;
406 /* Addresses of staticpro'd variables. */
408 #define NSTATICS 1280
409 Lisp_Object *staticvec[NSTATICS] = {0};
411 /* Index of next unused slot in staticvec. */
413 int staticidx = 0;
415 static POINTER_TYPE *pure_alloc P_ ((size_t, int));
418 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
419 ALIGNMENT must be a power of 2. */
421 #define ALIGN(SZ, ALIGNMENT) \
422 (((SZ) + (ALIGNMENT) - 1) & ~((ALIGNMENT) - 1))
426 /************************************************************************
427 Malloc
428 ************************************************************************/
430 /* Function malloc calls this if it finds we are near exhausting storage. */
432 void
433 malloc_warning (str)
434 char *str;
436 pending_malloc_warning = str;
440 /* Display an already-pending malloc warning. */
442 void
443 display_malloc_warning ()
445 call3 (intern ("display-warning"),
446 intern ("alloc"),
447 build_string (pending_malloc_warning),
448 intern ("emergency"));
449 pending_malloc_warning = 0;
453 #ifdef DOUG_LEA_MALLOC
454 # define BYTES_USED (mallinfo ().arena)
455 #else
456 # define BYTES_USED _bytes_used
457 #endif
460 /* Called if malloc returns zero. */
462 void
463 memory_full ()
465 Vmemory_full = Qt;
467 #ifndef SYSTEM_MALLOC
468 bytes_used_when_full = BYTES_USED;
469 #endif
471 /* The first time we get here, free the spare memory. */
472 if (spare_memory)
474 free (spare_memory);
475 spare_memory = 0;
478 /* This used to call error, but if we've run out of memory, we could
479 get infinite recursion trying to build the string. */
480 while (1)
481 Fsignal (Qnil, Vmemory_signal_data);
485 /* Called if we can't allocate relocatable space for a buffer. */
487 void
488 buffer_memory_full ()
490 /* If buffers use the relocating allocator, no need to free
491 spare_memory, because we may have plenty of malloc space left
492 that we could get, and if we don't, the malloc that fails will
493 itself cause spare_memory to be freed. If buffers don't use the
494 relocating allocator, treat this like any other failing
495 malloc. */
497 #ifndef REL_ALLOC
498 memory_full ();
499 #endif
501 Vmemory_full = Qt;
503 /* This used to call error, but if we've run out of memory, we could
504 get infinite recursion trying to build the string. */
505 while (1)
506 Fsignal (Qnil, Vmemory_signal_data);
510 /* Like malloc but check for no memory and block interrupt input.. */
512 POINTER_TYPE *
513 xmalloc (size)
514 size_t size;
516 register POINTER_TYPE *val;
518 BLOCK_INPUT;
519 val = (POINTER_TYPE *) malloc (size);
520 UNBLOCK_INPUT;
522 if (!val && size)
523 memory_full ();
524 return val;
528 /* Like realloc but check for no memory and block interrupt input.. */
530 POINTER_TYPE *
531 xrealloc (block, size)
532 POINTER_TYPE *block;
533 size_t size;
535 register POINTER_TYPE *val;
537 BLOCK_INPUT;
538 /* We must call malloc explicitly when BLOCK is 0, since some
539 reallocs don't do this. */
540 if (! block)
541 val = (POINTER_TYPE *) malloc (size);
542 else
543 val = (POINTER_TYPE *) realloc (block, size);
544 UNBLOCK_INPUT;
546 if (!val && size) memory_full ();
547 return val;
551 /* Like free but block interrupt input.. */
553 void
554 xfree (block)
555 POINTER_TYPE *block;
557 BLOCK_INPUT;
558 free (block);
559 UNBLOCK_INPUT;
563 /* Like strdup, but uses xmalloc. */
565 char *
566 xstrdup (s)
567 const char *s;
569 size_t len = strlen (s) + 1;
570 char *p = (char *) xmalloc (len);
571 bcopy (s, p, len);
572 return p;
576 /* Like malloc but used for allocating Lisp data. NBYTES is the
577 number of bytes to allocate, TYPE describes the intended use of the
578 allcated memory block (for strings, for conses, ...). */
580 static void *lisp_malloc_loser;
582 static POINTER_TYPE *
583 lisp_malloc (nbytes, type)
584 size_t nbytes;
585 enum mem_type type;
587 register void *val;
589 BLOCK_INPUT;
591 #ifdef GC_MALLOC_CHECK
592 allocated_mem_type = type;
593 #endif
595 val = (void *) malloc (nbytes);
597 /* If the memory just allocated cannot be addressed thru a Lisp
598 object's pointer, and it needs to be,
599 that's equivalent to running out of memory. */
600 if (val && type != MEM_TYPE_NON_LISP)
602 Lisp_Object tem;
603 XSETCONS (tem, (char *) val + nbytes - 1);
604 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
606 lisp_malloc_loser = val;
607 free (val);
608 val = 0;
612 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
613 if (val && type != MEM_TYPE_NON_LISP)
614 mem_insert (val, (char *) val + nbytes, type);
615 #endif
617 UNBLOCK_INPUT;
618 if (!val && nbytes)
619 memory_full ();
620 return val;
623 /* Free BLOCK. This must be called to free memory allocated with a
624 call to lisp_malloc. */
626 static void
627 lisp_free (block)
628 POINTER_TYPE *block;
630 BLOCK_INPUT;
631 free (block);
632 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
633 mem_delete (mem_find (block));
634 #endif
635 UNBLOCK_INPUT;
639 /* Return a new buffer structure allocated from the heap with
640 a call to lisp_malloc. */
642 struct buffer *
643 allocate_buffer ()
645 struct buffer *b
646 = (struct buffer *) lisp_malloc (sizeof (struct buffer),
647 MEM_TYPE_BUFFER);
648 return b;
652 /* Arranging to disable input signals while we're in malloc.
654 This only works with GNU malloc. To help out systems which can't
655 use GNU malloc, all the calls to malloc, realloc, and free
656 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
657 pairs; unfortunately, we have no idea what C library functions
658 might call malloc, so we can't really protect them unless you're
659 using GNU malloc. Fortunately, most of the major operating systems
660 can use GNU malloc. */
662 #ifndef SYSTEM_MALLOC
663 #ifndef DOUG_LEA_MALLOC
664 extern void * (*__malloc_hook) P_ ((size_t));
665 extern void * (*__realloc_hook) P_ ((void *, size_t));
666 extern void (*__free_hook) P_ ((void *));
667 /* Else declared in malloc.h, perhaps with an extra arg. */
668 #endif /* DOUG_LEA_MALLOC */
669 static void * (*old_malloc_hook) ();
670 static void * (*old_realloc_hook) ();
671 static void (*old_free_hook) ();
673 /* This function is used as the hook for free to call. */
675 static void
676 emacs_blocked_free (ptr)
677 void *ptr;
679 BLOCK_INPUT;
681 #ifdef GC_MALLOC_CHECK
682 if (ptr)
684 struct mem_node *m;
686 m = mem_find (ptr);
687 if (m == MEM_NIL || m->start != ptr)
689 fprintf (stderr,
690 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
691 abort ();
693 else
695 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
696 mem_delete (m);
699 #endif /* GC_MALLOC_CHECK */
701 __free_hook = old_free_hook;
702 free (ptr);
704 /* If we released our reserve (due to running out of memory),
705 and we have a fair amount free once again,
706 try to set aside another reserve in case we run out once more. */
707 if (spare_memory == 0
708 /* Verify there is enough space that even with the malloc
709 hysteresis this call won't run out again.
710 The code here is correct as long as SPARE_MEMORY
711 is substantially larger than the block size malloc uses. */
712 && (bytes_used_when_full
713 > BYTES_USED + max (malloc_hysteresis, 4) * SPARE_MEMORY))
714 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
716 __free_hook = emacs_blocked_free;
717 UNBLOCK_INPUT;
721 /* If we released our reserve (due to running out of memory),
722 and we have a fair amount free once again,
723 try to set aside another reserve in case we run out once more.
725 This is called when a relocatable block is freed in ralloc.c. */
727 void
728 refill_memory_reserve ()
730 if (spare_memory == 0)
731 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
735 /* This function is the malloc hook that Emacs uses. */
737 static void *
738 emacs_blocked_malloc (size)
739 size_t size;
741 void *value;
743 BLOCK_INPUT;
744 __malloc_hook = old_malloc_hook;
745 #ifdef DOUG_LEA_MALLOC
746 mallopt (M_TOP_PAD, malloc_hysteresis * 4096);
747 #else
748 __malloc_extra_blocks = malloc_hysteresis;
749 #endif
751 value = (void *) malloc (size);
753 #ifdef GC_MALLOC_CHECK
755 struct mem_node *m = mem_find (value);
756 if (m != MEM_NIL)
758 fprintf (stderr, "Malloc returned %p which is already in use\n",
759 value);
760 fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
761 m->start, m->end, (char *) m->end - (char *) m->start,
762 m->type);
763 abort ();
766 if (!dont_register_blocks)
768 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
769 allocated_mem_type = MEM_TYPE_NON_LISP;
772 #endif /* GC_MALLOC_CHECK */
774 __malloc_hook = emacs_blocked_malloc;
775 UNBLOCK_INPUT;
777 /* fprintf (stderr, "%p malloc\n", value); */
778 return value;
782 /* This function is the realloc hook that Emacs uses. */
784 static void *
785 emacs_blocked_realloc (ptr, size)
786 void *ptr;
787 size_t size;
789 void *value;
791 BLOCK_INPUT;
792 __realloc_hook = old_realloc_hook;
794 #ifdef GC_MALLOC_CHECK
795 if (ptr)
797 struct mem_node *m = mem_find (ptr);
798 if (m == MEM_NIL || m->start != ptr)
800 fprintf (stderr,
801 "Realloc of %p which wasn't allocated with malloc\n",
802 ptr);
803 abort ();
806 mem_delete (m);
809 /* fprintf (stderr, "%p -> realloc\n", ptr); */
811 /* Prevent malloc from registering blocks. */
812 dont_register_blocks = 1;
813 #endif /* GC_MALLOC_CHECK */
815 value = (void *) realloc (ptr, size);
817 #ifdef GC_MALLOC_CHECK
818 dont_register_blocks = 0;
821 struct mem_node *m = mem_find (value);
822 if (m != MEM_NIL)
824 fprintf (stderr, "Realloc returns memory that is already in use\n");
825 abort ();
828 /* Can't handle zero size regions in the red-black tree. */
829 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
832 /* fprintf (stderr, "%p <- realloc\n", value); */
833 #endif /* GC_MALLOC_CHECK */
835 __realloc_hook = emacs_blocked_realloc;
836 UNBLOCK_INPUT;
838 return value;
842 /* Called from main to set up malloc to use our hooks. */
844 void
845 uninterrupt_malloc ()
847 if (__free_hook != emacs_blocked_free)
848 old_free_hook = __free_hook;
849 __free_hook = emacs_blocked_free;
851 if (__malloc_hook != emacs_blocked_malloc)
852 old_malloc_hook = __malloc_hook;
853 __malloc_hook = emacs_blocked_malloc;
855 if (__realloc_hook != emacs_blocked_realloc)
856 old_realloc_hook = __realloc_hook;
857 __realloc_hook = emacs_blocked_realloc;
860 #endif /* not SYSTEM_MALLOC */
864 /***********************************************************************
865 Interval Allocation
866 ***********************************************************************/
868 /* Number of intervals allocated in an interval_block structure.
869 The 1020 is 1024 minus malloc overhead. */
871 #define INTERVAL_BLOCK_SIZE \
872 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
874 /* Intervals are allocated in chunks in form of an interval_block
875 structure. */
877 struct interval_block
879 struct interval_block *next;
880 struct interval intervals[INTERVAL_BLOCK_SIZE];
883 /* Current interval block. Its `next' pointer points to older
884 blocks. */
886 struct interval_block *interval_block;
888 /* Index in interval_block above of the next unused interval
889 structure. */
891 static int interval_block_index;
893 /* Number of free and live intervals. */
895 static int total_free_intervals, total_intervals;
897 /* List of free intervals. */
899 INTERVAL interval_free_list;
901 /* Total number of interval blocks now in use. */
903 int n_interval_blocks;
906 /* Initialize interval allocation. */
908 static void
909 init_intervals ()
911 interval_block
912 = (struct interval_block *) lisp_malloc (sizeof *interval_block,
913 MEM_TYPE_NON_LISP);
914 interval_block->next = 0;
915 bzero ((char *) interval_block->intervals, sizeof interval_block->intervals);
916 interval_block_index = 0;
917 interval_free_list = 0;
918 n_interval_blocks = 1;
922 /* Return a new interval. */
924 INTERVAL
925 make_interval ()
927 INTERVAL val;
929 if (interval_free_list)
931 val = interval_free_list;
932 interval_free_list = INTERVAL_PARENT (interval_free_list);
934 else
936 if (interval_block_index == INTERVAL_BLOCK_SIZE)
938 register struct interval_block *newi;
940 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
941 MEM_TYPE_NON_LISP);
943 newi->next = interval_block;
944 interval_block = newi;
945 interval_block_index = 0;
946 n_interval_blocks++;
948 val = &interval_block->intervals[interval_block_index++];
950 consing_since_gc += sizeof (struct interval);
951 intervals_consed++;
952 RESET_INTERVAL (val);
953 val->gcmarkbit = 0;
954 return val;
958 /* Mark Lisp objects in interval I. */
960 static void
961 mark_interval (i, dummy)
962 register INTERVAL i;
963 Lisp_Object dummy;
965 eassert (!i->gcmarkbit); /* Intervals are never shared. */
966 i->gcmarkbit = 1;
967 mark_object (&i->plist);
971 /* Mark the interval tree rooted in TREE. Don't call this directly;
972 use the macro MARK_INTERVAL_TREE instead. */
974 static void
975 mark_interval_tree (tree)
976 register INTERVAL tree;
978 /* No need to test if this tree has been marked already; this
979 function is always called through the MARK_INTERVAL_TREE macro,
980 which takes care of that. */
982 traverse_intervals_noorder (tree, mark_interval, Qnil);
986 /* Mark the interval tree rooted in I. */
988 #define MARK_INTERVAL_TREE(i) \
989 do { \
990 if (!NULL_INTERVAL_P (i) && !i->gcmarkbit) \
991 mark_interval_tree (i); \
992 } while (0)
995 #define UNMARK_BALANCE_INTERVALS(i) \
996 do { \
997 if (! NULL_INTERVAL_P (i)) \
998 (i) = balance_intervals (i); \
999 } while (0)
1002 /* Number support. If NO_UNION_TYPE isn't in effect, we
1003 can't create number objects in macros. */
1004 #ifndef make_number
1005 Lisp_Object
1006 make_number (n)
1007 int n;
1009 Lisp_Object obj;
1010 obj.s.val = n;
1011 obj.s.type = Lisp_Int;
1012 return obj;
1014 #endif
1016 /***********************************************************************
1017 String Allocation
1018 ***********************************************************************/
1020 /* Lisp_Strings are allocated in string_block structures. When a new
1021 string_block is allocated, all the Lisp_Strings it contains are
1022 added to a free-list string_free_list. When a new Lisp_String is
1023 needed, it is taken from that list. During the sweep phase of GC,
1024 string_blocks that are entirely free are freed, except two which
1025 we keep.
1027 String data is allocated from sblock structures. Strings larger
1028 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1029 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1031 Sblocks consist internally of sdata structures, one for each
1032 Lisp_String. The sdata structure points to the Lisp_String it
1033 belongs to. The Lisp_String points back to the `u.data' member of
1034 its sdata structure.
1036 When a Lisp_String is freed during GC, it is put back on
1037 string_free_list, and its `data' member and its sdata's `string'
1038 pointer is set to null. The size of the string is recorded in the
1039 `u.nbytes' member of the sdata. So, sdata structures that are no
1040 longer used, can be easily recognized, and it's easy to compact the
1041 sblocks of small strings which we do in compact_small_strings. */
1043 /* Size in bytes of an sblock structure used for small strings. This
1044 is 8192 minus malloc overhead. */
1046 #define SBLOCK_SIZE 8188
1048 /* Strings larger than this are considered large strings. String data
1049 for large strings is allocated from individual sblocks. */
1051 #define LARGE_STRING_BYTES 1024
1053 /* Structure describing string memory sub-allocated from an sblock.
1054 This is where the contents of Lisp strings are stored. */
1056 struct sdata
1058 /* Back-pointer to the string this sdata belongs to. If null, this
1059 structure is free, and the NBYTES member of the union below
1060 contains the string's byte size (the same value that STRING_BYTES
1061 would return if STRING were non-null). If non-null, STRING_BYTES
1062 (STRING) is the size of the data, and DATA contains the string's
1063 contents. */
1064 struct Lisp_String *string;
1066 #ifdef GC_CHECK_STRING_BYTES
1068 EMACS_INT nbytes;
1069 unsigned char data[1];
1071 #define SDATA_NBYTES(S) (S)->nbytes
1072 #define SDATA_DATA(S) (S)->data
1074 #else /* not GC_CHECK_STRING_BYTES */
1076 union
1078 /* When STRING in non-null. */
1079 unsigned char data[1];
1081 /* When STRING is null. */
1082 EMACS_INT nbytes;
1083 } u;
1086 #define SDATA_NBYTES(S) (S)->u.nbytes
1087 #define SDATA_DATA(S) (S)->u.data
1089 #endif /* not GC_CHECK_STRING_BYTES */
1093 /* Structure describing a block of memory which is sub-allocated to
1094 obtain string data memory for strings. Blocks for small strings
1095 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1096 as large as needed. */
1098 struct sblock
1100 /* Next in list. */
1101 struct sblock *next;
1103 /* Pointer to the next free sdata block. This points past the end
1104 of the sblock if there isn't any space left in this block. */
1105 struct sdata *next_free;
1107 /* Start of data. */
1108 struct sdata first_data;
1111 /* Number of Lisp strings in a string_block structure. The 1020 is
1112 1024 minus malloc overhead. */
1114 #define STRINGS_IN_STRING_BLOCK \
1115 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1117 /* Structure describing a block from which Lisp_String structures
1118 are allocated. */
1120 struct string_block
1122 struct string_block *next;
1123 struct Lisp_String strings[STRINGS_IN_STRING_BLOCK];
1126 /* Head and tail of the list of sblock structures holding Lisp string
1127 data. We always allocate from current_sblock. The NEXT pointers
1128 in the sblock structures go from oldest_sblock to current_sblock. */
1130 static struct sblock *oldest_sblock, *current_sblock;
1132 /* List of sblocks for large strings. */
1134 static struct sblock *large_sblocks;
1136 /* List of string_block structures, and how many there are. */
1138 static struct string_block *string_blocks;
1139 static int n_string_blocks;
1141 /* Free-list of Lisp_Strings. */
1143 static struct Lisp_String *string_free_list;
1145 /* Number of live and free Lisp_Strings. */
1147 static int total_strings, total_free_strings;
1149 /* Number of bytes used by live strings. */
1151 static int total_string_size;
1153 /* Given a pointer to a Lisp_String S which is on the free-list
1154 string_free_list, return a pointer to its successor in the
1155 free-list. */
1157 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1159 /* Return a pointer to the sdata structure belonging to Lisp string S.
1160 S must be live, i.e. S->data must not be null. S->data is actually
1161 a pointer to the `u.data' member of its sdata structure; the
1162 structure starts at a constant offset in front of that. */
1164 #ifdef GC_CHECK_STRING_BYTES
1166 #define SDATA_OF_STRING(S) \
1167 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *) \
1168 - sizeof (EMACS_INT)))
1170 #else /* not GC_CHECK_STRING_BYTES */
1172 #define SDATA_OF_STRING(S) \
1173 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))
1175 #endif /* not GC_CHECK_STRING_BYTES */
1177 /* Value is the size of an sdata structure large enough to hold NBYTES
1178 bytes of string data. The value returned includes a terminating
1179 NUL byte, the size of the sdata structure, and padding. */
1181 #ifdef GC_CHECK_STRING_BYTES
1183 #define SDATA_SIZE(NBYTES) \
1184 ((sizeof (struct Lisp_String *) \
1185 + (NBYTES) + 1 \
1186 + sizeof (EMACS_INT) \
1187 + sizeof (EMACS_INT) - 1) \
1188 & ~(sizeof (EMACS_INT) - 1))
1190 #else /* not GC_CHECK_STRING_BYTES */
1192 #define SDATA_SIZE(NBYTES) \
1193 ((sizeof (struct Lisp_String *) \
1194 + (NBYTES) + 1 \
1195 + sizeof (EMACS_INT) - 1) \
1196 & ~(sizeof (EMACS_INT) - 1))
1198 #endif /* not GC_CHECK_STRING_BYTES */
1200 /* Initialize string allocation. Called from init_alloc_once. */
1202 void
1203 init_strings ()
1205 total_strings = total_free_strings = total_string_size = 0;
1206 oldest_sblock = current_sblock = large_sblocks = NULL;
1207 string_blocks = NULL;
1208 n_string_blocks = 0;
1209 string_free_list = NULL;
1213 #ifdef GC_CHECK_STRING_BYTES
1215 static int check_string_bytes_count;
1217 void check_string_bytes P_ ((int));
1218 void check_sblock P_ ((struct sblock *));
1220 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1223 /* Like GC_STRING_BYTES, but with debugging check. */
1226 string_bytes (s)
1227 struct Lisp_String *s;
1229 int nbytes = (s->size_byte < 0 ? s->size & ~MARKBIT : s->size_byte);
1230 if (!PURE_POINTER_P (s)
1231 && s->data
1232 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1233 abort ();
1234 return nbytes;
1237 /* Check validity of Lisp strings' string_bytes member in B. */
1239 void
1240 check_sblock (b)
1241 struct sblock *b;
1243 struct sdata *from, *end, *from_end;
1245 end = b->next_free;
1247 for (from = &b->first_data; from < end; from = from_end)
1249 /* Compute the next FROM here because copying below may
1250 overwrite data we need to compute it. */
1251 int nbytes;
1253 /* Check that the string size recorded in the string is the
1254 same as the one recorded in the sdata structure. */
1255 if (from->string)
1256 CHECK_STRING_BYTES (from->string);
1258 if (from->string)
1259 nbytes = GC_STRING_BYTES (from->string);
1260 else
1261 nbytes = SDATA_NBYTES (from);
1263 nbytes = SDATA_SIZE (nbytes);
1264 from_end = (struct sdata *) ((char *) from + nbytes);
1269 /* Check validity of Lisp strings' string_bytes member. ALL_P
1270 non-zero means check all strings, otherwise check only most
1271 recently allocated strings. Used for hunting a bug. */
1273 void
1274 check_string_bytes (all_p)
1275 int all_p;
1277 if (all_p)
1279 struct sblock *b;
1281 for (b = large_sblocks; b; b = b->next)
1283 struct Lisp_String *s = b->first_data.string;
1284 if (s)
1285 CHECK_STRING_BYTES (s);
1288 for (b = oldest_sblock; b; b = b->next)
1289 check_sblock (b);
1291 else
1292 check_sblock (current_sblock);
1295 #endif /* GC_CHECK_STRING_BYTES */
1298 /* Return a new Lisp_String. */
1300 static struct Lisp_String *
1301 allocate_string ()
1303 struct Lisp_String *s;
1305 /* If the free-list is empty, allocate a new string_block, and
1306 add all the Lisp_Strings in it to the free-list. */
1307 if (string_free_list == NULL)
1309 struct string_block *b;
1310 int i;
1312 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1313 bzero (b, sizeof *b);
1314 b->next = string_blocks;
1315 string_blocks = b;
1316 ++n_string_blocks;
1318 for (i = STRINGS_IN_STRING_BLOCK - 1; i >= 0; --i)
1320 s = b->strings + i;
1321 NEXT_FREE_LISP_STRING (s) = string_free_list;
1322 string_free_list = s;
1325 total_free_strings += STRINGS_IN_STRING_BLOCK;
1328 /* Pop a Lisp_String off the free-list. */
1329 s = string_free_list;
1330 string_free_list = NEXT_FREE_LISP_STRING (s);
1332 /* Probably not strictly necessary, but play it safe. */
1333 bzero (s, sizeof *s);
1335 --total_free_strings;
1336 ++total_strings;
1337 ++strings_consed;
1338 consing_since_gc += sizeof *s;
1340 #ifdef GC_CHECK_STRING_BYTES
1341 if (!noninteractive
1342 #ifdef MAC_OS8
1343 && current_sblock
1344 #endif
1347 if (++check_string_bytes_count == 200)
1349 check_string_bytes_count = 0;
1350 check_string_bytes (1);
1352 else
1353 check_string_bytes (0);
1355 #endif /* GC_CHECK_STRING_BYTES */
1357 return s;
1361 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1362 plus a NUL byte at the end. Allocate an sdata structure for S, and
1363 set S->data to its `u.data' member. Store a NUL byte at the end of
1364 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1365 S->data if it was initially non-null. */
1367 void
1368 allocate_string_data (s, nchars, nbytes)
1369 struct Lisp_String *s;
1370 int nchars, nbytes;
1372 struct sdata *data, *old_data;
1373 struct sblock *b;
1374 int needed, old_nbytes;
1376 /* Determine the number of bytes needed to store NBYTES bytes
1377 of string data. */
1378 needed = SDATA_SIZE (nbytes);
1380 if (nbytes > LARGE_STRING_BYTES)
1382 size_t size = sizeof *b - sizeof (struct sdata) + needed;
1384 #ifdef DOUG_LEA_MALLOC
1385 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1386 because mapped region contents are not preserved in
1387 a dumped Emacs.
1389 In case you think of allowing it in a dumped Emacs at the
1390 cost of not being able to re-dump, there's another reason:
1391 mmap'ed data typically have an address towards the top of the
1392 address space, which won't fit into an EMACS_INT (at least on
1393 32-bit systems with the current tagging scheme). --fx */
1394 mallopt (M_MMAP_MAX, 0);
1395 #endif
1397 b = (struct sblock *) lisp_malloc (size, MEM_TYPE_NON_LISP);
1399 #ifdef DOUG_LEA_MALLOC
1400 /* Back to a reasonable maximum of mmap'ed areas. */
1401 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1402 #endif
1404 b->next_free = &b->first_data;
1405 b->first_data.string = NULL;
1406 b->next = large_sblocks;
1407 large_sblocks = b;
1409 else if (current_sblock == NULL
1410 || (((char *) current_sblock + SBLOCK_SIZE
1411 - (char *) current_sblock->next_free)
1412 < needed))
1414 /* Not enough room in the current sblock. */
1415 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1416 b->next_free = &b->first_data;
1417 b->first_data.string = NULL;
1418 b->next = NULL;
1420 if (current_sblock)
1421 current_sblock->next = b;
1422 else
1423 oldest_sblock = b;
1424 current_sblock = b;
1426 else
1427 b = current_sblock;
1429 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1430 old_nbytes = GC_STRING_BYTES (s);
1432 data = b->next_free;
1433 data->string = s;
1434 s->data = SDATA_DATA (data);
1435 #ifdef GC_CHECK_STRING_BYTES
1436 SDATA_NBYTES (data) = nbytes;
1437 #endif
1438 s->size = nchars;
1439 s->size_byte = nbytes;
1440 s->data[nbytes] = '\0';
1441 b->next_free = (struct sdata *) ((char *) data + needed);
1443 /* If S had already data assigned, mark that as free by setting its
1444 string back-pointer to null, and recording the size of the data
1445 in it. */
1446 if (old_data)
1448 SDATA_NBYTES (old_data) = old_nbytes;
1449 old_data->string = NULL;
1452 consing_since_gc += needed;
1456 /* Sweep and compact strings. */
1458 static void
1459 sweep_strings ()
1461 struct string_block *b, *next;
1462 struct string_block *live_blocks = NULL;
1464 string_free_list = NULL;
1465 total_strings = total_free_strings = 0;
1466 total_string_size = 0;
1468 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1469 for (b = string_blocks; b; b = next)
1471 int i, nfree = 0;
1472 struct Lisp_String *free_list_before = string_free_list;
1474 next = b->next;
1476 for (i = 0; i < STRINGS_IN_STRING_BLOCK; ++i)
1478 struct Lisp_String *s = b->strings + i;
1480 if (s->data)
1482 /* String was not on free-list before. */
1483 if (STRING_MARKED_P (s))
1485 /* String is live; unmark it and its intervals. */
1486 UNMARK_STRING (s);
1488 if (!NULL_INTERVAL_P (s->intervals))
1489 UNMARK_BALANCE_INTERVALS (s->intervals);
1491 ++total_strings;
1492 total_string_size += STRING_BYTES (s);
1494 else
1496 /* String is dead. Put it on the free-list. */
1497 struct sdata *data = SDATA_OF_STRING (s);
1499 /* Save the size of S in its sdata so that we know
1500 how large that is. Reset the sdata's string
1501 back-pointer so that we know it's free. */
1502 #ifdef GC_CHECK_STRING_BYTES
1503 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
1504 abort ();
1505 #else
1506 data->u.nbytes = GC_STRING_BYTES (s);
1507 #endif
1508 data->string = NULL;
1510 /* Reset the strings's `data' member so that we
1511 know it's free. */
1512 s->data = NULL;
1514 /* Put the string on the free-list. */
1515 NEXT_FREE_LISP_STRING (s) = string_free_list;
1516 string_free_list = s;
1517 ++nfree;
1520 else
1522 /* S was on the free-list before. Put it there again. */
1523 NEXT_FREE_LISP_STRING (s) = string_free_list;
1524 string_free_list = s;
1525 ++nfree;
1529 /* Free blocks that contain free Lisp_Strings only, except
1530 the first two of them. */
1531 if (nfree == STRINGS_IN_STRING_BLOCK
1532 && total_free_strings > STRINGS_IN_STRING_BLOCK)
1534 lisp_free (b);
1535 --n_string_blocks;
1536 string_free_list = free_list_before;
1538 else
1540 total_free_strings += nfree;
1541 b->next = live_blocks;
1542 live_blocks = b;
1546 string_blocks = live_blocks;
1547 free_large_strings ();
1548 compact_small_strings ();
1552 /* Free dead large strings. */
1554 static void
1555 free_large_strings ()
1557 struct sblock *b, *next;
1558 struct sblock *live_blocks = NULL;
1560 for (b = large_sblocks; b; b = next)
1562 next = b->next;
1564 if (b->first_data.string == NULL)
1565 lisp_free (b);
1566 else
1568 b->next = live_blocks;
1569 live_blocks = b;
1573 large_sblocks = live_blocks;
1577 /* Compact data of small strings. Free sblocks that don't contain
1578 data of live strings after compaction. */
1580 static void
1581 compact_small_strings ()
1583 struct sblock *b, *tb, *next;
1584 struct sdata *from, *to, *end, *tb_end;
1585 struct sdata *to_end, *from_end;
1587 /* TB is the sblock we copy to, TO is the sdata within TB we copy
1588 to, and TB_END is the end of TB. */
1589 tb = oldest_sblock;
1590 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1591 to = &tb->first_data;
1593 /* Step through the blocks from the oldest to the youngest. We
1594 expect that old blocks will stabilize over time, so that less
1595 copying will happen this way. */
1596 for (b = oldest_sblock; b; b = b->next)
1598 end = b->next_free;
1599 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
1601 for (from = &b->first_data; from < end; from = from_end)
1603 /* Compute the next FROM here because copying below may
1604 overwrite data we need to compute it. */
1605 int nbytes;
1607 #ifdef GC_CHECK_STRING_BYTES
1608 /* Check that the string size recorded in the string is the
1609 same as the one recorded in the sdata structure. */
1610 if (from->string
1611 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
1612 abort ();
1613 #endif /* GC_CHECK_STRING_BYTES */
1615 if (from->string)
1616 nbytes = GC_STRING_BYTES (from->string);
1617 else
1618 nbytes = SDATA_NBYTES (from);
1620 nbytes = SDATA_SIZE (nbytes);
1621 from_end = (struct sdata *) ((char *) from + nbytes);
1623 /* FROM->string non-null means it's alive. Copy its data. */
1624 if (from->string)
1626 /* If TB is full, proceed with the next sblock. */
1627 to_end = (struct sdata *) ((char *) to + nbytes);
1628 if (to_end > tb_end)
1630 tb->next_free = to;
1631 tb = tb->next;
1632 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1633 to = &tb->first_data;
1634 to_end = (struct sdata *) ((char *) to + nbytes);
1637 /* Copy, and update the string's `data' pointer. */
1638 if (from != to)
1640 xassert (tb != b || to <= from);
1641 safe_bcopy ((char *) from, (char *) to, nbytes);
1642 to->string->data = SDATA_DATA (to);
1645 /* Advance past the sdata we copied to. */
1646 to = to_end;
1651 /* The rest of the sblocks following TB don't contain live data, so
1652 we can free them. */
1653 for (b = tb->next; b; b = next)
1655 next = b->next;
1656 lisp_free (b);
1659 tb->next_free = to;
1660 tb->next = NULL;
1661 current_sblock = tb;
1665 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
1666 doc: /* Return a newly created string of length LENGTH, with each element being INIT.
1667 Both LENGTH and INIT must be numbers. */)
1668 (length, init)
1669 Lisp_Object length, init;
1671 register Lisp_Object val;
1672 register unsigned char *p, *end;
1673 int c, nbytes;
1675 CHECK_NATNUM (length);
1676 CHECK_NUMBER (init);
1678 c = XINT (init);
1679 if (SINGLE_BYTE_CHAR_P (c))
1681 nbytes = XINT (length);
1682 val = make_uninit_string (nbytes);
1683 p = SDATA (val);
1684 end = p + SCHARS (val);
1685 while (p != end)
1686 *p++ = c;
1688 else
1690 unsigned char str[MAX_MULTIBYTE_LENGTH];
1691 int len = CHAR_STRING (c, str);
1693 nbytes = len * XINT (length);
1694 val = make_uninit_multibyte_string (XINT (length), nbytes);
1695 p = SDATA (val);
1696 end = p + nbytes;
1697 while (p != end)
1699 bcopy (str, p, len);
1700 p += len;
1704 *p = 0;
1705 return val;
1709 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
1710 doc: /* Return a new bool-vector of length LENGTH, using INIT for as each element.
1711 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
1712 (length, init)
1713 Lisp_Object length, init;
1715 register Lisp_Object val;
1716 struct Lisp_Bool_Vector *p;
1717 int real_init, i;
1718 int length_in_chars, length_in_elts, bits_per_value;
1720 CHECK_NATNUM (length);
1722 bits_per_value = sizeof (EMACS_INT) * BITS_PER_CHAR;
1724 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
1725 length_in_chars = ((XFASTINT (length) + BITS_PER_CHAR - 1) / BITS_PER_CHAR);
1727 /* We must allocate one more elements than LENGTH_IN_ELTS for the
1728 slot `size' of the struct Lisp_Bool_Vector. */
1729 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
1730 p = XBOOL_VECTOR (val);
1732 /* Get rid of any bits that would cause confusion. */
1733 p->vector_size = 0;
1734 XSETBOOL_VECTOR (val, p);
1735 p->size = XFASTINT (length);
1737 real_init = (NILP (init) ? 0 : -1);
1738 for (i = 0; i < length_in_chars ; i++)
1739 p->data[i] = real_init;
1741 /* Clear the extraneous bits in the last byte. */
1742 if (XINT (length) != length_in_chars * BITS_PER_CHAR)
1743 XBOOL_VECTOR (val)->data[length_in_chars - 1]
1744 &= (1 << (XINT (length) % BITS_PER_CHAR)) - 1;
1746 return val;
1750 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
1751 of characters from the contents. This string may be unibyte or
1752 multibyte, depending on the contents. */
1754 Lisp_Object
1755 make_string (contents, nbytes)
1756 const char *contents;
1757 int nbytes;
1759 register Lisp_Object val;
1760 int nchars, multibyte_nbytes;
1762 parse_str_as_multibyte (contents, nbytes, &nchars, &multibyte_nbytes);
1763 if (nbytes == nchars || nbytes != multibyte_nbytes)
1764 /* CONTENTS contains no multibyte sequences or contains an invalid
1765 multibyte sequence. We must make unibyte string. */
1766 val = make_unibyte_string (contents, nbytes);
1767 else
1768 val = make_multibyte_string (contents, nchars, nbytes);
1769 return val;
1773 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
1775 Lisp_Object
1776 make_unibyte_string (contents, length)
1777 const char *contents;
1778 int length;
1780 register Lisp_Object val;
1781 val = make_uninit_string (length);
1782 bcopy (contents, SDATA (val), length);
1783 STRING_SET_UNIBYTE (val);
1784 return val;
1788 /* Make a multibyte string from NCHARS characters occupying NBYTES
1789 bytes at CONTENTS. */
1791 Lisp_Object
1792 make_multibyte_string (contents, nchars, nbytes)
1793 const char *contents;
1794 int nchars, nbytes;
1796 register Lisp_Object val;
1797 val = make_uninit_multibyte_string (nchars, nbytes);
1798 bcopy (contents, SDATA (val), nbytes);
1799 return val;
1803 /* Make a string from NCHARS characters occupying NBYTES bytes at
1804 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
1806 Lisp_Object
1807 make_string_from_bytes (contents, nchars, nbytes)
1808 const char *contents;
1809 int nchars, nbytes;
1811 register Lisp_Object val;
1812 val = make_uninit_multibyte_string (nchars, nbytes);
1813 bcopy (contents, SDATA (val), nbytes);
1814 if (SBYTES (val) == SCHARS (val))
1815 STRING_SET_UNIBYTE (val);
1816 return val;
1820 /* Make a string from NCHARS characters occupying NBYTES bytes at
1821 CONTENTS. The argument MULTIBYTE controls whether to label the
1822 string as multibyte. If NCHARS is negative, it counts the number of
1823 characters by itself. */
1825 Lisp_Object
1826 make_specified_string (contents, nchars, nbytes, multibyte)
1827 const char *contents;
1828 int nchars, nbytes;
1829 int multibyte;
1831 register Lisp_Object val;
1833 if (nchars < 0)
1835 if (multibyte)
1836 nchars = multibyte_chars_in_text (contents, nbytes);
1837 else
1838 nchars = nbytes;
1840 val = make_uninit_multibyte_string (nchars, nbytes);
1841 bcopy (contents, SDATA (val), nbytes);
1842 if (!multibyte)
1843 STRING_SET_UNIBYTE (val);
1844 return val;
1848 /* Make a string from the data at STR, treating it as multibyte if the
1849 data warrants. */
1851 Lisp_Object
1852 build_string (str)
1853 const char *str;
1855 return make_string (str, strlen (str));
1859 /* Return an unibyte Lisp_String set up to hold LENGTH characters
1860 occupying LENGTH bytes. */
1862 Lisp_Object
1863 make_uninit_string (length)
1864 int length;
1866 Lisp_Object val;
1867 val = make_uninit_multibyte_string (length, length);
1868 STRING_SET_UNIBYTE (val);
1869 return val;
1873 /* Return a multibyte Lisp_String set up to hold NCHARS characters
1874 which occupy NBYTES bytes. */
1876 Lisp_Object
1877 make_uninit_multibyte_string (nchars, nbytes)
1878 int nchars, nbytes;
1880 Lisp_Object string;
1881 struct Lisp_String *s;
1883 if (nchars < 0)
1884 abort ();
1886 s = allocate_string ();
1887 allocate_string_data (s, nchars, nbytes);
1888 XSETSTRING (string, s);
1889 string_chars_consed += nbytes;
1890 return string;
1895 /***********************************************************************
1896 Float Allocation
1897 ***********************************************************************/
1899 /* We store float cells inside of float_blocks, allocating a new
1900 float_block with malloc whenever necessary. Float cells reclaimed
1901 by GC are put on a free list to be reallocated before allocating
1902 any new float cells from the latest float_block.
1904 Each float_block is just under 1020 bytes long, since malloc really
1905 allocates in units of powers of two and uses 4 bytes for its own
1906 overhead. */
1908 #define FLOAT_BLOCK_SIZE \
1909 ((1020 - sizeof (struct float_block *)) / sizeof (struct Lisp_Float))
1911 struct float_block
1913 struct float_block *next;
1914 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
1917 /* Current float_block. */
1919 struct float_block *float_block;
1921 /* Index of first unused Lisp_Float in the current float_block. */
1923 int float_block_index;
1925 /* Total number of float blocks now in use. */
1927 int n_float_blocks;
1929 /* Free-list of Lisp_Floats. */
1931 struct Lisp_Float *float_free_list;
1934 /* Initialize float allocation. */
1936 void
1937 init_float ()
1939 float_block = (struct float_block *) lisp_malloc (sizeof *float_block,
1940 MEM_TYPE_FLOAT);
1941 float_block->next = 0;
1942 bzero ((char *) float_block->floats, sizeof float_block->floats);
1943 float_block_index = 0;
1944 float_free_list = 0;
1945 n_float_blocks = 1;
1949 /* Explicitly free a float cell by putting it on the free-list. */
1951 void
1952 free_float (ptr)
1953 struct Lisp_Float *ptr;
1955 *(struct Lisp_Float **)&ptr->data = float_free_list;
1956 #if GC_MARK_STACK
1957 ptr->type = Vdead;
1958 #endif
1959 float_free_list = ptr;
1963 /* Return a new float object with value FLOAT_VALUE. */
1965 Lisp_Object
1966 make_float (float_value)
1967 double float_value;
1969 register Lisp_Object val;
1971 if (float_free_list)
1973 /* We use the data field for chaining the free list
1974 so that we won't use the same field that has the mark bit. */
1975 XSETFLOAT (val, float_free_list);
1976 float_free_list = *(struct Lisp_Float **)&float_free_list->data;
1978 else
1980 if (float_block_index == FLOAT_BLOCK_SIZE)
1982 register struct float_block *new;
1984 new = (struct float_block *) lisp_malloc (sizeof *new,
1985 MEM_TYPE_FLOAT);
1986 new->next = float_block;
1987 float_block = new;
1988 float_block_index = 0;
1989 n_float_blocks++;
1991 XSETFLOAT (val, &float_block->floats[float_block_index++]);
1994 XFLOAT_DATA (val) = float_value;
1995 XSETFASTINT (XFLOAT (val)->type, 0); /* bug chasing -wsr */
1996 consing_since_gc += sizeof (struct Lisp_Float);
1997 floats_consed++;
1998 return val;
2003 /***********************************************************************
2004 Cons Allocation
2005 ***********************************************************************/
2007 /* We store cons cells inside of cons_blocks, allocating a new
2008 cons_block with malloc whenever necessary. Cons cells reclaimed by
2009 GC are put on a free list to be reallocated before allocating
2010 any new cons cells from the latest cons_block.
2012 Each cons_block is just under 1020 bytes long,
2013 since malloc really allocates in units of powers of two
2014 and uses 4 bytes for its own overhead. */
2016 #define CONS_BLOCK_SIZE \
2017 ((1020 - sizeof (struct cons_block *)) / sizeof (struct Lisp_Cons))
2019 struct cons_block
2021 struct cons_block *next;
2022 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2025 /* Current cons_block. */
2027 struct cons_block *cons_block;
2029 /* Index of first unused Lisp_Cons in the current block. */
2031 int cons_block_index;
2033 /* Free-list of Lisp_Cons structures. */
2035 struct Lisp_Cons *cons_free_list;
2037 /* Total number of cons blocks now in use. */
2039 int n_cons_blocks;
2042 /* Initialize cons allocation. */
2044 void
2045 init_cons ()
2047 cons_block = (struct cons_block *) lisp_malloc (sizeof *cons_block,
2048 MEM_TYPE_CONS);
2049 cons_block->next = 0;
2050 bzero ((char *) cons_block->conses, sizeof cons_block->conses);
2051 cons_block_index = 0;
2052 cons_free_list = 0;
2053 n_cons_blocks = 1;
2057 /* Explicitly free a cons cell by putting it on the free-list. */
2059 void
2060 free_cons (ptr)
2061 struct Lisp_Cons *ptr;
2063 *(struct Lisp_Cons **)&ptr->cdr = cons_free_list;
2064 #if GC_MARK_STACK
2065 ptr->car = Vdead;
2066 #endif
2067 cons_free_list = ptr;
2071 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2072 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2073 (car, cdr)
2074 Lisp_Object car, cdr;
2076 register Lisp_Object val;
2078 if (cons_free_list)
2080 /* We use the cdr for chaining the free list
2081 so that we won't use the same field that has the mark bit. */
2082 XSETCONS (val, cons_free_list);
2083 cons_free_list = *(struct Lisp_Cons **)&cons_free_list->cdr;
2085 else
2087 if (cons_block_index == CONS_BLOCK_SIZE)
2089 register struct cons_block *new;
2090 new = (struct cons_block *) lisp_malloc (sizeof *new,
2091 MEM_TYPE_CONS);
2092 new->next = cons_block;
2093 cons_block = new;
2094 cons_block_index = 0;
2095 n_cons_blocks++;
2097 XSETCONS (val, &cons_block->conses[cons_block_index++]);
2100 XSETCAR (val, car);
2101 XSETCDR (val, cdr);
2102 consing_since_gc += sizeof (struct Lisp_Cons);
2103 cons_cells_consed++;
2104 return val;
2108 /* Make a list of 2, 3, 4 or 5 specified objects. */
2110 Lisp_Object
2111 list2 (arg1, arg2)
2112 Lisp_Object arg1, arg2;
2114 return Fcons (arg1, Fcons (arg2, Qnil));
2118 Lisp_Object
2119 list3 (arg1, arg2, arg3)
2120 Lisp_Object arg1, arg2, arg3;
2122 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2126 Lisp_Object
2127 list4 (arg1, arg2, arg3, arg4)
2128 Lisp_Object arg1, arg2, arg3, arg4;
2130 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2134 Lisp_Object
2135 list5 (arg1, arg2, arg3, arg4, arg5)
2136 Lisp_Object arg1, arg2, arg3, arg4, arg5;
2138 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2139 Fcons (arg5, Qnil)))));
2143 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2144 doc: /* Return a newly created list with specified arguments as elements.
2145 Any number of arguments, even zero arguments, are allowed.
2146 usage: (list &rest OBJECTS) */)
2147 (nargs, args)
2148 int nargs;
2149 register Lisp_Object *args;
2151 register Lisp_Object val;
2152 val = Qnil;
2154 while (nargs > 0)
2156 nargs--;
2157 val = Fcons (args[nargs], val);
2159 return val;
2163 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2164 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2165 (length, init)
2166 register Lisp_Object length, init;
2168 register Lisp_Object val;
2169 register int size;
2171 CHECK_NATNUM (length);
2172 size = XFASTINT (length);
2174 val = Qnil;
2175 while (size > 0)
2177 val = Fcons (init, val);
2178 --size;
2180 if (size > 0)
2182 val = Fcons (init, val);
2183 --size;
2185 if (size > 0)
2187 val = Fcons (init, val);
2188 --size;
2190 if (size > 0)
2192 val = Fcons (init, val);
2193 --size;
2195 if (size > 0)
2197 val = Fcons (init, val);
2198 --size;
2204 QUIT;
2207 return val;
2212 /***********************************************************************
2213 Vector Allocation
2214 ***********************************************************************/
2216 /* Singly-linked list of all vectors. */
2218 struct Lisp_Vector *all_vectors;
2220 /* Total number of vector-like objects now in use. */
2222 int n_vectors;
2225 /* Value is a pointer to a newly allocated Lisp_Vector structure
2226 with room for LEN Lisp_Objects. */
2228 static struct Lisp_Vector *
2229 allocate_vectorlike (len, type)
2230 EMACS_INT len;
2231 enum mem_type type;
2233 struct Lisp_Vector *p;
2234 size_t nbytes;
2236 #ifdef DOUG_LEA_MALLOC
2237 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2238 because mapped region contents are not preserved in
2239 a dumped Emacs. */
2240 mallopt (M_MMAP_MAX, 0);
2241 #endif
2243 nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
2244 p = (struct Lisp_Vector *) lisp_malloc (nbytes, type);
2246 #ifdef DOUG_LEA_MALLOC
2247 /* Back to a reasonable maximum of mmap'ed areas. */
2248 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2249 #endif
2251 consing_since_gc += nbytes;
2252 vector_cells_consed += len;
2254 p->next = all_vectors;
2255 all_vectors = p;
2256 ++n_vectors;
2257 return p;
2261 /* Allocate a vector with NSLOTS slots. */
2263 struct Lisp_Vector *
2264 allocate_vector (nslots)
2265 EMACS_INT nslots;
2267 struct Lisp_Vector *v = allocate_vectorlike (nslots, MEM_TYPE_VECTOR);
2268 v->size = nslots;
2269 return v;
2273 /* Allocate other vector-like structures. */
2275 struct Lisp_Hash_Table *
2276 allocate_hash_table ()
2278 EMACS_INT len = VECSIZE (struct Lisp_Hash_Table);
2279 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_HASH_TABLE);
2280 EMACS_INT i;
2282 v->size = len;
2283 for (i = 0; i < len; ++i)
2284 v->contents[i] = Qnil;
2286 return (struct Lisp_Hash_Table *) v;
2290 struct window *
2291 allocate_window ()
2293 EMACS_INT len = VECSIZE (struct window);
2294 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_WINDOW);
2295 EMACS_INT i;
2297 for (i = 0; i < len; ++i)
2298 v->contents[i] = Qnil;
2299 v->size = len;
2301 return (struct window *) v;
2305 struct frame *
2306 allocate_frame ()
2308 EMACS_INT len = VECSIZE (struct frame);
2309 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_FRAME);
2310 EMACS_INT i;
2312 for (i = 0; i < len; ++i)
2313 v->contents[i] = make_number (0);
2314 v->size = len;
2315 return (struct frame *) v;
2319 struct Lisp_Process *
2320 allocate_process ()
2322 EMACS_INT len = VECSIZE (struct Lisp_Process);
2323 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_PROCESS);
2324 EMACS_INT i;
2326 for (i = 0; i < len; ++i)
2327 v->contents[i] = Qnil;
2328 v->size = len;
2330 return (struct Lisp_Process *) v;
2334 struct Lisp_Vector *
2335 allocate_other_vector (len)
2336 EMACS_INT len;
2338 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_VECTOR);
2339 EMACS_INT i;
2341 for (i = 0; i < len; ++i)
2342 v->contents[i] = Qnil;
2343 v->size = len;
2345 return v;
2349 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
2350 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
2351 See also the function `vector'. */)
2352 (length, init)
2353 register Lisp_Object length, init;
2355 Lisp_Object vector;
2356 register EMACS_INT sizei;
2357 register int index;
2358 register struct Lisp_Vector *p;
2360 CHECK_NATNUM (length);
2361 sizei = XFASTINT (length);
2363 p = allocate_vector (sizei);
2364 for (index = 0; index < sizei; index++)
2365 p->contents[index] = init;
2367 XSETVECTOR (vector, p);
2368 return vector;
2372 DEFUN ("make-char-table", Fmake_char_table, Smake_char_table, 1, 2, 0,
2373 doc: /* Return a newly created char-table, with purpose PURPOSE.
2374 Each element is initialized to INIT, which defaults to nil.
2375 PURPOSE should be a symbol which has a `char-table-extra-slots' property.
2376 The property's value should be an integer between 0 and 10. */)
2377 (purpose, init)
2378 register Lisp_Object purpose, init;
2380 Lisp_Object vector;
2381 Lisp_Object n;
2382 CHECK_SYMBOL (purpose);
2383 n = Fget (purpose, Qchar_table_extra_slots);
2384 CHECK_NUMBER (n);
2385 if (XINT (n) < 0 || XINT (n) > 10)
2386 args_out_of_range (n, Qnil);
2387 /* Add 2 to the size for the defalt and parent slots. */
2388 vector = Fmake_vector (make_number (CHAR_TABLE_STANDARD_SLOTS + XINT (n)),
2389 init);
2390 XCHAR_TABLE (vector)->top = Qt;
2391 XCHAR_TABLE (vector)->parent = Qnil;
2392 XCHAR_TABLE (vector)->purpose = purpose;
2393 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
2394 return vector;
2398 /* Return a newly created sub char table with default value DEFALT.
2399 Since a sub char table does not appear as a top level Emacs Lisp
2400 object, we don't need a Lisp interface to make it. */
2402 Lisp_Object
2403 make_sub_char_table (defalt)
2404 Lisp_Object defalt;
2406 Lisp_Object vector
2407 = Fmake_vector (make_number (SUB_CHAR_TABLE_STANDARD_SLOTS), Qnil);
2408 XCHAR_TABLE (vector)->top = Qnil;
2409 XCHAR_TABLE (vector)->defalt = defalt;
2410 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
2411 return vector;
2415 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
2416 doc: /* Return a newly created vector with specified arguments as elements.
2417 Any number of arguments, even zero arguments, are allowed.
2418 usage: (vector &rest OBJECTS) */)
2419 (nargs, args)
2420 register int nargs;
2421 Lisp_Object *args;
2423 register Lisp_Object len, val;
2424 register int index;
2425 register struct Lisp_Vector *p;
2427 XSETFASTINT (len, nargs);
2428 val = Fmake_vector (len, Qnil);
2429 p = XVECTOR (val);
2430 for (index = 0; index < nargs; index++)
2431 p->contents[index] = args[index];
2432 return val;
2436 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
2437 doc: /* Create a byte-code object with specified arguments as elements.
2438 The arguments should be the arglist, bytecode-string, constant vector,
2439 stack size, (optional) doc string, and (optional) interactive spec.
2440 The first four arguments are required; at most six have any
2441 significance.
2442 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
2443 (nargs, args)
2444 register int nargs;
2445 Lisp_Object *args;
2447 register Lisp_Object len, val;
2448 register int index;
2449 register struct Lisp_Vector *p;
2451 XSETFASTINT (len, nargs);
2452 if (!NILP (Vpurify_flag))
2453 val = make_pure_vector ((EMACS_INT) nargs);
2454 else
2455 val = Fmake_vector (len, Qnil);
2457 if (STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
2458 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
2459 earlier because they produced a raw 8-bit string for byte-code
2460 and now such a byte-code string is loaded as multibyte while
2461 raw 8-bit characters converted to multibyte form. Thus, now we
2462 must convert them back to the original unibyte form. */
2463 args[1] = Fstring_as_unibyte (args[1]);
2465 p = XVECTOR (val);
2466 for (index = 0; index < nargs; index++)
2468 if (!NILP (Vpurify_flag))
2469 args[index] = Fpurecopy (args[index]);
2470 p->contents[index] = args[index];
2472 XSETCOMPILED (val, p);
2473 return val;
2478 /***********************************************************************
2479 Symbol Allocation
2480 ***********************************************************************/
2482 /* Each symbol_block is just under 1020 bytes long, since malloc
2483 really allocates in units of powers of two and uses 4 bytes for its
2484 own overhead. */
2486 #define SYMBOL_BLOCK_SIZE \
2487 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
2489 struct symbol_block
2491 struct symbol_block *next;
2492 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
2495 /* Current symbol block and index of first unused Lisp_Symbol
2496 structure in it. */
2498 struct symbol_block *symbol_block;
2499 int symbol_block_index;
2501 /* List of free symbols. */
2503 struct Lisp_Symbol *symbol_free_list;
2505 /* Total number of symbol blocks now in use. */
2507 int n_symbol_blocks;
2510 /* Initialize symbol allocation. */
2512 void
2513 init_symbol ()
2515 symbol_block = (struct symbol_block *) lisp_malloc (sizeof *symbol_block,
2516 MEM_TYPE_SYMBOL);
2517 symbol_block->next = 0;
2518 bzero ((char *) symbol_block->symbols, sizeof symbol_block->symbols);
2519 symbol_block_index = 0;
2520 symbol_free_list = 0;
2521 n_symbol_blocks = 1;
2525 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
2526 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
2527 Its value and function definition are void, and its property list is nil. */)
2528 (name)
2529 Lisp_Object name;
2531 register Lisp_Object val;
2532 register struct Lisp_Symbol *p;
2534 CHECK_STRING (name);
2536 if (symbol_free_list)
2538 XSETSYMBOL (val, symbol_free_list);
2539 symbol_free_list = *(struct Lisp_Symbol **)&symbol_free_list->value;
2541 else
2543 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
2545 struct symbol_block *new;
2546 new = (struct symbol_block *) lisp_malloc (sizeof *new,
2547 MEM_TYPE_SYMBOL);
2548 new->next = symbol_block;
2549 symbol_block = new;
2550 symbol_block_index = 0;
2551 n_symbol_blocks++;
2553 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index++]);
2556 p = XSYMBOL (val);
2557 p->xname = name;
2558 p->plist = Qnil;
2559 p->value = Qunbound;
2560 p->function = Qunbound;
2561 p->next = NULL;
2562 p->gcmarkbit = 0;
2563 p->interned = SYMBOL_UNINTERNED;
2564 p->constant = 0;
2565 p->indirect_variable = 0;
2566 consing_since_gc += sizeof (struct Lisp_Symbol);
2567 symbols_consed++;
2568 return val;
2573 /***********************************************************************
2574 Marker (Misc) Allocation
2575 ***********************************************************************/
2577 /* Allocation of markers and other objects that share that structure.
2578 Works like allocation of conses. */
2580 #define MARKER_BLOCK_SIZE \
2581 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
2583 struct marker_block
2585 struct marker_block *next;
2586 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
2589 struct marker_block *marker_block;
2590 int marker_block_index;
2592 union Lisp_Misc *marker_free_list;
2594 /* Total number of marker blocks now in use. */
2596 int n_marker_blocks;
2598 void
2599 init_marker ()
2601 marker_block = (struct marker_block *) lisp_malloc (sizeof *marker_block,
2602 MEM_TYPE_MISC);
2603 marker_block->next = 0;
2604 bzero ((char *) marker_block->markers, sizeof marker_block->markers);
2605 marker_block_index = 0;
2606 marker_free_list = 0;
2607 n_marker_blocks = 1;
2610 /* Return a newly allocated Lisp_Misc object, with no substructure. */
2612 Lisp_Object
2613 allocate_misc ()
2615 Lisp_Object val;
2617 if (marker_free_list)
2619 XSETMISC (val, marker_free_list);
2620 marker_free_list = marker_free_list->u_free.chain;
2622 else
2624 if (marker_block_index == MARKER_BLOCK_SIZE)
2626 struct marker_block *new;
2627 new = (struct marker_block *) lisp_malloc (sizeof *new,
2628 MEM_TYPE_MISC);
2629 new->next = marker_block;
2630 marker_block = new;
2631 marker_block_index = 0;
2632 n_marker_blocks++;
2634 XSETMISC (val, &marker_block->markers[marker_block_index++]);
2637 consing_since_gc += sizeof (union Lisp_Misc);
2638 misc_objects_consed++;
2639 XMARKER (val)->gcmarkbit = 0;
2640 return val;
2643 /* Return a Lisp_Misc_Save_Value object containing POINTER and
2644 INTEGER. This is used to package C values to call record_unwind_protect.
2645 The unwind function can get the C values back using XSAVE_VALUE. */
2647 Lisp_Object
2648 make_save_value (pointer, integer)
2649 void *pointer;
2650 int integer;
2652 register Lisp_Object val;
2653 register struct Lisp_Save_Value *p;
2655 val = allocate_misc ();
2656 XMISCTYPE (val) = Lisp_Misc_Save_Value;
2657 p = XSAVE_VALUE (val);
2658 p->pointer = pointer;
2659 p->integer = integer;
2660 return val;
2663 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
2664 doc: /* Return a newly allocated marker which does not point at any place. */)
2667 register Lisp_Object val;
2668 register struct Lisp_Marker *p;
2670 val = allocate_misc ();
2671 XMISCTYPE (val) = Lisp_Misc_Marker;
2672 p = XMARKER (val);
2673 p->buffer = 0;
2674 p->bytepos = 0;
2675 p->charpos = 0;
2676 p->next = NULL;
2677 p->insertion_type = 0;
2678 return val;
2681 /* Put MARKER back on the free list after using it temporarily. */
2683 void
2684 free_marker (marker)
2685 Lisp_Object marker;
2687 unchain_marker (XMARKER (marker));
2689 XMISC (marker)->u_marker.type = Lisp_Misc_Free;
2690 XMISC (marker)->u_free.chain = marker_free_list;
2691 marker_free_list = XMISC (marker);
2693 total_free_markers++;
2697 /* Return a newly created vector or string with specified arguments as
2698 elements. If all the arguments are characters that can fit
2699 in a string of events, make a string; otherwise, make a vector.
2701 Any number of arguments, even zero arguments, are allowed. */
2703 Lisp_Object
2704 make_event_array (nargs, args)
2705 register int nargs;
2706 Lisp_Object *args;
2708 int i;
2710 for (i = 0; i < nargs; i++)
2711 /* The things that fit in a string
2712 are characters that are in 0...127,
2713 after discarding the meta bit and all the bits above it. */
2714 if (!INTEGERP (args[i])
2715 || (XUINT (args[i]) & ~(-CHAR_META)) >= 0200)
2716 return Fvector (nargs, args);
2718 /* Since the loop exited, we know that all the things in it are
2719 characters, so we can make a string. */
2721 Lisp_Object result;
2723 result = Fmake_string (make_number (nargs), make_number (0));
2724 for (i = 0; i < nargs; i++)
2726 SSET (result, i, XINT (args[i]));
2727 /* Move the meta bit to the right place for a string char. */
2728 if (XINT (args[i]) & CHAR_META)
2729 SSET (result, i, SREF (result, i) | 0x80);
2732 return result;
2738 /************************************************************************
2739 C Stack Marking
2740 ************************************************************************/
2742 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
2744 /* Conservative C stack marking requires a method to identify possibly
2745 live Lisp objects given a pointer value. We do this by keeping
2746 track of blocks of Lisp data that are allocated in a red-black tree
2747 (see also the comment of mem_node which is the type of nodes in
2748 that tree). Function lisp_malloc adds information for an allocated
2749 block to the red-black tree with calls to mem_insert, and function
2750 lisp_free removes it with mem_delete. Functions live_string_p etc
2751 call mem_find to lookup information about a given pointer in the
2752 tree, and use that to determine if the pointer points to a Lisp
2753 object or not. */
2755 /* Initialize this part of alloc.c. */
2757 static void
2758 mem_init ()
2760 mem_z.left = mem_z.right = MEM_NIL;
2761 mem_z.parent = NULL;
2762 mem_z.color = MEM_BLACK;
2763 mem_z.start = mem_z.end = NULL;
2764 mem_root = MEM_NIL;
2768 /* Value is a pointer to the mem_node containing START. Value is
2769 MEM_NIL if there is no node in the tree containing START. */
2771 static INLINE struct mem_node *
2772 mem_find (start)
2773 void *start;
2775 struct mem_node *p;
2777 if (start < min_heap_address || start > max_heap_address)
2778 return MEM_NIL;
2780 /* Make the search always successful to speed up the loop below. */
2781 mem_z.start = start;
2782 mem_z.end = (char *) start + 1;
2784 p = mem_root;
2785 while (start < p->start || start >= p->end)
2786 p = start < p->start ? p->left : p->right;
2787 return p;
2791 /* Insert a new node into the tree for a block of memory with start
2792 address START, end address END, and type TYPE. Value is a
2793 pointer to the node that was inserted. */
2795 static struct mem_node *
2796 mem_insert (start, end, type)
2797 void *start, *end;
2798 enum mem_type type;
2800 struct mem_node *c, *parent, *x;
2802 if (start < min_heap_address)
2803 min_heap_address = start;
2804 if (end > max_heap_address)
2805 max_heap_address = end;
2807 /* See where in the tree a node for START belongs. In this
2808 particular application, it shouldn't happen that a node is already
2809 present. For debugging purposes, let's check that. */
2810 c = mem_root;
2811 parent = NULL;
2813 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
2815 while (c != MEM_NIL)
2817 if (start >= c->start && start < c->end)
2818 abort ();
2819 parent = c;
2820 c = start < c->start ? c->left : c->right;
2823 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2825 while (c != MEM_NIL)
2827 parent = c;
2828 c = start < c->start ? c->left : c->right;
2831 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2833 /* Create a new node. */
2834 #ifdef GC_MALLOC_CHECK
2835 x = (struct mem_node *) _malloc_internal (sizeof *x);
2836 if (x == NULL)
2837 abort ();
2838 #else
2839 x = (struct mem_node *) xmalloc (sizeof *x);
2840 #endif
2841 x->start = start;
2842 x->end = end;
2843 x->type = type;
2844 x->parent = parent;
2845 x->left = x->right = MEM_NIL;
2846 x->color = MEM_RED;
2848 /* Insert it as child of PARENT or install it as root. */
2849 if (parent)
2851 if (start < parent->start)
2852 parent->left = x;
2853 else
2854 parent->right = x;
2856 else
2857 mem_root = x;
2859 /* Re-establish red-black tree properties. */
2860 mem_insert_fixup (x);
2862 return x;
2866 /* Re-establish the red-black properties of the tree, and thereby
2867 balance the tree, after node X has been inserted; X is always red. */
2869 static void
2870 mem_insert_fixup (x)
2871 struct mem_node *x;
2873 while (x != mem_root && x->parent->color == MEM_RED)
2875 /* X is red and its parent is red. This is a violation of
2876 red-black tree property #3. */
2878 if (x->parent == x->parent->parent->left)
2880 /* We're on the left side of our grandparent, and Y is our
2881 "uncle". */
2882 struct mem_node *y = x->parent->parent->right;
2884 if (y->color == MEM_RED)
2886 /* Uncle and parent are red but should be black because
2887 X is red. Change the colors accordingly and proceed
2888 with the grandparent. */
2889 x->parent->color = MEM_BLACK;
2890 y->color = MEM_BLACK;
2891 x->parent->parent->color = MEM_RED;
2892 x = x->parent->parent;
2894 else
2896 /* Parent and uncle have different colors; parent is
2897 red, uncle is black. */
2898 if (x == x->parent->right)
2900 x = x->parent;
2901 mem_rotate_left (x);
2904 x->parent->color = MEM_BLACK;
2905 x->parent->parent->color = MEM_RED;
2906 mem_rotate_right (x->parent->parent);
2909 else
2911 /* This is the symmetrical case of above. */
2912 struct mem_node *y = x->parent->parent->left;
2914 if (y->color == MEM_RED)
2916 x->parent->color = MEM_BLACK;
2917 y->color = MEM_BLACK;
2918 x->parent->parent->color = MEM_RED;
2919 x = x->parent->parent;
2921 else
2923 if (x == x->parent->left)
2925 x = x->parent;
2926 mem_rotate_right (x);
2929 x->parent->color = MEM_BLACK;
2930 x->parent->parent->color = MEM_RED;
2931 mem_rotate_left (x->parent->parent);
2936 /* The root may have been changed to red due to the algorithm. Set
2937 it to black so that property #5 is satisfied. */
2938 mem_root->color = MEM_BLACK;
2942 /* (x) (y)
2943 / \ / \
2944 a (y) ===> (x) c
2945 / \ / \
2946 b c a b */
2948 static void
2949 mem_rotate_left (x)
2950 struct mem_node *x;
2952 struct mem_node *y;
2954 /* Turn y's left sub-tree into x's right sub-tree. */
2955 y = x->right;
2956 x->right = y->left;
2957 if (y->left != MEM_NIL)
2958 y->left->parent = x;
2960 /* Y's parent was x's parent. */
2961 if (y != MEM_NIL)
2962 y->parent = x->parent;
2964 /* Get the parent to point to y instead of x. */
2965 if (x->parent)
2967 if (x == x->parent->left)
2968 x->parent->left = y;
2969 else
2970 x->parent->right = y;
2972 else
2973 mem_root = y;
2975 /* Put x on y's left. */
2976 y->left = x;
2977 if (x != MEM_NIL)
2978 x->parent = y;
2982 /* (x) (Y)
2983 / \ / \
2984 (y) c ===> a (x)
2985 / \ / \
2986 a b b c */
2988 static void
2989 mem_rotate_right (x)
2990 struct mem_node *x;
2992 struct mem_node *y = x->left;
2994 x->left = y->right;
2995 if (y->right != MEM_NIL)
2996 y->right->parent = x;
2998 if (y != MEM_NIL)
2999 y->parent = x->parent;
3000 if (x->parent)
3002 if (x == x->parent->right)
3003 x->parent->right = y;
3004 else
3005 x->parent->left = y;
3007 else
3008 mem_root = y;
3010 y->right = x;
3011 if (x != MEM_NIL)
3012 x->parent = y;
3016 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
3018 static void
3019 mem_delete (z)
3020 struct mem_node *z;
3022 struct mem_node *x, *y;
3024 if (!z || z == MEM_NIL)
3025 return;
3027 if (z->left == MEM_NIL || z->right == MEM_NIL)
3028 y = z;
3029 else
3031 y = z->right;
3032 while (y->left != MEM_NIL)
3033 y = y->left;
3036 if (y->left != MEM_NIL)
3037 x = y->left;
3038 else
3039 x = y->right;
3041 x->parent = y->parent;
3042 if (y->parent)
3044 if (y == y->parent->left)
3045 y->parent->left = x;
3046 else
3047 y->parent->right = x;
3049 else
3050 mem_root = x;
3052 if (y != z)
3054 z->start = y->start;
3055 z->end = y->end;
3056 z->type = y->type;
3059 if (y->color == MEM_BLACK)
3060 mem_delete_fixup (x);
3062 #ifdef GC_MALLOC_CHECK
3063 _free_internal (y);
3064 #else
3065 xfree (y);
3066 #endif
3070 /* Re-establish the red-black properties of the tree, after a
3071 deletion. */
3073 static void
3074 mem_delete_fixup (x)
3075 struct mem_node *x;
3077 while (x != mem_root && x->color == MEM_BLACK)
3079 if (x == x->parent->left)
3081 struct mem_node *w = x->parent->right;
3083 if (w->color == MEM_RED)
3085 w->color = MEM_BLACK;
3086 x->parent->color = MEM_RED;
3087 mem_rotate_left (x->parent);
3088 w = x->parent->right;
3091 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
3093 w->color = MEM_RED;
3094 x = x->parent;
3096 else
3098 if (w->right->color == MEM_BLACK)
3100 w->left->color = MEM_BLACK;
3101 w->color = MEM_RED;
3102 mem_rotate_right (w);
3103 w = x->parent->right;
3105 w->color = x->parent->color;
3106 x->parent->color = MEM_BLACK;
3107 w->right->color = MEM_BLACK;
3108 mem_rotate_left (x->parent);
3109 x = mem_root;
3112 else
3114 struct mem_node *w = x->parent->left;
3116 if (w->color == MEM_RED)
3118 w->color = MEM_BLACK;
3119 x->parent->color = MEM_RED;
3120 mem_rotate_right (x->parent);
3121 w = x->parent->left;
3124 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
3126 w->color = MEM_RED;
3127 x = x->parent;
3129 else
3131 if (w->left->color == MEM_BLACK)
3133 w->right->color = MEM_BLACK;
3134 w->color = MEM_RED;
3135 mem_rotate_left (w);
3136 w = x->parent->left;
3139 w->color = x->parent->color;
3140 x->parent->color = MEM_BLACK;
3141 w->left->color = MEM_BLACK;
3142 mem_rotate_right (x->parent);
3143 x = mem_root;
3148 x->color = MEM_BLACK;
3152 /* Value is non-zero if P is a pointer to a live Lisp string on
3153 the heap. M is a pointer to the mem_block for P. */
3155 static INLINE int
3156 live_string_p (m, p)
3157 struct mem_node *m;
3158 void *p;
3160 if (m->type == MEM_TYPE_STRING)
3162 struct string_block *b = (struct string_block *) m->start;
3163 int offset = (char *) p - (char *) &b->strings[0];
3165 /* P must point to the start of a Lisp_String structure, and it
3166 must not be on the free-list. */
3167 return (offset >= 0
3168 && offset % sizeof b->strings[0] == 0
3169 && ((struct Lisp_String *) p)->data != NULL);
3171 else
3172 return 0;
3176 /* Value is non-zero if P is a pointer to a live Lisp cons on
3177 the heap. M is a pointer to the mem_block for P. */
3179 static INLINE int
3180 live_cons_p (m, p)
3181 struct mem_node *m;
3182 void *p;
3184 if (m->type == MEM_TYPE_CONS)
3186 struct cons_block *b = (struct cons_block *) m->start;
3187 int offset = (char *) p - (char *) &b->conses[0];
3189 /* P must point to the start of a Lisp_Cons, not be
3190 one of the unused cells in the current cons block,
3191 and not be on the free-list. */
3192 return (offset >= 0
3193 && offset % sizeof b->conses[0] == 0
3194 && (b != cons_block
3195 || offset / sizeof b->conses[0] < cons_block_index)
3196 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
3198 else
3199 return 0;
3203 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3204 the heap. M is a pointer to the mem_block for P. */
3206 static INLINE int
3207 live_symbol_p (m, p)
3208 struct mem_node *m;
3209 void *p;
3211 if (m->type == MEM_TYPE_SYMBOL)
3213 struct symbol_block *b = (struct symbol_block *) m->start;
3214 int offset = (char *) p - (char *) &b->symbols[0];
3216 /* P must point to the start of a Lisp_Symbol, not be
3217 one of the unused cells in the current symbol block,
3218 and not be on the free-list. */
3219 return (offset >= 0
3220 && offset % sizeof b->symbols[0] == 0
3221 && (b != symbol_block
3222 || offset / sizeof b->symbols[0] < symbol_block_index)
3223 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
3225 else
3226 return 0;
3230 /* Value is non-zero if P is a pointer to a live Lisp float on
3231 the heap. M is a pointer to the mem_block for P. */
3233 static INLINE int
3234 live_float_p (m, p)
3235 struct mem_node *m;
3236 void *p;
3238 if (m->type == MEM_TYPE_FLOAT)
3240 struct float_block *b = (struct float_block *) m->start;
3241 int offset = (char *) p - (char *) &b->floats[0];
3243 /* P must point to the start of a Lisp_Float, not be
3244 one of the unused cells in the current float block,
3245 and not be on the free-list. */
3246 return (offset >= 0
3247 && offset % sizeof b->floats[0] == 0
3248 && (b != float_block
3249 || offset / sizeof b->floats[0] < float_block_index)
3250 && !EQ (((struct Lisp_Float *) p)->type, Vdead));
3252 else
3253 return 0;
3257 /* Value is non-zero if P is a pointer to a live Lisp Misc on
3258 the heap. M is a pointer to the mem_block for P. */
3260 static INLINE int
3261 live_misc_p (m, p)
3262 struct mem_node *m;
3263 void *p;
3265 if (m->type == MEM_TYPE_MISC)
3267 struct marker_block *b = (struct marker_block *) m->start;
3268 int offset = (char *) p - (char *) &b->markers[0];
3270 /* P must point to the start of a Lisp_Misc, not be
3271 one of the unused cells in the current misc block,
3272 and not be on the free-list. */
3273 return (offset >= 0
3274 && offset % sizeof b->markers[0] == 0
3275 && (b != marker_block
3276 || offset / sizeof b->markers[0] < marker_block_index)
3277 && ((union Lisp_Misc *) p)->u_marker.type != Lisp_Misc_Free);
3279 else
3280 return 0;
3284 /* Value is non-zero if P is a pointer to a live vector-like object.
3285 M is a pointer to the mem_block for P. */
3287 static INLINE int
3288 live_vector_p (m, p)
3289 struct mem_node *m;
3290 void *p;
3292 return (p == m->start
3293 && m->type >= MEM_TYPE_VECTOR
3294 && m->type <= MEM_TYPE_WINDOW);
3298 /* Value is non-zero if P is a pointer to a live buffer. M is a
3299 pointer to the mem_block for P. */
3301 static INLINE int
3302 live_buffer_p (m, p)
3303 struct mem_node *m;
3304 void *p;
3306 /* P must point to the start of the block, and the buffer
3307 must not have been killed. */
3308 return (m->type == MEM_TYPE_BUFFER
3309 && p == m->start
3310 && !NILP (((struct buffer *) p)->name));
3313 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
3315 #if GC_MARK_STACK
3317 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3319 /* Array of objects that are kept alive because the C stack contains
3320 a pattern that looks like a reference to them . */
3322 #define MAX_ZOMBIES 10
3323 static Lisp_Object zombies[MAX_ZOMBIES];
3325 /* Number of zombie objects. */
3327 static int nzombies;
3329 /* Number of garbage collections. */
3331 static int ngcs;
3333 /* Average percentage of zombies per collection. */
3335 static double avg_zombies;
3337 /* Max. number of live and zombie objects. */
3339 static int max_live, max_zombies;
3341 /* Average number of live objects per GC. */
3343 static double avg_live;
3345 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
3346 doc: /* Show information about live and zombie objects. */)
3349 Lisp_Object args[8], zombie_list = Qnil;
3350 int i;
3351 for (i = 0; i < nzombies; i++)
3352 zombie_list = Fcons (zombies[i], zombie_list);
3353 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
3354 args[1] = make_number (ngcs);
3355 args[2] = make_float (avg_live);
3356 args[3] = make_float (avg_zombies);
3357 args[4] = make_float (avg_zombies / avg_live / 100);
3358 args[5] = make_number (max_live);
3359 args[6] = make_number (max_zombies);
3360 args[7] = zombie_list;
3361 return Fmessage (8, args);
3364 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3367 /* Mark OBJ if we can prove it's a Lisp_Object. */
3369 static INLINE void
3370 mark_maybe_object (obj)
3371 Lisp_Object obj;
3373 void *po = (void *) XPNTR (obj);
3374 struct mem_node *m = mem_find (po);
3376 if (m != MEM_NIL)
3378 int mark_p = 0;
3380 switch (XGCTYPE (obj))
3382 case Lisp_String:
3383 mark_p = (live_string_p (m, po)
3384 && !STRING_MARKED_P ((struct Lisp_String *) po));
3385 break;
3387 case Lisp_Cons:
3388 mark_p = (live_cons_p (m, po)
3389 && !XMARKBIT (XCONS (obj)->car));
3390 break;
3392 case Lisp_Symbol:
3393 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
3394 break;
3396 case Lisp_Float:
3397 mark_p = (live_float_p (m, po)
3398 && !XMARKBIT (XFLOAT (obj)->type));
3399 break;
3401 case Lisp_Vectorlike:
3402 /* Note: can't check GC_BUFFERP before we know it's a
3403 buffer because checking that dereferences the pointer
3404 PO which might point anywhere. */
3405 if (live_vector_p (m, po))
3406 mark_p = !GC_SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
3407 else if (live_buffer_p (m, po))
3408 mark_p = GC_BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
3409 break;
3411 case Lisp_Misc:
3412 mark_p = (live_misc_p (m, po) && !XMARKER (obj)->gcmarkbit);
3413 break;
3415 case Lisp_Int:
3416 case Lisp_Type_Limit:
3417 break;
3420 if (mark_p)
3422 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3423 if (nzombies < MAX_ZOMBIES)
3424 zombies[nzombies] = obj;
3425 ++nzombies;
3426 #endif
3427 mark_object (&obj);
3433 /* If P points to Lisp data, mark that as live if it isn't already
3434 marked. */
3436 static INLINE void
3437 mark_maybe_pointer (p)
3438 void *p;
3440 struct mem_node *m;
3442 /* Quickly rule out some values which can't point to Lisp data. We
3443 assume that Lisp data is aligned on even addresses. */
3444 if ((EMACS_INT) p & 1)
3445 return;
3447 m = mem_find (p);
3448 if (m != MEM_NIL)
3450 Lisp_Object obj = Qnil;
3452 switch (m->type)
3454 case MEM_TYPE_NON_LISP:
3455 /* Nothing to do; not a pointer to Lisp memory. */
3456 break;
3458 case MEM_TYPE_BUFFER:
3459 if (live_buffer_p (m, p) && !VECTOR_MARKED_P((struct buffer *)p))
3460 XSETVECTOR (obj, p);
3461 break;
3463 case MEM_TYPE_CONS:
3464 if (live_cons_p (m, p)
3465 && !XMARKBIT (((struct Lisp_Cons *) p)->car))
3466 XSETCONS (obj, p);
3467 break;
3469 case MEM_TYPE_STRING:
3470 if (live_string_p (m, p)
3471 && !STRING_MARKED_P ((struct Lisp_String *) p))
3472 XSETSTRING (obj, p);
3473 break;
3475 case MEM_TYPE_MISC:
3476 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
3477 XSETMISC (obj, p);
3478 break;
3480 case MEM_TYPE_SYMBOL:
3481 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
3482 XSETSYMBOL (obj, p);
3483 break;
3485 case MEM_TYPE_FLOAT:
3486 if (live_float_p (m, p)
3487 && !XMARKBIT (((struct Lisp_Float *) p)->type))
3488 XSETFLOAT (obj, p);
3489 break;
3491 case MEM_TYPE_VECTOR:
3492 case MEM_TYPE_PROCESS:
3493 case MEM_TYPE_HASH_TABLE:
3494 case MEM_TYPE_FRAME:
3495 case MEM_TYPE_WINDOW:
3496 if (live_vector_p (m, p))
3498 Lisp_Object tem;
3499 XSETVECTOR (tem, p);
3500 if (!GC_SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
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 VECTOR_UNMARK (&buffer_defaults);
4290 VECTOR_UNMARK (&buffer_local_symbols);
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 (!VECTOR_MARKED_P (XBUFFER (obj)))
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 (VECTOR_MARKED_P (ptr))
4578 break; /* Already marked */
4580 CHECK_LIVE (live_vector_p);
4581 VECTOR_MARK (ptr); /* 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);
4597 if (VECTOR_MARKED_P (ptr)) break; /* Already marked */
4598 VECTOR_MARK (ptr); /* Else mark it */
4600 CHECK_LIVE (live_vector_p);
4601 mark_object (&ptr->name);
4602 mark_object (&ptr->icon_name);
4603 mark_object (&ptr->title);
4604 mark_object (&ptr->focus_frame);
4605 mark_object (&ptr->selected_window);
4606 mark_object (&ptr->minibuffer_window);
4607 mark_object (&ptr->param_alist);
4608 mark_object (&ptr->scroll_bars);
4609 mark_object (&ptr->condemned_scroll_bars);
4610 mark_object (&ptr->menu_bar_items);
4611 mark_object (&ptr->face_alist);
4612 mark_object (&ptr->menu_bar_vector);
4613 mark_object (&ptr->buffer_predicate);
4614 mark_object (&ptr->buffer_list);
4615 mark_object (&ptr->menu_bar_window);
4616 mark_object (&ptr->tool_bar_window);
4617 mark_face_cache (ptr->face_cache);
4618 #ifdef HAVE_WINDOW_SYSTEM
4619 mark_image_cache (ptr);
4620 mark_object (&ptr->tool_bar_items);
4621 mark_object (&ptr->desired_tool_bar_string);
4622 mark_object (&ptr->current_tool_bar_string);
4623 #endif /* HAVE_WINDOW_SYSTEM */
4625 else if (GC_BOOL_VECTOR_P (obj))
4627 register struct Lisp_Vector *ptr = XVECTOR (obj);
4629 if (VECTOR_MARKED_P (ptr))
4630 break; /* Already marked */
4631 CHECK_LIVE (live_vector_p);
4632 VECTOR_MARK (ptr); /* Else mark it */
4634 else if (GC_WINDOWP (obj))
4636 register struct Lisp_Vector *ptr = XVECTOR (obj);
4637 struct window *w = XWINDOW (obj);
4638 register int i;
4640 /* Stop if already marked. */
4641 if (VECTOR_MARKED_P (ptr))
4642 break;
4644 /* Mark it. */
4645 CHECK_LIVE (live_vector_p);
4646 VECTOR_MARK (ptr);
4648 /* There is no Lisp data above The member CURRENT_MATRIX in
4649 struct WINDOW. Stop marking when that slot is reached. */
4650 for (i = 0;
4651 (char *) &ptr->contents[i] < (char *) &w->current_matrix;
4652 i++)
4653 mark_object (&ptr->contents[i]);
4655 /* Mark glyphs for leaf windows. Marking window matrices is
4656 sufficient because frame matrices use the same glyph
4657 memory. */
4658 if (NILP (w->hchild)
4659 && NILP (w->vchild)
4660 && w->current_matrix)
4662 mark_glyph_matrix (w->current_matrix);
4663 mark_glyph_matrix (w->desired_matrix);
4666 else if (GC_HASH_TABLE_P (obj))
4668 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
4670 /* Stop if already marked. */
4671 if (VECTOR_MARKED_P (h))
4672 break;
4674 /* Mark it. */
4675 CHECK_LIVE (live_vector_p);
4676 VECTOR_MARK (h);
4678 /* Mark contents. */
4679 /* Do not mark next_free or next_weak.
4680 Being in the next_weak chain
4681 should not keep the hash table alive.
4682 No need to mark `count' since it is an integer. */
4683 mark_object (&h->test);
4684 mark_object (&h->weak);
4685 mark_object (&h->rehash_size);
4686 mark_object (&h->rehash_threshold);
4687 mark_object (&h->hash);
4688 mark_object (&h->next);
4689 mark_object (&h->index);
4690 mark_object (&h->user_hash_function);
4691 mark_object (&h->user_cmp_function);
4693 /* If hash table is not weak, mark all keys and values.
4694 For weak tables, mark only the vector. */
4695 if (GC_NILP (h->weak))
4696 mark_object (&h->key_and_value);
4697 else
4698 VECTOR_MARK (XVECTOR (h->key_and_value));
4700 else
4702 register struct Lisp_Vector *ptr = XVECTOR (obj);
4703 register EMACS_INT size = ptr->size;
4704 register int i;
4706 if (VECTOR_MARKED_P (ptr)) break; /* Already marked */
4707 CHECK_LIVE (live_vector_p);
4708 VECTOR_MARK (ptr); /* Else mark it */
4709 if (size & PSEUDOVECTOR_FLAG)
4710 size &= PSEUDOVECTOR_SIZE_MASK;
4712 for (i = 0; i < size; i++) /* and then mark its elements */
4713 mark_object (&ptr->contents[i]);
4715 break;
4717 case Lisp_Symbol:
4719 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
4720 struct Lisp_Symbol *ptrx;
4722 if (ptr->gcmarkbit) break;
4723 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
4724 ptr->gcmarkbit = 1;
4725 mark_object ((Lisp_Object *) &ptr->value);
4726 mark_object (&ptr->function);
4727 mark_object (&ptr->plist);
4729 if (!PURE_POINTER_P (XSTRING (ptr->xname)))
4730 MARK_STRING (XSTRING (ptr->xname));
4731 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr->xname));
4733 /* Note that we do not mark the obarray of the symbol.
4734 It is safe not to do so because nothing accesses that
4735 slot except to check whether it is nil. */
4736 ptr = ptr->next;
4737 if (ptr)
4739 /* For the benefit of the last_marked log. */
4740 objptr = (Lisp_Object *)&XSYMBOL (obj)->next;
4741 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
4742 XSETSYMBOL (obj, ptrx);
4743 /* We can't goto loop here because *objptr doesn't contain an
4744 actual Lisp_Object with valid datatype field. */
4745 goto loop2;
4748 break;
4750 case Lisp_Misc:
4751 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
4752 if (XMARKER (obj)->gcmarkbit)
4753 break;
4754 XMARKER (obj)->gcmarkbit = 1;
4755 switch (XMISCTYPE (obj))
4757 case Lisp_Misc_Buffer_Local_Value:
4758 case Lisp_Misc_Some_Buffer_Local_Value:
4760 register struct Lisp_Buffer_Local_Value *ptr
4761 = XBUFFER_LOCAL_VALUE (obj);
4762 /* If the cdr is nil, avoid recursion for the car. */
4763 if (EQ (ptr->cdr, Qnil))
4765 objptr = &ptr->realvalue;
4766 goto loop;
4768 mark_object (&ptr->realvalue);
4769 mark_object (&ptr->buffer);
4770 mark_object (&ptr->frame);
4771 objptr = &ptr->cdr;
4772 goto loop;
4775 case Lisp_Misc_Marker:
4776 /* DO NOT mark thru the marker's chain.
4777 The buffer's markers chain does not preserve markers from gc;
4778 instead, markers are removed from the chain when freed by gc. */
4779 case Lisp_Misc_Intfwd:
4780 case Lisp_Misc_Boolfwd:
4781 case Lisp_Misc_Objfwd:
4782 case Lisp_Misc_Buffer_Objfwd:
4783 case Lisp_Misc_Kboard_Objfwd:
4784 /* Don't bother with Lisp_Buffer_Objfwd,
4785 since all markable slots in current buffer marked anyway. */
4786 /* Don't need to do Lisp_Objfwd, since the places they point
4787 are protected with staticpro. */
4788 break;
4790 case Lisp_Misc_Overlay:
4792 struct Lisp_Overlay *ptr = XOVERLAY (obj);
4793 mark_object (&ptr->start);
4794 mark_object (&ptr->end);
4795 objptr = &ptr->plist;
4796 goto loop;
4798 break;
4800 default:
4801 abort ();
4803 break;
4805 case Lisp_Cons:
4807 register struct Lisp_Cons *ptr = XCONS (obj);
4808 if (XMARKBIT (ptr->car)) break;
4809 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
4810 XMARK (ptr->car);
4811 /* If the cdr is nil, avoid recursion for the car. */
4812 if (EQ (ptr->cdr, Qnil))
4814 objptr = &ptr->car;
4815 cdr_count = 0;
4816 goto loop;
4818 mark_object (&ptr->car);
4819 objptr = &ptr->cdr;
4820 cdr_count++;
4821 if (cdr_count == mark_object_loop_halt)
4822 abort ();
4823 goto loop;
4826 case Lisp_Float:
4827 CHECK_ALLOCATED_AND_LIVE (live_float_p);
4828 XMARK (XFLOAT (obj)->type);
4829 break;
4831 case Lisp_Int:
4832 break;
4834 default:
4835 abort ();
4838 #undef CHECK_LIVE
4839 #undef CHECK_ALLOCATED
4840 #undef CHECK_ALLOCATED_AND_LIVE
4843 /* Mark the pointers in a buffer structure. */
4845 static void
4846 mark_buffer (buf)
4847 Lisp_Object buf;
4849 register struct buffer *buffer = XBUFFER (buf);
4850 register Lisp_Object *ptr;
4851 Lisp_Object base_buffer;
4853 VECTOR_MARK (buffer);
4855 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
4857 if (CONSP (buffer->undo_list))
4859 Lisp_Object tail;
4860 tail = buffer->undo_list;
4862 /* We mark the undo list specially because
4863 its pointers to markers should be weak. */
4865 while (CONSP (tail))
4867 register struct Lisp_Cons *ptr = XCONS (tail);
4869 if (XMARKBIT (ptr->car))
4870 break;
4871 XMARK (ptr->car);
4872 if (GC_CONSP (ptr->car)
4873 && ! XMARKBIT (XCAR (ptr->car))
4874 && GC_MARKERP (XCAR (ptr->car)))
4876 XMARK (XCAR_AS_LVALUE (ptr->car));
4877 mark_object (&XCDR_AS_LVALUE (ptr->car));
4879 else
4880 mark_object (&ptr->car);
4882 if (CONSP (ptr->cdr))
4883 tail = ptr->cdr;
4884 else
4885 break;
4888 mark_object (&XCDR_AS_LVALUE (tail));
4890 else
4891 mark_object (&buffer->undo_list);
4893 for (ptr = &buffer->name;
4894 (char *)ptr < (char *)buffer + sizeof (struct buffer);
4895 ptr++)
4896 mark_object (ptr);
4898 /* If this is an indirect buffer, mark its base buffer. */
4899 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
4901 XSETBUFFER (base_buffer, buffer->base_buffer);
4902 mark_buffer (base_buffer);
4907 /* Value is non-zero if OBJ will survive the current GC because it's
4908 either marked or does not need to be marked to survive. */
4911 survives_gc_p (obj)
4912 Lisp_Object obj;
4914 int survives_p;
4916 switch (XGCTYPE (obj))
4918 case Lisp_Int:
4919 survives_p = 1;
4920 break;
4922 case Lisp_Symbol:
4923 survives_p = XSYMBOL (obj)->gcmarkbit;
4924 break;
4926 case Lisp_Misc:
4927 survives_p = XMARKER (obj)->gcmarkbit;
4928 break;
4930 case Lisp_String:
4932 struct Lisp_String *s = XSTRING (obj);
4933 survives_p = STRING_MARKED_P (s);
4935 break;
4937 case Lisp_Vectorlike:
4938 if (GC_BUFFERP (obj))
4939 survives_p = VECTOR_MARKED_P (XBUFFER (obj));
4940 else if (GC_SUBRP (obj))
4941 survives_p = 1;
4942 else
4943 survives_p = VECTOR_MARKED_P (XVECTOR (obj));
4944 break;
4946 case Lisp_Cons:
4947 survives_p = XMARKBIT (XCAR (obj));
4948 break;
4950 case Lisp_Float:
4951 survives_p = XMARKBIT (XFLOAT (obj)->type);
4952 break;
4954 default:
4955 abort ();
4958 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
4963 /* Sweep: find all structures not marked, and free them. */
4965 static void
4966 gc_sweep ()
4968 /* Remove or mark entries in weak hash tables.
4969 This must be done before any object is unmarked. */
4970 sweep_weak_hash_tables ();
4972 sweep_strings ();
4973 #ifdef GC_CHECK_STRING_BYTES
4974 if (!noninteractive)
4975 check_string_bytes (1);
4976 #endif
4978 /* Put all unmarked conses on free list */
4980 register struct cons_block *cblk;
4981 struct cons_block **cprev = &cons_block;
4982 register int lim = cons_block_index;
4983 register int num_free = 0, num_used = 0;
4985 cons_free_list = 0;
4987 for (cblk = cons_block; cblk; cblk = *cprev)
4989 register int i;
4990 int this_free = 0;
4991 for (i = 0; i < lim; i++)
4992 if (!XMARKBIT (cblk->conses[i].car))
4994 this_free++;
4995 *(struct Lisp_Cons **)&cblk->conses[i].cdr = cons_free_list;
4996 cons_free_list = &cblk->conses[i];
4997 #if GC_MARK_STACK
4998 cons_free_list->car = Vdead;
4999 #endif
5001 else
5003 num_used++;
5004 XUNMARK (cblk->conses[i].car);
5006 lim = CONS_BLOCK_SIZE;
5007 /* If this block contains only free conses and we have already
5008 seen more than two blocks worth of free conses then deallocate
5009 this block. */
5010 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
5012 *cprev = cblk->next;
5013 /* Unhook from the free list. */
5014 cons_free_list = *(struct Lisp_Cons **) &cblk->conses[0].cdr;
5015 lisp_free (cblk);
5016 n_cons_blocks--;
5018 else
5020 num_free += this_free;
5021 cprev = &cblk->next;
5024 total_conses = num_used;
5025 total_free_conses = num_free;
5028 /* Put all unmarked floats on free list */
5030 register struct float_block *fblk;
5031 struct float_block **fprev = &float_block;
5032 register int lim = float_block_index;
5033 register int num_free = 0, num_used = 0;
5035 float_free_list = 0;
5037 for (fblk = float_block; fblk; fblk = *fprev)
5039 register int i;
5040 int this_free = 0;
5041 for (i = 0; i < lim; i++)
5042 if (!XMARKBIT (fblk->floats[i].type))
5044 this_free++;
5045 *(struct Lisp_Float **)&fblk->floats[i].data = float_free_list;
5046 float_free_list = &fblk->floats[i];
5047 #if GC_MARK_STACK
5048 float_free_list->type = Vdead;
5049 #endif
5051 else
5053 num_used++;
5054 XUNMARK (fblk->floats[i].type);
5056 lim = FLOAT_BLOCK_SIZE;
5057 /* If this block contains only free floats and we have already
5058 seen more than two blocks worth of free floats then deallocate
5059 this block. */
5060 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
5062 *fprev = fblk->next;
5063 /* Unhook from the free list. */
5064 float_free_list = *(struct Lisp_Float **) &fblk->floats[0].data;
5065 lisp_free (fblk);
5066 n_float_blocks--;
5068 else
5070 num_free += this_free;
5071 fprev = &fblk->next;
5074 total_floats = num_used;
5075 total_free_floats = num_free;
5078 /* Put all unmarked intervals on free list */
5080 register struct interval_block *iblk;
5081 struct interval_block **iprev = &interval_block;
5082 register int lim = interval_block_index;
5083 register int num_free = 0, num_used = 0;
5085 interval_free_list = 0;
5087 for (iblk = interval_block; iblk; iblk = *iprev)
5089 register int i;
5090 int this_free = 0;
5092 for (i = 0; i < lim; i++)
5094 if (!iblk->intervals[i].gcmarkbit)
5096 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
5097 interval_free_list = &iblk->intervals[i];
5098 this_free++;
5100 else
5102 num_used++;
5103 iblk->intervals[i].gcmarkbit = 0;
5106 lim = INTERVAL_BLOCK_SIZE;
5107 /* If this block contains only free intervals and we have already
5108 seen more than two blocks worth of free intervals then
5109 deallocate this block. */
5110 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
5112 *iprev = iblk->next;
5113 /* Unhook from the free list. */
5114 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
5115 lisp_free (iblk);
5116 n_interval_blocks--;
5118 else
5120 num_free += this_free;
5121 iprev = &iblk->next;
5124 total_intervals = num_used;
5125 total_free_intervals = num_free;
5128 /* Put all unmarked symbols on free list */
5130 register struct symbol_block *sblk;
5131 struct symbol_block **sprev = &symbol_block;
5132 register int lim = symbol_block_index;
5133 register int num_free = 0, num_used = 0;
5135 symbol_free_list = NULL;
5137 for (sblk = symbol_block; sblk; sblk = *sprev)
5139 int this_free = 0;
5140 struct Lisp_Symbol *sym = sblk->symbols;
5141 struct Lisp_Symbol *end = sym + lim;
5143 for (; sym < end; ++sym)
5145 /* Check if the symbol was created during loadup. In such a case
5146 it might be pointed to by pure bytecode which we don't trace,
5147 so we conservatively assume that it is live. */
5148 int pure_p = PURE_POINTER_P (XSTRING (sym->xname));
5150 if (!sym->gcmarkbit && !pure_p)
5152 *(struct Lisp_Symbol **) &sym->value = symbol_free_list;
5153 symbol_free_list = sym;
5154 #if GC_MARK_STACK
5155 symbol_free_list->function = Vdead;
5156 #endif
5157 ++this_free;
5159 else
5161 ++num_used;
5162 if (!pure_p)
5163 UNMARK_STRING (XSTRING (sym->xname));
5164 sym->gcmarkbit = 0;
5168 lim = SYMBOL_BLOCK_SIZE;
5169 /* If this block contains only free symbols and we have already
5170 seen more than two blocks worth of free symbols then deallocate
5171 this block. */
5172 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
5174 *sprev = sblk->next;
5175 /* Unhook from the free list. */
5176 symbol_free_list = *(struct Lisp_Symbol **)&sblk->symbols[0].value;
5177 lisp_free (sblk);
5178 n_symbol_blocks--;
5180 else
5182 num_free += this_free;
5183 sprev = &sblk->next;
5186 total_symbols = num_used;
5187 total_free_symbols = num_free;
5190 /* Put all unmarked misc's on free list.
5191 For a marker, first unchain it from the buffer it points into. */
5193 register struct marker_block *mblk;
5194 struct marker_block **mprev = &marker_block;
5195 register int lim = marker_block_index;
5196 register int num_free = 0, num_used = 0;
5198 marker_free_list = 0;
5200 for (mblk = marker_block; mblk; mblk = *mprev)
5202 register int i;
5203 int this_free = 0;
5205 for (i = 0; i < lim; i++)
5207 if (!mblk->markers[i].u_marker.gcmarkbit)
5209 if (mblk->markers[i].u_marker.type == Lisp_Misc_Marker)
5210 unchain_marker (&mblk->markers[i].u_marker);
5211 /* Set the type of the freed object to Lisp_Misc_Free.
5212 We could leave the type alone, since nobody checks it,
5213 but this might catch bugs faster. */
5214 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
5215 mblk->markers[i].u_free.chain = marker_free_list;
5216 marker_free_list = &mblk->markers[i];
5217 this_free++;
5219 else
5221 num_used++;
5222 mblk->markers[i].u_marker.gcmarkbit = 0;
5225 lim = MARKER_BLOCK_SIZE;
5226 /* If this block contains only free markers and we have already
5227 seen more than two blocks worth of free markers then deallocate
5228 this block. */
5229 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
5231 *mprev = mblk->next;
5232 /* Unhook from the free list. */
5233 marker_free_list = mblk->markers[0].u_free.chain;
5234 lisp_free (mblk);
5235 n_marker_blocks--;
5237 else
5239 num_free += this_free;
5240 mprev = &mblk->next;
5244 total_markers = num_used;
5245 total_free_markers = num_free;
5248 /* Free all unmarked buffers */
5250 register struct buffer *buffer = all_buffers, *prev = 0, *next;
5252 while (buffer)
5253 if (!VECTOR_MARKED_P (buffer))
5255 if (prev)
5256 prev->next = buffer->next;
5257 else
5258 all_buffers = buffer->next;
5259 next = buffer->next;
5260 lisp_free (buffer);
5261 buffer = next;
5263 else
5265 VECTOR_UNMARK (buffer);
5266 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
5267 prev = buffer, buffer = buffer->next;
5271 /* Free all unmarked vectors */
5273 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
5274 total_vector_size = 0;
5276 while (vector)
5277 if (!VECTOR_MARKED_P (vector))
5279 if (prev)
5280 prev->next = vector->next;
5281 else
5282 all_vectors = vector->next;
5283 next = vector->next;
5284 lisp_free (vector);
5285 n_vectors--;
5286 vector = next;
5289 else
5291 VECTOR_UNMARK (vector);
5292 if (vector->size & PSEUDOVECTOR_FLAG)
5293 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
5294 else
5295 total_vector_size += vector->size;
5296 prev = vector, vector = vector->next;
5300 #ifdef GC_CHECK_STRING_BYTES
5301 if (!noninteractive)
5302 check_string_bytes (1);
5303 #endif
5309 /* Debugging aids. */
5311 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
5312 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
5313 This may be helpful in debugging Emacs's memory usage.
5314 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
5317 Lisp_Object end;
5319 XSETINT (end, (EMACS_INT) sbrk (0) / 1024);
5321 return end;
5324 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
5325 doc: /* Return a list of counters that measure how much consing there has been.
5326 Each of these counters increments for a certain kind of object.
5327 The counters wrap around from the largest positive integer to zero.
5328 Garbage collection does not decrease them.
5329 The elements of the value are as follows:
5330 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
5331 All are in units of 1 = one object consed
5332 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
5333 objects consed.
5334 MISCS include overlays, markers, and some internal types.
5335 Frames, windows, buffers, and subprocesses count as vectors
5336 (but the contents of a buffer's text do not count here). */)
5339 Lisp_Object consed[8];
5341 consed[0] = make_number (min (MOST_POSITIVE_FIXNUM, cons_cells_consed));
5342 consed[1] = make_number (min (MOST_POSITIVE_FIXNUM, floats_consed));
5343 consed[2] = make_number (min (MOST_POSITIVE_FIXNUM, vector_cells_consed));
5344 consed[3] = make_number (min (MOST_POSITIVE_FIXNUM, symbols_consed));
5345 consed[4] = make_number (min (MOST_POSITIVE_FIXNUM, string_chars_consed));
5346 consed[5] = make_number (min (MOST_POSITIVE_FIXNUM, misc_objects_consed));
5347 consed[6] = make_number (min (MOST_POSITIVE_FIXNUM, intervals_consed));
5348 consed[7] = make_number (min (MOST_POSITIVE_FIXNUM, strings_consed));
5350 return Flist (8, consed);
5353 int suppress_checking;
5354 void
5355 die (msg, file, line)
5356 const char *msg;
5357 const char *file;
5358 int line;
5360 fprintf (stderr, "\r\nEmacs fatal error: %s:%d: %s\r\n",
5361 file, line, msg);
5362 abort ();
5365 /* Initialization */
5367 void
5368 init_alloc_once ()
5370 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
5371 purebeg = PUREBEG;
5372 pure_size = PURESIZE;
5373 pure_bytes_used = 0;
5374 pure_bytes_used_before_overflow = 0;
5376 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
5377 mem_init ();
5378 Vdead = make_pure_string ("DEAD", 4, 4, 0);
5379 #endif
5381 all_vectors = 0;
5382 ignore_warnings = 1;
5383 #ifdef DOUG_LEA_MALLOC
5384 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
5385 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
5386 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
5387 #endif
5388 init_strings ();
5389 init_cons ();
5390 init_symbol ();
5391 init_marker ();
5392 init_float ();
5393 init_intervals ();
5395 #ifdef REL_ALLOC
5396 malloc_hysteresis = 32;
5397 #else
5398 malloc_hysteresis = 0;
5399 #endif
5401 spare_memory = (char *) malloc (SPARE_MEMORY);
5403 ignore_warnings = 0;
5404 gcprolist = 0;
5405 byte_stack_list = 0;
5406 staticidx = 0;
5407 consing_since_gc = 0;
5408 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
5409 #ifdef VIRT_ADDR_VARIES
5410 malloc_sbrk_unused = 1<<22; /* A large number */
5411 malloc_sbrk_used = 100000; /* as reasonable as any number */
5412 #endif /* VIRT_ADDR_VARIES */
5415 void
5416 init_alloc ()
5418 gcprolist = 0;
5419 byte_stack_list = 0;
5420 #if GC_MARK_STACK
5421 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
5422 setjmp_tested_p = longjmps_done = 0;
5423 #endif
5424 #endif
5425 Vgc_elapsed = make_float (0.0);
5426 gcs_done = 0;
5429 void
5430 syms_of_alloc ()
5432 DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold,
5433 doc: /* *Number of bytes of consing between garbage collections.
5434 Garbage collection can happen automatically once this many bytes have been
5435 allocated since the last garbage collection. All data types count.
5437 Garbage collection happens automatically only when `eval' is called.
5439 By binding this temporarily to a large number, you can effectively
5440 prevent garbage collection during a part of the program. */);
5442 DEFVAR_INT ("pure-bytes-used", &pure_bytes_used,
5443 doc: /* Number of bytes of sharable Lisp data allocated so far. */);
5445 DEFVAR_INT ("cons-cells-consed", &cons_cells_consed,
5446 doc: /* Number of cons cells that have been consed so far. */);
5448 DEFVAR_INT ("floats-consed", &floats_consed,
5449 doc: /* Number of floats that have been consed so far. */);
5451 DEFVAR_INT ("vector-cells-consed", &vector_cells_consed,
5452 doc: /* Number of vector cells that have been consed so far. */);
5454 DEFVAR_INT ("symbols-consed", &symbols_consed,
5455 doc: /* Number of symbols that have been consed so far. */);
5457 DEFVAR_INT ("string-chars-consed", &string_chars_consed,
5458 doc: /* Number of string characters that have been consed so far. */);
5460 DEFVAR_INT ("misc-objects-consed", &misc_objects_consed,
5461 doc: /* Number of miscellaneous objects that have been consed so far. */);
5463 DEFVAR_INT ("intervals-consed", &intervals_consed,
5464 doc: /* Number of intervals that have been consed so far. */);
5466 DEFVAR_INT ("strings-consed", &strings_consed,
5467 doc: /* Number of strings that have been consed so far. */);
5469 DEFVAR_LISP ("purify-flag", &Vpurify_flag,
5470 doc: /* Non-nil means loading Lisp code in order to dump an executable.
5471 This means that certain objects should be allocated in shared (pure) space. */);
5473 DEFVAR_INT ("undo-limit", &undo_limit,
5474 doc: /* Keep no more undo information once it exceeds this size.
5475 This limit is applied when garbage collection happens.
5476 The size is counted as the number of bytes occupied,
5477 which includes both saved text and other data. */);
5478 undo_limit = 20000;
5480 DEFVAR_INT ("undo-strong-limit", &undo_strong_limit,
5481 doc: /* Don't keep more than this much size of undo information.
5482 A command which pushes past this size is itself forgotten.
5483 This limit is applied when garbage collection happens.
5484 The size is counted as the number of bytes occupied,
5485 which includes both saved text and other data. */);
5486 undo_strong_limit = 30000;
5488 DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
5489 doc: /* Non-nil means display messages at start and end of garbage collection. */);
5490 garbage_collection_messages = 0;
5492 DEFVAR_LISP ("post-gc-hook", &Vpost_gc_hook,
5493 doc: /* Hook run after garbage collection has finished. */);
5494 Vpost_gc_hook = Qnil;
5495 Qpost_gc_hook = intern ("post-gc-hook");
5496 staticpro (&Qpost_gc_hook);
5498 DEFVAR_LISP ("memory-signal-data", &Vmemory_signal_data,
5499 doc: /* Precomputed `signal' argument for memory-full error. */);
5500 /* We build this in advance because if we wait until we need it, we might
5501 not be able to allocate the memory to hold it. */
5502 Vmemory_signal_data
5503 = list2 (Qerror,
5504 build_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
5506 DEFVAR_LISP ("memory-full", &Vmemory_full,
5507 doc: /* Non-nil means we are handling a memory-full error. */);
5508 Vmemory_full = Qnil;
5510 staticpro (&Qgc_cons_threshold);
5511 Qgc_cons_threshold = intern ("gc-cons-threshold");
5513 staticpro (&Qchar_table_extra_slots);
5514 Qchar_table_extra_slots = intern ("char-table-extra-slots");
5516 DEFVAR_LISP ("gc-elapsed", &Vgc_elapsed,
5517 doc: /* Accumulated time elapsed in garbage collections.
5518 The time is in seconds as a floating point value.
5519 Programs may reset this to get statistics in a specific period. */);
5520 DEFVAR_INT ("gcs-done", &gcs_done,
5521 doc: /* Accumulated number of garbage collections done.
5522 Programs may reset this to get statistics in a specific period. */);
5524 defsubr (&Scons);
5525 defsubr (&Slist);
5526 defsubr (&Svector);
5527 defsubr (&Smake_byte_code);
5528 defsubr (&Smake_list);
5529 defsubr (&Smake_vector);
5530 defsubr (&Smake_char_table);
5531 defsubr (&Smake_string);
5532 defsubr (&Smake_bool_vector);
5533 defsubr (&Smake_symbol);
5534 defsubr (&Smake_marker);
5535 defsubr (&Spurecopy);
5536 defsubr (&Sgarbage_collect);
5537 defsubr (&Smemory_limit);
5538 defsubr (&Smemory_use_counts);
5540 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5541 defsubr (&Sgc_status);
5542 #endif