*** empty log message ***
[emacs.git] / src / alloc.c
bloba0c06a5c35bbdcc96ae950539f1e3f0fcec492a5
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 "process.h"
43 #include "intervals.h"
44 #include "puresize.h"
45 #include "buffer.h"
46 #include "window.h"
47 #include "keyboard.h"
48 #include "frame.h"
49 #include "blockinput.h"
50 #include "charset.h"
51 #include "syssignal.h"
52 #include <setjmp.h>
54 #ifdef HAVE_UNISTD_H
55 #include <unistd.h>
56 #else
57 extern POINTER_TYPE *sbrk ();
58 #endif
60 #ifdef DOUG_LEA_MALLOC
62 #include <malloc.h>
63 /* malloc.h #defines this as size_t, at least in glibc2. */
64 #ifndef __malloc_size_t
65 #define __malloc_size_t int
66 #endif
68 /* Specify maximum number of areas to mmap. It would be nice to use a
69 value that explicitly means "no limit". */
71 #define MMAP_MAX_AREAS 100000000
73 #else /* not DOUG_LEA_MALLOC */
75 /* The following come from gmalloc.c. */
77 #define __malloc_size_t size_t
78 extern __malloc_size_t _bytes_used;
79 extern __malloc_size_t __malloc_extra_blocks;
81 #endif /* not DOUG_LEA_MALLOC */
83 #define max(A,B) ((A) > (B) ? (A) : (B))
84 #define min(A,B) ((A) < (B) ? (A) : (B))
86 /* Macro to verify that storage intended for Lisp objects is not
87 out of range to fit in the space for a pointer.
88 ADDRESS is the start of the block, and SIZE
89 is the amount of space within which objects can start. */
91 #define VALIDATE_LISP_STORAGE(address, size) \
92 do \
93 { \
94 Lisp_Object val; \
95 XSETCONS (val, (char *) address + size); \
96 if ((char *) XCONS (val) != (char *) address + size) \
97 { \
98 xfree (address); \
99 memory_full (); \
101 } while (0)
103 /* Value of _bytes_used, when spare_memory was freed. */
105 static __malloc_size_t bytes_used_when_full;
107 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
108 to a struct Lisp_String. */
110 #define MARK_STRING(S) ((S)->size |= MARKBIT)
111 #define UNMARK_STRING(S) ((S)->size &= ~MARKBIT)
112 #define STRING_MARKED_P(S) ((S)->size & MARKBIT)
114 /* Value is the number of bytes/chars of S, a pointer to a struct
115 Lisp_String. This must be used instead of STRING_BYTES (S) or
116 S->size during GC, because S->size contains the mark bit for
117 strings. */
119 #define GC_STRING_BYTES(S) (STRING_BYTES (S) & ~MARKBIT)
120 #define GC_STRING_CHARS(S) ((S)->size & ~MARKBIT)
122 /* Number of bytes of consing done since the last gc. */
124 int consing_since_gc;
126 /* Count the amount of consing of various sorts of space. */
128 int cons_cells_consed;
129 int floats_consed;
130 int vector_cells_consed;
131 int symbols_consed;
132 int string_chars_consed;
133 int misc_objects_consed;
134 int intervals_consed;
135 int strings_consed;
137 /* Number of bytes of consing since GC before another GC should be done. */
139 int gc_cons_threshold;
141 /* Nonzero during GC. */
143 int gc_in_progress;
145 /* Nonzero means display messages at beginning and end of GC. */
147 int garbage_collection_messages;
149 #ifndef VIRT_ADDR_VARIES
150 extern
151 #endif /* VIRT_ADDR_VARIES */
152 int malloc_sbrk_used;
154 #ifndef VIRT_ADDR_VARIES
155 extern
156 #endif /* VIRT_ADDR_VARIES */
157 int malloc_sbrk_unused;
159 /* Two limits controlling how much undo information to keep. */
161 int undo_limit;
162 int undo_strong_limit;
164 /* Number of live and free conses etc. */
166 static int total_conses, total_markers, total_symbols, total_vector_size;
167 static int total_free_conses, total_free_markers, total_free_symbols;
168 static int total_free_floats, total_floats;
170 /* Points to memory space allocated as "spare", to be freed if we run
171 out of memory. */
173 static char *spare_memory;
175 /* Amount of spare memory to keep in reserve. */
177 #define SPARE_MEMORY (1 << 14)
179 /* Number of extra blocks malloc should get when it needs more core. */
181 static int malloc_hysteresis;
183 /* Non-nil means defun should do purecopy on the function definition. */
185 Lisp_Object Vpurify_flag;
187 #ifndef HAVE_SHM
189 /* Force it into data space! */
191 EMACS_INT pure[PURESIZE / sizeof (EMACS_INT)] = {0,};
192 #define PUREBEG (char *) pure
194 #else /* not HAVE_SHM */
196 #define pure PURE_SEG_BITS /* Use shared memory segment */
197 #define PUREBEG (char *)PURE_SEG_BITS
199 /* This variable is used only by the XPNTR macro when HAVE_SHM is
200 defined. If we used the PURESIZE macro directly there, that would
201 make most of Emacs dependent on puresize.h, which we don't want -
202 you should be able to change that without too much recompilation.
203 So map_in_data initializes pure_size, and the dependencies work
204 out. */
206 EMACS_INT pure_size;
208 #endif /* not HAVE_SHM */
210 /* Value is non-zero if P points into pure space. */
212 #define PURE_POINTER_P(P) \
213 (((PNTR_COMPARISON_TYPE) (P) \
214 < (PNTR_COMPARISON_TYPE) ((char *) pure + PURESIZE)) \
215 && ((PNTR_COMPARISON_TYPE) (P) \
216 >= (PNTR_COMPARISON_TYPE) pure))
218 /* Index in pure at which next pure object will be allocated.. */
220 int pure_bytes_used;
222 /* If nonzero, this is a warning delivered by malloc and not yet
223 displayed. */
225 char *pending_malloc_warning;
227 /* Pre-computed signal argument for use when memory is exhausted. */
229 Lisp_Object memory_signal_data;
231 /* Maximum amount of C stack to save when a GC happens. */
233 #ifndef MAX_SAVE_STACK
234 #define MAX_SAVE_STACK 16000
235 #endif
237 /* Buffer in which we save a copy of the C stack at each GC. */
239 char *stack_copy;
240 int stack_copy_size;
242 /* Non-zero means ignore malloc warnings. Set during initialization.
243 Currently not used. */
245 int ignore_warnings;
247 Lisp_Object Qgc_cons_threshold, Qchar_table_extra_slots;
249 static void mark_buffer P_ ((Lisp_Object));
250 static void mark_kboards P_ ((void));
251 static void gc_sweep P_ ((void));
252 static void mark_glyph_matrix P_ ((struct glyph_matrix *));
253 static void mark_face_cache P_ ((struct face_cache *));
255 #ifdef HAVE_WINDOW_SYSTEM
256 static void mark_image P_ ((struct image *));
257 static void mark_image_cache P_ ((struct frame *));
258 #endif /* HAVE_WINDOW_SYSTEM */
260 static struct Lisp_String *allocate_string P_ ((void));
261 static void compact_small_strings P_ ((void));
262 static void free_large_strings P_ ((void));
263 static void sweep_strings P_ ((void));
265 extern int message_enable_multibyte;
267 /* When scanning the C stack for live Lisp objects, Emacs keeps track
268 of what memory allocated via lisp_malloc is intended for what
269 purpose. This enumeration specifies the type of memory. */
271 enum mem_type
273 MEM_TYPE_NON_LISP,
274 MEM_TYPE_BUFFER,
275 MEM_TYPE_CONS,
276 MEM_TYPE_STRING,
277 MEM_TYPE_MISC,
278 MEM_TYPE_SYMBOL,
279 MEM_TYPE_FLOAT,
280 /* Keep the following vector-like types together, with
281 MEM_TYPE_WINDOW being the last, and MEM_TYPE_VECTOR the
282 first. Or change the code of live_vector_p, for instance. */
283 MEM_TYPE_VECTOR,
284 MEM_TYPE_PROCESS,
285 MEM_TYPE_HASH_TABLE,
286 MEM_TYPE_FRAME,
287 MEM_TYPE_WINDOW
290 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
292 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
293 #include <stdio.h> /* For fprintf. */
294 #endif
296 /* A unique object in pure space used to make some Lisp objects
297 on free lists recognizable in O(1). */
299 Lisp_Object Vdead;
301 #ifdef GC_MALLOC_CHECK
303 enum mem_type allocated_mem_type;
304 int dont_register_blocks;
306 #endif /* GC_MALLOC_CHECK */
308 /* A node in the red-black tree describing allocated memory containing
309 Lisp data. Each such block is recorded with its start and end
310 address when it is allocated, and removed from the tree when it
311 is freed.
313 A red-black tree is a balanced binary tree with the following
314 properties:
316 1. Every node is either red or black.
317 2. Every leaf is black.
318 3. If a node is red, then both of its children are black.
319 4. Every simple path from a node to a descendant leaf contains
320 the same number of black nodes.
321 5. The root is always black.
323 When nodes are inserted into the tree, or deleted from the tree,
324 the tree is "fixed" so that these properties are always true.
326 A red-black tree with N internal nodes has height at most 2
327 log(N+1). Searches, insertions and deletions are done in O(log N).
328 Please see a text book about data structures for a detailed
329 description of red-black trees. Any book worth its salt should
330 describe them. */
332 struct mem_node
334 struct mem_node *left, *right, *parent;
336 /* Start and end of allocated region. */
337 void *start, *end;
339 /* Node color. */
340 enum {MEM_BLACK, MEM_RED} color;
342 /* Memory type. */
343 enum mem_type type;
346 /* Base address of stack. Set in main. */
348 Lisp_Object *stack_base;
350 /* Root of the tree describing allocated Lisp memory. */
352 static struct mem_node *mem_root;
354 /* Lowest and highest known address in the heap. */
356 static void *min_heap_address, *max_heap_address;
358 /* Sentinel node of the tree. */
360 static struct mem_node mem_z;
361 #define MEM_NIL &mem_z
363 static POINTER_TYPE *lisp_malloc P_ ((size_t, enum mem_type));
364 static struct Lisp_Vector *allocate_vectorlike P_ ((EMACS_INT, enum mem_type));
365 static void lisp_free P_ ((POINTER_TYPE *));
366 static void mark_stack P_ ((void));
367 static void init_stack P_ ((Lisp_Object *));
368 static int live_vector_p P_ ((struct mem_node *, void *));
369 static int live_buffer_p P_ ((struct mem_node *, void *));
370 static int live_string_p P_ ((struct mem_node *, void *));
371 static int live_cons_p P_ ((struct mem_node *, void *));
372 static int live_symbol_p P_ ((struct mem_node *, void *));
373 static int live_float_p P_ ((struct mem_node *, void *));
374 static int live_misc_p P_ ((struct mem_node *, void *));
375 static void mark_maybe_object P_ ((Lisp_Object));
376 static void mark_memory P_ ((void *, void *));
377 static void mem_init P_ ((void));
378 static struct mem_node *mem_insert P_ ((void *, void *, enum mem_type));
379 static void mem_insert_fixup P_ ((struct mem_node *));
380 static void mem_rotate_left P_ ((struct mem_node *));
381 static void mem_rotate_right P_ ((struct mem_node *));
382 static void mem_delete P_ ((struct mem_node *));
383 static void mem_delete_fixup P_ ((struct mem_node *));
384 static INLINE struct mem_node *mem_find P_ ((void *));
386 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
387 static void check_gcpros P_ ((void));
388 #endif
390 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
392 /* Recording what needs to be marked for gc. */
394 struct gcpro *gcprolist;
396 /* Addresses of staticpro'd variables. */
398 #define NSTATICS 1024
399 Lisp_Object *staticvec[NSTATICS] = {0};
401 /* Index of next unused slot in staticvec. */
403 int staticidx = 0;
405 static POINTER_TYPE *pure_alloc P_ ((size_t, int));
408 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
409 ALIGNMENT must be a power of 2. */
411 #define ALIGN(SZ, ALIGNMENT) \
412 (((SZ) + (ALIGNMENT) - 1) & ~((ALIGNMENT) - 1))
416 /************************************************************************
417 Malloc
418 ************************************************************************/
420 /* Write STR to Vstandard_output plus some advice on how to free some
421 memory. Called when memory gets low. */
423 Lisp_Object
424 malloc_warning_1 (str)
425 Lisp_Object str;
427 Fprinc (str, Vstandard_output);
428 write_string ("\nKilling some buffers may delay running out of memory.\n", -1);
429 write_string ("However, certainly by the time you receive the 95% warning,\n", -1);
430 write_string ("you should clean up, kill this Emacs, and start a new one.", -1);
431 return Qnil;
435 /* Function malloc calls this if it finds we are near exhausting
436 storage. */
438 void
439 malloc_warning (str)
440 char *str;
442 pending_malloc_warning = str;
446 /* Display a malloc warning in buffer *Danger*. */
448 void
449 display_malloc_warning ()
451 register Lisp_Object val;
453 val = build_string (pending_malloc_warning);
454 pending_malloc_warning = 0;
455 internal_with_output_to_temp_buffer (" *Danger*", malloc_warning_1, val);
459 #ifdef DOUG_LEA_MALLOC
460 # define BYTES_USED (mallinfo ().arena)
461 #else
462 # define BYTES_USED _bytes_used
463 #endif
466 /* Called if malloc returns zero. */
468 void
469 memory_full ()
471 #ifndef SYSTEM_MALLOC
472 bytes_used_when_full = BYTES_USED;
473 #endif
475 /* The first time we get here, free the spare memory. */
476 if (spare_memory)
478 free (spare_memory);
479 spare_memory = 0;
482 /* This used to call error, but if we've run out of memory, we could
483 get infinite recursion trying to build the string. */
484 while (1)
485 Fsignal (Qnil, memory_signal_data);
489 /* Called if we can't allocate relocatable space for a buffer. */
491 void
492 buffer_memory_full ()
494 /* If buffers use the relocating allocator, no need to free
495 spare_memory, because we may have plenty of malloc space left
496 that we could get, and if we don't, the malloc that fails will
497 itself cause spare_memory to be freed. If buffers don't use the
498 relocating allocator, treat this like any other failing
499 malloc. */
501 #ifndef REL_ALLOC
502 memory_full ();
503 #endif
505 /* This used to call error, but if we've run out of memory, we could
506 get infinite recursion trying to build the string. */
507 while (1)
508 Fsignal (Qerror, memory_signal_data);
512 /* Like malloc but check for no memory and block interrupt input.. */
514 POINTER_TYPE *
515 xmalloc (size)
516 size_t size;
518 register POINTER_TYPE *val;
520 BLOCK_INPUT;
521 val = (POINTER_TYPE *) malloc (size);
522 UNBLOCK_INPUT;
524 if (!val && size)
525 memory_full ();
526 return val;
530 /* Like realloc but check for no memory and block interrupt input.. */
532 POINTER_TYPE *
533 xrealloc (block, size)
534 POINTER_TYPE *block;
535 size_t size;
537 register POINTER_TYPE *val;
539 BLOCK_INPUT;
540 /* We must call malloc explicitly when BLOCK is 0, since some
541 reallocs don't do this. */
542 if (! block)
543 val = (POINTER_TYPE *) malloc (size);
544 else
545 val = (POINTER_TYPE *) realloc (block, size);
546 UNBLOCK_INPUT;
548 if (!val && size) memory_full ();
549 return val;
553 /* Like free but block interrupt input.. */
555 void
556 xfree (block)
557 POINTER_TYPE *block;
559 BLOCK_INPUT;
560 free (block);
561 UNBLOCK_INPUT;
565 /* Like strdup, but uses xmalloc. */
567 char *
568 xstrdup (s)
569 char *s;
571 size_t len = strlen (s) + 1;
572 char *p = (char *) xmalloc (len);
573 bcopy (s, p, len);
574 return p;
578 /* Like malloc but used for allocating Lisp data. NBYTES is the
579 number of bytes to allocate, TYPE describes the intended use of the
580 allcated memory block (for strings, for conses, ...). */
582 static POINTER_TYPE *
583 lisp_malloc (nbytes, type)
584 size_t nbytes;
585 enum mem_type type;
587 register void *val;
589 BLOCK_INPUT;
591 #ifdef GC_MALLOC_CHECK
592 allocated_mem_type = type;
593 #endif
595 val = (void *) malloc (nbytes);
597 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
598 if (val && type != MEM_TYPE_NON_LISP)
599 mem_insert (val, (char *) val + nbytes, type);
600 #endif
602 UNBLOCK_INPUT;
603 if (!val && nbytes)
604 memory_full ();
605 return val;
609 /* Return a new buffer structure allocated from the heap with
610 a call to lisp_malloc. */
612 struct buffer *
613 allocate_buffer ()
615 return (struct buffer *) lisp_malloc (sizeof (struct buffer),
616 MEM_TYPE_BUFFER);
620 /* Free BLOCK. This must be called to free memory allocated with a
621 call to lisp_malloc. */
623 static void
624 lisp_free (block)
625 POINTER_TYPE *block;
627 BLOCK_INPUT;
628 free (block);
629 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
630 mem_delete (mem_find (block));
631 #endif
632 UNBLOCK_INPUT;
636 /* Arranging to disable input signals while we're in malloc.
638 This only works with GNU malloc. To help out systems which can't
639 use GNU malloc, all the calls to malloc, realloc, and free
640 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
641 pairs; unfortunately, we have no idea what C library functions
642 might call malloc, so we can't really protect them unless you're
643 using GNU malloc. Fortunately, most of the major operating can use
644 GNU malloc. */
646 #ifndef SYSTEM_MALLOC
647 #ifndef DOUG_LEA_MALLOC
648 extern void * (*__malloc_hook) P_ ((size_t));
649 extern void * (*__realloc_hook) P_ ((void *, size_t));
650 extern void (*__free_hook) P_ ((void *));
651 /* Else declared in malloc.h, perhaps with an extra arg. */
652 #endif /* DOUG_LEA_MALLOC */
653 static void * (*old_malloc_hook) ();
654 static void * (*old_realloc_hook) ();
655 static void (*old_free_hook) ();
657 /* This function is used as the hook for free to call. */
659 static void
660 emacs_blocked_free (ptr)
661 void *ptr;
663 BLOCK_INPUT;
665 #ifdef GC_MALLOC_CHECK
666 if (ptr)
668 struct mem_node *m;
670 m = mem_find (ptr);
671 if (m == MEM_NIL || m->start != ptr)
673 fprintf (stderr,
674 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
675 abort ();
677 else
679 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
680 mem_delete (m);
683 #endif /* GC_MALLOC_CHECK */
685 __free_hook = old_free_hook;
686 free (ptr);
688 /* If we released our reserve (due to running out of memory),
689 and we have a fair amount free once again,
690 try to set aside another reserve in case we run out once more. */
691 if (spare_memory == 0
692 /* Verify there is enough space that even with the malloc
693 hysteresis this call won't run out again.
694 The code here is correct as long as SPARE_MEMORY
695 is substantially larger than the block size malloc uses. */
696 && (bytes_used_when_full
697 > BYTES_USED + max (malloc_hysteresis, 4) * SPARE_MEMORY))
698 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
700 __free_hook = emacs_blocked_free;
701 UNBLOCK_INPUT;
705 /* If we released our reserve (due to running out of memory),
706 and we have a fair amount free once again,
707 try to set aside another reserve in case we run out once more.
709 This is called when a relocatable block is freed in ralloc.c. */
711 void
712 refill_memory_reserve ()
714 if (spare_memory == 0)
715 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
719 /* This function is the malloc hook that Emacs uses. */
721 static void *
722 emacs_blocked_malloc (size)
723 size_t size;
725 void *value;
727 BLOCK_INPUT;
728 __malloc_hook = old_malloc_hook;
729 #ifdef DOUG_LEA_MALLOC
730 mallopt (M_TOP_PAD, malloc_hysteresis * 4096);
731 #else
732 __malloc_extra_blocks = malloc_hysteresis;
733 #endif
735 value = (void *) malloc (size);
737 #ifdef GC_MALLOC_CHECK
739 struct mem_node *m = mem_find (value);
740 if (m != MEM_NIL)
742 fprintf (stderr, "Malloc returned %p which is already in use\n",
743 value);
744 fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
745 m->start, m->end, (char *) m->end - (char *) m->start,
746 m->type);
747 abort ();
750 if (!dont_register_blocks)
752 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
753 allocated_mem_type = MEM_TYPE_NON_LISP;
756 #endif /* GC_MALLOC_CHECK */
758 __malloc_hook = emacs_blocked_malloc;
759 UNBLOCK_INPUT;
761 /* fprintf (stderr, "%p malloc\n", value); */
762 return value;
766 /* This function is the realloc hook that Emacs uses. */
768 static void *
769 emacs_blocked_realloc (ptr, size)
770 void *ptr;
771 size_t size;
773 void *value;
775 BLOCK_INPUT;
776 __realloc_hook = old_realloc_hook;
778 #ifdef GC_MALLOC_CHECK
779 if (ptr)
781 struct mem_node *m = mem_find (ptr);
782 if (m == MEM_NIL || m->start != ptr)
784 fprintf (stderr,
785 "Realloc of %p which wasn't allocated with malloc\n",
786 ptr);
787 abort ();
790 mem_delete (m);
793 /* fprintf (stderr, "%p -> realloc\n", ptr); */
795 /* Prevent malloc from registering blocks. */
796 dont_register_blocks = 1;
797 #endif /* GC_MALLOC_CHECK */
799 value = (void *) realloc (ptr, size);
801 #ifdef GC_MALLOC_CHECK
802 dont_register_blocks = 0;
805 struct mem_node *m = mem_find (value);
806 if (m != MEM_NIL)
808 fprintf (stderr, "Realloc returns memory that is already in use\n");
809 abort ();
812 /* Can't handle zero size regions in the red-black tree. */
813 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
816 /* fprintf (stderr, "%p <- realloc\n", value); */
817 #endif /* GC_MALLOC_CHECK */
819 __realloc_hook = emacs_blocked_realloc;
820 UNBLOCK_INPUT;
822 return value;
826 /* Called from main to set up malloc to use our hooks. */
828 void
829 uninterrupt_malloc ()
831 if (__free_hook != emacs_blocked_free)
832 old_free_hook = __free_hook;
833 __free_hook = emacs_blocked_free;
835 if (__malloc_hook != emacs_blocked_malloc)
836 old_malloc_hook = __malloc_hook;
837 __malloc_hook = emacs_blocked_malloc;
839 if (__realloc_hook != emacs_blocked_realloc)
840 old_realloc_hook = __realloc_hook;
841 __realloc_hook = emacs_blocked_realloc;
844 #endif /* not SYSTEM_MALLOC */
848 /***********************************************************************
849 Interval Allocation
850 ***********************************************************************/
852 /* Number of intervals allocated in an interval_block structure.
853 The 1020 is 1024 minus malloc overhead. */
855 #define INTERVAL_BLOCK_SIZE \
856 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
858 /* Intervals are allocated in chunks in form of an interval_block
859 structure. */
861 struct interval_block
863 struct interval_block *next;
864 struct interval intervals[INTERVAL_BLOCK_SIZE];
867 /* Current interval block. Its `next' pointer points to older
868 blocks. */
870 struct interval_block *interval_block;
872 /* Index in interval_block above of the next unused interval
873 structure. */
875 static int interval_block_index;
877 /* Number of free and live intervals. */
879 static int total_free_intervals, total_intervals;
881 /* List of free intervals. */
883 INTERVAL interval_free_list;
885 /* Total number of interval blocks now in use. */
887 int n_interval_blocks;
890 /* Initialize interval allocation. */
892 static void
893 init_intervals ()
895 interval_block
896 = (struct interval_block *) lisp_malloc (sizeof *interval_block,
897 MEM_TYPE_NON_LISP);
898 interval_block->next = 0;
899 bzero ((char *) interval_block->intervals, sizeof interval_block->intervals);
900 interval_block_index = 0;
901 interval_free_list = 0;
902 n_interval_blocks = 1;
906 /* Return a new interval. */
908 INTERVAL
909 make_interval ()
911 INTERVAL val;
913 if (interval_free_list)
915 val = interval_free_list;
916 interval_free_list = INTERVAL_PARENT (interval_free_list);
918 else
920 if (interval_block_index == INTERVAL_BLOCK_SIZE)
922 register struct interval_block *newi;
924 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
925 MEM_TYPE_NON_LISP);
927 VALIDATE_LISP_STORAGE (newi, sizeof *newi);
928 newi->next = interval_block;
929 interval_block = newi;
930 interval_block_index = 0;
931 n_interval_blocks++;
933 val = &interval_block->intervals[interval_block_index++];
935 consing_since_gc += sizeof (struct interval);
936 intervals_consed++;
937 RESET_INTERVAL (val);
938 return val;
942 /* Mark Lisp objects in interval I. */
944 static void
945 mark_interval (i, dummy)
946 register INTERVAL i;
947 Lisp_Object dummy;
949 if (XMARKBIT (i->plist))
950 abort ();
951 mark_object (&i->plist);
952 XMARK (i->plist);
956 /* Mark the interval tree rooted in TREE. Don't call this directly;
957 use the macro MARK_INTERVAL_TREE instead. */
959 static void
960 mark_interval_tree (tree)
961 register INTERVAL tree;
963 /* No need to test if this tree has been marked already; this
964 function is always called through the MARK_INTERVAL_TREE macro,
965 which takes care of that. */
967 /* XMARK expands to an assignment; the LHS of an assignment can't be
968 a cast. */
969 XMARK (tree->up.obj);
971 traverse_intervals (tree, 1, 0, mark_interval, Qnil);
975 /* Mark the interval tree rooted in I. */
977 #define MARK_INTERVAL_TREE(i) \
978 do { \
979 if (!NULL_INTERVAL_P (i) \
980 && ! XMARKBIT (i->up.obj)) \
981 mark_interval_tree (i); \
982 } while (0)
985 /* The oddity in the call to XUNMARK is necessary because XUNMARK
986 expands to an assignment to its argument, and most C compilers
987 don't support casts on the left operand of `='. */
989 #define UNMARK_BALANCE_INTERVALS(i) \
990 do { \
991 if (! NULL_INTERVAL_P (i)) \
993 XUNMARK ((i)->up.obj); \
994 (i) = balance_intervals (i); \
996 } while (0)
999 /* Number support. If NO_UNION_TYPE isn't in effect, we
1000 can't create number objects in macros. */
1001 #ifndef make_number
1002 Lisp_Object
1003 make_number (n)
1004 int n;
1006 Lisp_Object obj;
1007 obj.s.val = n;
1008 obj.s.type = Lisp_Int;
1009 return obj;
1011 #endif
1013 /***********************************************************************
1014 String Allocation
1015 ***********************************************************************/
1017 /* Lisp_Strings are allocated in string_block structures. When a new
1018 string_block is allocated, all the Lisp_Strings it contains are
1019 added to a free-list stiing_free_list. When a new Lisp_String is
1020 needed, it is taken from that list. During the sweep phase of GC,
1021 string_blocks that are entirely free are freed, except two which
1022 we keep.
1024 String data is allocated from sblock structures. Strings larger
1025 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1026 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1028 Sblocks consist internally of sdata structures, one for each
1029 Lisp_String. The sdata structure points to the Lisp_String it
1030 belongs to. The Lisp_String points back to the `u.data' member of
1031 its sdata structure.
1033 When a Lisp_String is freed during GC, it is put back on
1034 string_free_list, and its `data' member and its sdata's `string'
1035 pointer is set to null. The size of the string is recorded in the
1036 `u.nbytes' member of the sdata. So, sdata structures that are no
1037 longer used, can be easily recognized, and it's easy to compact the
1038 sblocks of small strings which we do in compact_small_strings. */
1040 /* Size in bytes of an sblock structure used for small strings. This
1041 is 8192 minus malloc overhead. */
1043 #define SBLOCK_SIZE 8188
1045 /* Strings larger than this are considered large strings. String data
1046 for large strings is allocated from individual sblocks. */
1048 #define LARGE_STRING_BYTES 1024
1050 /* Structure describing string memory sub-allocated from an sblock.
1051 This is where the contents of Lisp strings are stored. */
1053 struct sdata
1055 /* Back-pointer to the string this sdata belongs to. If null, this
1056 structure is free, and the NBYTES member of the union below
1057 contains the string's byte size (the same value that STRING_BYTES
1058 would return if STRING were non-null). If non-null, STRING_BYTES
1059 (STRING) is the size of the data, and DATA contains the string's
1060 contents. */
1061 struct Lisp_String *string;
1063 #ifdef GC_CHECK_STRING_BYTES
1065 EMACS_INT nbytes;
1066 unsigned char data[1];
1068 #define SDATA_NBYTES(S) (S)->nbytes
1069 #define SDATA_DATA(S) (S)->data
1071 #else /* not GC_CHECK_STRING_BYTES */
1073 union
1075 /* When STRING in non-null. */
1076 unsigned char data[1];
1078 /* When STRING is null. */
1079 EMACS_INT nbytes;
1080 } u;
1083 #define SDATA_NBYTES(S) (S)->u.nbytes
1084 #define SDATA_DATA(S) (S)->u.data
1086 #endif /* not GC_CHECK_STRING_BYTES */
1090 /* Structure describing a block of memory which is sub-allocated to
1091 obtain string data memory for strings. Blocks for small strings
1092 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1093 as large as needed. */
1095 struct sblock
1097 /* Next in list. */
1098 struct sblock *next;
1100 /* Pointer to the next free sdata block. This points past the end
1101 of the sblock if there isn't any space left in this block. */
1102 struct sdata *next_free;
1104 /* Start of data. */
1105 struct sdata first_data;
1108 /* Number of Lisp strings in a string_block structure. The 1020 is
1109 1024 minus malloc overhead. */
1111 #define STRINGS_IN_STRING_BLOCK \
1112 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1114 /* Structure describing a block from which Lisp_String structures
1115 are allocated. */
1117 struct string_block
1119 struct string_block *next;
1120 struct Lisp_String strings[STRINGS_IN_STRING_BLOCK];
1123 /* Head and tail of the list of sblock structures holding Lisp string
1124 data. We always allocate from current_sblock. The NEXT pointers
1125 in the sblock structures go from oldest_sblock to current_sblock. */
1127 static struct sblock *oldest_sblock, *current_sblock;
1129 /* List of sblocks for large strings. */
1131 static struct sblock *large_sblocks;
1133 /* List of string_block structures, and how many there are. */
1135 static struct string_block *string_blocks;
1136 static int n_string_blocks;
1138 /* Free-list of Lisp_Strings. */
1140 static struct Lisp_String *string_free_list;
1142 /* Number of live and free Lisp_Strings. */
1144 static int total_strings, total_free_strings;
1146 /* Number of bytes used by live strings. */
1148 static int total_string_size;
1150 /* Given a pointer to a Lisp_String S which is on the free-list
1151 string_free_list, return a pointer to its successor in the
1152 free-list. */
1154 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1156 /* Return a pointer to the sdata structure belonging to Lisp string S.
1157 S must be live, i.e. S->data must not be null. S->data is actually
1158 a pointer to the `u.data' member of its sdata structure; the
1159 structure starts at a constant offset in front of that. */
1161 #ifdef GC_CHECK_STRING_BYTES
1163 #define SDATA_OF_STRING(S) \
1164 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *) \
1165 - sizeof (EMACS_INT)))
1167 #else /* not GC_CHECK_STRING_BYTES */
1169 #define SDATA_OF_STRING(S) \
1170 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))
1172 #endif /* not GC_CHECK_STRING_BYTES */
1174 /* Value is the size of an sdata structure large enough to hold NBYTES
1175 bytes of string data. The value returned includes a terminating
1176 NUL byte, the size of the sdata structure, and padding. */
1178 #ifdef GC_CHECK_STRING_BYTES
1180 #define SDATA_SIZE(NBYTES) \
1181 ((sizeof (struct Lisp_String *) \
1182 + (NBYTES) + 1 \
1183 + sizeof (EMACS_INT) \
1184 + sizeof (EMACS_INT) - 1) \
1185 & ~(sizeof (EMACS_INT) - 1))
1187 #else /* not GC_CHECK_STRING_BYTES */
1189 #define SDATA_SIZE(NBYTES) \
1190 ((sizeof (struct Lisp_String *) \
1191 + (NBYTES) + 1 \
1192 + sizeof (EMACS_INT) - 1) \
1193 & ~(sizeof (EMACS_INT) - 1))
1195 #endif /* not GC_CHECK_STRING_BYTES */
1197 /* Initialize string allocation. Called from init_alloc_once. */
1199 void
1200 init_strings ()
1202 total_strings = total_free_strings = total_string_size = 0;
1203 oldest_sblock = current_sblock = large_sblocks = NULL;
1204 string_blocks = NULL;
1205 n_string_blocks = 0;
1206 string_free_list = NULL;
1210 #ifdef GC_CHECK_STRING_BYTES
1212 static int check_string_bytes_count;
1214 void check_string_bytes P_ ((int));
1215 void check_sblock P_ ((struct sblock *));
1217 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1220 /* Like GC_STRING_BYTES, but with debugging check. */
1223 string_bytes (s)
1224 struct Lisp_String *s;
1226 int nbytes = (s->size_byte < 0 ? s->size : s->size_byte) & ~MARKBIT;
1227 if (!PURE_POINTER_P (s)
1228 && s->data
1229 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1230 abort ();
1231 return nbytes;
1234 /* Check validity Lisp strings' string_bytes member in B. */
1236 void
1237 check_sblock (b)
1238 struct sblock *b;
1240 struct sdata *from, *end, *from_end;
1242 end = b->next_free;
1244 for (from = &b->first_data; from < end; from = from_end)
1246 /* Compute the next FROM here because copying below may
1247 overwrite data we need to compute it. */
1248 int nbytes;
1250 /* Check that the string size recorded in the string is the
1251 same as the one recorded in the sdata structure. */
1252 if (from->string)
1253 CHECK_STRING_BYTES (from->string);
1255 if (from->string)
1256 nbytes = GC_STRING_BYTES (from->string);
1257 else
1258 nbytes = SDATA_NBYTES (from);
1260 nbytes = SDATA_SIZE (nbytes);
1261 from_end = (struct sdata *) ((char *) from + nbytes);
1266 /* Check validity of Lisp strings' string_bytes member. ALL_P
1267 non-zero means check all strings, otherwise check only most
1268 recently allocated strings. Used for hunting a bug. */
1270 void
1271 check_string_bytes (all_p)
1272 int all_p;
1274 if (all_p)
1276 struct sblock *b;
1278 for (b = large_sblocks; b; b = b->next)
1280 struct Lisp_String *s = b->first_data.string;
1281 if (s)
1282 CHECK_STRING_BYTES (s);
1285 for (b = oldest_sblock; b; b = b->next)
1286 check_sblock (b);
1288 else
1289 check_sblock (current_sblock);
1292 #endif /* GC_CHECK_STRING_BYTES */
1295 /* Return a new Lisp_String. */
1297 static struct Lisp_String *
1298 allocate_string ()
1300 struct Lisp_String *s;
1302 /* If the free-list is empty, allocate a new string_block, and
1303 add all the Lisp_Strings in it to the free-list. */
1304 if (string_free_list == NULL)
1306 struct string_block *b;
1307 int i;
1309 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1310 VALIDATE_LISP_STORAGE (b, sizeof *b);
1311 bzero (b, sizeof *b);
1312 b->next = string_blocks;
1313 string_blocks = b;
1314 ++n_string_blocks;
1316 for (i = STRINGS_IN_STRING_BLOCK - 1; i >= 0; --i)
1318 s = b->strings + i;
1319 NEXT_FREE_LISP_STRING (s) = string_free_list;
1320 string_free_list = s;
1323 total_free_strings += STRINGS_IN_STRING_BLOCK;
1326 /* Pop a Lisp_String off the free-list. */
1327 s = string_free_list;
1328 string_free_list = NEXT_FREE_LISP_STRING (s);
1330 /* Probably not strictly necessary, but play it safe. */
1331 bzero (s, sizeof *s);
1333 --total_free_strings;
1334 ++total_strings;
1335 ++strings_consed;
1336 consing_since_gc += sizeof *s;
1338 #ifdef GC_CHECK_STRING_BYTES
1339 if (!noninteractive
1340 #ifdef macintosh
1341 && current_sblock
1342 #endif
1345 if (++check_string_bytes_count == 200)
1347 check_string_bytes_count = 0;
1348 check_string_bytes (1);
1350 else
1351 check_string_bytes (0);
1353 #endif /* GC_CHECK_STRING_BYTES */
1355 return s;
1359 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1360 plus a NUL byte at the end. Allocate an sdata structure for S, and
1361 set S->data to its `u.data' member. Store a NUL byte at the end of
1362 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1363 S->data if it was initially non-null. */
1365 void
1366 allocate_string_data (s, nchars, nbytes)
1367 struct Lisp_String *s;
1368 int nchars, nbytes;
1370 struct sdata *data, *old_data;
1371 struct sblock *b;
1372 int needed, old_nbytes;
1374 /* Determine the number of bytes needed to store NBYTES bytes
1375 of string data. */
1376 needed = SDATA_SIZE (nbytes);
1378 if (nbytes > LARGE_STRING_BYTES)
1380 size_t size = sizeof *b - sizeof (struct sdata) + needed;
1382 #ifdef DOUG_LEA_MALLOC
1383 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1384 because mapped region contents are not preserved in
1385 a dumped Emacs. */
1386 mallopt (M_MMAP_MAX, 0);
1387 #endif
1389 b = (struct sblock *) lisp_malloc (size, MEM_TYPE_NON_LISP);
1391 #ifdef DOUG_LEA_MALLOC
1392 /* Back to a reasonable maximum of mmap'ed areas. */
1393 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1394 #endif
1396 b->next_free = &b->first_data;
1397 b->first_data.string = NULL;
1398 b->next = large_sblocks;
1399 large_sblocks = b;
1401 else if (current_sblock == NULL
1402 || (((char *) current_sblock + SBLOCK_SIZE
1403 - (char *) current_sblock->next_free)
1404 < needed))
1406 /* Not enough room in the current sblock. */
1407 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1408 b->next_free = &b->first_data;
1409 b->first_data.string = NULL;
1410 b->next = NULL;
1412 if (current_sblock)
1413 current_sblock->next = b;
1414 else
1415 oldest_sblock = b;
1416 current_sblock = b;
1418 else
1419 b = current_sblock;
1421 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1422 old_nbytes = GC_STRING_BYTES (s);
1424 data = b->next_free;
1425 data->string = s;
1426 s->data = SDATA_DATA (data);
1427 #ifdef GC_CHECK_STRING_BYTES
1428 SDATA_NBYTES (data) = nbytes;
1429 #endif
1430 s->size = nchars;
1431 s->size_byte = nbytes;
1432 s->data[nbytes] = '\0';
1433 b->next_free = (struct sdata *) ((char *) data + needed);
1435 /* If S had already data assigned, mark that as free by setting its
1436 string back-pointer to null, and recording the size of the data
1437 in it. */
1438 if (old_data)
1440 SDATA_NBYTES (old_data) = old_nbytes;
1441 old_data->string = NULL;
1444 consing_since_gc += needed;
1448 /* Sweep and compact strings. */
1450 static void
1451 sweep_strings ()
1453 struct string_block *b, *next;
1454 struct string_block *live_blocks = NULL;
1456 string_free_list = NULL;
1457 total_strings = total_free_strings = 0;
1458 total_string_size = 0;
1460 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1461 for (b = string_blocks; b; b = next)
1463 int i, nfree = 0;
1464 struct Lisp_String *free_list_before = string_free_list;
1466 next = b->next;
1468 for (i = 0; i < STRINGS_IN_STRING_BLOCK; ++i)
1470 struct Lisp_String *s = b->strings + i;
1472 if (s->data)
1474 /* String was not on free-list before. */
1475 if (STRING_MARKED_P (s))
1477 /* String is live; unmark it and its intervals. */
1478 UNMARK_STRING (s);
1480 if (!NULL_INTERVAL_P (s->intervals))
1481 UNMARK_BALANCE_INTERVALS (s->intervals);
1483 ++total_strings;
1484 total_string_size += STRING_BYTES (s);
1486 else
1488 /* String is dead. Put it on the free-list. */
1489 struct sdata *data = SDATA_OF_STRING (s);
1491 /* Save the size of S in its sdata so that we know
1492 how large that is. Reset the sdata's string
1493 back-pointer so that we know it's free. */
1494 #ifdef GC_CHECK_STRING_BYTES
1495 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
1496 abort ();
1497 #else
1498 data->u.nbytes = GC_STRING_BYTES (s);
1499 #endif
1500 data->string = NULL;
1502 /* Reset the strings's `data' member so that we
1503 know it's free. */
1504 s->data = NULL;
1506 /* Put the string on the free-list. */
1507 NEXT_FREE_LISP_STRING (s) = string_free_list;
1508 string_free_list = s;
1509 ++nfree;
1512 else
1514 /* S was on the free-list before. Put it there again. */
1515 NEXT_FREE_LISP_STRING (s) = string_free_list;
1516 string_free_list = s;
1517 ++nfree;
1521 /* Free blocks that contain free Lisp_Strings only, except
1522 the first two of them. */
1523 if (nfree == STRINGS_IN_STRING_BLOCK
1524 && total_free_strings > STRINGS_IN_STRING_BLOCK)
1526 lisp_free (b);
1527 --n_string_blocks;
1528 string_free_list = free_list_before;
1530 else
1532 total_free_strings += nfree;
1533 b->next = live_blocks;
1534 live_blocks = b;
1538 string_blocks = live_blocks;
1539 free_large_strings ();
1540 compact_small_strings ();
1544 /* Free dead large strings. */
1546 static void
1547 free_large_strings ()
1549 struct sblock *b, *next;
1550 struct sblock *live_blocks = NULL;
1552 for (b = large_sblocks; b; b = next)
1554 next = b->next;
1556 if (b->first_data.string == NULL)
1557 lisp_free (b);
1558 else
1560 b->next = live_blocks;
1561 live_blocks = b;
1565 large_sblocks = live_blocks;
1569 /* Compact data of small strings. Free sblocks that don't contain
1570 data of live strings after compaction. */
1572 static void
1573 compact_small_strings ()
1575 struct sblock *b, *tb, *next;
1576 struct sdata *from, *to, *end, *tb_end;
1577 struct sdata *to_end, *from_end;
1579 /* TB is the sblock we copy to, TO is the sdata within TB we copy
1580 to, and TB_END is the end of TB. */
1581 tb = oldest_sblock;
1582 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1583 to = &tb->first_data;
1585 /* Step through the blocks from the oldest to the youngest. We
1586 expect that old blocks will stabilize over time, so that less
1587 copying will happen this way. */
1588 for (b = oldest_sblock; b; b = b->next)
1590 end = b->next_free;
1591 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
1593 for (from = &b->first_data; from < end; from = from_end)
1595 /* Compute the next FROM here because copying below may
1596 overwrite data we need to compute it. */
1597 int nbytes;
1599 #ifdef GC_CHECK_STRING_BYTES
1600 /* Check that the string size recorded in the string is the
1601 same as the one recorded in the sdata structure. */
1602 if (from->string
1603 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
1604 abort ();
1605 #endif /* GC_CHECK_STRING_BYTES */
1607 if (from->string)
1608 nbytes = GC_STRING_BYTES (from->string);
1609 else
1610 nbytes = SDATA_NBYTES (from);
1612 nbytes = SDATA_SIZE (nbytes);
1613 from_end = (struct sdata *) ((char *) from + nbytes);
1615 /* FROM->string non-null means it's alive. Copy its data. */
1616 if (from->string)
1618 /* If TB is full, proceed with the next sblock. */
1619 to_end = (struct sdata *) ((char *) to + nbytes);
1620 if (to_end > tb_end)
1622 tb->next_free = to;
1623 tb = tb->next;
1624 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1625 to = &tb->first_data;
1626 to_end = (struct sdata *) ((char *) to + nbytes);
1629 /* Copy, and update the string's `data' pointer. */
1630 if (from != to)
1632 xassert (tb != b || to <= from);
1633 safe_bcopy ((char *) from, (char *) to, nbytes);
1634 to->string->data = SDATA_DATA (to);
1637 /* Advance past the sdata we copied to. */
1638 to = to_end;
1643 /* The rest of the sblocks following TB don't contain live data, so
1644 we can free them. */
1645 for (b = tb->next; b; b = next)
1647 next = b->next;
1648 lisp_free (b);
1651 tb->next_free = to;
1652 tb->next = NULL;
1653 current_sblock = tb;
1657 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
1658 "Return a newly created string of length LENGTH, with each element being INIT.\n\
1659 Both LENGTH and INIT must be numbers.")
1660 (length, init)
1661 Lisp_Object length, init;
1663 register Lisp_Object val;
1664 register unsigned char *p, *end;
1665 int c, nbytes;
1667 CHECK_NATNUM (length, 0);
1668 CHECK_NUMBER (init, 1);
1670 c = XINT (init);
1671 if (SINGLE_BYTE_CHAR_P (c))
1673 nbytes = XINT (length);
1674 val = make_uninit_string (nbytes);
1675 p = XSTRING (val)->data;
1676 end = p + XSTRING (val)->size;
1677 while (p != end)
1678 *p++ = c;
1680 else
1682 unsigned char str[MAX_MULTIBYTE_LENGTH];
1683 int len = CHAR_STRING (c, str);
1685 nbytes = len * XINT (length);
1686 val = make_uninit_multibyte_string (XINT (length), nbytes);
1687 p = XSTRING (val)->data;
1688 end = p + nbytes;
1689 while (p != end)
1691 bcopy (str, p, len);
1692 p += len;
1696 *p = 0;
1697 return val;
1701 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
1702 "Return a new bool-vector of length LENGTH, using INIT for as each element.\n\
1703 LENGTH must be a number. INIT matters only in whether it is t or nil.")
1704 (length, init)
1705 Lisp_Object length, init;
1707 register Lisp_Object val;
1708 struct Lisp_Bool_Vector *p;
1709 int real_init, i;
1710 int length_in_chars, length_in_elts, bits_per_value;
1712 CHECK_NATNUM (length, 0);
1714 bits_per_value = sizeof (EMACS_INT) * BITS_PER_CHAR;
1716 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
1717 length_in_chars = ((XFASTINT (length) + BITS_PER_CHAR - 1) / BITS_PER_CHAR);
1719 /* We must allocate one more elements than LENGTH_IN_ELTS for the
1720 slot `size' of the struct Lisp_Bool_Vector. */
1721 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
1722 p = XBOOL_VECTOR (val);
1724 /* Get rid of any bits that would cause confusion. */
1725 p->vector_size = 0;
1726 XSETBOOL_VECTOR (val, p);
1727 p->size = XFASTINT (length);
1729 real_init = (NILP (init) ? 0 : -1);
1730 for (i = 0; i < length_in_chars ; i++)
1731 p->data[i] = real_init;
1733 /* Clear the extraneous bits in the last byte. */
1734 if (XINT (length) != length_in_chars * BITS_PER_CHAR)
1735 XBOOL_VECTOR (val)->data[length_in_chars - 1]
1736 &= (1 << (XINT (length) % BITS_PER_CHAR)) - 1;
1738 return val;
1742 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
1743 of characters from the contents. This string may be unibyte or
1744 multibyte, depending on the contents. */
1746 Lisp_Object
1747 make_string (contents, nbytes)
1748 char *contents;
1749 int nbytes;
1751 register Lisp_Object val;
1752 int nchars, multibyte_nbytes;
1754 parse_str_as_multibyte (contents, nbytes, &nchars, &multibyte_nbytes);
1755 if (nbytes == nchars || nbytes != multibyte_nbytes)
1756 /* CONTENTS contains no multibyte sequences or contains an invalid
1757 multibyte sequence. We must make unibyte string. */
1758 val = make_unibyte_string (contents, nbytes);
1759 else
1760 val = make_multibyte_string (contents, nchars, nbytes);
1761 return val;
1765 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
1767 Lisp_Object
1768 make_unibyte_string (contents, length)
1769 char *contents;
1770 int length;
1772 register Lisp_Object val;
1773 val = make_uninit_string (length);
1774 bcopy (contents, XSTRING (val)->data, length);
1775 SET_STRING_BYTES (XSTRING (val), -1);
1776 return val;
1780 /* Make a multibyte string from NCHARS characters occupying NBYTES
1781 bytes at CONTENTS. */
1783 Lisp_Object
1784 make_multibyte_string (contents, nchars, nbytes)
1785 char *contents;
1786 int nchars, nbytes;
1788 register Lisp_Object val;
1789 val = make_uninit_multibyte_string (nchars, nbytes);
1790 bcopy (contents, XSTRING (val)->data, nbytes);
1791 return val;
1795 /* Make a string from NCHARS characters occupying NBYTES bytes at
1796 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
1798 Lisp_Object
1799 make_string_from_bytes (contents, nchars, nbytes)
1800 char *contents;
1801 int nchars, nbytes;
1803 register Lisp_Object val;
1804 val = make_uninit_multibyte_string (nchars, nbytes);
1805 bcopy (contents, XSTRING (val)->data, nbytes);
1806 if (STRING_BYTES (XSTRING (val)) == XSTRING (val)->size)
1807 SET_STRING_BYTES (XSTRING (val), -1);
1808 return val;
1812 /* Make a string from NCHARS characters occupying NBYTES bytes at
1813 CONTENTS. The argument MULTIBYTE controls whether to label the
1814 string as multibyte. */
1816 Lisp_Object
1817 make_specified_string (contents, nchars, nbytes, multibyte)
1818 char *contents;
1819 int nchars, nbytes;
1820 int multibyte;
1822 register Lisp_Object val;
1823 val = make_uninit_multibyte_string (nchars, nbytes);
1824 bcopy (contents, XSTRING (val)->data, nbytes);
1825 if (!multibyte)
1826 SET_STRING_BYTES (XSTRING (val), -1);
1827 return val;
1831 /* Make a string from the data at STR, treating it as multibyte if the
1832 data warrants. */
1834 Lisp_Object
1835 build_string (str)
1836 char *str;
1838 return make_string (str, strlen (str));
1842 /* Return an unibyte Lisp_String set up to hold LENGTH characters
1843 occupying LENGTH bytes. */
1845 Lisp_Object
1846 make_uninit_string (length)
1847 int length;
1849 Lisp_Object val;
1850 val = make_uninit_multibyte_string (length, length);
1851 SET_STRING_BYTES (XSTRING (val), -1);
1852 return val;
1856 /* Return a multibyte Lisp_String set up to hold NCHARS characters
1857 which occupy NBYTES bytes. */
1859 Lisp_Object
1860 make_uninit_multibyte_string (nchars, nbytes)
1861 int nchars, nbytes;
1863 Lisp_Object string;
1864 struct Lisp_String *s;
1866 if (nchars < 0)
1867 abort ();
1869 s = allocate_string ();
1870 allocate_string_data (s, nchars, nbytes);
1871 XSETSTRING (string, s);
1872 string_chars_consed += nbytes;
1873 return string;
1878 /***********************************************************************
1879 Float Allocation
1880 ***********************************************************************/
1882 /* We store float cells inside of float_blocks, allocating a new
1883 float_block with malloc whenever necessary. Float cells reclaimed
1884 by GC are put on a free list to be reallocated before allocating
1885 any new float cells from the latest float_block.
1887 Each float_block is just under 1020 bytes long, since malloc really
1888 allocates in units of powers of two and uses 4 bytes for its own
1889 overhead. */
1891 #define FLOAT_BLOCK_SIZE \
1892 ((1020 - sizeof (struct float_block *)) / sizeof (struct Lisp_Float))
1894 struct float_block
1896 struct float_block *next;
1897 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
1900 /* Current float_block. */
1902 struct float_block *float_block;
1904 /* Index of first unused Lisp_Float in the current float_block. */
1906 int float_block_index;
1908 /* Total number of float blocks now in use. */
1910 int n_float_blocks;
1912 /* Free-list of Lisp_Floats. */
1914 struct Lisp_Float *float_free_list;
1917 /* Initialze float allocation. */
1919 void
1920 init_float ()
1922 float_block = (struct float_block *) lisp_malloc (sizeof *float_block,
1923 MEM_TYPE_FLOAT);
1924 float_block->next = 0;
1925 bzero ((char *) float_block->floats, sizeof float_block->floats);
1926 float_block_index = 0;
1927 float_free_list = 0;
1928 n_float_blocks = 1;
1932 /* Explicitly free a float cell by putting it on the free-list. */
1934 void
1935 free_float (ptr)
1936 struct Lisp_Float *ptr;
1938 *(struct Lisp_Float **)&ptr->data = float_free_list;
1939 #if GC_MARK_STACK
1940 ptr->type = Vdead;
1941 #endif
1942 float_free_list = ptr;
1946 /* Return a new float object with value FLOAT_VALUE. */
1948 Lisp_Object
1949 make_float (float_value)
1950 double float_value;
1952 register Lisp_Object val;
1954 if (float_free_list)
1956 /* We use the data field for chaining the free list
1957 so that we won't use the same field that has the mark bit. */
1958 XSETFLOAT (val, float_free_list);
1959 float_free_list = *(struct Lisp_Float **)&float_free_list->data;
1961 else
1963 if (float_block_index == FLOAT_BLOCK_SIZE)
1965 register struct float_block *new;
1967 new = (struct float_block *) lisp_malloc (sizeof *new,
1968 MEM_TYPE_FLOAT);
1969 VALIDATE_LISP_STORAGE (new, sizeof *new);
1970 new->next = float_block;
1971 float_block = new;
1972 float_block_index = 0;
1973 n_float_blocks++;
1975 XSETFLOAT (val, &float_block->floats[float_block_index++]);
1978 XFLOAT_DATA (val) = float_value;
1979 XSETFASTINT (XFLOAT (val)->type, 0); /* bug chasing -wsr */
1980 consing_since_gc += sizeof (struct Lisp_Float);
1981 floats_consed++;
1982 return val;
1987 /***********************************************************************
1988 Cons Allocation
1989 ***********************************************************************/
1991 /* We store cons cells inside of cons_blocks, allocating a new
1992 cons_block with malloc whenever necessary. Cons cells reclaimed by
1993 GC are put on a free list to be reallocated before allocating
1994 any new cons cells from the latest cons_block.
1996 Each cons_block is just under 1020 bytes long,
1997 since malloc really allocates in units of powers of two
1998 and uses 4 bytes for its own overhead. */
2000 #define CONS_BLOCK_SIZE \
2001 ((1020 - sizeof (struct cons_block *)) / sizeof (struct Lisp_Cons))
2003 struct cons_block
2005 struct cons_block *next;
2006 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2009 /* Current cons_block. */
2011 struct cons_block *cons_block;
2013 /* Index of first unused Lisp_Cons in the current block. */
2015 int cons_block_index;
2017 /* Free-list of Lisp_Cons structures. */
2019 struct Lisp_Cons *cons_free_list;
2021 /* Total number of cons blocks now in use. */
2023 int n_cons_blocks;
2026 /* Initialize cons allocation. */
2028 void
2029 init_cons ()
2031 cons_block = (struct cons_block *) lisp_malloc (sizeof *cons_block,
2032 MEM_TYPE_CONS);
2033 cons_block->next = 0;
2034 bzero ((char *) cons_block->conses, sizeof cons_block->conses);
2035 cons_block_index = 0;
2036 cons_free_list = 0;
2037 n_cons_blocks = 1;
2041 /* Explicitly free a cons cell by putting it on the free-list. */
2043 void
2044 free_cons (ptr)
2045 struct Lisp_Cons *ptr;
2047 *(struct Lisp_Cons **)&ptr->cdr = cons_free_list;
2048 #if GC_MARK_STACK
2049 ptr->car = Vdead;
2050 #endif
2051 cons_free_list = ptr;
2055 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2056 "Create a new cons, give it CAR and CDR as components, and return it.")
2057 (car, cdr)
2058 Lisp_Object car, cdr;
2060 register Lisp_Object val;
2062 if (cons_free_list)
2064 /* We use the cdr for chaining the free list
2065 so that we won't use the same field that has the mark bit. */
2066 XSETCONS (val, cons_free_list);
2067 cons_free_list = *(struct Lisp_Cons **)&cons_free_list->cdr;
2069 else
2071 if (cons_block_index == CONS_BLOCK_SIZE)
2073 register struct cons_block *new;
2074 new = (struct cons_block *) lisp_malloc (sizeof *new,
2075 MEM_TYPE_CONS);
2076 VALIDATE_LISP_STORAGE (new, sizeof *new);
2077 new->next = cons_block;
2078 cons_block = new;
2079 cons_block_index = 0;
2080 n_cons_blocks++;
2082 XSETCONS (val, &cons_block->conses[cons_block_index++]);
2085 XCAR (val) = car;
2086 XCDR (val) = cdr;
2087 consing_since_gc += sizeof (struct Lisp_Cons);
2088 cons_cells_consed++;
2089 return val;
2093 /* Make a list of 2, 3, 4 or 5 specified objects. */
2095 Lisp_Object
2096 list2 (arg1, arg2)
2097 Lisp_Object arg1, arg2;
2099 return Fcons (arg1, Fcons (arg2, Qnil));
2103 Lisp_Object
2104 list3 (arg1, arg2, arg3)
2105 Lisp_Object arg1, arg2, arg3;
2107 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2111 Lisp_Object
2112 list4 (arg1, arg2, arg3, arg4)
2113 Lisp_Object arg1, arg2, arg3, arg4;
2115 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2119 Lisp_Object
2120 list5 (arg1, arg2, arg3, arg4, arg5)
2121 Lisp_Object arg1, arg2, arg3, arg4, arg5;
2123 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2124 Fcons (arg5, Qnil)))));
2128 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2129 "Return a newly created list with specified arguments as elements.\n\
2130 Any number of arguments, even zero arguments, are allowed.")
2131 (nargs, args)
2132 int nargs;
2133 register Lisp_Object *args;
2135 register Lisp_Object val;
2136 val = Qnil;
2138 while (nargs > 0)
2140 nargs--;
2141 val = Fcons (args[nargs], val);
2143 return val;
2147 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2148 "Return a newly created list of length LENGTH, with each element being INIT.")
2149 (length, init)
2150 register Lisp_Object length, init;
2152 register Lisp_Object val;
2153 register int size;
2155 CHECK_NATNUM (length, 0);
2156 size = XFASTINT (length);
2158 val = Qnil;
2159 while (size > 0)
2161 val = Fcons (init, val);
2162 --size;
2164 if (size > 0)
2166 val = Fcons (init, val);
2167 --size;
2169 if (size > 0)
2171 val = Fcons (init, val);
2172 --size;
2174 if (size > 0)
2176 val = Fcons (init, val);
2177 --size;
2179 if (size > 0)
2181 val = Fcons (init, val);
2182 --size;
2188 QUIT;
2191 return val;
2196 /***********************************************************************
2197 Vector Allocation
2198 ***********************************************************************/
2200 /* Singly-linked list of all vectors. */
2202 struct Lisp_Vector *all_vectors;
2204 /* Total number of vector-like objects now in use. */
2206 int n_vectors;
2209 /* Value is a pointer to a newly allocated Lisp_Vector structure
2210 with room for LEN Lisp_Objects. */
2212 static struct Lisp_Vector *
2213 allocate_vectorlike (len, type)
2214 EMACS_INT len;
2215 enum mem_type type;
2217 struct Lisp_Vector *p;
2218 size_t nbytes;
2220 #ifdef DOUG_LEA_MALLOC
2221 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2222 because mapped region contents are not preserved in
2223 a dumped Emacs. */
2224 mallopt (M_MMAP_MAX, 0);
2225 #endif
2227 nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
2228 p = (struct Lisp_Vector *) lisp_malloc (nbytes, type);
2230 #ifdef DOUG_LEA_MALLOC
2231 /* Back to a reasonable maximum of mmap'ed areas. */
2232 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2233 #endif
2235 VALIDATE_LISP_STORAGE (p, 0);
2236 consing_since_gc += nbytes;
2237 vector_cells_consed += len;
2239 p->next = all_vectors;
2240 all_vectors = p;
2241 ++n_vectors;
2242 return p;
2246 /* Allocate a vector with NSLOTS slots. */
2248 struct Lisp_Vector *
2249 allocate_vector (nslots)
2250 EMACS_INT nslots;
2252 struct Lisp_Vector *v = allocate_vectorlike (nslots, MEM_TYPE_VECTOR);
2253 v->size = nslots;
2254 return v;
2258 /* Allocate other vector-like structures. */
2260 struct Lisp_Hash_Table *
2261 allocate_hash_table ()
2263 EMACS_INT len = VECSIZE (struct Lisp_Hash_Table);
2264 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_HASH_TABLE);
2265 EMACS_INT i;
2267 v->size = len;
2268 for (i = 0; i < len; ++i)
2269 v->contents[i] = Qnil;
2271 return (struct Lisp_Hash_Table *) v;
2275 struct window *
2276 allocate_window ()
2278 EMACS_INT len = VECSIZE (struct window);
2279 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_WINDOW);
2280 EMACS_INT i;
2282 for (i = 0; i < len; ++i)
2283 v->contents[i] = Qnil;
2284 v->size = len;
2286 return (struct window *) v;
2290 struct frame *
2291 allocate_frame ()
2293 EMACS_INT len = VECSIZE (struct frame);
2294 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_FRAME);
2295 EMACS_INT i;
2297 for (i = 0; i < len; ++i)
2298 v->contents[i] = make_number (0);
2299 v->size = len;
2300 return (struct frame *) v;
2304 struct Lisp_Process *
2305 allocate_process ()
2307 EMACS_INT len = VECSIZE (struct Lisp_Process);
2308 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_PROCESS);
2309 EMACS_INT i;
2311 for (i = 0; i < len; ++i)
2312 v->contents[i] = Qnil;
2313 v->size = len;
2315 return (struct Lisp_Process *) v;
2319 struct Lisp_Vector *
2320 allocate_other_vector (len)
2321 EMACS_INT len;
2323 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_VECTOR);
2324 EMACS_INT i;
2326 for (i = 0; i < len; ++i)
2327 v->contents[i] = Qnil;
2328 v->size = len;
2330 return v;
2334 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
2335 "Return a newly created vector of length LENGTH, with each element being INIT.\n\
2336 See also the function `vector'.")
2337 (length, init)
2338 register Lisp_Object length, init;
2340 Lisp_Object vector;
2341 register EMACS_INT sizei;
2342 register int index;
2343 register struct Lisp_Vector *p;
2345 CHECK_NATNUM (length, 0);
2346 sizei = XFASTINT (length);
2348 p = allocate_vector (sizei);
2349 for (index = 0; index < sizei; index++)
2350 p->contents[index] = init;
2352 XSETVECTOR (vector, p);
2353 return vector;
2357 DEFUN ("make-char-table", Fmake_char_table, Smake_char_table, 1, 2, 0,
2358 "Return a newly created char-table, with purpose PURPOSE.\n\
2359 Each element is initialized to INIT, which defaults to nil.\n\
2360 PURPOSE should be a symbol which has a `char-table-extra-slots' property.\n\
2361 The property's value should be an integer between 0 and 10.")
2362 (purpose, init)
2363 register Lisp_Object purpose, init;
2365 Lisp_Object vector;
2366 Lisp_Object n;
2367 CHECK_SYMBOL (purpose, 1);
2368 n = Fget (purpose, Qchar_table_extra_slots);
2369 CHECK_NUMBER (n, 0);
2370 if (XINT (n) < 0 || XINT (n) > 10)
2371 args_out_of_range (n, Qnil);
2372 /* Add 2 to the size for the defalt and parent slots. */
2373 vector = Fmake_vector (make_number (CHAR_TABLE_STANDARD_SLOTS + XINT (n)),
2374 init);
2375 XCHAR_TABLE (vector)->top = Qt;
2376 XCHAR_TABLE (vector)->parent = Qnil;
2377 XCHAR_TABLE (vector)->purpose = purpose;
2378 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
2379 return vector;
2383 /* Return a newly created sub char table with default value DEFALT.
2384 Since a sub char table does not appear as a top level Emacs Lisp
2385 object, we don't need a Lisp interface to make it. */
2387 Lisp_Object
2388 make_sub_char_table (defalt)
2389 Lisp_Object defalt;
2391 Lisp_Object vector
2392 = Fmake_vector (make_number (SUB_CHAR_TABLE_STANDARD_SLOTS), Qnil);
2393 XCHAR_TABLE (vector)->top = Qnil;
2394 XCHAR_TABLE (vector)->defalt = defalt;
2395 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
2396 return vector;
2400 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
2401 "Return a newly created vector with specified arguments as elements.\n\
2402 Any number of arguments, even zero arguments, are allowed.")
2403 (nargs, args)
2404 register int nargs;
2405 Lisp_Object *args;
2407 register Lisp_Object len, val;
2408 register int index;
2409 register struct Lisp_Vector *p;
2411 XSETFASTINT (len, nargs);
2412 val = Fmake_vector (len, Qnil);
2413 p = XVECTOR (val);
2414 for (index = 0; index < nargs; index++)
2415 p->contents[index] = args[index];
2416 return val;
2420 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
2421 "Create a byte-code object with specified arguments as elements.\n\
2422 The arguments should be the arglist, bytecode-string, constant vector,\n\
2423 stack size, (optional) doc string, and (optional) interactive spec.\n\
2424 The first four arguments are required; at most six have any\n\
2425 significance.")
2426 (nargs, args)
2427 register int nargs;
2428 Lisp_Object *args;
2430 register Lisp_Object len, val;
2431 register int index;
2432 register struct Lisp_Vector *p;
2434 XSETFASTINT (len, nargs);
2435 if (!NILP (Vpurify_flag))
2436 val = make_pure_vector ((EMACS_INT) nargs);
2437 else
2438 val = Fmake_vector (len, Qnil);
2440 if (STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
2441 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
2442 earlier because they produced a raw 8-bit string for byte-code
2443 and now such a byte-code string is loaded as multibyte while
2444 raw 8-bit characters converted to multibyte form. Thus, now we
2445 must convert them back to the original unibyte form. */
2446 args[1] = Fstring_as_unibyte (args[1]);
2448 p = XVECTOR (val);
2449 for (index = 0; index < nargs; index++)
2451 if (!NILP (Vpurify_flag))
2452 args[index] = Fpurecopy (args[index]);
2453 p->contents[index] = args[index];
2455 XSETCOMPILED (val, p);
2456 return val;
2461 /***********************************************************************
2462 Symbol Allocation
2463 ***********************************************************************/
2465 /* Each symbol_block is just under 1020 bytes long, since malloc
2466 really allocates in units of powers of two and uses 4 bytes for its
2467 own overhead. */
2469 #define SYMBOL_BLOCK_SIZE \
2470 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
2472 struct symbol_block
2474 struct symbol_block *next;
2475 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
2478 /* Current symbol block and index of first unused Lisp_Symbol
2479 structure in it. */
2481 struct symbol_block *symbol_block;
2482 int symbol_block_index;
2484 /* List of free symbols. */
2486 struct Lisp_Symbol *symbol_free_list;
2488 /* Total number of symbol blocks now in use. */
2490 int n_symbol_blocks;
2493 /* Initialize symbol allocation. */
2495 void
2496 init_symbol ()
2498 symbol_block = (struct symbol_block *) lisp_malloc (sizeof *symbol_block,
2499 MEM_TYPE_SYMBOL);
2500 symbol_block->next = 0;
2501 bzero ((char *) symbol_block->symbols, sizeof symbol_block->symbols);
2502 symbol_block_index = 0;
2503 symbol_free_list = 0;
2504 n_symbol_blocks = 1;
2508 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
2509 "Return a newly allocated uninterned symbol whose name is NAME.\n\
2510 Its value and function definition are void, and its property list is nil.")
2511 (name)
2512 Lisp_Object name;
2514 register Lisp_Object val;
2515 register struct Lisp_Symbol *p;
2517 CHECK_STRING (name, 0);
2519 if (symbol_free_list)
2521 XSETSYMBOL (val, symbol_free_list);
2522 symbol_free_list = *(struct Lisp_Symbol **)&symbol_free_list->value;
2524 else
2526 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
2528 struct symbol_block *new;
2529 new = (struct symbol_block *) lisp_malloc (sizeof *new,
2530 MEM_TYPE_SYMBOL);
2531 VALIDATE_LISP_STORAGE (new, sizeof *new);
2532 new->next = symbol_block;
2533 symbol_block = new;
2534 symbol_block_index = 0;
2535 n_symbol_blocks++;
2537 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index++]);
2540 p = XSYMBOL (val);
2541 p->name = XSTRING (name);
2542 p->obarray = Qnil;
2543 p->plist = Qnil;
2544 p->value = Qunbound;
2545 p->function = Qunbound;
2546 p->next = 0;
2547 consing_since_gc += sizeof (struct Lisp_Symbol);
2548 symbols_consed++;
2549 return val;
2554 /***********************************************************************
2555 Marker (Misc) Allocation
2556 ***********************************************************************/
2558 /* Allocation of markers and other objects that share that structure.
2559 Works like allocation of conses. */
2561 #define MARKER_BLOCK_SIZE \
2562 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
2564 struct marker_block
2566 struct marker_block *next;
2567 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
2570 struct marker_block *marker_block;
2571 int marker_block_index;
2573 union Lisp_Misc *marker_free_list;
2575 /* Total number of marker blocks now in use. */
2577 int n_marker_blocks;
2579 void
2580 init_marker ()
2582 marker_block = (struct marker_block *) lisp_malloc (sizeof *marker_block,
2583 MEM_TYPE_MISC);
2584 marker_block->next = 0;
2585 bzero ((char *) marker_block->markers, sizeof marker_block->markers);
2586 marker_block_index = 0;
2587 marker_free_list = 0;
2588 n_marker_blocks = 1;
2591 /* Return a newly allocated Lisp_Misc object, with no substructure. */
2593 Lisp_Object
2594 allocate_misc ()
2596 Lisp_Object val;
2598 if (marker_free_list)
2600 XSETMISC (val, marker_free_list);
2601 marker_free_list = marker_free_list->u_free.chain;
2603 else
2605 if (marker_block_index == MARKER_BLOCK_SIZE)
2607 struct marker_block *new;
2608 new = (struct marker_block *) lisp_malloc (sizeof *new,
2609 MEM_TYPE_MISC);
2610 VALIDATE_LISP_STORAGE (new, sizeof *new);
2611 new->next = marker_block;
2612 marker_block = new;
2613 marker_block_index = 0;
2614 n_marker_blocks++;
2616 XSETMISC (val, &marker_block->markers[marker_block_index++]);
2619 consing_since_gc += sizeof (union Lisp_Misc);
2620 misc_objects_consed++;
2621 return val;
2624 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
2625 "Return a newly allocated marker which does not point at any place.")
2628 register Lisp_Object val;
2629 register struct Lisp_Marker *p;
2631 val = allocate_misc ();
2632 XMISCTYPE (val) = Lisp_Misc_Marker;
2633 p = XMARKER (val);
2634 p->buffer = 0;
2635 p->bytepos = 0;
2636 p->charpos = 0;
2637 p->chain = Qnil;
2638 p->insertion_type = 0;
2639 return val;
2642 /* Put MARKER back on the free list after using it temporarily. */
2644 void
2645 free_marker (marker)
2646 Lisp_Object marker;
2648 unchain_marker (marker);
2650 XMISC (marker)->u_marker.type = Lisp_Misc_Free;
2651 XMISC (marker)->u_free.chain = marker_free_list;
2652 marker_free_list = XMISC (marker);
2654 total_free_markers++;
2658 /* Return a newly created vector or string with specified arguments as
2659 elements. If all the arguments are characters that can fit
2660 in a string of events, make a string; otherwise, make a vector.
2662 Any number of arguments, even zero arguments, are allowed. */
2664 Lisp_Object
2665 make_event_array (nargs, args)
2666 register int nargs;
2667 Lisp_Object *args;
2669 int i;
2671 for (i = 0; i < nargs; i++)
2672 /* The things that fit in a string
2673 are characters that are in 0...127,
2674 after discarding the meta bit and all the bits above it. */
2675 if (!INTEGERP (args[i])
2676 || (XUINT (args[i]) & ~(-CHAR_META)) >= 0200)
2677 return Fvector (nargs, args);
2679 /* Since the loop exited, we know that all the things in it are
2680 characters, so we can make a string. */
2682 Lisp_Object result;
2684 result = Fmake_string (make_number (nargs), make_number (0));
2685 for (i = 0; i < nargs; i++)
2687 XSTRING (result)->data[i] = XINT (args[i]);
2688 /* Move the meta bit to the right place for a string char. */
2689 if (XINT (args[i]) & CHAR_META)
2690 XSTRING (result)->data[i] |= 0x80;
2693 return result;
2699 /************************************************************************
2700 C Stack Marking
2701 ************************************************************************/
2703 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
2705 /* Initialize this part of alloc.c. */
2707 static void
2708 mem_init ()
2710 mem_z.left = mem_z.right = MEM_NIL;
2711 mem_z.parent = NULL;
2712 mem_z.color = MEM_BLACK;
2713 mem_z.start = mem_z.end = NULL;
2714 mem_root = MEM_NIL;
2718 /* Value is a pointer to the mem_node containing START. Value is
2719 MEM_NIL if there is no node in the tree containing START. */
2721 static INLINE struct mem_node *
2722 mem_find (start)
2723 void *start;
2725 struct mem_node *p;
2727 if (start < min_heap_address || start > max_heap_address)
2728 return MEM_NIL;
2730 /* Make the search always successful to speed up the loop below. */
2731 mem_z.start = start;
2732 mem_z.end = (char *) start + 1;
2734 p = mem_root;
2735 while (start < p->start || start >= p->end)
2736 p = start < p->start ? p->left : p->right;
2737 return p;
2741 /* Insert a new node into the tree for a block of memory with start
2742 address START, end address END, and type TYPE. Value is a
2743 pointer to the node that was inserted. */
2745 static struct mem_node *
2746 mem_insert (start, end, type)
2747 void *start, *end;
2748 enum mem_type type;
2750 struct mem_node *c, *parent, *x;
2752 if (start < min_heap_address)
2753 min_heap_address = start;
2754 if (end > max_heap_address)
2755 max_heap_address = end;
2757 /* See where in the tree a node for START belongs. In this
2758 particular application, it shouldn't happen that a node is already
2759 present. For debugging purposes, let's check that. */
2760 c = mem_root;
2761 parent = NULL;
2763 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
2765 while (c != MEM_NIL)
2767 if (start >= c->start && start < c->end)
2768 abort ();
2769 parent = c;
2770 c = start < c->start ? c->left : c->right;
2773 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2775 while (c != MEM_NIL)
2777 parent = c;
2778 c = start < c->start ? c->left : c->right;
2781 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2783 /* Create a new node. */
2784 #ifdef GC_MALLOC_CHECK
2785 x = (struct mem_node *) _malloc_internal (sizeof *x);
2786 if (x == NULL)
2787 abort ();
2788 #else
2789 x = (struct mem_node *) xmalloc (sizeof *x);
2790 #endif
2791 x->start = start;
2792 x->end = end;
2793 x->type = type;
2794 x->parent = parent;
2795 x->left = x->right = MEM_NIL;
2796 x->color = MEM_RED;
2798 /* Insert it as child of PARENT or install it as root. */
2799 if (parent)
2801 if (start < parent->start)
2802 parent->left = x;
2803 else
2804 parent->right = x;
2806 else
2807 mem_root = x;
2809 /* Re-establish red-black tree properties. */
2810 mem_insert_fixup (x);
2812 return x;
2816 /* Re-establish the red-black properties of the tree, and thereby
2817 balance the tree, after node X has been inserted; X is always red. */
2819 static void
2820 mem_insert_fixup (x)
2821 struct mem_node *x;
2823 while (x != mem_root && x->parent->color == MEM_RED)
2825 /* X is red and its parent is red. This is a violation of
2826 red-black tree property #3. */
2828 if (x->parent == x->parent->parent->left)
2830 /* We're on the left side of our grandparent, and Y is our
2831 "uncle". */
2832 struct mem_node *y = x->parent->parent->right;
2834 if (y->color == MEM_RED)
2836 /* Uncle and parent are red but should be black because
2837 X is red. Change the colors accordingly and proceed
2838 with the grandparent. */
2839 x->parent->color = MEM_BLACK;
2840 y->color = MEM_BLACK;
2841 x->parent->parent->color = MEM_RED;
2842 x = x->parent->parent;
2844 else
2846 /* Parent and uncle have different colors; parent is
2847 red, uncle is black. */
2848 if (x == x->parent->right)
2850 x = x->parent;
2851 mem_rotate_left (x);
2854 x->parent->color = MEM_BLACK;
2855 x->parent->parent->color = MEM_RED;
2856 mem_rotate_right (x->parent->parent);
2859 else
2861 /* This is the symmetrical case of above. */
2862 struct mem_node *y = x->parent->parent->left;
2864 if (y->color == MEM_RED)
2866 x->parent->color = MEM_BLACK;
2867 y->color = MEM_BLACK;
2868 x->parent->parent->color = MEM_RED;
2869 x = x->parent->parent;
2871 else
2873 if (x == x->parent->left)
2875 x = x->parent;
2876 mem_rotate_right (x);
2879 x->parent->color = MEM_BLACK;
2880 x->parent->parent->color = MEM_RED;
2881 mem_rotate_left (x->parent->parent);
2886 /* The root may have been changed to red due to the algorithm. Set
2887 it to black so that property #5 is satisfied. */
2888 mem_root->color = MEM_BLACK;
2892 /* (x) (y)
2893 / \ / \
2894 a (y) ===> (x) c
2895 / \ / \
2896 b c a b */
2898 static void
2899 mem_rotate_left (x)
2900 struct mem_node *x;
2902 struct mem_node *y;
2904 /* Turn y's left sub-tree into x's right sub-tree. */
2905 y = x->right;
2906 x->right = y->left;
2907 if (y->left != MEM_NIL)
2908 y->left->parent = x;
2910 /* Y's parent was x's parent. */
2911 if (y != MEM_NIL)
2912 y->parent = x->parent;
2914 /* Get the parent to point to y instead of x. */
2915 if (x->parent)
2917 if (x == x->parent->left)
2918 x->parent->left = y;
2919 else
2920 x->parent->right = y;
2922 else
2923 mem_root = y;
2925 /* Put x on y's left. */
2926 y->left = x;
2927 if (x != MEM_NIL)
2928 x->parent = y;
2932 /* (x) (Y)
2933 / \ / \
2934 (y) c ===> a (x)
2935 / \ / \
2936 a b b c */
2938 static void
2939 mem_rotate_right (x)
2940 struct mem_node *x;
2942 struct mem_node *y = x->left;
2944 x->left = y->right;
2945 if (y->right != MEM_NIL)
2946 y->right->parent = x;
2948 if (y != MEM_NIL)
2949 y->parent = x->parent;
2950 if (x->parent)
2952 if (x == x->parent->right)
2953 x->parent->right = y;
2954 else
2955 x->parent->left = y;
2957 else
2958 mem_root = y;
2960 y->right = x;
2961 if (x != MEM_NIL)
2962 x->parent = y;
2966 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
2968 static void
2969 mem_delete (z)
2970 struct mem_node *z;
2972 struct mem_node *x, *y;
2974 if (!z || z == MEM_NIL)
2975 return;
2977 if (z->left == MEM_NIL || z->right == MEM_NIL)
2978 y = z;
2979 else
2981 y = z->right;
2982 while (y->left != MEM_NIL)
2983 y = y->left;
2986 if (y->left != MEM_NIL)
2987 x = y->left;
2988 else
2989 x = y->right;
2991 x->parent = y->parent;
2992 if (y->parent)
2994 if (y == y->parent->left)
2995 y->parent->left = x;
2996 else
2997 y->parent->right = x;
2999 else
3000 mem_root = x;
3002 if (y != z)
3004 z->start = y->start;
3005 z->end = y->end;
3006 z->type = y->type;
3009 if (y->color == MEM_BLACK)
3010 mem_delete_fixup (x);
3012 #ifdef GC_MALLOC_CHECK
3013 _free_internal (y);
3014 #else
3015 xfree (y);
3016 #endif
3020 /* Re-establish the red-black properties of the tree, after a
3021 deletion. */
3023 static void
3024 mem_delete_fixup (x)
3025 struct mem_node *x;
3027 while (x != mem_root && x->color == MEM_BLACK)
3029 if (x == x->parent->left)
3031 struct mem_node *w = x->parent->right;
3033 if (w->color == MEM_RED)
3035 w->color = MEM_BLACK;
3036 x->parent->color = MEM_RED;
3037 mem_rotate_left (x->parent);
3038 w = x->parent->right;
3041 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
3043 w->color = MEM_RED;
3044 x = x->parent;
3046 else
3048 if (w->right->color == MEM_BLACK)
3050 w->left->color = MEM_BLACK;
3051 w->color = MEM_RED;
3052 mem_rotate_right (w);
3053 w = x->parent->right;
3055 w->color = x->parent->color;
3056 x->parent->color = MEM_BLACK;
3057 w->right->color = MEM_BLACK;
3058 mem_rotate_left (x->parent);
3059 x = mem_root;
3062 else
3064 struct mem_node *w = x->parent->left;
3066 if (w->color == MEM_RED)
3068 w->color = MEM_BLACK;
3069 x->parent->color = MEM_RED;
3070 mem_rotate_right (x->parent);
3071 w = x->parent->left;
3074 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
3076 w->color = MEM_RED;
3077 x = x->parent;
3079 else
3081 if (w->left->color == MEM_BLACK)
3083 w->right->color = MEM_BLACK;
3084 w->color = MEM_RED;
3085 mem_rotate_left (w);
3086 w = x->parent->left;
3089 w->color = x->parent->color;
3090 x->parent->color = MEM_BLACK;
3091 w->left->color = MEM_BLACK;
3092 mem_rotate_right (x->parent);
3093 x = mem_root;
3098 x->color = MEM_BLACK;
3102 /* Value is non-zero if P is a pointer to a live Lisp string on
3103 the heap. M is a pointer to the mem_block for P. */
3105 static INLINE int
3106 live_string_p (m, p)
3107 struct mem_node *m;
3108 void *p;
3110 if (m->type == MEM_TYPE_STRING)
3112 struct string_block *b = (struct string_block *) m->start;
3113 int offset = (char *) p - (char *) &b->strings[0];
3115 /* P must point to the start of a Lisp_String structure, and it
3116 must not be on the free-list. */
3117 return (offset >= 0
3118 && offset % sizeof b->strings[0] == 0
3119 && ((struct Lisp_String *) p)->data != NULL);
3121 else
3122 return 0;
3126 /* Value is non-zero if P is a pointer to a live Lisp cons on
3127 the heap. M is a pointer to the mem_block for P. */
3129 static INLINE int
3130 live_cons_p (m, p)
3131 struct mem_node *m;
3132 void *p;
3134 if (m->type == MEM_TYPE_CONS)
3136 struct cons_block *b = (struct cons_block *) m->start;
3137 int offset = (char *) p - (char *) &b->conses[0];
3139 /* P must point to the start of a Lisp_Cons, not be
3140 one of the unused cells in the current cons block,
3141 and not be on the free-list. */
3142 return (offset >= 0
3143 && offset % sizeof b->conses[0] == 0
3144 && (b != cons_block
3145 || offset / sizeof b->conses[0] < cons_block_index)
3146 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
3148 else
3149 return 0;
3153 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3154 the heap. M is a pointer to the mem_block for P. */
3156 static INLINE int
3157 live_symbol_p (m, p)
3158 struct mem_node *m;
3159 void *p;
3161 if (m->type == MEM_TYPE_SYMBOL)
3163 struct symbol_block *b = (struct symbol_block *) m->start;
3164 int offset = (char *) p - (char *) &b->symbols[0];
3166 /* P must point to the start of a Lisp_Symbol, not be
3167 one of the unused cells in the current symbol block,
3168 and not be on the free-list. */
3169 return (offset >= 0
3170 && offset % sizeof b->symbols[0] == 0
3171 && (b != symbol_block
3172 || offset / sizeof b->symbols[0] < symbol_block_index)
3173 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
3175 else
3176 return 0;
3180 /* Value is non-zero if P is a pointer to a live Lisp float on
3181 the heap. M is a pointer to the mem_block for P. */
3183 static INLINE int
3184 live_float_p (m, p)
3185 struct mem_node *m;
3186 void *p;
3188 if (m->type == MEM_TYPE_FLOAT)
3190 struct float_block *b = (struct float_block *) m->start;
3191 int offset = (char *) p - (char *) &b->floats[0];
3193 /* P must point to the start of a Lisp_Float, not be
3194 one of the unused cells in the current float block,
3195 and not be on the free-list. */
3196 return (offset >= 0
3197 && offset % sizeof b->floats[0] == 0
3198 && (b != float_block
3199 || offset / sizeof b->floats[0] < float_block_index)
3200 && !EQ (((struct Lisp_Float *) p)->type, Vdead));
3202 else
3203 return 0;
3207 /* Value is non-zero if P is a pointer to a live Lisp Misc on
3208 the heap. M is a pointer to the mem_block for P. */
3210 static INLINE int
3211 live_misc_p (m, p)
3212 struct mem_node *m;
3213 void *p;
3215 if (m->type == MEM_TYPE_MISC)
3217 struct marker_block *b = (struct marker_block *) m->start;
3218 int offset = (char *) p - (char *) &b->markers[0];
3220 /* P must point to the start of a Lisp_Misc, not be
3221 one of the unused cells in the current misc block,
3222 and not be on the free-list. */
3223 return (offset >= 0
3224 && offset % sizeof b->markers[0] == 0
3225 && (b != marker_block
3226 || offset / sizeof b->markers[0] < marker_block_index)
3227 && ((union Lisp_Misc *) p)->u_marker.type != Lisp_Misc_Free);
3229 else
3230 return 0;
3234 /* Value is non-zero if P is a pointer to a live vector-like object.
3235 M is a pointer to the mem_block for P. */
3237 static INLINE int
3238 live_vector_p (m, p)
3239 struct mem_node *m;
3240 void *p;
3242 return (p == m->start
3243 && m->type >= MEM_TYPE_VECTOR
3244 && m->type <= MEM_TYPE_WINDOW);
3248 /* Value is non-zero of P is a pointer to a live buffer. M is a
3249 pointer to the mem_block for P. */
3251 static INLINE int
3252 live_buffer_p (m, p)
3253 struct mem_node *m;
3254 void *p;
3256 /* P must point to the start of the block, and the buffer
3257 must not have been killed. */
3258 return (m->type == MEM_TYPE_BUFFER
3259 && p == m->start
3260 && !NILP (((struct buffer *) p)->name));
3263 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
3265 #if GC_MARK_STACK
3267 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3269 /* Array of objects that are kept alive because the C stack contains
3270 a pattern that looks like a reference to them . */
3272 #define MAX_ZOMBIES 10
3273 static Lisp_Object zombies[MAX_ZOMBIES];
3275 /* Number of zombie objects. */
3277 static int nzombies;
3279 /* Number of garbage collections. */
3281 static int ngcs;
3283 /* Average percentage of zombies per collection. */
3285 static double avg_zombies;
3287 /* Max. number of live and zombie objects. */
3289 static int max_live, max_zombies;
3291 /* Average number of live objects per GC. */
3293 static double avg_live;
3295 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
3296 "Show information about live and zombie objects.")
3299 Lisp_Object args[7];
3300 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d");
3301 args[1] = make_number (ngcs);
3302 args[2] = make_float (avg_live);
3303 args[3] = make_float (avg_zombies);
3304 args[4] = make_float (avg_zombies / avg_live / 100);
3305 args[5] = make_number (max_live);
3306 args[6] = make_number (max_zombies);
3307 return Fmessage (7, args);
3310 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3313 /* Mark OBJ if we can prove it's a Lisp_Object. */
3315 static INLINE void
3316 mark_maybe_object (obj)
3317 Lisp_Object obj;
3319 void *po = (void *) XPNTR (obj);
3320 struct mem_node *m = mem_find (po);
3322 if (m != MEM_NIL)
3324 int mark_p = 0;
3326 switch (XGCTYPE (obj))
3328 case Lisp_String:
3329 mark_p = (live_string_p (m, po)
3330 && !STRING_MARKED_P ((struct Lisp_String *) po));
3331 break;
3333 case Lisp_Cons:
3334 mark_p = (live_cons_p (m, po)
3335 && !XMARKBIT (XCONS (obj)->car));
3336 break;
3338 case Lisp_Symbol:
3339 mark_p = (live_symbol_p (m, po)
3340 && !XMARKBIT (XSYMBOL (obj)->plist));
3341 break;
3343 case Lisp_Float:
3344 mark_p = (live_float_p (m, po)
3345 && !XMARKBIT (XFLOAT (obj)->type));
3346 break;
3348 case Lisp_Vectorlike:
3349 /* Note: can't check GC_BUFFERP before we know it's a
3350 buffer because checking that dereferences the pointer
3351 PO which might point anywhere. */
3352 if (live_vector_p (m, po))
3353 mark_p = (!GC_SUBRP (obj)
3354 && !(XVECTOR (obj)->size & ARRAY_MARK_FLAG));
3355 else if (live_buffer_p (m, po))
3356 mark_p = GC_BUFFERP (obj) && !XMARKBIT (XBUFFER (obj)->name);
3357 break;
3359 case Lisp_Misc:
3360 if (live_misc_p (m, po))
3362 switch (XMISCTYPE (obj))
3364 case Lisp_Misc_Marker:
3365 mark_p = !XMARKBIT (XMARKER (obj)->chain);
3366 break;
3368 case Lisp_Misc_Buffer_Local_Value:
3369 case Lisp_Misc_Some_Buffer_Local_Value:
3370 mark_p = !XMARKBIT (XBUFFER_LOCAL_VALUE (obj)->realvalue);
3371 break;
3373 case Lisp_Misc_Overlay:
3374 mark_p = !XMARKBIT (XOVERLAY (obj)->plist);
3375 break;
3378 break;
3380 case Lisp_Int:
3381 case Lisp_Type_Limit:
3382 break;
3385 if (mark_p)
3387 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3388 if (nzombies < MAX_ZOMBIES)
3389 zombies[nzombies] = *p;
3390 ++nzombies;
3391 #endif
3392 mark_object (&obj);
3398 /* If P points to Lisp data, mark that as live if it isn't already
3399 marked. */
3401 static INLINE void
3402 mark_maybe_pointer (p)
3403 void *p;
3405 struct mem_node *m;
3407 /* Quickly rule out some values which can't point to Lisp data. We
3408 assume that Lisp data is aligned on even addresses. */
3409 if ((EMACS_INT) p & 1)
3410 return;
3412 m = mem_find (p);
3413 if (m != MEM_NIL)
3415 Lisp_Object obj = Qnil;
3417 switch (m->type)
3419 case MEM_TYPE_NON_LISP:
3420 /* Nothing to do; not a pointer to Lisp memory. */
3421 break;
3423 case MEM_TYPE_BUFFER:
3424 if (live_buffer_p (m, p)
3425 && !XMARKBIT (((struct buffer *) p)->name))
3426 XSETVECTOR (obj, p);
3427 break;
3429 case MEM_TYPE_CONS:
3430 if (live_cons_p (m, p)
3431 && !XMARKBIT (((struct Lisp_Cons *) p)->car))
3432 XSETCONS (obj, p);
3433 break;
3435 case MEM_TYPE_STRING:
3436 if (live_string_p (m, p)
3437 && !STRING_MARKED_P ((struct Lisp_String *) p))
3438 XSETSTRING (obj, p);
3439 break;
3441 case MEM_TYPE_MISC:
3442 if (live_misc_p (m, p))
3444 Lisp_Object tem;
3445 XSETMISC (tem, p);
3447 switch (XMISCTYPE (tem))
3449 case Lisp_Misc_Marker:
3450 if (!XMARKBIT (XMARKER (tem)->chain))
3451 obj = tem;
3452 break;
3454 case Lisp_Misc_Buffer_Local_Value:
3455 case Lisp_Misc_Some_Buffer_Local_Value:
3456 if (!XMARKBIT (XBUFFER_LOCAL_VALUE (tem)->realvalue))
3457 obj = tem;
3458 break;
3460 case Lisp_Misc_Overlay:
3461 if (!XMARKBIT (XOVERLAY (tem)->plist))
3462 obj = tem;
3463 break;
3466 break;
3468 case MEM_TYPE_SYMBOL:
3469 if (live_symbol_p (m, p)
3470 && !XMARKBIT (((struct Lisp_Symbol *) p)->plist))
3471 XSETSYMBOL (obj, p);
3472 break;
3474 case MEM_TYPE_FLOAT:
3475 if (live_float_p (m, p)
3476 && !XMARKBIT (((struct Lisp_Float *) p)->type))
3477 XSETFLOAT (obj, p);
3478 break;
3480 case MEM_TYPE_VECTOR:
3481 case MEM_TYPE_PROCESS:
3482 case MEM_TYPE_HASH_TABLE:
3483 case MEM_TYPE_FRAME:
3484 case MEM_TYPE_WINDOW:
3485 if (live_vector_p (m, p))
3487 Lisp_Object tem;
3488 XSETVECTOR (tem, p);
3489 if (!GC_SUBRP (tem)
3490 && !(XVECTOR (tem)->size & ARRAY_MARK_FLAG))
3491 obj = tem;
3493 break;
3495 default:
3496 abort ();
3499 if (!GC_NILP (obj))
3500 mark_object (&obj);
3505 /* Mark Lisp objects referenced from the address range START..END. */
3507 static void
3508 mark_memory (start, end)
3509 void *start, *end;
3511 Lisp_Object *p;
3512 void **pp;
3514 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3515 nzombies = 0;
3516 #endif
3518 /* Make START the pointer to the start of the memory region,
3519 if it isn't already. */
3520 if (end < start)
3522 void *tem = start;
3523 start = end;
3524 end = tem;
3527 /* Mark Lisp_Objects. */
3528 for (p = (Lisp_Object *) start; (void *) p < end; ++p)
3529 mark_maybe_object (*p);
3531 /* Mark Lisp data pointed to. This is necessary because, in some
3532 situations, the C compiler optimizes Lisp objects away, so that
3533 only a pointer to them remains. Example:
3535 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
3538 Lisp_Object obj = build_string ("test");
3539 struct Lisp_String *s = XSTRING (obj);
3540 Fgarbage_collect ();
3541 fprintf (stderr, "test `%s'\n", s->data);
3542 return Qnil;
3545 Here, `obj' isn't really used, and the compiler optimizes it
3546 away. The only reference to the life string is through the
3547 pointer `s'. */
3549 for (pp = (void **) start; (void *) pp < end; ++pp)
3550 mark_maybe_pointer (*pp);
3554 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
3556 static int setjmp_tested_p, longjmps_done;
3558 #define SETJMP_WILL_LIKELY_WORK "\
3560 Emacs garbage collector has been changed to use conservative stack\n\
3561 marking. Emacs has determined that the method it uses to do the\n\
3562 marking will likely work on your system, but this isn't sure.\n\
3564 If you are a system-programmer, or can get the help of a local wizard\n\
3565 who is, please take a look at the function mark_stack in alloc.c, and\n\
3566 verify that the methods used are appropriate for your system.\n\
3568 Please mail the result to <gerd@gnu.org>.\n\
3571 #define SETJMP_WILL_NOT_WORK "\
3573 Emacs garbage collector has been changed to use conservative stack\n\
3574 marking. Emacs has determined that the default method it uses to do the\n\
3575 marking will not work on your system. We will need a system-dependent\n\
3576 solution for your system.\n\
3578 Please take a look at the function mark_stack in alloc.c, and\n\
3579 try to find a way to make it work on your system.\n\
3580 Please mail the result to <gerd@gnu.org>.\n\
3584 /* Perform a quick check if it looks like setjmp saves registers in a
3585 jmp_buf. Print a message to stderr saying so. When this test
3586 succeeds, this is _not_ a proof that setjmp is sufficient for
3587 conservative stack marking. Only the sources or a disassembly
3588 can prove that. */
3590 static void
3591 test_setjmp ()
3593 char buf[10];
3594 register int x;
3595 jmp_buf jbuf;
3596 int result = 0;
3598 /* Arrange for X to be put in a register. */
3599 sprintf (buf, "1");
3600 x = strlen (buf);
3601 x = 2 * x - 1;
3603 setjmp (jbuf);
3604 if (longjmps_done == 1)
3606 /* Came here after the longjmp at the end of the function.
3608 If x == 1, the longjmp has restored the register to its
3609 value before the setjmp, and we can hope that setjmp
3610 saves all such registers in the jmp_buf, although that
3611 isn't sure.
3613 For other values of X, either something really strange is
3614 taking place, or the setjmp just didn't save the register. */
3616 if (x == 1)
3617 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
3618 else
3620 fprintf (stderr, SETJMP_WILL_NOT_WORK);
3621 exit (1);
3625 ++longjmps_done;
3626 x = 2;
3627 if (longjmps_done == 1)
3628 longjmp (jbuf, 1);
3631 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
3634 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
3636 /* Abort if anything GCPRO'd doesn't survive the GC. */
3638 static void
3639 check_gcpros ()
3641 struct gcpro *p;
3642 int i;
3644 for (p = gcprolist; p; p = p->next)
3645 for (i = 0; i < p->nvars; ++i)
3646 if (!survives_gc_p (p->var[i]))
3647 abort ();
3650 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3652 static void
3653 dump_zombies ()
3655 int i;
3657 fprintf (stderr, "\nZombies kept alive = %d:\n", nzombies);
3658 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
3660 fprintf (stderr, " %d = ", i);
3661 debug_print (zombies[i]);
3665 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3668 /* Mark live Lisp objects on the C stack.
3670 There are several system-dependent problems to consider when
3671 porting this to new architectures:
3673 Processor Registers
3675 We have to mark Lisp objects in CPU registers that can hold local
3676 variables or are used to pass parameters.
3678 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
3679 something that either saves relevant registers on the stack, or
3680 calls mark_maybe_object passing it each register's contents.
3682 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
3683 implementation assumes that calling setjmp saves registers we need
3684 to see in a jmp_buf which itself lies on the stack. This doesn't
3685 have to be true! It must be verified for each system, possibly
3686 by taking a look at the source code of setjmp.
3688 Stack Layout
3690 Architectures differ in the way their processor stack is organized.
3691 For example, the stack might look like this
3693 +----------------+
3694 | Lisp_Object | size = 4
3695 +----------------+
3696 | something else | size = 2
3697 +----------------+
3698 | Lisp_Object | size = 4
3699 +----------------+
3700 | ... |
3702 In such a case, not every Lisp_Object will be aligned equally. To
3703 find all Lisp_Object on the stack it won't be sufficient to walk
3704 the stack in steps of 4 bytes. Instead, two passes will be
3705 necessary, one starting at the start of the stack, and a second
3706 pass starting at the start of the stack + 2. Likewise, if the
3707 minimal alignment of Lisp_Objects on the stack is 1, four passes
3708 would be necessary, each one starting with one byte more offset
3709 from the stack start.
3711 The current code assumes by default that Lisp_Objects are aligned
3712 equally on the stack. */
3714 static void
3715 mark_stack ()
3717 jmp_buf j;
3718 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
3719 void *end;
3721 /* This trick flushes the register windows so that all the state of
3722 the process is contained in the stack. */
3723 #ifdef sparc
3724 asm ("ta 3");
3725 #endif
3727 /* Save registers that we need to see on the stack. We need to see
3728 registers used to hold register variables and registers used to
3729 pass parameters. */
3730 #ifdef GC_SAVE_REGISTERS_ON_STACK
3731 GC_SAVE_REGISTERS_ON_STACK (end);
3732 #else /* not GC_SAVE_REGISTERS_ON_STACK */
3734 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
3735 setjmp will definitely work, test it
3736 and print a message with the result
3737 of the test. */
3738 if (!setjmp_tested_p)
3740 setjmp_tested_p = 1;
3741 test_setjmp ();
3743 #endif /* GC_SETJMP_WORKS */
3745 setjmp (j);
3746 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
3747 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
3749 /* This assumes that the stack is a contiguous region in memory. If
3750 that's not the case, something has to be done here to iterate
3751 over the stack segments. */
3752 #if GC_LISP_OBJECT_ALIGNMENT == 1
3753 mark_memory (stack_base, end);
3754 mark_memory ((char *) stack_base + 1, end);
3755 mark_memory ((char *) stack_base + 2, end);
3756 mark_memory ((char *) stack_base + 3, end);
3757 #elif GC_LISP_OBJECT_ALIGNMENT == 2
3758 mark_memory (stack_base, end);
3759 mark_memory ((char *) stack_base + 2, end);
3760 #else
3761 mark_memory (stack_base, end);
3762 #endif
3764 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
3765 check_gcpros ();
3766 #endif
3770 #endif /* GC_MARK_STACK != 0 */
3774 /***********************************************************************
3775 Pure Storage Management
3776 ***********************************************************************/
3778 /* Allocate room for SIZE bytes from pure Lisp storage and return a
3779 pointer to it. TYPE is the Lisp type for which the memory is
3780 allocated. TYPE < 0 means it's not used for a Lisp object.
3782 If store_pure_type_info is set and TYPE is >= 0, the type of
3783 the allocated object is recorded in pure_types. */
3785 static POINTER_TYPE *
3786 pure_alloc (size, type)
3787 size_t size;
3788 int type;
3790 size_t nbytes;
3791 POINTER_TYPE *result;
3792 char *beg = PUREBEG;
3794 /* Give Lisp_Floats an extra alignment. */
3795 if (type == Lisp_Float)
3797 size_t alignment;
3798 #if defined __GNUC__ && __GNUC__ >= 2
3799 alignment = __alignof (struct Lisp_Float);
3800 #else
3801 alignment = sizeof (struct Lisp_Float);
3802 #endif
3803 pure_bytes_used = ALIGN (pure_bytes_used, alignment);
3806 nbytes = ALIGN (size, sizeof (EMACS_INT));
3807 if (pure_bytes_used + nbytes > PURESIZE)
3808 error ("Pure Lisp storage exhausted");
3810 result = (POINTER_TYPE *) (beg + pure_bytes_used);
3811 pure_bytes_used += nbytes;
3812 return result;
3816 /* Return a string allocated in pure space. DATA is a buffer holding
3817 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
3818 non-zero means make the result string multibyte.
3820 Must get an error if pure storage is full, since if it cannot hold
3821 a large string it may be able to hold conses that point to that
3822 string; then the string is not protected from gc. */
3824 Lisp_Object
3825 make_pure_string (data, nchars, nbytes, multibyte)
3826 char *data;
3827 int nchars, nbytes;
3828 int multibyte;
3830 Lisp_Object string;
3831 struct Lisp_String *s;
3833 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
3834 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
3835 s->size = nchars;
3836 s->size_byte = multibyte ? nbytes : -1;
3837 bcopy (data, s->data, nbytes);
3838 s->data[nbytes] = '\0';
3839 s->intervals = NULL_INTERVAL;
3840 XSETSTRING (string, s);
3841 return string;
3845 /* Return a cons allocated from pure space. Give it pure copies
3846 of CAR as car and CDR as cdr. */
3848 Lisp_Object
3849 pure_cons (car, cdr)
3850 Lisp_Object car, cdr;
3852 register Lisp_Object new;
3853 struct Lisp_Cons *p;
3855 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
3856 XSETCONS (new, p);
3857 XCAR (new) = Fpurecopy (car);
3858 XCDR (new) = Fpurecopy (cdr);
3859 return new;
3863 /* Value is a float object with value NUM allocated from pure space. */
3865 Lisp_Object
3866 make_pure_float (num)
3867 double num;
3869 register Lisp_Object new;
3870 struct Lisp_Float *p;
3872 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
3873 XSETFLOAT (new, p);
3874 XFLOAT_DATA (new) = num;
3875 return new;
3879 /* Return a vector with room for LEN Lisp_Objects allocated from
3880 pure space. */
3882 Lisp_Object
3883 make_pure_vector (len)
3884 EMACS_INT len;
3886 Lisp_Object new;
3887 struct Lisp_Vector *p;
3888 size_t size = sizeof *p + (len - 1) * sizeof (Lisp_Object);
3890 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
3891 XSETVECTOR (new, p);
3892 XVECTOR (new)->size = len;
3893 return new;
3897 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
3898 "Make a copy of OBJECT in pure storage.\n\
3899 Recursively copies contents of vectors and cons cells.\n\
3900 Does not copy symbols. Copies strings without text properties.")
3901 (obj)
3902 register Lisp_Object obj;
3904 if (NILP (Vpurify_flag))
3905 return obj;
3907 if (PURE_POINTER_P (XPNTR (obj)))
3908 return obj;
3910 if (CONSP (obj))
3911 return pure_cons (XCAR (obj), XCDR (obj));
3912 else if (FLOATP (obj))
3913 return make_pure_float (XFLOAT_DATA (obj));
3914 else if (STRINGP (obj))
3915 return make_pure_string (XSTRING (obj)->data, XSTRING (obj)->size,
3916 STRING_BYTES (XSTRING (obj)),
3917 STRING_MULTIBYTE (obj));
3918 else if (COMPILEDP (obj) || VECTORP (obj))
3920 register struct Lisp_Vector *vec;
3921 register int i, size;
3923 size = XVECTOR (obj)->size;
3924 if (size & PSEUDOVECTOR_FLAG)
3925 size &= PSEUDOVECTOR_SIZE_MASK;
3926 vec = XVECTOR (make_pure_vector ((EMACS_INT) size));
3927 for (i = 0; i < size; i++)
3928 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
3929 if (COMPILEDP (obj))
3930 XSETCOMPILED (obj, vec);
3931 else
3932 XSETVECTOR (obj, vec);
3933 return obj;
3935 else if (MARKERP (obj))
3936 error ("Attempt to copy a marker to pure storage");
3938 return obj;
3943 /***********************************************************************
3944 Protection from GC
3945 ***********************************************************************/
3947 /* Put an entry in staticvec, pointing at the variable with address
3948 VARADDRESS. */
3950 void
3951 staticpro (varaddress)
3952 Lisp_Object *varaddress;
3954 staticvec[staticidx++] = varaddress;
3955 if (staticidx >= NSTATICS)
3956 abort ();
3959 struct catchtag
3961 Lisp_Object tag;
3962 Lisp_Object val;
3963 struct catchtag *next;
3966 struct backtrace
3968 struct backtrace *next;
3969 Lisp_Object *function;
3970 Lisp_Object *args; /* Points to vector of args. */
3971 int nargs; /* Length of vector. */
3972 /* If nargs is UNEVALLED, args points to slot holding list of
3973 unevalled args. */
3974 char evalargs;
3979 /***********************************************************************
3980 Protection from GC
3981 ***********************************************************************/
3983 /* Temporarily prevent garbage collection. */
3986 inhibit_garbage_collection ()
3988 int count = specpdl_ptr - specpdl;
3989 Lisp_Object number;
3990 int nbits = min (VALBITS, BITS_PER_INT);
3992 XSETINT (number, ((EMACS_INT) 1 << (nbits - 1)) - 1);
3994 specbind (Qgc_cons_threshold, number);
3996 return count;
4000 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
4001 "Reclaim storage for Lisp objects no longer needed.\n\
4002 Returns info on amount of space in use:\n\
4003 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)\n\
4004 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS\n\
4005 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)\n\
4006 (USED-STRINGS . FREE-STRINGS))\n\
4007 Garbage collection happens automatically if you cons more than\n\
4008 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.")
4011 register struct gcpro *tail;
4012 register struct specbinding *bind;
4013 struct catchtag *catch;
4014 struct handler *handler;
4015 register struct backtrace *backlist;
4016 char stack_top_variable;
4017 register int i;
4018 int message_p;
4019 Lisp_Object total[8];
4020 int count = BINDING_STACK_SIZE ();
4022 /* In case user calls debug_print during GC,
4023 don't let that cause a recursive GC. */
4024 consing_since_gc = 0;
4026 /* Save what's currently displayed in the echo area. */
4027 message_p = push_message ();
4028 record_unwind_protect (push_message_unwind, Qnil);
4030 /* Save a copy of the contents of the stack, for debugging. */
4031 #if MAX_SAVE_STACK > 0
4032 if (NILP (Vpurify_flag))
4034 i = &stack_top_variable - stack_bottom;
4035 if (i < 0) i = -i;
4036 if (i < MAX_SAVE_STACK)
4038 if (stack_copy == 0)
4039 stack_copy = (char *) xmalloc (stack_copy_size = i);
4040 else if (stack_copy_size < i)
4041 stack_copy = (char *) xrealloc (stack_copy, (stack_copy_size = i));
4042 if (stack_copy)
4044 if ((EMACS_INT) (&stack_top_variable - stack_bottom) > 0)
4045 bcopy (stack_bottom, stack_copy, i);
4046 else
4047 bcopy (&stack_top_variable, stack_copy, i);
4051 #endif /* MAX_SAVE_STACK > 0 */
4053 if (garbage_collection_messages)
4054 message1_nolog ("Garbage collecting...");
4056 BLOCK_INPUT;
4058 shrink_regexp_cache ();
4060 /* Don't keep undo information around forever. */
4062 register struct buffer *nextb = all_buffers;
4064 while (nextb)
4066 /* If a buffer's undo list is Qt, that means that undo is
4067 turned off in that buffer. Calling truncate_undo_list on
4068 Qt tends to return NULL, which effectively turns undo back on.
4069 So don't call truncate_undo_list if undo_list is Qt. */
4070 if (! EQ (nextb->undo_list, Qt))
4071 nextb->undo_list
4072 = truncate_undo_list (nextb->undo_list, undo_limit,
4073 undo_strong_limit);
4074 nextb = nextb->next;
4078 gc_in_progress = 1;
4080 /* clear_marks (); */
4082 /* Mark all the special slots that serve as the roots of accessibility.
4084 Usually the special slots to mark are contained in particular structures.
4085 Then we know no slot is marked twice because the structures don't overlap.
4086 In some cases, the structures point to the slots to be marked.
4087 For these, we use MARKBIT to avoid double marking of the slot. */
4089 for (i = 0; i < staticidx; i++)
4090 mark_object (staticvec[i]);
4092 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
4093 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
4094 mark_stack ();
4095 #else
4096 for (tail = gcprolist; tail; tail = tail->next)
4097 for (i = 0; i < tail->nvars; i++)
4098 if (!XMARKBIT (tail->var[i]))
4100 /* Explicit casting prevents compiler warning about
4101 discarding the `volatile' qualifier. */
4102 mark_object ((Lisp_Object *)&tail->var[i]);
4103 XMARK (tail->var[i]);
4105 #endif
4107 mark_byte_stack ();
4108 for (bind = specpdl; bind != specpdl_ptr; bind++)
4110 mark_object (&bind->symbol);
4111 mark_object (&bind->old_value);
4113 for (catch = catchlist; catch; catch = catch->next)
4115 mark_object (&catch->tag);
4116 mark_object (&catch->val);
4118 for (handler = handlerlist; handler; handler = handler->next)
4120 mark_object (&handler->handler);
4121 mark_object (&handler->var);
4123 for (backlist = backtrace_list; backlist; backlist = backlist->next)
4125 if (!XMARKBIT (*backlist->function))
4127 mark_object (backlist->function);
4128 XMARK (*backlist->function);
4130 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
4131 i = 0;
4132 else
4133 i = backlist->nargs - 1;
4134 for (; i >= 0; i--)
4135 if (!XMARKBIT (backlist->args[i]))
4137 mark_object (&backlist->args[i]);
4138 XMARK (backlist->args[i]);
4141 mark_kboards ();
4143 /* Look thru every buffer's undo list
4144 for elements that update markers that were not marked,
4145 and delete them. */
4147 register struct buffer *nextb = all_buffers;
4149 while (nextb)
4151 /* If a buffer's undo list is Qt, that means that undo is
4152 turned off in that buffer. Calling truncate_undo_list on
4153 Qt tends to return NULL, which effectively turns undo back on.
4154 So don't call truncate_undo_list if undo_list is Qt. */
4155 if (! EQ (nextb->undo_list, Qt))
4157 Lisp_Object tail, prev;
4158 tail = nextb->undo_list;
4159 prev = Qnil;
4160 while (CONSP (tail))
4162 if (GC_CONSP (XCAR (tail))
4163 && GC_MARKERP (XCAR (XCAR (tail)))
4164 && ! XMARKBIT (XMARKER (XCAR (XCAR (tail)))->chain))
4166 if (NILP (prev))
4167 nextb->undo_list = tail = XCDR (tail);
4168 else
4169 tail = XCDR (prev) = XCDR (tail);
4171 else
4173 prev = tail;
4174 tail = XCDR (tail);
4179 nextb = nextb->next;
4183 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4184 mark_stack ();
4185 #endif
4187 gc_sweep ();
4189 /* Clear the mark bits that we set in certain root slots. */
4191 #if (GC_MARK_STACK == GC_USE_GCPROS_AS_BEFORE \
4192 || GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES)
4193 for (tail = gcprolist; tail; tail = tail->next)
4194 for (i = 0; i < tail->nvars; i++)
4195 XUNMARK (tail->var[i]);
4196 #endif
4198 unmark_byte_stack ();
4199 for (backlist = backtrace_list; backlist; backlist = backlist->next)
4201 XUNMARK (*backlist->function);
4202 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
4203 i = 0;
4204 else
4205 i = backlist->nargs - 1;
4206 for (; i >= 0; i--)
4207 XUNMARK (backlist->args[i]);
4209 XUNMARK (buffer_defaults.name);
4210 XUNMARK (buffer_local_symbols.name);
4212 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
4213 dump_zombies ();
4214 #endif
4216 UNBLOCK_INPUT;
4218 /* clear_marks (); */
4219 gc_in_progress = 0;
4221 consing_since_gc = 0;
4222 if (gc_cons_threshold < 10000)
4223 gc_cons_threshold = 10000;
4225 if (garbage_collection_messages)
4227 if (message_p || minibuf_level > 0)
4228 restore_message ();
4229 else
4230 message1_nolog ("Garbage collecting...done");
4233 unbind_to (count, Qnil);
4235 total[0] = Fcons (make_number (total_conses),
4236 make_number (total_free_conses));
4237 total[1] = Fcons (make_number (total_symbols),
4238 make_number (total_free_symbols));
4239 total[2] = Fcons (make_number (total_markers),
4240 make_number (total_free_markers));
4241 total[3] = make_number (total_string_size);
4242 total[4] = make_number (total_vector_size);
4243 total[5] = Fcons (make_number (total_floats),
4244 make_number (total_free_floats));
4245 total[6] = Fcons (make_number (total_intervals),
4246 make_number (total_free_intervals));
4247 total[7] = Fcons (make_number (total_strings),
4248 make_number (total_free_strings));
4250 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4252 /* Compute average percentage of zombies. */
4253 double nlive = 0;
4255 for (i = 0; i < 7; ++i)
4256 nlive += XFASTINT (XCAR (total[i]));
4258 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
4259 max_live = max (nlive, max_live);
4260 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
4261 max_zombies = max (nzombies, max_zombies);
4262 ++ngcs;
4264 #endif
4266 return Flist (sizeof total / sizeof *total, total);
4270 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
4271 only interesting objects referenced from glyphs are strings. */
4273 static void
4274 mark_glyph_matrix (matrix)
4275 struct glyph_matrix *matrix;
4277 struct glyph_row *row = matrix->rows;
4278 struct glyph_row *end = row + matrix->nrows;
4280 for (; row < end; ++row)
4281 if (row->enabled_p)
4283 int area;
4284 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
4286 struct glyph *glyph = row->glyphs[area];
4287 struct glyph *end_glyph = glyph + row->used[area];
4289 for (; glyph < end_glyph; ++glyph)
4290 if (GC_STRINGP (glyph->object)
4291 && !STRING_MARKED_P (XSTRING (glyph->object)))
4292 mark_object (&glyph->object);
4298 /* Mark Lisp faces in the face cache C. */
4300 static void
4301 mark_face_cache (c)
4302 struct face_cache *c;
4304 if (c)
4306 int i, j;
4307 for (i = 0; i < c->used; ++i)
4309 struct face *face = FACE_FROM_ID (c->f, i);
4311 if (face)
4313 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
4314 mark_object (&face->lface[j]);
4321 #ifdef HAVE_WINDOW_SYSTEM
4323 /* Mark Lisp objects in image IMG. */
4325 static void
4326 mark_image (img)
4327 struct image *img;
4329 mark_object (&img->spec);
4331 if (!NILP (img->data.lisp_val))
4332 mark_object (&img->data.lisp_val);
4336 /* Mark Lisp objects in image cache of frame F. It's done this way so
4337 that we don't have to include xterm.h here. */
4339 static void
4340 mark_image_cache (f)
4341 struct frame *f;
4343 forall_images_in_image_cache (f, mark_image);
4346 #endif /* HAVE_X_WINDOWS */
4350 /* Mark reference to a Lisp_Object.
4351 If the object referred to has not been seen yet, recursively mark
4352 all the references contained in it. */
4354 #define LAST_MARKED_SIZE 500
4355 Lisp_Object *last_marked[LAST_MARKED_SIZE];
4356 int last_marked_index;
4358 void
4359 mark_object (argptr)
4360 Lisp_Object *argptr;
4362 Lisp_Object *objptr = argptr;
4363 register Lisp_Object obj;
4364 #ifdef GC_CHECK_MARKED_OBJECTS
4365 void *po;
4366 struct mem_node *m;
4367 #endif
4369 loop:
4370 obj = *objptr;
4371 loop2:
4372 XUNMARK (obj);
4374 if (PURE_POINTER_P (XPNTR (obj)))
4375 return;
4377 last_marked[last_marked_index++] = objptr;
4378 if (last_marked_index == LAST_MARKED_SIZE)
4379 last_marked_index = 0;
4381 /* Perform some sanity checks on the objects marked here. Abort if
4382 we encounter an object we know is bogus. This increases GC time
4383 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
4384 #ifdef GC_CHECK_MARKED_OBJECTS
4386 po = (void *) XPNTR (obj);
4388 /* Check that the object pointed to by PO is known to be a Lisp
4389 structure allocated from the heap. */
4390 #define CHECK_ALLOCATED() \
4391 do { \
4392 m = mem_find (po); \
4393 if (m == MEM_NIL) \
4394 abort (); \
4395 } while (0)
4397 /* Check that the object pointed to by PO is live, using predicate
4398 function LIVEP. */
4399 #define CHECK_LIVE(LIVEP) \
4400 do { \
4401 if (!LIVEP (m, po)) \
4402 abort (); \
4403 } while (0)
4405 /* Check both of the above conditions. */
4406 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
4407 do { \
4408 CHECK_ALLOCATED (); \
4409 CHECK_LIVE (LIVEP); \
4410 } while (0) \
4412 #else /* not GC_CHECK_MARKED_OBJECTS */
4414 #define CHECK_ALLOCATED() (void) 0
4415 #define CHECK_LIVE(LIVEP) (void) 0
4416 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
4418 #endif /* not GC_CHECK_MARKED_OBJECTS */
4420 switch (SWITCH_ENUM_CAST (XGCTYPE (obj)))
4422 case Lisp_String:
4424 register struct Lisp_String *ptr = XSTRING (obj);
4425 CHECK_ALLOCATED_AND_LIVE (live_string_p);
4426 MARK_INTERVAL_TREE (ptr->intervals);
4427 MARK_STRING (ptr);
4428 #ifdef GC_CHECK_STRING_BYTES
4429 /* Check that the string size recorded in the string is the
4430 same as the one recorded in the sdata structure. */
4431 CHECK_STRING_BYTES (ptr);
4432 #endif /* GC_CHECK_STRING_BYTES */
4434 break;
4436 case Lisp_Vectorlike:
4437 #ifdef GC_CHECK_MARKED_OBJECTS
4438 m = mem_find (po);
4439 if (m == MEM_NIL && !GC_SUBRP (obj)
4440 && po != &buffer_defaults
4441 && po != &buffer_local_symbols)
4442 abort ();
4443 #endif /* GC_CHECK_MARKED_OBJECTS */
4445 if (GC_BUFFERP (obj))
4447 if (!XMARKBIT (XBUFFER (obj)->name))
4449 #ifdef GC_CHECK_MARKED_OBJECTS
4450 if (po != &buffer_defaults && po != &buffer_local_symbols)
4452 struct buffer *b;
4453 for (b = all_buffers; b && b != po; b = b->next)
4455 if (b == NULL)
4456 abort ();
4458 #endif /* GC_CHECK_MARKED_OBJECTS */
4459 mark_buffer (obj);
4462 else if (GC_SUBRP (obj))
4463 break;
4464 else if (GC_COMPILEDP (obj))
4465 /* We could treat this just like a vector, but it is better to
4466 save the COMPILED_CONSTANTS element for last and avoid
4467 recursion there. */
4469 register struct Lisp_Vector *ptr = XVECTOR (obj);
4470 register EMACS_INT size = ptr->size;
4471 register int i;
4473 if (size & ARRAY_MARK_FLAG)
4474 break; /* Already marked */
4476 CHECK_LIVE (live_vector_p);
4477 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4478 size &= PSEUDOVECTOR_SIZE_MASK;
4479 for (i = 0; i < size; i++) /* and then mark its elements */
4481 if (i != COMPILED_CONSTANTS)
4482 mark_object (&ptr->contents[i]);
4484 /* This cast should be unnecessary, but some Mips compiler complains
4485 (MIPS-ABI + SysVR4, DC/OSx, etc). */
4486 objptr = (Lisp_Object *) &ptr->contents[COMPILED_CONSTANTS];
4487 goto loop;
4489 else if (GC_FRAMEP (obj))
4491 register struct frame *ptr = XFRAME (obj);
4492 register EMACS_INT size = ptr->size;
4494 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
4495 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4497 CHECK_LIVE (live_vector_p);
4498 mark_object (&ptr->name);
4499 mark_object (&ptr->icon_name);
4500 mark_object (&ptr->title);
4501 mark_object (&ptr->focus_frame);
4502 mark_object (&ptr->selected_window);
4503 mark_object (&ptr->minibuffer_window);
4504 mark_object (&ptr->param_alist);
4505 mark_object (&ptr->scroll_bars);
4506 mark_object (&ptr->condemned_scroll_bars);
4507 mark_object (&ptr->menu_bar_items);
4508 mark_object (&ptr->face_alist);
4509 mark_object (&ptr->menu_bar_vector);
4510 mark_object (&ptr->buffer_predicate);
4511 mark_object (&ptr->buffer_list);
4512 mark_object (&ptr->menu_bar_window);
4513 mark_object (&ptr->tool_bar_window);
4514 mark_face_cache (ptr->face_cache);
4515 #ifdef HAVE_WINDOW_SYSTEM
4516 mark_image_cache (ptr);
4517 mark_object (&ptr->tool_bar_items);
4518 mark_object (&ptr->desired_tool_bar_string);
4519 mark_object (&ptr->current_tool_bar_string);
4520 #endif /* HAVE_WINDOW_SYSTEM */
4522 else if (GC_BOOL_VECTOR_P (obj))
4524 register struct Lisp_Vector *ptr = XVECTOR (obj);
4526 if (ptr->size & ARRAY_MARK_FLAG)
4527 break; /* Already marked */
4528 CHECK_LIVE (live_vector_p);
4529 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4531 else if (GC_WINDOWP (obj))
4533 register struct Lisp_Vector *ptr = XVECTOR (obj);
4534 struct window *w = XWINDOW (obj);
4535 register EMACS_INT size = ptr->size;
4536 register int i;
4538 /* Stop if already marked. */
4539 if (size & ARRAY_MARK_FLAG)
4540 break;
4542 /* Mark it. */
4543 CHECK_LIVE (live_vector_p);
4544 ptr->size |= ARRAY_MARK_FLAG;
4546 /* There is no Lisp data above The member CURRENT_MATRIX in
4547 struct WINDOW. Stop marking when that slot is reached. */
4548 for (i = 0;
4549 (char *) &ptr->contents[i] < (char *) &w->current_matrix;
4550 i++)
4551 mark_object (&ptr->contents[i]);
4553 /* Mark glyphs for leaf windows. Marking window matrices is
4554 sufficient because frame matrices use the same glyph
4555 memory. */
4556 if (NILP (w->hchild)
4557 && NILP (w->vchild)
4558 && w->current_matrix)
4560 mark_glyph_matrix (w->current_matrix);
4561 mark_glyph_matrix (w->desired_matrix);
4564 else if (GC_HASH_TABLE_P (obj))
4566 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
4567 EMACS_INT size = h->size;
4569 /* Stop if already marked. */
4570 if (size & ARRAY_MARK_FLAG)
4571 break;
4573 /* Mark it. */
4574 CHECK_LIVE (live_vector_p);
4575 h->size |= ARRAY_MARK_FLAG;
4577 /* Mark contents. */
4578 mark_object (&h->test);
4579 mark_object (&h->weak);
4580 mark_object (&h->rehash_size);
4581 mark_object (&h->rehash_threshold);
4582 mark_object (&h->hash);
4583 mark_object (&h->next);
4584 mark_object (&h->index);
4585 mark_object (&h->user_hash_function);
4586 mark_object (&h->user_cmp_function);
4588 /* If hash table is not weak, mark all keys and values.
4589 For weak tables, mark only the vector. */
4590 if (GC_NILP (h->weak))
4591 mark_object (&h->key_and_value);
4592 else
4593 XVECTOR (h->key_and_value)->size |= ARRAY_MARK_FLAG;
4596 else
4598 register struct Lisp_Vector *ptr = XVECTOR (obj);
4599 register EMACS_INT size = ptr->size;
4600 register int i;
4602 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
4603 CHECK_LIVE (live_vector_p);
4604 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4605 if (size & PSEUDOVECTOR_FLAG)
4606 size &= PSEUDOVECTOR_SIZE_MASK;
4608 for (i = 0; i < size; i++) /* and then mark its elements */
4609 mark_object (&ptr->contents[i]);
4611 break;
4613 case Lisp_Symbol:
4615 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
4616 struct Lisp_Symbol *ptrx;
4618 if (XMARKBIT (ptr->plist)) break;
4619 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
4620 XMARK (ptr->plist);
4621 mark_object ((Lisp_Object *) &ptr->value);
4622 mark_object (&ptr->function);
4623 mark_object (&ptr->plist);
4625 if (!PURE_POINTER_P (ptr->name))
4626 MARK_STRING (ptr->name);
4627 MARK_INTERVAL_TREE (ptr->name->intervals);
4629 /* Note that we do not mark the obarray of the symbol.
4630 It is safe not to do so because nothing accesses that
4631 slot except to check whether it is nil. */
4632 ptr = ptr->next;
4633 if (ptr)
4635 /* For the benefit of the last_marked log. */
4636 objptr = (Lisp_Object *)&XSYMBOL (obj)->next;
4637 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
4638 XSETSYMBOL (obj, ptrx);
4639 /* We can't goto loop here because *objptr doesn't contain an
4640 actual Lisp_Object with valid datatype field. */
4641 goto loop2;
4644 break;
4646 case Lisp_Misc:
4647 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
4648 switch (XMISCTYPE (obj))
4650 case Lisp_Misc_Marker:
4651 XMARK (XMARKER (obj)->chain);
4652 /* DO NOT mark thru the marker's chain.
4653 The buffer's markers chain does not preserve markers from gc;
4654 instead, markers are removed from the chain when freed by gc. */
4655 break;
4657 case Lisp_Misc_Buffer_Local_Value:
4658 case Lisp_Misc_Some_Buffer_Local_Value:
4660 register struct Lisp_Buffer_Local_Value *ptr
4661 = XBUFFER_LOCAL_VALUE (obj);
4662 if (XMARKBIT (ptr->realvalue)) break;
4663 XMARK (ptr->realvalue);
4664 /* If the cdr is nil, avoid recursion for the car. */
4665 if (EQ (ptr->cdr, Qnil))
4667 objptr = &ptr->realvalue;
4668 goto loop;
4670 mark_object (&ptr->realvalue);
4671 mark_object (&ptr->buffer);
4672 mark_object (&ptr->frame);
4673 objptr = &ptr->cdr;
4674 goto loop;
4677 case Lisp_Misc_Intfwd:
4678 case Lisp_Misc_Boolfwd:
4679 case Lisp_Misc_Objfwd:
4680 case Lisp_Misc_Buffer_Objfwd:
4681 case Lisp_Misc_Kboard_Objfwd:
4682 /* Don't bother with Lisp_Buffer_Objfwd,
4683 since all markable slots in current buffer marked anyway. */
4684 /* Don't need to do Lisp_Objfwd, since the places they point
4685 are protected with staticpro. */
4686 break;
4688 case Lisp_Misc_Overlay:
4690 struct Lisp_Overlay *ptr = XOVERLAY (obj);
4691 if (!XMARKBIT (ptr->plist))
4693 XMARK (ptr->plist);
4694 mark_object (&ptr->start);
4695 mark_object (&ptr->end);
4696 objptr = &ptr->plist;
4697 goto loop;
4700 break;
4702 default:
4703 abort ();
4705 break;
4707 case Lisp_Cons:
4709 register struct Lisp_Cons *ptr = XCONS (obj);
4710 if (XMARKBIT (ptr->car)) break;
4711 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
4712 XMARK (ptr->car);
4713 /* If the cdr is nil, avoid recursion for the car. */
4714 if (EQ (ptr->cdr, Qnil))
4716 objptr = &ptr->car;
4717 goto loop;
4719 mark_object (&ptr->car);
4720 objptr = &ptr->cdr;
4721 goto loop;
4724 case Lisp_Float:
4725 CHECK_ALLOCATED_AND_LIVE (live_float_p);
4726 XMARK (XFLOAT (obj)->type);
4727 break;
4729 case Lisp_Int:
4730 break;
4732 default:
4733 abort ();
4736 #undef CHECK_LIVE
4737 #undef CHECK_ALLOCATED
4738 #undef CHECK_ALLOCATED_AND_LIVE
4741 /* Mark the pointers in a buffer structure. */
4743 static void
4744 mark_buffer (buf)
4745 Lisp_Object buf;
4747 register struct buffer *buffer = XBUFFER (buf);
4748 register Lisp_Object *ptr;
4749 Lisp_Object base_buffer;
4751 /* This is the buffer's markbit */
4752 mark_object (&buffer->name);
4753 XMARK (buffer->name);
4755 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
4757 if (CONSP (buffer->undo_list))
4759 Lisp_Object tail;
4760 tail = buffer->undo_list;
4762 while (CONSP (tail))
4764 register struct Lisp_Cons *ptr = XCONS (tail);
4766 if (XMARKBIT (ptr->car))
4767 break;
4768 XMARK (ptr->car);
4769 if (GC_CONSP (ptr->car)
4770 && ! XMARKBIT (XCAR (ptr->car))
4771 && GC_MARKERP (XCAR (ptr->car)))
4773 XMARK (XCAR (ptr->car));
4774 mark_object (&XCDR (ptr->car));
4776 else
4777 mark_object (&ptr->car);
4779 if (CONSP (ptr->cdr))
4780 tail = ptr->cdr;
4781 else
4782 break;
4785 mark_object (&XCDR (tail));
4787 else
4788 mark_object (&buffer->undo_list);
4790 for (ptr = &buffer->name + 1;
4791 (char *)ptr < (char *)buffer + sizeof (struct buffer);
4792 ptr++)
4793 mark_object (ptr);
4795 /* If this is an indirect buffer, mark its base buffer. */
4796 if (buffer->base_buffer && !XMARKBIT (buffer->base_buffer->name))
4798 XSETBUFFER (base_buffer, buffer->base_buffer);
4799 mark_buffer (base_buffer);
4804 /* Mark the pointers in the kboard objects. */
4806 static void
4807 mark_kboards ()
4809 KBOARD *kb;
4810 Lisp_Object *p;
4811 for (kb = all_kboards; kb; kb = kb->next_kboard)
4813 if (kb->kbd_macro_buffer)
4814 for (p = kb->kbd_macro_buffer; p < kb->kbd_macro_ptr; p++)
4815 mark_object (p);
4816 mark_object (&kb->Voverriding_terminal_local_map);
4817 mark_object (&kb->Vlast_command);
4818 mark_object (&kb->Vreal_last_command);
4819 mark_object (&kb->Vprefix_arg);
4820 mark_object (&kb->Vlast_prefix_arg);
4821 mark_object (&kb->kbd_queue);
4822 mark_object (&kb->defining_kbd_macro);
4823 mark_object (&kb->Vlast_kbd_macro);
4824 mark_object (&kb->Vsystem_key_alist);
4825 mark_object (&kb->system_key_syms);
4826 mark_object (&kb->Vdefault_minibuffer_frame);
4831 /* Value is non-zero if OBJ will survive the current GC because it's
4832 either marked or does not need to be marked to survive. */
4835 survives_gc_p (obj)
4836 Lisp_Object obj;
4838 int survives_p;
4840 switch (XGCTYPE (obj))
4842 case Lisp_Int:
4843 survives_p = 1;
4844 break;
4846 case Lisp_Symbol:
4847 survives_p = XMARKBIT (XSYMBOL (obj)->plist);
4848 break;
4850 case Lisp_Misc:
4851 switch (XMISCTYPE (obj))
4853 case Lisp_Misc_Marker:
4854 survives_p = XMARKBIT (obj);
4855 break;
4857 case Lisp_Misc_Buffer_Local_Value:
4858 case Lisp_Misc_Some_Buffer_Local_Value:
4859 survives_p = XMARKBIT (XBUFFER_LOCAL_VALUE (obj)->realvalue);
4860 break;
4862 case Lisp_Misc_Intfwd:
4863 case Lisp_Misc_Boolfwd:
4864 case Lisp_Misc_Objfwd:
4865 case Lisp_Misc_Buffer_Objfwd:
4866 case Lisp_Misc_Kboard_Objfwd:
4867 survives_p = 1;
4868 break;
4870 case Lisp_Misc_Overlay:
4871 survives_p = XMARKBIT (XOVERLAY (obj)->plist);
4872 break;
4874 default:
4875 abort ();
4877 break;
4879 case Lisp_String:
4881 struct Lisp_String *s = XSTRING (obj);
4882 survives_p = STRING_MARKED_P (s);
4884 break;
4886 case Lisp_Vectorlike:
4887 if (GC_BUFFERP (obj))
4888 survives_p = XMARKBIT (XBUFFER (obj)->name);
4889 else if (GC_SUBRP (obj))
4890 survives_p = 1;
4891 else
4892 survives_p = XVECTOR (obj)->size & ARRAY_MARK_FLAG;
4893 break;
4895 case Lisp_Cons:
4896 survives_p = XMARKBIT (XCAR (obj));
4897 break;
4899 case Lisp_Float:
4900 survives_p = XMARKBIT (XFLOAT (obj)->type);
4901 break;
4903 default:
4904 abort ();
4907 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
4912 /* Sweep: find all structures not marked, and free them. */
4914 static void
4915 gc_sweep ()
4917 /* Remove or mark entries in weak hash tables.
4918 This must be done before any object is unmarked. */
4919 sweep_weak_hash_tables ();
4921 sweep_strings ();
4922 #ifdef GC_CHECK_STRING_BYTES
4923 if (!noninteractive)
4924 check_string_bytes (1);
4925 #endif
4927 /* Put all unmarked conses on free list */
4929 register struct cons_block *cblk;
4930 struct cons_block **cprev = &cons_block;
4931 register int lim = cons_block_index;
4932 register int num_free = 0, num_used = 0;
4934 cons_free_list = 0;
4936 for (cblk = cons_block; cblk; cblk = *cprev)
4938 register int i;
4939 int this_free = 0;
4940 for (i = 0; i < lim; i++)
4941 if (!XMARKBIT (cblk->conses[i].car))
4943 this_free++;
4944 *(struct Lisp_Cons **)&cblk->conses[i].cdr = cons_free_list;
4945 cons_free_list = &cblk->conses[i];
4946 #if GC_MARK_STACK
4947 cons_free_list->car = Vdead;
4948 #endif
4950 else
4952 num_used++;
4953 XUNMARK (cblk->conses[i].car);
4955 lim = CONS_BLOCK_SIZE;
4956 /* If this block contains only free conses and we have already
4957 seen more than two blocks worth of free conses then deallocate
4958 this block. */
4959 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
4961 *cprev = cblk->next;
4962 /* Unhook from the free list. */
4963 cons_free_list = *(struct Lisp_Cons **) &cblk->conses[0].cdr;
4964 lisp_free (cblk);
4965 n_cons_blocks--;
4967 else
4969 num_free += this_free;
4970 cprev = &cblk->next;
4973 total_conses = num_used;
4974 total_free_conses = num_free;
4977 /* Put all unmarked floats on free list */
4979 register struct float_block *fblk;
4980 struct float_block **fprev = &float_block;
4981 register int lim = float_block_index;
4982 register int num_free = 0, num_used = 0;
4984 float_free_list = 0;
4986 for (fblk = float_block; fblk; fblk = *fprev)
4988 register int i;
4989 int this_free = 0;
4990 for (i = 0; i < lim; i++)
4991 if (!XMARKBIT (fblk->floats[i].type))
4993 this_free++;
4994 *(struct Lisp_Float **)&fblk->floats[i].data = float_free_list;
4995 float_free_list = &fblk->floats[i];
4996 #if GC_MARK_STACK
4997 float_free_list->type = Vdead;
4998 #endif
5000 else
5002 num_used++;
5003 XUNMARK (fblk->floats[i].type);
5005 lim = FLOAT_BLOCK_SIZE;
5006 /* If this block contains only free floats and we have already
5007 seen more than two blocks worth of free floats then deallocate
5008 this block. */
5009 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
5011 *fprev = fblk->next;
5012 /* Unhook from the free list. */
5013 float_free_list = *(struct Lisp_Float **) &fblk->floats[0].data;
5014 lisp_free (fblk);
5015 n_float_blocks--;
5017 else
5019 num_free += this_free;
5020 fprev = &fblk->next;
5023 total_floats = num_used;
5024 total_free_floats = num_free;
5027 /* Put all unmarked intervals on free list */
5029 register struct interval_block *iblk;
5030 struct interval_block **iprev = &interval_block;
5031 register int lim = interval_block_index;
5032 register int num_free = 0, num_used = 0;
5034 interval_free_list = 0;
5036 for (iblk = interval_block; iblk; iblk = *iprev)
5038 register int i;
5039 int this_free = 0;
5041 for (i = 0; i < lim; i++)
5043 if (! XMARKBIT (iblk->intervals[i].plist))
5045 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
5046 interval_free_list = &iblk->intervals[i];
5047 this_free++;
5049 else
5051 num_used++;
5052 XUNMARK (iblk->intervals[i].plist);
5055 lim = INTERVAL_BLOCK_SIZE;
5056 /* If this block contains only free intervals and we have already
5057 seen more than two blocks worth of free intervals then
5058 deallocate this block. */
5059 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
5061 *iprev = iblk->next;
5062 /* Unhook from the free list. */
5063 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
5064 lisp_free (iblk);
5065 n_interval_blocks--;
5067 else
5069 num_free += this_free;
5070 iprev = &iblk->next;
5073 total_intervals = num_used;
5074 total_free_intervals = num_free;
5077 /* Put all unmarked symbols on free list */
5079 register struct symbol_block *sblk;
5080 struct symbol_block **sprev = &symbol_block;
5081 register int lim = symbol_block_index;
5082 register int num_free = 0, num_used = 0;
5084 symbol_free_list = NULL;
5086 for (sblk = symbol_block; sblk; sblk = *sprev)
5088 int this_free = 0;
5089 struct Lisp_Symbol *sym = sblk->symbols;
5090 struct Lisp_Symbol *end = sym + lim;
5092 for (; sym < end; ++sym)
5094 /* Check if the symbol was created during loadup. In such a case
5095 it might be pointed to by pure bytecode which we don't trace,
5096 so we conservatively assume that it is live. */
5097 int pure_p = PURE_POINTER_P (sym->name);
5099 if (!XMARKBIT (sym->plist) && !pure_p)
5101 *(struct Lisp_Symbol **) &sym->value = symbol_free_list;
5102 symbol_free_list = sym;
5103 #if GC_MARK_STACK
5104 symbol_free_list->function = Vdead;
5105 #endif
5106 ++this_free;
5108 else
5110 ++num_used;
5111 if (!pure_p)
5112 UNMARK_STRING (sym->name);
5113 XUNMARK (sym->plist);
5117 lim = SYMBOL_BLOCK_SIZE;
5118 /* If this block contains only free symbols and we have already
5119 seen more than two blocks worth of free symbols then deallocate
5120 this block. */
5121 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
5123 *sprev = sblk->next;
5124 /* Unhook from the free list. */
5125 symbol_free_list = *(struct Lisp_Symbol **)&sblk->symbols[0].value;
5126 lisp_free (sblk);
5127 n_symbol_blocks--;
5129 else
5131 num_free += this_free;
5132 sprev = &sblk->next;
5135 total_symbols = num_used;
5136 total_free_symbols = num_free;
5139 /* Put all unmarked misc's on free list.
5140 For a marker, first unchain it from the buffer it points into. */
5142 register struct marker_block *mblk;
5143 struct marker_block **mprev = &marker_block;
5144 register int lim = marker_block_index;
5145 register int num_free = 0, num_used = 0;
5147 marker_free_list = 0;
5149 for (mblk = marker_block; mblk; mblk = *mprev)
5151 register int i;
5152 int this_free = 0;
5153 EMACS_INT already_free = -1;
5155 for (i = 0; i < lim; i++)
5157 Lisp_Object *markword;
5158 switch (mblk->markers[i].u_marker.type)
5160 case Lisp_Misc_Marker:
5161 markword = &mblk->markers[i].u_marker.chain;
5162 break;
5163 case Lisp_Misc_Buffer_Local_Value:
5164 case Lisp_Misc_Some_Buffer_Local_Value:
5165 markword = &mblk->markers[i].u_buffer_local_value.realvalue;
5166 break;
5167 case Lisp_Misc_Overlay:
5168 markword = &mblk->markers[i].u_overlay.plist;
5169 break;
5170 case Lisp_Misc_Free:
5171 /* If the object was already free, keep it
5172 on the free list. */
5173 markword = (Lisp_Object *) &already_free;
5174 break;
5175 default:
5176 markword = 0;
5177 break;
5179 if (markword && !XMARKBIT (*markword))
5181 Lisp_Object tem;
5182 if (mblk->markers[i].u_marker.type == Lisp_Misc_Marker)
5184 /* tem1 avoids Sun compiler bug */
5185 struct Lisp_Marker *tem1 = &mblk->markers[i].u_marker;
5186 XSETMARKER (tem, tem1);
5187 unchain_marker (tem);
5189 /* Set the type of the freed object to Lisp_Misc_Free.
5190 We could leave the type alone, since nobody checks it,
5191 but this might catch bugs faster. */
5192 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
5193 mblk->markers[i].u_free.chain = marker_free_list;
5194 marker_free_list = &mblk->markers[i];
5195 this_free++;
5197 else
5199 num_used++;
5200 if (markword)
5201 XUNMARK (*markword);
5204 lim = MARKER_BLOCK_SIZE;
5205 /* If this block contains only free markers and we have already
5206 seen more than two blocks worth of free markers then deallocate
5207 this block. */
5208 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
5210 *mprev = mblk->next;
5211 /* Unhook from the free list. */
5212 marker_free_list = mblk->markers[0].u_free.chain;
5213 lisp_free (mblk);
5214 n_marker_blocks--;
5216 else
5218 num_free += this_free;
5219 mprev = &mblk->next;
5223 total_markers = num_used;
5224 total_free_markers = num_free;
5227 /* Free all unmarked buffers */
5229 register struct buffer *buffer = all_buffers, *prev = 0, *next;
5231 while (buffer)
5232 if (!XMARKBIT (buffer->name))
5234 if (prev)
5235 prev->next = buffer->next;
5236 else
5237 all_buffers = buffer->next;
5238 next = buffer->next;
5239 lisp_free (buffer);
5240 buffer = next;
5242 else
5244 XUNMARK (buffer->name);
5245 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
5246 prev = buffer, buffer = buffer->next;
5250 /* Free all unmarked vectors */
5252 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
5253 total_vector_size = 0;
5255 while (vector)
5256 if (!(vector->size & ARRAY_MARK_FLAG))
5258 if (prev)
5259 prev->next = vector->next;
5260 else
5261 all_vectors = vector->next;
5262 next = vector->next;
5263 lisp_free (vector);
5264 n_vectors--;
5265 vector = next;
5268 else
5270 vector->size &= ~ARRAY_MARK_FLAG;
5271 if (vector->size & PSEUDOVECTOR_FLAG)
5272 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
5273 else
5274 total_vector_size += vector->size;
5275 prev = vector, vector = vector->next;
5279 #ifdef GC_CHECK_STRING_BYTES
5280 if (!noninteractive)
5281 check_string_bytes (1);
5282 #endif
5288 /* Debugging aids. */
5290 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
5291 "Return the address of the last byte Emacs has allocated, divided by 1024.\n\
5292 This may be helpful in debugging Emacs's memory usage.\n\
5293 We divide the value by 1024 to make sure it fits in a Lisp integer.")
5296 Lisp_Object end;
5298 XSETINT (end, (EMACS_INT) sbrk (0) / 1024);
5300 return end;
5303 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
5304 "Return a list of counters that measure how much consing there has been.\n\
5305 Each of these counters increments for a certain kind of object.\n\
5306 The counters wrap around from the largest positive integer to zero.\n\
5307 Garbage collection does not decrease them.\n\
5308 The elements of the value are as follows:\n\
5309 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)\n\
5310 All are in units of 1 = one object consed\n\
5311 except for VECTOR-CELLS and STRING-CHARS, which count the total length of\n\
5312 objects consed.\n\
5313 MISCS include overlays, markers, and some internal types.\n\
5314 Frames, windows, buffers, and subprocesses count as vectors\n\
5315 (but the contents of a buffer's text do not count here).")
5318 Lisp_Object consed[8];
5320 XSETINT (consed[0],
5321 cons_cells_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5322 XSETINT (consed[1],
5323 floats_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5324 XSETINT (consed[2],
5325 vector_cells_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5326 XSETINT (consed[3],
5327 symbols_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5328 XSETINT (consed[4],
5329 string_chars_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5330 XSETINT (consed[5],
5331 misc_objects_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5332 XSETINT (consed[6],
5333 intervals_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5334 XSETINT (consed[7],
5335 strings_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5337 return Flist (8, consed);
5340 int suppress_checking;
5341 void
5342 die (msg, file, line)
5343 const char *msg;
5344 const char *file;
5345 int line;
5347 fprintf (stderr, "\r\nEmacs fatal error: %s:%d: %s\r\n",
5348 file, line, msg);
5349 abort ();
5352 /* Initialization */
5354 void
5355 init_alloc_once ()
5357 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
5358 pure_bytes_used = 0;
5359 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
5360 mem_init ();
5361 Vdead = make_pure_string ("DEAD", 4, 4, 0);
5362 #endif
5363 #ifdef HAVE_SHM
5364 pure_size = PURESIZE;
5365 #endif
5366 all_vectors = 0;
5367 ignore_warnings = 1;
5368 #ifdef DOUG_LEA_MALLOC
5369 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
5370 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
5371 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
5372 #endif
5373 init_strings ();
5374 init_cons ();
5375 init_symbol ();
5376 init_marker ();
5377 init_float ();
5378 init_intervals ();
5380 #ifdef REL_ALLOC
5381 malloc_hysteresis = 32;
5382 #else
5383 malloc_hysteresis = 0;
5384 #endif
5386 spare_memory = (char *) malloc (SPARE_MEMORY);
5388 ignore_warnings = 0;
5389 gcprolist = 0;
5390 byte_stack_list = 0;
5391 staticidx = 0;
5392 consing_since_gc = 0;
5393 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
5394 #ifdef VIRT_ADDR_VARIES
5395 malloc_sbrk_unused = 1<<22; /* A large number */
5396 malloc_sbrk_used = 100000; /* as reasonable as any number */
5397 #endif /* VIRT_ADDR_VARIES */
5400 void
5401 init_alloc ()
5403 gcprolist = 0;
5404 byte_stack_list = 0;
5405 #if GC_MARK_STACK
5406 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
5407 setjmp_tested_p = longjmps_done = 0;
5408 #endif
5409 #endif
5412 void
5413 syms_of_alloc ()
5415 DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold,
5416 "*Number of bytes of consing between garbage collections.\n\
5417 Garbage collection can happen automatically once this many bytes have been\n\
5418 allocated since the last garbage collection. All data types count.\n\n\
5419 Garbage collection happens automatically only when `eval' is called.\n\n\
5420 By binding this temporarily to a large number, you can effectively\n\
5421 prevent garbage collection during a part of the program.");
5423 DEFVAR_INT ("pure-bytes-used", &pure_bytes_used,
5424 "Number of bytes of sharable Lisp data allocated so far.");
5426 DEFVAR_INT ("cons-cells-consed", &cons_cells_consed,
5427 "Number of cons cells that have been consed so far.");
5429 DEFVAR_INT ("floats-consed", &floats_consed,
5430 "Number of floats that have been consed so far.");
5432 DEFVAR_INT ("vector-cells-consed", &vector_cells_consed,
5433 "Number of vector cells that have been consed so far.");
5435 DEFVAR_INT ("symbols-consed", &symbols_consed,
5436 "Number of symbols that have been consed so far.");
5438 DEFVAR_INT ("string-chars-consed", &string_chars_consed,
5439 "Number of string characters that have been consed so far.");
5441 DEFVAR_INT ("misc-objects-consed", &misc_objects_consed,
5442 "Number of miscellaneous objects that have been consed so far.");
5444 DEFVAR_INT ("intervals-consed", &intervals_consed,
5445 "Number of intervals that have been consed so far.");
5447 DEFVAR_INT ("strings-consed", &strings_consed,
5448 "Number of strings that have been consed so far.");
5450 DEFVAR_LISP ("purify-flag", &Vpurify_flag,
5451 "Non-nil means loading Lisp code in order to dump an executable.\n\
5452 This means that certain objects should be allocated in shared (pure) space.");
5454 DEFVAR_INT ("undo-limit", &undo_limit,
5455 "Keep no more undo information once it exceeds this size.\n\
5456 This limit is applied when garbage collection happens.\n\
5457 The size is counted as the number of bytes occupied,\n\
5458 which includes both saved text and other data.");
5459 undo_limit = 20000;
5461 DEFVAR_INT ("undo-strong-limit", &undo_strong_limit,
5462 "Don't keep more than this much size of undo information.\n\
5463 A command which pushes past this size is itself forgotten.\n\
5464 This limit is applied when garbage collection happens.\n\
5465 The size is counted as the number of bytes occupied,\n\
5466 which includes both saved text and other data.");
5467 undo_strong_limit = 30000;
5469 DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
5470 "Non-nil means display messages at start and end of garbage collection.");
5471 garbage_collection_messages = 0;
5473 /* We build this in advance because if we wait until we need it, we might
5474 not be able to allocate the memory to hold it. */
5475 memory_signal_data
5476 = Fcons (Qerror, Fcons (build_string ("Memory exhausted--use M-x save-some-buffers RET"), Qnil));
5477 staticpro (&memory_signal_data);
5479 staticpro (&Qgc_cons_threshold);
5480 Qgc_cons_threshold = intern ("gc-cons-threshold");
5482 staticpro (&Qchar_table_extra_slots);
5483 Qchar_table_extra_slots = intern ("char-table-extra-slots");
5485 defsubr (&Scons);
5486 defsubr (&Slist);
5487 defsubr (&Svector);
5488 defsubr (&Smake_byte_code);
5489 defsubr (&Smake_list);
5490 defsubr (&Smake_vector);
5491 defsubr (&Smake_char_table);
5492 defsubr (&Smake_string);
5493 defsubr (&Smake_bool_vector);
5494 defsubr (&Smake_symbol);
5495 defsubr (&Smake_marker);
5496 defsubr (&Spurecopy);
5497 defsubr (&Sgarbage_collect);
5498 defsubr (&Smemory_limit);
5499 defsubr (&Smemory_use_counts);
5501 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5502 defsubr (&Sgc_status);
5503 #endif