Change description of cus-test.el.
[emacs.git] / src / alloc.c
blob728c5f9557282152c0e52fbd9c62981270f5e22f
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
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 /* Macro to verify that storage intended for Lisp objects is not
88 out of range to fit in the space for a pointer.
89 ADDRESS is the start of the block, and SIZE
90 is the amount of space within which objects can start. */
92 #define VALIDATE_LISP_STORAGE(address, size) \
93 do \
94 { \
95 Lisp_Object val; \
96 XSETCONS (val, (char *) address + size); \
97 if ((char *) XCONS (val) != (char *) address + size) \
98 { \
99 xfree (address); \
100 memory_full (); \
102 } while (0)
104 /* Value of _bytes_used, when spare_memory was freed. */
106 static __malloc_size_t bytes_used_when_full;
108 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
109 to a struct Lisp_String. */
111 #define MARK_STRING(S) ((S)->size |= MARKBIT)
112 #define UNMARK_STRING(S) ((S)->size &= ~MARKBIT)
113 #define STRING_MARKED_P(S) ((S)->size & MARKBIT)
115 /* Value is the number of bytes/chars of S, a pointer to a struct
116 Lisp_String. This must be used instead of STRING_BYTES (S) or
117 S->size during GC, because S->size contains the mark bit for
118 strings. */
120 #define GC_STRING_BYTES(S) (STRING_BYTES (S) & ~MARKBIT)
121 #define GC_STRING_CHARS(S) ((S)->size & ~MARKBIT)
123 /* Number of bytes of consing done since the last gc. */
125 int consing_since_gc;
127 /* Count the amount of consing of various sorts of space. */
129 EMACS_INT cons_cells_consed;
130 EMACS_INT floats_consed;
131 EMACS_INT vector_cells_consed;
132 EMACS_INT symbols_consed;
133 EMACS_INT string_chars_consed;
134 EMACS_INT misc_objects_consed;
135 EMACS_INT intervals_consed;
136 EMACS_INT strings_consed;
138 /* Number of bytes of consing since GC before another GC should be done. */
140 EMACS_INT gc_cons_threshold;
142 /* Nonzero during GC. */
144 int gc_in_progress;
146 /* Nonzero means display messages at beginning and end of GC. */
148 int garbage_collection_messages;
150 #ifndef VIRT_ADDR_VARIES
151 extern
152 #endif /* VIRT_ADDR_VARIES */
153 int malloc_sbrk_used;
155 #ifndef VIRT_ADDR_VARIES
156 extern
157 #endif /* VIRT_ADDR_VARIES */
158 int malloc_sbrk_unused;
160 /* Two limits controlling how much undo information to keep. */
162 EMACS_INT undo_limit;
163 EMACS_INT undo_strong_limit;
165 /* Number of live and free conses etc. */
167 static int total_conses, total_markers, total_symbols, total_vector_size;
168 static int total_free_conses, total_free_markers, total_free_symbols;
169 static int total_free_floats, total_floats;
171 /* Points to memory space allocated as "spare", to be freed if we run
172 out of memory. */
174 static char *spare_memory;
176 /* Amount of spare memory to keep in reserve. */
178 #define SPARE_MEMORY (1 << 14)
180 /* Number of extra blocks malloc should get when it needs more core. */
182 static int malloc_hysteresis;
184 /* Non-nil means defun should do purecopy on the function definition. */
186 Lisp_Object Vpurify_flag;
188 /* Non-nil means we are handling a memory-full error. */
190 Lisp_Object Vmemory_full;
192 #ifndef HAVE_SHM
194 /* Force it into data space! */
196 EMACS_INT pure[PURESIZE / sizeof (EMACS_INT)] = {0,};
197 #define PUREBEG (char *) pure
199 #else /* HAVE_SHM */
201 #define pure PURE_SEG_BITS /* Use shared memory segment */
202 #define PUREBEG (char *)PURE_SEG_BITS
204 #endif /* HAVE_SHM */
206 /* Pointer to the pure area, and its size. */
208 static char *purebeg;
209 static size_t pure_size;
211 /* Number of bytes of pure storage used before pure storage overflowed.
212 If this is non-zero, this implies that an overflow occurred. */
214 static size_t pure_bytes_used_before_overflow;
216 /* Value is non-zero if P points into pure space. */
218 #define PURE_POINTER_P(P) \
219 (((PNTR_COMPARISON_TYPE) (P) \
220 < (PNTR_COMPARISON_TYPE) ((char *) purebeg + pure_size)) \
221 && ((PNTR_COMPARISON_TYPE) (P) \
222 >= (PNTR_COMPARISON_TYPE) purebeg))
224 /* Index in pure at which next pure object will be allocated.. */
226 EMACS_INT pure_bytes_used;
228 /* If nonzero, this is a warning delivered by malloc and not yet
229 displayed. */
231 char *pending_malloc_warning;
233 /* Pre-computed signal argument for use when memory is exhausted. */
235 Lisp_Object Vmemory_signal_data;
237 /* Maximum amount of C stack to save when a GC happens. */
239 #ifndef MAX_SAVE_STACK
240 #define MAX_SAVE_STACK 16000
241 #endif
243 /* Buffer in which we save a copy of the C stack at each GC. */
245 char *stack_copy;
246 int stack_copy_size;
248 /* Non-zero means ignore malloc warnings. Set during initialization.
249 Currently not used. */
251 int ignore_warnings;
253 Lisp_Object Qgc_cons_threshold, Qchar_table_extra_slots;
255 /* Hook run after GC has finished. */
257 Lisp_Object Vpost_gc_hook, Qpost_gc_hook;
259 static void mark_buffer P_ ((Lisp_Object));
260 static void mark_kboards P_ ((void));
261 static void gc_sweep P_ ((void));
262 static void mark_glyph_matrix P_ ((struct glyph_matrix *));
263 static void mark_face_cache P_ ((struct face_cache *));
265 #ifdef HAVE_WINDOW_SYSTEM
266 static void mark_image P_ ((struct image *));
267 static void mark_image_cache P_ ((struct frame *));
268 #endif /* HAVE_WINDOW_SYSTEM */
270 static struct Lisp_String *allocate_string P_ ((void));
271 static void compact_small_strings P_ ((void));
272 static void free_large_strings P_ ((void));
273 static void sweep_strings P_ ((void));
275 extern int message_enable_multibyte;
277 /* When scanning the C stack for live Lisp objects, Emacs keeps track
278 of what memory allocated via lisp_malloc is intended for what
279 purpose. This enumeration specifies the type of memory. */
281 enum mem_type
283 MEM_TYPE_NON_LISP,
284 MEM_TYPE_BUFFER,
285 MEM_TYPE_CONS,
286 MEM_TYPE_STRING,
287 MEM_TYPE_MISC,
288 MEM_TYPE_SYMBOL,
289 MEM_TYPE_FLOAT,
290 /* Keep the following vector-like types together, with
291 MEM_TYPE_WINDOW being the last, and MEM_TYPE_VECTOR the
292 first. Or change the code of live_vector_p, for instance. */
293 MEM_TYPE_VECTOR,
294 MEM_TYPE_PROCESS,
295 MEM_TYPE_HASH_TABLE,
296 MEM_TYPE_FRAME,
297 MEM_TYPE_WINDOW
300 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
302 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
303 #include <stdio.h> /* For fprintf. */
304 #endif
306 /* A unique object in pure space used to make some Lisp objects
307 on free lists recognizable in O(1). */
309 Lisp_Object Vdead;
311 #ifdef GC_MALLOC_CHECK
313 enum mem_type allocated_mem_type;
314 int dont_register_blocks;
316 #endif /* GC_MALLOC_CHECK */
318 /* A node in the red-black tree describing allocated memory containing
319 Lisp data. Each such block is recorded with its start and end
320 address when it is allocated, and removed from the tree when it
321 is freed.
323 A red-black tree is a balanced binary tree with the following
324 properties:
326 1. Every node is either red or black.
327 2. Every leaf is black.
328 3. If a node is red, then both of its children are black.
329 4. Every simple path from a node to a descendant leaf contains
330 the same number of black nodes.
331 5. The root is always black.
333 When nodes are inserted into the tree, or deleted from the tree,
334 the tree is "fixed" so that these properties are always true.
336 A red-black tree with N internal nodes has height at most 2
337 log(N+1). Searches, insertions and deletions are done in O(log N).
338 Please see a text book about data structures for a detailed
339 description of red-black trees. Any book worth its salt should
340 describe them. */
342 struct mem_node
344 struct mem_node *left, *right, *parent;
346 /* Start and end of allocated region. */
347 void *start, *end;
349 /* Node color. */
350 enum {MEM_BLACK, MEM_RED} color;
352 /* Memory type. */
353 enum mem_type type;
356 /* Base address of stack. Set in main. */
358 Lisp_Object *stack_base;
360 /* Root of the tree describing allocated Lisp memory. */
362 static struct mem_node *mem_root;
364 /* Lowest and highest known address in the heap. */
366 static void *min_heap_address, *max_heap_address;
368 /* Sentinel node of the tree. */
370 static struct mem_node mem_z;
371 #define MEM_NIL &mem_z
373 static POINTER_TYPE *lisp_malloc P_ ((size_t, enum mem_type));
374 static struct Lisp_Vector *allocate_vectorlike P_ ((EMACS_INT, enum mem_type));
375 static void lisp_free P_ ((POINTER_TYPE *));
376 static void mark_stack P_ ((void));
377 static int live_vector_p P_ ((struct mem_node *, void *));
378 static int live_buffer_p P_ ((struct mem_node *, void *));
379 static int live_string_p P_ ((struct mem_node *, void *));
380 static int live_cons_p P_ ((struct mem_node *, void *));
381 static int live_symbol_p P_ ((struct mem_node *, void *));
382 static int live_float_p P_ ((struct mem_node *, void *));
383 static int live_misc_p P_ ((struct mem_node *, void *));
384 static void mark_maybe_object P_ ((Lisp_Object));
385 static void mark_memory P_ ((void *, void *));
386 static void mem_init P_ ((void));
387 static struct mem_node *mem_insert P_ ((void *, void *, enum mem_type));
388 static void mem_insert_fixup P_ ((struct mem_node *));
389 static void mem_rotate_left P_ ((struct mem_node *));
390 static void mem_rotate_right P_ ((struct mem_node *));
391 static void mem_delete P_ ((struct mem_node *));
392 static void mem_delete_fixup P_ ((struct mem_node *));
393 static INLINE struct mem_node *mem_find P_ ((void *));
395 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
396 static void check_gcpros P_ ((void));
397 #endif
399 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
401 /* Recording what needs to be marked for gc. */
403 struct gcpro *gcprolist;
405 /* Addresses of staticpro'd variables. */
407 #define NSTATICS 1280
408 Lisp_Object *staticvec[NSTATICS] = {0};
410 /* Index of next unused slot in staticvec. */
412 int staticidx = 0;
414 static POINTER_TYPE *pure_alloc P_ ((size_t, int));
417 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
418 ALIGNMENT must be a power of 2. */
420 #define ALIGN(SZ, ALIGNMENT) \
421 (((SZ) + (ALIGNMENT) - 1) & ~((ALIGNMENT) - 1))
425 /************************************************************************
426 Malloc
427 ************************************************************************/
429 /* Function malloc calls this if it finds we are near exhausting storage. */
431 void
432 malloc_warning (str)
433 char *str;
435 pending_malloc_warning = str;
439 /* Display an already-pending malloc warning. */
441 void
442 display_malloc_warning ()
444 call3 (intern ("display-warning"),
445 intern ("alloc"),
446 build_string (pending_malloc_warning),
447 intern ("emergency"));
448 pending_malloc_warning = 0;
452 #ifdef DOUG_LEA_MALLOC
453 # define BYTES_USED (mallinfo ().arena)
454 #else
455 # define BYTES_USED _bytes_used
456 #endif
459 /* Called if malloc returns zero. */
461 void
462 memory_full ()
464 Vmemory_full = Qt;
466 #ifndef SYSTEM_MALLOC
467 bytes_used_when_full = BYTES_USED;
468 #endif
470 /* The first time we get here, free the spare memory. */
471 if (spare_memory)
473 free (spare_memory);
474 spare_memory = 0;
477 /* This used to call error, but if we've run out of memory, we could
478 get infinite recursion trying to build the string. */
479 while (1)
480 Fsignal (Qnil, Vmemory_signal_data);
484 /* Called if we can't allocate relocatable space for a buffer. */
486 void
487 buffer_memory_full ()
489 /* If buffers use the relocating allocator, no need to free
490 spare_memory, because we may have plenty of malloc space left
491 that we could get, and if we don't, the malloc that fails will
492 itself cause spare_memory to be freed. If buffers don't use the
493 relocating allocator, treat this like any other failing
494 malloc. */
496 #ifndef REL_ALLOC
497 memory_full ();
498 #endif
500 Vmemory_full = Qt;
502 /* This used to call error, but if we've run out of memory, we could
503 get infinite recursion trying to build the string. */
504 while (1)
505 Fsignal (Qnil, Vmemory_signal_data);
509 /* Like malloc but check for no memory and block interrupt input.. */
511 POINTER_TYPE *
512 xmalloc (size)
513 size_t size;
515 register POINTER_TYPE *val;
517 BLOCK_INPUT;
518 val = (POINTER_TYPE *) malloc (size);
519 UNBLOCK_INPUT;
521 if (!val && size)
522 memory_full ();
523 return val;
527 /* Like realloc but check for no memory and block interrupt input.. */
529 POINTER_TYPE *
530 xrealloc (block, size)
531 POINTER_TYPE *block;
532 size_t size;
534 register POINTER_TYPE *val;
536 BLOCK_INPUT;
537 /* We must call malloc explicitly when BLOCK is 0, since some
538 reallocs don't do this. */
539 if (! block)
540 val = (POINTER_TYPE *) malloc (size);
541 else
542 val = (POINTER_TYPE *) realloc (block, size);
543 UNBLOCK_INPUT;
545 if (!val && size) memory_full ();
546 return val;
550 /* Like free but block interrupt input.. */
552 void
553 xfree (block)
554 POINTER_TYPE *block;
556 BLOCK_INPUT;
557 free (block);
558 UNBLOCK_INPUT;
562 /* Like strdup, but uses xmalloc. */
564 char *
565 xstrdup (s)
566 const char *s;
568 size_t len = strlen (s) + 1;
569 char *p = (char *) xmalloc (len);
570 bcopy (s, p, len);
571 return p;
575 /* Like malloc but used for allocating Lisp data. NBYTES is the
576 number of bytes to allocate, TYPE describes the intended use of the
577 allcated memory block (for strings, for conses, ...). */
579 static POINTER_TYPE *
580 lisp_malloc (nbytes, type)
581 size_t nbytes;
582 enum mem_type type;
584 register void *val;
586 BLOCK_INPUT;
588 #ifdef GC_MALLOC_CHECK
589 allocated_mem_type = type;
590 #endif
592 val = (void *) malloc (nbytes);
594 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
595 if (val && type != MEM_TYPE_NON_LISP)
596 mem_insert (val, (char *) val + nbytes, type);
597 #endif
599 UNBLOCK_INPUT;
600 if (!val && nbytes)
601 memory_full ();
602 return val;
606 /* Return a new buffer structure allocated from the heap with
607 a call to lisp_malloc. */
609 struct buffer *
610 allocate_buffer ()
612 struct buffer *b
613 = (struct buffer *) lisp_malloc (sizeof (struct buffer),
614 MEM_TYPE_BUFFER);
615 VALIDATE_LISP_STORAGE (b, sizeof *b);
616 return b;
620 /* Free BLOCK. This must be called to free memory allocated with a
621 call to lisp_malloc. */
623 static void
624 lisp_free (block)
625 POINTER_TYPE *block;
627 BLOCK_INPUT;
628 free (block);
629 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
630 mem_delete (mem_find (block));
631 #endif
632 UNBLOCK_INPUT;
636 /* Arranging to disable input signals while we're in malloc.
638 This only works with GNU malloc. To help out systems which can't
639 use GNU malloc, all the calls to malloc, realloc, and free
640 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
641 pairs; unfortunately, we have no idea what C library functions
642 might call malloc, so we can't really protect them unless you're
643 using GNU malloc. Fortunately, most of the major operating can use
644 GNU malloc. */
646 #ifndef SYSTEM_MALLOC
647 #ifndef DOUG_LEA_MALLOC
648 extern void * (*__malloc_hook) P_ ((size_t));
649 extern void * (*__realloc_hook) P_ ((void *, size_t));
650 extern void (*__free_hook) P_ ((void *));
651 /* Else declared in malloc.h, perhaps with an extra arg. */
652 #endif /* DOUG_LEA_MALLOC */
653 static void * (*old_malloc_hook) ();
654 static void * (*old_realloc_hook) ();
655 static void (*old_free_hook) ();
657 /* This function is used as the hook for free to call. */
659 static void
660 emacs_blocked_free (ptr)
661 void *ptr;
663 BLOCK_INPUT;
665 #ifdef GC_MALLOC_CHECK
666 if (ptr)
668 struct mem_node *m;
670 m = mem_find (ptr);
671 if (m == MEM_NIL || m->start != ptr)
673 fprintf (stderr,
674 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
675 abort ();
677 else
679 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
680 mem_delete (m);
683 #endif /* GC_MALLOC_CHECK */
685 __free_hook = old_free_hook;
686 free (ptr);
688 /* If we released our reserve (due to running out of memory),
689 and we have a fair amount free once again,
690 try to set aside another reserve in case we run out once more. */
691 if (spare_memory == 0
692 /* Verify there is enough space that even with the malloc
693 hysteresis this call won't run out again.
694 The code here is correct as long as SPARE_MEMORY
695 is substantially larger than the block size malloc uses. */
696 && (bytes_used_when_full
697 > BYTES_USED + max (malloc_hysteresis, 4) * SPARE_MEMORY))
698 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
700 __free_hook = emacs_blocked_free;
701 UNBLOCK_INPUT;
705 /* If we released our reserve (due to running out of memory),
706 and we have a fair amount free once again,
707 try to set aside another reserve in case we run out once more.
709 This is called when a relocatable block is freed in ralloc.c. */
711 void
712 refill_memory_reserve ()
714 if (spare_memory == 0)
715 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
719 /* This function is the malloc hook that Emacs uses. */
721 static void *
722 emacs_blocked_malloc (size)
723 size_t size;
725 void *value;
727 BLOCK_INPUT;
728 __malloc_hook = old_malloc_hook;
729 #ifdef DOUG_LEA_MALLOC
730 mallopt (M_TOP_PAD, malloc_hysteresis * 4096);
731 #else
732 __malloc_extra_blocks = malloc_hysteresis;
733 #endif
735 value = (void *) malloc (size);
737 #ifdef GC_MALLOC_CHECK
739 struct mem_node *m = mem_find (value);
740 if (m != MEM_NIL)
742 fprintf (stderr, "Malloc returned %p which is already in use\n",
743 value);
744 fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
745 m->start, m->end, (char *) m->end - (char *) m->start,
746 m->type);
747 abort ();
750 if (!dont_register_blocks)
752 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
753 allocated_mem_type = MEM_TYPE_NON_LISP;
756 #endif /* GC_MALLOC_CHECK */
758 __malloc_hook = emacs_blocked_malloc;
759 UNBLOCK_INPUT;
761 /* fprintf (stderr, "%p malloc\n", value); */
762 return value;
766 /* This function is the realloc hook that Emacs uses. */
768 static void *
769 emacs_blocked_realloc (ptr, size)
770 void *ptr;
771 size_t size;
773 void *value;
775 BLOCK_INPUT;
776 __realloc_hook = old_realloc_hook;
778 #ifdef GC_MALLOC_CHECK
779 if (ptr)
781 struct mem_node *m = mem_find (ptr);
782 if (m == MEM_NIL || m->start != ptr)
784 fprintf (stderr,
785 "Realloc of %p which wasn't allocated with malloc\n",
786 ptr);
787 abort ();
790 mem_delete (m);
793 /* fprintf (stderr, "%p -> realloc\n", ptr); */
795 /* Prevent malloc from registering blocks. */
796 dont_register_blocks = 1;
797 #endif /* GC_MALLOC_CHECK */
799 value = (void *) realloc (ptr, size);
801 #ifdef GC_MALLOC_CHECK
802 dont_register_blocks = 0;
805 struct mem_node *m = mem_find (value);
806 if (m != MEM_NIL)
808 fprintf (stderr, "Realloc returns memory that is already in use\n");
809 abort ();
812 /* Can't handle zero size regions in the red-black tree. */
813 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
816 /* fprintf (stderr, "%p <- realloc\n", value); */
817 #endif /* GC_MALLOC_CHECK */
819 __realloc_hook = emacs_blocked_realloc;
820 UNBLOCK_INPUT;
822 return value;
826 /* Called from main to set up malloc to use our hooks. */
828 void
829 uninterrupt_malloc ()
831 if (__free_hook != emacs_blocked_free)
832 old_free_hook = __free_hook;
833 __free_hook = emacs_blocked_free;
835 if (__malloc_hook != emacs_blocked_malloc)
836 old_malloc_hook = __malloc_hook;
837 __malloc_hook = emacs_blocked_malloc;
839 if (__realloc_hook != emacs_blocked_realloc)
840 old_realloc_hook = __realloc_hook;
841 __realloc_hook = emacs_blocked_realloc;
844 #endif /* not SYSTEM_MALLOC */
848 /***********************************************************************
849 Interval Allocation
850 ***********************************************************************/
852 /* Number of intervals allocated in an interval_block structure.
853 The 1020 is 1024 minus malloc overhead. */
855 #define INTERVAL_BLOCK_SIZE \
856 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
858 /* Intervals are allocated in chunks in form of an interval_block
859 structure. */
861 struct interval_block
863 struct interval_block *next;
864 struct interval intervals[INTERVAL_BLOCK_SIZE];
867 /* Current interval block. Its `next' pointer points to older
868 blocks. */
870 struct interval_block *interval_block;
872 /* Index in interval_block above of the next unused interval
873 structure. */
875 static int interval_block_index;
877 /* Number of free and live intervals. */
879 static int total_free_intervals, total_intervals;
881 /* List of free intervals. */
883 INTERVAL interval_free_list;
885 /* Total number of interval blocks now in use. */
887 int n_interval_blocks;
890 /* Initialize interval allocation. */
892 static void
893 init_intervals ()
895 interval_block
896 = (struct interval_block *) lisp_malloc (sizeof *interval_block,
897 MEM_TYPE_NON_LISP);
898 interval_block->next = 0;
899 bzero ((char *) interval_block->intervals, sizeof interval_block->intervals);
900 interval_block_index = 0;
901 interval_free_list = 0;
902 n_interval_blocks = 1;
906 /* Return a new interval. */
908 INTERVAL
909 make_interval ()
911 INTERVAL val;
913 if (interval_free_list)
915 val = interval_free_list;
916 interval_free_list = INTERVAL_PARENT (interval_free_list);
918 else
920 if (interval_block_index == INTERVAL_BLOCK_SIZE)
922 register struct interval_block *newi;
924 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
925 MEM_TYPE_NON_LISP);
927 VALIDATE_LISP_STORAGE (newi, sizeof *newi);
928 newi->next = interval_block;
929 interval_block = newi;
930 interval_block_index = 0;
931 n_interval_blocks++;
933 val = &interval_block->intervals[interval_block_index++];
935 consing_since_gc += sizeof (struct interval);
936 intervals_consed++;
937 RESET_INTERVAL (val);
938 return val;
942 /* Mark Lisp objects in interval I. */
944 static void
945 mark_interval (i, dummy)
946 register INTERVAL i;
947 Lisp_Object dummy;
949 if (XMARKBIT (i->plist))
950 abort ();
951 mark_object (&i->plist);
952 XMARK (i->plist);
956 /* Mark the interval tree rooted in TREE. Don't call this directly;
957 use the macro MARK_INTERVAL_TREE instead. */
959 static void
960 mark_interval_tree (tree)
961 register INTERVAL tree;
963 /* No need to test if this tree has been marked already; this
964 function is always called through the MARK_INTERVAL_TREE macro,
965 which takes care of that. */
967 /* XMARK expands to an assignment; the LHS of an assignment can't be
968 a cast. */
969 XMARK (tree->up.obj);
971 traverse_intervals_noorder (tree, mark_interval, Qnil);
975 /* Mark the interval tree rooted in I. */
977 #define MARK_INTERVAL_TREE(i) \
978 do { \
979 if (!NULL_INTERVAL_P (i) \
980 && ! XMARKBIT (i->up.obj)) \
981 mark_interval_tree (i); \
982 } while (0)
985 /* The oddity in the call to XUNMARK is necessary because XUNMARK
986 expands to an assignment to its argument, and most C compilers
987 don't support casts on the left operand of `='. */
989 #define UNMARK_BALANCE_INTERVALS(i) \
990 do { \
991 if (! NULL_INTERVAL_P (i)) \
993 XUNMARK ((i)->up.obj); \
994 (i) = balance_intervals (i); \
996 } while (0)
999 /* Number support. If NO_UNION_TYPE isn't in effect, we
1000 can't create number objects in macros. */
1001 #ifndef make_number
1002 Lisp_Object
1003 make_number (n)
1004 int n;
1006 Lisp_Object obj;
1007 obj.s.val = n;
1008 obj.s.type = Lisp_Int;
1009 return obj;
1011 #endif
1013 /***********************************************************************
1014 String Allocation
1015 ***********************************************************************/
1017 /* Lisp_Strings are allocated in string_block structures. When a new
1018 string_block is allocated, all the Lisp_Strings it contains are
1019 added to a free-list string_free_list. When a new Lisp_String is
1020 needed, it is taken from that list. During the sweep phase of GC,
1021 string_blocks that are entirely free are freed, except two which
1022 we keep.
1024 String data is allocated from sblock structures. Strings larger
1025 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1026 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1028 Sblocks consist internally of sdata structures, one for each
1029 Lisp_String. The sdata structure points to the Lisp_String it
1030 belongs to. The Lisp_String points back to the `u.data' member of
1031 its sdata structure.
1033 When a Lisp_String is freed during GC, it is put back on
1034 string_free_list, and its `data' member and its sdata's `string'
1035 pointer is set to null. The size of the string is recorded in the
1036 `u.nbytes' member of the sdata. So, sdata structures that are no
1037 longer used, can be easily recognized, and it's easy to compact the
1038 sblocks of small strings which we do in compact_small_strings. */
1040 /* Size in bytes of an sblock structure used for small strings. This
1041 is 8192 minus malloc overhead. */
1043 #define SBLOCK_SIZE 8188
1045 /* Strings larger than this are considered large strings. String data
1046 for large strings is allocated from individual sblocks. */
1048 #define LARGE_STRING_BYTES 1024
1050 /* Structure describing string memory sub-allocated from an sblock.
1051 This is where the contents of Lisp strings are stored. */
1053 struct sdata
1055 /* Back-pointer to the string this sdata belongs to. If null, this
1056 structure is free, and the NBYTES member of the union below
1057 contains the string's byte size (the same value that STRING_BYTES
1058 would return if STRING were non-null). If non-null, STRING_BYTES
1059 (STRING) is the size of the data, and DATA contains the string's
1060 contents. */
1061 struct Lisp_String *string;
1063 #ifdef GC_CHECK_STRING_BYTES
1065 EMACS_INT nbytes;
1066 unsigned char data[1];
1068 #define SDATA_NBYTES(S) (S)->nbytes
1069 #define SDATA_DATA(S) (S)->data
1071 #else /* not GC_CHECK_STRING_BYTES */
1073 union
1075 /* When STRING in non-null. */
1076 unsigned char data[1];
1078 /* When STRING is null. */
1079 EMACS_INT nbytes;
1080 } u;
1083 #define SDATA_NBYTES(S) (S)->u.nbytes
1084 #define SDATA_DATA(S) (S)->u.data
1086 #endif /* not GC_CHECK_STRING_BYTES */
1090 /* Structure describing a block of memory which is sub-allocated to
1091 obtain string data memory for strings. Blocks for small strings
1092 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1093 as large as needed. */
1095 struct sblock
1097 /* Next in list. */
1098 struct sblock *next;
1100 /* Pointer to the next free sdata block. This points past the end
1101 of the sblock if there isn't any space left in this block. */
1102 struct sdata *next_free;
1104 /* Start of data. */
1105 struct sdata first_data;
1108 /* Number of Lisp strings in a string_block structure. The 1020 is
1109 1024 minus malloc overhead. */
1111 #define STRINGS_IN_STRING_BLOCK \
1112 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1114 /* Structure describing a block from which Lisp_String structures
1115 are allocated. */
1117 struct string_block
1119 struct string_block *next;
1120 struct Lisp_String strings[STRINGS_IN_STRING_BLOCK];
1123 /* Head and tail of the list of sblock structures holding Lisp string
1124 data. We always allocate from current_sblock. The NEXT pointers
1125 in the sblock structures go from oldest_sblock to current_sblock. */
1127 static struct sblock *oldest_sblock, *current_sblock;
1129 /* List of sblocks for large strings. */
1131 static struct sblock *large_sblocks;
1133 /* List of string_block structures, and how many there are. */
1135 static struct string_block *string_blocks;
1136 static int n_string_blocks;
1138 /* Free-list of Lisp_Strings. */
1140 static struct Lisp_String *string_free_list;
1142 /* Number of live and free Lisp_Strings. */
1144 static int total_strings, total_free_strings;
1146 /* Number of bytes used by live strings. */
1148 static int total_string_size;
1150 /* Given a pointer to a Lisp_String S which is on the free-list
1151 string_free_list, return a pointer to its successor in the
1152 free-list. */
1154 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1156 /* Return a pointer to the sdata structure belonging to Lisp string S.
1157 S must be live, i.e. S->data must not be null. S->data is actually
1158 a pointer to the `u.data' member of its sdata structure; the
1159 structure starts at a constant offset in front of that. */
1161 #ifdef GC_CHECK_STRING_BYTES
1163 #define SDATA_OF_STRING(S) \
1164 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *) \
1165 - sizeof (EMACS_INT)))
1167 #else /* not GC_CHECK_STRING_BYTES */
1169 #define SDATA_OF_STRING(S) \
1170 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))
1172 #endif /* not GC_CHECK_STRING_BYTES */
1174 /* Value is the size of an sdata structure large enough to hold NBYTES
1175 bytes of string data. The value returned includes a terminating
1176 NUL byte, the size of the sdata structure, and padding. */
1178 #ifdef GC_CHECK_STRING_BYTES
1180 #define SDATA_SIZE(NBYTES) \
1181 ((sizeof (struct Lisp_String *) \
1182 + (NBYTES) + 1 \
1183 + sizeof (EMACS_INT) \
1184 + sizeof (EMACS_INT) - 1) \
1185 & ~(sizeof (EMACS_INT) - 1))
1187 #else /* not GC_CHECK_STRING_BYTES */
1189 #define SDATA_SIZE(NBYTES) \
1190 ((sizeof (struct Lisp_String *) \
1191 + (NBYTES) + 1 \
1192 + sizeof (EMACS_INT) - 1) \
1193 & ~(sizeof (EMACS_INT) - 1))
1195 #endif /* not GC_CHECK_STRING_BYTES */
1197 /* Initialize string allocation. Called from init_alloc_once. */
1199 void
1200 init_strings ()
1202 total_strings = total_free_strings = total_string_size = 0;
1203 oldest_sblock = current_sblock = large_sblocks = NULL;
1204 string_blocks = NULL;
1205 n_string_blocks = 0;
1206 string_free_list = NULL;
1210 #ifdef GC_CHECK_STRING_BYTES
1212 static int check_string_bytes_count;
1214 void check_string_bytes P_ ((int));
1215 void check_sblock P_ ((struct sblock *));
1217 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1220 /* Like GC_STRING_BYTES, but with debugging check. */
1223 string_bytes (s)
1224 struct Lisp_String *s;
1226 int nbytes = (s->size_byte < 0 ? s->size : s->size_byte) & ~MARKBIT;
1227 if (!PURE_POINTER_P (s)
1228 && s->data
1229 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1230 abort ();
1231 return nbytes;
1234 /* Check validity Lisp strings' string_bytes member in B. */
1236 void
1237 check_sblock (b)
1238 struct sblock *b;
1240 struct sdata *from, *end, *from_end;
1242 end = b->next_free;
1244 for (from = &b->first_data; from < end; from = from_end)
1246 /* Compute the next FROM here because copying below may
1247 overwrite data we need to compute it. */
1248 int nbytes;
1250 /* Check that the string size recorded in the string is the
1251 same as the one recorded in the sdata structure. */
1252 if (from->string)
1253 CHECK_STRING_BYTES (from->string);
1255 if (from->string)
1256 nbytes = GC_STRING_BYTES (from->string);
1257 else
1258 nbytes = SDATA_NBYTES (from);
1260 nbytes = SDATA_SIZE (nbytes);
1261 from_end = (struct sdata *) ((char *) from + nbytes);
1266 /* Check validity of Lisp strings' string_bytes member. ALL_P
1267 non-zero means check all strings, otherwise check only most
1268 recently allocated strings. Used for hunting a bug. */
1270 void
1271 check_string_bytes (all_p)
1272 int all_p;
1274 if (all_p)
1276 struct sblock *b;
1278 for (b = large_sblocks; b; b = b->next)
1280 struct Lisp_String *s = b->first_data.string;
1281 if (s)
1282 CHECK_STRING_BYTES (s);
1285 for (b = oldest_sblock; b; b = b->next)
1286 check_sblock (b);
1288 else
1289 check_sblock (current_sblock);
1292 #endif /* GC_CHECK_STRING_BYTES */
1295 /* Return a new Lisp_String. */
1297 static struct Lisp_String *
1298 allocate_string ()
1300 struct Lisp_String *s;
1302 /* If the free-list is empty, allocate a new string_block, and
1303 add all the Lisp_Strings in it to the free-list. */
1304 if (string_free_list == NULL)
1306 struct string_block *b;
1307 int i;
1309 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1310 VALIDATE_LISP_STORAGE (b, sizeof *b);
1311 bzero (b, sizeof *b);
1312 b->next = string_blocks;
1313 string_blocks = b;
1314 ++n_string_blocks;
1316 for (i = STRINGS_IN_STRING_BLOCK - 1; i >= 0; --i)
1318 s = b->strings + i;
1319 NEXT_FREE_LISP_STRING (s) = string_free_list;
1320 string_free_list = s;
1323 total_free_strings += STRINGS_IN_STRING_BLOCK;
1326 /* Pop a Lisp_String off the free-list. */
1327 s = string_free_list;
1328 string_free_list = NEXT_FREE_LISP_STRING (s);
1330 /* Probably not strictly necessary, but play it safe. */
1331 bzero (s, sizeof *s);
1333 --total_free_strings;
1334 ++total_strings;
1335 ++strings_consed;
1336 consing_since_gc += sizeof *s;
1338 #ifdef GC_CHECK_STRING_BYTES
1339 if (!noninteractive
1340 #ifdef MAC_OS8
1341 && current_sblock
1342 #endif
1345 if (++check_string_bytes_count == 200)
1347 check_string_bytes_count = 0;
1348 check_string_bytes (1);
1350 else
1351 check_string_bytes (0);
1353 #endif /* GC_CHECK_STRING_BYTES */
1355 return s;
1359 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1360 plus a NUL byte at the end. Allocate an sdata structure for S, and
1361 set S->data to its `u.data' member. Store a NUL byte at the end of
1362 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1363 S->data if it was initially non-null. */
1365 void
1366 allocate_string_data (s, nchars, nbytes)
1367 struct Lisp_String *s;
1368 int nchars, nbytes;
1370 struct sdata *data, *old_data;
1371 struct sblock *b;
1372 int needed, old_nbytes;
1374 /* Determine the number of bytes needed to store NBYTES bytes
1375 of string data. */
1376 needed = SDATA_SIZE (nbytes);
1378 if (nbytes > LARGE_STRING_BYTES)
1380 size_t size = sizeof *b - sizeof (struct sdata) + needed;
1382 #ifdef DOUG_LEA_MALLOC
1383 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1384 because mapped region contents are not preserved in
1385 a dumped Emacs. */
1386 mallopt (M_MMAP_MAX, 0);
1387 #endif
1389 b = (struct sblock *) lisp_malloc (size, MEM_TYPE_NON_LISP);
1391 #ifdef DOUG_LEA_MALLOC
1392 /* Back to a reasonable maximum of mmap'ed areas. */
1393 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1394 #endif
1396 b->next_free = &b->first_data;
1397 b->first_data.string = NULL;
1398 b->next = large_sblocks;
1399 large_sblocks = b;
1401 else if (current_sblock == NULL
1402 || (((char *) current_sblock + SBLOCK_SIZE
1403 - (char *) current_sblock->next_free)
1404 < needed))
1406 /* Not enough room in the current sblock. */
1407 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1408 b->next_free = &b->first_data;
1409 b->first_data.string = NULL;
1410 b->next = NULL;
1412 if (current_sblock)
1413 current_sblock->next = b;
1414 else
1415 oldest_sblock = b;
1416 current_sblock = b;
1418 else
1419 b = current_sblock;
1421 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1422 old_nbytes = GC_STRING_BYTES (s);
1424 data = b->next_free;
1425 data->string = s;
1426 s->data = SDATA_DATA (data);
1427 #ifdef GC_CHECK_STRING_BYTES
1428 SDATA_NBYTES (data) = nbytes;
1429 #endif
1430 s->size = nchars;
1431 s->size_byte = nbytes;
1432 s->data[nbytes] = '\0';
1433 b->next_free = (struct sdata *) ((char *) data + needed);
1435 /* If S had already data assigned, mark that as free by setting its
1436 string back-pointer to null, and recording the size of the data
1437 in it. */
1438 if (old_data)
1440 SDATA_NBYTES (old_data) = old_nbytes;
1441 old_data->string = NULL;
1444 consing_since_gc += needed;
1448 /* Sweep and compact strings. */
1450 static void
1451 sweep_strings ()
1453 struct string_block *b, *next;
1454 struct string_block *live_blocks = NULL;
1456 string_free_list = NULL;
1457 total_strings = total_free_strings = 0;
1458 total_string_size = 0;
1460 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1461 for (b = string_blocks; b; b = next)
1463 int i, nfree = 0;
1464 struct Lisp_String *free_list_before = string_free_list;
1466 next = b->next;
1468 for (i = 0; i < STRINGS_IN_STRING_BLOCK; ++i)
1470 struct Lisp_String *s = b->strings + i;
1472 if (s->data)
1474 /* String was not on free-list before. */
1475 if (STRING_MARKED_P (s))
1477 /* String is live; unmark it and its intervals. */
1478 UNMARK_STRING (s);
1480 if (!NULL_INTERVAL_P (s->intervals))
1481 UNMARK_BALANCE_INTERVALS (s->intervals);
1483 ++total_strings;
1484 total_string_size += STRING_BYTES (s);
1486 else
1488 /* String is dead. Put it on the free-list. */
1489 struct sdata *data = SDATA_OF_STRING (s);
1491 /* Save the size of S in its sdata so that we know
1492 how large that is. Reset the sdata's string
1493 back-pointer so that we know it's free. */
1494 #ifdef GC_CHECK_STRING_BYTES
1495 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
1496 abort ();
1497 #else
1498 data->u.nbytes = GC_STRING_BYTES (s);
1499 #endif
1500 data->string = NULL;
1502 /* Reset the strings's `data' member so that we
1503 know it's free. */
1504 s->data = NULL;
1506 /* Put the string on the free-list. */
1507 NEXT_FREE_LISP_STRING (s) = string_free_list;
1508 string_free_list = s;
1509 ++nfree;
1512 else
1514 /* S was on the free-list before. Put it there again. */
1515 NEXT_FREE_LISP_STRING (s) = string_free_list;
1516 string_free_list = s;
1517 ++nfree;
1521 /* Free blocks that contain free Lisp_Strings only, except
1522 the first two of them. */
1523 if (nfree == STRINGS_IN_STRING_BLOCK
1524 && total_free_strings > STRINGS_IN_STRING_BLOCK)
1526 lisp_free (b);
1527 --n_string_blocks;
1528 string_free_list = free_list_before;
1530 else
1532 total_free_strings += nfree;
1533 b->next = live_blocks;
1534 live_blocks = b;
1538 string_blocks = live_blocks;
1539 free_large_strings ();
1540 compact_small_strings ();
1544 /* Free dead large strings. */
1546 static void
1547 free_large_strings ()
1549 struct sblock *b, *next;
1550 struct sblock *live_blocks = NULL;
1552 for (b = large_sblocks; b; b = next)
1554 next = b->next;
1556 if (b->first_data.string == NULL)
1557 lisp_free (b);
1558 else
1560 b->next = live_blocks;
1561 live_blocks = b;
1565 large_sblocks = live_blocks;
1569 /* Compact data of small strings. Free sblocks that don't contain
1570 data of live strings after compaction. */
1572 static void
1573 compact_small_strings ()
1575 struct sblock *b, *tb, *next;
1576 struct sdata *from, *to, *end, *tb_end;
1577 struct sdata *to_end, *from_end;
1579 /* TB is the sblock we copy to, TO is the sdata within TB we copy
1580 to, and TB_END is the end of TB. */
1581 tb = oldest_sblock;
1582 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1583 to = &tb->first_data;
1585 /* Step through the blocks from the oldest to the youngest. We
1586 expect that old blocks will stabilize over time, so that less
1587 copying will happen this way. */
1588 for (b = oldest_sblock; b; b = b->next)
1590 end = b->next_free;
1591 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
1593 for (from = &b->first_data; from < end; from = from_end)
1595 /* Compute the next FROM here because copying below may
1596 overwrite data we need to compute it. */
1597 int nbytes;
1599 #ifdef GC_CHECK_STRING_BYTES
1600 /* Check that the string size recorded in the string is the
1601 same as the one recorded in the sdata structure. */
1602 if (from->string
1603 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
1604 abort ();
1605 #endif /* GC_CHECK_STRING_BYTES */
1607 if (from->string)
1608 nbytes = GC_STRING_BYTES (from->string);
1609 else
1610 nbytes = SDATA_NBYTES (from);
1612 nbytes = SDATA_SIZE (nbytes);
1613 from_end = (struct sdata *) ((char *) from + nbytes);
1615 /* FROM->string non-null means it's alive. Copy its data. */
1616 if (from->string)
1618 /* If TB is full, proceed with the next sblock. */
1619 to_end = (struct sdata *) ((char *) to + nbytes);
1620 if (to_end > tb_end)
1622 tb->next_free = to;
1623 tb = tb->next;
1624 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1625 to = &tb->first_data;
1626 to_end = (struct sdata *) ((char *) to + nbytes);
1629 /* Copy, and update the string's `data' pointer. */
1630 if (from != to)
1632 xassert (tb != b || to <= from);
1633 safe_bcopy ((char *) from, (char *) to, nbytes);
1634 to->string->data = SDATA_DATA (to);
1637 /* Advance past the sdata we copied to. */
1638 to = to_end;
1643 /* The rest of the sblocks following TB don't contain live data, so
1644 we can free them. */
1645 for (b = tb->next; b; b = next)
1647 next = b->next;
1648 lisp_free (b);
1651 tb->next_free = to;
1652 tb->next = NULL;
1653 current_sblock = tb;
1657 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
1658 doc: /* Return a newly created string of length LENGTH, with each element being INIT.
1659 Both LENGTH and INIT must be numbers. */)
1660 (length, init)
1661 Lisp_Object length, init;
1663 register Lisp_Object val;
1664 register unsigned char *p, *end;
1665 int c, nbytes;
1667 CHECK_NATNUM (length);
1668 CHECK_NUMBER (init);
1670 c = XINT (init);
1671 if (SINGLE_BYTE_CHAR_P (c))
1673 nbytes = XINT (length);
1674 val = make_uninit_string (nbytes);
1675 p = SDATA (val);
1676 end = p + SCHARS (val);
1677 while (p != end)
1678 *p++ = c;
1680 else
1682 unsigned char str[MAX_MULTIBYTE_LENGTH];
1683 int len = CHAR_STRING (c, str);
1685 nbytes = len * XINT (length);
1686 val = make_uninit_multibyte_string (XINT (length), nbytes);
1687 p = SDATA (val);
1688 end = p + nbytes;
1689 while (p != end)
1691 bcopy (str, p, len);
1692 p += len;
1696 *p = 0;
1697 return val;
1701 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
1702 doc: /* Return a new bool-vector of length LENGTH, using INIT for as each element.
1703 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
1704 (length, init)
1705 Lisp_Object length, init;
1707 register Lisp_Object val;
1708 struct Lisp_Bool_Vector *p;
1709 int real_init, i;
1710 int length_in_chars, length_in_elts, bits_per_value;
1712 CHECK_NATNUM (length);
1714 bits_per_value = sizeof (EMACS_INT) * BITS_PER_CHAR;
1716 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
1717 length_in_chars = ((XFASTINT (length) + BITS_PER_CHAR - 1) / BITS_PER_CHAR);
1719 /* We must allocate one more elements than LENGTH_IN_ELTS for the
1720 slot `size' of the struct Lisp_Bool_Vector. */
1721 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
1722 p = XBOOL_VECTOR (val);
1724 /* Get rid of any bits that would cause confusion. */
1725 p->vector_size = 0;
1726 XSETBOOL_VECTOR (val, p);
1727 p->size = XFASTINT (length);
1729 real_init = (NILP (init) ? 0 : -1);
1730 for (i = 0; i < length_in_chars ; i++)
1731 p->data[i] = real_init;
1733 /* Clear the extraneous bits in the last byte. */
1734 if (XINT (length) != length_in_chars * BITS_PER_CHAR)
1735 XBOOL_VECTOR (val)->data[length_in_chars - 1]
1736 &= (1 << (XINT (length) % BITS_PER_CHAR)) - 1;
1738 return val;
1742 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
1743 of characters from the contents. This string may be unibyte or
1744 multibyte, depending on the contents. */
1746 Lisp_Object
1747 make_string (contents, nbytes)
1748 const char *contents;
1749 int nbytes;
1751 register Lisp_Object val;
1752 int nchars, multibyte_nbytes;
1754 parse_str_as_multibyte (contents, nbytes, &nchars, &multibyte_nbytes);
1755 if (nbytes == nchars || nbytes != multibyte_nbytes)
1756 /* CONTENTS contains no multibyte sequences or contains an invalid
1757 multibyte sequence. We must make unibyte string. */
1758 val = make_unibyte_string (contents, nbytes);
1759 else
1760 val = make_multibyte_string (contents, nchars, nbytes);
1761 return val;
1765 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
1767 Lisp_Object
1768 make_unibyte_string (contents, length)
1769 const char *contents;
1770 int length;
1772 register Lisp_Object val;
1773 val = make_uninit_string (length);
1774 bcopy (contents, SDATA (val), length);
1775 STRING_SET_UNIBYTE (val);
1776 return val;
1780 /* Make a multibyte string from NCHARS characters occupying NBYTES
1781 bytes at CONTENTS. */
1783 Lisp_Object
1784 make_multibyte_string (contents, nchars, nbytes)
1785 const char *contents;
1786 int nchars, nbytes;
1788 register Lisp_Object val;
1789 val = make_uninit_multibyte_string (nchars, nbytes);
1790 bcopy (contents, SDATA (val), nbytes);
1791 return val;
1795 /* Make a string from NCHARS characters occupying NBYTES bytes at
1796 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
1798 Lisp_Object
1799 make_string_from_bytes (contents, nchars, nbytes)
1800 char *contents;
1801 int nchars, nbytes;
1803 register Lisp_Object val;
1804 val = make_uninit_multibyte_string (nchars, nbytes);
1805 bcopy (contents, SDATA (val), nbytes);
1806 if (SBYTES (val) == SCHARS (val))
1807 STRING_SET_UNIBYTE (val);
1808 return val;
1812 /* Make a string from NCHARS characters occupying NBYTES bytes at
1813 CONTENTS. The argument MULTIBYTE controls whether to label the
1814 string as multibyte. */
1816 Lisp_Object
1817 make_specified_string (contents, nchars, nbytes, multibyte)
1818 char *contents;
1819 int nchars, nbytes;
1820 int multibyte;
1822 register Lisp_Object val;
1823 val = make_uninit_multibyte_string (nchars, nbytes);
1824 bcopy (contents, SDATA (val), nbytes);
1825 if (!multibyte)
1826 STRING_SET_UNIBYTE (val);
1827 return val;
1831 /* Make a string from the data at STR, treating it as multibyte if the
1832 data warrants. */
1834 Lisp_Object
1835 build_string (str)
1836 const char *str;
1838 return make_string (str, strlen (str));
1842 /* Return an unibyte Lisp_String set up to hold LENGTH characters
1843 occupying LENGTH bytes. */
1845 Lisp_Object
1846 make_uninit_string (length)
1847 int length;
1849 Lisp_Object val;
1850 val = make_uninit_multibyte_string (length, length);
1851 STRING_SET_UNIBYTE (val);
1852 return val;
1856 /* Return a multibyte Lisp_String set up to hold NCHARS characters
1857 which occupy NBYTES bytes. */
1859 Lisp_Object
1860 make_uninit_multibyte_string (nchars, nbytes)
1861 int nchars, nbytes;
1863 Lisp_Object string;
1864 struct Lisp_String *s;
1866 if (nchars < 0)
1867 abort ();
1869 s = allocate_string ();
1870 allocate_string_data (s, nchars, nbytes);
1871 XSETSTRING (string, s);
1872 string_chars_consed += nbytes;
1873 return string;
1878 /***********************************************************************
1879 Float Allocation
1880 ***********************************************************************/
1882 /* We store float cells inside of float_blocks, allocating a new
1883 float_block with malloc whenever necessary. Float cells reclaimed
1884 by GC are put on a free list to be reallocated before allocating
1885 any new float cells from the latest float_block.
1887 Each float_block is just under 1020 bytes long, since malloc really
1888 allocates in units of powers of two and uses 4 bytes for its own
1889 overhead. */
1891 #define FLOAT_BLOCK_SIZE \
1892 ((1020 - sizeof (struct float_block *)) / sizeof (struct Lisp_Float))
1894 struct float_block
1896 struct float_block *next;
1897 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
1900 /* Current float_block. */
1902 struct float_block *float_block;
1904 /* Index of first unused Lisp_Float in the current float_block. */
1906 int float_block_index;
1908 /* Total number of float blocks now in use. */
1910 int n_float_blocks;
1912 /* Free-list of Lisp_Floats. */
1914 struct Lisp_Float *float_free_list;
1917 /* Initialize float allocation. */
1919 void
1920 init_float ()
1922 float_block = (struct float_block *) lisp_malloc (sizeof *float_block,
1923 MEM_TYPE_FLOAT);
1924 float_block->next = 0;
1925 bzero ((char *) float_block->floats, sizeof float_block->floats);
1926 float_block_index = 0;
1927 float_free_list = 0;
1928 n_float_blocks = 1;
1932 /* Explicitly free a float cell by putting it on the free-list. */
1934 void
1935 free_float (ptr)
1936 struct Lisp_Float *ptr;
1938 *(struct Lisp_Float **)&ptr->data = float_free_list;
1939 #if GC_MARK_STACK
1940 ptr->type = Vdead;
1941 #endif
1942 float_free_list = ptr;
1946 /* Return a new float object with value FLOAT_VALUE. */
1948 Lisp_Object
1949 make_float (float_value)
1950 double float_value;
1952 register Lisp_Object val;
1954 if (float_free_list)
1956 /* We use the data field for chaining the free list
1957 so that we won't use the same field that has the mark bit. */
1958 XSETFLOAT (val, float_free_list);
1959 float_free_list = *(struct Lisp_Float **)&float_free_list->data;
1961 else
1963 if (float_block_index == FLOAT_BLOCK_SIZE)
1965 register struct float_block *new;
1967 new = (struct float_block *) lisp_malloc (sizeof *new,
1968 MEM_TYPE_FLOAT);
1969 VALIDATE_LISP_STORAGE (new, sizeof *new);
1970 new->next = float_block;
1971 float_block = new;
1972 float_block_index = 0;
1973 n_float_blocks++;
1975 XSETFLOAT (val, &float_block->floats[float_block_index++]);
1978 XFLOAT_DATA (val) = float_value;
1979 XSETFASTINT (XFLOAT (val)->type, 0); /* bug chasing -wsr */
1980 consing_since_gc += sizeof (struct Lisp_Float);
1981 floats_consed++;
1982 return val;
1987 /***********************************************************************
1988 Cons Allocation
1989 ***********************************************************************/
1991 /* We store cons cells inside of cons_blocks, allocating a new
1992 cons_block with malloc whenever necessary. Cons cells reclaimed by
1993 GC are put on a free list to be reallocated before allocating
1994 any new cons cells from the latest cons_block.
1996 Each cons_block is just under 1020 bytes long,
1997 since malloc really allocates in units of powers of two
1998 and uses 4 bytes for its own overhead. */
2000 #define CONS_BLOCK_SIZE \
2001 ((1020 - sizeof (struct cons_block *)) / sizeof (struct Lisp_Cons))
2003 struct cons_block
2005 struct cons_block *next;
2006 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2009 /* Current cons_block. */
2011 struct cons_block *cons_block;
2013 /* Index of first unused Lisp_Cons in the current block. */
2015 int cons_block_index;
2017 /* Free-list of Lisp_Cons structures. */
2019 struct Lisp_Cons *cons_free_list;
2021 /* Total number of cons blocks now in use. */
2023 int n_cons_blocks;
2026 /* Initialize cons allocation. */
2028 void
2029 init_cons ()
2031 cons_block = (struct cons_block *) lisp_malloc (sizeof *cons_block,
2032 MEM_TYPE_CONS);
2033 cons_block->next = 0;
2034 bzero ((char *) cons_block->conses, sizeof cons_block->conses);
2035 cons_block_index = 0;
2036 cons_free_list = 0;
2037 n_cons_blocks = 1;
2041 /* Explicitly free a cons cell by putting it on the free-list. */
2043 void
2044 free_cons (ptr)
2045 struct Lisp_Cons *ptr;
2047 *(struct Lisp_Cons **)&ptr->cdr = cons_free_list;
2048 #if GC_MARK_STACK
2049 ptr->car = Vdead;
2050 #endif
2051 cons_free_list = ptr;
2055 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2056 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2057 (car, cdr)
2058 Lisp_Object car, cdr;
2060 register Lisp_Object val;
2062 if (cons_free_list)
2064 /* We use the cdr for chaining the free list
2065 so that we won't use the same field that has the mark bit. */
2066 XSETCONS (val, cons_free_list);
2067 cons_free_list = *(struct Lisp_Cons **)&cons_free_list->cdr;
2069 else
2071 if (cons_block_index == CONS_BLOCK_SIZE)
2073 register struct cons_block *new;
2074 new = (struct cons_block *) lisp_malloc (sizeof *new,
2075 MEM_TYPE_CONS);
2076 VALIDATE_LISP_STORAGE (new, sizeof *new);
2077 new->next = cons_block;
2078 cons_block = new;
2079 cons_block_index = 0;
2080 n_cons_blocks++;
2082 XSETCONS (val, &cons_block->conses[cons_block_index++]);
2085 XSETCAR (val, car);
2086 XSETCDR (val, cdr);
2087 consing_since_gc += sizeof (struct Lisp_Cons);
2088 cons_cells_consed++;
2089 return val;
2093 /* Make a list of 2, 3, 4 or 5 specified objects. */
2095 Lisp_Object
2096 list2 (arg1, arg2)
2097 Lisp_Object arg1, arg2;
2099 return Fcons (arg1, Fcons (arg2, Qnil));
2103 Lisp_Object
2104 list3 (arg1, arg2, arg3)
2105 Lisp_Object arg1, arg2, arg3;
2107 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2111 Lisp_Object
2112 list4 (arg1, arg2, arg3, arg4)
2113 Lisp_Object arg1, arg2, arg3, arg4;
2115 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2119 Lisp_Object
2120 list5 (arg1, arg2, arg3, arg4, arg5)
2121 Lisp_Object arg1, arg2, arg3, arg4, arg5;
2123 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2124 Fcons (arg5, Qnil)))));
2128 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2129 doc: /* Return a newly created list with specified arguments as elements.
2130 Any number of arguments, even zero arguments, are allowed.
2131 usage: (list &rest OBJECTS) */)
2132 (nargs, args)
2133 int nargs;
2134 register Lisp_Object *args;
2136 register Lisp_Object val;
2137 val = Qnil;
2139 while (nargs > 0)
2141 nargs--;
2142 val = Fcons (args[nargs], val);
2144 return val;
2148 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2149 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2150 (length, init)
2151 register Lisp_Object length, init;
2153 register Lisp_Object val;
2154 register int size;
2156 CHECK_NATNUM (length);
2157 size = XFASTINT (length);
2159 val = Qnil;
2160 while (size > 0)
2162 val = Fcons (init, val);
2163 --size;
2165 if (size > 0)
2167 val = Fcons (init, val);
2168 --size;
2170 if (size > 0)
2172 val = Fcons (init, val);
2173 --size;
2175 if (size > 0)
2177 val = Fcons (init, val);
2178 --size;
2180 if (size > 0)
2182 val = Fcons (init, val);
2183 --size;
2189 QUIT;
2192 return val;
2197 /***********************************************************************
2198 Vector Allocation
2199 ***********************************************************************/
2201 /* Singly-linked list of all vectors. */
2203 struct Lisp_Vector *all_vectors;
2205 /* Total number of vector-like objects now in use. */
2207 int n_vectors;
2210 /* Value is a pointer to a newly allocated Lisp_Vector structure
2211 with room for LEN Lisp_Objects. */
2213 static struct Lisp_Vector *
2214 allocate_vectorlike (len, type)
2215 EMACS_INT len;
2216 enum mem_type type;
2218 struct Lisp_Vector *p;
2219 size_t nbytes;
2221 #ifdef DOUG_LEA_MALLOC
2222 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2223 because mapped region contents are not preserved in
2224 a dumped Emacs. */
2225 mallopt (M_MMAP_MAX, 0);
2226 #endif
2228 nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
2229 p = (struct Lisp_Vector *) lisp_malloc (nbytes, type);
2231 #ifdef DOUG_LEA_MALLOC
2232 /* Back to a reasonable maximum of mmap'ed areas. */
2233 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2234 #endif
2236 VALIDATE_LISP_STORAGE (p, 0);
2237 consing_since_gc += nbytes;
2238 vector_cells_consed += len;
2240 p->next = all_vectors;
2241 all_vectors = p;
2242 ++n_vectors;
2243 return p;
2247 /* Allocate a vector with NSLOTS slots. */
2249 struct Lisp_Vector *
2250 allocate_vector (nslots)
2251 EMACS_INT nslots;
2253 struct Lisp_Vector *v = allocate_vectorlike (nslots, MEM_TYPE_VECTOR);
2254 v->size = nslots;
2255 return v;
2259 /* Allocate other vector-like structures. */
2261 struct Lisp_Hash_Table *
2262 allocate_hash_table ()
2264 EMACS_INT len = VECSIZE (struct Lisp_Hash_Table);
2265 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_HASH_TABLE);
2266 EMACS_INT i;
2268 v->size = len;
2269 for (i = 0; i < len; ++i)
2270 v->contents[i] = Qnil;
2272 return (struct Lisp_Hash_Table *) v;
2276 struct window *
2277 allocate_window ()
2279 EMACS_INT len = VECSIZE (struct window);
2280 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_WINDOW);
2281 EMACS_INT i;
2283 for (i = 0; i < len; ++i)
2284 v->contents[i] = Qnil;
2285 v->size = len;
2287 return (struct window *) v;
2291 struct frame *
2292 allocate_frame ()
2294 EMACS_INT len = VECSIZE (struct frame);
2295 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_FRAME);
2296 EMACS_INT i;
2298 for (i = 0; i < len; ++i)
2299 v->contents[i] = make_number (0);
2300 v->size = len;
2301 return (struct frame *) v;
2305 struct Lisp_Process *
2306 allocate_process ()
2308 EMACS_INT len = VECSIZE (struct Lisp_Process);
2309 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_PROCESS);
2310 EMACS_INT i;
2312 for (i = 0; i < len; ++i)
2313 v->contents[i] = Qnil;
2314 v->size = len;
2316 return (struct Lisp_Process *) v;
2320 struct Lisp_Vector *
2321 allocate_other_vector (len)
2322 EMACS_INT len;
2324 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_VECTOR);
2325 EMACS_INT i;
2327 for (i = 0; i < len; ++i)
2328 v->contents[i] = Qnil;
2329 v->size = len;
2331 return v;
2335 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
2336 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
2337 See also the function `vector'. */)
2338 (length, init)
2339 register Lisp_Object length, init;
2341 Lisp_Object vector;
2342 register EMACS_INT sizei;
2343 register int index;
2344 register struct Lisp_Vector *p;
2346 CHECK_NATNUM (length);
2347 sizei = XFASTINT (length);
2349 p = allocate_vector (sizei);
2350 for (index = 0; index < sizei; index++)
2351 p->contents[index] = init;
2353 XSETVECTOR (vector, p);
2354 return vector;
2358 DEFUN ("make-char-table", Fmake_char_table, Smake_char_table, 1, 2, 0,
2359 doc: /* Return a newly created char-table, with purpose PURPOSE.
2360 Each element is initialized to INIT, which defaults to nil.
2361 PURPOSE should be a symbol which has a `char-table-extra-slots' property.
2362 The property's value should be an integer between 0 and 10. */)
2363 (purpose, init)
2364 register Lisp_Object purpose, init;
2366 Lisp_Object vector;
2367 Lisp_Object n;
2368 CHECK_SYMBOL (purpose);
2369 n = Fget (purpose, Qchar_table_extra_slots);
2370 CHECK_NUMBER (n);
2371 if (XINT (n) < 0 || XINT (n) > 10)
2372 args_out_of_range (n, Qnil);
2373 /* Add 2 to the size for the defalt and parent slots. */
2374 vector = Fmake_vector (make_number (CHAR_TABLE_STANDARD_SLOTS + XINT (n)),
2375 init);
2376 XCHAR_TABLE (vector)->top = Qt;
2377 XCHAR_TABLE (vector)->parent = Qnil;
2378 XCHAR_TABLE (vector)->purpose = purpose;
2379 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
2380 return vector;
2384 /* Return a newly created sub char table with default value DEFALT.
2385 Since a sub char table does not appear as a top level Emacs Lisp
2386 object, we don't need a Lisp interface to make it. */
2388 Lisp_Object
2389 make_sub_char_table (defalt)
2390 Lisp_Object defalt;
2392 Lisp_Object vector
2393 = Fmake_vector (make_number (SUB_CHAR_TABLE_STANDARD_SLOTS), Qnil);
2394 XCHAR_TABLE (vector)->top = Qnil;
2395 XCHAR_TABLE (vector)->defalt = defalt;
2396 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
2397 return vector;
2401 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
2402 doc: /* Return a newly created vector with specified arguments as elements.
2403 Any number of arguments, even zero arguments, are allowed.
2404 usage: (vector &rest OBJECTS) */)
2405 (nargs, args)
2406 register int nargs;
2407 Lisp_Object *args;
2409 register Lisp_Object len, val;
2410 register int index;
2411 register struct Lisp_Vector *p;
2413 XSETFASTINT (len, nargs);
2414 val = Fmake_vector (len, Qnil);
2415 p = XVECTOR (val);
2416 for (index = 0; index < nargs; index++)
2417 p->contents[index] = args[index];
2418 return val;
2422 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
2423 doc: /* Create a byte-code object with specified arguments as elements.
2424 The arguments should be the arglist, bytecode-string, constant vector,
2425 stack size, (optional) doc string, and (optional) interactive spec.
2426 The first four arguments are required; at most six have any
2427 significance.
2428 usage: (make-byte-code &rest ELEMENTS) */)
2429 (nargs, args)
2430 register int nargs;
2431 Lisp_Object *args;
2433 register Lisp_Object len, val;
2434 register int index;
2435 register struct Lisp_Vector *p;
2437 XSETFASTINT (len, nargs);
2438 if (!NILP (Vpurify_flag))
2439 val = make_pure_vector ((EMACS_INT) nargs);
2440 else
2441 val = Fmake_vector (len, Qnil);
2443 if (STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
2444 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
2445 earlier because they produced a raw 8-bit string for byte-code
2446 and now such a byte-code string is loaded as multibyte while
2447 raw 8-bit characters converted to multibyte form. Thus, now we
2448 must convert them back to the original unibyte form. */
2449 args[1] = Fstring_as_unibyte (args[1]);
2451 p = XVECTOR (val);
2452 for (index = 0; index < nargs; index++)
2454 if (!NILP (Vpurify_flag))
2455 args[index] = Fpurecopy (args[index]);
2456 p->contents[index] = args[index];
2458 XSETCOMPILED (val, p);
2459 return val;
2464 /***********************************************************************
2465 Symbol Allocation
2466 ***********************************************************************/
2468 /* Each symbol_block is just under 1020 bytes long, since malloc
2469 really allocates in units of powers of two and uses 4 bytes for its
2470 own overhead. */
2472 #define SYMBOL_BLOCK_SIZE \
2473 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
2475 struct symbol_block
2477 struct symbol_block *next;
2478 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
2481 /* Current symbol block and index of first unused Lisp_Symbol
2482 structure in it. */
2484 struct symbol_block *symbol_block;
2485 int symbol_block_index;
2487 /* List of free symbols. */
2489 struct Lisp_Symbol *symbol_free_list;
2491 /* Total number of symbol blocks now in use. */
2493 int n_symbol_blocks;
2496 /* Initialize symbol allocation. */
2498 void
2499 init_symbol ()
2501 symbol_block = (struct symbol_block *) lisp_malloc (sizeof *symbol_block,
2502 MEM_TYPE_SYMBOL);
2503 symbol_block->next = 0;
2504 bzero ((char *) symbol_block->symbols, sizeof symbol_block->symbols);
2505 symbol_block_index = 0;
2506 symbol_free_list = 0;
2507 n_symbol_blocks = 1;
2511 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
2512 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
2513 Its value and function definition are void, and its property list is nil. */)
2514 (name)
2515 Lisp_Object name;
2517 register Lisp_Object val;
2518 register struct Lisp_Symbol *p;
2520 CHECK_STRING (name);
2522 if (symbol_free_list)
2524 XSETSYMBOL (val, symbol_free_list);
2525 symbol_free_list = *(struct Lisp_Symbol **)&symbol_free_list->value;
2527 else
2529 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
2531 struct symbol_block *new;
2532 new = (struct symbol_block *) lisp_malloc (sizeof *new,
2533 MEM_TYPE_SYMBOL);
2534 VALIDATE_LISP_STORAGE (new, sizeof *new);
2535 new->next = symbol_block;
2536 symbol_block = new;
2537 symbol_block_index = 0;
2538 n_symbol_blocks++;
2540 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index++]);
2543 p = XSYMBOL (val);
2544 p->xname = name;
2545 p->plist = Qnil;
2546 p->value = Qunbound;
2547 p->function = Qunbound;
2548 p->next = NULL;
2549 p->interned = SYMBOL_UNINTERNED;
2550 p->constant = 0;
2551 p->indirect_variable = 0;
2552 consing_since_gc += sizeof (struct Lisp_Symbol);
2553 symbols_consed++;
2554 return val;
2559 /***********************************************************************
2560 Marker (Misc) Allocation
2561 ***********************************************************************/
2563 /* Allocation of markers and other objects that share that structure.
2564 Works like allocation of conses. */
2566 #define MARKER_BLOCK_SIZE \
2567 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
2569 struct marker_block
2571 struct marker_block *next;
2572 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
2575 struct marker_block *marker_block;
2576 int marker_block_index;
2578 union Lisp_Misc *marker_free_list;
2580 /* Total number of marker blocks now in use. */
2582 int n_marker_blocks;
2584 void
2585 init_marker ()
2587 marker_block = (struct marker_block *) lisp_malloc (sizeof *marker_block,
2588 MEM_TYPE_MISC);
2589 marker_block->next = 0;
2590 bzero ((char *) marker_block->markers, sizeof marker_block->markers);
2591 marker_block_index = 0;
2592 marker_free_list = 0;
2593 n_marker_blocks = 1;
2596 /* Return a newly allocated Lisp_Misc object, with no substructure. */
2598 Lisp_Object
2599 allocate_misc ()
2601 Lisp_Object val;
2603 if (marker_free_list)
2605 XSETMISC (val, marker_free_list);
2606 marker_free_list = marker_free_list->u_free.chain;
2608 else
2610 if (marker_block_index == MARKER_BLOCK_SIZE)
2612 struct marker_block *new;
2613 new = (struct marker_block *) lisp_malloc (sizeof *new,
2614 MEM_TYPE_MISC);
2615 VALIDATE_LISP_STORAGE (new, sizeof *new);
2616 new->next = marker_block;
2617 marker_block = new;
2618 marker_block_index = 0;
2619 n_marker_blocks++;
2621 XSETMISC (val, &marker_block->markers[marker_block_index++]);
2624 consing_since_gc += sizeof (union Lisp_Misc);
2625 misc_objects_consed++;
2626 return val;
2629 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
2630 doc: /* Return a newly allocated marker which does not point at any place. */)
2633 register Lisp_Object val;
2634 register struct Lisp_Marker *p;
2636 val = allocate_misc ();
2637 XMISCTYPE (val) = Lisp_Misc_Marker;
2638 p = XMARKER (val);
2639 p->buffer = 0;
2640 p->bytepos = 0;
2641 p->charpos = 0;
2642 p->chain = Qnil;
2643 p->insertion_type = 0;
2644 return val;
2647 /* Put MARKER back on the free list after using it temporarily. */
2649 void
2650 free_marker (marker)
2651 Lisp_Object marker;
2653 unchain_marker (marker);
2655 XMISC (marker)->u_marker.type = Lisp_Misc_Free;
2656 XMISC (marker)->u_free.chain = marker_free_list;
2657 marker_free_list = XMISC (marker);
2659 total_free_markers++;
2663 /* Return a newly created vector or string with specified arguments as
2664 elements. If all the arguments are characters that can fit
2665 in a string of events, make a string; otherwise, make a vector.
2667 Any number of arguments, even zero arguments, are allowed. */
2669 Lisp_Object
2670 make_event_array (nargs, args)
2671 register int nargs;
2672 Lisp_Object *args;
2674 int i;
2676 for (i = 0; i < nargs; i++)
2677 /* The things that fit in a string
2678 are characters that are in 0...127,
2679 after discarding the meta bit and all the bits above it. */
2680 if (!INTEGERP (args[i])
2681 || (XUINT (args[i]) & ~(-CHAR_META)) >= 0200)
2682 return Fvector (nargs, args);
2684 /* Since the loop exited, we know that all the things in it are
2685 characters, so we can make a string. */
2687 Lisp_Object result;
2689 result = Fmake_string (make_number (nargs), make_number (0));
2690 for (i = 0; i < nargs; i++)
2692 SSET (result, i, XINT (args[i]));
2693 /* Move the meta bit to the right place for a string char. */
2694 if (XINT (args[i]) & CHAR_META)
2695 SSET (result, i, SREF (result, i) | 0x80);
2698 return result;
2704 /************************************************************************
2705 C Stack Marking
2706 ************************************************************************/
2708 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
2710 /* Conservative C stack marking requires a method to identify possibly
2711 live Lisp objects given a pointer value. We do this by keeping
2712 track of blocks of Lisp data that are allocated in a red-black tree
2713 (see also the comment of mem_node which is the type of nodes in
2714 that tree). Function lisp_malloc adds information for an allocated
2715 block to the red-black tree with calls to mem_insert, and function
2716 lisp_free removes it with mem_delete. Functions live_string_p etc
2717 call mem_find to lookup information about a given pointer in the
2718 tree, and use that to determine if the pointer points to a Lisp
2719 object or not. */
2721 /* Initialize this part of alloc.c. */
2723 static void
2724 mem_init ()
2726 mem_z.left = mem_z.right = MEM_NIL;
2727 mem_z.parent = NULL;
2728 mem_z.color = MEM_BLACK;
2729 mem_z.start = mem_z.end = NULL;
2730 mem_root = MEM_NIL;
2734 /* Value is a pointer to the mem_node containing START. Value is
2735 MEM_NIL if there is no node in the tree containing START. */
2737 static INLINE struct mem_node *
2738 mem_find (start)
2739 void *start;
2741 struct mem_node *p;
2743 if (start < min_heap_address || start > max_heap_address)
2744 return MEM_NIL;
2746 /* Make the search always successful to speed up the loop below. */
2747 mem_z.start = start;
2748 mem_z.end = (char *) start + 1;
2750 p = mem_root;
2751 while (start < p->start || start >= p->end)
2752 p = start < p->start ? p->left : p->right;
2753 return p;
2757 /* Insert a new node into the tree for a block of memory with start
2758 address START, end address END, and type TYPE. Value is a
2759 pointer to the node that was inserted. */
2761 static struct mem_node *
2762 mem_insert (start, end, type)
2763 void *start, *end;
2764 enum mem_type type;
2766 struct mem_node *c, *parent, *x;
2768 if (start < min_heap_address)
2769 min_heap_address = start;
2770 if (end > max_heap_address)
2771 max_heap_address = end;
2773 /* See where in the tree a node for START belongs. In this
2774 particular application, it shouldn't happen that a node is already
2775 present. For debugging purposes, let's check that. */
2776 c = mem_root;
2777 parent = NULL;
2779 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
2781 while (c != MEM_NIL)
2783 if (start >= c->start && start < c->end)
2784 abort ();
2785 parent = c;
2786 c = start < c->start ? c->left : c->right;
2789 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2791 while (c != MEM_NIL)
2793 parent = c;
2794 c = start < c->start ? c->left : c->right;
2797 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2799 /* Create a new node. */
2800 #ifdef GC_MALLOC_CHECK
2801 x = (struct mem_node *) _malloc_internal (sizeof *x);
2802 if (x == NULL)
2803 abort ();
2804 #else
2805 x = (struct mem_node *) xmalloc (sizeof *x);
2806 #endif
2807 x->start = start;
2808 x->end = end;
2809 x->type = type;
2810 x->parent = parent;
2811 x->left = x->right = MEM_NIL;
2812 x->color = MEM_RED;
2814 /* Insert it as child of PARENT or install it as root. */
2815 if (parent)
2817 if (start < parent->start)
2818 parent->left = x;
2819 else
2820 parent->right = x;
2822 else
2823 mem_root = x;
2825 /* Re-establish red-black tree properties. */
2826 mem_insert_fixup (x);
2828 return x;
2832 /* Re-establish the red-black properties of the tree, and thereby
2833 balance the tree, after node X has been inserted; X is always red. */
2835 static void
2836 mem_insert_fixup (x)
2837 struct mem_node *x;
2839 while (x != mem_root && x->parent->color == MEM_RED)
2841 /* X is red and its parent is red. This is a violation of
2842 red-black tree property #3. */
2844 if (x->parent == x->parent->parent->left)
2846 /* We're on the left side of our grandparent, and Y is our
2847 "uncle". */
2848 struct mem_node *y = x->parent->parent->right;
2850 if (y->color == MEM_RED)
2852 /* Uncle and parent are red but should be black because
2853 X is red. Change the colors accordingly and proceed
2854 with the grandparent. */
2855 x->parent->color = MEM_BLACK;
2856 y->color = MEM_BLACK;
2857 x->parent->parent->color = MEM_RED;
2858 x = x->parent->parent;
2860 else
2862 /* Parent and uncle have different colors; parent is
2863 red, uncle is black. */
2864 if (x == x->parent->right)
2866 x = x->parent;
2867 mem_rotate_left (x);
2870 x->parent->color = MEM_BLACK;
2871 x->parent->parent->color = MEM_RED;
2872 mem_rotate_right (x->parent->parent);
2875 else
2877 /* This is the symmetrical case of above. */
2878 struct mem_node *y = x->parent->parent->left;
2880 if (y->color == MEM_RED)
2882 x->parent->color = MEM_BLACK;
2883 y->color = MEM_BLACK;
2884 x->parent->parent->color = MEM_RED;
2885 x = x->parent->parent;
2887 else
2889 if (x == x->parent->left)
2891 x = x->parent;
2892 mem_rotate_right (x);
2895 x->parent->color = MEM_BLACK;
2896 x->parent->parent->color = MEM_RED;
2897 mem_rotate_left (x->parent->parent);
2902 /* The root may have been changed to red due to the algorithm. Set
2903 it to black so that property #5 is satisfied. */
2904 mem_root->color = MEM_BLACK;
2908 /* (x) (y)
2909 / \ / \
2910 a (y) ===> (x) c
2911 / \ / \
2912 b c a b */
2914 static void
2915 mem_rotate_left (x)
2916 struct mem_node *x;
2918 struct mem_node *y;
2920 /* Turn y's left sub-tree into x's right sub-tree. */
2921 y = x->right;
2922 x->right = y->left;
2923 if (y->left != MEM_NIL)
2924 y->left->parent = x;
2926 /* Y's parent was x's parent. */
2927 if (y != MEM_NIL)
2928 y->parent = x->parent;
2930 /* Get the parent to point to y instead of x. */
2931 if (x->parent)
2933 if (x == x->parent->left)
2934 x->parent->left = y;
2935 else
2936 x->parent->right = y;
2938 else
2939 mem_root = y;
2941 /* Put x on y's left. */
2942 y->left = x;
2943 if (x != MEM_NIL)
2944 x->parent = y;
2948 /* (x) (Y)
2949 / \ / \
2950 (y) c ===> a (x)
2951 / \ / \
2952 a b b c */
2954 static void
2955 mem_rotate_right (x)
2956 struct mem_node *x;
2958 struct mem_node *y = x->left;
2960 x->left = y->right;
2961 if (y->right != MEM_NIL)
2962 y->right->parent = x;
2964 if (y != MEM_NIL)
2965 y->parent = x->parent;
2966 if (x->parent)
2968 if (x == x->parent->right)
2969 x->parent->right = y;
2970 else
2971 x->parent->left = y;
2973 else
2974 mem_root = y;
2976 y->right = x;
2977 if (x != MEM_NIL)
2978 x->parent = y;
2982 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
2984 static void
2985 mem_delete (z)
2986 struct mem_node *z;
2988 struct mem_node *x, *y;
2990 if (!z || z == MEM_NIL)
2991 return;
2993 if (z->left == MEM_NIL || z->right == MEM_NIL)
2994 y = z;
2995 else
2997 y = z->right;
2998 while (y->left != MEM_NIL)
2999 y = y->left;
3002 if (y->left != MEM_NIL)
3003 x = y->left;
3004 else
3005 x = y->right;
3007 x->parent = y->parent;
3008 if (y->parent)
3010 if (y == y->parent->left)
3011 y->parent->left = x;
3012 else
3013 y->parent->right = x;
3015 else
3016 mem_root = x;
3018 if (y != z)
3020 z->start = y->start;
3021 z->end = y->end;
3022 z->type = y->type;
3025 if (y->color == MEM_BLACK)
3026 mem_delete_fixup (x);
3028 #ifdef GC_MALLOC_CHECK
3029 _free_internal (y);
3030 #else
3031 xfree (y);
3032 #endif
3036 /* Re-establish the red-black properties of the tree, after a
3037 deletion. */
3039 static void
3040 mem_delete_fixup (x)
3041 struct mem_node *x;
3043 while (x != mem_root && x->color == MEM_BLACK)
3045 if (x == x->parent->left)
3047 struct mem_node *w = x->parent->right;
3049 if (w->color == MEM_RED)
3051 w->color = MEM_BLACK;
3052 x->parent->color = MEM_RED;
3053 mem_rotate_left (x->parent);
3054 w = x->parent->right;
3057 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
3059 w->color = MEM_RED;
3060 x = x->parent;
3062 else
3064 if (w->right->color == MEM_BLACK)
3066 w->left->color = MEM_BLACK;
3067 w->color = MEM_RED;
3068 mem_rotate_right (w);
3069 w = x->parent->right;
3071 w->color = x->parent->color;
3072 x->parent->color = MEM_BLACK;
3073 w->right->color = MEM_BLACK;
3074 mem_rotate_left (x->parent);
3075 x = mem_root;
3078 else
3080 struct mem_node *w = x->parent->left;
3082 if (w->color == MEM_RED)
3084 w->color = MEM_BLACK;
3085 x->parent->color = MEM_RED;
3086 mem_rotate_right (x->parent);
3087 w = x->parent->left;
3090 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
3092 w->color = MEM_RED;
3093 x = x->parent;
3095 else
3097 if (w->left->color == MEM_BLACK)
3099 w->right->color = MEM_BLACK;
3100 w->color = MEM_RED;
3101 mem_rotate_left (w);
3102 w = x->parent->left;
3105 w->color = x->parent->color;
3106 x->parent->color = MEM_BLACK;
3107 w->left->color = MEM_BLACK;
3108 mem_rotate_right (x->parent);
3109 x = mem_root;
3114 x->color = MEM_BLACK;
3118 /* Value is non-zero if P is a pointer to a live Lisp string on
3119 the heap. M is a pointer to the mem_block for P. */
3121 static INLINE int
3122 live_string_p (m, p)
3123 struct mem_node *m;
3124 void *p;
3126 if (m->type == MEM_TYPE_STRING)
3128 struct string_block *b = (struct string_block *) m->start;
3129 int offset = (char *) p - (char *) &b->strings[0];
3131 /* P must point to the start of a Lisp_String structure, and it
3132 must not be on the free-list. */
3133 return (offset >= 0
3134 && offset % sizeof b->strings[0] == 0
3135 && ((struct Lisp_String *) p)->data != NULL);
3137 else
3138 return 0;
3142 /* Value is non-zero if P is a pointer to a live Lisp cons on
3143 the heap. M is a pointer to the mem_block for P. */
3145 static INLINE int
3146 live_cons_p (m, p)
3147 struct mem_node *m;
3148 void *p;
3150 if (m->type == MEM_TYPE_CONS)
3152 struct cons_block *b = (struct cons_block *) m->start;
3153 int offset = (char *) p - (char *) &b->conses[0];
3155 /* P must point to the start of a Lisp_Cons, not be
3156 one of the unused cells in the current cons block,
3157 and not be on the free-list. */
3158 return (offset >= 0
3159 && offset % sizeof b->conses[0] == 0
3160 && (b != cons_block
3161 || offset / sizeof b->conses[0] < cons_block_index)
3162 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
3164 else
3165 return 0;
3169 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3170 the heap. M is a pointer to the mem_block for P. */
3172 static INLINE int
3173 live_symbol_p (m, p)
3174 struct mem_node *m;
3175 void *p;
3177 if (m->type == MEM_TYPE_SYMBOL)
3179 struct symbol_block *b = (struct symbol_block *) m->start;
3180 int offset = (char *) p - (char *) &b->symbols[0];
3182 /* P must point to the start of a Lisp_Symbol, not be
3183 one of the unused cells in the current symbol block,
3184 and not be on the free-list. */
3185 return (offset >= 0
3186 && offset % sizeof b->symbols[0] == 0
3187 && (b != symbol_block
3188 || offset / sizeof b->symbols[0] < symbol_block_index)
3189 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
3191 else
3192 return 0;
3196 /* Value is non-zero if P is a pointer to a live Lisp float on
3197 the heap. M is a pointer to the mem_block for P. */
3199 static INLINE int
3200 live_float_p (m, p)
3201 struct mem_node *m;
3202 void *p;
3204 if (m->type == MEM_TYPE_FLOAT)
3206 struct float_block *b = (struct float_block *) m->start;
3207 int offset = (char *) p - (char *) &b->floats[0];
3209 /* P must point to the start of a Lisp_Float, not be
3210 one of the unused cells in the current float block,
3211 and not be on the free-list. */
3212 return (offset >= 0
3213 && offset % sizeof b->floats[0] == 0
3214 && (b != float_block
3215 || offset / sizeof b->floats[0] < float_block_index)
3216 && !EQ (((struct Lisp_Float *) p)->type, Vdead));
3218 else
3219 return 0;
3223 /* Value is non-zero if P is a pointer to a live Lisp Misc on
3224 the heap. M is a pointer to the mem_block for P. */
3226 static INLINE int
3227 live_misc_p (m, p)
3228 struct mem_node *m;
3229 void *p;
3231 if (m->type == MEM_TYPE_MISC)
3233 struct marker_block *b = (struct marker_block *) m->start;
3234 int offset = (char *) p - (char *) &b->markers[0];
3236 /* P must point to the start of a Lisp_Misc, not be
3237 one of the unused cells in the current misc block,
3238 and not be on the free-list. */
3239 return (offset >= 0
3240 && offset % sizeof b->markers[0] == 0
3241 && (b != marker_block
3242 || offset / sizeof b->markers[0] < marker_block_index)
3243 && ((union Lisp_Misc *) p)->u_marker.type != Lisp_Misc_Free);
3245 else
3246 return 0;
3250 /* Value is non-zero if P is a pointer to a live vector-like object.
3251 M is a pointer to the mem_block for P. */
3253 static INLINE int
3254 live_vector_p (m, p)
3255 struct mem_node *m;
3256 void *p;
3258 return (p == m->start
3259 && m->type >= MEM_TYPE_VECTOR
3260 && m->type <= MEM_TYPE_WINDOW);
3264 /* Value is non-zero of P is a pointer to a live buffer. M is a
3265 pointer to the mem_block for P. */
3267 static INLINE int
3268 live_buffer_p (m, p)
3269 struct mem_node *m;
3270 void *p;
3272 /* P must point to the start of the block, and the buffer
3273 must not have been killed. */
3274 return (m->type == MEM_TYPE_BUFFER
3275 && p == m->start
3276 && !NILP (((struct buffer *) p)->name));
3279 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
3281 #if GC_MARK_STACK
3283 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3285 /* Array of objects that are kept alive because the C stack contains
3286 a pattern that looks like a reference to them . */
3288 #define MAX_ZOMBIES 10
3289 static Lisp_Object zombies[MAX_ZOMBIES];
3291 /* Number of zombie objects. */
3293 static int nzombies;
3295 /* Number of garbage collections. */
3297 static int ngcs;
3299 /* Average percentage of zombies per collection. */
3301 static double avg_zombies;
3303 /* Max. number of live and zombie objects. */
3305 static int max_live, max_zombies;
3307 /* Average number of live objects per GC. */
3309 static double avg_live;
3311 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
3312 doc: /* Show information about live and zombie objects. */)
3315 Lisp_Object args[7];
3316 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d");
3317 args[1] = make_number (ngcs);
3318 args[2] = make_float (avg_live);
3319 args[3] = make_float (avg_zombies);
3320 args[4] = make_float (avg_zombies / avg_live / 100);
3321 args[5] = make_number (max_live);
3322 args[6] = make_number (max_zombies);
3323 return Fmessage (7, args);
3326 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3329 /* Mark OBJ if we can prove it's a Lisp_Object. */
3331 static INLINE void
3332 mark_maybe_object (obj)
3333 Lisp_Object obj;
3335 void *po = (void *) XPNTR (obj);
3336 struct mem_node *m = mem_find (po);
3338 if (m != MEM_NIL)
3340 int mark_p = 0;
3342 switch (XGCTYPE (obj))
3344 case Lisp_String:
3345 mark_p = (live_string_p (m, po)
3346 && !STRING_MARKED_P ((struct Lisp_String *) po));
3347 break;
3349 case Lisp_Cons:
3350 mark_p = (live_cons_p (m, po)
3351 && !XMARKBIT (XCONS (obj)->car));
3352 break;
3354 case Lisp_Symbol:
3355 mark_p = (live_symbol_p (m, po)
3356 && !XMARKBIT (XSYMBOL (obj)->plist));
3357 break;
3359 case Lisp_Float:
3360 mark_p = (live_float_p (m, po)
3361 && !XMARKBIT (XFLOAT (obj)->type));
3362 break;
3364 case Lisp_Vectorlike:
3365 /* Note: can't check GC_BUFFERP before we know it's a
3366 buffer because checking that dereferences the pointer
3367 PO which might point anywhere. */
3368 if (live_vector_p (m, po))
3369 mark_p = (!GC_SUBRP (obj)
3370 && !(XVECTOR (obj)->size & ARRAY_MARK_FLAG));
3371 else if (live_buffer_p (m, po))
3372 mark_p = GC_BUFFERP (obj) && !XMARKBIT (XBUFFER (obj)->name);
3373 break;
3375 case Lisp_Misc:
3376 if (live_misc_p (m, po))
3378 switch (XMISCTYPE (obj))
3380 case Lisp_Misc_Marker:
3381 mark_p = !XMARKBIT (XMARKER (obj)->chain);
3382 break;
3384 case Lisp_Misc_Buffer_Local_Value:
3385 case Lisp_Misc_Some_Buffer_Local_Value:
3386 mark_p = !XMARKBIT (XBUFFER_LOCAL_VALUE (obj)->realvalue);
3387 break;
3389 case Lisp_Misc_Overlay:
3390 mark_p = !XMARKBIT (XOVERLAY (obj)->plist);
3391 break;
3394 break;
3396 case Lisp_Int:
3397 case Lisp_Type_Limit:
3398 break;
3401 if (mark_p)
3403 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3404 if (nzombies < MAX_ZOMBIES)
3405 zombies[nzombies] = *p;
3406 ++nzombies;
3407 #endif
3408 mark_object (&obj);
3414 /* If P points to Lisp data, mark that as live if it isn't already
3415 marked. */
3417 static INLINE void
3418 mark_maybe_pointer (p)
3419 void *p;
3421 struct mem_node *m;
3423 /* Quickly rule out some values which can't point to Lisp data. We
3424 assume that Lisp data is aligned on even addresses. */
3425 if ((EMACS_INT) p & 1)
3426 return;
3428 m = mem_find (p);
3429 if (m != MEM_NIL)
3431 Lisp_Object obj = Qnil;
3433 switch (m->type)
3435 case MEM_TYPE_NON_LISP:
3436 /* Nothing to do; not a pointer to Lisp memory. */
3437 break;
3439 case MEM_TYPE_BUFFER:
3440 if (live_buffer_p (m, p)
3441 && !XMARKBIT (((struct buffer *) p)->name))
3442 XSETVECTOR (obj, p);
3443 break;
3445 case MEM_TYPE_CONS:
3446 if (live_cons_p (m, p)
3447 && !XMARKBIT (((struct Lisp_Cons *) p)->car))
3448 XSETCONS (obj, p);
3449 break;
3451 case MEM_TYPE_STRING:
3452 if (live_string_p (m, p)
3453 && !STRING_MARKED_P ((struct Lisp_String *) p))
3454 XSETSTRING (obj, p);
3455 break;
3457 case MEM_TYPE_MISC:
3458 if (live_misc_p (m, p))
3460 Lisp_Object tem;
3461 XSETMISC (tem, p);
3463 switch (XMISCTYPE (tem))
3465 case Lisp_Misc_Marker:
3466 if (!XMARKBIT (XMARKER (tem)->chain))
3467 obj = tem;
3468 break;
3470 case Lisp_Misc_Buffer_Local_Value:
3471 case Lisp_Misc_Some_Buffer_Local_Value:
3472 if (!XMARKBIT (XBUFFER_LOCAL_VALUE (tem)->realvalue))
3473 obj = tem;
3474 break;
3476 case Lisp_Misc_Overlay:
3477 if (!XMARKBIT (XOVERLAY (tem)->plist))
3478 obj = tem;
3479 break;
3482 break;
3484 case MEM_TYPE_SYMBOL:
3485 if (live_symbol_p (m, p)
3486 && !XMARKBIT (((struct Lisp_Symbol *) p)->plist))
3487 XSETSYMBOL (obj, p);
3488 break;
3490 case MEM_TYPE_FLOAT:
3491 if (live_float_p (m, p)
3492 && !XMARKBIT (((struct Lisp_Float *) p)->type))
3493 XSETFLOAT (obj, p);
3494 break;
3496 case MEM_TYPE_VECTOR:
3497 case MEM_TYPE_PROCESS:
3498 case MEM_TYPE_HASH_TABLE:
3499 case MEM_TYPE_FRAME:
3500 case MEM_TYPE_WINDOW:
3501 if (live_vector_p (m, p))
3503 Lisp_Object tem;
3504 XSETVECTOR (tem, p);
3505 if (!GC_SUBRP (tem)
3506 && !(XVECTOR (tem)->size & ARRAY_MARK_FLAG))
3507 obj = tem;
3509 break;
3511 default:
3512 abort ();
3515 if (!GC_NILP (obj))
3516 mark_object (&obj);
3521 /* Mark Lisp objects referenced from the address range START..END. */
3523 static void
3524 mark_memory (start, end)
3525 void *start, *end;
3527 Lisp_Object *p;
3528 void **pp;
3530 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3531 nzombies = 0;
3532 #endif
3534 /* Make START the pointer to the start of the memory region,
3535 if it isn't already. */
3536 if (end < start)
3538 void *tem = start;
3539 start = end;
3540 end = tem;
3543 /* Mark Lisp_Objects. */
3544 for (p = (Lisp_Object *) start; (void *) p < end; ++p)
3545 mark_maybe_object (*p);
3547 /* Mark Lisp data pointed to. This is necessary because, in some
3548 situations, the C compiler optimizes Lisp objects away, so that
3549 only a pointer to them remains. Example:
3551 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
3554 Lisp_Object obj = build_string ("test");
3555 struct Lisp_String *s = XSTRING (obj);
3556 Fgarbage_collect ();
3557 fprintf (stderr, "test `%s'\n", s->data);
3558 return Qnil;
3561 Here, `obj' isn't really used, and the compiler optimizes it
3562 away. The only reference to the life string is through the
3563 pointer `s'. */
3565 for (pp = (void **) start; (void *) pp < end; ++pp)
3566 mark_maybe_pointer (*pp);
3570 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
3572 static int setjmp_tested_p, longjmps_done;
3574 #define SETJMP_WILL_LIKELY_WORK "\
3576 Emacs garbage collector has been changed to use conservative stack\n\
3577 marking. Emacs has determined that the method it uses to do the\n\
3578 marking will likely work on your system, but this isn't sure.\n\
3580 If you are a system-programmer, or can get the help of a local wizard\n\
3581 who is, please take a look at the function mark_stack in alloc.c, and\n\
3582 verify that the methods used are appropriate for your system.\n\
3584 Please mail the result to <emacs-devel@gnu.org>.\n\
3587 #define SETJMP_WILL_NOT_WORK "\
3589 Emacs garbage collector has been changed to use conservative stack\n\
3590 marking. Emacs has determined that the default method it uses to do the\n\
3591 marking will not work on your system. We will need a system-dependent\n\
3592 solution for your system.\n\
3594 Please take a look at the function mark_stack in alloc.c, and\n\
3595 try to find a way to make it work on your system.\n\
3596 Please mail the result to <emacs-devel@gnu.org>.\n\
3600 /* Perform a quick check if it looks like setjmp saves registers in a
3601 jmp_buf. Print a message to stderr saying so. When this test
3602 succeeds, this is _not_ a proof that setjmp is sufficient for
3603 conservative stack marking. Only the sources or a disassembly
3604 can prove that. */
3606 static void
3607 test_setjmp ()
3609 char buf[10];
3610 register int x;
3611 jmp_buf jbuf;
3612 int result = 0;
3614 /* Arrange for X to be put in a register. */
3615 sprintf (buf, "1");
3616 x = strlen (buf);
3617 x = 2 * x - 1;
3619 setjmp (jbuf);
3620 if (longjmps_done == 1)
3622 /* Came here after the longjmp at the end of the function.
3624 If x == 1, the longjmp has restored the register to its
3625 value before the setjmp, and we can hope that setjmp
3626 saves all such registers in the jmp_buf, although that
3627 isn't sure.
3629 For other values of X, either something really strange is
3630 taking place, or the setjmp just didn't save the register. */
3632 if (x == 1)
3633 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
3634 else
3636 fprintf (stderr, SETJMP_WILL_NOT_WORK);
3637 exit (1);
3641 ++longjmps_done;
3642 x = 2;
3643 if (longjmps_done == 1)
3644 longjmp (jbuf, 1);
3647 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
3650 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
3652 /* Abort if anything GCPRO'd doesn't survive the GC. */
3654 static void
3655 check_gcpros ()
3657 struct gcpro *p;
3658 int i;
3660 for (p = gcprolist; p; p = p->next)
3661 for (i = 0; i < p->nvars; ++i)
3662 if (!survives_gc_p (p->var[i]))
3663 abort ();
3666 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3668 static void
3669 dump_zombies ()
3671 int i;
3673 fprintf (stderr, "\nZombies kept alive = %d:\n", nzombies);
3674 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
3676 fprintf (stderr, " %d = ", i);
3677 debug_print (zombies[i]);
3681 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3684 /* Mark live Lisp objects on the C stack.
3686 There are several system-dependent problems to consider when
3687 porting this to new architectures:
3689 Processor Registers
3691 We have to mark Lisp objects in CPU registers that can hold local
3692 variables or are used to pass parameters.
3694 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
3695 something that either saves relevant registers on the stack, or
3696 calls mark_maybe_object passing it each register's contents.
3698 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
3699 implementation assumes that calling setjmp saves registers we need
3700 to see in a jmp_buf which itself lies on the stack. This doesn't
3701 have to be true! It must be verified for each system, possibly
3702 by taking a look at the source code of setjmp.
3704 Stack Layout
3706 Architectures differ in the way their processor stack is organized.
3707 For example, the stack might look like this
3709 +----------------+
3710 | Lisp_Object | size = 4
3711 +----------------+
3712 | something else | size = 2
3713 +----------------+
3714 | Lisp_Object | size = 4
3715 +----------------+
3716 | ... |
3718 In such a case, not every Lisp_Object will be aligned equally. To
3719 find all Lisp_Object on the stack it won't be sufficient to walk
3720 the stack in steps of 4 bytes. Instead, two passes will be
3721 necessary, one starting at the start of the stack, and a second
3722 pass starting at the start of the stack + 2. Likewise, if the
3723 minimal alignment of Lisp_Objects on the stack is 1, four passes
3724 would be necessary, each one starting with one byte more offset
3725 from the stack start.
3727 The current code assumes by default that Lisp_Objects are aligned
3728 equally on the stack. */
3730 static void
3731 mark_stack ()
3733 int i;
3734 jmp_buf j;
3735 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
3736 void *end;
3738 /* This trick flushes the register windows so that all the state of
3739 the process is contained in the stack. */
3740 #ifdef sparc
3741 asm ("ta 3");
3742 #endif
3744 /* Save registers that we need to see on the stack. We need to see
3745 registers used to hold register variables and registers used to
3746 pass parameters. */
3747 #ifdef GC_SAVE_REGISTERS_ON_STACK
3748 GC_SAVE_REGISTERS_ON_STACK (end);
3749 #else /* not GC_SAVE_REGISTERS_ON_STACK */
3751 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
3752 setjmp will definitely work, test it
3753 and print a message with the result
3754 of the test. */
3755 if (!setjmp_tested_p)
3757 setjmp_tested_p = 1;
3758 test_setjmp ();
3760 #endif /* GC_SETJMP_WORKS */
3762 setjmp (j);
3763 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
3764 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
3766 /* This assumes that the stack is a contiguous region in memory. If
3767 that's not the case, something has to be done here to iterate
3768 over the stack segments. */
3769 #ifndef GC_LISP_OBJECT_ALIGNMENT
3770 #define GC_LISP_OBJECT_ALIGNMENT sizeof (Lisp_Object)
3771 #endif
3772 for (i = 0; i < sizeof (Lisp_Object); i += GC_LISP_OBJECT_ALIGNMENT)
3773 mark_memory ((char *) stack_base + i, end);
3775 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
3776 check_gcpros ();
3777 #endif
3781 #endif /* GC_MARK_STACK != 0 */
3785 /***********************************************************************
3786 Pure Storage Management
3787 ***********************************************************************/
3789 /* Allocate room for SIZE bytes from pure Lisp storage and return a
3790 pointer to it. TYPE is the Lisp type for which the memory is
3791 allocated. TYPE < 0 means it's not used for a Lisp object.
3793 If store_pure_type_info is set and TYPE is >= 0, the type of
3794 the allocated object is recorded in pure_types. */
3796 static POINTER_TYPE *
3797 pure_alloc (size, type)
3798 size_t size;
3799 int type;
3801 size_t nbytes;
3802 POINTER_TYPE *result;
3803 char *beg = purebeg;
3805 /* Give Lisp_Floats an extra alignment. */
3806 if (type == Lisp_Float)
3808 size_t alignment;
3809 #if defined __GNUC__ && __GNUC__ >= 2
3810 alignment = __alignof (struct Lisp_Float);
3811 #else
3812 alignment = sizeof (struct Lisp_Float);
3813 #endif
3814 pure_bytes_used = ALIGN (pure_bytes_used, alignment);
3817 nbytes = ALIGN (size, sizeof (EMACS_INT));
3819 if (pure_bytes_used + nbytes > pure_size)
3821 /* Don't allocate a large amount here,
3822 because it might get mmap'd and then its address
3823 might not be usable. */
3824 beg = purebeg = (char *) xmalloc (10000);
3825 pure_size = 10000;
3826 pure_bytes_used_before_overflow += pure_bytes_used;
3827 pure_bytes_used = 0;
3830 result = (POINTER_TYPE *) (beg + pure_bytes_used);
3831 pure_bytes_used += nbytes;
3832 return result;
3836 /* Print a warning if PURESIZE is too small. */
3838 void
3839 check_pure_size ()
3841 if (pure_bytes_used_before_overflow)
3842 message ("Pure Lisp storage overflow (approx. %d bytes needed)",
3843 (int) (pure_bytes_used + pure_bytes_used_before_overflow));
3847 /* Return a string allocated in pure space. DATA is a buffer holding
3848 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
3849 non-zero means make the result string multibyte.
3851 Must get an error if pure storage is full, since if it cannot hold
3852 a large string it may be able to hold conses that point to that
3853 string; then the string is not protected from gc. */
3855 Lisp_Object
3856 make_pure_string (data, nchars, nbytes, multibyte)
3857 char *data;
3858 int nchars, nbytes;
3859 int multibyte;
3861 Lisp_Object string;
3862 struct Lisp_String *s;
3864 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
3865 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
3866 s->size = nchars;
3867 s->size_byte = multibyte ? nbytes : -1;
3868 bcopy (data, s->data, nbytes);
3869 s->data[nbytes] = '\0';
3870 s->intervals = NULL_INTERVAL;
3871 XSETSTRING (string, s);
3872 return string;
3876 /* Return a cons allocated from pure space. Give it pure copies
3877 of CAR as car and CDR as cdr. */
3879 Lisp_Object
3880 pure_cons (car, cdr)
3881 Lisp_Object car, cdr;
3883 register Lisp_Object new;
3884 struct Lisp_Cons *p;
3886 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
3887 XSETCONS (new, p);
3888 XSETCAR (new, Fpurecopy (car));
3889 XSETCDR (new, Fpurecopy (cdr));
3890 return new;
3894 /* Value is a float object with value NUM allocated from pure space. */
3896 Lisp_Object
3897 make_pure_float (num)
3898 double num;
3900 register Lisp_Object new;
3901 struct Lisp_Float *p;
3903 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
3904 XSETFLOAT (new, p);
3905 XFLOAT_DATA (new) = num;
3906 return new;
3910 /* Return a vector with room for LEN Lisp_Objects allocated from
3911 pure space. */
3913 Lisp_Object
3914 make_pure_vector (len)
3915 EMACS_INT len;
3917 Lisp_Object new;
3918 struct Lisp_Vector *p;
3919 size_t size = sizeof *p + (len - 1) * sizeof (Lisp_Object);
3921 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
3922 XSETVECTOR (new, p);
3923 XVECTOR (new)->size = len;
3924 return new;
3928 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
3929 doc: /* Make a copy of OBJECT in pure storage.
3930 Recursively copies contents of vectors and cons cells.
3931 Does not copy symbols. Copies strings without text properties. */)
3932 (obj)
3933 register Lisp_Object obj;
3935 if (NILP (Vpurify_flag))
3936 return obj;
3938 if (PURE_POINTER_P (XPNTR (obj)))
3939 return obj;
3941 if (CONSP (obj))
3942 return pure_cons (XCAR (obj), XCDR (obj));
3943 else if (FLOATP (obj))
3944 return make_pure_float (XFLOAT_DATA (obj));
3945 else if (STRINGP (obj))
3946 return make_pure_string (SDATA (obj), SCHARS (obj),
3947 SBYTES (obj),
3948 STRING_MULTIBYTE (obj));
3949 else if (COMPILEDP (obj) || VECTORP (obj))
3951 register struct Lisp_Vector *vec;
3952 register int i, size;
3954 size = XVECTOR (obj)->size;
3955 if (size & PSEUDOVECTOR_FLAG)
3956 size &= PSEUDOVECTOR_SIZE_MASK;
3957 vec = XVECTOR (make_pure_vector ((EMACS_INT) size));
3958 for (i = 0; i < size; i++)
3959 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
3960 if (COMPILEDP (obj))
3961 XSETCOMPILED (obj, vec);
3962 else
3963 XSETVECTOR (obj, vec);
3964 return obj;
3966 else if (MARKERP (obj))
3967 error ("Attempt to copy a marker to pure storage");
3969 return obj;
3974 /***********************************************************************
3975 Protection from GC
3976 ***********************************************************************/
3978 /* Put an entry in staticvec, pointing at the variable with address
3979 VARADDRESS. */
3981 void
3982 staticpro (varaddress)
3983 Lisp_Object *varaddress;
3985 staticvec[staticidx++] = varaddress;
3986 if (staticidx >= NSTATICS)
3987 abort ();
3990 struct catchtag
3992 Lisp_Object tag;
3993 Lisp_Object val;
3994 struct catchtag *next;
3997 struct backtrace
3999 struct backtrace *next;
4000 Lisp_Object *function;
4001 Lisp_Object *args; /* Points to vector of args. */
4002 int nargs; /* Length of vector. */
4003 /* If nargs is UNEVALLED, args points to slot holding list of
4004 unevalled args. */
4005 char evalargs;
4010 /***********************************************************************
4011 Protection from GC
4012 ***********************************************************************/
4014 /* Temporarily prevent garbage collection. */
4017 inhibit_garbage_collection ()
4019 int count = SPECPDL_INDEX ();
4020 int nbits = min (VALBITS, BITS_PER_INT);
4022 specbind (Qgc_cons_threshold, make_number (((EMACS_INT) 1 << (nbits - 1)) - 1));
4023 return count;
4027 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
4028 doc: /* Reclaim storage for Lisp objects no longer needed.
4029 Returns info on amount of space in use:
4030 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
4031 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
4032 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)
4033 (USED-STRINGS . FREE-STRINGS))
4034 Garbage collection happens automatically if you cons more than
4035 `gc-cons-threshold' bytes of Lisp data since previous garbage collection. */)
4038 register struct gcpro *tail;
4039 register struct specbinding *bind;
4040 struct catchtag *catch;
4041 struct handler *handler;
4042 register struct backtrace *backlist;
4043 char stack_top_variable;
4044 register int i;
4045 int message_p;
4046 Lisp_Object total[8];
4047 int count = SPECPDL_INDEX ();
4049 /* Can't GC if pure storage overflowed because we can't determine
4050 if something is a pure object or not. */
4051 if (pure_bytes_used_before_overflow)
4052 return Qnil;
4054 /* In case user calls debug_print during GC,
4055 don't let that cause a recursive GC. */
4056 consing_since_gc = 0;
4058 /* Save what's currently displayed in the echo area. */
4059 message_p = push_message ();
4060 record_unwind_protect (pop_message_unwind, Qnil);
4062 /* Save a copy of the contents of the stack, for debugging. */
4063 #if MAX_SAVE_STACK > 0
4064 if (NILP (Vpurify_flag))
4066 i = &stack_top_variable - stack_bottom;
4067 if (i < 0) i = -i;
4068 if (i < MAX_SAVE_STACK)
4070 if (stack_copy == 0)
4071 stack_copy = (char *) xmalloc (stack_copy_size = i);
4072 else if (stack_copy_size < i)
4073 stack_copy = (char *) xrealloc (stack_copy, (stack_copy_size = i));
4074 if (stack_copy)
4076 if ((EMACS_INT) (&stack_top_variable - stack_bottom) > 0)
4077 bcopy (stack_bottom, stack_copy, i);
4078 else
4079 bcopy (&stack_top_variable, stack_copy, i);
4083 #endif /* MAX_SAVE_STACK > 0 */
4085 if (garbage_collection_messages)
4086 message1_nolog ("Garbage collecting...");
4088 BLOCK_INPUT;
4090 shrink_regexp_cache ();
4092 /* Don't keep undo information around forever. */
4094 register struct buffer *nextb = all_buffers;
4096 while (nextb)
4098 /* If a buffer's undo list is Qt, that means that undo is
4099 turned off in that buffer. Calling truncate_undo_list on
4100 Qt tends to return NULL, which effectively turns undo back on.
4101 So don't call truncate_undo_list if undo_list is Qt. */
4102 if (! EQ (nextb->undo_list, Qt))
4103 nextb->undo_list
4104 = truncate_undo_list (nextb->undo_list, undo_limit,
4105 undo_strong_limit);
4107 /* Shrink buffer gaps, but skip indirect and dead buffers. */
4108 if (nextb->base_buffer == 0 && !NILP (nextb->name))
4110 /* If a buffer's gap size is more than 10% of the buffer
4111 size, or larger than 2000 bytes, then shrink it
4112 accordingly. Keep a minimum size of 20 bytes. */
4113 int size = min (2000, max (20, (nextb->text->z_byte / 10)));
4115 if (nextb->text->gap_size > size)
4117 struct buffer *save_current = current_buffer;
4118 current_buffer = nextb;
4119 make_gap (-(nextb->text->gap_size - size));
4120 current_buffer = save_current;
4124 nextb = nextb->next;
4128 gc_in_progress = 1;
4130 /* clear_marks (); */
4132 /* Mark all the special slots that serve as the roots of accessibility.
4134 Usually the special slots to mark are contained in particular structures.
4135 Then we know no slot is marked twice because the structures don't overlap.
4136 In some cases, the structures point to the slots to be marked.
4137 For these, we use MARKBIT to avoid double marking of the slot. */
4139 for (i = 0; i < staticidx; i++)
4140 mark_object (staticvec[i]);
4142 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
4143 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
4144 mark_stack ();
4145 #else
4146 for (tail = gcprolist; tail; tail = tail->next)
4147 for (i = 0; i < tail->nvars; i++)
4148 if (!XMARKBIT (tail->var[i]))
4150 /* Explicit casting prevents compiler warning about
4151 discarding the `volatile' qualifier. */
4152 mark_object ((Lisp_Object *)&tail->var[i]);
4153 XMARK (tail->var[i]);
4155 #endif
4157 mark_byte_stack ();
4158 for (bind = specpdl; bind != specpdl_ptr; bind++)
4160 mark_object (&bind->symbol);
4161 mark_object (&bind->old_value);
4163 for (catch = catchlist; catch; catch = catch->next)
4165 mark_object (&catch->tag);
4166 mark_object (&catch->val);
4168 for (handler = handlerlist; handler; handler = handler->next)
4170 mark_object (&handler->handler);
4171 mark_object (&handler->var);
4173 for (backlist = backtrace_list; backlist; backlist = backlist->next)
4175 if (!XMARKBIT (*backlist->function))
4177 mark_object (backlist->function);
4178 XMARK (*backlist->function);
4180 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
4181 i = 0;
4182 else
4183 i = backlist->nargs - 1;
4184 for (; i >= 0; i--)
4185 if (!XMARKBIT (backlist->args[i]))
4187 mark_object (&backlist->args[i]);
4188 XMARK (backlist->args[i]);
4191 mark_kboards ();
4193 /* Look thru every buffer's undo list
4194 for elements that update markers that were not marked,
4195 and delete them. */
4197 register struct buffer *nextb = all_buffers;
4199 while (nextb)
4201 /* If a buffer's undo list is Qt, that means that undo is
4202 turned off in that buffer. Calling truncate_undo_list on
4203 Qt tends to return NULL, which effectively turns undo back on.
4204 So don't call truncate_undo_list if undo_list is Qt. */
4205 if (! EQ (nextb->undo_list, Qt))
4207 Lisp_Object tail, prev;
4208 tail = nextb->undo_list;
4209 prev = Qnil;
4210 while (CONSP (tail))
4212 if (GC_CONSP (XCAR (tail))
4213 && GC_MARKERP (XCAR (XCAR (tail)))
4214 && ! XMARKBIT (XMARKER (XCAR (XCAR (tail)))->chain))
4216 if (NILP (prev))
4217 nextb->undo_list = tail = XCDR (tail);
4218 else
4220 tail = XCDR (tail);
4221 XSETCDR (prev, tail);
4224 else
4226 prev = tail;
4227 tail = XCDR (tail);
4232 nextb = nextb->next;
4236 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4237 mark_stack ();
4238 #endif
4240 gc_sweep ();
4242 /* Clear the mark bits that we set in certain root slots. */
4244 #if (GC_MARK_STACK == GC_USE_GCPROS_AS_BEFORE \
4245 || GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES)
4246 for (tail = gcprolist; tail; tail = tail->next)
4247 for (i = 0; i < tail->nvars; i++)
4248 XUNMARK (tail->var[i]);
4249 #endif
4251 unmark_byte_stack ();
4252 for (backlist = backtrace_list; backlist; backlist = backlist->next)
4254 XUNMARK (*backlist->function);
4255 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
4256 i = 0;
4257 else
4258 i = backlist->nargs - 1;
4259 for (; i >= 0; i--)
4260 XUNMARK (backlist->args[i]);
4262 XUNMARK (buffer_defaults.name);
4263 XUNMARK (buffer_local_symbols.name);
4265 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
4266 dump_zombies ();
4267 #endif
4269 UNBLOCK_INPUT;
4271 /* clear_marks (); */
4272 gc_in_progress = 0;
4274 consing_since_gc = 0;
4275 if (gc_cons_threshold < 10000)
4276 gc_cons_threshold = 10000;
4278 if (garbage_collection_messages)
4280 if (message_p || minibuf_level > 0)
4281 restore_message ();
4282 else
4283 message1_nolog ("Garbage collecting...done");
4286 unbind_to (count, Qnil);
4288 total[0] = Fcons (make_number (total_conses),
4289 make_number (total_free_conses));
4290 total[1] = Fcons (make_number (total_symbols),
4291 make_number (total_free_symbols));
4292 total[2] = Fcons (make_number (total_markers),
4293 make_number (total_free_markers));
4294 total[3] = make_number (total_string_size);
4295 total[4] = make_number (total_vector_size);
4296 total[5] = Fcons (make_number (total_floats),
4297 make_number (total_free_floats));
4298 total[6] = Fcons (make_number (total_intervals),
4299 make_number (total_free_intervals));
4300 total[7] = Fcons (make_number (total_strings),
4301 make_number (total_free_strings));
4303 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4305 /* Compute average percentage of zombies. */
4306 double nlive = 0;
4308 for (i = 0; i < 7; ++i)
4309 nlive += XFASTINT (XCAR (total[i]));
4311 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
4312 max_live = max (nlive, max_live);
4313 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
4314 max_zombies = max (nzombies, max_zombies);
4315 ++ngcs;
4317 #endif
4319 if (!NILP (Vpost_gc_hook))
4321 int count = inhibit_garbage_collection ();
4322 safe_run_hooks (Qpost_gc_hook);
4323 unbind_to (count, Qnil);
4326 return Flist (sizeof total / sizeof *total, total);
4330 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
4331 only interesting objects referenced from glyphs are strings. */
4333 static void
4334 mark_glyph_matrix (matrix)
4335 struct glyph_matrix *matrix;
4337 struct glyph_row *row = matrix->rows;
4338 struct glyph_row *end = row + matrix->nrows;
4340 for (; row < end; ++row)
4341 if (row->enabled_p)
4343 int area;
4344 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
4346 struct glyph *glyph = row->glyphs[area];
4347 struct glyph *end_glyph = glyph + row->used[area];
4349 for (; glyph < end_glyph; ++glyph)
4350 if (GC_STRINGP (glyph->object)
4351 && !STRING_MARKED_P (XSTRING (glyph->object)))
4352 mark_object (&glyph->object);
4358 /* Mark Lisp faces in the face cache C. */
4360 static void
4361 mark_face_cache (c)
4362 struct face_cache *c;
4364 if (c)
4366 int i, j;
4367 for (i = 0; i < c->used; ++i)
4369 struct face *face = FACE_FROM_ID (c->f, i);
4371 if (face)
4373 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
4374 mark_object (&face->lface[j]);
4381 #ifdef HAVE_WINDOW_SYSTEM
4383 /* Mark Lisp objects in image IMG. */
4385 static void
4386 mark_image (img)
4387 struct image *img;
4389 mark_object (&img->spec);
4391 if (!NILP (img->data.lisp_val))
4392 mark_object (&img->data.lisp_val);
4396 /* Mark Lisp objects in image cache of frame F. It's done this way so
4397 that we don't have to include xterm.h here. */
4399 static void
4400 mark_image_cache (f)
4401 struct frame *f;
4403 forall_images_in_image_cache (f, mark_image);
4406 #endif /* HAVE_X_WINDOWS */
4410 /* Mark reference to a Lisp_Object.
4411 If the object referred to has not been seen yet, recursively mark
4412 all the references contained in it. */
4414 #define LAST_MARKED_SIZE 500
4415 Lisp_Object *last_marked[LAST_MARKED_SIZE];
4416 int last_marked_index;
4418 /* For debugging--call abort when we cdr down this many
4419 links of a list, in mark_object. In debugging,
4420 the call to abort will hit a breakpoint.
4421 Normally this is zero and the check never goes off. */
4422 int mark_object_loop_halt;
4424 void
4425 mark_object (argptr)
4426 Lisp_Object *argptr;
4428 Lisp_Object *objptr = argptr;
4429 register Lisp_Object obj;
4430 #ifdef GC_CHECK_MARKED_OBJECTS
4431 void *po;
4432 struct mem_node *m;
4433 #endif
4434 int cdr_count = 0;
4436 loop:
4437 obj = *objptr;
4438 loop2:
4439 XUNMARK (obj);
4441 if (PURE_POINTER_P (XPNTR (obj)))
4442 return;
4444 last_marked[last_marked_index++] = objptr;
4445 if (last_marked_index == LAST_MARKED_SIZE)
4446 last_marked_index = 0;
4448 /* Perform some sanity checks on the objects marked here. Abort if
4449 we encounter an object we know is bogus. This increases GC time
4450 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
4451 #ifdef GC_CHECK_MARKED_OBJECTS
4453 po = (void *) XPNTR (obj);
4455 /* Check that the object pointed to by PO is known to be a Lisp
4456 structure allocated from the heap. */
4457 #define CHECK_ALLOCATED() \
4458 do { \
4459 m = mem_find (po); \
4460 if (m == MEM_NIL) \
4461 abort (); \
4462 } while (0)
4464 /* Check that the object pointed to by PO is live, using predicate
4465 function LIVEP. */
4466 #define CHECK_LIVE(LIVEP) \
4467 do { \
4468 if (!LIVEP (m, po)) \
4469 abort (); \
4470 } while (0)
4472 /* Check both of the above conditions. */
4473 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
4474 do { \
4475 CHECK_ALLOCATED (); \
4476 CHECK_LIVE (LIVEP); \
4477 } while (0) \
4479 #else /* not GC_CHECK_MARKED_OBJECTS */
4481 #define CHECK_ALLOCATED() (void) 0
4482 #define CHECK_LIVE(LIVEP) (void) 0
4483 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
4485 #endif /* not GC_CHECK_MARKED_OBJECTS */
4487 switch (SWITCH_ENUM_CAST (XGCTYPE (obj)))
4489 case Lisp_String:
4491 register struct Lisp_String *ptr = XSTRING (obj);
4492 CHECK_ALLOCATED_AND_LIVE (live_string_p);
4493 MARK_INTERVAL_TREE (ptr->intervals);
4494 MARK_STRING (ptr);
4495 #ifdef GC_CHECK_STRING_BYTES
4496 /* Check that the string size recorded in the string is the
4497 same as the one recorded in the sdata structure. */
4498 CHECK_STRING_BYTES (ptr);
4499 #endif /* GC_CHECK_STRING_BYTES */
4501 break;
4503 case Lisp_Vectorlike:
4504 #ifdef GC_CHECK_MARKED_OBJECTS
4505 m = mem_find (po);
4506 if (m == MEM_NIL && !GC_SUBRP (obj)
4507 && po != &buffer_defaults
4508 && po != &buffer_local_symbols)
4509 abort ();
4510 #endif /* GC_CHECK_MARKED_OBJECTS */
4512 if (GC_BUFFERP (obj))
4514 if (!XMARKBIT (XBUFFER (obj)->name))
4516 #ifdef GC_CHECK_MARKED_OBJECTS
4517 if (po != &buffer_defaults && po != &buffer_local_symbols)
4519 struct buffer *b;
4520 for (b = all_buffers; b && b != po; b = b->next)
4522 if (b == NULL)
4523 abort ();
4525 #endif /* GC_CHECK_MARKED_OBJECTS */
4526 mark_buffer (obj);
4529 else if (GC_SUBRP (obj))
4530 break;
4531 else if (GC_COMPILEDP (obj))
4532 /* We could treat this just like a vector, but it is better to
4533 save the COMPILED_CONSTANTS element for last and avoid
4534 recursion there. */
4536 register struct Lisp_Vector *ptr = XVECTOR (obj);
4537 register EMACS_INT size = ptr->size;
4538 register int i;
4540 if (size & ARRAY_MARK_FLAG)
4541 break; /* Already marked */
4543 CHECK_LIVE (live_vector_p);
4544 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4545 size &= PSEUDOVECTOR_SIZE_MASK;
4546 for (i = 0; i < size; i++) /* and then mark its elements */
4548 if (i != COMPILED_CONSTANTS)
4549 mark_object (&ptr->contents[i]);
4551 /* This cast should be unnecessary, but some Mips compiler complains
4552 (MIPS-ABI + SysVR4, DC/OSx, etc). */
4553 objptr = (Lisp_Object *) &ptr->contents[COMPILED_CONSTANTS];
4554 goto loop;
4556 else if (GC_FRAMEP (obj))
4558 register struct frame *ptr = XFRAME (obj);
4559 register EMACS_INT size = ptr->size;
4561 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
4562 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4564 CHECK_LIVE (live_vector_p);
4565 mark_object (&ptr->name);
4566 mark_object (&ptr->icon_name);
4567 mark_object (&ptr->title);
4568 mark_object (&ptr->focus_frame);
4569 mark_object (&ptr->selected_window);
4570 mark_object (&ptr->minibuffer_window);
4571 mark_object (&ptr->param_alist);
4572 mark_object (&ptr->scroll_bars);
4573 mark_object (&ptr->condemned_scroll_bars);
4574 mark_object (&ptr->menu_bar_items);
4575 mark_object (&ptr->face_alist);
4576 mark_object (&ptr->menu_bar_vector);
4577 mark_object (&ptr->buffer_predicate);
4578 mark_object (&ptr->buffer_list);
4579 mark_object (&ptr->menu_bar_window);
4580 mark_object (&ptr->tool_bar_window);
4581 mark_face_cache (ptr->face_cache);
4582 #ifdef HAVE_WINDOW_SYSTEM
4583 mark_image_cache (ptr);
4584 mark_object (&ptr->tool_bar_items);
4585 mark_object (&ptr->desired_tool_bar_string);
4586 mark_object (&ptr->current_tool_bar_string);
4587 #endif /* HAVE_WINDOW_SYSTEM */
4589 else if (GC_BOOL_VECTOR_P (obj))
4591 register struct Lisp_Vector *ptr = XVECTOR (obj);
4593 if (ptr->size & ARRAY_MARK_FLAG)
4594 break; /* Already marked */
4595 CHECK_LIVE (live_vector_p);
4596 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4598 else if (GC_WINDOWP (obj))
4600 register struct Lisp_Vector *ptr = XVECTOR (obj);
4601 struct window *w = XWINDOW (obj);
4602 register EMACS_INT size = ptr->size;
4603 register int i;
4605 /* Stop if already marked. */
4606 if (size & ARRAY_MARK_FLAG)
4607 break;
4609 /* Mark it. */
4610 CHECK_LIVE (live_vector_p);
4611 ptr->size |= ARRAY_MARK_FLAG;
4613 /* There is no Lisp data above The member CURRENT_MATRIX in
4614 struct WINDOW. Stop marking when that slot is reached. */
4615 for (i = 0;
4616 (char *) &ptr->contents[i] < (char *) &w->current_matrix;
4617 i++)
4618 mark_object (&ptr->contents[i]);
4620 /* Mark glyphs for leaf windows. Marking window matrices is
4621 sufficient because frame matrices use the same glyph
4622 memory. */
4623 if (NILP (w->hchild)
4624 && NILP (w->vchild)
4625 && w->current_matrix)
4627 mark_glyph_matrix (w->current_matrix);
4628 mark_glyph_matrix (w->desired_matrix);
4631 else if (GC_HASH_TABLE_P (obj))
4633 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
4634 EMACS_INT size = h->size;
4636 /* Stop if already marked. */
4637 if (size & ARRAY_MARK_FLAG)
4638 break;
4640 /* Mark it. */
4641 CHECK_LIVE (live_vector_p);
4642 h->size |= ARRAY_MARK_FLAG;
4644 /* Mark contents. */
4645 /* Do not mark next_free or next_weak.
4646 Being in the next_weak chain
4647 should not keep the hash table alive.
4648 No need to mark `count' since it is an integer. */
4649 mark_object (&h->test);
4650 mark_object (&h->weak);
4651 mark_object (&h->rehash_size);
4652 mark_object (&h->rehash_threshold);
4653 mark_object (&h->hash);
4654 mark_object (&h->next);
4655 mark_object (&h->index);
4656 mark_object (&h->user_hash_function);
4657 mark_object (&h->user_cmp_function);
4659 /* If hash table is not weak, mark all keys and values.
4660 For weak tables, mark only the vector. */
4661 if (GC_NILP (h->weak))
4662 mark_object (&h->key_and_value);
4663 else
4664 XVECTOR (h->key_and_value)->size |= ARRAY_MARK_FLAG;
4667 else
4669 register struct Lisp_Vector *ptr = XVECTOR (obj);
4670 register EMACS_INT size = ptr->size;
4671 register int i;
4673 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
4674 CHECK_LIVE (live_vector_p);
4675 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4676 if (size & PSEUDOVECTOR_FLAG)
4677 size &= PSEUDOVECTOR_SIZE_MASK;
4679 for (i = 0; i < size; i++) /* and then mark its elements */
4680 mark_object (&ptr->contents[i]);
4682 break;
4684 case Lisp_Symbol:
4686 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
4687 struct Lisp_Symbol *ptrx;
4689 if (XMARKBIT (ptr->plist)) break;
4690 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
4691 XMARK (ptr->plist);
4692 mark_object ((Lisp_Object *) &ptr->value);
4693 mark_object (&ptr->function);
4694 mark_object (&ptr->plist);
4696 if (!PURE_POINTER_P (XSTRING (ptr->xname)))
4697 MARK_STRING (XSTRING (ptr->xname));
4698 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr->xname));
4700 /* Note that we do not mark the obarray of the symbol.
4701 It is safe not to do so because nothing accesses that
4702 slot except to check whether it is nil. */
4703 ptr = ptr->next;
4704 if (ptr)
4706 /* For the benefit of the last_marked log. */
4707 objptr = (Lisp_Object *)&XSYMBOL (obj)->next;
4708 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
4709 XSETSYMBOL (obj, ptrx);
4710 /* We can't goto loop here because *objptr doesn't contain an
4711 actual Lisp_Object with valid datatype field. */
4712 goto loop2;
4715 break;
4717 case Lisp_Misc:
4718 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
4719 switch (XMISCTYPE (obj))
4721 case Lisp_Misc_Marker:
4722 XMARK (XMARKER (obj)->chain);
4723 /* DO NOT mark thru the marker's chain.
4724 The buffer's markers chain does not preserve markers from gc;
4725 instead, markers are removed from the chain when freed by gc. */
4726 break;
4728 case Lisp_Misc_Buffer_Local_Value:
4729 case Lisp_Misc_Some_Buffer_Local_Value:
4731 register struct Lisp_Buffer_Local_Value *ptr
4732 = XBUFFER_LOCAL_VALUE (obj);
4733 if (XMARKBIT (ptr->realvalue)) break;
4734 XMARK (ptr->realvalue);
4735 /* If the cdr is nil, avoid recursion for the car. */
4736 if (EQ (ptr->cdr, Qnil))
4738 objptr = &ptr->realvalue;
4739 goto loop;
4741 mark_object (&ptr->realvalue);
4742 mark_object (&ptr->buffer);
4743 mark_object (&ptr->frame);
4744 objptr = &ptr->cdr;
4745 goto loop;
4748 case Lisp_Misc_Intfwd:
4749 case Lisp_Misc_Boolfwd:
4750 case Lisp_Misc_Objfwd:
4751 case Lisp_Misc_Buffer_Objfwd:
4752 case Lisp_Misc_Kboard_Objfwd:
4753 /* Don't bother with Lisp_Buffer_Objfwd,
4754 since all markable slots in current buffer marked anyway. */
4755 /* Don't need to do Lisp_Objfwd, since the places they point
4756 are protected with staticpro. */
4757 break;
4759 case Lisp_Misc_Overlay:
4761 struct Lisp_Overlay *ptr = XOVERLAY (obj);
4762 if (!XMARKBIT (ptr->plist))
4764 XMARK (ptr->plist);
4765 mark_object (&ptr->start);
4766 mark_object (&ptr->end);
4767 objptr = &ptr->plist;
4768 goto loop;
4771 break;
4773 default:
4774 abort ();
4776 break;
4778 case Lisp_Cons:
4780 register struct Lisp_Cons *ptr = XCONS (obj);
4781 if (XMARKBIT (ptr->car)) break;
4782 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
4783 XMARK (ptr->car);
4784 /* If the cdr is nil, avoid recursion for the car. */
4785 if (EQ (ptr->cdr, Qnil))
4787 objptr = &ptr->car;
4788 cdr_count = 0;
4789 goto loop;
4791 mark_object (&ptr->car);
4792 objptr = &ptr->cdr;
4793 cdr_count++;
4794 if (cdr_count == mark_object_loop_halt)
4795 abort ();
4796 goto loop;
4799 case Lisp_Float:
4800 CHECK_ALLOCATED_AND_LIVE (live_float_p);
4801 XMARK (XFLOAT (obj)->type);
4802 break;
4804 case Lisp_Int:
4805 break;
4807 default:
4808 abort ();
4811 #undef CHECK_LIVE
4812 #undef CHECK_ALLOCATED
4813 #undef CHECK_ALLOCATED_AND_LIVE
4816 /* Mark the pointers in a buffer structure. */
4818 static void
4819 mark_buffer (buf)
4820 Lisp_Object buf;
4822 register struct buffer *buffer = XBUFFER (buf);
4823 register Lisp_Object *ptr;
4824 Lisp_Object base_buffer;
4826 /* This is the buffer's markbit */
4827 mark_object (&buffer->name);
4828 XMARK (buffer->name);
4830 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
4832 if (CONSP (buffer->undo_list))
4834 Lisp_Object tail;
4835 tail = buffer->undo_list;
4837 while (CONSP (tail))
4839 register struct Lisp_Cons *ptr = XCONS (tail);
4841 if (XMARKBIT (ptr->car))
4842 break;
4843 XMARK (ptr->car);
4844 if (GC_CONSP (ptr->car)
4845 && ! XMARKBIT (XCAR (ptr->car))
4846 && GC_MARKERP (XCAR (ptr->car)))
4848 XMARK (XCAR_AS_LVALUE (ptr->car));
4849 mark_object (&XCDR_AS_LVALUE (ptr->car));
4851 else
4852 mark_object (&ptr->car);
4854 if (CONSP (ptr->cdr))
4855 tail = ptr->cdr;
4856 else
4857 break;
4860 mark_object (&XCDR_AS_LVALUE (tail));
4862 else
4863 mark_object (&buffer->undo_list);
4865 for (ptr = &buffer->name + 1;
4866 (char *)ptr < (char *)buffer + sizeof (struct buffer);
4867 ptr++)
4868 mark_object (ptr);
4870 /* If this is an indirect buffer, mark its base buffer. */
4871 if (buffer->base_buffer && !XMARKBIT (buffer->base_buffer->name))
4873 XSETBUFFER (base_buffer, buffer->base_buffer);
4874 mark_buffer (base_buffer);
4879 /* Mark the pointers in the kboard objects. */
4881 static void
4882 mark_kboards ()
4884 KBOARD *kb;
4885 Lisp_Object *p;
4886 for (kb = all_kboards; kb; kb = kb->next_kboard)
4888 if (kb->kbd_macro_buffer)
4889 for (p = kb->kbd_macro_buffer; p < kb->kbd_macro_ptr; p++)
4890 mark_object (p);
4891 mark_object (&kb->Voverriding_terminal_local_map);
4892 mark_object (&kb->Vlast_command);
4893 mark_object (&kb->Vreal_last_command);
4894 mark_object (&kb->Vprefix_arg);
4895 mark_object (&kb->Vlast_prefix_arg);
4896 mark_object (&kb->kbd_queue);
4897 mark_object (&kb->defining_kbd_macro);
4898 mark_object (&kb->Vlast_kbd_macro);
4899 mark_object (&kb->Vsystem_key_alist);
4900 mark_object (&kb->system_key_syms);
4901 mark_object (&kb->Vdefault_minibuffer_frame);
4902 mark_object (&kb->echo_string);
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 = XMARKBIT (XSYMBOL (obj)->plist);
4924 break;
4926 case Lisp_Misc:
4927 switch (XMISCTYPE (obj))
4929 case Lisp_Misc_Marker:
4930 survives_p = XMARKBIT (obj);
4931 break;
4933 case Lisp_Misc_Buffer_Local_Value:
4934 case Lisp_Misc_Some_Buffer_Local_Value:
4935 survives_p = XMARKBIT (XBUFFER_LOCAL_VALUE (obj)->realvalue);
4936 break;
4938 case Lisp_Misc_Intfwd:
4939 case Lisp_Misc_Boolfwd:
4940 case Lisp_Misc_Objfwd:
4941 case Lisp_Misc_Buffer_Objfwd:
4942 case Lisp_Misc_Kboard_Objfwd:
4943 survives_p = 1;
4944 break;
4946 case Lisp_Misc_Overlay:
4947 survives_p = XMARKBIT (XOVERLAY (obj)->plist);
4948 break;
4950 default:
4951 abort ();
4953 break;
4955 case Lisp_String:
4957 struct Lisp_String *s = XSTRING (obj);
4958 survives_p = STRING_MARKED_P (s);
4960 break;
4962 case Lisp_Vectorlike:
4963 if (GC_BUFFERP (obj))
4964 survives_p = XMARKBIT (XBUFFER (obj)->name);
4965 else if (GC_SUBRP (obj))
4966 survives_p = 1;
4967 else
4968 survives_p = XVECTOR (obj)->size & ARRAY_MARK_FLAG;
4969 break;
4971 case Lisp_Cons:
4972 survives_p = XMARKBIT (XCAR (obj));
4973 break;
4975 case Lisp_Float:
4976 survives_p = XMARKBIT (XFLOAT (obj)->type);
4977 break;
4979 default:
4980 abort ();
4983 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
4988 /* Sweep: find all structures not marked, and free them. */
4990 static void
4991 gc_sweep ()
4993 /* Remove or mark entries in weak hash tables.
4994 This must be done before any object is unmarked. */
4995 sweep_weak_hash_tables ();
4997 sweep_strings ();
4998 #ifdef GC_CHECK_STRING_BYTES
4999 if (!noninteractive)
5000 check_string_bytes (1);
5001 #endif
5003 /* Put all unmarked conses on free list */
5005 register struct cons_block *cblk;
5006 struct cons_block **cprev = &cons_block;
5007 register int lim = cons_block_index;
5008 register int num_free = 0, num_used = 0;
5010 cons_free_list = 0;
5012 for (cblk = cons_block; cblk; cblk = *cprev)
5014 register int i;
5015 int this_free = 0;
5016 for (i = 0; i < lim; i++)
5017 if (!XMARKBIT (cblk->conses[i].car))
5019 this_free++;
5020 *(struct Lisp_Cons **)&cblk->conses[i].cdr = cons_free_list;
5021 cons_free_list = &cblk->conses[i];
5022 #if GC_MARK_STACK
5023 cons_free_list->car = Vdead;
5024 #endif
5026 else
5028 num_used++;
5029 XUNMARK (cblk->conses[i].car);
5031 lim = CONS_BLOCK_SIZE;
5032 /* If this block contains only free conses and we have already
5033 seen more than two blocks worth of free conses then deallocate
5034 this block. */
5035 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
5037 *cprev = cblk->next;
5038 /* Unhook from the free list. */
5039 cons_free_list = *(struct Lisp_Cons **) &cblk->conses[0].cdr;
5040 lisp_free (cblk);
5041 n_cons_blocks--;
5043 else
5045 num_free += this_free;
5046 cprev = &cblk->next;
5049 total_conses = num_used;
5050 total_free_conses = num_free;
5053 /* Put all unmarked floats on free list */
5055 register struct float_block *fblk;
5056 struct float_block **fprev = &float_block;
5057 register int lim = float_block_index;
5058 register int num_free = 0, num_used = 0;
5060 float_free_list = 0;
5062 for (fblk = float_block; fblk; fblk = *fprev)
5064 register int i;
5065 int this_free = 0;
5066 for (i = 0; i < lim; i++)
5067 if (!XMARKBIT (fblk->floats[i].type))
5069 this_free++;
5070 *(struct Lisp_Float **)&fblk->floats[i].data = float_free_list;
5071 float_free_list = &fblk->floats[i];
5072 #if GC_MARK_STACK
5073 float_free_list->type = Vdead;
5074 #endif
5076 else
5078 num_used++;
5079 XUNMARK (fblk->floats[i].type);
5081 lim = FLOAT_BLOCK_SIZE;
5082 /* If this block contains only free floats and we have already
5083 seen more than two blocks worth of free floats then deallocate
5084 this block. */
5085 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
5087 *fprev = fblk->next;
5088 /* Unhook from the free list. */
5089 float_free_list = *(struct Lisp_Float **) &fblk->floats[0].data;
5090 lisp_free (fblk);
5091 n_float_blocks--;
5093 else
5095 num_free += this_free;
5096 fprev = &fblk->next;
5099 total_floats = num_used;
5100 total_free_floats = num_free;
5103 /* Put all unmarked intervals on free list */
5105 register struct interval_block *iblk;
5106 struct interval_block **iprev = &interval_block;
5107 register int lim = interval_block_index;
5108 register int num_free = 0, num_used = 0;
5110 interval_free_list = 0;
5112 for (iblk = interval_block; iblk; iblk = *iprev)
5114 register int i;
5115 int this_free = 0;
5117 for (i = 0; i < lim; i++)
5119 if (! XMARKBIT (iblk->intervals[i].plist))
5121 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
5122 interval_free_list = &iblk->intervals[i];
5123 this_free++;
5125 else
5127 num_used++;
5128 XUNMARK (iblk->intervals[i].plist);
5131 lim = INTERVAL_BLOCK_SIZE;
5132 /* If this block contains only free intervals and we have already
5133 seen more than two blocks worth of free intervals then
5134 deallocate this block. */
5135 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
5137 *iprev = iblk->next;
5138 /* Unhook from the free list. */
5139 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
5140 lisp_free (iblk);
5141 n_interval_blocks--;
5143 else
5145 num_free += this_free;
5146 iprev = &iblk->next;
5149 total_intervals = num_used;
5150 total_free_intervals = num_free;
5153 /* Put all unmarked symbols on free list */
5155 register struct symbol_block *sblk;
5156 struct symbol_block **sprev = &symbol_block;
5157 register int lim = symbol_block_index;
5158 register int num_free = 0, num_used = 0;
5160 symbol_free_list = NULL;
5162 for (sblk = symbol_block; sblk; sblk = *sprev)
5164 int this_free = 0;
5165 struct Lisp_Symbol *sym = sblk->symbols;
5166 struct Lisp_Symbol *end = sym + lim;
5168 for (; sym < end; ++sym)
5170 /* Check if the symbol was created during loadup. In such a case
5171 it might be pointed to by pure bytecode which we don't trace,
5172 so we conservatively assume that it is live. */
5173 int pure_p = PURE_POINTER_P (XSTRING (sym->xname));
5175 if (!XMARKBIT (sym->plist) && !pure_p)
5177 *(struct Lisp_Symbol **) &sym->value = symbol_free_list;
5178 symbol_free_list = sym;
5179 #if GC_MARK_STACK
5180 symbol_free_list->function = Vdead;
5181 #endif
5182 ++this_free;
5184 else
5186 ++num_used;
5187 if (!pure_p)
5188 UNMARK_STRING (XSTRING (sym->xname));
5189 XUNMARK (sym->plist);
5193 lim = SYMBOL_BLOCK_SIZE;
5194 /* If this block contains only free symbols and we have already
5195 seen more than two blocks worth of free symbols then deallocate
5196 this block. */
5197 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
5199 *sprev = sblk->next;
5200 /* Unhook from the free list. */
5201 symbol_free_list = *(struct Lisp_Symbol **)&sblk->symbols[0].value;
5202 lisp_free (sblk);
5203 n_symbol_blocks--;
5205 else
5207 num_free += this_free;
5208 sprev = &sblk->next;
5211 total_symbols = num_used;
5212 total_free_symbols = num_free;
5215 /* Put all unmarked misc's on free list.
5216 For a marker, first unchain it from the buffer it points into. */
5218 register struct marker_block *mblk;
5219 struct marker_block **mprev = &marker_block;
5220 register int lim = marker_block_index;
5221 register int num_free = 0, num_used = 0;
5223 marker_free_list = 0;
5225 for (mblk = marker_block; mblk; mblk = *mprev)
5227 register int i;
5228 int this_free = 0;
5229 EMACS_INT already_free = -1;
5231 for (i = 0; i < lim; i++)
5233 Lisp_Object *markword;
5234 switch (mblk->markers[i].u_marker.type)
5236 case Lisp_Misc_Marker:
5237 markword = &mblk->markers[i].u_marker.chain;
5238 break;
5239 case Lisp_Misc_Buffer_Local_Value:
5240 case Lisp_Misc_Some_Buffer_Local_Value:
5241 markword = &mblk->markers[i].u_buffer_local_value.realvalue;
5242 break;
5243 case Lisp_Misc_Overlay:
5244 markword = &mblk->markers[i].u_overlay.plist;
5245 break;
5246 case Lisp_Misc_Free:
5247 /* If the object was already free, keep it
5248 on the free list. */
5249 markword = (Lisp_Object *) &already_free;
5250 break;
5251 default:
5252 markword = 0;
5253 break;
5255 if (markword && !XMARKBIT (*markword))
5257 Lisp_Object tem;
5258 if (mblk->markers[i].u_marker.type == Lisp_Misc_Marker)
5260 /* tem1 avoids Sun compiler bug */
5261 struct Lisp_Marker *tem1 = &mblk->markers[i].u_marker;
5262 XSETMARKER (tem, tem1);
5263 unchain_marker (tem);
5265 /* Set the type of the freed object to Lisp_Misc_Free.
5266 We could leave the type alone, since nobody checks it,
5267 but this might catch bugs faster. */
5268 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
5269 mblk->markers[i].u_free.chain = marker_free_list;
5270 marker_free_list = &mblk->markers[i];
5271 this_free++;
5273 else
5275 num_used++;
5276 if (markword)
5277 XUNMARK (*markword);
5280 lim = MARKER_BLOCK_SIZE;
5281 /* If this block contains only free markers and we have already
5282 seen more than two blocks worth of free markers then deallocate
5283 this block. */
5284 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
5286 *mprev = mblk->next;
5287 /* Unhook from the free list. */
5288 marker_free_list = mblk->markers[0].u_free.chain;
5289 lisp_free (mblk);
5290 n_marker_blocks--;
5292 else
5294 num_free += this_free;
5295 mprev = &mblk->next;
5299 total_markers = num_used;
5300 total_free_markers = num_free;
5303 /* Free all unmarked buffers */
5305 register struct buffer *buffer = all_buffers, *prev = 0, *next;
5307 while (buffer)
5308 if (!XMARKBIT (buffer->name))
5310 if (prev)
5311 prev->next = buffer->next;
5312 else
5313 all_buffers = buffer->next;
5314 next = buffer->next;
5315 lisp_free (buffer);
5316 buffer = next;
5318 else
5320 XUNMARK (buffer->name);
5321 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
5322 prev = buffer, buffer = buffer->next;
5326 /* Free all unmarked vectors */
5328 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
5329 total_vector_size = 0;
5331 while (vector)
5332 if (!(vector->size & ARRAY_MARK_FLAG))
5334 if (prev)
5335 prev->next = vector->next;
5336 else
5337 all_vectors = vector->next;
5338 next = vector->next;
5339 lisp_free (vector);
5340 n_vectors--;
5341 vector = next;
5344 else
5346 vector->size &= ~ARRAY_MARK_FLAG;
5347 if (vector->size & PSEUDOVECTOR_FLAG)
5348 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
5349 else
5350 total_vector_size += vector->size;
5351 prev = vector, vector = vector->next;
5355 #ifdef GC_CHECK_STRING_BYTES
5356 if (!noninteractive)
5357 check_string_bytes (1);
5358 #endif
5364 /* Debugging aids. */
5366 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
5367 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
5368 This may be helpful in debugging Emacs's memory usage.
5369 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
5372 Lisp_Object end;
5374 XSETINT (end, (EMACS_INT) sbrk (0) / 1024);
5376 return end;
5379 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
5380 doc: /* Return a list of counters that measure how much consing there has been.
5381 Each of these counters increments for a certain kind of object.
5382 The counters wrap around from the largest positive integer to zero.
5383 Garbage collection does not decrease them.
5384 The elements of the value are as follows:
5385 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
5386 All are in units of 1 = one object consed
5387 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
5388 objects consed.
5389 MISCS include overlays, markers, and some internal types.
5390 Frames, windows, buffers, and subprocesses count as vectors
5391 (but the contents of a buffer's text do not count here). */)
5394 Lisp_Object consed[8];
5396 consed[0] = make_number (min (MOST_POSITIVE_FIXNUM, cons_cells_consed));
5397 consed[1] = make_number (min (MOST_POSITIVE_FIXNUM, floats_consed));
5398 consed[2] = make_number (min (MOST_POSITIVE_FIXNUM, vector_cells_consed));
5399 consed[3] = make_number (min (MOST_POSITIVE_FIXNUM, symbols_consed));
5400 consed[4] = make_number (min (MOST_POSITIVE_FIXNUM, string_chars_consed));
5401 consed[5] = make_number (min (MOST_POSITIVE_FIXNUM, misc_objects_consed));
5402 consed[6] = make_number (min (MOST_POSITIVE_FIXNUM, intervals_consed));
5403 consed[7] = make_number (min (MOST_POSITIVE_FIXNUM, strings_consed));
5405 return Flist (8, consed);
5408 int suppress_checking;
5409 void
5410 die (msg, file, line)
5411 const char *msg;
5412 const char *file;
5413 int line;
5415 fprintf (stderr, "\r\nEmacs fatal error: %s:%d: %s\r\n",
5416 file, line, msg);
5417 abort ();
5420 /* Initialization */
5422 void
5423 init_alloc_once ()
5425 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
5426 purebeg = PUREBEG;
5427 pure_size = PURESIZE;
5428 pure_bytes_used = 0;
5429 pure_bytes_used_before_overflow = 0;
5431 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
5432 mem_init ();
5433 Vdead = make_pure_string ("DEAD", 4, 4, 0);
5434 #endif
5436 all_vectors = 0;
5437 ignore_warnings = 1;
5438 #ifdef DOUG_LEA_MALLOC
5439 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
5440 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
5441 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
5442 #endif
5443 init_strings ();
5444 init_cons ();
5445 init_symbol ();
5446 init_marker ();
5447 init_float ();
5448 init_intervals ();
5450 #ifdef REL_ALLOC
5451 malloc_hysteresis = 32;
5452 #else
5453 malloc_hysteresis = 0;
5454 #endif
5456 spare_memory = (char *) malloc (SPARE_MEMORY);
5458 ignore_warnings = 0;
5459 gcprolist = 0;
5460 byte_stack_list = 0;
5461 staticidx = 0;
5462 consing_since_gc = 0;
5463 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
5464 #ifdef VIRT_ADDR_VARIES
5465 malloc_sbrk_unused = 1<<22; /* A large number */
5466 malloc_sbrk_used = 100000; /* as reasonable as any number */
5467 #endif /* VIRT_ADDR_VARIES */
5470 void
5471 init_alloc ()
5473 gcprolist = 0;
5474 byte_stack_list = 0;
5475 #if GC_MARK_STACK
5476 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
5477 setjmp_tested_p = longjmps_done = 0;
5478 #endif
5479 #endif
5482 void
5483 syms_of_alloc ()
5485 DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold,
5486 doc: /* *Number of bytes of consing between garbage collections.
5487 Garbage collection can happen automatically once this many bytes have been
5488 allocated since the last garbage collection. All data types count.
5490 Garbage collection happens automatically only when `eval' is called.
5492 By binding this temporarily to a large number, you can effectively
5493 prevent garbage collection during a part of the program. */);
5495 DEFVAR_INT ("pure-bytes-used", &pure_bytes_used,
5496 doc: /* Number of bytes of sharable Lisp data allocated so far. */);
5498 DEFVAR_INT ("cons-cells-consed", &cons_cells_consed,
5499 doc: /* Number of cons cells that have been consed so far. */);
5501 DEFVAR_INT ("floats-consed", &floats_consed,
5502 doc: /* Number of floats that have been consed so far. */);
5504 DEFVAR_INT ("vector-cells-consed", &vector_cells_consed,
5505 doc: /* Number of vector cells that have been consed so far. */);
5507 DEFVAR_INT ("symbols-consed", &symbols_consed,
5508 doc: /* Number of symbols that have been consed so far. */);
5510 DEFVAR_INT ("string-chars-consed", &string_chars_consed,
5511 doc: /* Number of string characters that have been consed so far. */);
5513 DEFVAR_INT ("misc-objects-consed", &misc_objects_consed,
5514 doc: /* Number of miscellaneous objects that have been consed so far. */);
5516 DEFVAR_INT ("intervals-consed", &intervals_consed,
5517 doc: /* Number of intervals that have been consed so far. */);
5519 DEFVAR_INT ("strings-consed", &strings_consed,
5520 doc: /* Number of strings that have been consed so far. */);
5522 DEFVAR_LISP ("purify-flag", &Vpurify_flag,
5523 doc: /* Non-nil means loading Lisp code in order to dump an executable.
5524 This means that certain objects should be allocated in shared (pure) space. */);
5526 DEFVAR_INT ("undo-limit", &undo_limit,
5527 doc: /* Keep no more undo information once it exceeds this size.
5528 This limit is applied when garbage collection happens.
5529 The size is counted as the number of bytes occupied,
5530 which includes both saved text and other data. */);
5531 undo_limit = 20000;
5533 DEFVAR_INT ("undo-strong-limit", &undo_strong_limit,
5534 doc: /* Don't keep more than this much size of undo information.
5535 A command which pushes past this size is itself forgotten.
5536 This limit is applied when garbage collection happens.
5537 The size is counted as the number of bytes occupied,
5538 which includes both saved text and other data. */);
5539 undo_strong_limit = 30000;
5541 DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
5542 doc: /* Non-nil means display messages at start and end of garbage collection. */);
5543 garbage_collection_messages = 0;
5545 DEFVAR_LISP ("post-gc-hook", &Vpost_gc_hook,
5546 doc: /* Hook run after garbage collection has finished. */);
5547 Vpost_gc_hook = Qnil;
5548 Qpost_gc_hook = intern ("post-gc-hook");
5549 staticpro (&Qpost_gc_hook);
5551 DEFVAR_LISP ("memory-signal-data", &Vmemory_signal_data,
5552 doc: /* Precomputed `signal' argument for memory-full error. */);
5553 /* We build this in advance because if we wait until we need it, we might
5554 not be able to allocate the memory to hold it. */
5555 Vmemory_signal_data
5556 = list2 (Qerror,
5557 build_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
5559 DEFVAR_LISP ("memory-full", &Vmemory_full,
5560 doc: /* Non-nil means we are handling a memory-full error. */);
5561 Vmemory_full = Qnil;
5563 staticpro (&Qgc_cons_threshold);
5564 Qgc_cons_threshold = intern ("gc-cons-threshold");
5566 staticpro (&Qchar_table_extra_slots);
5567 Qchar_table_extra_slots = intern ("char-table-extra-slots");
5569 defsubr (&Scons);
5570 defsubr (&Slist);
5571 defsubr (&Svector);
5572 defsubr (&Smake_byte_code);
5573 defsubr (&Smake_list);
5574 defsubr (&Smake_vector);
5575 defsubr (&Smake_char_table);
5576 defsubr (&Smake_string);
5577 defsubr (&Smake_bool_vector);
5578 defsubr (&Smake_symbol);
5579 defsubr (&Smake_marker);
5580 defsubr (&Spurecopy);
5581 defsubr (&Sgarbage_collect);
5582 defsubr (&Smemory_limit);
5583 defsubr (&Smemory_use_counts);
5585 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5586 defsubr (&Sgc_status);
5587 #endif