(combine-run-hooks): New function.
[emacs.git] / src / alloc.c
blobba8b3ffd6ed0590f36f16ade68d8df7570a20487
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
2 Copyright (C) 1985, 86, 88, 93, 94, 95, 97, 98, 1999, 2000
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>
24 /* Note that this declares bzero on OSF/1. How dumb. */
26 #include <signal.h>
28 /* This file is part of the core Lisp implementation, and thus must
29 deal with the real data structures. If the Lisp implementation is
30 replaced, this file likely will not be used. */
32 #undef HIDE_LISP_IMPLEMENTATION
33 #include "lisp.h"
34 #include "intervals.h"
35 #include "puresize.h"
36 #include "buffer.h"
37 #include "window.h"
38 #include "frame.h"
39 #include "blockinput.h"
40 #include "keyboard.h"
41 #include "charset.h"
42 #include "syssignal.h"
43 #include <setjmp.h>
45 extern char *sbrk ();
47 #ifdef DOUG_LEA_MALLOC
49 #include <malloc.h>
50 #define __malloc_size_t int
52 /* Specify maximum number of areas to mmap. It would be nice to use a
53 value that explicitly means "no limit". */
55 #define MMAP_MAX_AREAS 100000000
57 #else /* not DOUG_LEA_MALLOC */
59 /* The following come from gmalloc.c. */
61 #if defined (__STDC__) && __STDC__
62 #include <stddef.h>
63 #define __malloc_size_t size_t
64 #else
65 #define __malloc_size_t unsigned int
66 #endif
67 extern __malloc_size_t _bytes_used;
68 extern int __malloc_extra_blocks;
70 #endif /* not DOUG_LEA_MALLOC */
72 #define max(A,B) ((A) > (B) ? (A) : (B))
73 #define min(A,B) ((A) < (B) ? (A) : (B))
75 /* Macro to verify that storage intended for Lisp objects is not
76 out of range to fit in the space for a pointer.
77 ADDRESS is the start of the block, and SIZE
78 is the amount of space within which objects can start. */
80 #define VALIDATE_LISP_STORAGE(address, size) \
81 do \
82 { \
83 Lisp_Object val; \
84 XSETCONS (val, (char *) address + size); \
85 if ((char *) XCONS (val) != (char *) address + size) \
86 { \
87 xfree (address); \
88 memory_full (); \
89 } \
90 } while (0)
92 /* Value of _bytes_used, when spare_memory was freed. */
94 static __malloc_size_t bytes_used_when_full;
96 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
97 to a struct Lisp_String. */
99 #define MARK_STRING(S) XMARK ((S)->size)
100 #define UNMARK_STRING(S) XUNMARK ((S)->size)
101 #define STRING_MARKED_P(S) XMARKBIT ((S)->size)
103 /* Value is the number of bytes/chars of S, a pointer to a struct
104 Lisp_String. This must be used instead of STRING_BYTES (S) or
105 S->size during GC, because S->size contains the mark bit for
106 strings. */
108 #define GC_STRING_BYTES(S) (STRING_BYTES (S) & ~MARKBIT)
109 #define GC_STRING_CHARS(S) ((S)->size & ~MARKBIT)
111 /* Number of bytes of consing done since the last gc. */
113 int consing_since_gc;
115 /* Count the amount of consing of various sorts of space. */
117 int cons_cells_consed;
118 int floats_consed;
119 int vector_cells_consed;
120 int symbols_consed;
121 int string_chars_consed;
122 int misc_objects_consed;
123 int intervals_consed;
124 int strings_consed;
126 /* Number of bytes of consing since GC before another GC should be done. */
128 int gc_cons_threshold;
130 /* Nonzero during GC. */
132 int gc_in_progress;
134 /* Nonzero means display messages at beginning and end of GC. */
136 int garbage_collection_messages;
138 #ifndef VIRT_ADDR_VARIES
139 extern
140 #endif /* VIRT_ADDR_VARIES */
141 int malloc_sbrk_used;
143 #ifndef VIRT_ADDR_VARIES
144 extern
145 #endif /* VIRT_ADDR_VARIES */
146 int malloc_sbrk_unused;
148 /* Two limits controlling how much undo information to keep. */
150 int undo_limit;
151 int undo_strong_limit;
153 /* Number of live and free conses etc. */
155 static int total_conses, total_markers, total_symbols, total_vector_size;
156 static int total_free_conses, total_free_markers, total_free_symbols;
157 static int total_free_floats, total_floats;
159 /* Points to memory space allocated as "spare", to be freed if we run
160 out of memory. */
162 static char *spare_memory;
164 /* Amount of spare memory to keep in reserve. */
166 #define SPARE_MEMORY (1 << 14)
168 /* Number of extra blocks malloc should get when it needs more core. */
170 static int malloc_hysteresis;
172 /* Nonzero when malloc is called for allocating Lisp object space.
173 Currently set but not used. */
175 int allocating_for_lisp;
177 /* Non-nil means defun should do purecopy on the function definition. */
179 Lisp_Object Vpurify_flag;
181 #ifndef HAVE_SHM
183 /* Force it into data space! */
185 EMACS_INT pure[PURESIZE / sizeof (EMACS_INT)] = {0,};
186 #define PUREBEG (char *) pure
188 #else /* not HAVE_SHM */
190 #define pure PURE_SEG_BITS /* Use shared memory segment */
191 #define PUREBEG (char *)PURE_SEG_BITS
193 /* This variable is used only by the XPNTR macro when HAVE_SHM is
194 defined. If we used the PURESIZE macro directly there, that would
195 make most of Emacs dependent on puresize.h, which we don't want -
196 you should be able to change that without too much recompilation.
197 So map_in_data initializes pure_size, and the dependencies work
198 out. */
200 EMACS_INT pure_size;
202 #endif /* not HAVE_SHM */
204 /* Value is non-zero if P points into pure space. */
206 #define PURE_POINTER_P(P) \
207 (((PNTR_COMPARISON_TYPE) (P) \
208 < (PNTR_COMPARISON_TYPE) ((char *) pure + PURESIZE)) \
209 && ((PNTR_COMPARISON_TYPE) (P) \
210 >= (PNTR_COMPARISON_TYPE) pure))
212 /* Index in pure at which next pure object will be allocated.. */
214 int pureptr;
216 /* If nonzero, this is a warning delivered by malloc and not yet
217 displayed. */
219 char *pending_malloc_warning;
221 /* Pre-computed signal argument for use when memory is exhausted. */
223 Lisp_Object memory_signal_data;
225 /* Maximum amount of C stack to save when a GC happens. */
227 #ifndef MAX_SAVE_STACK
228 #define MAX_SAVE_STACK 16000
229 #endif
231 /* Buffer in which we save a copy of the C stack at each GC. */
233 char *stack_copy;
234 int stack_copy_size;
236 /* Non-zero means ignore malloc warnings. Set during initialization.
237 Currently not used. */
239 int ignore_warnings;
241 Lisp_Object Qgc_cons_threshold, Qchar_table_extra_slots;
243 static void mark_buffer P_ ((Lisp_Object));
244 static void mark_kboards P_ ((void));
245 static void gc_sweep P_ ((void));
246 static void mark_glyph_matrix P_ ((struct glyph_matrix *));
247 static void mark_face_cache P_ ((struct face_cache *));
249 #ifdef HAVE_WINDOW_SYSTEM
250 static void mark_image P_ ((struct image *));
251 static void mark_image_cache P_ ((struct frame *));
252 #endif /* HAVE_WINDOW_SYSTEM */
254 static struct Lisp_String *allocate_string P_ ((void));
255 static void compact_small_strings P_ ((void));
256 static void free_large_strings P_ ((void));
257 static void sweep_strings P_ ((void));
259 extern int message_enable_multibyte;
261 /* When scanning the C stack for live Lisp objects, Emacs keeps track
262 of what memory allocated via lisp_malloc is intended for what
263 purpose. This enumeration specifies the type of memory. */
265 enum mem_type
267 MEM_TYPE_NON_LISP,
268 MEM_TYPE_BUFFER,
269 MEM_TYPE_CONS,
270 MEM_TYPE_STRING,
271 MEM_TYPE_MISC,
272 MEM_TYPE_SYMBOL,
273 MEM_TYPE_FLOAT,
274 MEM_TYPE_VECTOR
277 #if GC_MARK_STACK
279 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
280 #include <stdio.h> /* For fprintf. */
281 #endif
283 /* A unique object in pure space used to make some Lisp objects
284 on free lists recognizable in O(1). */
286 Lisp_Object Vdead;
288 struct mem_node;
289 static void *lisp_malloc P_ ((int, enum mem_type));
290 static void mark_stack P_ ((void));
291 static void init_stack P_ ((Lisp_Object *));
292 static int live_vector_p P_ ((struct mem_node *, void *));
293 static int live_buffer_p P_ ((struct mem_node *, void *));
294 static int live_string_p P_ ((struct mem_node *, void *));
295 static int live_cons_p P_ ((struct mem_node *, void *));
296 static int live_symbol_p P_ ((struct mem_node *, void *));
297 static int live_float_p P_ ((struct mem_node *, void *));
298 static int live_misc_p P_ ((struct mem_node *, void *));
299 static void mark_memory P_ ((void *, void *));
300 static void mem_init P_ ((void));
301 static struct mem_node *mem_insert P_ ((void *, void *, enum mem_type));
302 static void mem_insert_fixup P_ ((struct mem_node *));
303 static void mem_rotate_left P_ ((struct mem_node *));
304 static void mem_rotate_right P_ ((struct mem_node *));
305 static void mem_delete P_ ((struct mem_node *));
306 static void mem_delete_fixup P_ ((struct mem_node *));
307 static INLINE struct mem_node *mem_find P_ ((void *));
309 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
310 static void check_gcpros P_ ((void));
311 #endif
313 #endif /* GC_MARK_STACK != 0 */
316 /************************************************************************
317 Malloc
318 ************************************************************************/
320 /* Write STR to Vstandard_output plus some advice on how to free some
321 memory. Called when memory gets low. */
323 Lisp_Object
324 malloc_warning_1 (str)
325 Lisp_Object str;
327 Fprinc (str, Vstandard_output);
328 write_string ("\nKilling some buffers may delay running out of memory.\n", -1);
329 write_string ("However, certainly by the time you receive the 95% warning,\n", -1);
330 write_string ("you should clean up, kill this Emacs, and start a new one.", -1);
331 return Qnil;
335 /* Function malloc calls this if it finds we are near exhausting
336 storage. */
338 void
339 malloc_warning (str)
340 char *str;
342 pending_malloc_warning = str;
346 /* Display a malloc warning in buffer *Danger*. */
348 void
349 display_malloc_warning ()
351 register Lisp_Object val;
353 val = build_string (pending_malloc_warning);
354 pending_malloc_warning = 0;
355 internal_with_output_to_temp_buffer (" *Danger*", malloc_warning_1, val);
359 #ifdef DOUG_LEA_MALLOC
360 # define BYTES_USED (mallinfo ().arena)
361 #else
362 # define BYTES_USED _bytes_used
363 #endif
366 /* Called if malloc returns zero. */
368 void
369 memory_full ()
371 #ifndef SYSTEM_MALLOC
372 bytes_used_when_full = BYTES_USED;
373 #endif
375 /* The first time we get here, free the spare memory. */
376 if (spare_memory)
378 free (spare_memory);
379 spare_memory = 0;
382 /* This used to call error, but if we've run out of memory, we could
383 get infinite recursion trying to build the string. */
384 while (1)
385 Fsignal (Qnil, memory_signal_data);
389 /* Called if we can't allocate relocatable space for a buffer. */
391 void
392 buffer_memory_full ()
394 /* If buffers use the relocating allocator, no need to free
395 spare_memory, because we may have plenty of malloc space left
396 that we could get, and if we don't, the malloc that fails will
397 itself cause spare_memory to be freed. If buffers don't use the
398 relocating allocator, treat this like any other failing
399 malloc. */
401 #ifndef REL_ALLOC
402 memory_full ();
403 #endif
405 /* This used to call error, but if we've run out of memory, we could
406 get infinite recursion trying to build the string. */
407 while (1)
408 Fsignal (Qerror, memory_signal_data);
412 /* Like malloc but check for no memory and block interrupt input.. */
414 long *
415 xmalloc (size)
416 int size;
418 register long *val;
420 BLOCK_INPUT;
421 val = (long *) malloc (size);
422 UNBLOCK_INPUT;
424 if (!val && size)
425 memory_full ();
426 return val;
430 /* Like realloc but check for no memory and block interrupt input.. */
432 long *
433 xrealloc (block, size)
434 long *block;
435 int size;
437 register long *val;
439 BLOCK_INPUT;
440 /* We must call malloc explicitly when BLOCK is 0, since some
441 reallocs don't do this. */
442 if (! block)
443 val = (long *) malloc (size);
444 else
445 val = (long *) realloc (block, size);
446 UNBLOCK_INPUT;
448 if (!val && size) memory_full ();
449 return val;
453 /* Like free but block interrupt input.. */
455 void
456 xfree (block)
457 long *block;
459 BLOCK_INPUT;
460 free (block);
461 UNBLOCK_INPUT;
465 /* Like malloc but used for allocating Lisp data. NBYTES is the
466 number of bytes to allocate, TYPE describes the intended use of the
467 allcated memory block (for strings, for conses, ...). */
469 static void *
470 lisp_malloc (nbytes, type)
471 int nbytes;
472 enum mem_type type;
474 register void *val;
476 BLOCK_INPUT;
477 allocating_for_lisp++;
478 val = (void *) malloc (nbytes);
479 allocating_for_lisp--;
480 UNBLOCK_INPUT;
482 if (!val && nbytes)
483 memory_full ();
485 #if GC_MARK_STACK
486 if (type != MEM_TYPE_NON_LISP)
487 mem_insert (val, (char *) val + nbytes, type);
488 #endif
490 return val;
494 /* Return a new buffer structure allocated from the heap with
495 a call to lisp_malloc. */
497 struct buffer *
498 allocate_buffer ()
500 return (struct buffer *) lisp_malloc (sizeof (struct buffer),
501 MEM_TYPE_BUFFER);
505 /* Free BLOCK. This must be called to free memory allocated with a
506 call to lisp_malloc. */
508 void
509 lisp_free (block)
510 long *block;
512 BLOCK_INPUT;
513 allocating_for_lisp++;
514 free (block);
515 #if GC_MARK_STACK
516 mem_delete (mem_find (block));
517 #endif
518 allocating_for_lisp--;
519 UNBLOCK_INPUT;
523 /* Arranging to disable input signals while we're in malloc.
525 This only works with GNU malloc. To help out systems which can't
526 use GNU malloc, all the calls to malloc, realloc, and free
527 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
528 pairs; unfortunately, we have no idea what C library functions
529 might call malloc, so we can't really protect them unless you're
530 using GNU malloc. Fortunately, most of the major operating can use
531 GNU malloc. */
533 #ifndef SYSTEM_MALLOC
535 extern void * (*__malloc_hook) ();
536 static void * (*old_malloc_hook) ();
537 extern void * (*__realloc_hook) ();
538 static void * (*old_realloc_hook) ();
539 extern void (*__free_hook) ();
540 static void (*old_free_hook) ();
542 /* This function is used as the hook for free to call. */
544 static void
545 emacs_blocked_free (ptr)
546 void *ptr;
548 BLOCK_INPUT;
549 __free_hook = old_free_hook;
550 free (ptr);
551 /* If we released our reserve (due to running out of memory),
552 and we have a fair amount free once again,
553 try to set aside another reserve in case we run out once more. */
554 if (spare_memory == 0
555 /* Verify there is enough space that even with the malloc
556 hysteresis this call won't run out again.
557 The code here is correct as long as SPARE_MEMORY
558 is substantially larger than the block size malloc uses. */
559 && (bytes_used_when_full
560 > BYTES_USED + max (malloc_hysteresis, 4) * SPARE_MEMORY))
561 spare_memory = (char *) malloc (SPARE_MEMORY);
563 __free_hook = emacs_blocked_free;
564 UNBLOCK_INPUT;
568 /* If we released our reserve (due to running out of memory),
569 and we have a fair amount free once again,
570 try to set aside another reserve in case we run out once more.
572 This is called when a relocatable block is freed in ralloc.c. */
574 void
575 refill_memory_reserve ()
577 if (spare_memory == 0)
578 spare_memory = (char *) malloc (SPARE_MEMORY);
582 /* This function is the malloc hook that Emacs uses. */
584 static void *
585 emacs_blocked_malloc (size)
586 unsigned size;
588 void *value;
590 BLOCK_INPUT;
591 __malloc_hook = old_malloc_hook;
592 #ifdef DOUG_LEA_MALLOC
593 mallopt (M_TOP_PAD, malloc_hysteresis * 4096);
594 #else
595 __malloc_extra_blocks = malloc_hysteresis;
596 #endif
597 value = (void *) malloc (size);
598 __malloc_hook = emacs_blocked_malloc;
599 UNBLOCK_INPUT;
601 return value;
605 /* This function is the realloc hook that Emacs uses. */
607 static void *
608 emacs_blocked_realloc (ptr, size)
609 void *ptr;
610 unsigned size;
612 void *value;
614 BLOCK_INPUT;
615 __realloc_hook = old_realloc_hook;
616 value = (void *) realloc (ptr, size);
617 __realloc_hook = emacs_blocked_realloc;
618 UNBLOCK_INPUT;
620 return value;
624 /* Called from main to set up malloc to use our hooks. */
626 void
627 uninterrupt_malloc ()
629 if (__free_hook != emacs_blocked_free)
630 old_free_hook = __free_hook;
631 __free_hook = emacs_blocked_free;
633 if (__malloc_hook != emacs_blocked_malloc)
634 old_malloc_hook = __malloc_hook;
635 __malloc_hook = emacs_blocked_malloc;
637 if (__realloc_hook != emacs_blocked_realloc)
638 old_realloc_hook = __realloc_hook;
639 __realloc_hook = emacs_blocked_realloc;
642 #endif /* not SYSTEM_MALLOC */
646 /***********************************************************************
647 Interval Allocation
648 ***********************************************************************/
650 /* Number of intervals allocated in an interval_block structure.
651 The 1020 is 1024 minus malloc overhead. */
653 #define INTERVAL_BLOCK_SIZE \
654 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
656 /* Intervals are allocated in chunks in form of an interval_block
657 structure. */
659 struct interval_block
661 struct interval_block *next;
662 struct interval intervals[INTERVAL_BLOCK_SIZE];
665 /* Current interval block. Its `next' pointer points to older
666 blocks. */
668 struct interval_block *interval_block;
670 /* Index in interval_block above of the next unused interval
671 structure. */
673 static int interval_block_index;
675 /* Number of free and live intervals. */
677 static int total_free_intervals, total_intervals;
679 /* List of free intervals. */
681 INTERVAL interval_free_list;
683 /* Total number of interval blocks now in use. */
685 int n_interval_blocks;
688 /* Initialize interval allocation. */
690 static void
691 init_intervals ()
693 interval_block
694 = (struct interval_block *) lisp_malloc (sizeof *interval_block,
695 MEM_TYPE_NON_LISP);
696 interval_block->next = 0;
697 bzero ((char *) interval_block->intervals, sizeof interval_block->intervals);
698 interval_block_index = 0;
699 interval_free_list = 0;
700 n_interval_blocks = 1;
704 /* Return a new interval. */
706 INTERVAL
707 make_interval ()
709 INTERVAL val;
711 if (interval_free_list)
713 val = interval_free_list;
714 interval_free_list = interval_free_list->parent;
716 else
718 if (interval_block_index == INTERVAL_BLOCK_SIZE)
720 register struct interval_block *newi;
722 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
723 MEM_TYPE_NON_LISP);
725 VALIDATE_LISP_STORAGE (newi, sizeof *newi);
726 newi->next = interval_block;
727 interval_block = newi;
728 interval_block_index = 0;
729 n_interval_blocks++;
731 val = &interval_block->intervals[interval_block_index++];
733 consing_since_gc += sizeof (struct interval);
734 intervals_consed++;
735 RESET_INTERVAL (val);
736 return val;
740 /* Mark Lisp objects in interval I. */
742 static void
743 mark_interval (i, dummy)
744 register INTERVAL i;
745 Lisp_Object dummy;
747 if (XMARKBIT (i->plist))
748 abort ();
749 mark_object (&i->plist);
750 XMARK (i->plist);
754 /* Mark the interval tree rooted in TREE. Don't call this directly;
755 use the macro MARK_INTERVAL_TREE instead. */
757 static void
758 mark_interval_tree (tree)
759 register INTERVAL tree;
761 /* No need to test if this tree has been marked already; this
762 function is always called through the MARK_INTERVAL_TREE macro,
763 which takes care of that. */
765 /* XMARK expands to an assignment; the LHS of an assignment can't be
766 a cast. */
767 XMARK (* (Lisp_Object *) &tree->parent);
769 traverse_intervals (tree, 1, 0, mark_interval, Qnil);
773 /* Mark the interval tree rooted in I. */
775 #define MARK_INTERVAL_TREE(i) \
776 do { \
777 if (!NULL_INTERVAL_P (i) \
778 && ! XMARKBIT (*(Lisp_Object *) &i->parent)) \
779 mark_interval_tree (i); \
780 } while (0)
783 /* The oddity in the call to XUNMARK is necessary because XUNMARK
784 expands to an assignment to its argument, and most C compilers
785 don't support casts on the left operand of `='. */
787 #define UNMARK_BALANCE_INTERVALS(i) \
788 do { \
789 if (! NULL_INTERVAL_P (i)) \
791 XUNMARK (* (Lisp_Object *) (&(i)->parent)); \
792 (i) = balance_intervals (i); \
794 } while (0)
798 /***********************************************************************
799 String Allocation
800 ***********************************************************************/
802 /* Lisp_Strings are allocated in string_block structures. When a new
803 string_block is allocated, all the Lisp_Strings it contains are
804 added to a free-list stiing_free_list. When a new Lisp_String is
805 needed, it is taken from that list. During the sweep phase of GC,
806 string_blocks that are entirely free are freed, except two which
807 we keep.
809 String data is allocated from sblock structures. Strings larger
810 than LARGE_STRING_BYTES, get their own sblock, data for smaller
811 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
813 Sblocks consist internally of sdata structures, one for each
814 Lisp_String. The sdata structure points to the Lisp_String it
815 belongs to. The Lisp_String points back to the `u.data' member of
816 its sdata structure.
818 When a Lisp_String is freed during GC, it is put back on
819 string_free_list, and its `data' member and its sdata's `string'
820 pointer is set to null. The size of the string is recorded in the
821 `u.nbytes' member of the sdata. So, sdata structures that are no
822 longer used, can be easily recognized, and it's easy to compact the
823 sblocks of small strings which we do in compact_small_strings. */
825 /* Size in bytes of an sblock structure used for small strings. This
826 is 8192 minus malloc overhead. */
828 #define SBLOCK_SIZE 8188
830 /* Strings larger than this are considered large strings. String data
831 for large strings is allocated from individual sblocks. */
833 #define LARGE_STRING_BYTES 1024
835 /* Structure describing string memory sub-allocated from an sblock.
836 This is where the contents of Lisp strings are stored. */
838 struct sdata
840 /* Back-pointer to the string this sdata belongs to. If null, this
841 structure is free, and the NBYTES member of the union below
842 contains the string's byte size (the same value that STRING_BYTES
843 would return if STRING were non-null). If non-null, STRING_BYTES
844 (STRING) is the size of the data, and DATA contains the string's
845 contents. */
846 struct Lisp_String *string;
848 union
850 /* When STRING in non-null. */
851 unsigned char data[1];
853 /* When STRING is null. */
854 EMACS_INT nbytes;
855 } u;
858 /* Structure describing a block of memory which is sub-allocated to
859 obtain string data memory for strings. Blocks for small strings
860 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
861 as large as needed. */
863 struct sblock
865 /* Next in list. */
866 struct sblock *next;
868 /* Pointer to the next free sdata block. This points past the end
869 of the sblock if there isn't any space left in this block. */
870 struct sdata *next_free;
872 /* Start of data. */
873 struct sdata first_data;
876 /* Number of Lisp strings in a string_block structure. The 1020 is
877 1024 minus malloc overhead. */
879 #define STRINGS_IN_STRING_BLOCK \
880 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
882 /* Structure describing a block from which Lisp_String structures
883 are allocated. */
885 struct string_block
887 struct string_block *next;
888 struct Lisp_String strings[STRINGS_IN_STRING_BLOCK];
891 /* Head and tail of the list of sblock structures holding Lisp string
892 data. We always allocate from current_sblock. The NEXT pointers
893 in the sblock structures go from oldest_sblock to current_sblock. */
895 static struct sblock *oldest_sblock, *current_sblock;
897 /* List of sblocks for large strings. */
899 static struct sblock *large_sblocks;
901 /* List of string_block structures, and how many there are. */
903 static struct string_block *string_blocks;
904 static int n_string_blocks;
906 /* Free-list of Lisp_Strings. */
908 static struct Lisp_String *string_free_list;
910 /* Number of live and free Lisp_Strings. */
912 static int total_strings, total_free_strings;
914 /* Number of bytes used by live strings. */
916 static int total_string_size;
918 /* Given a pointer to a Lisp_String S which is on the free-list
919 string_free_list, return a pointer to its successor in the
920 free-list. */
922 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
924 /* Return a pointer to the sdata structure belonging to Lisp string S.
925 S must be live, i.e. S->data must not be null. S->data is actually
926 a pointer to the `u.data' member of its sdata structure; the
927 structure starts at a constant offset in front of that. */
929 #define SDATA_OF_STRING(S) \
930 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))
932 /* Value is the size of an sdata structure large enough to hold NBYTES
933 bytes of string data. The value returned includes a terminating
934 NUL byte, the size of the sdata structure, and padding. */
936 #define SDATA_SIZE(NBYTES) \
937 ((sizeof (struct Lisp_String *) \
938 + (NBYTES) + 1 \
939 + sizeof (EMACS_INT) - 1) \
940 & ~(sizeof (EMACS_INT) - 1))
943 /* Initialize string allocation. Called from init_alloc_once. */
945 void
946 init_strings ()
948 total_strings = total_free_strings = total_string_size = 0;
949 oldest_sblock = current_sblock = large_sblocks = NULL;
950 string_blocks = NULL;
951 n_string_blocks = 0;
952 string_free_list = NULL;
956 /* Return a new Lisp_String. */
958 static struct Lisp_String *
959 allocate_string ()
961 struct Lisp_String *s;
963 /* If the free-list is empty, allocate a new string_block, and
964 add all the Lisp_Strings in it to the free-list. */
965 if (string_free_list == NULL)
967 struct string_block *b;
968 int i;
970 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
971 VALIDATE_LISP_STORAGE (b, sizeof *b);
972 bzero (b, sizeof *b);
973 b->next = string_blocks;
974 string_blocks = b;
975 ++n_string_blocks;
977 for (i = STRINGS_IN_STRING_BLOCK - 1; i >= 0; --i)
979 s = b->strings + i;
980 NEXT_FREE_LISP_STRING (s) = string_free_list;
981 string_free_list = s;
984 total_free_strings += STRINGS_IN_STRING_BLOCK;
987 /* Pop a Lisp_String off the free-list. */
988 s = string_free_list;
989 string_free_list = NEXT_FREE_LISP_STRING (s);
991 /* Probably not strictly necessary, but play it safe. */
992 bzero (s, sizeof *s);
994 --total_free_strings;
995 ++total_strings;
996 ++strings_consed;
997 consing_since_gc += sizeof *s;
999 return s;
1003 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1004 plus a NUL byte at the end. Allocate an sdata structure for S, and
1005 set S->data to its `u.data' member. Store a NUL byte at the end of
1006 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1007 S->data if it was initially non-null. */
1009 void
1010 allocate_string_data (s, nchars, nbytes)
1011 struct Lisp_String *s;
1012 int nchars, nbytes;
1014 struct sdata *data;
1015 struct sblock *b;
1016 int needed;
1018 /* Determine the number of bytes needed to store NBYTES bytes
1019 of string data. */
1020 needed = SDATA_SIZE (nbytes);
1022 if (nbytes > LARGE_STRING_BYTES)
1024 int size = sizeof *b - sizeof (struct sdata) + needed;
1026 #ifdef DOUG_LEA_MALLOC
1027 /* Prevent mmap'ing the chunk (which is potentially very large). */
1028 mallopt (M_MMAP_MAX, 0);
1029 #endif
1031 b = (struct sblock *) lisp_malloc (size, MEM_TYPE_NON_LISP);
1033 #ifdef DOUG_LEA_MALLOC
1034 /* Back to a reasonable maximum of mmap'ed areas. */
1035 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1036 #endif
1038 b->next_free = &b->first_data;
1039 b->first_data.string = NULL;
1040 b->next = large_sblocks;
1041 large_sblocks = b;
1043 else if (current_sblock == NULL
1044 || (((char *) current_sblock + SBLOCK_SIZE
1045 - (char *) current_sblock->next_free)
1046 < needed))
1048 /* Not enough room in the current sblock. */
1049 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1050 b->next_free = &b->first_data;
1051 b->first_data.string = NULL;
1052 b->next = NULL;
1054 if (current_sblock)
1055 current_sblock->next = b;
1056 else
1057 oldest_sblock = b;
1058 current_sblock = b;
1060 else
1061 b = current_sblock;
1063 /* If S had already data assigned, mark that as free by setting
1064 its string back-pointer to null, and recording the size of
1065 the data in it.. */
1066 if (s->data)
1068 data = SDATA_OF_STRING (s);
1069 data->u.nbytes = GC_STRING_BYTES (s);
1070 data->string = NULL;
1073 data = b->next_free;
1074 data->string = s;
1075 s->data = data->u.data;
1076 s->size = nchars;
1077 s->size_byte = nbytes;
1078 s->data[nbytes] = '\0';
1079 b->next_free = (struct sdata *) ((char *) data + needed);
1081 consing_since_gc += needed;
1085 /* Sweep and compact strings. */
1087 static void
1088 sweep_strings ()
1090 struct string_block *b, *next;
1091 struct string_block *live_blocks = NULL;
1093 string_free_list = NULL;
1094 total_strings = total_free_strings = 0;
1095 total_string_size = 0;
1097 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1098 for (b = string_blocks; b; b = next)
1100 int i, nfree = 0;
1101 struct Lisp_String *free_list_before = string_free_list;
1103 next = b->next;
1105 for (i = 0; i < STRINGS_IN_STRING_BLOCK; ++i)
1107 struct Lisp_String *s = b->strings + i;
1109 if (s->data)
1111 /* String was not on free-list before. */
1112 if (STRING_MARKED_P (s))
1114 /* String is live; unmark it and its intervals. */
1115 UNMARK_STRING (s);
1117 if (!NULL_INTERVAL_P (s->intervals))
1118 UNMARK_BALANCE_INTERVALS (s->intervals);
1120 ++total_strings;
1121 total_string_size += STRING_BYTES (s);
1123 else
1125 /* String is dead. Put it on the free-list. */
1126 struct sdata *data = SDATA_OF_STRING (s);
1128 /* Save the size of S in its sdata so that we know
1129 how large that is. Reset the sdata's string
1130 back-pointer so that we know it's free. */
1131 data->u.nbytes = GC_STRING_BYTES (s);
1132 data->string = NULL;
1134 /* Reset the strings's `data' member so that we
1135 know it's free. */
1136 s->data = NULL;
1138 /* Put the string on the free-list. */
1139 NEXT_FREE_LISP_STRING (s) = string_free_list;
1140 string_free_list = s;
1141 ++nfree;
1144 else
1146 /* S was on the free-list before. Put it there again. */
1147 NEXT_FREE_LISP_STRING (s) = string_free_list;
1148 string_free_list = s;
1149 ++nfree;
1153 /* Free blocks that contain free Lisp_Strings only, except
1154 the first two of them. */
1155 if (nfree == STRINGS_IN_STRING_BLOCK
1156 && total_free_strings > STRINGS_IN_STRING_BLOCK)
1158 lisp_free (b);
1159 --n_string_blocks;
1160 string_free_list = free_list_before;
1162 else
1164 total_free_strings += nfree;
1165 b->next = live_blocks;
1166 live_blocks = b;
1170 string_blocks = live_blocks;
1171 free_large_strings ();
1172 compact_small_strings ();
1176 /* Free dead large strings. */
1178 static void
1179 free_large_strings ()
1181 struct sblock *b, *next;
1182 struct sblock *live_blocks = NULL;
1184 for (b = large_sblocks; b; b = next)
1186 next = b->next;
1188 if (b->first_data.string == NULL)
1189 lisp_free (b);
1190 else
1192 b->next = live_blocks;
1193 live_blocks = b;
1197 large_sblocks = live_blocks;
1201 /* Compact data of small strings. Free sblocks that don't contain
1202 data of live strings after compaction. */
1204 static void
1205 compact_small_strings ()
1207 struct sblock *b, *tb, *next;
1208 struct sdata *from, *to, *end, *tb_end;
1209 struct sdata *to_end, *from_end;
1211 /* TB is the sblock we copy to, TO is the sdata within TB we copy
1212 to, and TB_END is the end of TB. */
1213 tb = oldest_sblock;
1214 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1215 to = &tb->first_data;
1217 /* Step through the blocks from the oldest to the youngest. We
1218 expect that old blocks will stabilize over time, so that less
1219 copying will happen this way. */
1220 for (b = oldest_sblock; b; b = b->next)
1222 end = b->next_free;
1223 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
1225 for (from = &b->first_data; from < end; from = from_end)
1227 /* Compute the next FROM here because copying below may
1228 overwrite data we need to compute it. */
1229 int nbytes;
1231 if (from->string)
1232 nbytes = GC_STRING_BYTES (from->string);
1233 else
1234 nbytes = from->u.nbytes;
1236 nbytes = SDATA_SIZE (nbytes);
1237 from_end = (struct sdata *) ((char *) from + nbytes);
1239 /* FROM->string non-null means it's alive. Copy its data. */
1240 if (from->string)
1242 /* If TB is full, proceed with the next sblock. */
1243 to_end = (struct sdata *) ((char *) to + nbytes);
1244 if (to_end > tb_end)
1246 tb->next_free = to;
1247 tb = tb->next;
1248 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1249 to = &tb->first_data;
1250 to_end = (struct sdata *) ((char *) to + nbytes);
1253 /* Copy, and update the string's `data' pointer. */
1254 if (from != to)
1256 bcopy (from, to, nbytes);
1257 to->string->data = to->u.data;
1260 /* Advance past the sdata we copied to. */
1261 to = to_end;
1266 /* The rest of the sblocks following TB don't contain live data, so
1267 we can free them. */
1268 for (b = tb->next; b; b = next)
1270 next = b->next;
1271 lisp_free (b);
1274 tb->next_free = to;
1275 tb->next = NULL;
1276 current_sblock = tb;
1280 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
1281 "Return a newly created string of length LENGTH, with each element being INIT.\n\
1282 Both LENGTH and INIT must be numbers.")
1283 (length, init)
1284 Lisp_Object length, init;
1286 register Lisp_Object val;
1287 register unsigned char *p, *end;
1288 int c, nbytes;
1290 CHECK_NATNUM (length, 0);
1291 CHECK_NUMBER (init, 1);
1293 c = XINT (init);
1294 if (SINGLE_BYTE_CHAR_P (c))
1296 nbytes = XINT (length);
1297 val = make_uninit_string (nbytes);
1298 p = XSTRING (val)->data;
1299 end = p + XSTRING (val)->size;
1300 while (p != end)
1301 *p++ = c;
1303 else
1305 unsigned char str[4];
1306 int len = CHAR_STRING (c, str);
1308 nbytes = len * XINT (length);
1309 val = make_uninit_multibyte_string (XINT (length), nbytes);
1310 p = XSTRING (val)->data;
1311 end = p + nbytes;
1312 while (p != end)
1314 bcopy (str, p, len);
1315 p += len;
1319 *p = 0;
1320 return val;
1324 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
1325 "Return a new bool-vector of length LENGTH, using INIT for as each element.\n\
1326 LENGTH must be a number. INIT matters only in whether it is t or nil.")
1327 (length, init)
1328 Lisp_Object length, init;
1330 register Lisp_Object val;
1331 struct Lisp_Bool_Vector *p;
1332 int real_init, i;
1333 int length_in_chars, length_in_elts, bits_per_value;
1335 CHECK_NATNUM (length, 0);
1337 bits_per_value = sizeof (EMACS_INT) * BITS_PER_CHAR;
1339 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
1340 length_in_chars = ((XFASTINT (length) + BITS_PER_CHAR - 1) / BITS_PER_CHAR);
1342 /* We must allocate one more elements than LENGTH_IN_ELTS for the
1343 slot `size' of the struct Lisp_Bool_Vector. */
1344 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
1345 p = XBOOL_VECTOR (val);
1347 /* Get rid of any bits that would cause confusion. */
1348 p->vector_size = 0;
1349 XSETBOOL_VECTOR (val, p);
1350 p->size = XFASTINT (length);
1352 real_init = (NILP (init) ? 0 : -1);
1353 for (i = 0; i < length_in_chars ; i++)
1354 p->data[i] = real_init;
1356 /* Clear the extraneous bits in the last byte. */
1357 if (XINT (length) != length_in_chars * BITS_PER_CHAR)
1358 XBOOL_VECTOR (val)->data[length_in_chars - 1]
1359 &= (1 << (XINT (length) % BITS_PER_CHAR)) - 1;
1361 return val;
1365 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
1366 of characters from the contents. This string may be unibyte or
1367 multibyte, depending on the contents. */
1369 Lisp_Object
1370 make_string (contents, nbytes)
1371 char *contents;
1372 int nbytes;
1374 register Lisp_Object val;
1375 int nchars = chars_in_text (contents, nbytes);
1376 val = make_uninit_multibyte_string (nchars, nbytes);
1377 bcopy (contents, XSTRING (val)->data, nbytes);
1378 if (STRING_BYTES (XSTRING (val)) == XSTRING (val)->size)
1379 SET_STRING_BYTES (XSTRING (val), -1);
1380 return val;
1384 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
1386 Lisp_Object
1387 make_unibyte_string (contents, length)
1388 char *contents;
1389 int length;
1391 register Lisp_Object val;
1392 val = make_uninit_string (length);
1393 bcopy (contents, XSTRING (val)->data, length);
1394 SET_STRING_BYTES (XSTRING (val), -1);
1395 return val;
1399 /* Make a multibyte string from NCHARS characters occupying NBYTES
1400 bytes at CONTENTS. */
1402 Lisp_Object
1403 make_multibyte_string (contents, nchars, nbytes)
1404 char *contents;
1405 int nchars, nbytes;
1407 register Lisp_Object val;
1408 val = make_uninit_multibyte_string (nchars, nbytes);
1409 bcopy (contents, XSTRING (val)->data, nbytes);
1410 return val;
1414 /* Make a string from NCHARS characters occupying NBYTES bytes at
1415 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
1417 Lisp_Object
1418 make_string_from_bytes (contents, nchars, nbytes)
1419 char *contents;
1420 int nchars, nbytes;
1422 register Lisp_Object val;
1423 val = make_uninit_multibyte_string (nchars, nbytes);
1424 bcopy (contents, XSTRING (val)->data, nbytes);
1425 if (STRING_BYTES (XSTRING (val)) == XSTRING (val)->size)
1426 SET_STRING_BYTES (XSTRING (val), -1);
1427 return val;
1431 /* Make a string from NCHARS characters occupying NBYTES bytes at
1432 CONTENTS. The argument MULTIBYTE controls whether to label the
1433 string as multibyte. */
1435 Lisp_Object
1436 make_specified_string (contents, nchars, nbytes, multibyte)
1437 char *contents;
1438 int nchars, nbytes;
1439 int multibyte;
1441 register Lisp_Object val;
1442 val = make_uninit_multibyte_string (nchars, nbytes);
1443 bcopy (contents, XSTRING (val)->data, nbytes);
1444 if (!multibyte)
1445 SET_STRING_BYTES (XSTRING (val), -1);
1446 return val;
1450 /* Make a string from the data at STR, treating it as multibyte if the
1451 data warrants. */
1453 Lisp_Object
1454 build_string (str)
1455 char *str;
1457 return make_string (str, strlen (str));
1461 /* Return an unibyte Lisp_String set up to hold LENGTH characters
1462 occupying LENGTH bytes. */
1464 Lisp_Object
1465 make_uninit_string (length)
1466 int length;
1468 Lisp_Object val;
1469 val = make_uninit_multibyte_string (length, length);
1470 SET_STRING_BYTES (XSTRING (val), -1);
1471 return val;
1475 /* Return a multibyte Lisp_String set up to hold NCHARS characters
1476 which occupy NBYTES bytes. */
1478 Lisp_Object
1479 make_uninit_multibyte_string (nchars, nbytes)
1480 int nchars, nbytes;
1482 Lisp_Object string;
1483 struct Lisp_String *s;
1485 if (nchars < 0)
1486 abort ();
1488 s = allocate_string ();
1489 allocate_string_data (s, nchars, nbytes);
1490 XSETSTRING (string, s);
1491 string_chars_consed += nbytes;
1492 return string;
1497 /***********************************************************************
1498 Float Allocation
1499 ***********************************************************************/
1501 /* We store float cells inside of float_blocks, allocating a new
1502 float_block with malloc whenever necessary. Float cells reclaimed
1503 by GC are put on a free list to be reallocated before allocating
1504 any new float cells from the latest float_block.
1506 Each float_block is just under 1020 bytes long, since malloc really
1507 allocates in units of powers of two and uses 4 bytes for its own
1508 overhead. */
1510 #define FLOAT_BLOCK_SIZE \
1511 ((1020 - sizeof (struct float_block *)) / sizeof (struct Lisp_Float))
1513 struct float_block
1515 struct float_block *next;
1516 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
1519 /* Current float_block. */
1521 struct float_block *float_block;
1523 /* Index of first unused Lisp_Float in the current float_block. */
1525 int float_block_index;
1527 /* Total number of float blocks now in use. */
1529 int n_float_blocks;
1531 /* Free-list of Lisp_Floats. */
1533 struct Lisp_Float *float_free_list;
1536 /* Initialze float allocation. */
1538 void
1539 init_float ()
1541 float_block = (struct float_block *) lisp_malloc (sizeof *float_block,
1542 MEM_TYPE_FLOAT);
1543 float_block->next = 0;
1544 bzero ((char *) float_block->floats, sizeof float_block->floats);
1545 float_block_index = 0;
1546 float_free_list = 0;
1547 n_float_blocks = 1;
1551 /* Explicitly free a float cell by putting it on the free-list. */
1553 void
1554 free_float (ptr)
1555 struct Lisp_Float *ptr;
1557 *(struct Lisp_Float **)&ptr->data = float_free_list;
1558 #if GC_MARK_STACK
1559 ptr->type = Vdead;
1560 #endif
1561 float_free_list = ptr;
1565 /* Return a new float object with value FLOAT_VALUE. */
1567 Lisp_Object
1568 make_float (float_value)
1569 double float_value;
1571 register Lisp_Object val;
1573 if (float_free_list)
1575 /* We use the data field for chaining the free list
1576 so that we won't use the same field that has the mark bit. */
1577 XSETFLOAT (val, float_free_list);
1578 float_free_list = *(struct Lisp_Float **)&float_free_list->data;
1580 else
1582 if (float_block_index == FLOAT_BLOCK_SIZE)
1584 register struct float_block *new;
1586 new = (struct float_block *) lisp_malloc (sizeof *new,
1587 MEM_TYPE_FLOAT);
1588 VALIDATE_LISP_STORAGE (new, sizeof *new);
1589 new->next = float_block;
1590 float_block = new;
1591 float_block_index = 0;
1592 n_float_blocks++;
1594 XSETFLOAT (val, &float_block->floats[float_block_index++]);
1597 XFLOAT_DATA (val) = float_value;
1598 XSETFASTINT (XFLOAT (val)->type, 0); /* bug chasing -wsr */
1599 consing_since_gc += sizeof (struct Lisp_Float);
1600 floats_consed++;
1601 return val;
1606 /***********************************************************************
1607 Cons Allocation
1608 ***********************************************************************/
1610 /* We store cons cells inside of cons_blocks, allocating a new
1611 cons_block with malloc whenever necessary. Cons cells reclaimed by
1612 GC are put on a free list to be reallocated before allocating
1613 any new cons cells from the latest cons_block.
1615 Each cons_block is just under 1020 bytes long,
1616 since malloc really allocates in units of powers of two
1617 and uses 4 bytes for its own overhead. */
1619 #define CONS_BLOCK_SIZE \
1620 ((1020 - sizeof (struct cons_block *)) / sizeof (struct Lisp_Cons))
1622 struct cons_block
1624 struct cons_block *next;
1625 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
1628 /* Current cons_block. */
1630 struct cons_block *cons_block;
1632 /* Index of first unused Lisp_Cons in the current block. */
1634 int cons_block_index;
1636 /* Free-list of Lisp_Cons structures. */
1638 struct Lisp_Cons *cons_free_list;
1640 /* Total number of cons blocks now in use. */
1642 int n_cons_blocks;
1645 /* Initialize cons allocation. */
1647 void
1648 init_cons ()
1650 cons_block = (struct cons_block *) lisp_malloc (sizeof *cons_block,
1651 MEM_TYPE_CONS);
1652 cons_block->next = 0;
1653 bzero ((char *) cons_block->conses, sizeof cons_block->conses);
1654 cons_block_index = 0;
1655 cons_free_list = 0;
1656 n_cons_blocks = 1;
1660 /* Explicitly free a cons cell by putting it on the free-list. */
1662 void
1663 free_cons (ptr)
1664 struct Lisp_Cons *ptr;
1666 *(struct Lisp_Cons **)&ptr->cdr = cons_free_list;
1667 #if GC_MARK_STACK
1668 ptr->car = Vdead;
1669 #endif
1670 cons_free_list = ptr;
1674 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
1675 "Create a new cons, give it CAR and CDR as components, and return it.")
1676 (car, cdr)
1677 Lisp_Object car, cdr;
1679 register Lisp_Object val;
1681 if (cons_free_list)
1683 /* We use the cdr for chaining the free list
1684 so that we won't use the same field that has the mark bit. */
1685 XSETCONS (val, cons_free_list);
1686 cons_free_list = *(struct Lisp_Cons **)&cons_free_list->cdr;
1688 else
1690 if (cons_block_index == CONS_BLOCK_SIZE)
1692 register struct cons_block *new;
1693 new = (struct cons_block *) lisp_malloc (sizeof *new,
1694 MEM_TYPE_CONS);
1695 VALIDATE_LISP_STORAGE (new, sizeof *new);
1696 new->next = cons_block;
1697 cons_block = new;
1698 cons_block_index = 0;
1699 n_cons_blocks++;
1701 XSETCONS (val, &cons_block->conses[cons_block_index++]);
1704 XCAR (val) = car;
1705 XCDR (val) = cdr;
1706 consing_since_gc += sizeof (struct Lisp_Cons);
1707 cons_cells_consed++;
1708 return val;
1712 /* Make a list of 2, 3, 4 or 5 specified objects. */
1714 Lisp_Object
1715 list2 (arg1, arg2)
1716 Lisp_Object arg1, arg2;
1718 return Fcons (arg1, Fcons (arg2, Qnil));
1722 Lisp_Object
1723 list3 (arg1, arg2, arg3)
1724 Lisp_Object arg1, arg2, arg3;
1726 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
1730 Lisp_Object
1731 list4 (arg1, arg2, arg3, arg4)
1732 Lisp_Object arg1, arg2, arg3, arg4;
1734 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
1738 Lisp_Object
1739 list5 (arg1, arg2, arg3, arg4, arg5)
1740 Lisp_Object arg1, arg2, arg3, arg4, arg5;
1742 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
1743 Fcons (arg5, Qnil)))));
1747 DEFUN ("list", Flist, Slist, 0, MANY, 0,
1748 "Return a newly created list with specified arguments as elements.\n\
1749 Any number of arguments, even zero arguments, are allowed.")
1750 (nargs, args)
1751 int nargs;
1752 register Lisp_Object *args;
1754 register Lisp_Object val;
1755 val = Qnil;
1757 while (nargs > 0)
1759 nargs--;
1760 val = Fcons (args[nargs], val);
1762 return val;
1766 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
1767 "Return a newly created list of length LENGTH, with each element being INIT.")
1768 (length, init)
1769 register Lisp_Object length, init;
1771 register Lisp_Object val;
1772 register int size;
1774 CHECK_NATNUM (length, 0);
1775 size = XFASTINT (length);
1777 val = Qnil;
1778 while (size-- > 0)
1779 val = Fcons (init, val);
1780 return val;
1785 /***********************************************************************
1786 Vector Allocation
1787 ***********************************************************************/
1789 /* Singly-linked list of all vectors. */
1791 struct Lisp_Vector *all_vectors;
1793 /* Total number of vector-like objects now in use. */
1795 int n_vectors;
1798 /* Value is a pointer to a newly allocated Lisp_Vector structure
1799 with room for LEN Lisp_Objects. */
1801 struct Lisp_Vector *
1802 allocate_vectorlike (len)
1803 EMACS_INT len;
1805 struct Lisp_Vector *p;
1806 int nbytes;
1808 #ifdef DOUG_LEA_MALLOC
1809 /* Prevent mmap'ing the chunk (which is potentially very large).. */
1810 mallopt (M_MMAP_MAX, 0);
1811 #endif
1813 nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
1814 p = (struct Lisp_Vector *) lisp_malloc (nbytes, MEM_TYPE_VECTOR);
1816 #ifdef DOUG_LEA_MALLOC
1817 /* Back to a reasonable maximum of mmap'ed areas. */
1818 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1819 #endif
1821 VALIDATE_LISP_STORAGE (p, 0);
1822 consing_since_gc += nbytes;
1823 vector_cells_consed += len;
1825 p->next = all_vectors;
1826 all_vectors = p;
1827 ++n_vectors;
1828 return p;
1832 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
1833 "Return a newly created vector of length LENGTH, with each element being INIT.\n\
1834 See also the function `vector'.")
1835 (length, init)
1836 register Lisp_Object length, init;
1838 Lisp_Object vector;
1839 register EMACS_INT sizei;
1840 register int index;
1841 register struct Lisp_Vector *p;
1843 CHECK_NATNUM (length, 0);
1844 sizei = XFASTINT (length);
1846 p = allocate_vectorlike (sizei);
1847 p->size = sizei;
1848 for (index = 0; index < sizei; index++)
1849 p->contents[index] = init;
1851 XSETVECTOR (vector, p);
1852 return vector;
1856 DEFUN ("make-char-table", Fmake_char_table, Smake_char_table, 1, 2, 0,
1857 "Return a newly created char-table, with purpose PURPOSE.\n\
1858 Each element is initialized to INIT, which defaults to nil.\n\
1859 PURPOSE should be a symbol which has a `char-table-extra-slots' property.\n\
1860 The property's value should be an integer between 0 and 10.")
1861 (purpose, init)
1862 register Lisp_Object purpose, init;
1864 Lisp_Object vector;
1865 Lisp_Object n;
1866 CHECK_SYMBOL (purpose, 1);
1867 n = Fget (purpose, Qchar_table_extra_slots);
1868 CHECK_NUMBER (n, 0);
1869 if (XINT (n) < 0 || XINT (n) > 10)
1870 args_out_of_range (n, Qnil);
1871 /* Add 2 to the size for the defalt and parent slots. */
1872 vector = Fmake_vector (make_number (CHAR_TABLE_STANDARD_SLOTS + XINT (n)),
1873 init);
1874 XCHAR_TABLE (vector)->top = Qt;
1875 XCHAR_TABLE (vector)->parent = Qnil;
1876 XCHAR_TABLE (vector)->purpose = purpose;
1877 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
1878 return vector;
1882 /* Return a newly created sub char table with default value DEFALT.
1883 Since a sub char table does not appear as a top level Emacs Lisp
1884 object, we don't need a Lisp interface to make it. */
1886 Lisp_Object
1887 make_sub_char_table (defalt)
1888 Lisp_Object defalt;
1890 Lisp_Object vector
1891 = Fmake_vector (make_number (SUB_CHAR_TABLE_STANDARD_SLOTS), Qnil);
1892 XCHAR_TABLE (vector)->top = Qnil;
1893 XCHAR_TABLE (vector)->defalt = defalt;
1894 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
1895 return vector;
1899 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
1900 "Return a newly created vector with specified arguments as elements.\n\
1901 Any number of arguments, even zero arguments, are allowed.")
1902 (nargs, args)
1903 register int nargs;
1904 Lisp_Object *args;
1906 register Lisp_Object len, val;
1907 register int index;
1908 register struct Lisp_Vector *p;
1910 XSETFASTINT (len, nargs);
1911 val = Fmake_vector (len, Qnil);
1912 p = XVECTOR (val);
1913 for (index = 0; index < nargs; index++)
1914 p->contents[index] = args[index];
1915 return val;
1919 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
1920 "Create a byte-code object with specified arguments as elements.\n\
1921 The arguments should be the arglist, bytecode-string, constant vector,\n\
1922 stack size, (optional) doc string, and (optional) interactive spec.\n\
1923 The first four arguments are required; at most six have any\n\
1924 significance.")
1925 (nargs, args)
1926 register int nargs;
1927 Lisp_Object *args;
1929 register Lisp_Object len, val;
1930 register int index;
1931 register struct Lisp_Vector *p;
1933 XSETFASTINT (len, nargs);
1934 if (!NILP (Vpurify_flag))
1935 val = make_pure_vector ((EMACS_INT) nargs);
1936 else
1937 val = Fmake_vector (len, Qnil);
1938 p = XVECTOR (val);
1939 for (index = 0; index < nargs; index++)
1941 if (!NILP (Vpurify_flag))
1942 args[index] = Fpurecopy (args[index]);
1943 p->contents[index] = args[index];
1945 XSETCOMPILED (val, p);
1946 return val;
1951 /***********************************************************************
1952 Symbol Allocation
1953 ***********************************************************************/
1955 /* Each symbol_block is just under 1020 bytes long, since malloc
1956 really allocates in units of powers of two and uses 4 bytes for its
1957 own overhead. */
1959 #define SYMBOL_BLOCK_SIZE \
1960 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
1962 struct symbol_block
1964 struct symbol_block *next;
1965 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
1968 /* Current symbol block and index of first unused Lisp_Symbol
1969 structure in it. */
1971 struct symbol_block *symbol_block;
1972 int symbol_block_index;
1974 /* List of free symbols. */
1976 struct Lisp_Symbol *symbol_free_list;
1978 /* Total number of symbol blocks now in use. */
1980 int n_symbol_blocks;
1983 /* Initialize symbol allocation. */
1985 void
1986 init_symbol ()
1988 symbol_block = (struct symbol_block *) lisp_malloc (sizeof *symbol_block,
1989 MEM_TYPE_SYMBOL);
1990 symbol_block->next = 0;
1991 bzero ((char *) symbol_block->symbols, sizeof symbol_block->symbols);
1992 symbol_block_index = 0;
1993 symbol_free_list = 0;
1994 n_symbol_blocks = 1;
1998 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
1999 "Return a newly allocated uninterned symbol whose name is NAME.\n\
2000 Its value and function definition are void, and its property list is nil.")
2001 (name)
2002 Lisp_Object name;
2004 register Lisp_Object val;
2005 register struct Lisp_Symbol *p;
2007 CHECK_STRING (name, 0);
2009 if (symbol_free_list)
2011 XSETSYMBOL (val, symbol_free_list);
2012 symbol_free_list = *(struct Lisp_Symbol **)&symbol_free_list->value;
2014 else
2016 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
2018 struct symbol_block *new;
2019 new = (struct symbol_block *) lisp_malloc (sizeof *new,
2020 MEM_TYPE_SYMBOL);
2021 VALIDATE_LISP_STORAGE (new, sizeof *new);
2022 new->next = symbol_block;
2023 symbol_block = new;
2024 symbol_block_index = 0;
2025 n_symbol_blocks++;
2027 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index++]);
2030 p = XSYMBOL (val);
2031 p->name = XSTRING (name);
2032 p->obarray = Qnil;
2033 p->plist = Qnil;
2034 p->value = Qunbound;
2035 p->function = Qunbound;
2036 p->next = 0;
2037 consing_since_gc += sizeof (struct Lisp_Symbol);
2038 symbols_consed++;
2039 return val;
2044 /***********************************************************************
2045 Marker (Misc) Allocation
2046 ***********************************************************************/
2048 /* Allocation of markers and other objects that share that structure.
2049 Works like allocation of conses. */
2051 #define MARKER_BLOCK_SIZE \
2052 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
2054 struct marker_block
2056 struct marker_block *next;
2057 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
2060 struct marker_block *marker_block;
2061 int marker_block_index;
2063 union Lisp_Misc *marker_free_list;
2065 /* Total number of marker blocks now in use. */
2067 int n_marker_blocks;
2069 void
2070 init_marker ()
2072 marker_block = (struct marker_block *) lisp_malloc (sizeof *marker_block,
2073 MEM_TYPE_MISC);
2074 marker_block->next = 0;
2075 bzero ((char *) marker_block->markers, sizeof marker_block->markers);
2076 marker_block_index = 0;
2077 marker_free_list = 0;
2078 n_marker_blocks = 1;
2081 /* Return a newly allocated Lisp_Misc object, with no substructure. */
2083 Lisp_Object
2084 allocate_misc ()
2086 Lisp_Object val;
2088 if (marker_free_list)
2090 XSETMISC (val, marker_free_list);
2091 marker_free_list = marker_free_list->u_free.chain;
2093 else
2095 if (marker_block_index == MARKER_BLOCK_SIZE)
2097 struct marker_block *new;
2098 new = (struct marker_block *) lisp_malloc (sizeof *new,
2099 MEM_TYPE_MISC);
2100 VALIDATE_LISP_STORAGE (new, sizeof *new);
2101 new->next = marker_block;
2102 marker_block = new;
2103 marker_block_index = 0;
2104 n_marker_blocks++;
2106 XSETMISC (val, &marker_block->markers[marker_block_index++]);
2109 consing_since_gc += sizeof (union Lisp_Misc);
2110 misc_objects_consed++;
2111 return val;
2114 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
2115 "Return a newly allocated marker which does not point at any place.")
2118 register Lisp_Object val;
2119 register struct Lisp_Marker *p;
2121 val = allocate_misc ();
2122 XMISCTYPE (val) = Lisp_Misc_Marker;
2123 p = XMARKER (val);
2124 p->buffer = 0;
2125 p->bytepos = 0;
2126 p->charpos = 0;
2127 p->chain = Qnil;
2128 p->insertion_type = 0;
2129 return val;
2132 /* Put MARKER back on the free list after using it temporarily. */
2134 void
2135 free_marker (marker)
2136 Lisp_Object marker;
2138 unchain_marker (marker);
2140 XMISC (marker)->u_marker.type = Lisp_Misc_Free;
2141 XMISC (marker)->u_free.chain = marker_free_list;
2142 marker_free_list = XMISC (marker);
2144 total_free_markers++;
2148 /* Return a newly created vector or string with specified arguments as
2149 elements. If all the arguments are characters that can fit
2150 in a string of events, make a string; otherwise, make a vector.
2152 Any number of arguments, even zero arguments, are allowed. */
2154 Lisp_Object
2155 make_event_array (nargs, args)
2156 register int nargs;
2157 Lisp_Object *args;
2159 int i;
2161 for (i = 0; i < nargs; i++)
2162 /* The things that fit in a string
2163 are characters that are in 0...127,
2164 after discarding the meta bit and all the bits above it. */
2165 if (!INTEGERP (args[i])
2166 || (XUINT (args[i]) & ~(-CHAR_META)) >= 0200)
2167 return Fvector (nargs, args);
2169 /* Since the loop exited, we know that all the things in it are
2170 characters, so we can make a string. */
2172 Lisp_Object result;
2174 result = Fmake_string (make_number (nargs), make_number (0));
2175 for (i = 0; i < nargs; i++)
2177 XSTRING (result)->data[i] = XINT (args[i]);
2178 /* Move the meta bit to the right place for a string char. */
2179 if (XINT (args[i]) & CHAR_META)
2180 XSTRING (result)->data[i] |= 0x80;
2183 return result;
2189 /************************************************************************
2190 C Stack Marking
2191 ************************************************************************/
2193 #if GC_MARK_STACK
2196 /* Base address of stack. Set in main. */
2198 Lisp_Object *stack_base;
2200 /* A node in the red-black tree describing allocated memory containing
2201 Lisp data. Each such block is recorded with its start and end
2202 address when it is allocated, and removed from the tree when it
2203 is freed.
2205 A red-black tree is a balanced binary tree with the following
2206 properties:
2208 1. Every node is either red or black.
2209 2. Every leaf is black.
2210 3. If a node is red, then both of its children are black.
2211 4. Every simple path from a node to a descendant leaf contains
2212 the same number of black nodes.
2213 5. The root is always black.
2215 When nodes are inserted into the tree, or deleted from the tree,
2216 the tree is "fixed" so that these properties are always true.
2218 A red-black tree with N internal nodes has height at most 2
2219 log(N+1). Searches, insertions and deletions are done in O(log N).
2220 Please see a text book about data structures for a detailed
2221 description of red-black trees. Any book worth its salt should
2222 describe them. */
2224 struct mem_node
2226 struct mem_node *left, *right, *parent;
2228 /* Start and end of allocated region. */
2229 void *start, *end;
2231 /* Node color. */
2232 enum {MEM_BLACK, MEM_RED} color;
2234 /* Memory type. */
2235 enum mem_type type;
2238 /* Root of the tree describing allocated Lisp memory. */
2240 static struct mem_node *mem_root;
2242 /* Sentinel node of the tree. */
2244 static struct mem_node mem_z;
2245 #define MEM_NIL &mem_z
2248 /* Initialize this part of alloc.c. */
2250 static void
2251 mem_init ()
2253 mem_z.left = mem_z.right = MEM_NIL;
2254 mem_z.parent = NULL;
2255 mem_z.color = MEM_BLACK;
2256 mem_z.start = mem_z.end = NULL;
2257 mem_root = MEM_NIL;
2261 /* Value is a pointer to the mem_node containing START. Value is
2262 MEM_NIL if there is no node in the tree containing START. */
2264 static INLINE struct mem_node *
2265 mem_find (start)
2266 void *start;
2268 struct mem_node *p;
2270 /* Make the search always successful to speed up the loop below. */
2271 mem_z.start = start;
2272 mem_z.end = (char *) start + 1;
2274 p = mem_root;
2275 while (start < p->start || start >= p->end)
2276 p = start < p->start ? p->left : p->right;
2277 return p;
2281 /* Insert a new node into the tree for a block of memory with start
2282 address START, end address END, and type TYPE. Value is a
2283 pointer to the node that was inserted. */
2285 static struct mem_node *
2286 mem_insert (start, end, type)
2287 void *start, *end;
2288 enum mem_type type;
2290 struct mem_node *c, *parent, *x;
2292 /* See where in the tree a node for START belongs. In this
2293 particular application, it shouldn't happen that a node is already
2294 present. For debugging purposes, let's check that. */
2295 c = mem_root;
2296 parent = NULL;
2298 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
2300 while (c != MEM_NIL)
2302 if (start >= c->start && start < c->end)
2303 abort ();
2304 parent = c;
2305 c = start < c->start ? c->left : c->right;
2308 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2310 while (c != MEM_NIL)
2312 parent = c;
2313 c = start < c->start ? c->left : c->right;
2316 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2318 /* Create a new node. */
2319 x = (struct mem_node *) xmalloc (sizeof *x);
2320 x->start = start;
2321 x->end = end;
2322 x->type = type;
2323 x->parent = parent;
2324 x->left = x->right = MEM_NIL;
2325 x->color = MEM_RED;
2327 /* Insert it as child of PARENT or install it as root. */
2328 if (parent)
2330 if (start < parent->start)
2331 parent->left = x;
2332 else
2333 parent->right = x;
2335 else
2336 mem_root = x;
2338 /* Re-establish red-black tree properties. */
2339 mem_insert_fixup (x);
2340 return x;
2344 /* Re-establish the red-black properties of the tree, and thereby
2345 balance the tree, after node X has been inserted; X is always red. */
2347 static void
2348 mem_insert_fixup (x)
2349 struct mem_node *x;
2351 while (x != mem_root && x->parent->color == MEM_RED)
2353 /* X is red and its parent is red. This is a violation of
2354 red-black tree property #3. */
2356 if (x->parent == x->parent->parent->left)
2358 /* We're on the left side of our grandparent, and Y is our
2359 "uncle". */
2360 struct mem_node *y = x->parent->parent->right;
2362 if (y->color == MEM_RED)
2364 /* Uncle and parent are red but should be black because
2365 X is red. Change the colors accordingly and proceed
2366 with the grandparent. */
2367 x->parent->color = MEM_BLACK;
2368 y->color = MEM_BLACK;
2369 x->parent->parent->color = MEM_RED;
2370 x = x->parent->parent;
2372 else
2374 /* Parent and uncle have different colors; parent is
2375 red, uncle is black. */
2376 if (x == x->parent->right)
2378 x = x->parent;
2379 mem_rotate_left (x);
2382 x->parent->color = MEM_BLACK;
2383 x->parent->parent->color = MEM_RED;
2384 mem_rotate_right (x->parent->parent);
2387 else
2389 /* This is the symmetrical case of above. */
2390 struct mem_node *y = x->parent->parent->left;
2392 if (y->color == MEM_RED)
2394 x->parent->color = MEM_BLACK;
2395 y->color = MEM_BLACK;
2396 x->parent->parent->color = MEM_RED;
2397 x = x->parent->parent;
2399 else
2401 if (x == x->parent->left)
2403 x = x->parent;
2404 mem_rotate_right (x);
2407 x->parent->color = MEM_BLACK;
2408 x->parent->parent->color = MEM_RED;
2409 mem_rotate_left (x->parent->parent);
2414 /* The root may have been changed to red due to the algorithm. Set
2415 it to black so that property #5 is satisfied. */
2416 mem_root->color = MEM_BLACK;
2420 /* (x) (y)
2421 / \ / \
2422 a (y) ===> (x) c
2423 / \ / \
2424 b c a b */
2426 static void
2427 mem_rotate_left (x)
2428 struct mem_node *x;
2430 struct mem_node *y;
2432 /* Turn y's left sub-tree into x's right sub-tree. */
2433 y = x->right;
2434 x->right = y->left;
2435 if (y->left != MEM_NIL)
2436 y->left->parent = x;
2438 /* Y's parent was x's parent. */
2439 if (y != MEM_NIL)
2440 y->parent = x->parent;
2442 /* Get the parent to point to y instead of x. */
2443 if (x->parent)
2445 if (x == x->parent->left)
2446 x->parent->left = y;
2447 else
2448 x->parent->right = y;
2450 else
2451 mem_root = y;
2453 /* Put x on y's left. */
2454 y->left = x;
2455 if (x != MEM_NIL)
2456 x->parent = y;
2460 /* (x) (Y)
2461 / \ / \
2462 (y) c ===> a (x)
2463 / \ / \
2464 a b b c */
2466 static void
2467 mem_rotate_right (x)
2468 struct mem_node *x;
2470 struct mem_node *y = x->left;
2472 x->left = y->right;
2473 if (y->right != MEM_NIL)
2474 y->right->parent = x;
2476 if (y != MEM_NIL)
2477 y->parent = x->parent;
2478 if (x->parent)
2480 if (x == x->parent->right)
2481 x->parent->right = y;
2482 else
2483 x->parent->left = y;
2485 else
2486 mem_root = y;
2488 y->right = x;
2489 if (x != MEM_NIL)
2490 x->parent = y;
2494 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
2496 static void
2497 mem_delete (z)
2498 struct mem_node *z;
2500 struct mem_node *x, *y;
2502 if (!z || z == MEM_NIL)
2503 return;
2505 if (z->left == MEM_NIL || z->right == MEM_NIL)
2506 y = z;
2507 else
2509 y = z->right;
2510 while (y->left != MEM_NIL)
2511 y = y->left;
2514 if (y->left != MEM_NIL)
2515 x = y->left;
2516 else
2517 x = y->right;
2519 x->parent = y->parent;
2520 if (y->parent)
2522 if (y == y->parent->left)
2523 y->parent->left = x;
2524 else
2525 y->parent->right = x;
2527 else
2528 mem_root = x;
2530 if (y != z)
2532 z->start = y->start;
2533 z->end = y->end;
2534 z->type = y->type;
2537 if (y->color == MEM_BLACK)
2538 mem_delete_fixup (x);
2539 xfree (y);
2543 /* Re-establish the red-black properties of the tree, after a
2544 deletion. */
2546 static void
2547 mem_delete_fixup (x)
2548 struct mem_node *x;
2550 while (x != mem_root && x->color == MEM_BLACK)
2552 if (x == x->parent->left)
2554 struct mem_node *w = x->parent->right;
2556 if (w->color == MEM_RED)
2558 w->color = MEM_BLACK;
2559 x->parent->color = MEM_RED;
2560 mem_rotate_left (x->parent);
2561 w = x->parent->right;
2564 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
2566 w->color = MEM_RED;
2567 x = x->parent;
2569 else
2571 if (w->right->color == MEM_BLACK)
2573 w->left->color = MEM_BLACK;
2574 w->color = MEM_RED;
2575 mem_rotate_right (w);
2576 w = x->parent->right;
2578 w->color = x->parent->color;
2579 x->parent->color = MEM_BLACK;
2580 w->right->color = MEM_BLACK;
2581 mem_rotate_left (x->parent);
2582 x = mem_root;
2585 else
2587 struct mem_node *w = x->parent->left;
2589 if (w->color == MEM_RED)
2591 w->color = MEM_BLACK;
2592 x->parent->color = MEM_RED;
2593 mem_rotate_right (x->parent);
2594 w = x->parent->left;
2597 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
2599 w->color = MEM_RED;
2600 x = x->parent;
2602 else
2604 if (w->left->color == MEM_BLACK)
2606 w->right->color = MEM_BLACK;
2607 w->color = MEM_RED;
2608 mem_rotate_left (w);
2609 w = x->parent->left;
2612 w->color = x->parent->color;
2613 x->parent->color = MEM_BLACK;
2614 w->left->color = MEM_BLACK;
2615 mem_rotate_right (x->parent);
2616 x = mem_root;
2621 x->color = MEM_BLACK;
2625 /* Value is non-zero if P is a pointer to a live Lisp string on
2626 the heap. M is a pointer to the mem_block for P. */
2628 static INLINE int
2629 live_string_p (m, p)
2630 struct mem_node *m;
2631 void *p;
2633 if (m->type == MEM_TYPE_STRING)
2635 struct string_block *b = (struct string_block *) m->start;
2636 int offset = (char *) p - (char *) &b->strings[0];
2638 /* P must point to the start of a Lisp_String structure, and it
2639 must not be on the free-list. */
2640 return (offset % sizeof b->strings[0] == 0
2641 && ((struct Lisp_String *) p)->data != NULL);
2643 else
2644 return 0;
2648 /* Value is non-zero if P is a pointer to a live Lisp cons on
2649 the heap. M is a pointer to the mem_block for P. */
2651 static INLINE int
2652 live_cons_p (m, p)
2653 struct mem_node *m;
2654 void *p;
2656 if (m->type == MEM_TYPE_CONS)
2658 struct cons_block *b = (struct cons_block *) m->start;
2659 int offset = (char *) p - (char *) &b->conses[0];
2661 /* P must point to the start of a Lisp_Cons, not be
2662 one of the unused cells in the current cons block,
2663 and not be on the free-list. */
2664 return (offset % sizeof b->conses[0] == 0
2665 && (b != cons_block
2666 || offset / sizeof b->conses[0] < cons_block_index)
2667 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
2669 else
2670 return 0;
2674 /* Value is non-zero if P is a pointer to a live Lisp symbol on
2675 the heap. M is a pointer to the mem_block for P. */
2677 static INLINE int
2678 live_symbol_p (m, p)
2679 struct mem_node *m;
2680 void *p;
2682 if (m->type == MEM_TYPE_SYMBOL)
2684 struct symbol_block *b = (struct symbol_block *) m->start;
2685 int offset = (char *) p - (char *) &b->symbols[0];
2687 /* P must point to the start of a Lisp_Symbol, not be
2688 one of the unused cells in the current symbol block,
2689 and not be on the free-list. */
2690 return (offset % sizeof b->symbols[0] == 0
2691 && (b != symbol_block
2692 || offset / sizeof b->symbols[0] < symbol_block_index)
2693 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
2695 else
2696 return 0;
2700 /* Value is non-zero if P is a pointer to a live Lisp float on
2701 the heap. M is a pointer to the mem_block for P. */
2703 static INLINE int
2704 live_float_p (m, p)
2705 struct mem_node *m;
2706 void *p;
2708 if (m->type == MEM_TYPE_FLOAT)
2710 struct float_block *b = (struct float_block *) m->start;
2711 int offset = (char *) p - (char *) &b->floats[0];
2713 /* P must point to the start of a Lisp_Float, not be
2714 one of the unused cells in the current float block,
2715 and not be on the free-list. */
2716 return (offset % sizeof b->floats[0] == 0
2717 && (b != float_block
2718 || offset / sizeof b->floats[0] < float_block_index)
2719 && !EQ (((struct Lisp_Float *) p)->type, Vdead));
2721 else
2722 return 0;
2726 /* Value is non-zero if P is a pointer to a live Lisp Misc on
2727 the heap. M is a pointer to the mem_block for P. */
2729 static INLINE int
2730 live_misc_p (m, p)
2731 struct mem_node *m;
2732 void *p;
2734 if (m->type == MEM_TYPE_MISC)
2736 struct marker_block *b = (struct marker_block *) m->start;
2737 int offset = (char *) p - (char *) &b->markers[0];
2739 /* P must point to the start of a Lisp_Misc, not be
2740 one of the unused cells in the current misc block,
2741 and not be on the free-list. */
2742 return (offset % sizeof b->markers[0] == 0
2743 && (b != marker_block
2744 || offset / sizeof b->markers[0] < marker_block_index)
2745 && ((union Lisp_Misc *) p)->u_marker.type != Lisp_Misc_Free);
2747 else
2748 return 0;
2752 /* Value is non-zero if P is a pointer to a live vector-like object.
2753 M is a pointer to the mem_block for P. */
2755 static INLINE int
2756 live_vector_p (m, p)
2757 struct mem_node *m;
2758 void *p;
2760 return m->type == MEM_TYPE_VECTOR && p == m->start;
2764 /* Value is non-zero of P is a pointer to a live buffer. M is a
2765 pointer to the mem_block for P. */
2767 static INLINE int
2768 live_buffer_p (m, p)
2769 struct mem_node *m;
2770 void *p;
2772 /* P must point to the start of the block, and the buffer
2773 must not have been killed. */
2774 return (m->type == MEM_TYPE_BUFFER
2775 && p == m->start
2776 && !NILP (((struct buffer *) p)->name));
2780 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
2782 /* Array of objects that are kept alive because the C stack contains
2783 a pattern that looks like a reference to them . */
2785 #define MAX_ZOMBIES 10
2786 static Lisp_Object zombies[MAX_ZOMBIES];
2788 /* Number of zombie objects. */
2790 static int nzombies;
2792 /* Number of garbage collections. */
2794 static int ngcs;
2796 /* Average percentage of zombies per collection. */
2798 static double avg_zombies;
2800 /* Max. number of live and zombie objects. */
2802 static int max_live, max_zombies;
2804 /* Average number of live objects per GC. */
2806 static double avg_live;
2808 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
2809 "Show information about live and zombie objects.")
2812 Lisp_Object args[7];
2813 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d");
2814 args[1] = make_number (ngcs);
2815 args[2] = make_float (avg_live);
2816 args[3] = make_float (avg_zombies);
2817 args[4] = make_float (avg_zombies / avg_live / 100);
2818 args[5] = make_number (max_live);
2819 args[6] = make_number (max_zombies);
2820 return Fmessage (7, args);
2823 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
2826 /* Mark Lisp objects in the address range START..END. */
2828 static void
2829 mark_memory (start, end)
2830 void *start, *end;
2832 Lisp_Object *p;
2834 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
2835 nzombies = 0;
2836 #endif
2838 /* Make START the pointer to the start of the memory region,
2839 if it isn't already. */
2840 if (end < start)
2842 void *tem = start;
2843 start = end;
2844 end = tem;
2847 for (p = (Lisp_Object *) start; (void *) p < end; ++p)
2849 void *po = (void *) XPNTR (*p);
2850 struct mem_node *m = mem_find (po);
2852 if (m != MEM_NIL)
2854 int mark_p = 0;
2856 switch (XGCTYPE (*p))
2858 case Lisp_String:
2859 mark_p = (live_string_p (m, po)
2860 && !STRING_MARKED_P ((struct Lisp_String *) po));
2861 break;
2863 case Lisp_Cons:
2864 mark_p = (live_cons_p (m, po)
2865 && !XMARKBIT (XCONS (*p)->car));
2866 break;
2868 case Lisp_Symbol:
2869 mark_p = (live_symbol_p (m, po)
2870 && !XMARKBIT (XSYMBOL (*p)->plist));
2871 break;
2873 case Lisp_Float:
2874 mark_p = (live_float_p (m, po)
2875 && !XMARKBIT (XFLOAT (*p)->type));
2876 break;
2878 case Lisp_Vectorlike:
2879 /* Note: can't check GC_BUFFERP before we know it's a
2880 buffer because checking that dereferences the pointer
2881 PO which might point anywhere. */
2882 if (live_vector_p (m, po))
2883 mark_p = (!GC_SUBRP (*p)
2884 && !(XVECTOR (*p)->size & ARRAY_MARK_FLAG));
2885 else if (live_buffer_p (m, po))
2886 mark_p = GC_BUFFERP (*p) && !XMARKBIT (XBUFFER (*p)->name);
2887 break;
2889 case Lisp_Misc:
2890 if (live_misc_p (m, po))
2892 switch (XMISCTYPE (*p))
2894 case Lisp_Misc_Marker:
2895 mark_p = !XMARKBIT (XMARKER (*p)->chain);
2896 break;
2898 case Lisp_Misc_Buffer_Local_Value:
2899 case Lisp_Misc_Some_Buffer_Local_Value:
2900 mark_p = !XMARKBIT (XBUFFER_LOCAL_VALUE (*p)->realvalue);
2901 break;
2903 case Lisp_Misc_Overlay:
2904 mark_p = !XMARKBIT (XOVERLAY (*p)->plist);
2905 break;
2908 break;
2911 if (mark_p)
2913 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
2914 if (nzombies < MAX_ZOMBIES)
2915 zombies[nzombies] = *p;
2916 ++nzombies;
2917 #endif
2918 mark_object (p);
2925 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
2927 /* Abort if anything GCPRO'd doesn't survive the GC. */
2929 static void
2930 check_gcpros ()
2932 struct gcpro *p;
2933 int i;
2935 for (p = gcprolist; p; p = p->next)
2936 for (i = 0; i < p->nvars; ++i)
2937 if (!survives_gc_p (p->var[i]))
2938 abort ();
2941 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
2943 static void
2944 dump_zombies ()
2946 int i;
2948 fprintf (stderr, "\nZombies kept alive = %d:\n", nzombies);
2949 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
2951 fprintf (stderr, " %d = ", i);
2952 debug_print (zombies[i]);
2956 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
2959 /* Mark live Lisp objects on the C stack. */
2961 static void
2962 mark_stack ()
2964 jmp_buf j;
2965 int stack_grows_down_p = (char *) &j > (char *) stack_base;
2966 void *end;
2968 /* This trick flushes the register windows so that all the state of
2969 the process is contained in the stack. */
2970 #ifdef sparc
2971 asm ("ta 3");
2972 #endif
2974 /* Save registers that we need to see on the stack. We need to see
2975 registers used to hold register variables and registers used to
2976 pass parameters. */
2977 #ifdef GC_SAVE_REGISTERS_ON_STACK
2978 GC_SAVE_REGISTERS_ON_STACK (end);
2979 #else
2980 setjmp (j);
2981 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
2982 #endif
2984 /* This assumes that the stack is a contiguous region in memory. If
2985 that's not the case, something has to be done here to iterate over
2986 the stack segments. */
2987 mark_memory (stack_base, end);
2989 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
2990 check_gcpros ();
2991 #endif
2995 #endif /* GC_MARK_STACK != 0 */
2999 /***********************************************************************
3000 Pure Storage Management
3001 ***********************************************************************/
3003 /* Return a string allocated in pure space. DATA is a buffer holding
3004 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
3005 non-zero means make the result string multibyte.
3007 Must get an error if pure storage is full, since if it cannot hold
3008 a large string it may be able to hold conses that point to that
3009 string; then the string is not protected from gc. */
3011 Lisp_Object
3012 make_pure_string (data, nchars, nbytes, multibyte)
3013 char *data;
3014 int nchars, nbytes;
3015 int multibyte;
3017 Lisp_Object string;
3018 struct Lisp_String *s;
3019 int string_size, data_size;
3021 #define PAD(SZ) (((SZ) + sizeof (EMACS_INT) - 1) & ~(sizeof (EMACS_INT) - 1))
3023 string_size = PAD (sizeof (struct Lisp_String));
3024 data_size = PAD (nbytes + 1);
3026 #undef PAD
3028 if (pureptr + string_size + data_size > PURESIZE)
3029 error ("Pure Lisp storage exhausted");
3031 s = (struct Lisp_String *) (PUREBEG + pureptr);
3032 pureptr += string_size;
3033 s->data = (unsigned char *) (PUREBEG + pureptr);
3034 pureptr += data_size;
3036 s->size = nchars;
3037 s->size_byte = multibyte ? nbytes : -1;
3038 bcopy (data, s->data, nbytes);
3039 s->data[nbytes] = '\0';
3040 s->intervals = NULL_INTERVAL;
3042 XSETSTRING (string, s);
3043 return string;
3047 /* Return a cons allocated from pure space. Give it pure copies
3048 of CAR as car and CDR as cdr. */
3050 Lisp_Object
3051 pure_cons (car, cdr)
3052 Lisp_Object car, cdr;
3054 register Lisp_Object new;
3056 if (pureptr + sizeof (struct Lisp_Cons) > PURESIZE)
3057 error ("Pure Lisp storage exhausted");
3058 XSETCONS (new, PUREBEG + pureptr);
3059 pureptr += sizeof (struct Lisp_Cons);
3060 XCAR (new) = Fpurecopy (car);
3061 XCDR (new) = Fpurecopy (cdr);
3062 return new;
3066 /* Value is a float object with value NUM allocated from pure space. */
3068 Lisp_Object
3069 make_pure_float (num)
3070 double num;
3072 register Lisp_Object new;
3074 /* Make sure that PUREBEG + pureptr is aligned on at least a sizeof
3075 (double) boundary. Some architectures (like the sparc) require
3076 this, and I suspect that floats are rare enough that it's no
3077 tragedy for those that do. */
3079 int alignment;
3080 char *p = PUREBEG + pureptr;
3082 #ifdef __GNUC__
3083 #if __GNUC__ >= 2
3084 alignment = __alignof (struct Lisp_Float);
3085 #else
3086 alignment = sizeof (struct Lisp_Float);
3087 #endif
3088 #else
3089 alignment = sizeof (struct Lisp_Float);
3090 #endif
3091 p = (char *) (((unsigned long) p + alignment - 1) & - alignment);
3092 pureptr = p - PUREBEG;
3095 if (pureptr + sizeof (struct Lisp_Float) > PURESIZE)
3096 error ("Pure Lisp storage exhausted");
3097 XSETFLOAT (new, PUREBEG + pureptr);
3098 pureptr += sizeof (struct Lisp_Float);
3099 XFLOAT_DATA (new) = num;
3100 XSETFASTINT (XFLOAT (new)->type, 0); /* bug chasing -wsr */
3101 return new;
3105 /* Return a vector with room for LEN Lisp_Objects allocated from
3106 pure space. */
3108 Lisp_Object
3109 make_pure_vector (len)
3110 EMACS_INT len;
3112 register Lisp_Object new;
3113 register EMACS_INT size = (sizeof (struct Lisp_Vector)
3114 + (len - 1) * sizeof (Lisp_Object));
3116 if (pureptr + size > PURESIZE)
3117 error ("Pure Lisp storage exhausted");
3119 XSETVECTOR (new, PUREBEG + pureptr);
3120 pureptr += size;
3121 XVECTOR (new)->size = len;
3122 return new;
3126 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
3127 "Make a copy of OBJECT in pure storage.\n\
3128 Recursively copies contents of vectors and cons cells.\n\
3129 Does not copy symbols. Copies strings without text properties.")
3130 (obj)
3131 register Lisp_Object obj;
3133 if (NILP (Vpurify_flag))
3134 return obj;
3136 if ((PNTR_COMPARISON_TYPE) XPNTR (obj) < (PNTR_COMPARISON_TYPE) ((char *) pure + PURESIZE)
3137 && (PNTR_COMPARISON_TYPE) XPNTR (obj) >= (PNTR_COMPARISON_TYPE) pure)
3138 return obj;
3140 if (CONSP (obj))
3141 return pure_cons (XCAR (obj), XCDR (obj));
3142 else if (FLOATP (obj))
3143 return make_pure_float (XFLOAT_DATA (obj));
3144 else if (STRINGP (obj))
3145 return make_pure_string (XSTRING (obj)->data, XSTRING (obj)->size,
3146 STRING_BYTES (XSTRING (obj)),
3147 STRING_MULTIBYTE (obj));
3148 else if (COMPILEDP (obj) || VECTORP (obj))
3150 register struct Lisp_Vector *vec;
3151 register int i, size;
3153 size = XVECTOR (obj)->size;
3154 if (size & PSEUDOVECTOR_FLAG)
3155 size &= PSEUDOVECTOR_SIZE_MASK;
3156 vec = XVECTOR (make_pure_vector ((EMACS_INT) size));
3157 for (i = 0; i < size; i++)
3158 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
3159 if (COMPILEDP (obj))
3160 XSETCOMPILED (obj, vec);
3161 else
3162 XSETVECTOR (obj, vec);
3163 return obj;
3165 else if (MARKERP (obj))
3166 error ("Attempt to copy a marker to pure storage");
3167 else
3168 return obj;
3173 /***********************************************************************
3174 Protection from GC
3175 ***********************************************************************/
3177 /* Recording what needs to be marked for gc. */
3179 struct gcpro *gcprolist;
3181 /* Addresses of staticpro'd variables. */
3183 #define NSTATICS 1024
3184 Lisp_Object *staticvec[NSTATICS] = {0};
3186 /* Index of next unused slot in staticvec. */
3188 int staticidx = 0;
3191 /* Put an entry in staticvec, pointing at the variable with address
3192 VARADDRESS. */
3194 void
3195 staticpro (varaddress)
3196 Lisp_Object *varaddress;
3198 staticvec[staticidx++] = varaddress;
3199 if (staticidx >= NSTATICS)
3200 abort ();
3203 struct catchtag
3205 Lisp_Object tag;
3206 Lisp_Object val;
3207 struct catchtag *next;
3210 struct backtrace
3212 struct backtrace *next;
3213 Lisp_Object *function;
3214 Lisp_Object *args; /* Points to vector of args. */
3215 int nargs; /* Length of vector. */
3216 /* If nargs is UNEVALLED, args points to slot holding list of
3217 unevalled args. */
3218 char evalargs;
3223 /***********************************************************************
3224 Protection from GC
3225 ***********************************************************************/
3227 /* Temporarily prevent garbage collection. */
3230 inhibit_garbage_collection ()
3232 int count = specpdl_ptr - specpdl;
3233 Lisp_Object number;
3234 int nbits = min (VALBITS, BITS_PER_INT);
3236 XSETINT (number, ((EMACS_INT) 1 << (nbits - 1)) - 1);
3238 specbind (Qgc_cons_threshold, number);
3240 return count;
3244 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
3245 "Reclaim storage for Lisp objects no longer needed.\n\
3246 Returns info on amount of space in use:\n\
3247 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)\n\
3248 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS\n\
3249 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS\n\
3250 (USED-STRINGS . FREE-STRINGS))\n\
3251 Garbage collection happens automatically if you cons more than\n\
3252 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.")
3255 register struct gcpro *tail;
3256 register struct specbinding *bind;
3257 struct catchtag *catch;
3258 struct handler *handler;
3259 register struct backtrace *backlist;
3260 char stack_top_variable;
3261 register int i;
3262 int message_p;
3263 Lisp_Object total[7];
3265 /* In case user calls debug_print during GC,
3266 don't let that cause a recursive GC. */
3267 consing_since_gc = 0;
3269 /* Save what's currently displayed in the echo area. */
3270 message_p = push_message ();
3272 /* Save a copy of the contents of the stack, for debugging. */
3273 #if MAX_SAVE_STACK > 0
3274 if (NILP (Vpurify_flag))
3276 i = &stack_top_variable - stack_bottom;
3277 if (i < 0) i = -i;
3278 if (i < MAX_SAVE_STACK)
3280 if (stack_copy == 0)
3281 stack_copy = (char *) xmalloc (stack_copy_size = i);
3282 else if (stack_copy_size < i)
3283 stack_copy = (char *) xrealloc (stack_copy, (stack_copy_size = i));
3284 if (stack_copy)
3286 if ((EMACS_INT) (&stack_top_variable - stack_bottom) > 0)
3287 bcopy (stack_bottom, stack_copy, i);
3288 else
3289 bcopy (&stack_top_variable, stack_copy, i);
3293 #endif /* MAX_SAVE_STACK > 0 */
3295 if (garbage_collection_messages)
3296 message1_nolog ("Garbage collecting...");
3298 BLOCK_INPUT;
3300 shrink_regexp_cache ();
3302 /* Don't keep undo information around forever. */
3304 register struct buffer *nextb = all_buffers;
3306 while (nextb)
3308 /* If a buffer's undo list is Qt, that means that undo is
3309 turned off in that buffer. Calling truncate_undo_list on
3310 Qt tends to return NULL, which effectively turns undo back on.
3311 So don't call truncate_undo_list if undo_list is Qt. */
3312 if (! EQ (nextb->undo_list, Qt))
3313 nextb->undo_list
3314 = truncate_undo_list (nextb->undo_list, undo_limit,
3315 undo_strong_limit);
3316 nextb = nextb->next;
3320 gc_in_progress = 1;
3322 /* clear_marks (); */
3324 /* Mark all the special slots that serve as the roots of accessibility.
3326 Usually the special slots to mark are contained in particular structures.
3327 Then we know no slot is marked twice because the structures don't overlap.
3328 In some cases, the structures point to the slots to be marked.
3329 For these, we use MARKBIT to avoid double marking of the slot. */
3331 for (i = 0; i < staticidx; i++)
3332 mark_object (staticvec[i]);
3334 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
3335 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
3336 mark_stack ();
3337 #else
3338 for (tail = gcprolist; tail; tail = tail->next)
3339 for (i = 0; i < tail->nvars; i++)
3340 if (!XMARKBIT (tail->var[i]))
3342 mark_object (&tail->var[i]);
3343 XMARK (tail->var[i]);
3345 #endif
3347 mark_byte_stack ();
3348 for (bind = specpdl; bind != specpdl_ptr; bind++)
3350 mark_object (&bind->symbol);
3351 mark_object (&bind->old_value);
3353 for (catch = catchlist; catch; catch = catch->next)
3355 mark_object (&catch->tag);
3356 mark_object (&catch->val);
3358 for (handler = handlerlist; handler; handler = handler->next)
3360 mark_object (&handler->handler);
3361 mark_object (&handler->var);
3363 for (backlist = backtrace_list; backlist; backlist = backlist->next)
3365 if (!XMARKBIT (*backlist->function))
3367 mark_object (backlist->function);
3368 XMARK (*backlist->function);
3370 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
3371 i = 0;
3372 else
3373 i = backlist->nargs - 1;
3374 for (; i >= 0; i--)
3375 if (!XMARKBIT (backlist->args[i]))
3377 mark_object (&backlist->args[i]);
3378 XMARK (backlist->args[i]);
3381 mark_kboards ();
3383 /* Look thru every buffer's undo list
3384 for elements that update markers that were not marked,
3385 and delete them. */
3387 register struct buffer *nextb = all_buffers;
3389 while (nextb)
3391 /* If a buffer's undo list is Qt, that means that undo is
3392 turned off in that buffer. Calling truncate_undo_list on
3393 Qt tends to return NULL, which effectively turns undo back on.
3394 So don't call truncate_undo_list if undo_list is Qt. */
3395 if (! EQ (nextb->undo_list, Qt))
3397 Lisp_Object tail, prev;
3398 tail = nextb->undo_list;
3399 prev = Qnil;
3400 while (CONSP (tail))
3402 if (GC_CONSP (XCAR (tail))
3403 && GC_MARKERP (XCAR (XCAR (tail)))
3404 && ! XMARKBIT (XMARKER (XCAR (XCAR (tail)))->chain))
3406 if (NILP (prev))
3407 nextb->undo_list = tail = XCDR (tail);
3408 else
3409 tail = XCDR (prev) = XCDR (tail);
3411 else
3413 prev = tail;
3414 tail = XCDR (tail);
3419 nextb = nextb->next;
3423 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3424 mark_stack ();
3425 #endif
3427 gc_sweep ();
3429 /* Clear the mark bits that we set in certain root slots. */
3431 #if (GC_MARK_STACK == GC_USE_GCPROS_AS_BEFORE \
3432 || GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES)
3433 for (tail = gcprolist; tail; tail = tail->next)
3434 for (i = 0; i < tail->nvars; i++)
3435 XUNMARK (tail->var[i]);
3436 #endif
3438 unmark_byte_stack ();
3439 for (backlist = backtrace_list; backlist; backlist = backlist->next)
3441 XUNMARK (*backlist->function);
3442 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
3443 i = 0;
3444 else
3445 i = backlist->nargs - 1;
3446 for (; i >= 0; i--)
3447 XUNMARK (backlist->args[i]);
3449 XUNMARK (buffer_defaults.name);
3450 XUNMARK (buffer_local_symbols.name);
3452 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
3453 dump_zombies ();
3454 #endif
3456 UNBLOCK_INPUT;
3458 /* clear_marks (); */
3459 gc_in_progress = 0;
3461 consing_since_gc = 0;
3462 if (gc_cons_threshold < 10000)
3463 gc_cons_threshold = 10000;
3465 if (garbage_collection_messages)
3467 if (message_p || minibuf_level > 0)
3468 restore_message ();
3469 else
3470 message1_nolog ("Garbage collecting...done");
3473 pop_message ();
3475 total[0] = Fcons (make_number (total_conses),
3476 make_number (total_free_conses));
3477 total[1] = Fcons (make_number (total_symbols),
3478 make_number (total_free_symbols));
3479 total[2] = Fcons (make_number (total_markers),
3480 make_number (total_free_markers));
3481 total[3] = Fcons (make_number (total_string_size),
3482 make_number (total_vector_size));
3483 total[4] = Fcons (make_number (total_floats),
3484 make_number (total_free_floats));
3485 total[5] = Fcons (make_number (total_intervals),
3486 make_number (total_free_intervals));
3487 total[6] = Fcons (make_number (total_strings),
3488 make_number (total_free_strings));
3490 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3492 /* Compute average percentage of zombies. */
3493 double nlive = 0;
3495 for (i = 0; i < 7; ++i)
3496 nlive += XFASTINT (XCAR (total[i]));
3498 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
3499 max_live = max (nlive, max_live);
3500 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
3501 max_zombies = max (nzombies, max_zombies);
3502 ++ngcs;
3504 #endif
3506 return Flist (7, total);
3510 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
3511 only interesting objects referenced from glyphs are strings. */
3513 static void
3514 mark_glyph_matrix (matrix)
3515 struct glyph_matrix *matrix;
3517 struct glyph_row *row = matrix->rows;
3518 struct glyph_row *end = row + matrix->nrows;
3520 for (; row < end; ++row)
3521 if (row->enabled_p)
3523 int area;
3524 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
3526 struct glyph *glyph = row->glyphs[area];
3527 struct glyph *end_glyph = glyph + row->used[area];
3529 for (; glyph < end_glyph; ++glyph)
3530 if (GC_STRINGP (glyph->object)
3531 && !STRING_MARKED_P (XSTRING (glyph->object)))
3532 mark_object (&glyph->object);
3538 /* Mark Lisp faces in the face cache C. */
3540 static void
3541 mark_face_cache (c)
3542 struct face_cache *c;
3544 if (c)
3546 int i, j;
3547 for (i = 0; i < c->used; ++i)
3549 struct face *face = FACE_FROM_ID (c->f, i);
3551 if (face)
3553 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
3554 mark_object (&face->lface[j]);
3561 #ifdef HAVE_WINDOW_SYSTEM
3563 /* Mark Lisp objects in image IMG. */
3565 static void
3566 mark_image (img)
3567 struct image *img;
3569 mark_object (&img->spec);
3571 if (!NILP (img->data.lisp_val))
3572 mark_object (&img->data.lisp_val);
3576 /* Mark Lisp objects in image cache of frame F. It's done this way so
3577 that we don't have to include xterm.h here. */
3579 static void
3580 mark_image_cache (f)
3581 struct frame *f;
3583 forall_images_in_image_cache (f, mark_image);
3586 #endif /* HAVE_X_WINDOWS */
3590 /* Mark reference to a Lisp_Object.
3591 If the object referred to has not been seen yet, recursively mark
3592 all the references contained in it. */
3594 #define LAST_MARKED_SIZE 500
3595 Lisp_Object *last_marked[LAST_MARKED_SIZE];
3596 int last_marked_index;
3598 void
3599 mark_object (argptr)
3600 Lisp_Object *argptr;
3602 Lisp_Object *objptr = argptr;
3603 register Lisp_Object obj;
3605 loop:
3606 obj = *objptr;
3607 loop2:
3608 XUNMARK (obj);
3610 if (PURE_POINTER_P ((PNTR_COMPARISON_TYPE) XPNTR (obj)))
3611 return;
3613 last_marked[last_marked_index++] = objptr;
3614 if (last_marked_index == LAST_MARKED_SIZE)
3615 last_marked_index = 0;
3617 switch (SWITCH_ENUM_CAST (XGCTYPE (obj)))
3619 case Lisp_String:
3621 register struct Lisp_String *ptr = XSTRING (obj);
3622 MARK_INTERVAL_TREE (ptr->intervals);
3623 MARK_STRING (ptr);
3625 break;
3627 case Lisp_Vectorlike:
3628 if (GC_BUFFERP (obj))
3630 if (!XMARKBIT (XBUFFER (obj)->name))
3631 mark_buffer (obj);
3633 else if (GC_SUBRP (obj))
3634 break;
3635 else if (GC_COMPILEDP (obj))
3636 /* We could treat this just like a vector, but it is better to
3637 save the COMPILED_CONSTANTS element for last and avoid
3638 recursion there. */
3640 register struct Lisp_Vector *ptr = XVECTOR (obj);
3641 register EMACS_INT size = ptr->size;
3642 /* See comment above under Lisp_Vector. */
3643 struct Lisp_Vector *volatile ptr1 = ptr;
3644 register int i;
3646 if (size & ARRAY_MARK_FLAG)
3647 break; /* Already marked */
3648 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
3649 size &= PSEUDOVECTOR_SIZE_MASK;
3650 for (i = 0; i < size; i++) /* and then mark its elements */
3652 if (i != COMPILED_CONSTANTS)
3653 mark_object (&ptr1->contents[i]);
3655 /* This cast should be unnecessary, but some Mips compiler complains
3656 (MIPS-ABI + SysVR4, DC/OSx, etc). */
3657 objptr = (Lisp_Object *) &ptr1->contents[COMPILED_CONSTANTS];
3658 goto loop;
3660 else if (GC_FRAMEP (obj))
3662 /* See comment above under Lisp_Vector for why this is volatile. */
3663 register struct frame *volatile ptr = XFRAME (obj);
3664 register EMACS_INT size = ptr->size;
3666 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
3667 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
3669 mark_object (&ptr->name);
3670 mark_object (&ptr->icon_name);
3671 mark_object (&ptr->title);
3672 mark_object (&ptr->focus_frame);
3673 mark_object (&ptr->selected_window);
3674 mark_object (&ptr->minibuffer_window);
3675 mark_object (&ptr->param_alist);
3676 mark_object (&ptr->scroll_bars);
3677 mark_object (&ptr->condemned_scroll_bars);
3678 mark_object (&ptr->menu_bar_items);
3679 mark_object (&ptr->face_alist);
3680 mark_object (&ptr->menu_bar_vector);
3681 mark_object (&ptr->buffer_predicate);
3682 mark_object (&ptr->buffer_list);
3683 mark_object (&ptr->menu_bar_window);
3684 mark_object (&ptr->tool_bar_window);
3685 mark_face_cache (ptr->face_cache);
3686 #ifdef HAVE_WINDOW_SYSTEM
3687 mark_image_cache (ptr);
3688 mark_object (&ptr->desired_tool_bar_items);
3689 mark_object (&ptr->current_tool_bar_items);
3690 mark_object (&ptr->desired_tool_bar_string);
3691 mark_object (&ptr->current_tool_bar_string);
3692 #endif /* HAVE_WINDOW_SYSTEM */
3694 else if (GC_BOOL_VECTOR_P (obj))
3696 register struct Lisp_Vector *ptr = XVECTOR (obj);
3698 if (ptr->size & ARRAY_MARK_FLAG)
3699 break; /* Already marked */
3700 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
3702 else if (GC_WINDOWP (obj))
3704 register struct Lisp_Vector *ptr = XVECTOR (obj);
3705 struct window *w = XWINDOW (obj);
3706 register EMACS_INT size = ptr->size;
3707 /* The reason we use ptr1 is to avoid an apparent hardware bug
3708 that happens occasionally on the FSF's HP 300s.
3709 The bug is that a2 gets clobbered by recursive calls to mark_object.
3710 The clobberage seems to happen during function entry,
3711 perhaps in the moveml instruction.
3712 Yes, this is a crock, but we have to do it. */
3713 struct Lisp_Vector *volatile ptr1 = ptr;
3714 register int i;
3716 /* Stop if already marked. */
3717 if (size & ARRAY_MARK_FLAG)
3718 break;
3720 /* Mark it. */
3721 ptr->size |= ARRAY_MARK_FLAG;
3723 /* There is no Lisp data above The member CURRENT_MATRIX in
3724 struct WINDOW. Stop marking when that slot is reached. */
3725 for (i = 0;
3726 (char *) &ptr1->contents[i] < (char *) &w->current_matrix;
3727 i++)
3728 mark_object (&ptr1->contents[i]);
3730 /* Mark glyphs for leaf windows. Marking window matrices is
3731 sufficient because frame matrices use the same glyph
3732 memory. */
3733 if (NILP (w->hchild)
3734 && NILP (w->vchild)
3735 && w->current_matrix)
3737 mark_glyph_matrix (w->current_matrix);
3738 mark_glyph_matrix (w->desired_matrix);
3741 else if (GC_HASH_TABLE_P (obj))
3743 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
3744 EMACS_INT size = h->size;
3746 /* Stop if already marked. */
3747 if (size & ARRAY_MARK_FLAG)
3748 break;
3750 /* Mark it. */
3751 h->size |= ARRAY_MARK_FLAG;
3753 /* Mark contents. */
3754 mark_object (&h->test);
3755 mark_object (&h->weak);
3756 mark_object (&h->rehash_size);
3757 mark_object (&h->rehash_threshold);
3758 mark_object (&h->hash);
3759 mark_object (&h->next);
3760 mark_object (&h->index);
3761 mark_object (&h->user_hash_function);
3762 mark_object (&h->user_cmp_function);
3764 /* If hash table is not weak, mark all keys and values.
3765 For weak tables, mark only the vector. */
3766 if (GC_NILP (h->weak))
3767 mark_object (&h->key_and_value);
3768 else
3769 XVECTOR (h->key_and_value)->size |= ARRAY_MARK_FLAG;
3772 else
3774 register struct Lisp_Vector *ptr = XVECTOR (obj);
3775 register EMACS_INT size = ptr->size;
3776 /* The reason we use ptr1 is to avoid an apparent hardware bug
3777 that happens occasionally on the FSF's HP 300s.
3778 The bug is that a2 gets clobbered by recursive calls to mark_object.
3779 The clobberage seems to happen during function entry,
3780 perhaps in the moveml instruction.
3781 Yes, this is a crock, but we have to do it. */
3782 struct Lisp_Vector *volatile ptr1 = ptr;
3783 register int i;
3785 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
3786 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
3787 if (size & PSEUDOVECTOR_FLAG)
3788 size &= PSEUDOVECTOR_SIZE_MASK;
3790 for (i = 0; i < size; i++) /* and then mark its elements */
3791 mark_object (&ptr1->contents[i]);
3793 break;
3795 case Lisp_Symbol:
3797 /* See comment above under Lisp_Vector for why this is volatile. */
3798 register struct Lisp_Symbol *volatile ptr = XSYMBOL (obj);
3799 struct Lisp_Symbol *ptrx;
3801 if (XMARKBIT (ptr->plist)) break;
3802 XMARK (ptr->plist);
3803 mark_object ((Lisp_Object *) &ptr->value);
3804 mark_object (&ptr->function);
3805 mark_object (&ptr->plist);
3807 if (!PURE_POINTER_P (ptr->name))
3808 MARK_STRING (ptr->name);
3809 MARK_INTERVAL_TREE (ptr->name->intervals);
3811 /* Note that we do not mark the obarray of the symbol.
3812 It is safe not to do so because nothing accesses that
3813 slot except to check whether it is nil. */
3814 ptr = ptr->next;
3815 if (ptr)
3817 /* For the benefit of the last_marked log. */
3818 objptr = (Lisp_Object *)&XSYMBOL (obj)->next;
3819 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
3820 XSETSYMBOL (obj, ptrx);
3821 /* We can't goto loop here because *objptr doesn't contain an
3822 actual Lisp_Object with valid datatype field. */
3823 goto loop2;
3826 break;
3828 case Lisp_Misc:
3829 switch (XMISCTYPE (obj))
3831 case Lisp_Misc_Marker:
3832 XMARK (XMARKER (obj)->chain);
3833 /* DO NOT mark thru the marker's chain.
3834 The buffer's markers chain does not preserve markers from gc;
3835 instead, markers are removed from the chain when freed by gc. */
3836 break;
3838 case Lisp_Misc_Buffer_Local_Value:
3839 case Lisp_Misc_Some_Buffer_Local_Value:
3841 register struct Lisp_Buffer_Local_Value *ptr
3842 = XBUFFER_LOCAL_VALUE (obj);
3843 if (XMARKBIT (ptr->realvalue)) break;
3844 XMARK (ptr->realvalue);
3845 /* If the cdr is nil, avoid recursion for the car. */
3846 if (EQ (ptr->cdr, Qnil))
3848 objptr = &ptr->realvalue;
3849 goto loop;
3851 mark_object (&ptr->realvalue);
3852 mark_object (&ptr->buffer);
3853 mark_object (&ptr->frame);
3854 /* See comment above under Lisp_Vector for why not use ptr here. */
3855 objptr = &XBUFFER_LOCAL_VALUE (obj)->cdr;
3856 goto loop;
3859 case Lisp_Misc_Intfwd:
3860 case Lisp_Misc_Boolfwd:
3861 case Lisp_Misc_Objfwd:
3862 case Lisp_Misc_Buffer_Objfwd:
3863 case Lisp_Misc_Kboard_Objfwd:
3864 /* Don't bother with Lisp_Buffer_Objfwd,
3865 since all markable slots in current buffer marked anyway. */
3866 /* Don't need to do Lisp_Objfwd, since the places they point
3867 are protected with staticpro. */
3868 break;
3870 case Lisp_Misc_Overlay:
3872 struct Lisp_Overlay *ptr = XOVERLAY (obj);
3873 if (!XMARKBIT (ptr->plist))
3875 XMARK (ptr->plist);
3876 mark_object (&ptr->start);
3877 mark_object (&ptr->end);
3878 objptr = &ptr->plist;
3879 goto loop;
3882 break;
3884 default:
3885 abort ();
3887 break;
3889 case Lisp_Cons:
3891 register struct Lisp_Cons *ptr = XCONS (obj);
3892 if (XMARKBIT (ptr->car)) break;
3893 XMARK (ptr->car);
3894 /* If the cdr is nil, avoid recursion for the car. */
3895 if (EQ (ptr->cdr, Qnil))
3897 objptr = &ptr->car;
3898 goto loop;
3900 mark_object (&ptr->car);
3901 /* See comment above under Lisp_Vector for why not use ptr here. */
3902 objptr = &XCDR (obj);
3903 goto loop;
3906 case Lisp_Float:
3907 XMARK (XFLOAT (obj)->type);
3908 break;
3910 case Lisp_Int:
3911 break;
3913 default:
3914 abort ();
3918 /* Mark the pointers in a buffer structure. */
3920 static void
3921 mark_buffer (buf)
3922 Lisp_Object buf;
3924 register struct buffer *buffer = XBUFFER (buf);
3925 register Lisp_Object *ptr;
3926 Lisp_Object base_buffer;
3928 /* This is the buffer's markbit */
3929 mark_object (&buffer->name);
3930 XMARK (buffer->name);
3932 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
3934 if (CONSP (buffer->undo_list))
3936 Lisp_Object tail;
3937 tail = buffer->undo_list;
3939 while (CONSP (tail))
3941 register struct Lisp_Cons *ptr = XCONS (tail);
3943 if (XMARKBIT (ptr->car))
3944 break;
3945 XMARK (ptr->car);
3946 if (GC_CONSP (ptr->car)
3947 && ! XMARKBIT (XCAR (ptr->car))
3948 && GC_MARKERP (XCAR (ptr->car)))
3950 XMARK (XCAR (ptr->car));
3951 mark_object (&XCDR (ptr->car));
3953 else
3954 mark_object (&ptr->car);
3956 if (CONSP (ptr->cdr))
3957 tail = ptr->cdr;
3958 else
3959 break;
3962 mark_object (&XCDR (tail));
3964 else
3965 mark_object (&buffer->undo_list);
3967 for (ptr = &buffer->name + 1;
3968 (char *)ptr < (char *)buffer + sizeof (struct buffer);
3969 ptr++)
3970 mark_object (ptr);
3972 /* If this is an indirect buffer, mark its base buffer. */
3973 if (buffer->base_buffer && !XMARKBIT (buffer->base_buffer->name))
3975 XSETBUFFER (base_buffer, buffer->base_buffer);
3976 mark_buffer (base_buffer);
3981 /* Mark the pointers in the kboard objects. */
3983 static void
3984 mark_kboards ()
3986 KBOARD *kb;
3987 Lisp_Object *p;
3988 for (kb = all_kboards; kb; kb = kb->next_kboard)
3990 if (kb->kbd_macro_buffer)
3991 for (p = kb->kbd_macro_buffer; p < kb->kbd_macro_ptr; p++)
3992 mark_object (p);
3993 mark_object (&kb->Voverriding_terminal_local_map);
3994 mark_object (&kb->Vlast_command);
3995 mark_object (&kb->Vreal_last_command);
3996 mark_object (&kb->Vprefix_arg);
3997 mark_object (&kb->Vlast_prefix_arg);
3998 mark_object (&kb->kbd_queue);
3999 mark_object (&kb->defining_kbd_macro);
4000 mark_object (&kb->Vlast_kbd_macro);
4001 mark_object (&kb->Vsystem_key_alist);
4002 mark_object (&kb->system_key_syms);
4003 mark_object (&kb->Vdefault_minibuffer_frame);
4008 /* Value is non-zero if OBJ will survive the current GC because it's
4009 either marked or does not need to be marked to survive. */
4012 survives_gc_p (obj)
4013 Lisp_Object obj;
4015 int survives_p;
4017 switch (XGCTYPE (obj))
4019 case Lisp_Int:
4020 survives_p = 1;
4021 break;
4023 case Lisp_Symbol:
4024 survives_p = XMARKBIT (XSYMBOL (obj)->plist);
4025 break;
4027 case Lisp_Misc:
4028 switch (XMISCTYPE (obj))
4030 case Lisp_Misc_Marker:
4031 survives_p = XMARKBIT (obj);
4032 break;
4034 case Lisp_Misc_Buffer_Local_Value:
4035 case Lisp_Misc_Some_Buffer_Local_Value:
4036 survives_p = XMARKBIT (XBUFFER_LOCAL_VALUE (obj)->realvalue);
4037 break;
4039 case Lisp_Misc_Intfwd:
4040 case Lisp_Misc_Boolfwd:
4041 case Lisp_Misc_Objfwd:
4042 case Lisp_Misc_Buffer_Objfwd:
4043 case Lisp_Misc_Kboard_Objfwd:
4044 survives_p = 1;
4045 break;
4047 case Lisp_Misc_Overlay:
4048 survives_p = XMARKBIT (XOVERLAY (obj)->plist);
4049 break;
4051 default:
4052 abort ();
4054 break;
4056 case Lisp_String:
4058 struct Lisp_String *s = XSTRING (obj);
4059 survives_p = STRING_MARKED_P (s);
4061 break;
4063 case Lisp_Vectorlike:
4064 if (GC_BUFFERP (obj))
4065 survives_p = XMARKBIT (XBUFFER (obj)->name);
4066 else if (GC_SUBRP (obj))
4067 survives_p = 1;
4068 else
4069 survives_p = XVECTOR (obj)->size & ARRAY_MARK_FLAG;
4070 break;
4072 case Lisp_Cons:
4073 survives_p = XMARKBIT (XCAR (obj));
4074 break;
4076 case Lisp_Float:
4077 survives_p = XMARKBIT (XFLOAT (obj)->type);
4078 break;
4080 default:
4081 abort ();
4084 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
4089 /* Sweep: find all structures not marked, and free them. */
4091 static void
4092 gc_sweep ()
4094 /* Remove or mark entries in weak hash tables.
4095 This must be done before any object is unmarked. */
4096 sweep_weak_hash_tables ();
4098 sweep_strings ();
4100 /* Put all unmarked conses on free list */
4102 register struct cons_block *cblk;
4103 struct cons_block **cprev = &cons_block;
4104 register int lim = cons_block_index;
4105 register int num_free = 0, num_used = 0;
4107 cons_free_list = 0;
4109 for (cblk = cons_block; cblk; cblk = *cprev)
4111 register int i;
4112 int this_free = 0;
4113 for (i = 0; i < lim; i++)
4114 if (!XMARKBIT (cblk->conses[i].car))
4116 this_free++;
4117 *(struct Lisp_Cons **)&cblk->conses[i].cdr = cons_free_list;
4118 cons_free_list = &cblk->conses[i];
4119 #if GC_MARK_STACK
4120 cons_free_list->car = Vdead;
4121 #endif
4123 else
4125 num_used++;
4126 XUNMARK (cblk->conses[i].car);
4128 lim = CONS_BLOCK_SIZE;
4129 /* If this block contains only free conses and we have already
4130 seen more than two blocks worth of free conses then deallocate
4131 this block. */
4132 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
4134 *cprev = cblk->next;
4135 /* Unhook from the free list. */
4136 cons_free_list = *(struct Lisp_Cons **) &cblk->conses[0].cdr;
4137 lisp_free (cblk);
4138 n_cons_blocks--;
4140 else
4142 num_free += this_free;
4143 cprev = &cblk->next;
4146 total_conses = num_used;
4147 total_free_conses = num_free;
4150 /* Put all unmarked floats on free list */
4152 register struct float_block *fblk;
4153 struct float_block **fprev = &float_block;
4154 register int lim = float_block_index;
4155 register int num_free = 0, num_used = 0;
4157 float_free_list = 0;
4159 for (fblk = float_block; fblk; fblk = *fprev)
4161 register int i;
4162 int this_free = 0;
4163 for (i = 0; i < lim; i++)
4164 if (!XMARKBIT (fblk->floats[i].type))
4166 this_free++;
4167 *(struct Lisp_Float **)&fblk->floats[i].data = float_free_list;
4168 float_free_list = &fblk->floats[i];
4169 #if GC_MARK_STACK
4170 float_free_list->type = Vdead;
4171 #endif
4173 else
4175 num_used++;
4176 XUNMARK (fblk->floats[i].type);
4178 lim = FLOAT_BLOCK_SIZE;
4179 /* If this block contains only free floats and we have already
4180 seen more than two blocks worth of free floats then deallocate
4181 this block. */
4182 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
4184 *fprev = fblk->next;
4185 /* Unhook from the free list. */
4186 float_free_list = *(struct Lisp_Float **) &fblk->floats[0].data;
4187 lisp_free (fblk);
4188 n_float_blocks--;
4190 else
4192 num_free += this_free;
4193 fprev = &fblk->next;
4196 total_floats = num_used;
4197 total_free_floats = num_free;
4200 /* Put all unmarked intervals on free list */
4202 register struct interval_block *iblk;
4203 struct interval_block **iprev = &interval_block;
4204 register int lim = interval_block_index;
4205 register int num_free = 0, num_used = 0;
4207 interval_free_list = 0;
4209 for (iblk = interval_block; iblk; iblk = *iprev)
4211 register int i;
4212 int this_free = 0;
4214 for (i = 0; i < lim; i++)
4216 if (! XMARKBIT (iblk->intervals[i].plist))
4218 iblk->intervals[i].parent = interval_free_list;
4219 interval_free_list = &iblk->intervals[i];
4220 this_free++;
4222 else
4224 num_used++;
4225 XUNMARK (iblk->intervals[i].plist);
4228 lim = INTERVAL_BLOCK_SIZE;
4229 /* If this block contains only free intervals and we have already
4230 seen more than two blocks worth of free intervals then
4231 deallocate this block. */
4232 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
4234 *iprev = iblk->next;
4235 /* Unhook from the free list. */
4236 interval_free_list = iblk->intervals[0].parent;
4237 lisp_free (iblk);
4238 n_interval_blocks--;
4240 else
4242 num_free += this_free;
4243 iprev = &iblk->next;
4246 total_intervals = num_used;
4247 total_free_intervals = num_free;
4250 /* Put all unmarked symbols on free list */
4252 register struct symbol_block *sblk;
4253 struct symbol_block **sprev = &symbol_block;
4254 register int lim = symbol_block_index;
4255 register int num_free = 0, num_used = 0;
4257 symbol_free_list = 0;
4259 for (sblk = symbol_block; sblk; sblk = *sprev)
4261 register int i;
4262 int this_free = 0;
4263 for (i = 0; i < lim; i++)
4264 if (!XMARKBIT (sblk->symbols[i].plist))
4266 *(struct Lisp_Symbol **)&sblk->symbols[i].value = symbol_free_list;
4267 symbol_free_list = &sblk->symbols[i];
4268 #if GC_MARK_STACK
4269 symbol_free_list->function = Vdead;
4270 #endif
4271 this_free++;
4273 else
4275 num_used++;
4276 if (!PURE_POINTER_P (sblk->symbols[i].name))
4277 UNMARK_STRING (sblk->symbols[i].name);
4278 XUNMARK (sblk->symbols[i].plist);
4280 lim = SYMBOL_BLOCK_SIZE;
4281 /* If this block contains only free symbols and we have already
4282 seen more than two blocks worth of free symbols then deallocate
4283 this block. */
4284 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
4286 *sprev = sblk->next;
4287 /* Unhook from the free list. */
4288 symbol_free_list = *(struct Lisp_Symbol **)&sblk->symbols[0].value;
4289 lisp_free (sblk);
4290 n_symbol_blocks--;
4292 else
4294 num_free += this_free;
4295 sprev = &sblk->next;
4298 total_symbols = num_used;
4299 total_free_symbols = num_free;
4302 /* Put all unmarked misc's on free list.
4303 For a marker, first unchain it from the buffer it points into. */
4305 register struct marker_block *mblk;
4306 struct marker_block **mprev = &marker_block;
4307 register int lim = marker_block_index;
4308 register int num_free = 0, num_used = 0;
4310 marker_free_list = 0;
4312 for (mblk = marker_block; mblk; mblk = *mprev)
4314 register int i;
4315 int this_free = 0;
4316 EMACS_INT already_free = -1;
4318 for (i = 0; i < lim; i++)
4320 Lisp_Object *markword;
4321 switch (mblk->markers[i].u_marker.type)
4323 case Lisp_Misc_Marker:
4324 markword = &mblk->markers[i].u_marker.chain;
4325 break;
4326 case Lisp_Misc_Buffer_Local_Value:
4327 case Lisp_Misc_Some_Buffer_Local_Value:
4328 markword = &mblk->markers[i].u_buffer_local_value.realvalue;
4329 break;
4330 case Lisp_Misc_Overlay:
4331 markword = &mblk->markers[i].u_overlay.plist;
4332 break;
4333 case Lisp_Misc_Free:
4334 /* If the object was already free, keep it
4335 on the free list. */
4336 markword = (Lisp_Object *) &already_free;
4337 break;
4338 default:
4339 markword = 0;
4340 break;
4342 if (markword && !XMARKBIT (*markword))
4344 Lisp_Object tem;
4345 if (mblk->markers[i].u_marker.type == Lisp_Misc_Marker)
4347 /* tem1 avoids Sun compiler bug */
4348 struct Lisp_Marker *tem1 = &mblk->markers[i].u_marker;
4349 XSETMARKER (tem, tem1);
4350 unchain_marker (tem);
4352 /* Set the type of the freed object to Lisp_Misc_Free.
4353 We could leave the type alone, since nobody checks it,
4354 but this might catch bugs faster. */
4355 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
4356 mblk->markers[i].u_free.chain = marker_free_list;
4357 marker_free_list = &mblk->markers[i];
4358 this_free++;
4360 else
4362 num_used++;
4363 if (markword)
4364 XUNMARK (*markword);
4367 lim = MARKER_BLOCK_SIZE;
4368 /* If this block contains only free markers and we have already
4369 seen more than two blocks worth of free markers then deallocate
4370 this block. */
4371 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
4373 *mprev = mblk->next;
4374 /* Unhook from the free list. */
4375 marker_free_list = mblk->markers[0].u_free.chain;
4376 lisp_free (mblk);
4377 n_marker_blocks--;
4379 else
4381 num_free += this_free;
4382 mprev = &mblk->next;
4386 total_markers = num_used;
4387 total_free_markers = num_free;
4390 /* Free all unmarked buffers */
4392 register struct buffer *buffer = all_buffers, *prev = 0, *next;
4394 while (buffer)
4395 if (!XMARKBIT (buffer->name))
4397 if (prev)
4398 prev->next = buffer->next;
4399 else
4400 all_buffers = buffer->next;
4401 next = buffer->next;
4402 lisp_free (buffer);
4403 buffer = next;
4405 else
4407 XUNMARK (buffer->name);
4408 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
4409 prev = buffer, buffer = buffer->next;
4413 /* Free all unmarked vectors */
4415 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
4416 total_vector_size = 0;
4418 while (vector)
4419 if (!(vector->size & ARRAY_MARK_FLAG))
4421 if (prev)
4422 prev->next = vector->next;
4423 else
4424 all_vectors = vector->next;
4425 next = vector->next;
4426 lisp_free (vector);
4427 n_vectors--;
4428 vector = next;
4431 else
4433 vector->size &= ~ARRAY_MARK_FLAG;
4434 if (vector->size & PSEUDOVECTOR_FLAG)
4435 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
4436 else
4437 total_vector_size += vector->size;
4438 prev = vector, vector = vector->next;
4446 /* Debugging aids. */
4448 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
4449 "Return the address of the last byte Emacs has allocated, divided by 1024.\n\
4450 This may be helpful in debugging Emacs's memory usage.\n\
4451 We divide the value by 1024 to make sure it fits in a Lisp integer.")
4454 Lisp_Object end;
4456 XSETINT (end, (EMACS_INT) sbrk (0) / 1024);
4458 return end;
4461 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
4462 "Return a list of counters that measure how much consing there has been.\n\
4463 Each of these counters increments for a certain kind of object.\n\
4464 The counters wrap around from the largest positive integer to zero.\n\
4465 Garbage collection does not decrease them.\n\
4466 The elements of the value are as follows:\n\
4467 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)\n\
4468 All are in units of 1 = one object consed\n\
4469 except for VECTOR-CELLS and STRING-CHARS, which count the total length of\n\
4470 objects consed.\n\
4471 MISCS include overlays, markers, and some internal types.\n\
4472 Frames, windows, buffers, and subprocesses count as vectors\n\
4473 (but the contents of a buffer's text do not count here).")
4476 Lisp_Object consed[8];
4478 XSETINT (consed[0],
4479 cons_cells_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
4480 XSETINT (consed[1],
4481 floats_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
4482 XSETINT (consed[2],
4483 vector_cells_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
4484 XSETINT (consed[3],
4485 symbols_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
4486 XSETINT (consed[4],
4487 string_chars_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
4488 XSETINT (consed[5],
4489 misc_objects_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
4490 XSETINT (consed[6],
4491 intervals_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
4492 XSETINT (consed[7],
4493 strings_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
4495 return Flist (8, consed);
4498 /* Initialization */
4500 void
4501 init_alloc_once ()
4503 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
4504 pureptr = 0;
4505 #if GC_MARK_STACK
4506 mem_init ();
4507 Vdead = make_pure_string ("DEAD", 4, 4, 0);
4508 #endif
4509 #ifdef HAVE_SHM
4510 pure_size = PURESIZE;
4511 #endif
4512 all_vectors = 0;
4513 ignore_warnings = 1;
4514 #ifdef DOUG_LEA_MALLOC
4515 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
4516 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
4517 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
4518 #endif
4519 init_strings ();
4520 init_cons ();
4521 init_symbol ();
4522 init_marker ();
4523 init_float ();
4524 init_intervals ();
4526 #ifdef REL_ALLOC
4527 malloc_hysteresis = 32;
4528 #else
4529 malloc_hysteresis = 0;
4530 #endif
4532 spare_memory = (char *) malloc (SPARE_MEMORY);
4534 ignore_warnings = 0;
4535 gcprolist = 0;
4536 byte_stack_list = 0;
4537 staticidx = 0;
4538 consing_since_gc = 0;
4539 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
4540 #ifdef VIRT_ADDR_VARIES
4541 malloc_sbrk_unused = 1<<22; /* A large number */
4542 malloc_sbrk_used = 100000; /* as reasonable as any number */
4543 #endif /* VIRT_ADDR_VARIES */
4546 void
4547 init_alloc ()
4549 gcprolist = 0;
4550 byte_stack_list = 0;
4553 void
4554 syms_of_alloc ()
4556 DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold,
4557 "*Number of bytes of consing between garbage collections.\n\
4558 Garbage collection can happen automatically once this many bytes have been\n\
4559 allocated since the last garbage collection. All data types count.\n\n\
4560 Garbage collection happens automatically only when `eval' is called.\n\n\
4561 By binding this temporarily to a large number, you can effectively\n\
4562 prevent garbage collection during a part of the program.");
4564 DEFVAR_INT ("pure-bytes-used", &pureptr,
4565 "Number of bytes of sharable Lisp data allocated so far.");
4567 DEFVAR_INT ("cons-cells-consed", &cons_cells_consed,
4568 "Number of cons cells that have been consed so far.");
4570 DEFVAR_INT ("floats-consed", &floats_consed,
4571 "Number of floats that have been consed so far.");
4573 DEFVAR_INT ("vector-cells-consed", &vector_cells_consed,
4574 "Number of vector cells that have been consed so far.");
4576 DEFVAR_INT ("symbols-consed", &symbols_consed,
4577 "Number of symbols that have been consed so far.");
4579 DEFVAR_INT ("string-chars-consed", &string_chars_consed,
4580 "Number of string characters that have been consed so far.");
4582 DEFVAR_INT ("misc-objects-consed", &misc_objects_consed,
4583 "Number of miscellaneous objects that have been consed so far.");
4585 DEFVAR_INT ("intervals-consed", &intervals_consed,
4586 "Number of intervals that have been consed so far.");
4588 DEFVAR_INT ("strings-consed", &strings_consed,
4589 "Number of strings that have been consed so far.");
4591 DEFVAR_LISP ("purify-flag", &Vpurify_flag,
4592 "Non-nil means loading Lisp code in order to dump an executable.\n\
4593 This means that certain objects should be allocated in shared (pure) space.");
4595 DEFVAR_INT ("undo-limit", &undo_limit,
4596 "Keep no more undo information once it exceeds this size.\n\
4597 This limit is applied when garbage collection happens.\n\
4598 The size is counted as the number of bytes occupied,\n\
4599 which includes both saved text and other data.");
4600 undo_limit = 20000;
4602 DEFVAR_INT ("undo-strong-limit", &undo_strong_limit,
4603 "Don't keep more than this much size of undo information.\n\
4604 A command which pushes past this size is itself forgotten.\n\
4605 This limit is applied when garbage collection happens.\n\
4606 The size is counted as the number of bytes occupied,\n\
4607 which includes both saved text and other data.");
4608 undo_strong_limit = 30000;
4610 DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
4611 "Non-nil means display messages at start and end of garbage collection.");
4612 garbage_collection_messages = 0;
4614 /* We build this in advance because if we wait until we need it, we might
4615 not be able to allocate the memory to hold it. */
4616 memory_signal_data
4617 = Fcons (Qerror, Fcons (build_string ("Memory exhausted--use M-x save-some-buffers RET"), Qnil));
4618 staticpro (&memory_signal_data);
4620 staticpro (&Qgc_cons_threshold);
4621 Qgc_cons_threshold = intern ("gc-cons-threshold");
4623 staticpro (&Qchar_table_extra_slots);
4624 Qchar_table_extra_slots = intern ("char-table-extra-slots");
4626 defsubr (&Scons);
4627 defsubr (&Slist);
4628 defsubr (&Svector);
4629 defsubr (&Smake_byte_code);
4630 defsubr (&Smake_list);
4631 defsubr (&Smake_vector);
4632 defsubr (&Smake_char_table);
4633 defsubr (&Smake_string);
4634 defsubr (&Smake_bool_vector);
4635 defsubr (&Smake_symbol);
4636 defsubr (&Smake_marker);
4637 defsubr (&Spurecopy);
4638 defsubr (&Sgarbage_collect);
4639 defsubr (&Smemory_limit);
4640 defsubr (&Smemory_use_counts);
4642 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4643 defsubr (&Sgc_status);
4644 #endif