(Autoinserting): Remove doubled `insert'.
[emacs.git] / src / alloc.c
blob4affa42e6831472cd652e3fa85f4e7b44918db23
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
2 Copyright (C) 1985, 86, 88, 93, 94, 95, 97, 98, 1999, 2000, 2001
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 #include <config.h>
23 #include <stdio.h>
25 /* Note that this declares bzero on OSF/1. How dumb. */
27 #include <signal.h>
29 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
30 memory. Can do this only if using gmalloc.c. */
32 #if defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC
33 #undef GC_MALLOC_CHECK
34 #endif
36 /* This file is part of the core Lisp implementation, and thus must
37 deal with the real data structures. If the Lisp implementation is
38 replaced, this file likely will not be used. */
40 #undef HIDE_LISP_IMPLEMENTATION
41 #include "lisp.h"
42 #include "intervals.h"
43 #include "puresize.h"
44 #include "buffer.h"
45 #include "window.h"
46 #include "keyboard.h"
47 #include "frame.h"
48 #include "blockinput.h"
49 #include "charset.h"
50 #include "syssignal.h"
51 #include <setjmp.h>
53 #ifdef HAVE_UNISTD_H
54 #include <unistd.h>
55 #else
56 extern POINTER_TYPE *sbrk ();
57 #endif
59 #ifdef DOUG_LEA_MALLOC
61 #include <malloc.h>
62 /* malloc.h #defines this as size_t, at least in glibc2. */
63 #ifndef __malloc_size_t
64 #define __malloc_size_t int
65 #endif
67 /* Specify maximum number of areas to mmap. It would be nice to use a
68 value that explicitly means "no limit". */
70 #define MMAP_MAX_AREAS 100000000
72 #else /* not DOUG_LEA_MALLOC */
74 /* The following come from gmalloc.c. */
76 #define __malloc_size_t size_t
77 extern __malloc_size_t _bytes_used;
78 extern __malloc_size_t __malloc_extra_blocks;
80 #endif /* not DOUG_LEA_MALLOC */
82 #define max(A,B) ((A) > (B) ? (A) : (B))
83 #define min(A,B) ((A) < (B) ? (A) : (B))
85 /* Macro to verify that storage intended for Lisp objects is not
86 out of range to fit in the space for a pointer.
87 ADDRESS is the start of the block, and SIZE
88 is the amount of space within which objects can start. */
90 #define VALIDATE_LISP_STORAGE(address, size) \
91 do \
92 { \
93 Lisp_Object val; \
94 XSETCONS (val, (char *) address + size); \
95 if ((char *) XCONS (val) != (char *) address + size) \
96 { \
97 xfree (address); \
98 memory_full (); \
99 } \
100 } while (0)
102 /* Value of _bytes_used, when spare_memory was freed. */
104 static __malloc_size_t bytes_used_when_full;
106 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
107 to a struct Lisp_String. */
109 #define MARK_STRING(S) ((S)->size |= MARKBIT)
110 #define UNMARK_STRING(S) ((S)->size &= ~MARKBIT)
111 #define STRING_MARKED_P(S) ((S)->size & MARKBIT)
113 /* Value is the number of bytes/chars of S, a pointer to a struct
114 Lisp_String. This must be used instead of STRING_BYTES (S) or
115 S->size during GC, because S->size contains the mark bit for
116 strings. */
118 #define GC_STRING_BYTES(S) (STRING_BYTES (S) & ~MARKBIT)
119 #define GC_STRING_CHARS(S) ((S)->size & ~MARKBIT)
121 /* Number of bytes of consing done since the last gc. */
123 int consing_since_gc;
125 /* Count the amount of consing of various sorts of space. */
127 int cons_cells_consed;
128 int floats_consed;
129 int vector_cells_consed;
130 int symbols_consed;
131 int string_chars_consed;
132 int misc_objects_consed;
133 int intervals_consed;
134 int strings_consed;
136 /* Number of bytes of consing since GC before another GC should be done. */
138 int gc_cons_threshold;
140 /* Nonzero during GC. */
142 int gc_in_progress;
144 /* Nonzero means display messages at beginning and end of GC. */
146 int garbage_collection_messages;
148 #ifndef VIRT_ADDR_VARIES
149 extern
150 #endif /* VIRT_ADDR_VARIES */
151 int malloc_sbrk_used;
153 #ifndef VIRT_ADDR_VARIES
154 extern
155 #endif /* VIRT_ADDR_VARIES */
156 int malloc_sbrk_unused;
158 /* Two limits controlling how much undo information to keep. */
160 int undo_limit;
161 int undo_strong_limit;
163 /* Number of live and free conses etc. */
165 static int total_conses, total_markers, total_symbols, total_vector_size;
166 static int total_free_conses, total_free_markers, total_free_symbols;
167 static int total_free_floats, total_floats;
169 /* Points to memory space allocated as "spare", to be freed if we run
170 out of memory. */
172 static char *spare_memory;
174 /* Amount of spare memory to keep in reserve. */
176 #define SPARE_MEMORY (1 << 14)
178 /* Number of extra blocks malloc should get when it needs more core. */
180 static int malloc_hysteresis;
182 /* Non-nil means defun should do purecopy on the function definition. */
184 Lisp_Object Vpurify_flag;
186 #ifndef HAVE_SHM
188 /* Force it into data space! */
190 EMACS_INT pure[PURESIZE / sizeof (EMACS_INT)] = {0,};
191 #define PUREBEG (char *) pure
193 #else /* not HAVE_SHM */
195 #define pure PURE_SEG_BITS /* Use shared memory segment */
196 #define PUREBEG (char *)PURE_SEG_BITS
198 /* This variable is used only by the XPNTR macro when HAVE_SHM is
199 defined. If we used the PURESIZE macro directly there, that would
200 make most of Emacs dependent on puresize.h, which we don't want -
201 you should be able to change that without too much recompilation.
202 So map_in_data initializes pure_size, and the dependencies work
203 out. */
205 EMACS_INT pure_size;
207 #endif /* not HAVE_SHM */
209 /* Value is non-zero if P points into pure space. */
211 #define PURE_POINTER_P(P) \
212 (((PNTR_COMPARISON_TYPE) (P) \
213 < (PNTR_COMPARISON_TYPE) ((char *) pure + PURESIZE)) \
214 && ((PNTR_COMPARISON_TYPE) (P) \
215 >= (PNTR_COMPARISON_TYPE) pure))
217 /* Index in pure at which next pure object will be allocated.. */
219 int pure_bytes_used;
221 /* If nonzero, this is a warning delivered by malloc and not yet
222 displayed. */
224 char *pending_malloc_warning;
226 /* Pre-computed signal argument for use when memory is exhausted. */
228 Lisp_Object memory_signal_data;
230 /* Maximum amount of C stack to save when a GC happens. */
232 #ifndef MAX_SAVE_STACK
233 #define MAX_SAVE_STACK 16000
234 #endif
236 /* Buffer in which we save a copy of the C stack at each GC. */
238 char *stack_copy;
239 int stack_copy_size;
241 /* Non-zero means ignore malloc warnings. Set during initialization.
242 Currently not used. */
244 int ignore_warnings;
246 Lisp_Object Qgc_cons_threshold, Qchar_table_extra_slots;
248 static void mark_buffer P_ ((Lisp_Object));
249 static void mark_kboards P_ ((void));
250 static void gc_sweep P_ ((void));
251 static void mark_glyph_matrix P_ ((struct glyph_matrix *));
252 static void mark_face_cache P_ ((struct face_cache *));
254 #ifdef HAVE_WINDOW_SYSTEM
255 static void mark_image P_ ((struct image *));
256 static void mark_image_cache P_ ((struct frame *));
257 #endif /* HAVE_WINDOW_SYSTEM */
259 static struct Lisp_String *allocate_string P_ ((void));
260 static void compact_small_strings P_ ((void));
261 static void free_large_strings P_ ((void));
262 static void sweep_strings P_ ((void));
264 extern int message_enable_multibyte;
266 /* When scanning the C stack for live Lisp objects, Emacs keeps track
267 of what memory allocated via lisp_malloc is intended for what
268 purpose. This enumeration specifies the type of memory. */
270 enum mem_type
272 MEM_TYPE_NON_LISP,
273 MEM_TYPE_BUFFER,
274 MEM_TYPE_CONS,
275 MEM_TYPE_STRING,
276 MEM_TYPE_MISC,
277 MEM_TYPE_SYMBOL,
278 MEM_TYPE_FLOAT,
279 MEM_TYPE_VECTOR
282 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
284 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
285 #include <stdio.h> /* For fprintf. */
286 #endif
288 /* A unique object in pure space used to make some Lisp objects
289 on free lists recognizable in O(1). */
291 Lisp_Object Vdead;
293 #ifdef GC_MALLOC_CHECK
295 enum mem_type allocated_mem_type;
296 int dont_register_blocks;
298 #endif /* GC_MALLOC_CHECK */
300 /* A node in the red-black tree describing allocated memory containing
301 Lisp data. Each such block is recorded with its start and end
302 address when it is allocated, and removed from the tree when it
303 is freed.
305 A red-black tree is a balanced binary tree with the following
306 properties:
308 1. Every node is either red or black.
309 2. Every leaf is black.
310 3. If a node is red, then both of its children are black.
311 4. Every simple path from a node to a descendant leaf contains
312 the same number of black nodes.
313 5. The root is always black.
315 When nodes are inserted into the tree, or deleted from the tree,
316 the tree is "fixed" so that these properties are always true.
318 A red-black tree with N internal nodes has height at most 2
319 log(N+1). Searches, insertions and deletions are done in O(log N).
320 Please see a text book about data structures for a detailed
321 description of red-black trees. Any book worth its salt should
322 describe them. */
324 struct mem_node
326 struct mem_node *left, *right, *parent;
328 /* Start and end of allocated region. */
329 void *start, *end;
331 /* Node color. */
332 enum {MEM_BLACK, MEM_RED} color;
334 /* Memory type. */
335 enum mem_type type;
338 /* Base address of stack. Set in main. */
340 Lisp_Object *stack_base;
342 /* Root of the tree describing allocated Lisp memory. */
344 static struct mem_node *mem_root;
346 /* Sentinel node of the tree. */
348 static struct mem_node mem_z;
349 #define MEM_NIL &mem_z
351 static POINTER_TYPE *lisp_malloc P_ ((size_t, enum mem_type));
352 static void lisp_free P_ ((POINTER_TYPE *));
353 static void mark_stack P_ ((void));
354 static void init_stack P_ ((Lisp_Object *));
355 static int live_vector_p P_ ((struct mem_node *, void *));
356 static int live_buffer_p P_ ((struct mem_node *, void *));
357 static int live_string_p P_ ((struct mem_node *, void *));
358 static int live_cons_p P_ ((struct mem_node *, void *));
359 static int live_symbol_p P_ ((struct mem_node *, void *));
360 static int live_float_p P_ ((struct mem_node *, void *));
361 static int live_misc_p P_ ((struct mem_node *, void *));
362 static void mark_maybe_object P_ ((Lisp_Object));
363 static void mark_memory P_ ((void *, void *));
364 static void mem_init P_ ((void));
365 static struct mem_node *mem_insert P_ ((void *, void *, enum mem_type));
366 static void mem_insert_fixup P_ ((struct mem_node *));
367 static void mem_rotate_left P_ ((struct mem_node *));
368 static void mem_rotate_right P_ ((struct mem_node *));
369 static void mem_delete P_ ((struct mem_node *));
370 static void mem_delete_fixup P_ ((struct mem_node *));
371 static INLINE struct mem_node *mem_find P_ ((void *));
373 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
374 static void check_gcpros P_ ((void));
375 #endif
377 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
379 /* Recording what needs to be marked for gc. */
381 struct gcpro *gcprolist;
383 /* Addresses of staticpro'd variables. */
385 #define NSTATICS 1024
386 Lisp_Object *staticvec[NSTATICS] = {0};
388 /* Index of next unused slot in staticvec. */
390 int staticidx = 0;
392 static POINTER_TYPE *pure_alloc P_ ((size_t, int));
395 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
396 ALIGNMENT must be a power of 2. */
398 #define ALIGN(SZ, ALIGNMENT) \
399 (((SZ) + (ALIGNMENT) - 1) & ~((ALIGNMENT) - 1))
402 /************************************************************************
403 Malloc
404 ************************************************************************/
406 /* Write STR to Vstandard_output plus some advice on how to free some
407 memory. Called when memory gets low. */
409 Lisp_Object
410 malloc_warning_1 (str)
411 Lisp_Object str;
413 Fprinc (str, Vstandard_output);
414 write_string ("\nKilling some buffers may delay running out of memory.\n", -1);
415 write_string ("However, certainly by the time you receive the 95% warning,\n", -1);
416 write_string ("you should clean up, kill this Emacs, and start a new one.", -1);
417 return Qnil;
421 /* Function malloc calls this if it finds we are near exhausting
422 storage. */
424 void
425 malloc_warning (str)
426 char *str;
428 pending_malloc_warning = str;
432 /* Display a malloc warning in buffer *Danger*. */
434 void
435 display_malloc_warning ()
437 register Lisp_Object val;
439 val = build_string (pending_malloc_warning);
440 pending_malloc_warning = 0;
441 internal_with_output_to_temp_buffer (" *Danger*", malloc_warning_1, val);
445 #ifdef DOUG_LEA_MALLOC
446 # define BYTES_USED (mallinfo ().arena)
447 #else
448 # define BYTES_USED _bytes_used
449 #endif
452 /* Called if malloc returns zero. */
454 void
455 memory_full ()
457 #ifndef SYSTEM_MALLOC
458 bytes_used_when_full = BYTES_USED;
459 #endif
461 /* The first time we get here, free the spare memory. */
462 if (spare_memory)
464 free (spare_memory);
465 spare_memory = 0;
468 /* This used to call error, but if we've run out of memory, we could
469 get infinite recursion trying to build the string. */
470 while (1)
471 Fsignal (Qnil, memory_signal_data);
475 /* Called if we can't allocate relocatable space for a buffer. */
477 void
478 buffer_memory_full ()
480 /* If buffers use the relocating allocator, no need to free
481 spare_memory, because we may have plenty of malloc space left
482 that we could get, and if we don't, the malloc that fails will
483 itself cause spare_memory to be freed. If buffers don't use the
484 relocating allocator, treat this like any other failing
485 malloc. */
487 #ifndef REL_ALLOC
488 memory_full ();
489 #endif
491 /* This used to call error, but if we've run out of memory, we could
492 get infinite recursion trying to build the string. */
493 while (1)
494 Fsignal (Qerror, memory_signal_data);
498 /* Like malloc but check for no memory and block interrupt input.. */
500 POINTER_TYPE *
501 xmalloc (size)
502 size_t size;
504 register POINTER_TYPE *val;
506 BLOCK_INPUT;
507 val = (POINTER_TYPE *) malloc (size);
508 UNBLOCK_INPUT;
510 if (!val && size)
511 memory_full ();
512 return val;
516 /* Like realloc but check for no memory and block interrupt input.. */
518 POINTER_TYPE *
519 xrealloc (block, size)
520 POINTER_TYPE *block;
521 size_t size;
523 register POINTER_TYPE *val;
525 BLOCK_INPUT;
526 /* We must call malloc explicitly when BLOCK is 0, since some
527 reallocs don't do this. */
528 if (! block)
529 val = (POINTER_TYPE *) malloc (size);
530 else
531 val = (POINTER_TYPE *) realloc (block, size);
532 UNBLOCK_INPUT;
534 if (!val && size) memory_full ();
535 return val;
539 /* Like free but block interrupt input.. */
541 void
542 xfree (block)
543 POINTER_TYPE *block;
545 BLOCK_INPUT;
546 free (block);
547 UNBLOCK_INPUT;
551 /* Like strdup, but uses xmalloc. */
553 char *
554 xstrdup (s)
555 char *s;
557 size_t len = strlen (s) + 1;
558 char *p = (char *) xmalloc (len);
559 bcopy (s, p, len);
560 return p;
564 /* Like malloc but used for allocating Lisp data. NBYTES is the
565 number of bytes to allocate, TYPE describes the intended use of the
566 allcated memory block (for strings, for conses, ...). */
568 static POINTER_TYPE *
569 lisp_malloc (nbytes, type)
570 size_t nbytes;
571 enum mem_type type;
573 register void *val;
575 BLOCK_INPUT;
577 #ifdef GC_MALLOC_CHECK
578 allocated_mem_type = type;
579 #endif
581 val = (void *) malloc (nbytes);
583 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
584 if (val && type != MEM_TYPE_NON_LISP)
585 mem_insert (val, (char *) val + nbytes, type);
586 #endif
588 UNBLOCK_INPUT;
589 if (!val && nbytes)
590 memory_full ();
591 return val;
595 /* Return a new buffer structure allocated from the heap with
596 a call to lisp_malloc. */
598 struct buffer *
599 allocate_buffer ()
601 return (struct buffer *) lisp_malloc (sizeof (struct buffer),
602 MEM_TYPE_BUFFER);
606 /* Free BLOCK. This must be called to free memory allocated with a
607 call to lisp_malloc. */
609 static void
610 lisp_free (block)
611 POINTER_TYPE *block;
613 BLOCK_INPUT;
614 free (block);
615 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
616 mem_delete (mem_find (block));
617 #endif
618 UNBLOCK_INPUT;
622 /* Arranging to disable input signals while we're in malloc.
624 This only works with GNU malloc. To help out systems which can't
625 use GNU malloc, all the calls to malloc, realloc, and free
626 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
627 pairs; unfortunately, we have no idea what C library functions
628 might call malloc, so we can't really protect them unless you're
629 using GNU malloc. Fortunately, most of the major operating can use
630 GNU malloc. */
632 #ifndef SYSTEM_MALLOC
633 #ifndef DOUG_LEA_MALLOC
634 extern void * (*__malloc_hook) P_ ((size_t));
635 extern void * (*__realloc_hook) P_ ((void *, size_t));
636 extern void (*__free_hook) P_ ((void *));
637 /* Else declared in malloc.h, perhaps with an extra arg. */
638 #endif /* DOUG_LEA_MALLOC */
639 static void * (*old_malloc_hook) ();
640 static void * (*old_realloc_hook) ();
641 static void (*old_free_hook) ();
643 /* This function is used as the hook for free to call. */
645 static void
646 emacs_blocked_free (ptr)
647 void *ptr;
649 BLOCK_INPUT;
651 #ifdef GC_MALLOC_CHECK
652 if (ptr)
654 struct mem_node *m;
656 m = mem_find (ptr);
657 if (m == MEM_NIL || m->start != ptr)
659 fprintf (stderr,
660 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
661 abort ();
663 else
665 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
666 mem_delete (m);
669 #endif /* GC_MALLOC_CHECK */
671 __free_hook = old_free_hook;
672 free (ptr);
674 /* If we released our reserve (due to running out of memory),
675 and we have a fair amount free once again,
676 try to set aside another reserve in case we run out once more. */
677 if (spare_memory == 0
678 /* Verify there is enough space that even with the malloc
679 hysteresis this call won't run out again.
680 The code here is correct as long as SPARE_MEMORY
681 is substantially larger than the block size malloc uses. */
682 && (bytes_used_when_full
683 > BYTES_USED + max (malloc_hysteresis, 4) * SPARE_MEMORY))
684 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
686 __free_hook = emacs_blocked_free;
687 UNBLOCK_INPUT;
691 /* If we released our reserve (due to running out of memory),
692 and we have a fair amount free once again,
693 try to set aside another reserve in case we run out once more.
695 This is called when a relocatable block is freed in ralloc.c. */
697 void
698 refill_memory_reserve ()
700 if (spare_memory == 0)
701 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
705 /* This function is the malloc hook that Emacs uses. */
707 static void *
708 emacs_blocked_malloc (size)
709 size_t size;
711 void *value;
713 BLOCK_INPUT;
714 __malloc_hook = old_malloc_hook;
715 #ifdef DOUG_LEA_MALLOC
716 mallopt (M_TOP_PAD, malloc_hysteresis * 4096);
717 #else
718 __malloc_extra_blocks = malloc_hysteresis;
719 #endif
721 value = (void *) malloc (size);
723 #ifdef GC_MALLOC_CHECK
725 struct mem_node *m = mem_find (value);
726 if (m != MEM_NIL)
728 fprintf (stderr, "Malloc returned %p which is already in use\n",
729 value);
730 fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
731 m->start, m->end, (char *) m->end - (char *) m->start,
732 m->type);
733 abort ();
736 if (!dont_register_blocks)
738 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
739 allocated_mem_type = MEM_TYPE_NON_LISP;
742 #endif /* GC_MALLOC_CHECK */
744 __malloc_hook = emacs_blocked_malloc;
745 UNBLOCK_INPUT;
747 /* fprintf (stderr, "%p malloc\n", value); */
748 return value;
752 /* This function is the realloc hook that Emacs uses. */
754 static void *
755 emacs_blocked_realloc (ptr, size)
756 void *ptr;
757 size_t size;
759 void *value;
761 BLOCK_INPUT;
762 __realloc_hook = old_realloc_hook;
764 #ifdef GC_MALLOC_CHECK
765 if (ptr)
767 struct mem_node *m = mem_find (ptr);
768 if (m == MEM_NIL || m->start != ptr)
770 fprintf (stderr,
771 "Realloc of %p which wasn't allocated with malloc\n",
772 ptr);
773 abort ();
776 mem_delete (m);
779 /* fprintf (stderr, "%p -> realloc\n", ptr); */
781 /* Prevent malloc from registering blocks. */
782 dont_register_blocks = 1;
783 #endif /* GC_MALLOC_CHECK */
785 value = (void *) realloc (ptr, size);
787 #ifdef GC_MALLOC_CHECK
788 dont_register_blocks = 0;
791 struct mem_node *m = mem_find (value);
792 if (m != MEM_NIL)
794 fprintf (stderr, "Realloc returns memory that is already in use\n");
795 abort ();
798 /* Can't handle zero size regions in the red-black tree. */
799 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
802 /* fprintf (stderr, "%p <- realloc\n", value); */
803 #endif /* GC_MALLOC_CHECK */
805 __realloc_hook = emacs_blocked_realloc;
806 UNBLOCK_INPUT;
808 return value;
812 /* Called from main to set up malloc to use our hooks. */
814 void
815 uninterrupt_malloc ()
817 if (__free_hook != emacs_blocked_free)
818 old_free_hook = __free_hook;
819 __free_hook = emacs_blocked_free;
821 if (__malloc_hook != emacs_blocked_malloc)
822 old_malloc_hook = __malloc_hook;
823 __malloc_hook = emacs_blocked_malloc;
825 if (__realloc_hook != emacs_blocked_realloc)
826 old_realloc_hook = __realloc_hook;
827 __realloc_hook = emacs_blocked_realloc;
830 #endif /* not SYSTEM_MALLOC */
834 /***********************************************************************
835 Interval Allocation
836 ***********************************************************************/
838 /* Number of intervals allocated in an interval_block structure.
839 The 1020 is 1024 minus malloc overhead. */
841 #define INTERVAL_BLOCK_SIZE \
842 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
844 /* Intervals are allocated in chunks in form of an interval_block
845 structure. */
847 struct interval_block
849 struct interval_block *next;
850 struct interval intervals[INTERVAL_BLOCK_SIZE];
853 /* Current interval block. Its `next' pointer points to older
854 blocks. */
856 struct interval_block *interval_block;
858 /* Index in interval_block above of the next unused interval
859 structure. */
861 static int interval_block_index;
863 /* Number of free and live intervals. */
865 static int total_free_intervals, total_intervals;
867 /* List of free intervals. */
869 INTERVAL interval_free_list;
871 /* Total number of interval blocks now in use. */
873 int n_interval_blocks;
876 /* Initialize interval allocation. */
878 static void
879 init_intervals ()
881 interval_block
882 = (struct interval_block *) lisp_malloc (sizeof *interval_block,
883 MEM_TYPE_NON_LISP);
884 interval_block->next = 0;
885 bzero ((char *) interval_block->intervals, sizeof interval_block->intervals);
886 interval_block_index = 0;
887 interval_free_list = 0;
888 n_interval_blocks = 1;
892 /* Return a new interval. */
894 INTERVAL
895 make_interval ()
897 INTERVAL val;
899 if (interval_free_list)
901 val = interval_free_list;
902 interval_free_list = INTERVAL_PARENT (interval_free_list);
904 else
906 if (interval_block_index == INTERVAL_BLOCK_SIZE)
908 register struct interval_block *newi;
910 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
911 MEM_TYPE_NON_LISP);
913 VALIDATE_LISP_STORAGE (newi, sizeof *newi);
914 newi->next = interval_block;
915 interval_block = newi;
916 interval_block_index = 0;
917 n_interval_blocks++;
919 val = &interval_block->intervals[interval_block_index++];
921 consing_since_gc += sizeof (struct interval);
922 intervals_consed++;
923 RESET_INTERVAL (val);
924 return val;
928 /* Mark Lisp objects in interval I. */
930 static void
931 mark_interval (i, dummy)
932 register INTERVAL i;
933 Lisp_Object dummy;
935 if (XMARKBIT (i->plist))
936 abort ();
937 mark_object (&i->plist);
938 XMARK (i->plist);
942 /* Mark the interval tree rooted in TREE. Don't call this directly;
943 use the macro MARK_INTERVAL_TREE instead. */
945 static void
946 mark_interval_tree (tree)
947 register INTERVAL tree;
949 /* No need to test if this tree has been marked already; this
950 function is always called through the MARK_INTERVAL_TREE macro,
951 which takes care of that. */
953 /* XMARK expands to an assignment; the LHS of an assignment can't be
954 a cast. */
955 XMARK (tree->up.obj);
957 traverse_intervals (tree, 1, 0, mark_interval, Qnil);
961 /* Mark the interval tree rooted in I. */
963 #define MARK_INTERVAL_TREE(i) \
964 do { \
965 if (!NULL_INTERVAL_P (i) \
966 && ! XMARKBIT (i->up.obj)) \
967 mark_interval_tree (i); \
968 } while (0)
971 /* The oddity in the call to XUNMARK is necessary because XUNMARK
972 expands to an assignment to its argument, and most C compilers
973 don't support casts on the left operand of `='. */
975 #define UNMARK_BALANCE_INTERVALS(i) \
976 do { \
977 if (! NULL_INTERVAL_P (i)) \
979 XUNMARK ((i)->up.obj); \
980 (i) = balance_intervals (i); \
982 } while (0)
985 /* Number support. If NO_UNION_TYPE isn't in effect, we
986 can't create number objects in macros. */
987 #ifndef make_number
988 Lisp_Object
989 make_number (n)
990 int n;
992 Lisp_Object obj;
993 obj.s.val = n;
994 obj.s.type = Lisp_Int;
995 return obj;
997 #endif
999 /***********************************************************************
1000 String Allocation
1001 ***********************************************************************/
1003 /* Lisp_Strings are allocated in string_block structures. When a new
1004 string_block is allocated, all the Lisp_Strings it contains are
1005 added to a free-list stiing_free_list. When a new Lisp_String is
1006 needed, it is taken from that list. During the sweep phase of GC,
1007 string_blocks that are entirely free are freed, except two which
1008 we keep.
1010 String data is allocated from sblock structures. Strings larger
1011 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1012 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1014 Sblocks consist internally of sdata structures, one for each
1015 Lisp_String. The sdata structure points to the Lisp_String it
1016 belongs to. The Lisp_String points back to the `u.data' member of
1017 its sdata structure.
1019 When a Lisp_String is freed during GC, it is put back on
1020 string_free_list, and its `data' member and its sdata's `string'
1021 pointer is set to null. The size of the string is recorded in the
1022 `u.nbytes' member of the sdata. So, sdata structures that are no
1023 longer used, can be easily recognized, and it's easy to compact the
1024 sblocks of small strings which we do in compact_small_strings. */
1026 /* Size in bytes of an sblock structure used for small strings. This
1027 is 8192 minus malloc overhead. */
1029 #define SBLOCK_SIZE 8188
1031 /* Strings larger than this are considered large strings. String data
1032 for large strings is allocated from individual sblocks. */
1034 #define LARGE_STRING_BYTES 1024
1036 /* Structure describing string memory sub-allocated from an sblock.
1037 This is where the contents of Lisp strings are stored. */
1039 struct sdata
1041 /* Back-pointer to the string this sdata belongs to. If null, this
1042 structure is free, and the NBYTES member of the union below
1043 contains the string's byte size (the same value that STRING_BYTES
1044 would return if STRING were non-null). If non-null, STRING_BYTES
1045 (STRING) is the size of the data, and DATA contains the string's
1046 contents. */
1047 struct Lisp_String *string;
1049 #ifdef GC_CHECK_STRING_BYTES
1051 EMACS_INT nbytes;
1052 unsigned char data[1];
1054 #define SDATA_NBYTES(S) (S)->nbytes
1055 #define SDATA_DATA(S) (S)->data
1057 #else /* not GC_CHECK_STRING_BYTES */
1059 union
1061 /* When STRING in non-null. */
1062 unsigned char data[1];
1064 /* When STRING is null. */
1065 EMACS_INT nbytes;
1066 } u;
1069 #define SDATA_NBYTES(S) (S)->u.nbytes
1070 #define SDATA_DATA(S) (S)->u.data
1072 #endif /* not GC_CHECK_STRING_BYTES */
1076 /* Structure describing a block of memory which is sub-allocated to
1077 obtain string data memory for strings. Blocks for small strings
1078 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1079 as large as needed. */
1081 struct sblock
1083 /* Next in list. */
1084 struct sblock *next;
1086 /* Pointer to the next free sdata block. This points past the end
1087 of the sblock if there isn't any space left in this block. */
1088 struct sdata *next_free;
1090 /* Start of data. */
1091 struct sdata first_data;
1094 /* Number of Lisp strings in a string_block structure. The 1020 is
1095 1024 minus malloc overhead. */
1097 #define STRINGS_IN_STRING_BLOCK \
1098 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1100 /* Structure describing a block from which Lisp_String structures
1101 are allocated. */
1103 struct string_block
1105 struct string_block *next;
1106 struct Lisp_String strings[STRINGS_IN_STRING_BLOCK];
1109 /* Head and tail of the list of sblock structures holding Lisp string
1110 data. We always allocate from current_sblock. The NEXT pointers
1111 in the sblock structures go from oldest_sblock to current_sblock. */
1113 static struct sblock *oldest_sblock, *current_sblock;
1115 /* List of sblocks for large strings. */
1117 static struct sblock *large_sblocks;
1119 /* List of string_block structures, and how many there are. */
1121 static struct string_block *string_blocks;
1122 static int n_string_blocks;
1124 /* Free-list of Lisp_Strings. */
1126 static struct Lisp_String *string_free_list;
1128 /* Number of live and free Lisp_Strings. */
1130 static int total_strings, total_free_strings;
1132 /* Number of bytes used by live strings. */
1134 static int total_string_size;
1136 /* Given a pointer to a Lisp_String S which is on the free-list
1137 string_free_list, return a pointer to its successor in the
1138 free-list. */
1140 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1142 /* Return a pointer to the sdata structure belonging to Lisp string S.
1143 S must be live, i.e. S->data must not be null. S->data is actually
1144 a pointer to the `u.data' member of its sdata structure; the
1145 structure starts at a constant offset in front of that. */
1147 #ifdef GC_CHECK_STRING_BYTES
1149 #define SDATA_OF_STRING(S) \
1150 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *) \
1151 - sizeof (EMACS_INT)))
1153 #else /* not GC_CHECK_STRING_BYTES */
1155 #define SDATA_OF_STRING(S) \
1156 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))
1158 #endif /* not GC_CHECK_STRING_BYTES */
1160 /* Value is the size of an sdata structure large enough to hold NBYTES
1161 bytes of string data. The value returned includes a terminating
1162 NUL byte, the size of the sdata structure, and padding. */
1164 #ifdef GC_CHECK_STRING_BYTES
1166 #define SDATA_SIZE(NBYTES) \
1167 ((sizeof (struct Lisp_String *) \
1168 + (NBYTES) + 1 \
1169 + sizeof (EMACS_INT) \
1170 + sizeof (EMACS_INT) - 1) \
1171 & ~(sizeof (EMACS_INT) - 1))
1173 #else /* not GC_CHECK_STRING_BYTES */
1175 #define SDATA_SIZE(NBYTES) \
1176 ((sizeof (struct Lisp_String *) \
1177 + (NBYTES) + 1 \
1178 + sizeof (EMACS_INT) - 1) \
1179 & ~(sizeof (EMACS_INT) - 1))
1181 #endif /* not GC_CHECK_STRING_BYTES */
1183 /* Initialize string allocation. Called from init_alloc_once. */
1185 void
1186 init_strings ()
1188 total_strings = total_free_strings = total_string_size = 0;
1189 oldest_sblock = current_sblock = large_sblocks = NULL;
1190 string_blocks = NULL;
1191 n_string_blocks = 0;
1192 string_free_list = NULL;
1196 #ifdef GC_CHECK_STRING_BYTES
1198 static int check_string_bytes_count;
1200 void check_string_bytes P_ ((int));
1201 void check_sblock P_ ((struct sblock *));
1203 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1206 /* Like GC_STRING_BYTES, but with debugging check. */
1209 string_bytes (s)
1210 struct Lisp_String *s;
1212 int nbytes = (s->size_byte < 0 ? s->size : s->size_byte) & ~MARKBIT;
1213 if (!PURE_POINTER_P (s)
1214 && s->data
1215 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1216 abort ();
1217 return nbytes;
1220 /* Check validity Lisp strings' string_bytes member in B. */
1222 void
1223 check_sblock (b)
1224 struct sblock *b;
1226 struct sdata *from, *end, *from_end;
1228 end = b->next_free;
1230 for (from = &b->first_data; from < end; from = from_end)
1232 /* Compute the next FROM here because copying below may
1233 overwrite data we need to compute it. */
1234 int nbytes;
1236 /* Check that the string size recorded in the string is the
1237 same as the one recorded in the sdata structure. */
1238 if (from->string)
1239 CHECK_STRING_BYTES (from->string);
1241 if (from->string)
1242 nbytes = GC_STRING_BYTES (from->string);
1243 else
1244 nbytes = SDATA_NBYTES (from);
1246 nbytes = SDATA_SIZE (nbytes);
1247 from_end = (struct sdata *) ((char *) from + nbytes);
1252 /* Check validity of Lisp strings' string_bytes member. ALL_P
1253 non-zero means check all strings, otherwise check only most
1254 recently allocated strings. Used for hunting a bug. */
1256 void
1257 check_string_bytes (all_p)
1258 int all_p;
1260 if (all_p)
1262 struct sblock *b;
1264 for (b = large_sblocks; b; b = b->next)
1266 struct Lisp_String *s = b->first_data.string;
1267 if (s)
1268 CHECK_STRING_BYTES (s);
1271 for (b = oldest_sblock; b; b = b->next)
1272 check_sblock (b);
1274 else
1275 check_sblock (current_sblock);
1278 #endif /* GC_CHECK_STRING_BYTES */
1281 /* Return a new Lisp_String. */
1283 static struct Lisp_String *
1284 allocate_string ()
1286 struct Lisp_String *s;
1288 /* If the free-list is empty, allocate a new string_block, and
1289 add all the Lisp_Strings in it to the free-list. */
1290 if (string_free_list == NULL)
1292 struct string_block *b;
1293 int i;
1295 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1296 VALIDATE_LISP_STORAGE (b, sizeof *b);
1297 bzero (b, sizeof *b);
1298 b->next = string_blocks;
1299 string_blocks = b;
1300 ++n_string_blocks;
1302 for (i = STRINGS_IN_STRING_BLOCK - 1; i >= 0; --i)
1304 s = b->strings + i;
1305 NEXT_FREE_LISP_STRING (s) = string_free_list;
1306 string_free_list = s;
1309 total_free_strings += STRINGS_IN_STRING_BLOCK;
1312 /* Pop a Lisp_String off the free-list. */
1313 s = string_free_list;
1314 string_free_list = NEXT_FREE_LISP_STRING (s);
1316 /* Probably not strictly necessary, but play it safe. */
1317 bzero (s, sizeof *s);
1319 --total_free_strings;
1320 ++total_strings;
1321 ++strings_consed;
1322 consing_since_gc += sizeof *s;
1324 #ifdef GC_CHECK_STRING_BYTES
1325 if (!noninteractive
1326 #ifdef macintosh
1327 && current_sblock
1328 #endif
1331 if (++check_string_bytes_count == 200)
1333 check_string_bytes_count = 0;
1334 check_string_bytes (1);
1336 else
1337 check_string_bytes (0);
1339 #endif /* GC_CHECK_STRING_BYTES */
1341 return s;
1345 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1346 plus a NUL byte at the end. Allocate an sdata structure for S, and
1347 set S->data to its `u.data' member. Store a NUL byte at the end of
1348 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1349 S->data if it was initially non-null. */
1351 void
1352 allocate_string_data (s, nchars, nbytes)
1353 struct Lisp_String *s;
1354 int nchars, nbytes;
1356 struct sdata *data, *old_data;
1357 struct sblock *b;
1358 int needed, old_nbytes;
1360 /* Determine the number of bytes needed to store NBYTES bytes
1361 of string data. */
1362 needed = SDATA_SIZE (nbytes);
1364 if (nbytes > LARGE_STRING_BYTES)
1366 size_t size = sizeof *b - sizeof (struct sdata) + needed;
1368 #ifdef DOUG_LEA_MALLOC
1369 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1370 because mapped region contents are not preserved in
1371 a dumped Emacs. */
1372 mallopt (M_MMAP_MAX, 0);
1373 #endif
1375 b = (struct sblock *) lisp_malloc (size, MEM_TYPE_NON_LISP);
1377 #ifdef DOUG_LEA_MALLOC
1378 /* Back to a reasonable maximum of mmap'ed areas. */
1379 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1380 #endif
1382 b->next_free = &b->first_data;
1383 b->first_data.string = NULL;
1384 b->next = large_sblocks;
1385 large_sblocks = b;
1387 else if (current_sblock == NULL
1388 || (((char *) current_sblock + SBLOCK_SIZE
1389 - (char *) current_sblock->next_free)
1390 < needed))
1392 /* Not enough room in the current sblock. */
1393 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1394 b->next_free = &b->first_data;
1395 b->first_data.string = NULL;
1396 b->next = NULL;
1398 if (current_sblock)
1399 current_sblock->next = b;
1400 else
1401 oldest_sblock = b;
1402 current_sblock = b;
1404 else
1405 b = current_sblock;
1407 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1408 old_nbytes = GC_STRING_BYTES (s);
1410 data = b->next_free;
1411 data->string = s;
1412 s->data = SDATA_DATA (data);
1413 #ifdef GC_CHECK_STRING_BYTES
1414 SDATA_NBYTES (data) = nbytes;
1415 #endif
1416 s->size = nchars;
1417 s->size_byte = nbytes;
1418 s->data[nbytes] = '\0';
1419 b->next_free = (struct sdata *) ((char *) data + needed);
1421 /* If S had already data assigned, mark that as free by setting its
1422 string back-pointer to null, and recording the size of the data
1423 in it. */
1424 if (old_data)
1426 SDATA_NBYTES (old_data) = old_nbytes;
1427 old_data->string = NULL;
1430 consing_since_gc += needed;
1434 /* Sweep and compact strings. */
1436 static void
1437 sweep_strings ()
1439 struct string_block *b, *next;
1440 struct string_block *live_blocks = NULL;
1442 string_free_list = NULL;
1443 total_strings = total_free_strings = 0;
1444 total_string_size = 0;
1446 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1447 for (b = string_blocks; b; b = next)
1449 int i, nfree = 0;
1450 struct Lisp_String *free_list_before = string_free_list;
1452 next = b->next;
1454 for (i = 0; i < STRINGS_IN_STRING_BLOCK; ++i)
1456 struct Lisp_String *s = b->strings + i;
1458 if (s->data)
1460 /* String was not on free-list before. */
1461 if (STRING_MARKED_P (s))
1463 /* String is live; unmark it and its intervals. */
1464 UNMARK_STRING (s);
1466 if (!NULL_INTERVAL_P (s->intervals))
1467 UNMARK_BALANCE_INTERVALS (s->intervals);
1469 ++total_strings;
1470 total_string_size += STRING_BYTES (s);
1472 else
1474 /* String is dead. Put it on the free-list. */
1475 struct sdata *data = SDATA_OF_STRING (s);
1477 /* Save the size of S in its sdata so that we know
1478 how large that is. Reset the sdata's string
1479 back-pointer so that we know it's free. */
1480 #ifdef GC_CHECK_STRING_BYTES
1481 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
1482 abort ();
1483 #else
1484 data->u.nbytes = GC_STRING_BYTES (s);
1485 #endif
1486 data->string = NULL;
1488 /* Reset the strings's `data' member so that we
1489 know it's free. */
1490 s->data = NULL;
1492 /* Put the string on the free-list. */
1493 NEXT_FREE_LISP_STRING (s) = string_free_list;
1494 string_free_list = s;
1495 ++nfree;
1498 else
1500 /* S was on the free-list before. Put it there again. */
1501 NEXT_FREE_LISP_STRING (s) = string_free_list;
1502 string_free_list = s;
1503 ++nfree;
1507 /* Free blocks that contain free Lisp_Strings only, except
1508 the first two of them. */
1509 if (nfree == STRINGS_IN_STRING_BLOCK
1510 && total_free_strings > STRINGS_IN_STRING_BLOCK)
1512 lisp_free (b);
1513 --n_string_blocks;
1514 string_free_list = free_list_before;
1516 else
1518 total_free_strings += nfree;
1519 b->next = live_blocks;
1520 live_blocks = b;
1524 string_blocks = live_blocks;
1525 free_large_strings ();
1526 compact_small_strings ();
1530 /* Free dead large strings. */
1532 static void
1533 free_large_strings ()
1535 struct sblock *b, *next;
1536 struct sblock *live_blocks = NULL;
1538 for (b = large_sblocks; b; b = next)
1540 next = b->next;
1542 if (b->first_data.string == NULL)
1543 lisp_free (b);
1544 else
1546 b->next = live_blocks;
1547 live_blocks = b;
1551 large_sblocks = live_blocks;
1555 /* Compact data of small strings. Free sblocks that don't contain
1556 data of live strings after compaction. */
1558 static void
1559 compact_small_strings ()
1561 struct sblock *b, *tb, *next;
1562 struct sdata *from, *to, *end, *tb_end;
1563 struct sdata *to_end, *from_end;
1565 /* TB is the sblock we copy to, TO is the sdata within TB we copy
1566 to, and TB_END is the end of TB. */
1567 tb = oldest_sblock;
1568 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1569 to = &tb->first_data;
1571 /* Step through the blocks from the oldest to the youngest. We
1572 expect that old blocks will stabilize over time, so that less
1573 copying will happen this way. */
1574 for (b = oldest_sblock; b; b = b->next)
1576 end = b->next_free;
1577 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
1579 for (from = &b->first_data; from < end; from = from_end)
1581 /* Compute the next FROM here because copying below may
1582 overwrite data we need to compute it. */
1583 int nbytes;
1585 #ifdef GC_CHECK_STRING_BYTES
1586 /* Check that the string size recorded in the string is the
1587 same as the one recorded in the sdata structure. */
1588 if (from->string
1589 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
1590 abort ();
1591 #endif /* GC_CHECK_STRING_BYTES */
1593 if (from->string)
1594 nbytes = GC_STRING_BYTES (from->string);
1595 else
1596 nbytes = SDATA_NBYTES (from);
1598 nbytes = SDATA_SIZE (nbytes);
1599 from_end = (struct sdata *) ((char *) from + nbytes);
1601 /* FROM->string non-null means it's alive. Copy its data. */
1602 if (from->string)
1604 /* If TB is full, proceed with the next sblock. */
1605 to_end = (struct sdata *) ((char *) to + nbytes);
1606 if (to_end > tb_end)
1608 tb->next_free = to;
1609 tb = tb->next;
1610 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1611 to = &tb->first_data;
1612 to_end = (struct sdata *) ((char *) to + nbytes);
1615 /* Copy, and update the string's `data' pointer. */
1616 if (from != to)
1618 xassert (tb != b || to <= from);
1619 safe_bcopy ((char *) from, (char *) to, nbytes);
1620 to->string->data = SDATA_DATA (to);
1623 /* Advance past the sdata we copied to. */
1624 to = to_end;
1629 /* The rest of the sblocks following TB don't contain live data, so
1630 we can free them. */
1631 for (b = tb->next; b; b = next)
1633 next = b->next;
1634 lisp_free (b);
1637 tb->next_free = to;
1638 tb->next = NULL;
1639 current_sblock = tb;
1643 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
1644 "Return a newly created string of length LENGTH, with each element being INIT.\n\
1645 Both LENGTH and INIT must be numbers.")
1646 (length, init)
1647 Lisp_Object length, init;
1649 register Lisp_Object val;
1650 register unsigned char *p, *end;
1651 int c, nbytes;
1653 CHECK_NATNUM (length, 0);
1654 CHECK_NUMBER (init, 1);
1656 c = XINT (init);
1657 if (SINGLE_BYTE_CHAR_P (c))
1659 nbytes = XINT (length);
1660 val = make_uninit_string (nbytes);
1661 p = XSTRING (val)->data;
1662 end = p + XSTRING (val)->size;
1663 while (p != end)
1664 *p++ = c;
1666 else
1668 unsigned char str[MAX_MULTIBYTE_LENGTH];
1669 int len = CHAR_STRING (c, str);
1671 nbytes = len * XINT (length);
1672 val = make_uninit_multibyte_string (XINT (length), nbytes);
1673 p = XSTRING (val)->data;
1674 end = p + nbytes;
1675 while (p != end)
1677 bcopy (str, p, len);
1678 p += len;
1682 *p = 0;
1683 return val;
1687 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
1688 "Return a new bool-vector of length LENGTH, using INIT for as each element.\n\
1689 LENGTH must be a number. INIT matters only in whether it is t or nil.")
1690 (length, init)
1691 Lisp_Object length, init;
1693 register Lisp_Object val;
1694 struct Lisp_Bool_Vector *p;
1695 int real_init, i;
1696 int length_in_chars, length_in_elts, bits_per_value;
1698 CHECK_NATNUM (length, 0);
1700 bits_per_value = sizeof (EMACS_INT) * BITS_PER_CHAR;
1702 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
1703 length_in_chars = ((XFASTINT (length) + BITS_PER_CHAR - 1) / BITS_PER_CHAR);
1705 /* We must allocate one more elements than LENGTH_IN_ELTS for the
1706 slot `size' of the struct Lisp_Bool_Vector. */
1707 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
1708 p = XBOOL_VECTOR (val);
1710 /* Get rid of any bits that would cause confusion. */
1711 p->vector_size = 0;
1712 XSETBOOL_VECTOR (val, p);
1713 p->size = XFASTINT (length);
1715 real_init = (NILP (init) ? 0 : -1);
1716 for (i = 0; i < length_in_chars ; i++)
1717 p->data[i] = real_init;
1719 /* Clear the extraneous bits in the last byte. */
1720 if (XINT (length) != length_in_chars * BITS_PER_CHAR)
1721 XBOOL_VECTOR (val)->data[length_in_chars - 1]
1722 &= (1 << (XINT (length) % BITS_PER_CHAR)) - 1;
1724 return val;
1728 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
1729 of characters from the contents. This string may be unibyte or
1730 multibyte, depending on the contents. */
1732 Lisp_Object
1733 make_string (contents, nbytes)
1734 char *contents;
1735 int nbytes;
1737 register Lisp_Object val;
1738 int nchars, multibyte_nbytes;
1740 parse_str_as_multibyte (contents, nbytes, &nchars, &multibyte_nbytes);
1741 if (nbytes == nchars || nbytes != multibyte_nbytes)
1742 /* CONTENTS contains no multibyte sequences or contains an invalid
1743 multibyte sequence. We must make unibyte string. */
1744 val = make_unibyte_string (contents, nbytes);
1745 else
1746 val = make_multibyte_string (contents, nchars, nbytes);
1747 return val;
1751 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
1753 Lisp_Object
1754 make_unibyte_string (contents, length)
1755 char *contents;
1756 int length;
1758 register Lisp_Object val;
1759 val = make_uninit_string (length);
1760 bcopy (contents, XSTRING (val)->data, length);
1761 SET_STRING_BYTES (XSTRING (val), -1);
1762 return val;
1766 /* Make a multibyte string from NCHARS characters occupying NBYTES
1767 bytes at CONTENTS. */
1769 Lisp_Object
1770 make_multibyte_string (contents, nchars, nbytes)
1771 char *contents;
1772 int nchars, nbytes;
1774 register Lisp_Object val;
1775 val = make_uninit_multibyte_string (nchars, nbytes);
1776 bcopy (contents, XSTRING (val)->data, nbytes);
1777 return val;
1781 /* Make a string from NCHARS characters occupying NBYTES bytes at
1782 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
1784 Lisp_Object
1785 make_string_from_bytes (contents, nchars, nbytes)
1786 char *contents;
1787 int nchars, nbytes;
1789 register Lisp_Object val;
1790 val = make_uninit_multibyte_string (nchars, nbytes);
1791 bcopy (contents, XSTRING (val)->data, nbytes);
1792 if (STRING_BYTES (XSTRING (val)) == XSTRING (val)->size)
1793 SET_STRING_BYTES (XSTRING (val), -1);
1794 return val;
1798 /* Make a string from NCHARS characters occupying NBYTES bytes at
1799 CONTENTS. The argument MULTIBYTE controls whether to label the
1800 string as multibyte. */
1802 Lisp_Object
1803 make_specified_string (contents, nchars, nbytes, multibyte)
1804 char *contents;
1805 int nchars, nbytes;
1806 int multibyte;
1808 register Lisp_Object val;
1809 val = make_uninit_multibyte_string (nchars, nbytes);
1810 bcopy (contents, XSTRING (val)->data, nbytes);
1811 if (!multibyte)
1812 SET_STRING_BYTES (XSTRING (val), -1);
1813 return val;
1817 /* Make a string from the data at STR, treating it as multibyte if the
1818 data warrants. */
1820 Lisp_Object
1821 build_string (str)
1822 char *str;
1824 return make_string (str, strlen (str));
1828 /* Return an unibyte Lisp_String set up to hold LENGTH characters
1829 occupying LENGTH bytes. */
1831 Lisp_Object
1832 make_uninit_string (length)
1833 int length;
1835 Lisp_Object val;
1836 val = make_uninit_multibyte_string (length, length);
1837 SET_STRING_BYTES (XSTRING (val), -1);
1838 return val;
1842 /* Return a multibyte Lisp_String set up to hold NCHARS characters
1843 which occupy NBYTES bytes. */
1845 Lisp_Object
1846 make_uninit_multibyte_string (nchars, nbytes)
1847 int nchars, nbytes;
1849 Lisp_Object string;
1850 struct Lisp_String *s;
1852 if (nchars < 0)
1853 abort ();
1855 s = allocate_string ();
1856 allocate_string_data (s, nchars, nbytes);
1857 XSETSTRING (string, s);
1858 string_chars_consed += nbytes;
1859 return string;
1864 /***********************************************************************
1865 Float Allocation
1866 ***********************************************************************/
1868 /* We store float cells inside of float_blocks, allocating a new
1869 float_block with malloc whenever necessary. Float cells reclaimed
1870 by GC are put on a free list to be reallocated before allocating
1871 any new float cells from the latest float_block.
1873 Each float_block is just under 1020 bytes long, since malloc really
1874 allocates in units of powers of two and uses 4 bytes for its own
1875 overhead. */
1877 #define FLOAT_BLOCK_SIZE \
1878 ((1020 - sizeof (struct float_block *)) / sizeof (struct Lisp_Float))
1880 struct float_block
1882 struct float_block *next;
1883 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
1886 /* Current float_block. */
1888 struct float_block *float_block;
1890 /* Index of first unused Lisp_Float in the current float_block. */
1892 int float_block_index;
1894 /* Total number of float blocks now in use. */
1896 int n_float_blocks;
1898 /* Free-list of Lisp_Floats. */
1900 struct Lisp_Float *float_free_list;
1903 /* Initialze float allocation. */
1905 void
1906 init_float ()
1908 float_block = (struct float_block *) lisp_malloc (sizeof *float_block,
1909 MEM_TYPE_FLOAT);
1910 float_block->next = 0;
1911 bzero ((char *) float_block->floats, sizeof float_block->floats);
1912 float_block_index = 0;
1913 float_free_list = 0;
1914 n_float_blocks = 1;
1918 /* Explicitly free a float cell by putting it on the free-list. */
1920 void
1921 free_float (ptr)
1922 struct Lisp_Float *ptr;
1924 *(struct Lisp_Float **)&ptr->data = float_free_list;
1925 #if GC_MARK_STACK
1926 ptr->type = Vdead;
1927 #endif
1928 float_free_list = ptr;
1932 /* Return a new float object with value FLOAT_VALUE. */
1934 Lisp_Object
1935 make_float (float_value)
1936 double float_value;
1938 register Lisp_Object val;
1940 if (float_free_list)
1942 /* We use the data field for chaining the free list
1943 so that we won't use the same field that has the mark bit. */
1944 XSETFLOAT (val, float_free_list);
1945 float_free_list = *(struct Lisp_Float **)&float_free_list->data;
1947 else
1949 if (float_block_index == FLOAT_BLOCK_SIZE)
1951 register struct float_block *new;
1953 new = (struct float_block *) lisp_malloc (sizeof *new,
1954 MEM_TYPE_FLOAT);
1955 VALIDATE_LISP_STORAGE (new, sizeof *new);
1956 new->next = float_block;
1957 float_block = new;
1958 float_block_index = 0;
1959 n_float_blocks++;
1961 XSETFLOAT (val, &float_block->floats[float_block_index++]);
1964 XFLOAT_DATA (val) = float_value;
1965 XSETFASTINT (XFLOAT (val)->type, 0); /* bug chasing -wsr */
1966 consing_since_gc += sizeof (struct Lisp_Float);
1967 floats_consed++;
1968 return val;
1973 /***********************************************************************
1974 Cons Allocation
1975 ***********************************************************************/
1977 /* We store cons cells inside of cons_blocks, allocating a new
1978 cons_block with malloc whenever necessary. Cons cells reclaimed by
1979 GC are put on a free list to be reallocated before allocating
1980 any new cons cells from the latest cons_block.
1982 Each cons_block is just under 1020 bytes long,
1983 since malloc really allocates in units of powers of two
1984 and uses 4 bytes for its own overhead. */
1986 #define CONS_BLOCK_SIZE \
1987 ((1020 - sizeof (struct cons_block *)) / sizeof (struct Lisp_Cons))
1989 struct cons_block
1991 struct cons_block *next;
1992 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
1995 /* Current cons_block. */
1997 struct cons_block *cons_block;
1999 /* Index of first unused Lisp_Cons in the current block. */
2001 int cons_block_index;
2003 /* Free-list of Lisp_Cons structures. */
2005 struct Lisp_Cons *cons_free_list;
2007 /* Total number of cons blocks now in use. */
2009 int n_cons_blocks;
2012 /* Initialize cons allocation. */
2014 void
2015 init_cons ()
2017 cons_block = (struct cons_block *) lisp_malloc (sizeof *cons_block,
2018 MEM_TYPE_CONS);
2019 cons_block->next = 0;
2020 bzero ((char *) cons_block->conses, sizeof cons_block->conses);
2021 cons_block_index = 0;
2022 cons_free_list = 0;
2023 n_cons_blocks = 1;
2027 /* Explicitly free a cons cell by putting it on the free-list. */
2029 void
2030 free_cons (ptr)
2031 struct Lisp_Cons *ptr;
2033 *(struct Lisp_Cons **)&ptr->cdr = cons_free_list;
2034 #if GC_MARK_STACK
2035 ptr->car = Vdead;
2036 #endif
2037 cons_free_list = ptr;
2041 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2042 "Create a new cons, give it CAR and CDR as components, and return it.")
2043 (car, cdr)
2044 Lisp_Object car, cdr;
2046 register Lisp_Object val;
2048 if (cons_free_list)
2050 /* We use the cdr for chaining the free list
2051 so that we won't use the same field that has the mark bit. */
2052 XSETCONS (val, cons_free_list);
2053 cons_free_list = *(struct Lisp_Cons **)&cons_free_list->cdr;
2055 else
2057 if (cons_block_index == CONS_BLOCK_SIZE)
2059 register struct cons_block *new;
2060 new = (struct cons_block *) lisp_malloc (sizeof *new,
2061 MEM_TYPE_CONS);
2062 VALIDATE_LISP_STORAGE (new, sizeof *new);
2063 new->next = cons_block;
2064 cons_block = new;
2065 cons_block_index = 0;
2066 n_cons_blocks++;
2068 XSETCONS (val, &cons_block->conses[cons_block_index++]);
2071 XCAR (val) = car;
2072 XCDR (val) = cdr;
2073 consing_since_gc += sizeof (struct Lisp_Cons);
2074 cons_cells_consed++;
2075 return val;
2079 /* Make a list of 2, 3, 4 or 5 specified objects. */
2081 Lisp_Object
2082 list2 (arg1, arg2)
2083 Lisp_Object arg1, arg2;
2085 return Fcons (arg1, Fcons (arg2, Qnil));
2089 Lisp_Object
2090 list3 (arg1, arg2, arg3)
2091 Lisp_Object arg1, arg2, arg3;
2093 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2097 Lisp_Object
2098 list4 (arg1, arg2, arg3, arg4)
2099 Lisp_Object arg1, arg2, arg3, arg4;
2101 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2105 Lisp_Object
2106 list5 (arg1, arg2, arg3, arg4, arg5)
2107 Lisp_Object arg1, arg2, arg3, arg4, arg5;
2109 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2110 Fcons (arg5, Qnil)))));
2114 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2115 "Return a newly created list with specified arguments as elements.\n\
2116 Any number of arguments, even zero arguments, are allowed.")
2117 (nargs, args)
2118 int nargs;
2119 register Lisp_Object *args;
2121 register Lisp_Object val;
2122 val = Qnil;
2124 while (nargs > 0)
2126 nargs--;
2127 val = Fcons (args[nargs], val);
2129 return val;
2133 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2134 "Return a newly created list of length LENGTH, with each element being INIT.")
2135 (length, init)
2136 register Lisp_Object length, init;
2138 register Lisp_Object val;
2139 register int size;
2141 CHECK_NATNUM (length, 0);
2142 size = XFASTINT (length);
2144 val = Qnil;
2145 while (size > 0)
2147 val = Fcons (init, val);
2148 --size;
2150 if (size > 0)
2152 val = Fcons (init, val);
2153 --size;
2155 if (size > 0)
2157 val = Fcons (init, val);
2158 --size;
2160 if (size > 0)
2162 val = Fcons (init, val);
2163 --size;
2165 if (size > 0)
2167 val = Fcons (init, val);
2168 --size;
2174 QUIT;
2177 return val;
2182 /***********************************************************************
2183 Vector Allocation
2184 ***********************************************************************/
2186 /* Singly-linked list of all vectors. */
2188 struct Lisp_Vector *all_vectors;
2190 /* Total number of vector-like objects now in use. */
2192 int n_vectors;
2195 /* Value is a pointer to a newly allocated Lisp_Vector structure
2196 with room for LEN Lisp_Objects. */
2198 struct Lisp_Vector *
2199 allocate_vectorlike (len)
2200 EMACS_INT len;
2202 struct Lisp_Vector *p;
2203 size_t nbytes;
2205 #ifdef DOUG_LEA_MALLOC
2206 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2207 because mapped region contents are not preserved in
2208 a dumped Emacs. */
2209 mallopt (M_MMAP_MAX, 0);
2210 #endif
2212 nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
2213 p = (struct Lisp_Vector *) lisp_malloc (nbytes, MEM_TYPE_VECTOR);
2215 #ifdef DOUG_LEA_MALLOC
2216 /* Back to a reasonable maximum of mmap'ed areas. */
2217 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2218 #endif
2220 VALIDATE_LISP_STORAGE (p, 0);
2221 consing_since_gc += nbytes;
2222 vector_cells_consed += len;
2224 p->next = all_vectors;
2225 all_vectors = p;
2226 ++n_vectors;
2227 return p;
2231 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
2232 "Return a newly created vector of length LENGTH, with each element being INIT.\n\
2233 See also the function `vector'.")
2234 (length, init)
2235 register Lisp_Object length, init;
2237 Lisp_Object vector;
2238 register EMACS_INT sizei;
2239 register int index;
2240 register struct Lisp_Vector *p;
2242 CHECK_NATNUM (length, 0);
2243 sizei = XFASTINT (length);
2245 p = allocate_vectorlike (sizei);
2246 p->size = sizei;
2247 for (index = 0; index < sizei; index++)
2248 p->contents[index] = init;
2250 XSETVECTOR (vector, p);
2251 return vector;
2255 DEFUN ("make-char-table", Fmake_char_table, Smake_char_table, 1, 2, 0,
2256 "Return a newly created char-table, with purpose PURPOSE.\n\
2257 Each element is initialized to INIT, which defaults to nil.\n\
2258 PURPOSE should be a symbol which has a `char-table-extra-slots' property.\n\
2259 The property's value should be an integer between 0 and 10.")
2260 (purpose, init)
2261 register Lisp_Object purpose, init;
2263 Lisp_Object vector;
2264 Lisp_Object n;
2265 CHECK_SYMBOL (purpose, 1);
2266 n = Fget (purpose, Qchar_table_extra_slots);
2267 CHECK_NUMBER (n, 0);
2268 if (XINT (n) < 0 || XINT (n) > 10)
2269 args_out_of_range (n, Qnil);
2270 /* Add 2 to the size for the defalt and parent slots. */
2271 vector = Fmake_vector (make_number (CHAR_TABLE_STANDARD_SLOTS + XINT (n)),
2272 init);
2273 XCHAR_TABLE (vector)->top = Qt;
2274 XCHAR_TABLE (vector)->parent = Qnil;
2275 XCHAR_TABLE (vector)->purpose = purpose;
2276 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
2277 return vector;
2281 /* Return a newly created sub char table with default value DEFALT.
2282 Since a sub char table does not appear as a top level Emacs Lisp
2283 object, we don't need a Lisp interface to make it. */
2285 Lisp_Object
2286 make_sub_char_table (defalt)
2287 Lisp_Object defalt;
2289 Lisp_Object vector
2290 = Fmake_vector (make_number (SUB_CHAR_TABLE_STANDARD_SLOTS), Qnil);
2291 XCHAR_TABLE (vector)->top = Qnil;
2292 XCHAR_TABLE (vector)->defalt = defalt;
2293 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
2294 return vector;
2298 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
2299 "Return a newly created vector with specified arguments as elements.\n\
2300 Any number of arguments, even zero arguments, are allowed.")
2301 (nargs, args)
2302 register int nargs;
2303 Lisp_Object *args;
2305 register Lisp_Object len, val;
2306 register int index;
2307 register struct Lisp_Vector *p;
2309 XSETFASTINT (len, nargs);
2310 val = Fmake_vector (len, Qnil);
2311 p = XVECTOR (val);
2312 for (index = 0; index < nargs; index++)
2313 p->contents[index] = args[index];
2314 return val;
2318 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
2319 "Create a byte-code object with specified arguments as elements.\n\
2320 The arguments should be the arglist, bytecode-string, constant vector,\n\
2321 stack size, (optional) doc string, and (optional) interactive spec.\n\
2322 The first four arguments are required; at most six have any\n\
2323 significance.")
2324 (nargs, args)
2325 register int nargs;
2326 Lisp_Object *args;
2328 register Lisp_Object len, val;
2329 register int index;
2330 register struct Lisp_Vector *p;
2332 XSETFASTINT (len, nargs);
2333 if (!NILP (Vpurify_flag))
2334 val = make_pure_vector ((EMACS_INT) nargs);
2335 else
2336 val = Fmake_vector (len, Qnil);
2338 if (STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
2339 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
2340 earlier because they produced a raw 8-bit string for byte-code
2341 and now such a byte-code string is loaded as multibyte while
2342 raw 8-bit characters converted to multibyte form. Thus, now we
2343 must convert them back to the original unibyte form. */
2344 args[1] = Fstring_as_unibyte (args[1]);
2346 p = XVECTOR (val);
2347 for (index = 0; index < nargs; index++)
2349 if (!NILP (Vpurify_flag))
2350 args[index] = Fpurecopy (args[index]);
2351 p->contents[index] = args[index];
2353 XSETCOMPILED (val, p);
2354 return val;
2359 /***********************************************************************
2360 Symbol Allocation
2361 ***********************************************************************/
2363 /* Each symbol_block is just under 1020 bytes long, since malloc
2364 really allocates in units of powers of two and uses 4 bytes for its
2365 own overhead. */
2367 #define SYMBOL_BLOCK_SIZE \
2368 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
2370 struct symbol_block
2372 struct symbol_block *next;
2373 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
2376 /* Current symbol block and index of first unused Lisp_Symbol
2377 structure in it. */
2379 struct symbol_block *symbol_block;
2380 int symbol_block_index;
2382 /* List of free symbols. */
2384 struct Lisp_Symbol *symbol_free_list;
2386 /* Total number of symbol blocks now in use. */
2388 int n_symbol_blocks;
2391 /* Initialize symbol allocation. */
2393 void
2394 init_symbol ()
2396 symbol_block = (struct symbol_block *) lisp_malloc (sizeof *symbol_block,
2397 MEM_TYPE_SYMBOL);
2398 symbol_block->next = 0;
2399 bzero ((char *) symbol_block->symbols, sizeof symbol_block->symbols);
2400 symbol_block_index = 0;
2401 symbol_free_list = 0;
2402 n_symbol_blocks = 1;
2406 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
2407 "Return a newly allocated uninterned symbol whose name is NAME.\n\
2408 Its value and function definition are void, and its property list is nil.")
2409 (name)
2410 Lisp_Object name;
2412 register Lisp_Object val;
2413 register struct Lisp_Symbol *p;
2415 CHECK_STRING (name, 0);
2417 if (symbol_free_list)
2419 XSETSYMBOL (val, symbol_free_list);
2420 symbol_free_list = *(struct Lisp_Symbol **)&symbol_free_list->value;
2422 else
2424 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
2426 struct symbol_block *new;
2427 new = (struct symbol_block *) lisp_malloc (sizeof *new,
2428 MEM_TYPE_SYMBOL);
2429 VALIDATE_LISP_STORAGE (new, sizeof *new);
2430 new->next = symbol_block;
2431 symbol_block = new;
2432 symbol_block_index = 0;
2433 n_symbol_blocks++;
2435 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index++]);
2438 p = XSYMBOL (val);
2439 p->name = XSTRING (name);
2440 p->obarray = Qnil;
2441 p->plist = Qnil;
2442 p->value = Qunbound;
2443 p->function = Qunbound;
2444 p->next = 0;
2445 consing_since_gc += sizeof (struct Lisp_Symbol);
2446 symbols_consed++;
2447 return val;
2452 /***********************************************************************
2453 Marker (Misc) Allocation
2454 ***********************************************************************/
2456 /* Allocation of markers and other objects that share that structure.
2457 Works like allocation of conses. */
2459 #define MARKER_BLOCK_SIZE \
2460 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
2462 struct marker_block
2464 struct marker_block *next;
2465 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
2468 struct marker_block *marker_block;
2469 int marker_block_index;
2471 union Lisp_Misc *marker_free_list;
2473 /* Total number of marker blocks now in use. */
2475 int n_marker_blocks;
2477 void
2478 init_marker ()
2480 marker_block = (struct marker_block *) lisp_malloc (sizeof *marker_block,
2481 MEM_TYPE_MISC);
2482 marker_block->next = 0;
2483 bzero ((char *) marker_block->markers, sizeof marker_block->markers);
2484 marker_block_index = 0;
2485 marker_free_list = 0;
2486 n_marker_blocks = 1;
2489 /* Return a newly allocated Lisp_Misc object, with no substructure. */
2491 Lisp_Object
2492 allocate_misc ()
2494 Lisp_Object val;
2496 if (marker_free_list)
2498 XSETMISC (val, marker_free_list);
2499 marker_free_list = marker_free_list->u_free.chain;
2501 else
2503 if (marker_block_index == MARKER_BLOCK_SIZE)
2505 struct marker_block *new;
2506 new = (struct marker_block *) lisp_malloc (sizeof *new,
2507 MEM_TYPE_MISC);
2508 VALIDATE_LISP_STORAGE (new, sizeof *new);
2509 new->next = marker_block;
2510 marker_block = new;
2511 marker_block_index = 0;
2512 n_marker_blocks++;
2514 XSETMISC (val, &marker_block->markers[marker_block_index++]);
2517 consing_since_gc += sizeof (union Lisp_Misc);
2518 misc_objects_consed++;
2519 return val;
2522 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
2523 "Return a newly allocated marker which does not point at any place.")
2526 register Lisp_Object val;
2527 register struct Lisp_Marker *p;
2529 val = allocate_misc ();
2530 XMISCTYPE (val) = Lisp_Misc_Marker;
2531 p = XMARKER (val);
2532 p->buffer = 0;
2533 p->bytepos = 0;
2534 p->charpos = 0;
2535 p->chain = Qnil;
2536 p->insertion_type = 0;
2537 return val;
2540 /* Put MARKER back on the free list after using it temporarily. */
2542 void
2543 free_marker (marker)
2544 Lisp_Object marker;
2546 unchain_marker (marker);
2548 XMISC (marker)->u_marker.type = Lisp_Misc_Free;
2549 XMISC (marker)->u_free.chain = marker_free_list;
2550 marker_free_list = XMISC (marker);
2552 total_free_markers++;
2556 /* Return a newly created vector or string with specified arguments as
2557 elements. If all the arguments are characters that can fit
2558 in a string of events, make a string; otherwise, make a vector.
2560 Any number of arguments, even zero arguments, are allowed. */
2562 Lisp_Object
2563 make_event_array (nargs, args)
2564 register int nargs;
2565 Lisp_Object *args;
2567 int i;
2569 for (i = 0; i < nargs; i++)
2570 /* The things that fit in a string
2571 are characters that are in 0...127,
2572 after discarding the meta bit and all the bits above it. */
2573 if (!INTEGERP (args[i])
2574 || (XUINT (args[i]) & ~(-CHAR_META)) >= 0200)
2575 return Fvector (nargs, args);
2577 /* Since the loop exited, we know that all the things in it are
2578 characters, so we can make a string. */
2580 Lisp_Object result;
2582 result = Fmake_string (make_number (nargs), make_number (0));
2583 for (i = 0; i < nargs; i++)
2585 XSTRING (result)->data[i] = XINT (args[i]);
2586 /* Move the meta bit to the right place for a string char. */
2587 if (XINT (args[i]) & CHAR_META)
2588 XSTRING (result)->data[i] |= 0x80;
2591 return result;
2597 /************************************************************************
2598 C Stack Marking
2599 ************************************************************************/
2601 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
2603 /* Initialize this part of alloc.c. */
2605 static void
2606 mem_init ()
2608 mem_z.left = mem_z.right = MEM_NIL;
2609 mem_z.parent = NULL;
2610 mem_z.color = MEM_BLACK;
2611 mem_z.start = mem_z.end = NULL;
2612 mem_root = MEM_NIL;
2616 /* Value is a pointer to the mem_node containing START. Value is
2617 MEM_NIL if there is no node in the tree containing START. */
2619 static INLINE struct mem_node *
2620 mem_find (start)
2621 void *start;
2623 struct mem_node *p;
2625 /* Make the search always successful to speed up the loop below. */
2626 mem_z.start = start;
2627 mem_z.end = (char *) start + 1;
2629 p = mem_root;
2630 while (start < p->start || start >= p->end)
2631 p = start < p->start ? p->left : p->right;
2632 return p;
2636 /* Insert a new node into the tree for a block of memory with start
2637 address START, end address END, and type TYPE. Value is a
2638 pointer to the node that was inserted. */
2640 static struct mem_node *
2641 mem_insert (start, end, type)
2642 void *start, *end;
2643 enum mem_type type;
2645 struct mem_node *c, *parent, *x;
2647 /* See where in the tree a node for START belongs. In this
2648 particular application, it shouldn't happen that a node is already
2649 present. For debugging purposes, let's check that. */
2650 c = mem_root;
2651 parent = NULL;
2653 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
2655 while (c != MEM_NIL)
2657 if (start >= c->start && start < c->end)
2658 abort ();
2659 parent = c;
2660 c = start < c->start ? c->left : c->right;
2663 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2665 while (c != MEM_NIL)
2667 parent = c;
2668 c = start < c->start ? c->left : c->right;
2671 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2673 /* Create a new node. */
2674 #ifdef GC_MALLOC_CHECK
2675 x = (struct mem_node *) _malloc_internal (sizeof *x);
2676 if (x == NULL)
2677 abort ();
2678 #else
2679 x = (struct mem_node *) xmalloc (sizeof *x);
2680 #endif
2681 x->start = start;
2682 x->end = end;
2683 x->type = type;
2684 x->parent = parent;
2685 x->left = x->right = MEM_NIL;
2686 x->color = MEM_RED;
2688 /* Insert it as child of PARENT or install it as root. */
2689 if (parent)
2691 if (start < parent->start)
2692 parent->left = x;
2693 else
2694 parent->right = x;
2696 else
2697 mem_root = x;
2699 /* Re-establish red-black tree properties. */
2700 mem_insert_fixup (x);
2702 return x;
2706 /* Re-establish the red-black properties of the tree, and thereby
2707 balance the tree, after node X has been inserted; X is always red. */
2709 static void
2710 mem_insert_fixup (x)
2711 struct mem_node *x;
2713 while (x != mem_root && x->parent->color == MEM_RED)
2715 /* X is red and its parent is red. This is a violation of
2716 red-black tree property #3. */
2718 if (x->parent == x->parent->parent->left)
2720 /* We're on the left side of our grandparent, and Y is our
2721 "uncle". */
2722 struct mem_node *y = x->parent->parent->right;
2724 if (y->color == MEM_RED)
2726 /* Uncle and parent are red but should be black because
2727 X is red. Change the colors accordingly and proceed
2728 with the grandparent. */
2729 x->parent->color = MEM_BLACK;
2730 y->color = MEM_BLACK;
2731 x->parent->parent->color = MEM_RED;
2732 x = x->parent->parent;
2734 else
2736 /* Parent and uncle have different colors; parent is
2737 red, uncle is black. */
2738 if (x == x->parent->right)
2740 x = x->parent;
2741 mem_rotate_left (x);
2744 x->parent->color = MEM_BLACK;
2745 x->parent->parent->color = MEM_RED;
2746 mem_rotate_right (x->parent->parent);
2749 else
2751 /* This is the symmetrical case of above. */
2752 struct mem_node *y = x->parent->parent->left;
2754 if (y->color == MEM_RED)
2756 x->parent->color = MEM_BLACK;
2757 y->color = MEM_BLACK;
2758 x->parent->parent->color = MEM_RED;
2759 x = x->parent->parent;
2761 else
2763 if (x == x->parent->left)
2765 x = x->parent;
2766 mem_rotate_right (x);
2769 x->parent->color = MEM_BLACK;
2770 x->parent->parent->color = MEM_RED;
2771 mem_rotate_left (x->parent->parent);
2776 /* The root may have been changed to red due to the algorithm. Set
2777 it to black so that property #5 is satisfied. */
2778 mem_root->color = MEM_BLACK;
2782 /* (x) (y)
2783 / \ / \
2784 a (y) ===> (x) c
2785 / \ / \
2786 b c a b */
2788 static void
2789 mem_rotate_left (x)
2790 struct mem_node *x;
2792 struct mem_node *y;
2794 /* Turn y's left sub-tree into x's right sub-tree. */
2795 y = x->right;
2796 x->right = y->left;
2797 if (y->left != MEM_NIL)
2798 y->left->parent = x;
2800 /* Y's parent was x's parent. */
2801 if (y != MEM_NIL)
2802 y->parent = x->parent;
2804 /* Get the parent to point to y instead of x. */
2805 if (x->parent)
2807 if (x == x->parent->left)
2808 x->parent->left = y;
2809 else
2810 x->parent->right = y;
2812 else
2813 mem_root = y;
2815 /* Put x on y's left. */
2816 y->left = x;
2817 if (x != MEM_NIL)
2818 x->parent = y;
2822 /* (x) (Y)
2823 / \ / \
2824 (y) c ===> a (x)
2825 / \ / \
2826 a b b c */
2828 static void
2829 mem_rotate_right (x)
2830 struct mem_node *x;
2832 struct mem_node *y = x->left;
2834 x->left = y->right;
2835 if (y->right != MEM_NIL)
2836 y->right->parent = x;
2838 if (y != MEM_NIL)
2839 y->parent = x->parent;
2840 if (x->parent)
2842 if (x == x->parent->right)
2843 x->parent->right = y;
2844 else
2845 x->parent->left = y;
2847 else
2848 mem_root = y;
2850 y->right = x;
2851 if (x != MEM_NIL)
2852 x->parent = y;
2856 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
2858 static void
2859 mem_delete (z)
2860 struct mem_node *z;
2862 struct mem_node *x, *y;
2864 if (!z || z == MEM_NIL)
2865 return;
2867 if (z->left == MEM_NIL || z->right == MEM_NIL)
2868 y = z;
2869 else
2871 y = z->right;
2872 while (y->left != MEM_NIL)
2873 y = y->left;
2876 if (y->left != MEM_NIL)
2877 x = y->left;
2878 else
2879 x = y->right;
2881 x->parent = y->parent;
2882 if (y->parent)
2884 if (y == y->parent->left)
2885 y->parent->left = x;
2886 else
2887 y->parent->right = x;
2889 else
2890 mem_root = x;
2892 if (y != z)
2894 z->start = y->start;
2895 z->end = y->end;
2896 z->type = y->type;
2899 if (y->color == MEM_BLACK)
2900 mem_delete_fixup (x);
2902 #ifdef GC_MALLOC_CHECK
2903 _free_internal (y);
2904 #else
2905 xfree (y);
2906 #endif
2910 /* Re-establish the red-black properties of the tree, after a
2911 deletion. */
2913 static void
2914 mem_delete_fixup (x)
2915 struct mem_node *x;
2917 while (x != mem_root && x->color == MEM_BLACK)
2919 if (x == x->parent->left)
2921 struct mem_node *w = x->parent->right;
2923 if (w->color == MEM_RED)
2925 w->color = MEM_BLACK;
2926 x->parent->color = MEM_RED;
2927 mem_rotate_left (x->parent);
2928 w = x->parent->right;
2931 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
2933 w->color = MEM_RED;
2934 x = x->parent;
2936 else
2938 if (w->right->color == MEM_BLACK)
2940 w->left->color = MEM_BLACK;
2941 w->color = MEM_RED;
2942 mem_rotate_right (w);
2943 w = x->parent->right;
2945 w->color = x->parent->color;
2946 x->parent->color = MEM_BLACK;
2947 w->right->color = MEM_BLACK;
2948 mem_rotate_left (x->parent);
2949 x = mem_root;
2952 else
2954 struct mem_node *w = x->parent->left;
2956 if (w->color == MEM_RED)
2958 w->color = MEM_BLACK;
2959 x->parent->color = MEM_RED;
2960 mem_rotate_right (x->parent);
2961 w = x->parent->left;
2964 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
2966 w->color = MEM_RED;
2967 x = x->parent;
2969 else
2971 if (w->left->color == MEM_BLACK)
2973 w->right->color = MEM_BLACK;
2974 w->color = MEM_RED;
2975 mem_rotate_left (w);
2976 w = x->parent->left;
2979 w->color = x->parent->color;
2980 x->parent->color = MEM_BLACK;
2981 w->left->color = MEM_BLACK;
2982 mem_rotate_right (x->parent);
2983 x = mem_root;
2988 x->color = MEM_BLACK;
2992 /* Value is non-zero if P is a pointer to a live Lisp string on
2993 the heap. M is a pointer to the mem_block for P. */
2995 static INLINE int
2996 live_string_p (m, p)
2997 struct mem_node *m;
2998 void *p;
3000 if (m->type == MEM_TYPE_STRING)
3002 struct string_block *b = (struct string_block *) m->start;
3003 int offset = (char *) p - (char *) &b->strings[0];
3005 /* P must point to the start of a Lisp_String structure, and it
3006 must not be on the free-list. */
3007 return (offset % sizeof b->strings[0] == 0
3008 && ((struct Lisp_String *) p)->data != NULL);
3010 else
3011 return 0;
3015 /* Value is non-zero if P is a pointer to a live Lisp cons on
3016 the heap. M is a pointer to the mem_block for P. */
3018 static INLINE int
3019 live_cons_p (m, p)
3020 struct mem_node *m;
3021 void *p;
3023 if (m->type == MEM_TYPE_CONS)
3025 struct cons_block *b = (struct cons_block *) m->start;
3026 int offset = (char *) p - (char *) &b->conses[0];
3028 /* P must point to the start of a Lisp_Cons, not be
3029 one of the unused cells in the current cons block,
3030 and not be on the free-list. */
3031 return (offset % sizeof b->conses[0] == 0
3032 && (b != cons_block
3033 || offset / sizeof b->conses[0] < cons_block_index)
3034 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
3036 else
3037 return 0;
3041 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3042 the heap. M is a pointer to the mem_block for P. */
3044 static INLINE int
3045 live_symbol_p (m, p)
3046 struct mem_node *m;
3047 void *p;
3049 if (m->type == MEM_TYPE_SYMBOL)
3051 struct symbol_block *b = (struct symbol_block *) m->start;
3052 int offset = (char *) p - (char *) &b->symbols[0];
3054 /* P must point to the start of a Lisp_Symbol, not be
3055 one of the unused cells in the current symbol block,
3056 and not be on the free-list. */
3057 return (offset % sizeof b->symbols[0] == 0
3058 && (b != symbol_block
3059 || offset / sizeof b->symbols[0] < symbol_block_index)
3060 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
3062 else
3063 return 0;
3067 /* Value is non-zero if P is a pointer to a live Lisp float on
3068 the heap. M is a pointer to the mem_block for P. */
3070 static INLINE int
3071 live_float_p (m, p)
3072 struct mem_node *m;
3073 void *p;
3075 if (m->type == MEM_TYPE_FLOAT)
3077 struct float_block *b = (struct float_block *) m->start;
3078 int offset = (char *) p - (char *) &b->floats[0];
3080 /* P must point to the start of a Lisp_Float, not be
3081 one of the unused cells in the current float block,
3082 and not be on the free-list. */
3083 return (offset % sizeof b->floats[0] == 0
3084 && (b != float_block
3085 || offset / sizeof b->floats[0] < float_block_index)
3086 && !EQ (((struct Lisp_Float *) p)->type, Vdead));
3088 else
3089 return 0;
3093 /* Value is non-zero if P is a pointer to a live Lisp Misc on
3094 the heap. M is a pointer to the mem_block for P. */
3096 static INLINE int
3097 live_misc_p (m, p)
3098 struct mem_node *m;
3099 void *p;
3101 if (m->type == MEM_TYPE_MISC)
3103 struct marker_block *b = (struct marker_block *) m->start;
3104 int offset = (char *) p - (char *) &b->markers[0];
3106 /* P must point to the start of a Lisp_Misc, not be
3107 one of the unused cells in the current misc block,
3108 and not be on the free-list. */
3109 return (offset % sizeof b->markers[0] == 0
3110 && (b != marker_block
3111 || offset / sizeof b->markers[0] < marker_block_index)
3112 && ((union Lisp_Misc *) p)->u_marker.type != Lisp_Misc_Free);
3114 else
3115 return 0;
3119 /* Value is non-zero if P is a pointer to a live vector-like object.
3120 M is a pointer to the mem_block for P. */
3122 static INLINE int
3123 live_vector_p (m, p)
3124 struct mem_node *m;
3125 void *p;
3127 return m->type == MEM_TYPE_VECTOR && p == m->start;
3131 /* Value is non-zero of P is a pointer to a live buffer. M is a
3132 pointer to the mem_block for P. */
3134 static INLINE int
3135 live_buffer_p (m, p)
3136 struct mem_node *m;
3137 void *p;
3139 /* P must point to the start of the block, and the buffer
3140 must not have been killed. */
3141 return (m->type == MEM_TYPE_BUFFER
3142 && p == m->start
3143 && !NILP (((struct buffer *) p)->name));
3146 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
3148 #if GC_MARK_STACK
3150 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3152 /* Array of objects that are kept alive because the C stack contains
3153 a pattern that looks like a reference to them . */
3155 #define MAX_ZOMBIES 10
3156 static Lisp_Object zombies[MAX_ZOMBIES];
3158 /* Number of zombie objects. */
3160 static int nzombies;
3162 /* Number of garbage collections. */
3164 static int ngcs;
3166 /* Average percentage of zombies per collection. */
3168 static double avg_zombies;
3170 /* Max. number of live and zombie objects. */
3172 static int max_live, max_zombies;
3174 /* Average number of live objects per GC. */
3176 static double avg_live;
3178 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
3179 "Show information about live and zombie objects.")
3182 Lisp_Object args[7];
3183 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d");
3184 args[1] = make_number (ngcs);
3185 args[2] = make_float (avg_live);
3186 args[3] = make_float (avg_zombies);
3187 args[4] = make_float (avg_zombies / avg_live / 100);
3188 args[5] = make_number (max_live);
3189 args[6] = make_number (max_zombies);
3190 return Fmessage (7, args);
3193 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3196 /* Mark OBJ if we can prove it's a Lisp_Object. */
3198 static INLINE void
3199 mark_maybe_object (obj)
3200 Lisp_Object obj;
3202 void *po = (void *) XPNTR (obj);
3203 struct mem_node *m = mem_find (po);
3205 if (m != MEM_NIL)
3207 int mark_p = 0;
3209 switch (XGCTYPE (obj))
3211 case Lisp_String:
3212 mark_p = (live_string_p (m, po)
3213 && !STRING_MARKED_P ((struct Lisp_String *) po));
3214 break;
3216 case Lisp_Cons:
3217 mark_p = (live_cons_p (m, po)
3218 && !XMARKBIT (XCONS (obj)->car));
3219 break;
3221 case Lisp_Symbol:
3222 mark_p = (live_symbol_p (m, po)
3223 && !XMARKBIT (XSYMBOL (obj)->plist));
3224 break;
3226 case Lisp_Float:
3227 mark_p = (live_float_p (m, po)
3228 && !XMARKBIT (XFLOAT (obj)->type));
3229 break;
3231 case Lisp_Vectorlike:
3232 /* Note: can't check GC_BUFFERP before we know it's a
3233 buffer because checking that dereferences the pointer
3234 PO which might point anywhere. */
3235 if (live_vector_p (m, po))
3236 mark_p = (!GC_SUBRP (obj)
3237 && !(XVECTOR (obj)->size & ARRAY_MARK_FLAG));
3238 else if (live_buffer_p (m, po))
3239 mark_p = GC_BUFFERP (obj) && !XMARKBIT (XBUFFER (obj)->name);
3240 break;
3242 case Lisp_Misc:
3243 if (live_misc_p (m, po))
3245 switch (XMISCTYPE (obj))
3247 case Lisp_Misc_Marker:
3248 mark_p = !XMARKBIT (XMARKER (obj)->chain);
3249 break;
3251 case Lisp_Misc_Buffer_Local_Value:
3252 case Lisp_Misc_Some_Buffer_Local_Value:
3253 mark_p = !XMARKBIT (XBUFFER_LOCAL_VALUE (obj)->realvalue);
3254 break;
3256 case Lisp_Misc_Overlay:
3257 mark_p = !XMARKBIT (XOVERLAY (obj)->plist);
3258 break;
3261 break;
3263 case Lisp_Int:
3264 case Lisp_Type_Limit:
3265 break;
3268 if (mark_p)
3270 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3271 if (nzombies < MAX_ZOMBIES)
3272 zombies[nzombies] = *p;
3273 ++nzombies;
3274 #endif
3275 mark_object (&obj);
3280 /* Mark Lisp objects in the address range START..END. */
3282 static void
3283 mark_memory (start, end)
3284 void *start, *end;
3286 Lisp_Object *p;
3288 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3289 nzombies = 0;
3290 #endif
3292 /* Make START the pointer to the start of the memory region,
3293 if it isn't already. */
3294 if (end < start)
3296 void *tem = start;
3297 start = end;
3298 end = tem;
3301 for (p = (Lisp_Object *) start; (void *) p < end; ++p)
3302 mark_maybe_object (*p);
3306 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
3308 static int setjmp_tested_p, longjmps_done;
3310 #define SETJMP_WILL_LIKELY_WORK "\
3312 Emacs garbage collector has been changed to use conservative stack\n\
3313 marking. Emacs has determined that the method it uses to do the\n\
3314 marking will likely work on your system, but this isn't sure.\n\
3316 If you are a system-programmer, or can get the help of a local wizard\n\
3317 who is, please take a look at the function mark_stack in alloc.c, and\n\
3318 verify that the methods used are appropriate for your system.\n\
3320 Please mail the result to <gerd@gnu.org>.\n\
3323 #define SETJMP_WILL_NOT_WORK "\
3325 Emacs garbage collector has been changed to use conservative stack\n\
3326 marking. Emacs has determined that the default method it uses to do the\n\
3327 marking will not work on your system. We will need a system-dependent\n\
3328 solution for your system.\n\
3330 Please take a look at the function mark_stack in alloc.c, and\n\
3331 try to find a way to make it work on your system.\n\
3332 Please mail the result to <gerd@gnu.org>.\n\
3336 /* Perform a quick check if it looks like setjmp saves registers in a
3337 jmp_buf. Print a message to stderr saying so. When this test
3338 succeeds, this is _not_ a proof that setjmp is sufficient for
3339 conservative stack marking. Only the sources or a disassembly
3340 can prove that. */
3342 static void
3343 test_setjmp ()
3345 char buf[10];
3346 register int x;
3347 jmp_buf jbuf;
3348 int result = 0;
3350 /* Arrange for X to be put in a register. */
3351 sprintf (buf, "1");
3352 x = strlen (buf);
3353 x = 2 * x - 1;
3355 setjmp (jbuf);
3356 if (longjmps_done == 1)
3358 /* Came here after the longjmp at the end of the function.
3360 If x == 1, the longjmp has restored the register to its
3361 value before the setjmp, and we can hope that setjmp
3362 saves all such registers in the jmp_buf, although that
3363 isn't sure.
3365 For other values of X, either something really strange is
3366 taking place, or the setjmp just didn't save the register. */
3368 if (x == 1)
3369 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
3370 else
3372 fprintf (stderr, SETJMP_WILL_NOT_WORK);
3373 exit (1);
3377 ++longjmps_done;
3378 x = 2;
3379 if (longjmps_done == 1)
3380 longjmp (jbuf, 1);
3383 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
3386 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
3388 /* Abort if anything GCPRO'd doesn't survive the GC. */
3390 static void
3391 check_gcpros ()
3393 struct gcpro *p;
3394 int i;
3396 for (p = gcprolist; p; p = p->next)
3397 for (i = 0; i < p->nvars; ++i)
3398 if (!survives_gc_p (p->var[i]))
3399 abort ();
3402 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3404 static void
3405 dump_zombies ()
3407 int i;
3409 fprintf (stderr, "\nZombies kept alive = %d:\n", nzombies);
3410 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
3412 fprintf (stderr, " %d = ", i);
3413 debug_print (zombies[i]);
3417 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3420 /* Mark live Lisp objects on the C stack.
3422 There are several system-dependent problems to consider when
3423 porting this to new architectures:
3425 Processor Registers
3427 We have to mark Lisp objects in CPU registers that can hold local
3428 variables or are used to pass parameters.
3430 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
3431 something that either saves relevant registers on the stack, or
3432 calls mark_maybe_object passing it each register's contents.
3434 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
3435 implementation assumes that calling setjmp saves registers we need
3436 to see in a jmp_buf which itself lies on the stack. This doesn't
3437 have to be true! It must be verified for each system, possibly
3438 by taking a look at the source code of setjmp.
3440 Stack Layout
3442 Architectures differ in the way their processor stack is organized.
3443 For example, the stack might look like this
3445 +----------------+
3446 | Lisp_Object | size = 4
3447 +----------------+
3448 | something else | size = 2
3449 +----------------+
3450 | Lisp_Object | size = 4
3451 +----------------+
3452 | ... |
3454 In such a case, not every Lisp_Object will be aligned equally. To
3455 find all Lisp_Object on the stack it won't be sufficient to walk
3456 the stack in steps of 4 bytes. Instead, two passes will be
3457 necessary, one starting at the start of the stack, and a second
3458 pass starting at the start of the stack + 2. Likewise, if the
3459 minimal alignment of Lisp_Objects on the stack is 1, four passes
3460 would be necessary, each one starting with one byte more offset
3461 from the stack start.
3463 The current code assumes by default that Lisp_Objects are aligned
3464 equally on the stack. */
3466 static void
3467 mark_stack ()
3469 jmp_buf j;
3470 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
3471 void *end;
3473 /* This trick flushes the register windows so that all the state of
3474 the process is contained in the stack. */
3475 #ifdef sparc
3476 asm ("ta 3");
3477 #endif
3479 /* Save registers that we need to see on the stack. We need to see
3480 registers used to hold register variables and registers used to
3481 pass parameters. */
3482 #ifdef GC_SAVE_REGISTERS_ON_STACK
3483 GC_SAVE_REGISTERS_ON_STACK (end);
3484 #else /* not GC_SAVE_REGISTERS_ON_STACK */
3486 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
3487 setjmp will definitely work, test it
3488 and print a message with the result
3489 of the test. */
3490 if (!setjmp_tested_p)
3492 setjmp_tested_p = 1;
3493 test_setjmp ();
3495 #endif /* GC_SETJMP_WORKS */
3497 setjmp (j);
3498 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
3499 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
3501 /* This assumes that the stack is a contiguous region in memory. If
3502 that's not the case, something has to be done here to iterate
3503 over the stack segments. */
3504 #if GC_LISP_OBJECT_ALIGNMENT == 1
3505 mark_memory (stack_base, end);
3506 mark_memory ((char *) stack_base + 1, end);
3507 mark_memory ((char *) stack_base + 2, end);
3508 mark_memory ((char *) stack_base + 3, end);
3509 #elif GC_LISP_OBJECT_ALIGNMENT == 2
3510 mark_memory (stack_base, end);
3511 mark_memory ((char *) stack_base + 2, end);
3512 #else
3513 mark_memory (stack_base, end);
3514 #endif
3516 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
3517 check_gcpros ();
3518 #endif
3522 #endif /* GC_MARK_STACK != 0 */
3526 /***********************************************************************
3527 Pure Storage Management
3528 ***********************************************************************/
3530 /* Allocate room for SIZE bytes from pure Lisp storage and return a
3531 pointer to it. TYPE is the Lisp type for which the memory is
3532 allocated. TYPE < 0 means it's not used for a Lisp object.
3534 If store_pure_type_info is set and TYPE is >= 0, the type of
3535 the allocated object is recorded in pure_types. */
3537 static POINTER_TYPE *
3538 pure_alloc (size, type)
3539 size_t size;
3540 int type;
3542 size_t nbytes;
3543 POINTER_TYPE *result;
3544 char *beg = PUREBEG;
3546 /* Give Lisp_Floats an extra alignment. */
3547 if (type == Lisp_Float)
3549 size_t alignment;
3550 #if defined __GNUC__ && __GNUC__ >= 2
3551 alignment = __alignof (struct Lisp_Float);
3552 #else
3553 alignment = sizeof (struct Lisp_Float);
3554 #endif
3555 pure_bytes_used = ALIGN (pure_bytes_used, alignment);
3558 nbytes = ALIGN (size, sizeof (EMACS_INT));
3559 if (pure_bytes_used + nbytes > PURESIZE)
3560 error ("Pure Lisp storage exhausted");
3562 result = (POINTER_TYPE *) (beg + pure_bytes_used);
3563 pure_bytes_used += nbytes;
3564 return result;
3568 /* Return a string allocated in pure space. DATA is a buffer holding
3569 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
3570 non-zero means make the result string multibyte.
3572 Must get an error if pure storage is full, since if it cannot hold
3573 a large string it may be able to hold conses that point to that
3574 string; then the string is not protected from gc. */
3576 Lisp_Object
3577 make_pure_string (data, nchars, nbytes, multibyte)
3578 char *data;
3579 int nchars, nbytes;
3580 int multibyte;
3582 Lisp_Object string;
3583 struct Lisp_String *s;
3585 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
3586 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
3587 s->size = nchars;
3588 s->size_byte = multibyte ? nbytes : -1;
3589 bcopy (data, s->data, nbytes);
3590 s->data[nbytes] = '\0';
3591 s->intervals = NULL_INTERVAL;
3592 XSETSTRING (string, s);
3593 return string;
3597 /* Return a cons allocated from pure space. Give it pure copies
3598 of CAR as car and CDR as cdr. */
3600 Lisp_Object
3601 pure_cons (car, cdr)
3602 Lisp_Object car, cdr;
3604 register Lisp_Object new;
3605 struct Lisp_Cons *p;
3607 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
3608 XSETCONS (new, p);
3609 XCAR (new) = Fpurecopy (car);
3610 XCDR (new) = Fpurecopy (cdr);
3611 return new;
3615 /* Value is a float object with value NUM allocated from pure space. */
3617 Lisp_Object
3618 make_pure_float (num)
3619 double num;
3621 register Lisp_Object new;
3622 struct Lisp_Float *p;
3624 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
3625 XSETFLOAT (new, p);
3626 XFLOAT_DATA (new) = num;
3627 return new;
3631 /* Return a vector with room for LEN Lisp_Objects allocated from
3632 pure space. */
3634 Lisp_Object
3635 make_pure_vector (len)
3636 EMACS_INT len;
3638 Lisp_Object new;
3639 struct Lisp_Vector *p;
3640 size_t size = sizeof *p + (len - 1) * sizeof (Lisp_Object);
3642 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
3643 XSETVECTOR (new, p);
3644 XVECTOR (new)->size = len;
3645 return new;
3649 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
3650 "Make a copy of OBJECT in pure storage.\n\
3651 Recursively copies contents of vectors and cons cells.\n\
3652 Does not copy symbols. Copies strings without text properties.")
3653 (obj)
3654 register Lisp_Object obj;
3656 if (NILP (Vpurify_flag))
3657 return obj;
3659 if (PURE_POINTER_P (XPNTR (obj)))
3660 return obj;
3662 if (CONSP (obj))
3663 return pure_cons (XCAR (obj), XCDR (obj));
3664 else if (FLOATP (obj))
3665 return make_pure_float (XFLOAT_DATA (obj));
3666 else if (STRINGP (obj))
3667 return make_pure_string (XSTRING (obj)->data, XSTRING (obj)->size,
3668 STRING_BYTES (XSTRING (obj)),
3669 STRING_MULTIBYTE (obj));
3670 else if (COMPILEDP (obj) || VECTORP (obj))
3672 register struct Lisp_Vector *vec;
3673 register int i, size;
3675 size = XVECTOR (obj)->size;
3676 if (size & PSEUDOVECTOR_FLAG)
3677 size &= PSEUDOVECTOR_SIZE_MASK;
3678 vec = XVECTOR (make_pure_vector ((EMACS_INT) size));
3679 for (i = 0; i < size; i++)
3680 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
3681 if (COMPILEDP (obj))
3682 XSETCOMPILED (obj, vec);
3683 else
3684 XSETVECTOR (obj, vec);
3685 return obj;
3687 else if (MARKERP (obj))
3688 error ("Attempt to copy a marker to pure storage");
3690 return obj;
3695 /***********************************************************************
3696 Protection from GC
3697 ***********************************************************************/
3699 /* Put an entry in staticvec, pointing at the variable with address
3700 VARADDRESS. */
3702 void
3703 staticpro (varaddress)
3704 Lisp_Object *varaddress;
3706 staticvec[staticidx++] = varaddress;
3707 if (staticidx >= NSTATICS)
3708 abort ();
3711 struct catchtag
3713 Lisp_Object tag;
3714 Lisp_Object val;
3715 struct catchtag *next;
3718 struct backtrace
3720 struct backtrace *next;
3721 Lisp_Object *function;
3722 Lisp_Object *args; /* Points to vector of args. */
3723 int nargs; /* Length of vector. */
3724 /* If nargs is UNEVALLED, args points to slot holding list of
3725 unevalled args. */
3726 char evalargs;
3731 /***********************************************************************
3732 Protection from GC
3733 ***********************************************************************/
3735 /* Temporarily prevent garbage collection. */
3738 inhibit_garbage_collection ()
3740 int count = specpdl_ptr - specpdl;
3741 Lisp_Object number;
3742 int nbits = min (VALBITS, BITS_PER_INT);
3744 XSETINT (number, ((EMACS_INT) 1 << (nbits - 1)) - 1);
3746 specbind (Qgc_cons_threshold, number);
3748 return count;
3752 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
3753 "Reclaim storage for Lisp objects no longer needed.\n\
3754 Returns info on amount of space in use:\n\
3755 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)\n\
3756 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS\n\
3757 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)\n\
3758 (USED-STRINGS . FREE-STRINGS))\n\
3759 Garbage collection happens automatically if you cons more than\n\
3760 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.")
3763 register struct gcpro *tail;
3764 register struct specbinding *bind;
3765 struct catchtag *catch;
3766 struct handler *handler;
3767 register struct backtrace *backlist;
3768 char stack_top_variable;
3769 register int i;
3770 int message_p;
3771 Lisp_Object total[8];
3772 int count = BINDING_STACK_SIZE ();
3774 /* In case user calls debug_print during GC,
3775 don't let that cause a recursive GC. */
3776 consing_since_gc = 0;
3778 /* Save what's currently displayed in the echo area. */
3779 message_p = push_message ();
3780 record_unwind_protect (push_message_unwind, Qnil);
3782 /* Save a copy of the contents of the stack, for debugging. */
3783 #if MAX_SAVE_STACK > 0
3784 if (NILP (Vpurify_flag))
3786 i = &stack_top_variable - stack_bottom;
3787 if (i < 0) i = -i;
3788 if (i < MAX_SAVE_STACK)
3790 if (stack_copy == 0)
3791 stack_copy = (char *) xmalloc (stack_copy_size = i);
3792 else if (stack_copy_size < i)
3793 stack_copy = (char *) xrealloc (stack_copy, (stack_copy_size = i));
3794 if (stack_copy)
3796 if ((EMACS_INT) (&stack_top_variable - stack_bottom) > 0)
3797 bcopy (stack_bottom, stack_copy, i);
3798 else
3799 bcopy (&stack_top_variable, stack_copy, i);
3803 #endif /* MAX_SAVE_STACK > 0 */
3805 if (garbage_collection_messages)
3806 message1_nolog ("Garbage collecting...");
3808 BLOCK_INPUT;
3810 shrink_regexp_cache ();
3812 /* Don't keep undo information around forever. */
3814 register struct buffer *nextb = all_buffers;
3816 while (nextb)
3818 /* If a buffer's undo list is Qt, that means that undo is
3819 turned off in that buffer. Calling truncate_undo_list on
3820 Qt tends to return NULL, which effectively turns undo back on.
3821 So don't call truncate_undo_list if undo_list is Qt. */
3822 if (! EQ (nextb->undo_list, Qt))
3823 nextb->undo_list
3824 = truncate_undo_list (nextb->undo_list, undo_limit,
3825 undo_strong_limit);
3826 nextb = nextb->next;
3830 gc_in_progress = 1;
3832 /* clear_marks (); */
3834 /* Mark all the special slots that serve as the roots of accessibility.
3836 Usually the special slots to mark are contained in particular structures.
3837 Then we know no slot is marked twice because the structures don't overlap.
3838 In some cases, the structures point to the slots to be marked.
3839 For these, we use MARKBIT to avoid double marking of the slot. */
3841 for (i = 0; i < staticidx; i++)
3842 mark_object (staticvec[i]);
3844 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
3845 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
3846 mark_stack ();
3847 #else
3848 for (tail = gcprolist; tail; tail = tail->next)
3849 for (i = 0; i < tail->nvars; i++)
3850 if (!XMARKBIT (tail->var[i]))
3852 /* Explicit casting prevents compiler warning about
3853 discarding the `volatile' qualifier. */
3854 mark_object ((Lisp_Object *)&tail->var[i]);
3855 XMARK (tail->var[i]);
3857 #endif
3859 mark_byte_stack ();
3860 for (bind = specpdl; bind != specpdl_ptr; bind++)
3862 mark_object (&bind->symbol);
3863 mark_object (&bind->old_value);
3865 for (catch = catchlist; catch; catch = catch->next)
3867 mark_object (&catch->tag);
3868 mark_object (&catch->val);
3870 for (handler = handlerlist; handler; handler = handler->next)
3872 mark_object (&handler->handler);
3873 mark_object (&handler->var);
3875 for (backlist = backtrace_list; backlist; backlist = backlist->next)
3877 if (!XMARKBIT (*backlist->function))
3879 mark_object (backlist->function);
3880 XMARK (*backlist->function);
3882 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
3883 i = 0;
3884 else
3885 i = backlist->nargs - 1;
3886 for (; i >= 0; i--)
3887 if (!XMARKBIT (backlist->args[i]))
3889 mark_object (&backlist->args[i]);
3890 XMARK (backlist->args[i]);
3893 mark_kboards ();
3895 /* Look thru every buffer's undo list
3896 for elements that update markers that were not marked,
3897 and delete them. */
3899 register struct buffer *nextb = all_buffers;
3901 while (nextb)
3903 /* If a buffer's undo list is Qt, that means that undo is
3904 turned off in that buffer. Calling truncate_undo_list on
3905 Qt tends to return NULL, which effectively turns undo back on.
3906 So don't call truncate_undo_list if undo_list is Qt. */
3907 if (! EQ (nextb->undo_list, Qt))
3909 Lisp_Object tail, prev;
3910 tail = nextb->undo_list;
3911 prev = Qnil;
3912 while (CONSP (tail))
3914 if (GC_CONSP (XCAR (tail))
3915 && GC_MARKERP (XCAR (XCAR (tail)))
3916 && ! XMARKBIT (XMARKER (XCAR (XCAR (tail)))->chain))
3918 if (NILP (prev))
3919 nextb->undo_list = tail = XCDR (tail);
3920 else
3921 tail = XCDR (prev) = XCDR (tail);
3923 else
3925 prev = tail;
3926 tail = XCDR (tail);
3931 nextb = nextb->next;
3935 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3936 mark_stack ();
3937 #endif
3939 gc_sweep ();
3941 /* Clear the mark bits that we set in certain root slots. */
3943 #if (GC_MARK_STACK == GC_USE_GCPROS_AS_BEFORE \
3944 || GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES)
3945 for (tail = gcprolist; tail; tail = tail->next)
3946 for (i = 0; i < tail->nvars; i++)
3947 XUNMARK (tail->var[i]);
3948 #endif
3950 unmark_byte_stack ();
3951 for (backlist = backtrace_list; backlist; backlist = backlist->next)
3953 XUNMARK (*backlist->function);
3954 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
3955 i = 0;
3956 else
3957 i = backlist->nargs - 1;
3958 for (; i >= 0; i--)
3959 XUNMARK (backlist->args[i]);
3961 XUNMARK (buffer_defaults.name);
3962 XUNMARK (buffer_local_symbols.name);
3964 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
3965 dump_zombies ();
3966 #endif
3968 UNBLOCK_INPUT;
3970 /* clear_marks (); */
3971 gc_in_progress = 0;
3973 consing_since_gc = 0;
3974 if (gc_cons_threshold < 10000)
3975 gc_cons_threshold = 10000;
3977 if (garbage_collection_messages)
3979 if (message_p || minibuf_level > 0)
3980 restore_message ();
3981 else
3982 message1_nolog ("Garbage collecting...done");
3985 unbind_to (count, Qnil);
3987 total[0] = Fcons (make_number (total_conses),
3988 make_number (total_free_conses));
3989 total[1] = Fcons (make_number (total_symbols),
3990 make_number (total_free_symbols));
3991 total[2] = Fcons (make_number (total_markers),
3992 make_number (total_free_markers));
3993 total[3] = make_number (total_string_size);
3994 total[4] = make_number (total_vector_size);
3995 total[5] = Fcons (make_number (total_floats),
3996 make_number (total_free_floats));
3997 total[6] = Fcons (make_number (total_intervals),
3998 make_number (total_free_intervals));
3999 total[7] = Fcons (make_number (total_strings),
4000 make_number (total_free_strings));
4002 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4004 /* Compute average percentage of zombies. */
4005 double nlive = 0;
4007 for (i = 0; i < 7; ++i)
4008 nlive += XFASTINT (XCAR (total[i]));
4010 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
4011 max_live = max (nlive, max_live);
4012 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
4013 max_zombies = max (nzombies, max_zombies);
4014 ++ngcs;
4016 #endif
4018 return Flist (sizeof total / sizeof *total, total);
4022 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
4023 only interesting objects referenced from glyphs are strings. */
4025 static void
4026 mark_glyph_matrix (matrix)
4027 struct glyph_matrix *matrix;
4029 struct glyph_row *row = matrix->rows;
4030 struct glyph_row *end = row + matrix->nrows;
4032 for (; row < end; ++row)
4033 if (row->enabled_p)
4035 int area;
4036 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
4038 struct glyph *glyph = row->glyphs[area];
4039 struct glyph *end_glyph = glyph + row->used[area];
4041 for (; glyph < end_glyph; ++glyph)
4042 if (GC_STRINGP (glyph->object)
4043 && !STRING_MARKED_P (XSTRING (glyph->object)))
4044 mark_object (&glyph->object);
4050 /* Mark Lisp faces in the face cache C. */
4052 static void
4053 mark_face_cache (c)
4054 struct face_cache *c;
4056 if (c)
4058 int i, j;
4059 for (i = 0; i < c->used; ++i)
4061 struct face *face = FACE_FROM_ID (c->f, i);
4063 if (face)
4065 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
4066 mark_object (&face->lface[j]);
4073 #ifdef HAVE_WINDOW_SYSTEM
4075 /* Mark Lisp objects in image IMG. */
4077 static void
4078 mark_image (img)
4079 struct image *img;
4081 mark_object (&img->spec);
4083 if (!NILP (img->data.lisp_val))
4084 mark_object (&img->data.lisp_val);
4088 /* Mark Lisp objects in image cache of frame F. It's done this way so
4089 that we don't have to include xterm.h here. */
4091 static void
4092 mark_image_cache (f)
4093 struct frame *f;
4095 forall_images_in_image_cache (f, mark_image);
4098 #endif /* HAVE_X_WINDOWS */
4102 /* Mark reference to a Lisp_Object.
4103 If the object referred to has not been seen yet, recursively mark
4104 all the references contained in it. */
4106 #define LAST_MARKED_SIZE 500
4107 Lisp_Object *last_marked[LAST_MARKED_SIZE];
4108 int last_marked_index;
4110 void
4111 mark_object (argptr)
4112 Lisp_Object *argptr;
4114 Lisp_Object *objptr = argptr;
4115 register Lisp_Object obj;
4116 #ifdef GC_CHECK_MARKED_OBJECTS
4117 void *po;
4118 struct mem_node *m;
4119 #endif
4121 loop:
4122 obj = *objptr;
4123 loop2:
4124 XUNMARK (obj);
4126 if (PURE_POINTER_P (XPNTR (obj)))
4127 return;
4129 last_marked[last_marked_index++] = objptr;
4130 if (last_marked_index == LAST_MARKED_SIZE)
4131 last_marked_index = 0;
4133 /* Perform some sanity checks on the objects marked here. Abort if
4134 we encounter an object we know is bogus. This increases GC time
4135 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
4136 #ifdef GC_CHECK_MARKED_OBJECTS
4138 po = (void *) XPNTR (obj);
4140 /* Check that the object pointed to by PO is known to be a Lisp
4141 structure allocated from the heap. */
4142 #define CHECK_ALLOCATED() \
4143 do { \
4144 m = mem_find (po); \
4145 if (m == MEM_NIL) \
4146 abort (); \
4147 } while (0)
4149 /* Check that the object pointed to by PO is live, using predicate
4150 function LIVEP. */
4151 #define CHECK_LIVE(LIVEP) \
4152 do { \
4153 if (!LIVEP (m, po)) \
4154 abort (); \
4155 } while (0)
4157 /* Check both of the above conditions. */
4158 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
4159 do { \
4160 CHECK_ALLOCATED (); \
4161 CHECK_LIVE (LIVEP); \
4162 } while (0) \
4164 #else /* not GC_CHECK_MARKED_OBJECTS */
4166 #define CHECK_ALLOCATED() (void) 0
4167 #define CHECK_LIVE(LIVEP) (void) 0
4168 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
4170 #endif /* not GC_CHECK_MARKED_OBJECTS */
4172 switch (SWITCH_ENUM_CAST (XGCTYPE (obj)))
4174 case Lisp_String:
4176 register struct Lisp_String *ptr = XSTRING (obj);
4177 CHECK_ALLOCATED_AND_LIVE (live_string_p);
4178 MARK_INTERVAL_TREE (ptr->intervals);
4179 MARK_STRING (ptr);
4180 #ifdef GC_CHECK_STRING_BYTES
4181 /* Check that the string size recorded in the string is the
4182 same as the one recorded in the sdata structure. */
4183 CHECK_STRING_BYTES (ptr);
4184 #endif /* GC_CHECK_STRING_BYTES */
4186 break;
4188 case Lisp_Vectorlike:
4189 #ifdef GC_CHECK_MARKED_OBJECTS
4190 m = mem_find (po);
4191 if (m == MEM_NIL && !GC_SUBRP (obj)
4192 && po != &buffer_defaults
4193 && po != &buffer_local_symbols)
4194 abort ();
4195 #endif /* GC_CHECK_MARKED_OBJECTS */
4197 if (GC_BUFFERP (obj))
4199 if (!XMARKBIT (XBUFFER (obj)->name))
4201 #ifdef GC_CHECK_MARKED_OBJECTS
4202 if (po != &buffer_defaults && po != &buffer_local_symbols)
4204 struct buffer *b;
4205 for (b = all_buffers; b && b != po; b = b->next)
4207 if (b == NULL)
4208 abort ();
4210 #endif /* GC_CHECK_MARKED_OBJECTS */
4211 mark_buffer (obj);
4214 else if (GC_SUBRP (obj))
4215 break;
4216 else if (GC_COMPILEDP (obj))
4217 /* We could treat this just like a vector, but it is better to
4218 save the COMPILED_CONSTANTS element for last and avoid
4219 recursion there. */
4221 register struct Lisp_Vector *ptr = XVECTOR (obj);
4222 register EMACS_INT size = ptr->size;
4223 register int i;
4225 if (size & ARRAY_MARK_FLAG)
4226 break; /* Already marked */
4228 CHECK_LIVE (live_vector_p);
4229 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4230 size &= PSEUDOVECTOR_SIZE_MASK;
4231 for (i = 0; i < size; i++) /* and then mark its elements */
4233 if (i != COMPILED_CONSTANTS)
4234 mark_object (&ptr->contents[i]);
4236 /* This cast should be unnecessary, but some Mips compiler complains
4237 (MIPS-ABI + SysVR4, DC/OSx, etc). */
4238 objptr = (Lisp_Object *) &ptr->contents[COMPILED_CONSTANTS];
4239 goto loop;
4241 else if (GC_FRAMEP (obj))
4243 register struct frame *ptr = XFRAME (obj);
4244 register EMACS_INT size = ptr->size;
4246 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
4247 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4249 CHECK_LIVE (live_vector_p);
4250 mark_object (&ptr->name);
4251 mark_object (&ptr->icon_name);
4252 mark_object (&ptr->title);
4253 mark_object (&ptr->focus_frame);
4254 mark_object (&ptr->selected_window);
4255 mark_object (&ptr->minibuffer_window);
4256 mark_object (&ptr->param_alist);
4257 mark_object (&ptr->scroll_bars);
4258 mark_object (&ptr->condemned_scroll_bars);
4259 mark_object (&ptr->menu_bar_items);
4260 mark_object (&ptr->face_alist);
4261 mark_object (&ptr->menu_bar_vector);
4262 mark_object (&ptr->buffer_predicate);
4263 mark_object (&ptr->buffer_list);
4264 mark_object (&ptr->menu_bar_window);
4265 mark_object (&ptr->tool_bar_window);
4266 mark_face_cache (ptr->face_cache);
4267 #ifdef HAVE_WINDOW_SYSTEM
4268 mark_image_cache (ptr);
4269 mark_object (&ptr->tool_bar_items);
4270 mark_object (&ptr->desired_tool_bar_string);
4271 mark_object (&ptr->current_tool_bar_string);
4272 #endif /* HAVE_WINDOW_SYSTEM */
4274 else if (GC_BOOL_VECTOR_P (obj))
4276 register struct Lisp_Vector *ptr = XVECTOR (obj);
4278 if (ptr->size & ARRAY_MARK_FLAG)
4279 break; /* Already marked */
4280 CHECK_LIVE (live_vector_p);
4281 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4283 else if (GC_WINDOWP (obj))
4285 register struct Lisp_Vector *ptr = XVECTOR (obj);
4286 struct window *w = XWINDOW (obj);
4287 register EMACS_INT size = ptr->size;
4288 register int i;
4290 /* Stop if already marked. */
4291 if (size & ARRAY_MARK_FLAG)
4292 break;
4294 /* Mark it. */
4295 CHECK_LIVE (live_vector_p);
4296 ptr->size |= ARRAY_MARK_FLAG;
4298 /* There is no Lisp data above The member CURRENT_MATRIX in
4299 struct WINDOW. Stop marking when that slot is reached. */
4300 for (i = 0;
4301 (char *) &ptr->contents[i] < (char *) &w->current_matrix;
4302 i++)
4303 mark_object (&ptr->contents[i]);
4305 /* Mark glyphs for leaf windows. Marking window matrices is
4306 sufficient because frame matrices use the same glyph
4307 memory. */
4308 if (NILP (w->hchild)
4309 && NILP (w->vchild)
4310 && w->current_matrix)
4312 mark_glyph_matrix (w->current_matrix);
4313 mark_glyph_matrix (w->desired_matrix);
4316 else if (GC_HASH_TABLE_P (obj))
4318 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
4319 EMACS_INT size = h->size;
4321 /* Stop if already marked. */
4322 if (size & ARRAY_MARK_FLAG)
4323 break;
4325 /* Mark it. */
4326 CHECK_LIVE (live_vector_p);
4327 h->size |= ARRAY_MARK_FLAG;
4329 /* Mark contents. */
4330 mark_object (&h->test);
4331 mark_object (&h->weak);
4332 mark_object (&h->rehash_size);
4333 mark_object (&h->rehash_threshold);
4334 mark_object (&h->hash);
4335 mark_object (&h->next);
4336 mark_object (&h->index);
4337 mark_object (&h->user_hash_function);
4338 mark_object (&h->user_cmp_function);
4340 /* If hash table is not weak, mark all keys and values.
4341 For weak tables, mark only the vector. */
4342 if (GC_NILP (h->weak))
4343 mark_object (&h->key_and_value);
4344 else
4345 XVECTOR (h->key_and_value)->size |= ARRAY_MARK_FLAG;
4348 else
4350 register struct Lisp_Vector *ptr = XVECTOR (obj);
4351 register EMACS_INT size = ptr->size;
4352 register int i;
4354 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
4355 CHECK_LIVE (live_vector_p);
4356 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4357 if (size & PSEUDOVECTOR_FLAG)
4358 size &= PSEUDOVECTOR_SIZE_MASK;
4360 for (i = 0; i < size; i++) /* and then mark its elements */
4361 mark_object (&ptr->contents[i]);
4363 break;
4365 case Lisp_Symbol:
4367 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
4368 struct Lisp_Symbol *ptrx;
4370 if (XMARKBIT (ptr->plist)) break;
4371 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
4372 XMARK (ptr->plist);
4373 mark_object ((Lisp_Object *) &ptr->value);
4374 mark_object (&ptr->function);
4375 mark_object (&ptr->plist);
4377 if (!PURE_POINTER_P (ptr->name))
4378 MARK_STRING (ptr->name);
4379 MARK_INTERVAL_TREE (ptr->name->intervals);
4381 /* Note that we do not mark the obarray of the symbol.
4382 It is safe not to do so because nothing accesses that
4383 slot except to check whether it is nil. */
4384 ptr = ptr->next;
4385 if (ptr)
4387 /* For the benefit of the last_marked log. */
4388 objptr = (Lisp_Object *)&XSYMBOL (obj)->next;
4389 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
4390 XSETSYMBOL (obj, ptrx);
4391 /* We can't goto loop here because *objptr doesn't contain an
4392 actual Lisp_Object with valid datatype field. */
4393 goto loop2;
4396 break;
4398 case Lisp_Misc:
4399 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
4400 switch (XMISCTYPE (obj))
4402 case Lisp_Misc_Marker:
4403 XMARK (XMARKER (obj)->chain);
4404 /* DO NOT mark thru the marker's chain.
4405 The buffer's markers chain does not preserve markers from gc;
4406 instead, markers are removed from the chain when freed by gc. */
4407 break;
4409 case Lisp_Misc_Buffer_Local_Value:
4410 case Lisp_Misc_Some_Buffer_Local_Value:
4412 register struct Lisp_Buffer_Local_Value *ptr
4413 = XBUFFER_LOCAL_VALUE (obj);
4414 if (XMARKBIT (ptr->realvalue)) break;
4415 XMARK (ptr->realvalue);
4416 /* If the cdr is nil, avoid recursion for the car. */
4417 if (EQ (ptr->cdr, Qnil))
4419 objptr = &ptr->realvalue;
4420 goto loop;
4422 mark_object (&ptr->realvalue);
4423 mark_object (&ptr->buffer);
4424 mark_object (&ptr->frame);
4425 objptr = &ptr->cdr;
4426 goto loop;
4429 case Lisp_Misc_Intfwd:
4430 case Lisp_Misc_Boolfwd:
4431 case Lisp_Misc_Objfwd:
4432 case Lisp_Misc_Buffer_Objfwd:
4433 case Lisp_Misc_Kboard_Objfwd:
4434 /* Don't bother with Lisp_Buffer_Objfwd,
4435 since all markable slots in current buffer marked anyway. */
4436 /* Don't need to do Lisp_Objfwd, since the places they point
4437 are protected with staticpro. */
4438 break;
4440 case Lisp_Misc_Overlay:
4442 struct Lisp_Overlay *ptr = XOVERLAY (obj);
4443 if (!XMARKBIT (ptr->plist))
4445 XMARK (ptr->plist);
4446 mark_object (&ptr->start);
4447 mark_object (&ptr->end);
4448 objptr = &ptr->plist;
4449 goto loop;
4452 break;
4454 default:
4455 abort ();
4457 break;
4459 case Lisp_Cons:
4461 register struct Lisp_Cons *ptr = XCONS (obj);
4462 if (XMARKBIT (ptr->car)) break;
4463 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
4464 XMARK (ptr->car);
4465 /* If the cdr is nil, avoid recursion for the car. */
4466 if (EQ (ptr->cdr, Qnil))
4468 objptr = &ptr->car;
4469 goto loop;
4471 mark_object (&ptr->car);
4472 objptr = &ptr->cdr;
4473 goto loop;
4476 case Lisp_Float:
4477 CHECK_ALLOCATED_AND_LIVE (live_float_p);
4478 XMARK (XFLOAT (obj)->type);
4479 break;
4481 case Lisp_Int:
4482 break;
4484 default:
4485 abort ();
4488 #undef CHECK_LIVE
4489 #undef CHECK_ALLOCATED
4490 #undef CHECK_ALLOCATED_AND_LIVE
4493 /* Mark the pointers in a buffer structure. */
4495 static void
4496 mark_buffer (buf)
4497 Lisp_Object buf;
4499 register struct buffer *buffer = XBUFFER (buf);
4500 register Lisp_Object *ptr;
4501 Lisp_Object base_buffer;
4503 /* This is the buffer's markbit */
4504 mark_object (&buffer->name);
4505 XMARK (buffer->name);
4507 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
4509 if (CONSP (buffer->undo_list))
4511 Lisp_Object tail;
4512 tail = buffer->undo_list;
4514 while (CONSP (tail))
4516 register struct Lisp_Cons *ptr = XCONS (tail);
4518 if (XMARKBIT (ptr->car))
4519 break;
4520 XMARK (ptr->car);
4521 if (GC_CONSP (ptr->car)
4522 && ! XMARKBIT (XCAR (ptr->car))
4523 && GC_MARKERP (XCAR (ptr->car)))
4525 XMARK (XCAR (ptr->car));
4526 mark_object (&XCDR (ptr->car));
4528 else
4529 mark_object (&ptr->car);
4531 if (CONSP (ptr->cdr))
4532 tail = ptr->cdr;
4533 else
4534 break;
4537 mark_object (&XCDR (tail));
4539 else
4540 mark_object (&buffer->undo_list);
4542 for (ptr = &buffer->name + 1;
4543 (char *)ptr < (char *)buffer + sizeof (struct buffer);
4544 ptr++)
4545 mark_object (ptr);
4547 /* If this is an indirect buffer, mark its base buffer. */
4548 if (buffer->base_buffer && !XMARKBIT (buffer->base_buffer->name))
4550 XSETBUFFER (base_buffer, buffer->base_buffer);
4551 mark_buffer (base_buffer);
4556 /* Mark the pointers in the kboard objects. */
4558 static void
4559 mark_kboards ()
4561 KBOARD *kb;
4562 Lisp_Object *p;
4563 for (kb = all_kboards; kb; kb = kb->next_kboard)
4565 if (kb->kbd_macro_buffer)
4566 for (p = kb->kbd_macro_buffer; p < kb->kbd_macro_ptr; p++)
4567 mark_object (p);
4568 mark_object (&kb->Voverriding_terminal_local_map);
4569 mark_object (&kb->Vlast_command);
4570 mark_object (&kb->Vreal_last_command);
4571 mark_object (&kb->Vprefix_arg);
4572 mark_object (&kb->Vlast_prefix_arg);
4573 mark_object (&kb->kbd_queue);
4574 mark_object (&kb->defining_kbd_macro);
4575 mark_object (&kb->Vlast_kbd_macro);
4576 mark_object (&kb->Vsystem_key_alist);
4577 mark_object (&kb->system_key_syms);
4578 mark_object (&kb->Vdefault_minibuffer_frame);
4583 /* Value is non-zero if OBJ will survive the current GC because it's
4584 either marked or does not need to be marked to survive. */
4587 survives_gc_p (obj)
4588 Lisp_Object obj;
4590 int survives_p;
4592 switch (XGCTYPE (obj))
4594 case Lisp_Int:
4595 survives_p = 1;
4596 break;
4598 case Lisp_Symbol:
4599 survives_p = XMARKBIT (XSYMBOL (obj)->plist);
4600 break;
4602 case Lisp_Misc:
4603 switch (XMISCTYPE (obj))
4605 case Lisp_Misc_Marker:
4606 survives_p = XMARKBIT (obj);
4607 break;
4609 case Lisp_Misc_Buffer_Local_Value:
4610 case Lisp_Misc_Some_Buffer_Local_Value:
4611 survives_p = XMARKBIT (XBUFFER_LOCAL_VALUE (obj)->realvalue);
4612 break;
4614 case Lisp_Misc_Intfwd:
4615 case Lisp_Misc_Boolfwd:
4616 case Lisp_Misc_Objfwd:
4617 case Lisp_Misc_Buffer_Objfwd:
4618 case Lisp_Misc_Kboard_Objfwd:
4619 survives_p = 1;
4620 break;
4622 case Lisp_Misc_Overlay:
4623 survives_p = XMARKBIT (XOVERLAY (obj)->plist);
4624 break;
4626 default:
4627 abort ();
4629 break;
4631 case Lisp_String:
4633 struct Lisp_String *s = XSTRING (obj);
4634 survives_p = STRING_MARKED_P (s);
4636 break;
4638 case Lisp_Vectorlike:
4639 if (GC_BUFFERP (obj))
4640 survives_p = XMARKBIT (XBUFFER (obj)->name);
4641 else if (GC_SUBRP (obj))
4642 survives_p = 1;
4643 else
4644 survives_p = XVECTOR (obj)->size & ARRAY_MARK_FLAG;
4645 break;
4647 case Lisp_Cons:
4648 survives_p = XMARKBIT (XCAR (obj));
4649 break;
4651 case Lisp_Float:
4652 survives_p = XMARKBIT (XFLOAT (obj)->type);
4653 break;
4655 default:
4656 abort ();
4659 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
4664 /* Sweep: find all structures not marked, and free them. */
4666 static void
4667 gc_sweep ()
4669 /* Remove or mark entries in weak hash tables.
4670 This must be done before any object is unmarked. */
4671 sweep_weak_hash_tables ();
4673 sweep_strings ();
4674 #ifdef GC_CHECK_STRING_BYTES
4675 if (!noninteractive)
4676 check_string_bytes (1);
4677 #endif
4679 /* Put all unmarked conses on free list */
4681 register struct cons_block *cblk;
4682 struct cons_block **cprev = &cons_block;
4683 register int lim = cons_block_index;
4684 register int num_free = 0, num_used = 0;
4686 cons_free_list = 0;
4688 for (cblk = cons_block; cblk; cblk = *cprev)
4690 register int i;
4691 int this_free = 0;
4692 for (i = 0; i < lim; i++)
4693 if (!XMARKBIT (cblk->conses[i].car))
4695 this_free++;
4696 *(struct Lisp_Cons **)&cblk->conses[i].cdr = cons_free_list;
4697 cons_free_list = &cblk->conses[i];
4698 #if GC_MARK_STACK
4699 cons_free_list->car = Vdead;
4700 #endif
4702 else
4704 num_used++;
4705 XUNMARK (cblk->conses[i].car);
4707 lim = CONS_BLOCK_SIZE;
4708 /* If this block contains only free conses and we have already
4709 seen more than two blocks worth of free conses then deallocate
4710 this block. */
4711 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
4713 *cprev = cblk->next;
4714 /* Unhook from the free list. */
4715 cons_free_list = *(struct Lisp_Cons **) &cblk->conses[0].cdr;
4716 lisp_free (cblk);
4717 n_cons_blocks--;
4719 else
4721 num_free += this_free;
4722 cprev = &cblk->next;
4725 total_conses = num_used;
4726 total_free_conses = num_free;
4729 /* Put all unmarked floats on free list */
4731 register struct float_block *fblk;
4732 struct float_block **fprev = &float_block;
4733 register int lim = float_block_index;
4734 register int num_free = 0, num_used = 0;
4736 float_free_list = 0;
4738 for (fblk = float_block; fblk; fblk = *fprev)
4740 register int i;
4741 int this_free = 0;
4742 for (i = 0; i < lim; i++)
4743 if (!XMARKBIT (fblk->floats[i].type))
4745 this_free++;
4746 *(struct Lisp_Float **)&fblk->floats[i].data = float_free_list;
4747 float_free_list = &fblk->floats[i];
4748 #if GC_MARK_STACK
4749 float_free_list->type = Vdead;
4750 #endif
4752 else
4754 num_used++;
4755 XUNMARK (fblk->floats[i].type);
4757 lim = FLOAT_BLOCK_SIZE;
4758 /* If this block contains only free floats and we have already
4759 seen more than two blocks worth of free floats then deallocate
4760 this block. */
4761 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
4763 *fprev = fblk->next;
4764 /* Unhook from the free list. */
4765 float_free_list = *(struct Lisp_Float **) &fblk->floats[0].data;
4766 lisp_free (fblk);
4767 n_float_blocks--;
4769 else
4771 num_free += this_free;
4772 fprev = &fblk->next;
4775 total_floats = num_used;
4776 total_free_floats = num_free;
4779 /* Put all unmarked intervals on free list */
4781 register struct interval_block *iblk;
4782 struct interval_block **iprev = &interval_block;
4783 register int lim = interval_block_index;
4784 register int num_free = 0, num_used = 0;
4786 interval_free_list = 0;
4788 for (iblk = interval_block; iblk; iblk = *iprev)
4790 register int i;
4791 int this_free = 0;
4793 for (i = 0; i < lim; i++)
4795 if (! XMARKBIT (iblk->intervals[i].plist))
4797 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
4798 interval_free_list = &iblk->intervals[i];
4799 this_free++;
4801 else
4803 num_used++;
4804 XUNMARK (iblk->intervals[i].plist);
4807 lim = INTERVAL_BLOCK_SIZE;
4808 /* If this block contains only free intervals and we have already
4809 seen more than two blocks worth of free intervals then
4810 deallocate this block. */
4811 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
4813 *iprev = iblk->next;
4814 /* Unhook from the free list. */
4815 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
4816 lisp_free (iblk);
4817 n_interval_blocks--;
4819 else
4821 num_free += this_free;
4822 iprev = &iblk->next;
4825 total_intervals = num_used;
4826 total_free_intervals = num_free;
4829 /* Put all unmarked symbols on free list */
4831 register struct symbol_block *sblk;
4832 struct symbol_block **sprev = &symbol_block;
4833 register int lim = symbol_block_index;
4834 register int num_free = 0, num_used = 0;
4836 symbol_free_list = NULL;
4838 for (sblk = symbol_block; sblk; sblk = *sprev)
4840 int this_free = 0;
4841 struct Lisp_Symbol *sym = sblk->symbols;
4842 struct Lisp_Symbol *end = sym + lim;
4844 for (; sym < end; ++sym)
4846 /* Check if the symbol was created during loadup. In such a case
4847 it might be pointed to by pure bytecode which we don't trace,
4848 so we conservatively assume that it is live. */
4849 int pure_p = PURE_POINTER_P (sym->name);
4851 if (!XMARKBIT (sym->plist) && !pure_p)
4853 *(struct Lisp_Symbol **) &sym->value = symbol_free_list;
4854 symbol_free_list = sym;
4855 #if GC_MARK_STACK
4856 symbol_free_list->function = Vdead;
4857 #endif
4858 ++this_free;
4860 else
4862 ++num_used;
4863 if (!pure_p)
4864 UNMARK_STRING (sym->name);
4865 XUNMARK (sym->plist);
4869 lim = SYMBOL_BLOCK_SIZE;
4870 /* If this block contains only free symbols and we have already
4871 seen more than two blocks worth of free symbols then deallocate
4872 this block. */
4873 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
4875 *sprev = sblk->next;
4876 /* Unhook from the free list. */
4877 symbol_free_list = *(struct Lisp_Symbol **)&sblk->symbols[0].value;
4878 lisp_free (sblk);
4879 n_symbol_blocks--;
4881 else
4883 num_free += this_free;
4884 sprev = &sblk->next;
4887 total_symbols = num_used;
4888 total_free_symbols = num_free;
4891 /* Put all unmarked misc's on free list.
4892 For a marker, first unchain it from the buffer it points into. */
4894 register struct marker_block *mblk;
4895 struct marker_block **mprev = &marker_block;
4896 register int lim = marker_block_index;
4897 register int num_free = 0, num_used = 0;
4899 marker_free_list = 0;
4901 for (mblk = marker_block; mblk; mblk = *mprev)
4903 register int i;
4904 int this_free = 0;
4905 EMACS_INT already_free = -1;
4907 for (i = 0; i < lim; i++)
4909 Lisp_Object *markword;
4910 switch (mblk->markers[i].u_marker.type)
4912 case Lisp_Misc_Marker:
4913 markword = &mblk->markers[i].u_marker.chain;
4914 break;
4915 case Lisp_Misc_Buffer_Local_Value:
4916 case Lisp_Misc_Some_Buffer_Local_Value:
4917 markword = &mblk->markers[i].u_buffer_local_value.realvalue;
4918 break;
4919 case Lisp_Misc_Overlay:
4920 markword = &mblk->markers[i].u_overlay.plist;
4921 break;
4922 case Lisp_Misc_Free:
4923 /* If the object was already free, keep it
4924 on the free list. */
4925 markword = (Lisp_Object *) &already_free;
4926 break;
4927 default:
4928 markword = 0;
4929 break;
4931 if (markword && !XMARKBIT (*markword))
4933 Lisp_Object tem;
4934 if (mblk->markers[i].u_marker.type == Lisp_Misc_Marker)
4936 /* tem1 avoids Sun compiler bug */
4937 struct Lisp_Marker *tem1 = &mblk->markers[i].u_marker;
4938 XSETMARKER (tem, tem1);
4939 unchain_marker (tem);
4941 /* Set the type of the freed object to Lisp_Misc_Free.
4942 We could leave the type alone, since nobody checks it,
4943 but this might catch bugs faster. */
4944 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
4945 mblk->markers[i].u_free.chain = marker_free_list;
4946 marker_free_list = &mblk->markers[i];
4947 this_free++;
4949 else
4951 num_used++;
4952 if (markword)
4953 XUNMARK (*markword);
4956 lim = MARKER_BLOCK_SIZE;
4957 /* If this block contains only free markers and we have already
4958 seen more than two blocks worth of free markers then deallocate
4959 this block. */
4960 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
4962 *mprev = mblk->next;
4963 /* Unhook from the free list. */
4964 marker_free_list = mblk->markers[0].u_free.chain;
4965 lisp_free (mblk);
4966 n_marker_blocks--;
4968 else
4970 num_free += this_free;
4971 mprev = &mblk->next;
4975 total_markers = num_used;
4976 total_free_markers = num_free;
4979 /* Free all unmarked buffers */
4981 register struct buffer *buffer = all_buffers, *prev = 0, *next;
4983 while (buffer)
4984 if (!XMARKBIT (buffer->name))
4986 if (prev)
4987 prev->next = buffer->next;
4988 else
4989 all_buffers = buffer->next;
4990 next = buffer->next;
4991 lisp_free (buffer);
4992 buffer = next;
4994 else
4996 XUNMARK (buffer->name);
4997 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
4998 prev = buffer, buffer = buffer->next;
5002 /* Free all unmarked vectors */
5004 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
5005 total_vector_size = 0;
5007 while (vector)
5008 if (!(vector->size & ARRAY_MARK_FLAG))
5010 if (prev)
5011 prev->next = vector->next;
5012 else
5013 all_vectors = vector->next;
5014 next = vector->next;
5015 lisp_free (vector);
5016 n_vectors--;
5017 vector = next;
5020 else
5022 vector->size &= ~ARRAY_MARK_FLAG;
5023 if (vector->size & PSEUDOVECTOR_FLAG)
5024 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
5025 else
5026 total_vector_size += vector->size;
5027 prev = vector, vector = vector->next;
5031 #ifdef GC_CHECK_STRING_BYTES
5032 if (!noninteractive)
5033 check_string_bytes (1);
5034 #endif
5040 /* Debugging aids. */
5042 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
5043 "Return the address of the last byte Emacs has allocated, divided by 1024.\n\
5044 This may be helpful in debugging Emacs's memory usage.\n\
5045 We divide the value by 1024 to make sure it fits in a Lisp integer.")
5048 Lisp_Object end;
5050 XSETINT (end, (EMACS_INT) sbrk (0) / 1024);
5052 return end;
5055 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
5056 "Return a list of counters that measure how much consing there has been.\n\
5057 Each of these counters increments for a certain kind of object.\n\
5058 The counters wrap around from the largest positive integer to zero.\n\
5059 Garbage collection does not decrease them.\n\
5060 The elements of the value are as follows:\n\
5061 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)\n\
5062 All are in units of 1 = one object consed\n\
5063 except for VECTOR-CELLS and STRING-CHARS, which count the total length of\n\
5064 objects consed.\n\
5065 MISCS include overlays, markers, and some internal types.\n\
5066 Frames, windows, buffers, and subprocesses count as vectors\n\
5067 (but the contents of a buffer's text do not count here).")
5070 Lisp_Object consed[8];
5072 XSETINT (consed[0],
5073 cons_cells_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5074 XSETINT (consed[1],
5075 floats_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5076 XSETINT (consed[2],
5077 vector_cells_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5078 XSETINT (consed[3],
5079 symbols_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5080 XSETINT (consed[4],
5081 string_chars_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5082 XSETINT (consed[5],
5083 misc_objects_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5084 XSETINT (consed[6],
5085 intervals_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5086 XSETINT (consed[7],
5087 strings_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5089 return Flist (8, consed);
5092 int suppress_checking;
5093 void
5094 die (msg, file, line)
5095 const char *msg;
5096 const char *file;
5097 int line;
5099 fprintf (stderr, "\r\nEmacs fatal error: %s:%d: %s\r\n",
5100 file, line, msg);
5101 abort ();
5104 /* Initialization */
5106 void
5107 init_alloc_once ()
5109 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
5110 pure_bytes_used = 0;
5111 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
5112 mem_init ();
5113 Vdead = make_pure_string ("DEAD", 4, 4, 0);
5114 #endif
5115 #ifdef HAVE_SHM
5116 pure_size = PURESIZE;
5117 #endif
5118 all_vectors = 0;
5119 ignore_warnings = 1;
5120 #ifdef DOUG_LEA_MALLOC
5121 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
5122 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
5123 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
5124 #endif
5125 init_strings ();
5126 init_cons ();
5127 init_symbol ();
5128 init_marker ();
5129 init_float ();
5130 init_intervals ();
5132 #ifdef REL_ALLOC
5133 malloc_hysteresis = 32;
5134 #else
5135 malloc_hysteresis = 0;
5136 #endif
5138 spare_memory = (char *) malloc (SPARE_MEMORY);
5140 ignore_warnings = 0;
5141 gcprolist = 0;
5142 byte_stack_list = 0;
5143 staticidx = 0;
5144 consing_since_gc = 0;
5145 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
5146 #ifdef VIRT_ADDR_VARIES
5147 malloc_sbrk_unused = 1<<22; /* A large number */
5148 malloc_sbrk_used = 100000; /* as reasonable as any number */
5149 #endif /* VIRT_ADDR_VARIES */
5152 void
5153 init_alloc ()
5155 gcprolist = 0;
5156 byte_stack_list = 0;
5157 #if GC_MARK_STACK
5158 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
5159 setjmp_tested_p = longjmps_done = 0;
5160 #endif
5161 #endif
5164 void
5165 syms_of_alloc ()
5167 DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold,
5168 "*Number of bytes of consing between garbage collections.\n\
5169 Garbage collection can happen automatically once this many bytes have been\n\
5170 allocated since the last garbage collection. All data types count.\n\n\
5171 Garbage collection happens automatically only when `eval' is called.\n\n\
5172 By binding this temporarily to a large number, you can effectively\n\
5173 prevent garbage collection during a part of the program.");
5175 DEFVAR_INT ("pure-bytes-used", &pure_bytes_used,
5176 "Number of bytes of sharable Lisp data allocated so far.");
5178 DEFVAR_INT ("cons-cells-consed", &cons_cells_consed,
5179 "Number of cons cells that have been consed so far.");
5181 DEFVAR_INT ("floats-consed", &floats_consed,
5182 "Number of floats that have been consed so far.");
5184 DEFVAR_INT ("vector-cells-consed", &vector_cells_consed,
5185 "Number of vector cells that have been consed so far.");
5187 DEFVAR_INT ("symbols-consed", &symbols_consed,
5188 "Number of symbols that have been consed so far.");
5190 DEFVAR_INT ("string-chars-consed", &string_chars_consed,
5191 "Number of string characters that have been consed so far.");
5193 DEFVAR_INT ("misc-objects-consed", &misc_objects_consed,
5194 "Number of miscellaneous objects that have been consed so far.");
5196 DEFVAR_INT ("intervals-consed", &intervals_consed,
5197 "Number of intervals that have been consed so far.");
5199 DEFVAR_INT ("strings-consed", &strings_consed,
5200 "Number of strings that have been consed so far.");
5202 DEFVAR_LISP ("purify-flag", &Vpurify_flag,
5203 "Non-nil means loading Lisp code in order to dump an executable.\n\
5204 This means that certain objects should be allocated in shared (pure) space.");
5206 DEFVAR_INT ("undo-limit", &undo_limit,
5207 "Keep no more undo information once it exceeds this size.\n\
5208 This limit is applied when garbage collection happens.\n\
5209 The size is counted as the number of bytes occupied,\n\
5210 which includes both saved text and other data.");
5211 undo_limit = 20000;
5213 DEFVAR_INT ("undo-strong-limit", &undo_strong_limit,
5214 "Don't keep more than this much size of undo information.\n\
5215 A command which pushes past this size is itself forgotten.\n\
5216 This limit is applied when garbage collection happens.\n\
5217 The size is counted as the number of bytes occupied,\n\
5218 which includes both saved text and other data.");
5219 undo_strong_limit = 30000;
5221 DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
5222 "Non-nil means display messages at start and end of garbage collection.");
5223 garbage_collection_messages = 0;
5225 /* We build this in advance because if we wait until we need it, we might
5226 not be able to allocate the memory to hold it. */
5227 memory_signal_data
5228 = Fcons (Qerror, Fcons (build_string ("Memory exhausted--use M-x save-some-buffers RET"), Qnil));
5229 staticpro (&memory_signal_data);
5231 staticpro (&Qgc_cons_threshold);
5232 Qgc_cons_threshold = intern ("gc-cons-threshold");
5234 staticpro (&Qchar_table_extra_slots);
5235 Qchar_table_extra_slots = intern ("char-table-extra-slots");
5237 defsubr (&Scons);
5238 defsubr (&Slist);
5239 defsubr (&Svector);
5240 defsubr (&Smake_byte_code);
5241 defsubr (&Smake_list);
5242 defsubr (&Smake_vector);
5243 defsubr (&Smake_char_table);
5244 defsubr (&Smake_string);
5245 defsubr (&Smake_bool_vector);
5246 defsubr (&Smake_symbol);
5247 defsubr (&Smake_marker);
5248 defsubr (&Spurecopy);
5249 defsubr (&Sgarbage_collect);
5250 defsubr (&Smemory_limit);
5251 defsubr (&Smemory_use_counts);
5253 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5254 defsubr (&Sgc_status);
5255 #endif