(access_keymap): Fix last change to not consider
[emacs.git] / src / alloc.c
blob5c0e0dd3c689d76a51b8dd45d3be52d2a68984d1
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 int live_vector_p P_ ((struct mem_node *, void *));
368 static int live_buffer_p P_ ((struct mem_node *, void *));
369 static int live_string_p P_ ((struct mem_node *, void *));
370 static int live_cons_p P_ ((struct mem_node *, void *));
371 static int live_symbol_p P_ ((struct mem_node *, void *));
372 static int live_float_p P_ ((struct mem_node *, void *));
373 static int live_misc_p P_ ((struct mem_node *, void *));
374 static void mark_maybe_object P_ ((Lisp_Object));
375 static void mark_memory P_ ((void *, void *));
376 static void mem_init P_ ((void));
377 static struct mem_node *mem_insert P_ ((void *, void *, enum mem_type));
378 static void mem_insert_fixup P_ ((struct mem_node *));
379 static void mem_rotate_left P_ ((struct mem_node *));
380 static void mem_rotate_right P_ ((struct mem_node *));
381 static void mem_delete P_ ((struct mem_node *));
382 static void mem_delete_fixup P_ ((struct mem_node *));
383 static INLINE struct mem_node *mem_find P_ ((void *));
385 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
386 static void check_gcpros P_ ((void));
387 #endif
389 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
391 /* Recording what needs to be marked for gc. */
393 struct gcpro *gcprolist;
395 /* Addresses of staticpro'd variables. */
397 #define NSTATICS 1024
398 Lisp_Object *staticvec[NSTATICS] = {0};
400 /* Index of next unused slot in staticvec. */
402 int staticidx = 0;
404 static POINTER_TYPE *pure_alloc P_ ((size_t, int));
407 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
408 ALIGNMENT must be a power of 2. */
410 #define ALIGN(SZ, ALIGNMENT) \
411 (((SZ) + (ALIGNMENT) - 1) & ~((ALIGNMENT) - 1))
415 /************************************************************************
416 Malloc
417 ************************************************************************/
419 /* Write STR to Vstandard_output plus some advice on how to free some
420 memory. Called when memory gets low. */
422 Lisp_Object
423 malloc_warning_1 (str)
424 Lisp_Object str;
426 Fprinc (str, Vstandard_output);
427 write_string ("\nKilling some buffers may delay running out of memory.\n", -1);
428 write_string ("However, certainly by the time you receive the 95% warning,\n", -1);
429 write_string ("you should clean up, kill this Emacs, and start a new one.", -1);
430 return Qnil;
434 /* Function malloc calls this if it finds we are near exhausting
435 storage. */
437 void
438 malloc_warning (str)
439 char *str;
441 pending_malloc_warning = str;
445 /* Display a malloc warning in buffer *Danger*. */
447 void
448 display_malloc_warning ()
450 register Lisp_Object val;
452 val = build_string (pending_malloc_warning);
453 pending_malloc_warning = 0;
454 internal_with_output_to_temp_buffer (" *Danger*", malloc_warning_1, val);
458 #ifdef DOUG_LEA_MALLOC
459 # define BYTES_USED (mallinfo ().arena)
460 #else
461 # define BYTES_USED _bytes_used
462 #endif
465 /* Called if malloc returns zero. */
467 void
468 memory_full ()
470 #ifndef SYSTEM_MALLOC
471 bytes_used_when_full = BYTES_USED;
472 #endif
474 /* The first time we get here, free the spare memory. */
475 if (spare_memory)
477 free (spare_memory);
478 spare_memory = 0;
481 /* This used to call error, but if we've run out of memory, we could
482 get infinite recursion trying to build the string. */
483 while (1)
484 Fsignal (Qnil, memory_signal_data);
488 /* Called if we can't allocate relocatable space for a buffer. */
490 void
491 buffer_memory_full ()
493 /* If buffers use the relocating allocator, no need to free
494 spare_memory, because we may have plenty of malloc space left
495 that we could get, and if we don't, the malloc that fails will
496 itself cause spare_memory to be freed. If buffers don't use the
497 relocating allocator, treat this like any other failing
498 malloc. */
500 #ifndef REL_ALLOC
501 memory_full ();
502 #endif
504 /* This used to call error, but if we've run out of memory, we could
505 get infinite recursion trying to build the string. */
506 while (1)
507 Fsignal (Qerror, memory_signal_data);
511 /* Like malloc but check for no memory and block interrupt input.. */
513 POINTER_TYPE *
514 xmalloc (size)
515 size_t size;
517 register POINTER_TYPE *val;
519 BLOCK_INPUT;
520 val = (POINTER_TYPE *) malloc (size);
521 UNBLOCK_INPUT;
523 if (!val && size)
524 memory_full ();
525 return val;
529 /* Like realloc but check for no memory and block interrupt input.. */
531 POINTER_TYPE *
532 xrealloc (block, size)
533 POINTER_TYPE *block;
534 size_t size;
536 register POINTER_TYPE *val;
538 BLOCK_INPUT;
539 /* We must call malloc explicitly when BLOCK is 0, since some
540 reallocs don't do this. */
541 if (! block)
542 val = (POINTER_TYPE *) malloc (size);
543 else
544 val = (POINTER_TYPE *) realloc (block, size);
545 UNBLOCK_INPUT;
547 if (!val && size) memory_full ();
548 return val;
552 /* Like free but block interrupt input.. */
554 void
555 xfree (block)
556 POINTER_TYPE *block;
558 BLOCK_INPUT;
559 free (block);
560 UNBLOCK_INPUT;
564 /* Like strdup, but uses xmalloc. */
566 char *
567 xstrdup (s)
568 char *s;
570 size_t len = strlen (s) + 1;
571 char *p = (char *) xmalloc (len);
572 bcopy (s, p, len);
573 return p;
577 /* Like malloc but used for allocating Lisp data. NBYTES is the
578 number of bytes to allocate, TYPE describes the intended use of the
579 allcated memory block (for strings, for conses, ...). */
581 static POINTER_TYPE *
582 lisp_malloc (nbytes, type)
583 size_t nbytes;
584 enum mem_type type;
586 register void *val;
588 BLOCK_INPUT;
590 #ifdef GC_MALLOC_CHECK
591 allocated_mem_type = type;
592 #endif
594 val = (void *) malloc (nbytes);
596 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
597 if (val && type != MEM_TYPE_NON_LISP)
598 mem_insert (val, (char *) val + nbytes, type);
599 #endif
601 UNBLOCK_INPUT;
602 if (!val && nbytes)
603 memory_full ();
604 return val;
608 /* Return a new buffer structure allocated from the heap with
609 a call to lisp_malloc. */
611 struct buffer *
612 allocate_buffer ()
614 return (struct buffer *) lisp_malloc (sizeof (struct buffer),
615 MEM_TYPE_BUFFER);
619 /* Free BLOCK. This must be called to free memory allocated with a
620 call to lisp_malloc. */
622 static void
623 lisp_free (block)
624 POINTER_TYPE *block;
626 BLOCK_INPUT;
627 free (block);
628 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
629 mem_delete (mem_find (block));
630 #endif
631 UNBLOCK_INPUT;
635 /* Arranging to disable input signals while we're in malloc.
637 This only works with GNU malloc. To help out systems which can't
638 use GNU malloc, all the calls to malloc, realloc, and free
639 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
640 pairs; unfortunately, we have no idea what C library functions
641 might call malloc, so we can't really protect them unless you're
642 using GNU malloc. Fortunately, most of the major operating can use
643 GNU malloc. */
645 #ifndef SYSTEM_MALLOC
646 #ifndef DOUG_LEA_MALLOC
647 extern void * (*__malloc_hook) P_ ((size_t));
648 extern void * (*__realloc_hook) P_ ((void *, size_t));
649 extern void (*__free_hook) P_ ((void *));
650 /* Else declared in malloc.h, perhaps with an extra arg. */
651 #endif /* DOUG_LEA_MALLOC */
652 static void * (*old_malloc_hook) ();
653 static void * (*old_realloc_hook) ();
654 static void (*old_free_hook) ();
656 /* This function is used as the hook for free to call. */
658 static void
659 emacs_blocked_free (ptr)
660 void *ptr;
662 BLOCK_INPUT;
664 #ifdef GC_MALLOC_CHECK
665 if (ptr)
667 struct mem_node *m;
669 m = mem_find (ptr);
670 if (m == MEM_NIL || m->start != ptr)
672 fprintf (stderr,
673 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
674 abort ();
676 else
678 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
679 mem_delete (m);
682 #endif /* GC_MALLOC_CHECK */
684 __free_hook = old_free_hook;
685 free (ptr);
687 /* If we released our reserve (due to running out of memory),
688 and we have a fair amount free once again,
689 try to set aside another reserve in case we run out once more. */
690 if (spare_memory == 0
691 /* Verify there is enough space that even with the malloc
692 hysteresis this call won't run out again.
693 The code here is correct as long as SPARE_MEMORY
694 is substantially larger than the block size malloc uses. */
695 && (bytes_used_when_full
696 > BYTES_USED + max (malloc_hysteresis, 4) * SPARE_MEMORY))
697 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
699 __free_hook = emacs_blocked_free;
700 UNBLOCK_INPUT;
704 /* If we released our reserve (due to running out of memory),
705 and we have a fair amount free once again,
706 try to set aside another reserve in case we run out once more.
708 This is called when a relocatable block is freed in ralloc.c. */
710 void
711 refill_memory_reserve ()
713 if (spare_memory == 0)
714 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
718 /* This function is the malloc hook that Emacs uses. */
720 static void *
721 emacs_blocked_malloc (size)
722 size_t size;
724 void *value;
726 BLOCK_INPUT;
727 __malloc_hook = old_malloc_hook;
728 #ifdef DOUG_LEA_MALLOC
729 mallopt (M_TOP_PAD, malloc_hysteresis * 4096);
730 #else
731 __malloc_extra_blocks = malloc_hysteresis;
732 #endif
734 value = (void *) malloc (size);
736 #ifdef GC_MALLOC_CHECK
738 struct mem_node *m = mem_find (value);
739 if (m != MEM_NIL)
741 fprintf (stderr, "Malloc returned %p which is already in use\n",
742 value);
743 fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
744 m->start, m->end, (char *) m->end - (char *) m->start,
745 m->type);
746 abort ();
749 if (!dont_register_blocks)
751 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
752 allocated_mem_type = MEM_TYPE_NON_LISP;
755 #endif /* GC_MALLOC_CHECK */
757 __malloc_hook = emacs_blocked_malloc;
758 UNBLOCK_INPUT;
760 /* fprintf (stderr, "%p malloc\n", value); */
761 return value;
765 /* This function is the realloc hook that Emacs uses. */
767 static void *
768 emacs_blocked_realloc (ptr, size)
769 void *ptr;
770 size_t size;
772 void *value;
774 BLOCK_INPUT;
775 __realloc_hook = old_realloc_hook;
777 #ifdef GC_MALLOC_CHECK
778 if (ptr)
780 struct mem_node *m = mem_find (ptr);
781 if (m == MEM_NIL || m->start != ptr)
783 fprintf (stderr,
784 "Realloc of %p which wasn't allocated with malloc\n",
785 ptr);
786 abort ();
789 mem_delete (m);
792 /* fprintf (stderr, "%p -> realloc\n", ptr); */
794 /* Prevent malloc from registering blocks. */
795 dont_register_blocks = 1;
796 #endif /* GC_MALLOC_CHECK */
798 value = (void *) realloc (ptr, size);
800 #ifdef GC_MALLOC_CHECK
801 dont_register_blocks = 0;
804 struct mem_node *m = mem_find (value);
805 if (m != MEM_NIL)
807 fprintf (stderr, "Realloc returns memory that is already in use\n");
808 abort ();
811 /* Can't handle zero size regions in the red-black tree. */
812 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
815 /* fprintf (stderr, "%p <- realloc\n", value); */
816 #endif /* GC_MALLOC_CHECK */
818 __realloc_hook = emacs_blocked_realloc;
819 UNBLOCK_INPUT;
821 return value;
825 /* Called from main to set up malloc to use our hooks. */
827 void
828 uninterrupt_malloc ()
830 if (__free_hook != emacs_blocked_free)
831 old_free_hook = __free_hook;
832 __free_hook = emacs_blocked_free;
834 if (__malloc_hook != emacs_blocked_malloc)
835 old_malloc_hook = __malloc_hook;
836 __malloc_hook = emacs_blocked_malloc;
838 if (__realloc_hook != emacs_blocked_realloc)
839 old_realloc_hook = __realloc_hook;
840 __realloc_hook = emacs_blocked_realloc;
843 #endif /* not SYSTEM_MALLOC */
847 /***********************************************************************
848 Interval Allocation
849 ***********************************************************************/
851 /* Number of intervals allocated in an interval_block structure.
852 The 1020 is 1024 minus malloc overhead. */
854 #define INTERVAL_BLOCK_SIZE \
855 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
857 /* Intervals are allocated in chunks in form of an interval_block
858 structure. */
860 struct interval_block
862 struct interval_block *next;
863 struct interval intervals[INTERVAL_BLOCK_SIZE];
866 /* Current interval block. Its `next' pointer points to older
867 blocks. */
869 struct interval_block *interval_block;
871 /* Index in interval_block above of the next unused interval
872 structure. */
874 static int interval_block_index;
876 /* Number of free and live intervals. */
878 static int total_free_intervals, total_intervals;
880 /* List of free intervals. */
882 INTERVAL interval_free_list;
884 /* Total number of interval blocks now in use. */
886 int n_interval_blocks;
889 /* Initialize interval allocation. */
891 static void
892 init_intervals ()
894 interval_block
895 = (struct interval_block *) lisp_malloc (sizeof *interval_block,
896 MEM_TYPE_NON_LISP);
897 interval_block->next = 0;
898 bzero ((char *) interval_block->intervals, sizeof interval_block->intervals);
899 interval_block_index = 0;
900 interval_free_list = 0;
901 n_interval_blocks = 1;
905 /* Return a new interval. */
907 INTERVAL
908 make_interval ()
910 INTERVAL val;
912 if (interval_free_list)
914 val = interval_free_list;
915 interval_free_list = INTERVAL_PARENT (interval_free_list);
917 else
919 if (interval_block_index == INTERVAL_BLOCK_SIZE)
921 register struct interval_block *newi;
923 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
924 MEM_TYPE_NON_LISP);
926 VALIDATE_LISP_STORAGE (newi, sizeof *newi);
927 newi->next = interval_block;
928 interval_block = newi;
929 interval_block_index = 0;
930 n_interval_blocks++;
932 val = &interval_block->intervals[interval_block_index++];
934 consing_since_gc += sizeof (struct interval);
935 intervals_consed++;
936 RESET_INTERVAL (val);
937 return val;
941 /* Mark Lisp objects in interval I. */
943 static void
944 mark_interval (i, dummy)
945 register INTERVAL i;
946 Lisp_Object dummy;
948 if (XMARKBIT (i->plist))
949 abort ();
950 mark_object (&i->plist);
951 XMARK (i->plist);
955 /* Mark the interval tree rooted in TREE. Don't call this directly;
956 use the macro MARK_INTERVAL_TREE instead. */
958 static void
959 mark_interval_tree (tree)
960 register INTERVAL tree;
962 /* No need to test if this tree has been marked already; this
963 function is always called through the MARK_INTERVAL_TREE macro,
964 which takes care of that. */
966 /* XMARK expands to an assignment; the LHS of an assignment can't be
967 a cast. */
968 XMARK (tree->up.obj);
970 traverse_intervals (tree, 1, 0, mark_interval, Qnil);
974 /* Mark the interval tree rooted in I. */
976 #define MARK_INTERVAL_TREE(i) \
977 do { \
978 if (!NULL_INTERVAL_P (i) \
979 && ! XMARKBIT (i->up.obj)) \
980 mark_interval_tree (i); \
981 } while (0)
984 /* The oddity in the call to XUNMARK is necessary because XUNMARK
985 expands to an assignment to its argument, and most C compilers
986 don't support casts on the left operand of `='. */
988 #define UNMARK_BALANCE_INTERVALS(i) \
989 do { \
990 if (! NULL_INTERVAL_P (i)) \
992 XUNMARK ((i)->up.obj); \
993 (i) = balance_intervals (i); \
995 } while (0)
998 /* Number support. If NO_UNION_TYPE isn't in effect, we
999 can't create number objects in macros. */
1000 #ifndef make_number
1001 Lisp_Object
1002 make_number (n)
1003 int n;
1005 Lisp_Object obj;
1006 obj.s.val = n;
1007 obj.s.type = Lisp_Int;
1008 return obj;
1010 #endif
1012 /***********************************************************************
1013 String Allocation
1014 ***********************************************************************/
1016 /* Lisp_Strings are allocated in string_block structures. When a new
1017 string_block is allocated, all the Lisp_Strings it contains are
1018 added to a free-list stiing_free_list. When a new Lisp_String is
1019 needed, it is taken from that list. During the sweep phase of GC,
1020 string_blocks that are entirely free are freed, except two which
1021 we keep.
1023 String data is allocated from sblock structures. Strings larger
1024 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1025 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1027 Sblocks consist internally of sdata structures, one for each
1028 Lisp_String. The sdata structure points to the Lisp_String it
1029 belongs to. The Lisp_String points back to the `u.data' member of
1030 its sdata structure.
1032 When a Lisp_String is freed during GC, it is put back on
1033 string_free_list, and its `data' member and its sdata's `string'
1034 pointer is set to null. The size of the string is recorded in the
1035 `u.nbytes' member of the sdata. So, sdata structures that are no
1036 longer used, can be easily recognized, and it's easy to compact the
1037 sblocks of small strings which we do in compact_small_strings. */
1039 /* Size in bytes of an sblock structure used for small strings. This
1040 is 8192 minus malloc overhead. */
1042 #define SBLOCK_SIZE 8188
1044 /* Strings larger than this are considered large strings. String data
1045 for large strings is allocated from individual sblocks. */
1047 #define LARGE_STRING_BYTES 1024
1049 /* Structure describing string memory sub-allocated from an sblock.
1050 This is where the contents of Lisp strings are stored. */
1052 struct sdata
1054 /* Back-pointer to the string this sdata belongs to. If null, this
1055 structure is free, and the NBYTES member of the union below
1056 contains the string's byte size (the same value that STRING_BYTES
1057 would return if STRING were non-null). If non-null, STRING_BYTES
1058 (STRING) is the size of the data, and DATA contains the string's
1059 contents. */
1060 struct Lisp_String *string;
1062 #ifdef GC_CHECK_STRING_BYTES
1064 EMACS_INT nbytes;
1065 unsigned char data[1];
1067 #define SDATA_NBYTES(S) (S)->nbytes
1068 #define SDATA_DATA(S) (S)->data
1070 #else /* not GC_CHECK_STRING_BYTES */
1072 union
1074 /* When STRING in non-null. */
1075 unsigned char data[1];
1077 /* When STRING is null. */
1078 EMACS_INT nbytes;
1079 } u;
1082 #define SDATA_NBYTES(S) (S)->u.nbytes
1083 #define SDATA_DATA(S) (S)->u.data
1085 #endif /* not GC_CHECK_STRING_BYTES */
1089 /* Structure describing a block of memory which is sub-allocated to
1090 obtain string data memory for strings. Blocks for small strings
1091 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1092 as large as needed. */
1094 struct sblock
1096 /* Next in list. */
1097 struct sblock *next;
1099 /* Pointer to the next free sdata block. This points past the end
1100 of the sblock if there isn't any space left in this block. */
1101 struct sdata *next_free;
1103 /* Start of data. */
1104 struct sdata first_data;
1107 /* Number of Lisp strings in a string_block structure. The 1020 is
1108 1024 minus malloc overhead. */
1110 #define STRINGS_IN_STRING_BLOCK \
1111 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1113 /* Structure describing a block from which Lisp_String structures
1114 are allocated. */
1116 struct string_block
1118 struct string_block *next;
1119 struct Lisp_String strings[STRINGS_IN_STRING_BLOCK];
1122 /* Head and tail of the list of sblock structures holding Lisp string
1123 data. We always allocate from current_sblock. The NEXT pointers
1124 in the sblock structures go from oldest_sblock to current_sblock. */
1126 static struct sblock *oldest_sblock, *current_sblock;
1128 /* List of sblocks for large strings. */
1130 static struct sblock *large_sblocks;
1132 /* List of string_block structures, and how many there are. */
1134 static struct string_block *string_blocks;
1135 static int n_string_blocks;
1137 /* Free-list of Lisp_Strings. */
1139 static struct Lisp_String *string_free_list;
1141 /* Number of live and free Lisp_Strings. */
1143 static int total_strings, total_free_strings;
1145 /* Number of bytes used by live strings. */
1147 static int total_string_size;
1149 /* Given a pointer to a Lisp_String S which is on the free-list
1150 string_free_list, return a pointer to its successor in the
1151 free-list. */
1153 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1155 /* Return a pointer to the sdata structure belonging to Lisp string S.
1156 S must be live, i.e. S->data must not be null. S->data is actually
1157 a pointer to the `u.data' member of its sdata structure; the
1158 structure starts at a constant offset in front of that. */
1160 #ifdef GC_CHECK_STRING_BYTES
1162 #define SDATA_OF_STRING(S) \
1163 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *) \
1164 - sizeof (EMACS_INT)))
1166 #else /* not GC_CHECK_STRING_BYTES */
1168 #define SDATA_OF_STRING(S) \
1169 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))
1171 #endif /* not GC_CHECK_STRING_BYTES */
1173 /* Value is the size of an sdata structure large enough to hold NBYTES
1174 bytes of string data. The value returned includes a terminating
1175 NUL byte, the size of the sdata structure, and padding. */
1177 #ifdef GC_CHECK_STRING_BYTES
1179 #define SDATA_SIZE(NBYTES) \
1180 ((sizeof (struct Lisp_String *) \
1181 + (NBYTES) + 1 \
1182 + sizeof (EMACS_INT) \
1183 + sizeof (EMACS_INT) - 1) \
1184 & ~(sizeof (EMACS_INT) - 1))
1186 #else /* not GC_CHECK_STRING_BYTES */
1188 #define SDATA_SIZE(NBYTES) \
1189 ((sizeof (struct Lisp_String *) \
1190 + (NBYTES) + 1 \
1191 + sizeof (EMACS_INT) - 1) \
1192 & ~(sizeof (EMACS_INT) - 1))
1194 #endif /* not GC_CHECK_STRING_BYTES */
1196 /* Initialize string allocation. Called from init_alloc_once. */
1198 void
1199 init_strings ()
1201 total_strings = total_free_strings = total_string_size = 0;
1202 oldest_sblock = current_sblock = large_sblocks = NULL;
1203 string_blocks = NULL;
1204 n_string_blocks = 0;
1205 string_free_list = NULL;
1209 #ifdef GC_CHECK_STRING_BYTES
1211 static int check_string_bytes_count;
1213 void check_string_bytes P_ ((int));
1214 void check_sblock P_ ((struct sblock *));
1216 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1219 /* Like GC_STRING_BYTES, but with debugging check. */
1222 string_bytes (s)
1223 struct Lisp_String *s;
1225 int nbytes = (s->size_byte < 0 ? s->size : s->size_byte) & ~MARKBIT;
1226 if (!PURE_POINTER_P (s)
1227 && s->data
1228 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1229 abort ();
1230 return nbytes;
1233 /* Check validity Lisp strings' string_bytes member in B. */
1235 void
1236 check_sblock (b)
1237 struct sblock *b;
1239 struct sdata *from, *end, *from_end;
1241 end = b->next_free;
1243 for (from = &b->first_data; from < end; from = from_end)
1245 /* Compute the next FROM here because copying below may
1246 overwrite data we need to compute it. */
1247 int nbytes;
1249 /* Check that the string size recorded in the string is the
1250 same as the one recorded in the sdata structure. */
1251 if (from->string)
1252 CHECK_STRING_BYTES (from->string);
1254 if (from->string)
1255 nbytes = GC_STRING_BYTES (from->string);
1256 else
1257 nbytes = SDATA_NBYTES (from);
1259 nbytes = SDATA_SIZE (nbytes);
1260 from_end = (struct sdata *) ((char *) from + nbytes);
1265 /* Check validity of Lisp strings' string_bytes member. ALL_P
1266 non-zero means check all strings, otherwise check only most
1267 recently allocated strings. Used for hunting a bug. */
1269 void
1270 check_string_bytes (all_p)
1271 int all_p;
1273 if (all_p)
1275 struct sblock *b;
1277 for (b = large_sblocks; b; b = b->next)
1279 struct Lisp_String *s = b->first_data.string;
1280 if (s)
1281 CHECK_STRING_BYTES (s);
1284 for (b = oldest_sblock; b; b = b->next)
1285 check_sblock (b);
1287 else
1288 check_sblock (current_sblock);
1291 #endif /* GC_CHECK_STRING_BYTES */
1294 /* Return a new Lisp_String. */
1296 static struct Lisp_String *
1297 allocate_string ()
1299 struct Lisp_String *s;
1301 /* If the free-list is empty, allocate a new string_block, and
1302 add all the Lisp_Strings in it to the free-list. */
1303 if (string_free_list == NULL)
1305 struct string_block *b;
1306 int i;
1308 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1309 VALIDATE_LISP_STORAGE (b, sizeof *b);
1310 bzero (b, sizeof *b);
1311 b->next = string_blocks;
1312 string_blocks = b;
1313 ++n_string_blocks;
1315 for (i = STRINGS_IN_STRING_BLOCK - 1; i >= 0; --i)
1317 s = b->strings + i;
1318 NEXT_FREE_LISP_STRING (s) = string_free_list;
1319 string_free_list = s;
1322 total_free_strings += STRINGS_IN_STRING_BLOCK;
1325 /* Pop a Lisp_String off the free-list. */
1326 s = string_free_list;
1327 string_free_list = NEXT_FREE_LISP_STRING (s);
1329 /* Probably not strictly necessary, but play it safe. */
1330 bzero (s, sizeof *s);
1332 --total_free_strings;
1333 ++total_strings;
1334 ++strings_consed;
1335 consing_since_gc += sizeof *s;
1337 #ifdef GC_CHECK_STRING_BYTES
1338 if (!noninteractive
1339 #ifdef macintosh
1340 && current_sblock
1341 #endif
1344 if (++check_string_bytes_count == 200)
1346 check_string_bytes_count = 0;
1347 check_string_bytes (1);
1349 else
1350 check_string_bytes (0);
1352 #endif /* GC_CHECK_STRING_BYTES */
1354 return s;
1358 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1359 plus a NUL byte at the end. Allocate an sdata structure for S, and
1360 set S->data to its `u.data' member. Store a NUL byte at the end of
1361 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1362 S->data if it was initially non-null. */
1364 void
1365 allocate_string_data (s, nchars, nbytes)
1366 struct Lisp_String *s;
1367 int nchars, nbytes;
1369 struct sdata *data, *old_data;
1370 struct sblock *b;
1371 int needed, old_nbytes;
1373 /* Determine the number of bytes needed to store NBYTES bytes
1374 of string data. */
1375 needed = SDATA_SIZE (nbytes);
1377 if (nbytes > LARGE_STRING_BYTES)
1379 size_t size = sizeof *b - sizeof (struct sdata) + needed;
1381 #ifdef DOUG_LEA_MALLOC
1382 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1383 because mapped region contents are not preserved in
1384 a dumped Emacs. */
1385 mallopt (M_MMAP_MAX, 0);
1386 #endif
1388 b = (struct sblock *) lisp_malloc (size, MEM_TYPE_NON_LISP);
1390 #ifdef DOUG_LEA_MALLOC
1391 /* Back to a reasonable maximum of mmap'ed areas. */
1392 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1393 #endif
1395 b->next_free = &b->first_data;
1396 b->first_data.string = NULL;
1397 b->next = large_sblocks;
1398 large_sblocks = b;
1400 else if (current_sblock == NULL
1401 || (((char *) current_sblock + SBLOCK_SIZE
1402 - (char *) current_sblock->next_free)
1403 < needed))
1405 /* Not enough room in the current sblock. */
1406 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1407 b->next_free = &b->first_data;
1408 b->first_data.string = NULL;
1409 b->next = NULL;
1411 if (current_sblock)
1412 current_sblock->next = b;
1413 else
1414 oldest_sblock = b;
1415 current_sblock = b;
1417 else
1418 b = current_sblock;
1420 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1421 old_nbytes = GC_STRING_BYTES (s);
1423 data = b->next_free;
1424 data->string = s;
1425 s->data = SDATA_DATA (data);
1426 #ifdef GC_CHECK_STRING_BYTES
1427 SDATA_NBYTES (data) = nbytes;
1428 #endif
1429 s->size = nchars;
1430 s->size_byte = nbytes;
1431 s->data[nbytes] = '\0';
1432 b->next_free = (struct sdata *) ((char *) data + needed);
1434 /* If S had already data assigned, mark that as free by setting its
1435 string back-pointer to null, and recording the size of the data
1436 in it. */
1437 if (old_data)
1439 SDATA_NBYTES (old_data) = old_nbytes;
1440 old_data->string = NULL;
1443 consing_since_gc += needed;
1447 /* Sweep and compact strings. */
1449 static void
1450 sweep_strings ()
1452 struct string_block *b, *next;
1453 struct string_block *live_blocks = NULL;
1455 string_free_list = NULL;
1456 total_strings = total_free_strings = 0;
1457 total_string_size = 0;
1459 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1460 for (b = string_blocks; b; b = next)
1462 int i, nfree = 0;
1463 struct Lisp_String *free_list_before = string_free_list;
1465 next = b->next;
1467 for (i = 0; i < STRINGS_IN_STRING_BLOCK; ++i)
1469 struct Lisp_String *s = b->strings + i;
1471 if (s->data)
1473 /* String was not on free-list before. */
1474 if (STRING_MARKED_P (s))
1476 /* String is live; unmark it and its intervals. */
1477 UNMARK_STRING (s);
1479 if (!NULL_INTERVAL_P (s->intervals))
1480 UNMARK_BALANCE_INTERVALS (s->intervals);
1482 ++total_strings;
1483 total_string_size += STRING_BYTES (s);
1485 else
1487 /* String is dead. Put it on the free-list. */
1488 struct sdata *data = SDATA_OF_STRING (s);
1490 /* Save the size of S in its sdata so that we know
1491 how large that is. Reset the sdata's string
1492 back-pointer so that we know it's free. */
1493 #ifdef GC_CHECK_STRING_BYTES
1494 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
1495 abort ();
1496 #else
1497 data->u.nbytes = GC_STRING_BYTES (s);
1498 #endif
1499 data->string = NULL;
1501 /* Reset the strings's `data' member so that we
1502 know it's free. */
1503 s->data = NULL;
1505 /* Put the string on the free-list. */
1506 NEXT_FREE_LISP_STRING (s) = string_free_list;
1507 string_free_list = s;
1508 ++nfree;
1511 else
1513 /* S was on the free-list before. Put it there again. */
1514 NEXT_FREE_LISP_STRING (s) = string_free_list;
1515 string_free_list = s;
1516 ++nfree;
1520 /* Free blocks that contain free Lisp_Strings only, except
1521 the first two of them. */
1522 if (nfree == STRINGS_IN_STRING_BLOCK
1523 && total_free_strings > STRINGS_IN_STRING_BLOCK)
1525 lisp_free (b);
1526 --n_string_blocks;
1527 string_free_list = free_list_before;
1529 else
1531 total_free_strings += nfree;
1532 b->next = live_blocks;
1533 live_blocks = b;
1537 string_blocks = live_blocks;
1538 free_large_strings ();
1539 compact_small_strings ();
1543 /* Free dead large strings. */
1545 static void
1546 free_large_strings ()
1548 struct sblock *b, *next;
1549 struct sblock *live_blocks = NULL;
1551 for (b = large_sblocks; b; b = next)
1553 next = b->next;
1555 if (b->first_data.string == NULL)
1556 lisp_free (b);
1557 else
1559 b->next = live_blocks;
1560 live_blocks = b;
1564 large_sblocks = live_blocks;
1568 /* Compact data of small strings. Free sblocks that don't contain
1569 data of live strings after compaction. */
1571 static void
1572 compact_small_strings ()
1574 struct sblock *b, *tb, *next;
1575 struct sdata *from, *to, *end, *tb_end;
1576 struct sdata *to_end, *from_end;
1578 /* TB is the sblock we copy to, TO is the sdata within TB we copy
1579 to, and TB_END is the end of TB. */
1580 tb = oldest_sblock;
1581 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1582 to = &tb->first_data;
1584 /* Step through the blocks from the oldest to the youngest. We
1585 expect that old blocks will stabilize over time, so that less
1586 copying will happen this way. */
1587 for (b = oldest_sblock; b; b = b->next)
1589 end = b->next_free;
1590 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
1592 for (from = &b->first_data; from < end; from = from_end)
1594 /* Compute the next FROM here because copying below may
1595 overwrite data we need to compute it. */
1596 int nbytes;
1598 #ifdef GC_CHECK_STRING_BYTES
1599 /* Check that the string size recorded in the string is the
1600 same as the one recorded in the sdata structure. */
1601 if (from->string
1602 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
1603 abort ();
1604 #endif /* GC_CHECK_STRING_BYTES */
1606 if (from->string)
1607 nbytes = GC_STRING_BYTES (from->string);
1608 else
1609 nbytes = SDATA_NBYTES (from);
1611 nbytes = SDATA_SIZE (nbytes);
1612 from_end = (struct sdata *) ((char *) from + nbytes);
1614 /* FROM->string non-null means it's alive. Copy its data. */
1615 if (from->string)
1617 /* If TB is full, proceed with the next sblock. */
1618 to_end = (struct sdata *) ((char *) to + nbytes);
1619 if (to_end > tb_end)
1621 tb->next_free = to;
1622 tb = tb->next;
1623 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1624 to = &tb->first_data;
1625 to_end = (struct sdata *) ((char *) to + nbytes);
1628 /* Copy, and update the string's `data' pointer. */
1629 if (from != to)
1631 xassert (tb != b || to <= from);
1632 safe_bcopy ((char *) from, (char *) to, nbytes);
1633 to->string->data = SDATA_DATA (to);
1636 /* Advance past the sdata we copied to. */
1637 to = to_end;
1642 /* The rest of the sblocks following TB don't contain live data, so
1643 we can free them. */
1644 for (b = tb->next; b; b = next)
1646 next = b->next;
1647 lisp_free (b);
1650 tb->next_free = to;
1651 tb->next = NULL;
1652 current_sblock = tb;
1656 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
1657 "Return a newly created string of length LENGTH, with each element being INIT.\n\
1658 Both LENGTH and INIT must be numbers.")
1659 (length, init)
1660 Lisp_Object length, init;
1662 register Lisp_Object val;
1663 register unsigned char *p, *end;
1664 int c, nbytes;
1666 CHECK_NATNUM (length, 0);
1667 CHECK_NUMBER (init, 1);
1669 c = XINT (init);
1670 if (SINGLE_BYTE_CHAR_P (c))
1672 nbytes = XINT (length);
1673 val = make_uninit_string (nbytes);
1674 p = XSTRING (val)->data;
1675 end = p + XSTRING (val)->size;
1676 while (p != end)
1677 *p++ = c;
1679 else
1681 unsigned char str[MAX_MULTIBYTE_LENGTH];
1682 int len = CHAR_STRING (c, str);
1684 nbytes = len * XINT (length);
1685 val = make_uninit_multibyte_string (XINT (length), nbytes);
1686 p = XSTRING (val)->data;
1687 end = p + nbytes;
1688 while (p != end)
1690 bcopy (str, p, len);
1691 p += len;
1695 *p = 0;
1696 return val;
1700 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
1701 "Return a new bool-vector of length LENGTH, using INIT for as each element.\n\
1702 LENGTH must be a number. INIT matters only in whether it is t or nil.")
1703 (length, init)
1704 Lisp_Object length, init;
1706 register Lisp_Object val;
1707 struct Lisp_Bool_Vector *p;
1708 int real_init, i;
1709 int length_in_chars, length_in_elts, bits_per_value;
1711 CHECK_NATNUM (length, 0);
1713 bits_per_value = sizeof (EMACS_INT) * BITS_PER_CHAR;
1715 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
1716 length_in_chars = ((XFASTINT (length) + BITS_PER_CHAR - 1) / BITS_PER_CHAR);
1718 /* We must allocate one more elements than LENGTH_IN_ELTS for the
1719 slot `size' of the struct Lisp_Bool_Vector. */
1720 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
1721 p = XBOOL_VECTOR (val);
1723 /* Get rid of any bits that would cause confusion. */
1724 p->vector_size = 0;
1725 XSETBOOL_VECTOR (val, p);
1726 p->size = XFASTINT (length);
1728 real_init = (NILP (init) ? 0 : -1);
1729 for (i = 0; i < length_in_chars ; i++)
1730 p->data[i] = real_init;
1732 /* Clear the extraneous bits in the last byte. */
1733 if (XINT (length) != length_in_chars * BITS_PER_CHAR)
1734 XBOOL_VECTOR (val)->data[length_in_chars - 1]
1735 &= (1 << (XINT (length) % BITS_PER_CHAR)) - 1;
1737 return val;
1741 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
1742 of characters from the contents. This string may be unibyte or
1743 multibyte, depending on the contents. */
1745 Lisp_Object
1746 make_string (contents, nbytes)
1747 char *contents;
1748 int nbytes;
1750 register Lisp_Object val;
1751 int nchars, multibyte_nbytes;
1753 parse_str_as_multibyte (contents, nbytes, &nchars, &multibyte_nbytes);
1754 if (nbytes == nchars || nbytes != multibyte_nbytes)
1755 /* CONTENTS contains no multibyte sequences or contains an invalid
1756 multibyte sequence. We must make unibyte string. */
1757 val = make_unibyte_string (contents, nbytes);
1758 else
1759 val = make_multibyte_string (contents, nchars, nbytes);
1760 return val;
1764 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
1766 Lisp_Object
1767 make_unibyte_string (contents, length)
1768 char *contents;
1769 int length;
1771 register Lisp_Object val;
1772 val = make_uninit_string (length);
1773 bcopy (contents, XSTRING (val)->data, length);
1774 SET_STRING_BYTES (XSTRING (val), -1);
1775 return val;
1779 /* Make a multibyte string from NCHARS characters occupying NBYTES
1780 bytes at CONTENTS. */
1782 Lisp_Object
1783 make_multibyte_string (contents, nchars, nbytes)
1784 char *contents;
1785 int nchars, nbytes;
1787 register Lisp_Object val;
1788 val = make_uninit_multibyte_string (nchars, nbytes);
1789 bcopy (contents, XSTRING (val)->data, nbytes);
1790 return val;
1794 /* Make a string from NCHARS characters occupying NBYTES bytes at
1795 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
1797 Lisp_Object
1798 make_string_from_bytes (contents, nchars, nbytes)
1799 char *contents;
1800 int nchars, nbytes;
1802 register Lisp_Object val;
1803 val = make_uninit_multibyte_string (nchars, nbytes);
1804 bcopy (contents, XSTRING (val)->data, nbytes);
1805 if (STRING_BYTES (XSTRING (val)) == XSTRING (val)->size)
1806 SET_STRING_BYTES (XSTRING (val), -1);
1807 return val;
1811 /* Make a string from NCHARS characters occupying NBYTES bytes at
1812 CONTENTS. The argument MULTIBYTE controls whether to label the
1813 string as multibyte. */
1815 Lisp_Object
1816 make_specified_string (contents, nchars, nbytes, multibyte)
1817 char *contents;
1818 int nchars, nbytes;
1819 int multibyte;
1821 register Lisp_Object val;
1822 val = make_uninit_multibyte_string (nchars, nbytes);
1823 bcopy (contents, XSTRING (val)->data, nbytes);
1824 if (!multibyte)
1825 SET_STRING_BYTES (XSTRING (val), -1);
1826 return val;
1830 /* Make a string from the data at STR, treating it as multibyte if the
1831 data warrants. */
1833 Lisp_Object
1834 build_string (str)
1835 char *str;
1837 return make_string (str, strlen (str));
1841 /* Return an unibyte Lisp_String set up to hold LENGTH characters
1842 occupying LENGTH bytes. */
1844 Lisp_Object
1845 make_uninit_string (length)
1846 int length;
1848 Lisp_Object val;
1849 val = make_uninit_multibyte_string (length, length);
1850 SET_STRING_BYTES (XSTRING (val), -1);
1851 return val;
1855 /* Return a multibyte Lisp_String set up to hold NCHARS characters
1856 which occupy NBYTES bytes. */
1858 Lisp_Object
1859 make_uninit_multibyte_string (nchars, nbytes)
1860 int nchars, nbytes;
1862 Lisp_Object string;
1863 struct Lisp_String *s;
1865 if (nchars < 0)
1866 abort ();
1868 s = allocate_string ();
1869 allocate_string_data (s, nchars, nbytes);
1870 XSETSTRING (string, s);
1871 string_chars_consed += nbytes;
1872 return string;
1877 /***********************************************************************
1878 Float Allocation
1879 ***********************************************************************/
1881 /* We store float cells inside of float_blocks, allocating a new
1882 float_block with malloc whenever necessary. Float cells reclaimed
1883 by GC are put on a free list to be reallocated before allocating
1884 any new float cells from the latest float_block.
1886 Each float_block is just under 1020 bytes long, since malloc really
1887 allocates in units of powers of two and uses 4 bytes for its own
1888 overhead. */
1890 #define FLOAT_BLOCK_SIZE \
1891 ((1020 - sizeof (struct float_block *)) / sizeof (struct Lisp_Float))
1893 struct float_block
1895 struct float_block *next;
1896 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
1899 /* Current float_block. */
1901 struct float_block *float_block;
1903 /* Index of first unused Lisp_Float in the current float_block. */
1905 int float_block_index;
1907 /* Total number of float blocks now in use. */
1909 int n_float_blocks;
1911 /* Free-list of Lisp_Floats. */
1913 struct Lisp_Float *float_free_list;
1916 /* Initialze float allocation. */
1918 void
1919 init_float ()
1921 float_block = (struct float_block *) lisp_malloc (sizeof *float_block,
1922 MEM_TYPE_FLOAT);
1923 float_block->next = 0;
1924 bzero ((char *) float_block->floats, sizeof float_block->floats);
1925 float_block_index = 0;
1926 float_free_list = 0;
1927 n_float_blocks = 1;
1931 /* Explicitly free a float cell by putting it on the free-list. */
1933 void
1934 free_float (ptr)
1935 struct Lisp_Float *ptr;
1937 *(struct Lisp_Float **)&ptr->data = float_free_list;
1938 #if GC_MARK_STACK
1939 ptr->type = Vdead;
1940 #endif
1941 float_free_list = ptr;
1945 /* Return a new float object with value FLOAT_VALUE. */
1947 Lisp_Object
1948 make_float (float_value)
1949 double float_value;
1951 register Lisp_Object val;
1953 if (float_free_list)
1955 /* We use the data field for chaining the free list
1956 so that we won't use the same field that has the mark bit. */
1957 XSETFLOAT (val, float_free_list);
1958 float_free_list = *(struct Lisp_Float **)&float_free_list->data;
1960 else
1962 if (float_block_index == FLOAT_BLOCK_SIZE)
1964 register struct float_block *new;
1966 new = (struct float_block *) lisp_malloc (sizeof *new,
1967 MEM_TYPE_FLOAT);
1968 VALIDATE_LISP_STORAGE (new, sizeof *new);
1969 new->next = float_block;
1970 float_block = new;
1971 float_block_index = 0;
1972 n_float_blocks++;
1974 XSETFLOAT (val, &float_block->floats[float_block_index++]);
1977 XFLOAT_DATA (val) = float_value;
1978 XSETFASTINT (XFLOAT (val)->type, 0); /* bug chasing -wsr */
1979 consing_since_gc += sizeof (struct Lisp_Float);
1980 floats_consed++;
1981 return val;
1986 /***********************************************************************
1987 Cons Allocation
1988 ***********************************************************************/
1990 /* We store cons cells inside of cons_blocks, allocating a new
1991 cons_block with malloc whenever necessary. Cons cells reclaimed by
1992 GC are put on a free list to be reallocated before allocating
1993 any new cons cells from the latest cons_block.
1995 Each cons_block is just under 1020 bytes long,
1996 since malloc really allocates in units of powers of two
1997 and uses 4 bytes for its own overhead. */
1999 #define CONS_BLOCK_SIZE \
2000 ((1020 - sizeof (struct cons_block *)) / sizeof (struct Lisp_Cons))
2002 struct cons_block
2004 struct cons_block *next;
2005 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2008 /* Current cons_block. */
2010 struct cons_block *cons_block;
2012 /* Index of first unused Lisp_Cons in the current block. */
2014 int cons_block_index;
2016 /* Free-list of Lisp_Cons structures. */
2018 struct Lisp_Cons *cons_free_list;
2020 /* Total number of cons blocks now in use. */
2022 int n_cons_blocks;
2025 /* Initialize cons allocation. */
2027 void
2028 init_cons ()
2030 cons_block = (struct cons_block *) lisp_malloc (sizeof *cons_block,
2031 MEM_TYPE_CONS);
2032 cons_block->next = 0;
2033 bzero ((char *) cons_block->conses, sizeof cons_block->conses);
2034 cons_block_index = 0;
2035 cons_free_list = 0;
2036 n_cons_blocks = 1;
2040 /* Explicitly free a cons cell by putting it on the free-list. */
2042 void
2043 free_cons (ptr)
2044 struct Lisp_Cons *ptr;
2046 *(struct Lisp_Cons **)&ptr->cdr = cons_free_list;
2047 #if GC_MARK_STACK
2048 ptr->car = Vdead;
2049 #endif
2050 cons_free_list = ptr;
2054 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2055 "Create a new cons, give it CAR and CDR as components, and return it.")
2056 (car, cdr)
2057 Lisp_Object car, cdr;
2059 register Lisp_Object val;
2061 if (cons_free_list)
2063 /* We use the cdr for chaining the free list
2064 so that we won't use the same field that has the mark bit. */
2065 XSETCONS (val, cons_free_list);
2066 cons_free_list = *(struct Lisp_Cons **)&cons_free_list->cdr;
2068 else
2070 if (cons_block_index == CONS_BLOCK_SIZE)
2072 register struct cons_block *new;
2073 new = (struct cons_block *) lisp_malloc (sizeof *new,
2074 MEM_TYPE_CONS);
2075 VALIDATE_LISP_STORAGE (new, sizeof *new);
2076 new->next = cons_block;
2077 cons_block = new;
2078 cons_block_index = 0;
2079 n_cons_blocks++;
2081 XSETCONS (val, &cons_block->conses[cons_block_index++]);
2084 XCAR (val) = car;
2085 XCDR (val) = cdr;
2086 consing_since_gc += sizeof (struct Lisp_Cons);
2087 cons_cells_consed++;
2088 return val;
2092 /* Make a list of 2, 3, 4 or 5 specified objects. */
2094 Lisp_Object
2095 list2 (arg1, arg2)
2096 Lisp_Object arg1, arg2;
2098 return Fcons (arg1, Fcons (arg2, Qnil));
2102 Lisp_Object
2103 list3 (arg1, arg2, arg3)
2104 Lisp_Object arg1, arg2, arg3;
2106 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2110 Lisp_Object
2111 list4 (arg1, arg2, arg3, arg4)
2112 Lisp_Object arg1, arg2, arg3, arg4;
2114 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2118 Lisp_Object
2119 list5 (arg1, arg2, arg3, arg4, arg5)
2120 Lisp_Object arg1, arg2, arg3, arg4, arg5;
2122 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2123 Fcons (arg5, Qnil)))));
2127 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2128 "Return a newly created list with specified arguments as elements.\n\
2129 Any number of arguments, even zero arguments, are allowed.")
2130 (nargs, args)
2131 int nargs;
2132 register Lisp_Object *args;
2134 register Lisp_Object val;
2135 val = Qnil;
2137 while (nargs > 0)
2139 nargs--;
2140 val = Fcons (args[nargs], val);
2142 return val;
2146 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2147 "Return a newly created list of length LENGTH, with each element being INIT.")
2148 (length, init)
2149 register Lisp_Object length, init;
2151 register Lisp_Object val;
2152 register int size;
2154 CHECK_NATNUM (length, 0);
2155 size = XFASTINT (length);
2157 val = Qnil;
2158 while (size > 0)
2160 val = Fcons (init, val);
2161 --size;
2163 if (size > 0)
2165 val = Fcons (init, val);
2166 --size;
2168 if (size > 0)
2170 val = Fcons (init, val);
2171 --size;
2173 if (size > 0)
2175 val = Fcons (init, val);
2176 --size;
2178 if (size > 0)
2180 val = Fcons (init, val);
2181 --size;
2187 QUIT;
2190 return val;
2195 /***********************************************************************
2196 Vector Allocation
2197 ***********************************************************************/
2199 /* Singly-linked list of all vectors. */
2201 struct Lisp_Vector *all_vectors;
2203 /* Total number of vector-like objects now in use. */
2205 int n_vectors;
2208 /* Value is a pointer to a newly allocated Lisp_Vector structure
2209 with room for LEN Lisp_Objects. */
2211 static struct Lisp_Vector *
2212 allocate_vectorlike (len, type)
2213 EMACS_INT len;
2214 enum mem_type type;
2216 struct Lisp_Vector *p;
2217 size_t nbytes;
2219 #ifdef DOUG_LEA_MALLOC
2220 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2221 because mapped region contents are not preserved in
2222 a dumped Emacs. */
2223 mallopt (M_MMAP_MAX, 0);
2224 #endif
2226 nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
2227 p = (struct Lisp_Vector *) lisp_malloc (nbytes, type);
2229 #ifdef DOUG_LEA_MALLOC
2230 /* Back to a reasonable maximum of mmap'ed areas. */
2231 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2232 #endif
2234 VALIDATE_LISP_STORAGE (p, 0);
2235 consing_since_gc += nbytes;
2236 vector_cells_consed += len;
2238 p->next = all_vectors;
2239 all_vectors = p;
2240 ++n_vectors;
2241 return p;
2245 /* Allocate a vector with NSLOTS slots. */
2247 struct Lisp_Vector *
2248 allocate_vector (nslots)
2249 EMACS_INT nslots;
2251 struct Lisp_Vector *v = allocate_vectorlike (nslots, MEM_TYPE_VECTOR);
2252 v->size = nslots;
2253 return v;
2257 /* Allocate other vector-like structures. */
2259 struct Lisp_Hash_Table *
2260 allocate_hash_table ()
2262 EMACS_INT len = VECSIZE (struct Lisp_Hash_Table);
2263 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_HASH_TABLE);
2264 EMACS_INT i;
2266 v->size = len;
2267 for (i = 0; i < len; ++i)
2268 v->contents[i] = Qnil;
2270 return (struct Lisp_Hash_Table *) v;
2274 struct window *
2275 allocate_window ()
2277 EMACS_INT len = VECSIZE (struct window);
2278 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_WINDOW);
2279 EMACS_INT i;
2281 for (i = 0; i < len; ++i)
2282 v->contents[i] = Qnil;
2283 v->size = len;
2285 return (struct window *) v;
2289 struct frame *
2290 allocate_frame ()
2292 EMACS_INT len = VECSIZE (struct frame);
2293 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_FRAME);
2294 EMACS_INT i;
2296 for (i = 0; i < len; ++i)
2297 v->contents[i] = make_number (0);
2298 v->size = len;
2299 return (struct frame *) v;
2303 struct Lisp_Process *
2304 allocate_process ()
2306 EMACS_INT len = VECSIZE (struct Lisp_Process);
2307 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_PROCESS);
2308 EMACS_INT i;
2310 for (i = 0; i < len; ++i)
2311 v->contents[i] = Qnil;
2312 v->size = len;
2314 return (struct Lisp_Process *) v;
2318 struct Lisp_Vector *
2319 allocate_other_vector (len)
2320 EMACS_INT len;
2322 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_VECTOR);
2323 EMACS_INT i;
2325 for (i = 0; i < len; ++i)
2326 v->contents[i] = Qnil;
2327 v->size = len;
2329 return v;
2333 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
2334 "Return a newly created vector of length LENGTH, with each element being INIT.\n\
2335 See also the function `vector'.")
2336 (length, init)
2337 register Lisp_Object length, init;
2339 Lisp_Object vector;
2340 register EMACS_INT sizei;
2341 register int index;
2342 register struct Lisp_Vector *p;
2344 CHECK_NATNUM (length, 0);
2345 sizei = XFASTINT (length);
2347 p = allocate_vector (sizei);
2348 for (index = 0; index < sizei; index++)
2349 p->contents[index] = init;
2351 XSETVECTOR (vector, p);
2352 return vector;
2356 DEFUN ("make-char-table", Fmake_char_table, Smake_char_table, 1, 2, 0,
2357 "Return a newly created char-table, with purpose PURPOSE.\n\
2358 Each element is initialized to INIT, which defaults to nil.\n\
2359 PURPOSE should be a symbol which has a `char-table-extra-slots' property.\n\
2360 The property's value should be an integer between 0 and 10.")
2361 (purpose, init)
2362 register Lisp_Object purpose, init;
2364 Lisp_Object vector;
2365 Lisp_Object n;
2366 CHECK_SYMBOL (purpose, 1);
2367 n = Fget (purpose, Qchar_table_extra_slots);
2368 CHECK_NUMBER (n, 0);
2369 if (XINT (n) < 0 || XINT (n) > 10)
2370 args_out_of_range (n, Qnil);
2371 /* Add 2 to the size for the defalt and parent slots. */
2372 vector = Fmake_vector (make_number (CHAR_TABLE_STANDARD_SLOTS + XINT (n)),
2373 init);
2374 XCHAR_TABLE (vector)->top = Qt;
2375 XCHAR_TABLE (vector)->parent = Qnil;
2376 XCHAR_TABLE (vector)->purpose = purpose;
2377 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
2378 return vector;
2382 /* Return a newly created sub char table with default value DEFALT.
2383 Since a sub char table does not appear as a top level Emacs Lisp
2384 object, we don't need a Lisp interface to make it. */
2386 Lisp_Object
2387 make_sub_char_table (defalt)
2388 Lisp_Object defalt;
2390 Lisp_Object vector
2391 = Fmake_vector (make_number (SUB_CHAR_TABLE_STANDARD_SLOTS), Qnil);
2392 XCHAR_TABLE (vector)->top = Qnil;
2393 XCHAR_TABLE (vector)->defalt = defalt;
2394 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
2395 return vector;
2399 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
2400 "Return a newly created vector with specified arguments as elements.\n\
2401 Any number of arguments, even zero arguments, are allowed.")
2402 (nargs, args)
2403 register int nargs;
2404 Lisp_Object *args;
2406 register Lisp_Object len, val;
2407 register int index;
2408 register struct Lisp_Vector *p;
2410 XSETFASTINT (len, nargs);
2411 val = Fmake_vector (len, Qnil);
2412 p = XVECTOR (val);
2413 for (index = 0; index < nargs; index++)
2414 p->contents[index] = args[index];
2415 return val;
2419 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
2420 "Create a byte-code object with specified arguments as elements.\n\
2421 The arguments should be the arglist, bytecode-string, constant vector,\n\
2422 stack size, (optional) doc string, and (optional) interactive spec.\n\
2423 The first four arguments are required; at most six have any\n\
2424 significance.")
2425 (nargs, args)
2426 register int nargs;
2427 Lisp_Object *args;
2429 register Lisp_Object len, val;
2430 register int index;
2431 register struct Lisp_Vector *p;
2433 XSETFASTINT (len, nargs);
2434 if (!NILP (Vpurify_flag))
2435 val = make_pure_vector ((EMACS_INT) nargs);
2436 else
2437 val = Fmake_vector (len, Qnil);
2439 if (STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
2440 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
2441 earlier because they produced a raw 8-bit string for byte-code
2442 and now such a byte-code string is loaded as multibyte while
2443 raw 8-bit characters converted to multibyte form. Thus, now we
2444 must convert them back to the original unibyte form. */
2445 args[1] = Fstring_as_unibyte (args[1]);
2447 p = XVECTOR (val);
2448 for (index = 0; index < nargs; index++)
2450 if (!NILP (Vpurify_flag))
2451 args[index] = Fpurecopy (args[index]);
2452 p->contents[index] = args[index];
2454 XSETCOMPILED (val, p);
2455 return val;
2460 /***********************************************************************
2461 Symbol Allocation
2462 ***********************************************************************/
2464 /* Each symbol_block is just under 1020 bytes long, since malloc
2465 really allocates in units of powers of two and uses 4 bytes for its
2466 own overhead. */
2468 #define SYMBOL_BLOCK_SIZE \
2469 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
2471 struct symbol_block
2473 struct symbol_block *next;
2474 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
2477 /* Current symbol block and index of first unused Lisp_Symbol
2478 structure in it. */
2480 struct symbol_block *symbol_block;
2481 int symbol_block_index;
2483 /* List of free symbols. */
2485 struct Lisp_Symbol *symbol_free_list;
2487 /* Total number of symbol blocks now in use. */
2489 int n_symbol_blocks;
2492 /* Initialize symbol allocation. */
2494 void
2495 init_symbol ()
2497 symbol_block = (struct symbol_block *) lisp_malloc (sizeof *symbol_block,
2498 MEM_TYPE_SYMBOL);
2499 symbol_block->next = 0;
2500 bzero ((char *) symbol_block->symbols, sizeof symbol_block->symbols);
2501 symbol_block_index = 0;
2502 symbol_free_list = 0;
2503 n_symbol_blocks = 1;
2507 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
2508 "Return a newly allocated uninterned symbol whose name is NAME.\n\
2509 Its value and function definition are void, and its property list is nil.")
2510 (name)
2511 Lisp_Object name;
2513 register Lisp_Object val;
2514 register struct Lisp_Symbol *p;
2516 CHECK_STRING (name, 0);
2518 if (symbol_free_list)
2520 XSETSYMBOL (val, symbol_free_list);
2521 symbol_free_list = *(struct Lisp_Symbol **)&symbol_free_list->value;
2523 else
2525 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
2527 struct symbol_block *new;
2528 new = (struct symbol_block *) lisp_malloc (sizeof *new,
2529 MEM_TYPE_SYMBOL);
2530 VALIDATE_LISP_STORAGE (new, sizeof *new);
2531 new->next = symbol_block;
2532 symbol_block = new;
2533 symbol_block_index = 0;
2534 n_symbol_blocks++;
2536 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index++]);
2539 p = XSYMBOL (val);
2540 p->name = XSTRING (name);
2541 p->obarray = Qnil;
2542 p->plist = Qnil;
2543 p->value = Qunbound;
2544 p->function = Qunbound;
2545 p->next = 0;
2546 consing_since_gc += sizeof (struct Lisp_Symbol);
2547 symbols_consed++;
2548 return val;
2553 /***********************************************************************
2554 Marker (Misc) Allocation
2555 ***********************************************************************/
2557 /* Allocation of markers and other objects that share that structure.
2558 Works like allocation of conses. */
2560 #define MARKER_BLOCK_SIZE \
2561 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
2563 struct marker_block
2565 struct marker_block *next;
2566 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
2569 struct marker_block *marker_block;
2570 int marker_block_index;
2572 union Lisp_Misc *marker_free_list;
2574 /* Total number of marker blocks now in use. */
2576 int n_marker_blocks;
2578 void
2579 init_marker ()
2581 marker_block = (struct marker_block *) lisp_malloc (sizeof *marker_block,
2582 MEM_TYPE_MISC);
2583 marker_block->next = 0;
2584 bzero ((char *) marker_block->markers, sizeof marker_block->markers);
2585 marker_block_index = 0;
2586 marker_free_list = 0;
2587 n_marker_blocks = 1;
2590 /* Return a newly allocated Lisp_Misc object, with no substructure. */
2592 Lisp_Object
2593 allocate_misc ()
2595 Lisp_Object val;
2597 if (marker_free_list)
2599 XSETMISC (val, marker_free_list);
2600 marker_free_list = marker_free_list->u_free.chain;
2602 else
2604 if (marker_block_index == MARKER_BLOCK_SIZE)
2606 struct marker_block *new;
2607 new = (struct marker_block *) lisp_malloc (sizeof *new,
2608 MEM_TYPE_MISC);
2609 VALIDATE_LISP_STORAGE (new, sizeof *new);
2610 new->next = marker_block;
2611 marker_block = new;
2612 marker_block_index = 0;
2613 n_marker_blocks++;
2615 XSETMISC (val, &marker_block->markers[marker_block_index++]);
2618 consing_since_gc += sizeof (union Lisp_Misc);
2619 misc_objects_consed++;
2620 return val;
2623 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
2624 "Return a newly allocated marker which does not point at any place.")
2627 register Lisp_Object val;
2628 register struct Lisp_Marker *p;
2630 val = allocate_misc ();
2631 XMISCTYPE (val) = Lisp_Misc_Marker;
2632 p = XMARKER (val);
2633 p->buffer = 0;
2634 p->bytepos = 0;
2635 p->charpos = 0;
2636 p->chain = Qnil;
2637 p->insertion_type = 0;
2638 return val;
2641 /* Put MARKER back on the free list after using it temporarily. */
2643 void
2644 free_marker (marker)
2645 Lisp_Object marker;
2647 unchain_marker (marker);
2649 XMISC (marker)->u_marker.type = Lisp_Misc_Free;
2650 XMISC (marker)->u_free.chain = marker_free_list;
2651 marker_free_list = XMISC (marker);
2653 total_free_markers++;
2657 /* Return a newly created vector or string with specified arguments as
2658 elements. If all the arguments are characters that can fit
2659 in a string of events, make a string; otherwise, make a vector.
2661 Any number of arguments, even zero arguments, are allowed. */
2663 Lisp_Object
2664 make_event_array (nargs, args)
2665 register int nargs;
2666 Lisp_Object *args;
2668 int i;
2670 for (i = 0; i < nargs; i++)
2671 /* The things that fit in a string
2672 are characters that are in 0...127,
2673 after discarding the meta bit and all the bits above it. */
2674 if (!INTEGERP (args[i])
2675 || (XUINT (args[i]) & ~(-CHAR_META)) >= 0200)
2676 return Fvector (nargs, args);
2678 /* Since the loop exited, we know that all the things in it are
2679 characters, so we can make a string. */
2681 Lisp_Object result;
2683 result = Fmake_string (make_number (nargs), make_number (0));
2684 for (i = 0; i < nargs; i++)
2686 XSTRING (result)->data[i] = XINT (args[i]);
2687 /* Move the meta bit to the right place for a string char. */
2688 if (XINT (args[i]) & CHAR_META)
2689 XSTRING (result)->data[i] |= 0x80;
2692 return result;
2698 /************************************************************************
2699 C Stack Marking
2700 ************************************************************************/
2702 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
2704 /* Initialize this part of alloc.c. */
2706 static void
2707 mem_init ()
2709 mem_z.left = mem_z.right = MEM_NIL;
2710 mem_z.parent = NULL;
2711 mem_z.color = MEM_BLACK;
2712 mem_z.start = mem_z.end = NULL;
2713 mem_root = MEM_NIL;
2717 /* Value is a pointer to the mem_node containing START. Value is
2718 MEM_NIL if there is no node in the tree containing START. */
2720 static INLINE struct mem_node *
2721 mem_find (start)
2722 void *start;
2724 struct mem_node *p;
2726 if (start < min_heap_address || start > max_heap_address)
2727 return MEM_NIL;
2729 /* Make the search always successful to speed up the loop below. */
2730 mem_z.start = start;
2731 mem_z.end = (char *) start + 1;
2733 p = mem_root;
2734 while (start < p->start || start >= p->end)
2735 p = start < p->start ? p->left : p->right;
2736 return p;
2740 /* Insert a new node into the tree for a block of memory with start
2741 address START, end address END, and type TYPE. Value is a
2742 pointer to the node that was inserted. */
2744 static struct mem_node *
2745 mem_insert (start, end, type)
2746 void *start, *end;
2747 enum mem_type type;
2749 struct mem_node *c, *parent, *x;
2751 if (start < min_heap_address)
2752 min_heap_address = start;
2753 if (end > max_heap_address)
2754 max_heap_address = end;
2756 /* See where in the tree a node for START belongs. In this
2757 particular application, it shouldn't happen that a node is already
2758 present. For debugging purposes, let's check that. */
2759 c = mem_root;
2760 parent = NULL;
2762 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
2764 while (c != MEM_NIL)
2766 if (start >= c->start && start < c->end)
2767 abort ();
2768 parent = c;
2769 c = start < c->start ? c->left : c->right;
2772 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2774 while (c != MEM_NIL)
2776 parent = c;
2777 c = start < c->start ? c->left : c->right;
2780 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2782 /* Create a new node. */
2783 #ifdef GC_MALLOC_CHECK
2784 x = (struct mem_node *) _malloc_internal (sizeof *x);
2785 if (x == NULL)
2786 abort ();
2787 #else
2788 x = (struct mem_node *) xmalloc (sizeof *x);
2789 #endif
2790 x->start = start;
2791 x->end = end;
2792 x->type = type;
2793 x->parent = parent;
2794 x->left = x->right = MEM_NIL;
2795 x->color = MEM_RED;
2797 /* Insert it as child of PARENT or install it as root. */
2798 if (parent)
2800 if (start < parent->start)
2801 parent->left = x;
2802 else
2803 parent->right = x;
2805 else
2806 mem_root = x;
2808 /* Re-establish red-black tree properties. */
2809 mem_insert_fixup (x);
2811 return x;
2815 /* Re-establish the red-black properties of the tree, and thereby
2816 balance the tree, after node X has been inserted; X is always red. */
2818 static void
2819 mem_insert_fixup (x)
2820 struct mem_node *x;
2822 while (x != mem_root && x->parent->color == MEM_RED)
2824 /* X is red and its parent is red. This is a violation of
2825 red-black tree property #3. */
2827 if (x->parent == x->parent->parent->left)
2829 /* We're on the left side of our grandparent, and Y is our
2830 "uncle". */
2831 struct mem_node *y = x->parent->parent->right;
2833 if (y->color == MEM_RED)
2835 /* Uncle and parent are red but should be black because
2836 X is red. Change the colors accordingly and proceed
2837 with the grandparent. */
2838 x->parent->color = MEM_BLACK;
2839 y->color = MEM_BLACK;
2840 x->parent->parent->color = MEM_RED;
2841 x = x->parent->parent;
2843 else
2845 /* Parent and uncle have different colors; parent is
2846 red, uncle is black. */
2847 if (x == x->parent->right)
2849 x = x->parent;
2850 mem_rotate_left (x);
2853 x->parent->color = MEM_BLACK;
2854 x->parent->parent->color = MEM_RED;
2855 mem_rotate_right (x->parent->parent);
2858 else
2860 /* This is the symmetrical case of above. */
2861 struct mem_node *y = x->parent->parent->left;
2863 if (y->color == MEM_RED)
2865 x->parent->color = MEM_BLACK;
2866 y->color = MEM_BLACK;
2867 x->parent->parent->color = MEM_RED;
2868 x = x->parent->parent;
2870 else
2872 if (x == x->parent->left)
2874 x = x->parent;
2875 mem_rotate_right (x);
2878 x->parent->color = MEM_BLACK;
2879 x->parent->parent->color = MEM_RED;
2880 mem_rotate_left (x->parent->parent);
2885 /* The root may have been changed to red due to the algorithm. Set
2886 it to black so that property #5 is satisfied. */
2887 mem_root->color = MEM_BLACK;
2891 /* (x) (y)
2892 / \ / \
2893 a (y) ===> (x) c
2894 / \ / \
2895 b c a b */
2897 static void
2898 mem_rotate_left (x)
2899 struct mem_node *x;
2901 struct mem_node *y;
2903 /* Turn y's left sub-tree into x's right sub-tree. */
2904 y = x->right;
2905 x->right = y->left;
2906 if (y->left != MEM_NIL)
2907 y->left->parent = x;
2909 /* Y's parent was x's parent. */
2910 if (y != MEM_NIL)
2911 y->parent = x->parent;
2913 /* Get the parent to point to y instead of x. */
2914 if (x->parent)
2916 if (x == x->parent->left)
2917 x->parent->left = y;
2918 else
2919 x->parent->right = y;
2921 else
2922 mem_root = y;
2924 /* Put x on y's left. */
2925 y->left = x;
2926 if (x != MEM_NIL)
2927 x->parent = y;
2931 /* (x) (Y)
2932 / \ / \
2933 (y) c ===> a (x)
2934 / \ / \
2935 a b b c */
2937 static void
2938 mem_rotate_right (x)
2939 struct mem_node *x;
2941 struct mem_node *y = x->left;
2943 x->left = y->right;
2944 if (y->right != MEM_NIL)
2945 y->right->parent = x;
2947 if (y != MEM_NIL)
2948 y->parent = x->parent;
2949 if (x->parent)
2951 if (x == x->parent->right)
2952 x->parent->right = y;
2953 else
2954 x->parent->left = y;
2956 else
2957 mem_root = y;
2959 y->right = x;
2960 if (x != MEM_NIL)
2961 x->parent = y;
2965 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
2967 static void
2968 mem_delete (z)
2969 struct mem_node *z;
2971 struct mem_node *x, *y;
2973 if (!z || z == MEM_NIL)
2974 return;
2976 if (z->left == MEM_NIL || z->right == MEM_NIL)
2977 y = z;
2978 else
2980 y = z->right;
2981 while (y->left != MEM_NIL)
2982 y = y->left;
2985 if (y->left != MEM_NIL)
2986 x = y->left;
2987 else
2988 x = y->right;
2990 x->parent = y->parent;
2991 if (y->parent)
2993 if (y == y->parent->left)
2994 y->parent->left = x;
2995 else
2996 y->parent->right = x;
2998 else
2999 mem_root = x;
3001 if (y != z)
3003 z->start = y->start;
3004 z->end = y->end;
3005 z->type = y->type;
3008 if (y->color == MEM_BLACK)
3009 mem_delete_fixup (x);
3011 #ifdef GC_MALLOC_CHECK
3012 _free_internal (y);
3013 #else
3014 xfree (y);
3015 #endif
3019 /* Re-establish the red-black properties of the tree, after a
3020 deletion. */
3022 static void
3023 mem_delete_fixup (x)
3024 struct mem_node *x;
3026 while (x != mem_root && x->color == MEM_BLACK)
3028 if (x == x->parent->left)
3030 struct mem_node *w = x->parent->right;
3032 if (w->color == MEM_RED)
3034 w->color = MEM_BLACK;
3035 x->parent->color = MEM_RED;
3036 mem_rotate_left (x->parent);
3037 w = x->parent->right;
3040 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
3042 w->color = MEM_RED;
3043 x = x->parent;
3045 else
3047 if (w->right->color == MEM_BLACK)
3049 w->left->color = MEM_BLACK;
3050 w->color = MEM_RED;
3051 mem_rotate_right (w);
3052 w = x->parent->right;
3054 w->color = x->parent->color;
3055 x->parent->color = MEM_BLACK;
3056 w->right->color = MEM_BLACK;
3057 mem_rotate_left (x->parent);
3058 x = mem_root;
3061 else
3063 struct mem_node *w = x->parent->left;
3065 if (w->color == MEM_RED)
3067 w->color = MEM_BLACK;
3068 x->parent->color = MEM_RED;
3069 mem_rotate_right (x->parent);
3070 w = x->parent->left;
3073 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
3075 w->color = MEM_RED;
3076 x = x->parent;
3078 else
3080 if (w->left->color == MEM_BLACK)
3082 w->right->color = MEM_BLACK;
3083 w->color = MEM_RED;
3084 mem_rotate_left (w);
3085 w = x->parent->left;
3088 w->color = x->parent->color;
3089 x->parent->color = MEM_BLACK;
3090 w->left->color = MEM_BLACK;
3091 mem_rotate_right (x->parent);
3092 x = mem_root;
3097 x->color = MEM_BLACK;
3101 /* Value is non-zero if P is a pointer to a live Lisp string on
3102 the heap. M is a pointer to the mem_block for P. */
3104 static INLINE int
3105 live_string_p (m, p)
3106 struct mem_node *m;
3107 void *p;
3109 if (m->type == MEM_TYPE_STRING)
3111 struct string_block *b = (struct string_block *) m->start;
3112 int offset = (char *) p - (char *) &b->strings[0];
3114 /* P must point to the start of a Lisp_String structure, and it
3115 must not be on the free-list. */
3116 return (offset >= 0
3117 && offset % sizeof b->strings[0] == 0
3118 && ((struct Lisp_String *) p)->data != NULL);
3120 else
3121 return 0;
3125 /* Value is non-zero if P is a pointer to a live Lisp cons on
3126 the heap. M is a pointer to the mem_block for P. */
3128 static INLINE int
3129 live_cons_p (m, p)
3130 struct mem_node *m;
3131 void *p;
3133 if (m->type == MEM_TYPE_CONS)
3135 struct cons_block *b = (struct cons_block *) m->start;
3136 int offset = (char *) p - (char *) &b->conses[0];
3138 /* P must point to the start of a Lisp_Cons, not be
3139 one of the unused cells in the current cons block,
3140 and not be on the free-list. */
3141 return (offset >= 0
3142 && offset % sizeof b->conses[0] == 0
3143 && (b != cons_block
3144 || offset / sizeof b->conses[0] < cons_block_index)
3145 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
3147 else
3148 return 0;
3152 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3153 the heap. M is a pointer to the mem_block for P. */
3155 static INLINE int
3156 live_symbol_p (m, p)
3157 struct mem_node *m;
3158 void *p;
3160 if (m->type == MEM_TYPE_SYMBOL)
3162 struct symbol_block *b = (struct symbol_block *) m->start;
3163 int offset = (char *) p - (char *) &b->symbols[0];
3165 /* P must point to the start of a Lisp_Symbol, not be
3166 one of the unused cells in the current symbol block,
3167 and not be on the free-list. */
3168 return (offset >= 0
3169 && offset % sizeof b->symbols[0] == 0
3170 && (b != symbol_block
3171 || offset / sizeof b->symbols[0] < symbol_block_index)
3172 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
3174 else
3175 return 0;
3179 /* Value is non-zero if P is a pointer to a live Lisp float on
3180 the heap. M is a pointer to the mem_block for P. */
3182 static INLINE int
3183 live_float_p (m, p)
3184 struct mem_node *m;
3185 void *p;
3187 if (m->type == MEM_TYPE_FLOAT)
3189 struct float_block *b = (struct float_block *) m->start;
3190 int offset = (char *) p - (char *) &b->floats[0];
3192 /* P must point to the start of a Lisp_Float, not be
3193 one of the unused cells in the current float block,
3194 and not be on the free-list. */
3195 return (offset >= 0
3196 && offset % sizeof b->floats[0] == 0
3197 && (b != float_block
3198 || offset / sizeof b->floats[0] < float_block_index)
3199 && !EQ (((struct Lisp_Float *) p)->type, Vdead));
3201 else
3202 return 0;
3206 /* Value is non-zero if P is a pointer to a live Lisp Misc on
3207 the heap. M is a pointer to the mem_block for P. */
3209 static INLINE int
3210 live_misc_p (m, p)
3211 struct mem_node *m;
3212 void *p;
3214 if (m->type == MEM_TYPE_MISC)
3216 struct marker_block *b = (struct marker_block *) m->start;
3217 int offset = (char *) p - (char *) &b->markers[0];
3219 /* P must point to the start of a Lisp_Misc, not be
3220 one of the unused cells in the current misc block,
3221 and not be on the free-list. */
3222 return (offset >= 0
3223 && offset % sizeof b->markers[0] == 0
3224 && (b != marker_block
3225 || offset / sizeof b->markers[0] < marker_block_index)
3226 && ((union Lisp_Misc *) p)->u_marker.type != Lisp_Misc_Free);
3228 else
3229 return 0;
3233 /* Value is non-zero if P is a pointer to a live vector-like object.
3234 M is a pointer to the mem_block for P. */
3236 static INLINE int
3237 live_vector_p (m, p)
3238 struct mem_node *m;
3239 void *p;
3241 return (p == m->start
3242 && m->type >= MEM_TYPE_VECTOR
3243 && m->type <= MEM_TYPE_WINDOW);
3247 /* Value is non-zero of P is a pointer to a live buffer. M is a
3248 pointer to the mem_block for P. */
3250 static INLINE int
3251 live_buffer_p (m, p)
3252 struct mem_node *m;
3253 void *p;
3255 /* P must point to the start of the block, and the buffer
3256 must not have been killed. */
3257 return (m->type == MEM_TYPE_BUFFER
3258 && p == m->start
3259 && !NILP (((struct buffer *) p)->name));
3262 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
3264 #if GC_MARK_STACK
3266 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3268 /* Array of objects that are kept alive because the C stack contains
3269 a pattern that looks like a reference to them . */
3271 #define MAX_ZOMBIES 10
3272 static Lisp_Object zombies[MAX_ZOMBIES];
3274 /* Number of zombie objects. */
3276 static int nzombies;
3278 /* Number of garbage collections. */
3280 static int ngcs;
3282 /* Average percentage of zombies per collection. */
3284 static double avg_zombies;
3286 /* Max. number of live and zombie objects. */
3288 static int max_live, max_zombies;
3290 /* Average number of live objects per GC. */
3292 static double avg_live;
3294 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
3295 "Show information about live and zombie objects.")
3298 Lisp_Object args[7];
3299 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d");
3300 args[1] = make_number (ngcs);
3301 args[2] = make_float (avg_live);
3302 args[3] = make_float (avg_zombies);
3303 args[4] = make_float (avg_zombies / avg_live / 100);
3304 args[5] = make_number (max_live);
3305 args[6] = make_number (max_zombies);
3306 return Fmessage (7, args);
3309 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3312 /* Mark OBJ if we can prove it's a Lisp_Object. */
3314 static INLINE void
3315 mark_maybe_object (obj)
3316 Lisp_Object obj;
3318 void *po = (void *) XPNTR (obj);
3319 struct mem_node *m = mem_find (po);
3321 if (m != MEM_NIL)
3323 int mark_p = 0;
3325 switch (XGCTYPE (obj))
3327 case Lisp_String:
3328 mark_p = (live_string_p (m, po)
3329 && !STRING_MARKED_P ((struct Lisp_String *) po));
3330 break;
3332 case Lisp_Cons:
3333 mark_p = (live_cons_p (m, po)
3334 && !XMARKBIT (XCONS (obj)->car));
3335 break;
3337 case Lisp_Symbol:
3338 mark_p = (live_symbol_p (m, po)
3339 && !XMARKBIT (XSYMBOL (obj)->plist));
3340 break;
3342 case Lisp_Float:
3343 mark_p = (live_float_p (m, po)
3344 && !XMARKBIT (XFLOAT (obj)->type));
3345 break;
3347 case Lisp_Vectorlike:
3348 /* Note: can't check GC_BUFFERP before we know it's a
3349 buffer because checking that dereferences the pointer
3350 PO which might point anywhere. */
3351 if (live_vector_p (m, po))
3352 mark_p = (!GC_SUBRP (obj)
3353 && !(XVECTOR (obj)->size & ARRAY_MARK_FLAG));
3354 else if (live_buffer_p (m, po))
3355 mark_p = GC_BUFFERP (obj) && !XMARKBIT (XBUFFER (obj)->name);
3356 break;
3358 case Lisp_Misc:
3359 if (live_misc_p (m, po))
3361 switch (XMISCTYPE (obj))
3363 case Lisp_Misc_Marker:
3364 mark_p = !XMARKBIT (XMARKER (obj)->chain);
3365 break;
3367 case Lisp_Misc_Buffer_Local_Value:
3368 case Lisp_Misc_Some_Buffer_Local_Value:
3369 mark_p = !XMARKBIT (XBUFFER_LOCAL_VALUE (obj)->realvalue);
3370 break;
3372 case Lisp_Misc_Overlay:
3373 mark_p = !XMARKBIT (XOVERLAY (obj)->plist);
3374 break;
3377 break;
3379 case Lisp_Int:
3380 case Lisp_Type_Limit:
3381 break;
3384 if (mark_p)
3386 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3387 if (nzombies < MAX_ZOMBIES)
3388 zombies[nzombies] = *p;
3389 ++nzombies;
3390 #endif
3391 mark_object (&obj);
3397 /* If P points to Lisp data, mark that as live if it isn't already
3398 marked. */
3400 static INLINE void
3401 mark_maybe_pointer (p)
3402 void *p;
3404 struct mem_node *m;
3406 /* Quickly rule out some values which can't point to Lisp data. We
3407 assume that Lisp data is aligned on even addresses. */
3408 if ((EMACS_INT) p & 1)
3409 return;
3411 m = mem_find (p);
3412 if (m != MEM_NIL)
3414 Lisp_Object obj = Qnil;
3416 switch (m->type)
3418 case MEM_TYPE_NON_LISP:
3419 /* Nothing to do; not a pointer to Lisp memory. */
3420 break;
3422 case MEM_TYPE_BUFFER:
3423 if (live_buffer_p (m, p)
3424 && !XMARKBIT (((struct buffer *) p)->name))
3425 XSETVECTOR (obj, p);
3426 break;
3428 case MEM_TYPE_CONS:
3429 if (live_cons_p (m, p)
3430 && !XMARKBIT (((struct Lisp_Cons *) p)->car))
3431 XSETCONS (obj, p);
3432 break;
3434 case MEM_TYPE_STRING:
3435 if (live_string_p (m, p)
3436 && !STRING_MARKED_P ((struct Lisp_String *) p))
3437 XSETSTRING (obj, p);
3438 break;
3440 case MEM_TYPE_MISC:
3441 if (live_misc_p (m, p))
3443 Lisp_Object tem;
3444 XSETMISC (tem, p);
3446 switch (XMISCTYPE (tem))
3448 case Lisp_Misc_Marker:
3449 if (!XMARKBIT (XMARKER (tem)->chain))
3450 obj = tem;
3451 break;
3453 case Lisp_Misc_Buffer_Local_Value:
3454 case Lisp_Misc_Some_Buffer_Local_Value:
3455 if (!XMARKBIT (XBUFFER_LOCAL_VALUE (tem)->realvalue))
3456 obj = tem;
3457 break;
3459 case Lisp_Misc_Overlay:
3460 if (!XMARKBIT (XOVERLAY (tem)->plist))
3461 obj = tem;
3462 break;
3465 break;
3467 case MEM_TYPE_SYMBOL:
3468 if (live_symbol_p (m, p)
3469 && !XMARKBIT (((struct Lisp_Symbol *) p)->plist))
3470 XSETSYMBOL (obj, p);
3471 break;
3473 case MEM_TYPE_FLOAT:
3474 if (live_float_p (m, p)
3475 && !XMARKBIT (((struct Lisp_Float *) p)->type))
3476 XSETFLOAT (obj, p);
3477 break;
3479 case MEM_TYPE_VECTOR:
3480 case MEM_TYPE_PROCESS:
3481 case MEM_TYPE_HASH_TABLE:
3482 case MEM_TYPE_FRAME:
3483 case MEM_TYPE_WINDOW:
3484 if (live_vector_p (m, p))
3486 Lisp_Object tem;
3487 XSETVECTOR (tem, p);
3488 if (!GC_SUBRP (tem)
3489 && !(XVECTOR (tem)->size & ARRAY_MARK_FLAG))
3490 obj = tem;
3492 break;
3494 default:
3495 abort ();
3498 if (!GC_NILP (obj))
3499 mark_object (&obj);
3504 /* Mark Lisp objects referenced from the address range START..END. */
3506 static void
3507 mark_memory (start, end)
3508 void *start, *end;
3510 Lisp_Object *p;
3511 void **pp;
3513 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3514 nzombies = 0;
3515 #endif
3517 /* Make START the pointer to the start of the memory region,
3518 if it isn't already. */
3519 if (end < start)
3521 void *tem = start;
3522 start = end;
3523 end = tem;
3526 /* Mark Lisp_Objects. */
3527 for (p = (Lisp_Object *) start; (void *) p < end; ++p)
3528 mark_maybe_object (*p);
3530 /* Mark Lisp data pointed to. This is necessary because, in some
3531 situations, the C compiler optimizes Lisp objects away, so that
3532 only a pointer to them remains. Example:
3534 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
3537 Lisp_Object obj = build_string ("test");
3538 struct Lisp_String *s = XSTRING (obj);
3539 Fgarbage_collect ();
3540 fprintf (stderr, "test `%s'\n", s->data);
3541 return Qnil;
3544 Here, `obj' isn't really used, and the compiler optimizes it
3545 away. The only reference to the life string is through the
3546 pointer `s'. */
3548 for (pp = (void **) start; (void *) pp < end; ++pp)
3549 mark_maybe_pointer (*pp);
3553 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
3555 static int setjmp_tested_p, longjmps_done;
3557 #define SETJMP_WILL_LIKELY_WORK "\
3559 Emacs garbage collector has been changed to use conservative stack\n\
3560 marking. Emacs has determined that the method it uses to do the\n\
3561 marking will likely work on your system, but this isn't sure.\n\
3563 If you are a system-programmer, or can get the help of a local wizard\n\
3564 who is, please take a look at the function mark_stack in alloc.c, and\n\
3565 verify that the methods used are appropriate for your system.\n\
3567 Please mail the result to <gerd@gnu.org>.\n\
3570 #define SETJMP_WILL_NOT_WORK "\
3572 Emacs garbage collector has been changed to use conservative stack\n\
3573 marking. Emacs has determined that the default method it uses to do the\n\
3574 marking will not work on your system. We will need a system-dependent\n\
3575 solution for your system.\n\
3577 Please take a look at the function mark_stack in alloc.c, and\n\
3578 try to find a way to make it work on your system.\n\
3579 Please mail the result to <gerd@gnu.org>.\n\
3583 /* Perform a quick check if it looks like setjmp saves registers in a
3584 jmp_buf. Print a message to stderr saying so. When this test
3585 succeeds, this is _not_ a proof that setjmp is sufficient for
3586 conservative stack marking. Only the sources or a disassembly
3587 can prove that. */
3589 static void
3590 test_setjmp ()
3592 char buf[10];
3593 register int x;
3594 jmp_buf jbuf;
3595 int result = 0;
3597 /* Arrange for X to be put in a register. */
3598 sprintf (buf, "1");
3599 x = strlen (buf);
3600 x = 2 * x - 1;
3602 setjmp (jbuf);
3603 if (longjmps_done == 1)
3605 /* Came here after the longjmp at the end of the function.
3607 If x == 1, the longjmp has restored the register to its
3608 value before the setjmp, and we can hope that setjmp
3609 saves all such registers in the jmp_buf, although that
3610 isn't sure.
3612 For other values of X, either something really strange is
3613 taking place, or the setjmp just didn't save the register. */
3615 if (x == 1)
3616 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
3617 else
3619 fprintf (stderr, SETJMP_WILL_NOT_WORK);
3620 exit (1);
3624 ++longjmps_done;
3625 x = 2;
3626 if (longjmps_done == 1)
3627 longjmp (jbuf, 1);
3630 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
3633 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
3635 /* Abort if anything GCPRO'd doesn't survive the GC. */
3637 static void
3638 check_gcpros ()
3640 struct gcpro *p;
3641 int i;
3643 for (p = gcprolist; p; p = p->next)
3644 for (i = 0; i < p->nvars; ++i)
3645 if (!survives_gc_p (p->var[i]))
3646 abort ();
3649 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3651 static void
3652 dump_zombies ()
3654 int i;
3656 fprintf (stderr, "\nZombies kept alive = %d:\n", nzombies);
3657 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
3659 fprintf (stderr, " %d = ", i);
3660 debug_print (zombies[i]);
3664 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3667 /* Mark live Lisp objects on the C stack.
3669 There are several system-dependent problems to consider when
3670 porting this to new architectures:
3672 Processor Registers
3674 We have to mark Lisp objects in CPU registers that can hold local
3675 variables or are used to pass parameters.
3677 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
3678 something that either saves relevant registers on the stack, or
3679 calls mark_maybe_object passing it each register's contents.
3681 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
3682 implementation assumes that calling setjmp saves registers we need
3683 to see in a jmp_buf which itself lies on the stack. This doesn't
3684 have to be true! It must be verified for each system, possibly
3685 by taking a look at the source code of setjmp.
3687 Stack Layout
3689 Architectures differ in the way their processor stack is organized.
3690 For example, the stack might look like this
3692 +----------------+
3693 | Lisp_Object | size = 4
3694 +----------------+
3695 | something else | size = 2
3696 +----------------+
3697 | Lisp_Object | size = 4
3698 +----------------+
3699 | ... |
3701 In such a case, not every Lisp_Object will be aligned equally. To
3702 find all Lisp_Object on the stack it won't be sufficient to walk
3703 the stack in steps of 4 bytes. Instead, two passes will be
3704 necessary, one starting at the start of the stack, and a second
3705 pass starting at the start of the stack + 2. Likewise, if the
3706 minimal alignment of Lisp_Objects on the stack is 1, four passes
3707 would be necessary, each one starting with one byte more offset
3708 from the stack start.
3710 The current code assumes by default that Lisp_Objects are aligned
3711 equally on the stack. */
3713 static void
3714 mark_stack ()
3716 jmp_buf j;
3717 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
3718 void *end;
3720 /* This trick flushes the register windows so that all the state of
3721 the process is contained in the stack. */
3722 #ifdef sparc
3723 asm ("ta 3");
3724 #endif
3726 /* Save registers that we need to see on the stack. We need to see
3727 registers used to hold register variables and registers used to
3728 pass parameters. */
3729 #ifdef GC_SAVE_REGISTERS_ON_STACK
3730 GC_SAVE_REGISTERS_ON_STACK (end);
3731 #else /* not GC_SAVE_REGISTERS_ON_STACK */
3733 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
3734 setjmp will definitely work, test it
3735 and print a message with the result
3736 of the test. */
3737 if (!setjmp_tested_p)
3739 setjmp_tested_p = 1;
3740 test_setjmp ();
3742 #endif /* GC_SETJMP_WORKS */
3744 setjmp (j);
3745 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
3746 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
3748 /* This assumes that the stack is a contiguous region in memory. If
3749 that's not the case, something has to be done here to iterate
3750 over the stack segments. */
3751 #if GC_LISP_OBJECT_ALIGNMENT == 1
3752 mark_memory (stack_base, end);
3753 mark_memory ((char *) stack_base + 1, end);
3754 mark_memory ((char *) stack_base + 2, end);
3755 mark_memory ((char *) stack_base + 3, end);
3756 #elif GC_LISP_OBJECT_ALIGNMENT == 2
3757 mark_memory (stack_base, end);
3758 mark_memory ((char *) stack_base + 2, end);
3759 #else
3760 mark_memory (stack_base, end);
3761 #endif
3763 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
3764 check_gcpros ();
3765 #endif
3769 #endif /* GC_MARK_STACK != 0 */
3773 /***********************************************************************
3774 Pure Storage Management
3775 ***********************************************************************/
3777 /* Allocate room for SIZE bytes from pure Lisp storage and return a
3778 pointer to it. TYPE is the Lisp type for which the memory is
3779 allocated. TYPE < 0 means it's not used for a Lisp object.
3781 If store_pure_type_info is set and TYPE is >= 0, the type of
3782 the allocated object is recorded in pure_types. */
3784 static POINTER_TYPE *
3785 pure_alloc (size, type)
3786 size_t size;
3787 int type;
3789 size_t nbytes;
3790 POINTER_TYPE *result;
3791 char *beg = PUREBEG;
3793 /* Give Lisp_Floats an extra alignment. */
3794 if (type == Lisp_Float)
3796 size_t alignment;
3797 #if defined __GNUC__ && __GNUC__ >= 2
3798 alignment = __alignof (struct Lisp_Float);
3799 #else
3800 alignment = sizeof (struct Lisp_Float);
3801 #endif
3802 pure_bytes_used = ALIGN (pure_bytes_used, alignment);
3805 nbytes = ALIGN (size, sizeof (EMACS_INT));
3806 if (pure_bytes_used + nbytes > PURESIZE)
3807 error ("Pure Lisp storage exhausted");
3809 result = (POINTER_TYPE *) (beg + pure_bytes_used);
3810 pure_bytes_used += nbytes;
3811 return result;
3815 /* Return a string allocated in pure space. DATA is a buffer holding
3816 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
3817 non-zero means make the result string multibyte.
3819 Must get an error if pure storage is full, since if it cannot hold
3820 a large string it may be able to hold conses that point to that
3821 string; then the string is not protected from gc. */
3823 Lisp_Object
3824 make_pure_string (data, nchars, nbytes, multibyte)
3825 char *data;
3826 int nchars, nbytes;
3827 int multibyte;
3829 Lisp_Object string;
3830 struct Lisp_String *s;
3832 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
3833 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
3834 s->size = nchars;
3835 s->size_byte = multibyte ? nbytes : -1;
3836 bcopy (data, s->data, nbytes);
3837 s->data[nbytes] = '\0';
3838 s->intervals = NULL_INTERVAL;
3839 XSETSTRING (string, s);
3840 return string;
3844 /* Return a cons allocated from pure space. Give it pure copies
3845 of CAR as car and CDR as cdr. */
3847 Lisp_Object
3848 pure_cons (car, cdr)
3849 Lisp_Object car, cdr;
3851 register Lisp_Object new;
3852 struct Lisp_Cons *p;
3854 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
3855 XSETCONS (new, p);
3856 XCAR (new) = Fpurecopy (car);
3857 XCDR (new) = Fpurecopy (cdr);
3858 return new;
3862 /* Value is a float object with value NUM allocated from pure space. */
3864 Lisp_Object
3865 make_pure_float (num)
3866 double num;
3868 register Lisp_Object new;
3869 struct Lisp_Float *p;
3871 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
3872 XSETFLOAT (new, p);
3873 XFLOAT_DATA (new) = num;
3874 return new;
3878 /* Return a vector with room for LEN Lisp_Objects allocated from
3879 pure space. */
3881 Lisp_Object
3882 make_pure_vector (len)
3883 EMACS_INT len;
3885 Lisp_Object new;
3886 struct Lisp_Vector *p;
3887 size_t size = sizeof *p + (len - 1) * sizeof (Lisp_Object);
3889 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
3890 XSETVECTOR (new, p);
3891 XVECTOR (new)->size = len;
3892 return new;
3896 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
3897 "Make a copy of OBJECT in pure storage.\n\
3898 Recursively copies contents of vectors and cons cells.\n\
3899 Does not copy symbols. Copies strings without text properties.")
3900 (obj)
3901 register Lisp_Object obj;
3903 if (NILP (Vpurify_flag))
3904 return obj;
3906 if (PURE_POINTER_P (XPNTR (obj)))
3907 return obj;
3909 if (CONSP (obj))
3910 return pure_cons (XCAR (obj), XCDR (obj));
3911 else if (FLOATP (obj))
3912 return make_pure_float (XFLOAT_DATA (obj));
3913 else if (STRINGP (obj))
3914 return make_pure_string (XSTRING (obj)->data, XSTRING (obj)->size,
3915 STRING_BYTES (XSTRING (obj)),
3916 STRING_MULTIBYTE (obj));
3917 else if (COMPILEDP (obj) || VECTORP (obj))
3919 register struct Lisp_Vector *vec;
3920 register int i, size;
3922 size = XVECTOR (obj)->size;
3923 if (size & PSEUDOVECTOR_FLAG)
3924 size &= PSEUDOVECTOR_SIZE_MASK;
3925 vec = XVECTOR (make_pure_vector ((EMACS_INT) size));
3926 for (i = 0; i < size; i++)
3927 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
3928 if (COMPILEDP (obj))
3929 XSETCOMPILED (obj, vec);
3930 else
3931 XSETVECTOR (obj, vec);
3932 return obj;
3934 else if (MARKERP (obj))
3935 error ("Attempt to copy a marker to pure storage");
3937 return obj;
3942 /***********************************************************************
3943 Protection from GC
3944 ***********************************************************************/
3946 /* Put an entry in staticvec, pointing at the variable with address
3947 VARADDRESS. */
3949 void
3950 staticpro (varaddress)
3951 Lisp_Object *varaddress;
3953 staticvec[staticidx++] = varaddress;
3954 if (staticidx >= NSTATICS)
3955 abort ();
3958 struct catchtag
3960 Lisp_Object tag;
3961 Lisp_Object val;
3962 struct catchtag *next;
3965 struct backtrace
3967 struct backtrace *next;
3968 Lisp_Object *function;
3969 Lisp_Object *args; /* Points to vector of args. */
3970 int nargs; /* Length of vector. */
3971 /* If nargs is UNEVALLED, args points to slot holding list of
3972 unevalled args. */
3973 char evalargs;
3978 /***********************************************************************
3979 Protection from GC
3980 ***********************************************************************/
3982 /* Temporarily prevent garbage collection. */
3985 inhibit_garbage_collection ()
3987 int count = specpdl_ptr - specpdl;
3988 Lisp_Object number;
3989 int nbits = min (VALBITS, BITS_PER_INT);
3991 XSETINT (number, ((EMACS_INT) 1 << (nbits - 1)) - 1);
3993 specbind (Qgc_cons_threshold, number);
3995 return count;
3999 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
4000 "Reclaim storage for Lisp objects no longer needed.\n\
4001 Returns info on amount of space in use:\n\
4002 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)\n\
4003 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS\n\
4004 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)\n\
4005 (USED-STRINGS . FREE-STRINGS))\n\
4006 Garbage collection happens automatically if you cons more than\n\
4007 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.")
4010 register struct gcpro *tail;
4011 register struct specbinding *bind;
4012 struct catchtag *catch;
4013 struct handler *handler;
4014 register struct backtrace *backlist;
4015 char stack_top_variable;
4016 register int i;
4017 int message_p;
4018 Lisp_Object total[8];
4019 int count = BINDING_STACK_SIZE ();
4021 /* In case user calls debug_print during GC,
4022 don't let that cause a recursive GC. */
4023 consing_since_gc = 0;
4025 /* Save what's currently displayed in the echo area. */
4026 message_p = push_message ();
4027 record_unwind_protect (push_message_unwind, Qnil);
4029 /* Save a copy of the contents of the stack, for debugging. */
4030 #if MAX_SAVE_STACK > 0
4031 if (NILP (Vpurify_flag))
4033 i = &stack_top_variable - stack_bottom;
4034 if (i < 0) i = -i;
4035 if (i < MAX_SAVE_STACK)
4037 if (stack_copy == 0)
4038 stack_copy = (char *) xmalloc (stack_copy_size = i);
4039 else if (stack_copy_size < i)
4040 stack_copy = (char *) xrealloc (stack_copy, (stack_copy_size = i));
4041 if (stack_copy)
4043 if ((EMACS_INT) (&stack_top_variable - stack_bottom) > 0)
4044 bcopy (stack_bottom, stack_copy, i);
4045 else
4046 bcopy (&stack_top_variable, stack_copy, i);
4050 #endif /* MAX_SAVE_STACK > 0 */
4052 if (garbage_collection_messages)
4053 message1_nolog ("Garbage collecting...");
4055 BLOCK_INPUT;
4057 shrink_regexp_cache ();
4059 /* Don't keep undo information around forever. */
4061 register struct buffer *nextb = all_buffers;
4063 while (nextb)
4065 /* If a buffer's undo list is Qt, that means that undo is
4066 turned off in that buffer. Calling truncate_undo_list on
4067 Qt tends to return NULL, which effectively turns undo back on.
4068 So don't call truncate_undo_list if undo_list is Qt. */
4069 if (! EQ (nextb->undo_list, Qt))
4070 nextb->undo_list
4071 = truncate_undo_list (nextb->undo_list, undo_limit,
4072 undo_strong_limit);
4073 nextb = nextb->next;
4077 gc_in_progress = 1;
4079 /* clear_marks (); */
4081 /* Mark all the special slots that serve as the roots of accessibility.
4083 Usually the special slots to mark are contained in particular structures.
4084 Then we know no slot is marked twice because the structures don't overlap.
4085 In some cases, the structures point to the slots to be marked.
4086 For these, we use MARKBIT to avoid double marking of the slot. */
4088 for (i = 0; i < staticidx; i++)
4089 mark_object (staticvec[i]);
4091 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
4092 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
4093 mark_stack ();
4094 #else
4095 for (tail = gcprolist; tail; tail = tail->next)
4096 for (i = 0; i < tail->nvars; i++)
4097 if (!XMARKBIT (tail->var[i]))
4099 /* Explicit casting prevents compiler warning about
4100 discarding the `volatile' qualifier. */
4101 mark_object ((Lisp_Object *)&tail->var[i]);
4102 XMARK (tail->var[i]);
4104 #endif
4106 mark_byte_stack ();
4107 for (bind = specpdl; bind != specpdl_ptr; bind++)
4109 mark_object (&bind->symbol);
4110 mark_object (&bind->old_value);
4112 for (catch = catchlist; catch; catch = catch->next)
4114 mark_object (&catch->tag);
4115 mark_object (&catch->val);
4117 for (handler = handlerlist; handler; handler = handler->next)
4119 mark_object (&handler->handler);
4120 mark_object (&handler->var);
4122 for (backlist = backtrace_list; backlist; backlist = backlist->next)
4124 if (!XMARKBIT (*backlist->function))
4126 mark_object (backlist->function);
4127 XMARK (*backlist->function);
4129 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
4130 i = 0;
4131 else
4132 i = backlist->nargs - 1;
4133 for (; i >= 0; i--)
4134 if (!XMARKBIT (backlist->args[i]))
4136 mark_object (&backlist->args[i]);
4137 XMARK (backlist->args[i]);
4140 mark_kboards ();
4142 /* Look thru every buffer's undo list
4143 for elements that update markers that were not marked,
4144 and delete them. */
4146 register struct buffer *nextb = all_buffers;
4148 while (nextb)
4150 /* If a buffer's undo list is Qt, that means that undo is
4151 turned off in that buffer. Calling truncate_undo_list on
4152 Qt tends to return NULL, which effectively turns undo back on.
4153 So don't call truncate_undo_list if undo_list is Qt. */
4154 if (! EQ (nextb->undo_list, Qt))
4156 Lisp_Object tail, prev;
4157 tail = nextb->undo_list;
4158 prev = Qnil;
4159 while (CONSP (tail))
4161 if (GC_CONSP (XCAR (tail))
4162 && GC_MARKERP (XCAR (XCAR (tail)))
4163 && ! XMARKBIT (XMARKER (XCAR (XCAR (tail)))->chain))
4165 if (NILP (prev))
4166 nextb->undo_list = tail = XCDR (tail);
4167 else
4168 tail = XCDR (prev) = XCDR (tail);
4170 else
4172 prev = tail;
4173 tail = XCDR (tail);
4178 nextb = nextb->next;
4182 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4183 mark_stack ();
4184 #endif
4186 gc_sweep ();
4188 /* Clear the mark bits that we set in certain root slots. */
4190 #if (GC_MARK_STACK == GC_USE_GCPROS_AS_BEFORE \
4191 || GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES)
4192 for (tail = gcprolist; tail; tail = tail->next)
4193 for (i = 0; i < tail->nvars; i++)
4194 XUNMARK (tail->var[i]);
4195 #endif
4197 unmark_byte_stack ();
4198 for (backlist = backtrace_list; backlist; backlist = backlist->next)
4200 XUNMARK (*backlist->function);
4201 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
4202 i = 0;
4203 else
4204 i = backlist->nargs - 1;
4205 for (; i >= 0; i--)
4206 XUNMARK (backlist->args[i]);
4208 XUNMARK (buffer_defaults.name);
4209 XUNMARK (buffer_local_symbols.name);
4211 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
4212 dump_zombies ();
4213 #endif
4215 UNBLOCK_INPUT;
4217 /* clear_marks (); */
4218 gc_in_progress = 0;
4220 consing_since_gc = 0;
4221 if (gc_cons_threshold < 10000)
4222 gc_cons_threshold = 10000;
4224 if (garbage_collection_messages)
4226 if (message_p || minibuf_level > 0)
4227 restore_message ();
4228 else
4229 message1_nolog ("Garbage collecting...done");
4232 unbind_to (count, Qnil);
4234 total[0] = Fcons (make_number (total_conses),
4235 make_number (total_free_conses));
4236 total[1] = Fcons (make_number (total_symbols),
4237 make_number (total_free_symbols));
4238 total[2] = Fcons (make_number (total_markers),
4239 make_number (total_free_markers));
4240 total[3] = make_number (total_string_size);
4241 total[4] = make_number (total_vector_size);
4242 total[5] = Fcons (make_number (total_floats),
4243 make_number (total_free_floats));
4244 total[6] = Fcons (make_number (total_intervals),
4245 make_number (total_free_intervals));
4246 total[7] = Fcons (make_number (total_strings),
4247 make_number (total_free_strings));
4249 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4251 /* Compute average percentage of zombies. */
4252 double nlive = 0;
4254 for (i = 0; i < 7; ++i)
4255 nlive += XFASTINT (XCAR (total[i]));
4257 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
4258 max_live = max (nlive, max_live);
4259 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
4260 max_zombies = max (nzombies, max_zombies);
4261 ++ngcs;
4263 #endif
4265 return Flist (sizeof total / sizeof *total, total);
4269 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
4270 only interesting objects referenced from glyphs are strings. */
4272 static void
4273 mark_glyph_matrix (matrix)
4274 struct glyph_matrix *matrix;
4276 struct glyph_row *row = matrix->rows;
4277 struct glyph_row *end = row + matrix->nrows;
4279 for (; row < end; ++row)
4280 if (row->enabled_p)
4282 int area;
4283 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
4285 struct glyph *glyph = row->glyphs[area];
4286 struct glyph *end_glyph = glyph + row->used[area];
4288 for (; glyph < end_glyph; ++glyph)
4289 if (GC_STRINGP (glyph->object)
4290 && !STRING_MARKED_P (XSTRING (glyph->object)))
4291 mark_object (&glyph->object);
4297 /* Mark Lisp faces in the face cache C. */
4299 static void
4300 mark_face_cache (c)
4301 struct face_cache *c;
4303 if (c)
4305 int i, j;
4306 for (i = 0; i < c->used; ++i)
4308 struct face *face = FACE_FROM_ID (c->f, i);
4310 if (face)
4312 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
4313 mark_object (&face->lface[j]);
4320 #ifdef HAVE_WINDOW_SYSTEM
4322 /* Mark Lisp objects in image IMG. */
4324 static void
4325 mark_image (img)
4326 struct image *img;
4328 mark_object (&img->spec);
4330 if (!NILP (img->data.lisp_val))
4331 mark_object (&img->data.lisp_val);
4335 /* Mark Lisp objects in image cache of frame F. It's done this way so
4336 that we don't have to include xterm.h here. */
4338 static void
4339 mark_image_cache (f)
4340 struct frame *f;
4342 forall_images_in_image_cache (f, mark_image);
4345 #endif /* HAVE_X_WINDOWS */
4349 /* Mark reference to a Lisp_Object.
4350 If the object referred to has not been seen yet, recursively mark
4351 all the references contained in it. */
4353 #define LAST_MARKED_SIZE 500
4354 Lisp_Object *last_marked[LAST_MARKED_SIZE];
4355 int last_marked_index;
4357 void
4358 mark_object (argptr)
4359 Lisp_Object *argptr;
4361 Lisp_Object *objptr = argptr;
4362 register Lisp_Object obj;
4363 #ifdef GC_CHECK_MARKED_OBJECTS
4364 void *po;
4365 struct mem_node *m;
4366 #endif
4368 loop:
4369 obj = *objptr;
4370 loop2:
4371 XUNMARK (obj);
4373 if (PURE_POINTER_P (XPNTR (obj)))
4374 return;
4376 last_marked[last_marked_index++] = objptr;
4377 if (last_marked_index == LAST_MARKED_SIZE)
4378 last_marked_index = 0;
4380 /* Perform some sanity checks on the objects marked here. Abort if
4381 we encounter an object we know is bogus. This increases GC time
4382 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
4383 #ifdef GC_CHECK_MARKED_OBJECTS
4385 po = (void *) XPNTR (obj);
4387 /* Check that the object pointed to by PO is known to be a Lisp
4388 structure allocated from the heap. */
4389 #define CHECK_ALLOCATED() \
4390 do { \
4391 m = mem_find (po); \
4392 if (m == MEM_NIL) \
4393 abort (); \
4394 } while (0)
4396 /* Check that the object pointed to by PO is live, using predicate
4397 function LIVEP. */
4398 #define CHECK_LIVE(LIVEP) \
4399 do { \
4400 if (!LIVEP (m, po)) \
4401 abort (); \
4402 } while (0)
4404 /* Check both of the above conditions. */
4405 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
4406 do { \
4407 CHECK_ALLOCATED (); \
4408 CHECK_LIVE (LIVEP); \
4409 } while (0) \
4411 #else /* not GC_CHECK_MARKED_OBJECTS */
4413 #define CHECK_ALLOCATED() (void) 0
4414 #define CHECK_LIVE(LIVEP) (void) 0
4415 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
4417 #endif /* not GC_CHECK_MARKED_OBJECTS */
4419 switch (SWITCH_ENUM_CAST (XGCTYPE (obj)))
4421 case Lisp_String:
4423 register struct Lisp_String *ptr = XSTRING (obj);
4424 CHECK_ALLOCATED_AND_LIVE (live_string_p);
4425 MARK_INTERVAL_TREE (ptr->intervals);
4426 MARK_STRING (ptr);
4427 #ifdef GC_CHECK_STRING_BYTES
4428 /* Check that the string size recorded in the string is the
4429 same as the one recorded in the sdata structure. */
4430 CHECK_STRING_BYTES (ptr);
4431 #endif /* GC_CHECK_STRING_BYTES */
4433 break;
4435 case Lisp_Vectorlike:
4436 #ifdef GC_CHECK_MARKED_OBJECTS
4437 m = mem_find (po);
4438 if (m == MEM_NIL && !GC_SUBRP (obj)
4439 && po != &buffer_defaults
4440 && po != &buffer_local_symbols)
4441 abort ();
4442 #endif /* GC_CHECK_MARKED_OBJECTS */
4444 if (GC_BUFFERP (obj))
4446 if (!XMARKBIT (XBUFFER (obj)->name))
4448 #ifdef GC_CHECK_MARKED_OBJECTS
4449 if (po != &buffer_defaults && po != &buffer_local_symbols)
4451 struct buffer *b;
4452 for (b = all_buffers; b && b != po; b = b->next)
4454 if (b == NULL)
4455 abort ();
4457 #endif /* GC_CHECK_MARKED_OBJECTS */
4458 mark_buffer (obj);
4461 else if (GC_SUBRP (obj))
4462 break;
4463 else if (GC_COMPILEDP (obj))
4464 /* We could treat this just like a vector, but it is better to
4465 save the COMPILED_CONSTANTS element for last and avoid
4466 recursion there. */
4468 register struct Lisp_Vector *ptr = XVECTOR (obj);
4469 register EMACS_INT size = ptr->size;
4470 register int i;
4472 if (size & ARRAY_MARK_FLAG)
4473 break; /* Already marked */
4475 CHECK_LIVE (live_vector_p);
4476 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4477 size &= PSEUDOVECTOR_SIZE_MASK;
4478 for (i = 0; i < size; i++) /* and then mark its elements */
4480 if (i != COMPILED_CONSTANTS)
4481 mark_object (&ptr->contents[i]);
4483 /* This cast should be unnecessary, but some Mips compiler complains
4484 (MIPS-ABI + SysVR4, DC/OSx, etc). */
4485 objptr = (Lisp_Object *) &ptr->contents[COMPILED_CONSTANTS];
4486 goto loop;
4488 else if (GC_FRAMEP (obj))
4490 register struct frame *ptr = XFRAME (obj);
4491 register EMACS_INT size = ptr->size;
4493 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
4494 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4496 CHECK_LIVE (live_vector_p);
4497 mark_object (&ptr->name);
4498 mark_object (&ptr->icon_name);
4499 mark_object (&ptr->title);
4500 mark_object (&ptr->focus_frame);
4501 mark_object (&ptr->selected_window);
4502 mark_object (&ptr->minibuffer_window);
4503 mark_object (&ptr->param_alist);
4504 mark_object (&ptr->scroll_bars);
4505 mark_object (&ptr->condemned_scroll_bars);
4506 mark_object (&ptr->menu_bar_items);
4507 mark_object (&ptr->face_alist);
4508 mark_object (&ptr->menu_bar_vector);
4509 mark_object (&ptr->buffer_predicate);
4510 mark_object (&ptr->buffer_list);
4511 mark_object (&ptr->menu_bar_window);
4512 mark_object (&ptr->tool_bar_window);
4513 mark_face_cache (ptr->face_cache);
4514 #ifdef HAVE_WINDOW_SYSTEM
4515 mark_image_cache (ptr);
4516 mark_object (&ptr->tool_bar_items);
4517 mark_object (&ptr->desired_tool_bar_string);
4518 mark_object (&ptr->current_tool_bar_string);
4519 #endif /* HAVE_WINDOW_SYSTEM */
4521 else if (GC_BOOL_VECTOR_P (obj))
4523 register struct Lisp_Vector *ptr = XVECTOR (obj);
4525 if (ptr->size & ARRAY_MARK_FLAG)
4526 break; /* Already marked */
4527 CHECK_LIVE (live_vector_p);
4528 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4530 else if (GC_WINDOWP (obj))
4532 register struct Lisp_Vector *ptr = XVECTOR (obj);
4533 struct window *w = XWINDOW (obj);
4534 register EMACS_INT size = ptr->size;
4535 register int i;
4537 /* Stop if already marked. */
4538 if (size & ARRAY_MARK_FLAG)
4539 break;
4541 /* Mark it. */
4542 CHECK_LIVE (live_vector_p);
4543 ptr->size |= ARRAY_MARK_FLAG;
4545 /* There is no Lisp data above The member CURRENT_MATRIX in
4546 struct WINDOW. Stop marking when that slot is reached. */
4547 for (i = 0;
4548 (char *) &ptr->contents[i] < (char *) &w->current_matrix;
4549 i++)
4550 mark_object (&ptr->contents[i]);
4552 /* Mark glyphs for leaf windows. Marking window matrices is
4553 sufficient because frame matrices use the same glyph
4554 memory. */
4555 if (NILP (w->hchild)
4556 && NILP (w->vchild)
4557 && w->current_matrix)
4559 mark_glyph_matrix (w->current_matrix);
4560 mark_glyph_matrix (w->desired_matrix);
4563 else if (GC_HASH_TABLE_P (obj))
4565 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
4566 EMACS_INT size = h->size;
4568 /* Stop if already marked. */
4569 if (size & ARRAY_MARK_FLAG)
4570 break;
4572 /* Mark it. */
4573 CHECK_LIVE (live_vector_p);
4574 h->size |= ARRAY_MARK_FLAG;
4576 /* Mark contents. */
4577 mark_object (&h->test);
4578 mark_object (&h->weak);
4579 mark_object (&h->rehash_size);
4580 mark_object (&h->rehash_threshold);
4581 mark_object (&h->hash);
4582 mark_object (&h->next);
4583 mark_object (&h->index);
4584 mark_object (&h->user_hash_function);
4585 mark_object (&h->user_cmp_function);
4587 /* If hash table is not weak, mark all keys and values.
4588 For weak tables, mark only the vector. */
4589 if (GC_NILP (h->weak))
4590 mark_object (&h->key_and_value);
4591 else
4592 XVECTOR (h->key_and_value)->size |= ARRAY_MARK_FLAG;
4595 else
4597 register struct Lisp_Vector *ptr = XVECTOR (obj);
4598 register EMACS_INT size = ptr->size;
4599 register int i;
4601 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
4602 CHECK_LIVE (live_vector_p);
4603 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4604 if (size & PSEUDOVECTOR_FLAG)
4605 size &= PSEUDOVECTOR_SIZE_MASK;
4607 for (i = 0; i < size; i++) /* and then mark its elements */
4608 mark_object (&ptr->contents[i]);
4610 break;
4612 case Lisp_Symbol:
4614 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
4615 struct Lisp_Symbol *ptrx;
4617 if (XMARKBIT (ptr->plist)) break;
4618 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
4619 XMARK (ptr->plist);
4620 mark_object ((Lisp_Object *) &ptr->value);
4621 mark_object (&ptr->function);
4622 mark_object (&ptr->plist);
4624 if (!PURE_POINTER_P (ptr->name))
4625 MARK_STRING (ptr->name);
4626 MARK_INTERVAL_TREE (ptr->name->intervals);
4628 /* Note that we do not mark the obarray of the symbol.
4629 It is safe not to do so because nothing accesses that
4630 slot except to check whether it is nil. */
4631 ptr = ptr->next;
4632 if (ptr)
4634 /* For the benefit of the last_marked log. */
4635 objptr = (Lisp_Object *)&XSYMBOL (obj)->next;
4636 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
4637 XSETSYMBOL (obj, ptrx);
4638 /* We can't goto loop here because *objptr doesn't contain an
4639 actual Lisp_Object with valid datatype field. */
4640 goto loop2;
4643 break;
4645 case Lisp_Misc:
4646 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
4647 switch (XMISCTYPE (obj))
4649 case Lisp_Misc_Marker:
4650 XMARK (XMARKER (obj)->chain);
4651 /* DO NOT mark thru the marker's chain.
4652 The buffer's markers chain does not preserve markers from gc;
4653 instead, markers are removed from the chain when freed by gc. */
4654 break;
4656 case Lisp_Misc_Buffer_Local_Value:
4657 case Lisp_Misc_Some_Buffer_Local_Value:
4659 register struct Lisp_Buffer_Local_Value *ptr
4660 = XBUFFER_LOCAL_VALUE (obj);
4661 if (XMARKBIT (ptr->realvalue)) break;
4662 XMARK (ptr->realvalue);
4663 /* If the cdr is nil, avoid recursion for the car. */
4664 if (EQ (ptr->cdr, Qnil))
4666 objptr = &ptr->realvalue;
4667 goto loop;
4669 mark_object (&ptr->realvalue);
4670 mark_object (&ptr->buffer);
4671 mark_object (&ptr->frame);
4672 objptr = &ptr->cdr;
4673 goto loop;
4676 case Lisp_Misc_Intfwd:
4677 case Lisp_Misc_Boolfwd:
4678 case Lisp_Misc_Objfwd:
4679 case Lisp_Misc_Buffer_Objfwd:
4680 case Lisp_Misc_Kboard_Objfwd:
4681 /* Don't bother with Lisp_Buffer_Objfwd,
4682 since all markable slots in current buffer marked anyway. */
4683 /* Don't need to do Lisp_Objfwd, since the places they point
4684 are protected with staticpro. */
4685 break;
4687 case Lisp_Misc_Overlay:
4689 struct Lisp_Overlay *ptr = XOVERLAY (obj);
4690 if (!XMARKBIT (ptr->plist))
4692 XMARK (ptr->plist);
4693 mark_object (&ptr->start);
4694 mark_object (&ptr->end);
4695 objptr = &ptr->plist;
4696 goto loop;
4699 break;
4701 default:
4702 abort ();
4704 break;
4706 case Lisp_Cons:
4708 register struct Lisp_Cons *ptr = XCONS (obj);
4709 if (XMARKBIT (ptr->car)) break;
4710 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
4711 XMARK (ptr->car);
4712 /* If the cdr is nil, avoid recursion for the car. */
4713 if (EQ (ptr->cdr, Qnil))
4715 objptr = &ptr->car;
4716 goto loop;
4718 mark_object (&ptr->car);
4719 objptr = &ptr->cdr;
4720 goto loop;
4723 case Lisp_Float:
4724 CHECK_ALLOCATED_AND_LIVE (live_float_p);
4725 XMARK (XFLOAT (obj)->type);
4726 break;
4728 case Lisp_Int:
4729 break;
4731 default:
4732 abort ();
4735 #undef CHECK_LIVE
4736 #undef CHECK_ALLOCATED
4737 #undef CHECK_ALLOCATED_AND_LIVE
4740 /* Mark the pointers in a buffer structure. */
4742 static void
4743 mark_buffer (buf)
4744 Lisp_Object buf;
4746 register struct buffer *buffer = XBUFFER (buf);
4747 register Lisp_Object *ptr;
4748 Lisp_Object base_buffer;
4750 /* This is the buffer's markbit */
4751 mark_object (&buffer->name);
4752 XMARK (buffer->name);
4754 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
4756 if (CONSP (buffer->undo_list))
4758 Lisp_Object tail;
4759 tail = buffer->undo_list;
4761 while (CONSP (tail))
4763 register struct Lisp_Cons *ptr = XCONS (tail);
4765 if (XMARKBIT (ptr->car))
4766 break;
4767 XMARK (ptr->car);
4768 if (GC_CONSP (ptr->car)
4769 && ! XMARKBIT (XCAR (ptr->car))
4770 && GC_MARKERP (XCAR (ptr->car)))
4772 XMARK (XCAR (ptr->car));
4773 mark_object (&XCDR (ptr->car));
4775 else
4776 mark_object (&ptr->car);
4778 if (CONSP (ptr->cdr))
4779 tail = ptr->cdr;
4780 else
4781 break;
4784 mark_object (&XCDR (tail));
4786 else
4787 mark_object (&buffer->undo_list);
4789 for (ptr = &buffer->name + 1;
4790 (char *)ptr < (char *)buffer + sizeof (struct buffer);
4791 ptr++)
4792 mark_object (ptr);
4794 /* If this is an indirect buffer, mark its base buffer. */
4795 if (buffer->base_buffer && !XMARKBIT (buffer->base_buffer->name))
4797 XSETBUFFER (base_buffer, buffer->base_buffer);
4798 mark_buffer (base_buffer);
4803 /* Mark the pointers in the kboard objects. */
4805 static void
4806 mark_kboards ()
4808 KBOARD *kb;
4809 Lisp_Object *p;
4810 for (kb = all_kboards; kb; kb = kb->next_kboard)
4812 if (kb->kbd_macro_buffer)
4813 for (p = kb->kbd_macro_buffer; p < kb->kbd_macro_ptr; p++)
4814 mark_object (p);
4815 mark_object (&kb->Voverriding_terminal_local_map);
4816 mark_object (&kb->Vlast_command);
4817 mark_object (&kb->Vreal_last_command);
4818 mark_object (&kb->Vprefix_arg);
4819 mark_object (&kb->Vlast_prefix_arg);
4820 mark_object (&kb->kbd_queue);
4821 mark_object (&kb->defining_kbd_macro);
4822 mark_object (&kb->Vlast_kbd_macro);
4823 mark_object (&kb->Vsystem_key_alist);
4824 mark_object (&kb->system_key_syms);
4825 mark_object (&kb->Vdefault_minibuffer_frame);
4830 /* Value is non-zero if OBJ will survive the current GC because it's
4831 either marked or does not need to be marked to survive. */
4834 survives_gc_p (obj)
4835 Lisp_Object obj;
4837 int survives_p;
4839 switch (XGCTYPE (obj))
4841 case Lisp_Int:
4842 survives_p = 1;
4843 break;
4845 case Lisp_Symbol:
4846 survives_p = XMARKBIT (XSYMBOL (obj)->plist);
4847 break;
4849 case Lisp_Misc:
4850 switch (XMISCTYPE (obj))
4852 case Lisp_Misc_Marker:
4853 survives_p = XMARKBIT (obj);
4854 break;
4856 case Lisp_Misc_Buffer_Local_Value:
4857 case Lisp_Misc_Some_Buffer_Local_Value:
4858 survives_p = XMARKBIT (XBUFFER_LOCAL_VALUE (obj)->realvalue);
4859 break;
4861 case Lisp_Misc_Intfwd:
4862 case Lisp_Misc_Boolfwd:
4863 case Lisp_Misc_Objfwd:
4864 case Lisp_Misc_Buffer_Objfwd:
4865 case Lisp_Misc_Kboard_Objfwd:
4866 survives_p = 1;
4867 break;
4869 case Lisp_Misc_Overlay:
4870 survives_p = XMARKBIT (XOVERLAY (obj)->plist);
4871 break;
4873 default:
4874 abort ();
4876 break;
4878 case Lisp_String:
4880 struct Lisp_String *s = XSTRING (obj);
4881 survives_p = STRING_MARKED_P (s);
4883 break;
4885 case Lisp_Vectorlike:
4886 if (GC_BUFFERP (obj))
4887 survives_p = XMARKBIT (XBUFFER (obj)->name);
4888 else if (GC_SUBRP (obj))
4889 survives_p = 1;
4890 else
4891 survives_p = XVECTOR (obj)->size & ARRAY_MARK_FLAG;
4892 break;
4894 case Lisp_Cons:
4895 survives_p = XMARKBIT (XCAR (obj));
4896 break;
4898 case Lisp_Float:
4899 survives_p = XMARKBIT (XFLOAT (obj)->type);
4900 break;
4902 default:
4903 abort ();
4906 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
4911 /* Sweep: find all structures not marked, and free them. */
4913 static void
4914 gc_sweep ()
4916 /* Remove or mark entries in weak hash tables.
4917 This must be done before any object is unmarked. */
4918 sweep_weak_hash_tables ();
4920 sweep_strings ();
4921 #ifdef GC_CHECK_STRING_BYTES
4922 if (!noninteractive)
4923 check_string_bytes (1);
4924 #endif
4926 /* Put all unmarked conses on free list */
4928 register struct cons_block *cblk;
4929 struct cons_block **cprev = &cons_block;
4930 register int lim = cons_block_index;
4931 register int num_free = 0, num_used = 0;
4933 cons_free_list = 0;
4935 for (cblk = cons_block; cblk; cblk = *cprev)
4937 register int i;
4938 int this_free = 0;
4939 for (i = 0; i < lim; i++)
4940 if (!XMARKBIT (cblk->conses[i].car))
4942 this_free++;
4943 *(struct Lisp_Cons **)&cblk->conses[i].cdr = cons_free_list;
4944 cons_free_list = &cblk->conses[i];
4945 #if GC_MARK_STACK
4946 cons_free_list->car = Vdead;
4947 #endif
4949 else
4951 num_used++;
4952 XUNMARK (cblk->conses[i].car);
4954 lim = CONS_BLOCK_SIZE;
4955 /* If this block contains only free conses and we have already
4956 seen more than two blocks worth of free conses then deallocate
4957 this block. */
4958 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
4960 *cprev = cblk->next;
4961 /* Unhook from the free list. */
4962 cons_free_list = *(struct Lisp_Cons **) &cblk->conses[0].cdr;
4963 lisp_free (cblk);
4964 n_cons_blocks--;
4966 else
4968 num_free += this_free;
4969 cprev = &cblk->next;
4972 total_conses = num_used;
4973 total_free_conses = num_free;
4976 /* Put all unmarked floats on free list */
4978 register struct float_block *fblk;
4979 struct float_block **fprev = &float_block;
4980 register int lim = float_block_index;
4981 register int num_free = 0, num_used = 0;
4983 float_free_list = 0;
4985 for (fblk = float_block; fblk; fblk = *fprev)
4987 register int i;
4988 int this_free = 0;
4989 for (i = 0; i < lim; i++)
4990 if (!XMARKBIT (fblk->floats[i].type))
4992 this_free++;
4993 *(struct Lisp_Float **)&fblk->floats[i].data = float_free_list;
4994 float_free_list = &fblk->floats[i];
4995 #if GC_MARK_STACK
4996 float_free_list->type = Vdead;
4997 #endif
4999 else
5001 num_used++;
5002 XUNMARK (fblk->floats[i].type);
5004 lim = FLOAT_BLOCK_SIZE;
5005 /* If this block contains only free floats and we have already
5006 seen more than two blocks worth of free floats then deallocate
5007 this block. */
5008 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
5010 *fprev = fblk->next;
5011 /* Unhook from the free list. */
5012 float_free_list = *(struct Lisp_Float **) &fblk->floats[0].data;
5013 lisp_free (fblk);
5014 n_float_blocks--;
5016 else
5018 num_free += this_free;
5019 fprev = &fblk->next;
5022 total_floats = num_used;
5023 total_free_floats = num_free;
5026 /* Put all unmarked intervals on free list */
5028 register struct interval_block *iblk;
5029 struct interval_block **iprev = &interval_block;
5030 register int lim = interval_block_index;
5031 register int num_free = 0, num_used = 0;
5033 interval_free_list = 0;
5035 for (iblk = interval_block; iblk; iblk = *iprev)
5037 register int i;
5038 int this_free = 0;
5040 for (i = 0; i < lim; i++)
5042 if (! XMARKBIT (iblk->intervals[i].plist))
5044 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
5045 interval_free_list = &iblk->intervals[i];
5046 this_free++;
5048 else
5050 num_used++;
5051 XUNMARK (iblk->intervals[i].plist);
5054 lim = INTERVAL_BLOCK_SIZE;
5055 /* If this block contains only free intervals and we have already
5056 seen more than two blocks worth of free intervals then
5057 deallocate this block. */
5058 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
5060 *iprev = iblk->next;
5061 /* Unhook from the free list. */
5062 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
5063 lisp_free (iblk);
5064 n_interval_blocks--;
5066 else
5068 num_free += this_free;
5069 iprev = &iblk->next;
5072 total_intervals = num_used;
5073 total_free_intervals = num_free;
5076 /* Put all unmarked symbols on free list */
5078 register struct symbol_block *sblk;
5079 struct symbol_block **sprev = &symbol_block;
5080 register int lim = symbol_block_index;
5081 register int num_free = 0, num_used = 0;
5083 symbol_free_list = NULL;
5085 for (sblk = symbol_block; sblk; sblk = *sprev)
5087 int this_free = 0;
5088 struct Lisp_Symbol *sym = sblk->symbols;
5089 struct Lisp_Symbol *end = sym + lim;
5091 for (; sym < end; ++sym)
5093 /* Check if the symbol was created during loadup. In such a case
5094 it might be pointed to by pure bytecode which we don't trace,
5095 so we conservatively assume that it is live. */
5096 int pure_p = PURE_POINTER_P (sym->name);
5098 if (!XMARKBIT (sym->plist) && !pure_p)
5100 *(struct Lisp_Symbol **) &sym->value = symbol_free_list;
5101 symbol_free_list = sym;
5102 #if GC_MARK_STACK
5103 symbol_free_list->function = Vdead;
5104 #endif
5105 ++this_free;
5107 else
5109 ++num_used;
5110 if (!pure_p)
5111 UNMARK_STRING (sym->name);
5112 XUNMARK (sym->plist);
5116 lim = SYMBOL_BLOCK_SIZE;
5117 /* If this block contains only free symbols and we have already
5118 seen more than two blocks worth of free symbols then deallocate
5119 this block. */
5120 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
5122 *sprev = sblk->next;
5123 /* Unhook from the free list. */
5124 symbol_free_list = *(struct Lisp_Symbol **)&sblk->symbols[0].value;
5125 lisp_free (sblk);
5126 n_symbol_blocks--;
5128 else
5130 num_free += this_free;
5131 sprev = &sblk->next;
5134 total_symbols = num_used;
5135 total_free_symbols = num_free;
5138 /* Put all unmarked misc's on free list.
5139 For a marker, first unchain it from the buffer it points into. */
5141 register struct marker_block *mblk;
5142 struct marker_block **mprev = &marker_block;
5143 register int lim = marker_block_index;
5144 register int num_free = 0, num_used = 0;
5146 marker_free_list = 0;
5148 for (mblk = marker_block; mblk; mblk = *mprev)
5150 register int i;
5151 int this_free = 0;
5152 EMACS_INT already_free = -1;
5154 for (i = 0; i < lim; i++)
5156 Lisp_Object *markword;
5157 switch (mblk->markers[i].u_marker.type)
5159 case Lisp_Misc_Marker:
5160 markword = &mblk->markers[i].u_marker.chain;
5161 break;
5162 case Lisp_Misc_Buffer_Local_Value:
5163 case Lisp_Misc_Some_Buffer_Local_Value:
5164 markword = &mblk->markers[i].u_buffer_local_value.realvalue;
5165 break;
5166 case Lisp_Misc_Overlay:
5167 markword = &mblk->markers[i].u_overlay.plist;
5168 break;
5169 case Lisp_Misc_Free:
5170 /* If the object was already free, keep it
5171 on the free list. */
5172 markword = (Lisp_Object *) &already_free;
5173 break;
5174 default:
5175 markword = 0;
5176 break;
5178 if (markword && !XMARKBIT (*markword))
5180 Lisp_Object tem;
5181 if (mblk->markers[i].u_marker.type == Lisp_Misc_Marker)
5183 /* tem1 avoids Sun compiler bug */
5184 struct Lisp_Marker *tem1 = &mblk->markers[i].u_marker;
5185 XSETMARKER (tem, tem1);
5186 unchain_marker (tem);
5188 /* Set the type of the freed object to Lisp_Misc_Free.
5189 We could leave the type alone, since nobody checks it,
5190 but this might catch bugs faster. */
5191 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
5192 mblk->markers[i].u_free.chain = marker_free_list;
5193 marker_free_list = &mblk->markers[i];
5194 this_free++;
5196 else
5198 num_used++;
5199 if (markword)
5200 XUNMARK (*markword);
5203 lim = MARKER_BLOCK_SIZE;
5204 /* If this block contains only free markers and we have already
5205 seen more than two blocks worth of free markers then deallocate
5206 this block. */
5207 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
5209 *mprev = mblk->next;
5210 /* Unhook from the free list. */
5211 marker_free_list = mblk->markers[0].u_free.chain;
5212 lisp_free (mblk);
5213 n_marker_blocks--;
5215 else
5217 num_free += this_free;
5218 mprev = &mblk->next;
5222 total_markers = num_used;
5223 total_free_markers = num_free;
5226 /* Free all unmarked buffers */
5228 register struct buffer *buffer = all_buffers, *prev = 0, *next;
5230 while (buffer)
5231 if (!XMARKBIT (buffer->name))
5233 if (prev)
5234 prev->next = buffer->next;
5235 else
5236 all_buffers = buffer->next;
5237 next = buffer->next;
5238 lisp_free (buffer);
5239 buffer = next;
5241 else
5243 XUNMARK (buffer->name);
5244 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
5245 prev = buffer, buffer = buffer->next;
5249 /* Free all unmarked vectors */
5251 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
5252 total_vector_size = 0;
5254 while (vector)
5255 if (!(vector->size & ARRAY_MARK_FLAG))
5257 if (prev)
5258 prev->next = vector->next;
5259 else
5260 all_vectors = vector->next;
5261 next = vector->next;
5262 lisp_free (vector);
5263 n_vectors--;
5264 vector = next;
5267 else
5269 vector->size &= ~ARRAY_MARK_FLAG;
5270 if (vector->size & PSEUDOVECTOR_FLAG)
5271 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
5272 else
5273 total_vector_size += vector->size;
5274 prev = vector, vector = vector->next;
5278 #ifdef GC_CHECK_STRING_BYTES
5279 if (!noninteractive)
5280 check_string_bytes (1);
5281 #endif
5287 /* Debugging aids. */
5289 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
5290 "Return the address of the last byte Emacs has allocated, divided by 1024.\n\
5291 This may be helpful in debugging Emacs's memory usage.\n\
5292 We divide the value by 1024 to make sure it fits in a Lisp integer.")
5295 Lisp_Object end;
5297 XSETINT (end, (EMACS_INT) sbrk (0) / 1024);
5299 return end;
5302 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
5303 "Return a list of counters that measure how much consing there has been.\n\
5304 Each of these counters increments for a certain kind of object.\n\
5305 The counters wrap around from the largest positive integer to zero.\n\
5306 Garbage collection does not decrease them.\n\
5307 The elements of the value are as follows:\n\
5308 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)\n\
5309 All are in units of 1 = one object consed\n\
5310 except for VECTOR-CELLS and STRING-CHARS, which count the total length of\n\
5311 objects consed.\n\
5312 MISCS include overlays, markers, and some internal types.\n\
5313 Frames, windows, buffers, and subprocesses count as vectors\n\
5314 (but the contents of a buffer's text do not count here).")
5317 Lisp_Object consed[8];
5319 XSETINT (consed[0],
5320 cons_cells_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5321 XSETINT (consed[1],
5322 floats_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5323 XSETINT (consed[2],
5324 vector_cells_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5325 XSETINT (consed[3],
5326 symbols_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5327 XSETINT (consed[4],
5328 string_chars_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5329 XSETINT (consed[5],
5330 misc_objects_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5331 XSETINT (consed[6],
5332 intervals_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5333 XSETINT (consed[7],
5334 strings_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
5336 return Flist (8, consed);
5339 int suppress_checking;
5340 void
5341 die (msg, file, line)
5342 const char *msg;
5343 const char *file;
5344 int line;
5346 fprintf (stderr, "\r\nEmacs fatal error: %s:%d: %s\r\n",
5347 file, line, msg);
5348 abort ();
5351 /* Initialization */
5353 void
5354 init_alloc_once ()
5356 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
5357 pure_bytes_used = 0;
5358 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
5359 mem_init ();
5360 Vdead = make_pure_string ("DEAD", 4, 4, 0);
5361 #endif
5362 #ifdef HAVE_SHM
5363 pure_size = PURESIZE;
5364 #endif
5365 all_vectors = 0;
5366 ignore_warnings = 1;
5367 #ifdef DOUG_LEA_MALLOC
5368 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
5369 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
5370 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
5371 #endif
5372 init_strings ();
5373 init_cons ();
5374 init_symbol ();
5375 init_marker ();
5376 init_float ();
5377 init_intervals ();
5379 #ifdef REL_ALLOC
5380 malloc_hysteresis = 32;
5381 #else
5382 malloc_hysteresis = 0;
5383 #endif
5385 spare_memory = (char *) malloc (SPARE_MEMORY);
5387 ignore_warnings = 0;
5388 gcprolist = 0;
5389 byte_stack_list = 0;
5390 staticidx = 0;
5391 consing_since_gc = 0;
5392 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
5393 #ifdef VIRT_ADDR_VARIES
5394 malloc_sbrk_unused = 1<<22; /* A large number */
5395 malloc_sbrk_used = 100000; /* as reasonable as any number */
5396 #endif /* VIRT_ADDR_VARIES */
5399 void
5400 init_alloc ()
5402 gcprolist = 0;
5403 byte_stack_list = 0;
5404 #if GC_MARK_STACK
5405 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
5406 setjmp_tested_p = longjmps_done = 0;
5407 #endif
5408 #endif
5411 void
5412 syms_of_alloc ()
5414 DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold,
5415 "*Number of bytes of consing between garbage collections.\n\
5416 Garbage collection can happen automatically once this many bytes have been\n\
5417 allocated since the last garbage collection. All data types count.\n\n\
5418 Garbage collection happens automatically only when `eval' is called.\n\n\
5419 By binding this temporarily to a large number, you can effectively\n\
5420 prevent garbage collection during a part of the program.");
5422 DEFVAR_INT ("pure-bytes-used", &pure_bytes_used,
5423 "Number of bytes of sharable Lisp data allocated so far.");
5425 DEFVAR_INT ("cons-cells-consed", &cons_cells_consed,
5426 "Number of cons cells that have been consed so far.");
5428 DEFVAR_INT ("floats-consed", &floats_consed,
5429 "Number of floats that have been consed so far.");
5431 DEFVAR_INT ("vector-cells-consed", &vector_cells_consed,
5432 "Number of vector cells that have been consed so far.");
5434 DEFVAR_INT ("symbols-consed", &symbols_consed,
5435 "Number of symbols that have been consed so far.");
5437 DEFVAR_INT ("string-chars-consed", &string_chars_consed,
5438 "Number of string characters that have been consed so far.");
5440 DEFVAR_INT ("misc-objects-consed", &misc_objects_consed,
5441 "Number of miscellaneous objects that have been consed so far.");
5443 DEFVAR_INT ("intervals-consed", &intervals_consed,
5444 "Number of intervals that have been consed so far.");
5446 DEFVAR_INT ("strings-consed", &strings_consed,
5447 "Number of strings that have been consed so far.");
5449 DEFVAR_LISP ("purify-flag", &Vpurify_flag,
5450 "Non-nil means loading Lisp code in order to dump an executable.\n\
5451 This means that certain objects should be allocated in shared (pure) space.");
5453 DEFVAR_INT ("undo-limit", &undo_limit,
5454 "Keep no more undo information once it exceeds this size.\n\
5455 This limit is applied when garbage collection happens.\n\
5456 The size is counted as the number of bytes occupied,\n\
5457 which includes both saved text and other data.");
5458 undo_limit = 20000;
5460 DEFVAR_INT ("undo-strong-limit", &undo_strong_limit,
5461 "Don't keep more than this much size of undo information.\n\
5462 A command which pushes past this size is itself forgotten.\n\
5463 This limit is applied when garbage collection happens.\n\
5464 The size is counted as the number of bytes occupied,\n\
5465 which includes both saved text and other data.");
5466 undo_strong_limit = 30000;
5468 DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
5469 "Non-nil means display messages at start and end of garbage collection.");
5470 garbage_collection_messages = 0;
5472 /* We build this in advance because if we wait until we need it, we might
5473 not be able to allocate the memory to hold it. */
5474 memory_signal_data
5475 = Fcons (Qerror, Fcons (build_string ("Memory exhausted--use M-x save-some-buffers RET"), Qnil));
5476 staticpro (&memory_signal_data);
5478 staticpro (&Qgc_cons_threshold);
5479 Qgc_cons_threshold = intern ("gc-cons-threshold");
5481 staticpro (&Qchar_table_extra_slots);
5482 Qchar_table_extra_slots = intern ("char-table-extra-slots");
5484 defsubr (&Scons);
5485 defsubr (&Slist);
5486 defsubr (&Svector);
5487 defsubr (&Smake_byte_code);
5488 defsubr (&Smake_list);
5489 defsubr (&Smake_vector);
5490 defsubr (&Smake_char_table);
5491 defsubr (&Smake_string);
5492 defsubr (&Smake_bool_vector);
5493 defsubr (&Smake_symbol);
5494 defsubr (&Smake_marker);
5495 defsubr (&Spurecopy);
5496 defsubr (&Sgarbage_collect);
5497 defsubr (&Smemory_limit);
5498 defsubr (&Smemory_use_counts);
5500 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5501 defsubr (&Sgc_status);
5502 #endif