(post-read-decode-hz)
[emacs.git] / src / alloc.c
blobde1f11050bc9ef7b02580aaefae7c16708c157de
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
2 Copyright (C) 1985, 86, 88, 93, 94, 95, 97, 98, 1999, 2000, 2001, 2002
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 #include <config.h>
23 #include <stdio.h>
25 /* 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 "character.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 /* Macro to verify that storage intended for Lisp objects is not
84 out of range to fit in the space for a pointer.
85 ADDRESS is the start of the block, and SIZE
86 is the amount of space within which objects can start. */
88 #define VALIDATE_LISP_STORAGE(address, size) \
89 do \
90 { \
91 Lisp_Object val; \
92 XSETCONS (val, (char *) address + size); \
93 if ((char *) XCONS (val) != (char *) address + size) \
94 { \
95 xfree (address); \
96 memory_full (); \
97 } \
98 } while (0)
100 /* Value of _bytes_used, when spare_memory was freed. */
102 static __malloc_size_t bytes_used_when_full;
104 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
105 to a struct Lisp_String. */
107 #define MARK_STRING(S) ((S)->size |= MARKBIT)
108 #define UNMARK_STRING(S) ((S)->size &= ~MARKBIT)
109 #define STRING_MARKED_P(S) ((S)->size & MARKBIT)
111 /* Value is the number of bytes/chars of S, a pointer to a struct
112 Lisp_String. This must be used instead of STRING_BYTES (S) or
113 S->size during GC, because S->size contains the mark bit for
114 strings. */
116 #define GC_STRING_BYTES(S) (STRING_BYTES (S) & ~MARKBIT)
117 #define GC_STRING_CHARS(S) ((S)->size & ~MARKBIT)
119 /* Number of bytes of consing done since the last gc. */
121 int consing_since_gc;
123 /* Count the amount of consing of various sorts of space. */
125 int cons_cells_consed;
126 int floats_consed;
127 int vector_cells_consed;
128 int symbols_consed;
129 int string_chars_consed;
130 int misc_objects_consed;
131 int intervals_consed;
132 int strings_consed;
134 /* Number of bytes of consing since GC before another GC should be done. */
136 int gc_cons_threshold;
138 /* Nonzero during GC. */
140 int gc_in_progress;
142 /* Nonzero means display messages at beginning and end of GC. */
144 int garbage_collection_messages;
146 #ifndef VIRT_ADDR_VARIES
147 extern
148 #endif /* VIRT_ADDR_VARIES */
149 int malloc_sbrk_used;
151 #ifndef VIRT_ADDR_VARIES
152 extern
153 #endif /* VIRT_ADDR_VARIES */
154 int malloc_sbrk_unused;
156 /* Two limits controlling how much undo information to keep. */
158 int undo_limit;
159 int undo_strong_limit;
161 /* Number of live and free conses etc. */
163 static int total_conses, total_markers, total_symbols, total_vector_size;
164 static int total_free_conses, total_free_markers, total_free_symbols;
165 static int total_free_floats, total_floats;
167 /* Points to memory space allocated as "spare", to be freed if we run
168 out of memory. */
170 static char *spare_memory;
172 /* Amount of spare memory to keep in reserve. */
174 #define SPARE_MEMORY (1 << 14)
176 /* Number of extra blocks malloc should get when it needs more core. */
178 static int malloc_hysteresis;
180 /* Non-nil means defun should do purecopy on the function definition. */
182 Lisp_Object Vpurify_flag;
184 #ifndef HAVE_SHM
186 /* Force it into data space! */
188 EMACS_INT pure[PURESIZE / sizeof (EMACS_INT)] = {0,};
189 #define PUREBEG (char *) pure
191 #else /* HAVE_SHM */
193 #define pure PURE_SEG_BITS /* Use shared memory segment */
194 #define PUREBEG (char *)PURE_SEG_BITS
196 #endif /* HAVE_SHM */
198 /* Pointer to the pure area, and its size. */
200 static char *purebeg;
201 static size_t pure_size;
203 /* Number of bytes of pure storage used before pure storage overflowed.
204 If this is non-zero, this implies that an overflow occurred. */
206 static size_t pure_bytes_used_before_overflow;
208 /* Value is non-zero if P points into pure space. */
210 #define PURE_POINTER_P(P) \
211 (((PNTR_COMPARISON_TYPE) (P) \
212 < (PNTR_COMPARISON_TYPE) ((char *) purebeg + pure_size)) \
213 && ((PNTR_COMPARISON_TYPE) (P) \
214 >= (PNTR_COMPARISON_TYPE) purebeg))
216 /* Index in pure at which next pure object will be allocated.. */
218 int pure_bytes_used;
220 /* If nonzero, this is a warning delivered by malloc and not yet
221 displayed. */
223 char *pending_malloc_warning;
225 /* Pre-computed signal argument for use when memory is exhausted. */
227 Lisp_Object memory_signal_data;
229 /* Maximum amount of C stack to save when a GC happens. */
231 #ifndef MAX_SAVE_STACK
232 #define MAX_SAVE_STACK 16000
233 #endif
235 /* Buffer in which we save a copy of the C stack at each GC. */
237 char *stack_copy;
238 int stack_copy_size;
240 /* Non-zero means ignore malloc warnings. Set during initialization.
241 Currently not used. */
243 int ignore_warnings;
245 Lisp_Object Qgc_cons_threshold, Qchar_table_extra_slots;
247 /* Hook run after GC has finished. */
249 Lisp_Object Vpost_gc_hook, Qpost_gc_hook;
251 static void mark_buffer P_ ((Lisp_Object));
252 static void mark_kboards P_ ((void));
253 static void gc_sweep P_ ((void));
254 static void mark_glyph_matrix P_ ((struct glyph_matrix *));
255 static void mark_face_cache P_ ((struct face_cache *));
257 #ifdef HAVE_WINDOW_SYSTEM
258 static void mark_image P_ ((struct image *));
259 static void mark_image_cache P_ ((struct frame *));
260 #endif /* HAVE_WINDOW_SYSTEM */
262 static struct Lisp_String *allocate_string P_ ((void));
263 static void compact_small_strings P_ ((void));
264 static void free_large_strings P_ ((void));
265 static void sweep_strings P_ ((void));
267 extern int message_enable_multibyte;
269 /* When scanning the C stack for live Lisp objects, Emacs keeps track
270 of what memory allocated via lisp_malloc is intended for what
271 purpose. This enumeration specifies the type of memory. */
273 enum mem_type
275 MEM_TYPE_NON_LISP,
276 MEM_TYPE_BUFFER,
277 MEM_TYPE_CONS,
278 MEM_TYPE_STRING,
279 MEM_TYPE_MISC,
280 MEM_TYPE_SYMBOL,
281 MEM_TYPE_FLOAT,
282 /* Keep the following vector-like types together, with
283 MEM_TYPE_WINDOW being the last, and MEM_TYPE_VECTOR the
284 first. Or change the code of live_vector_p, for instance. */
285 MEM_TYPE_VECTOR,
286 MEM_TYPE_PROCESS,
287 MEM_TYPE_HASH_TABLE,
288 MEM_TYPE_FRAME,
289 MEM_TYPE_WINDOW
292 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
294 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
295 #include <stdio.h> /* For fprintf. */
296 #endif
298 /* A unique object in pure space used to make some Lisp objects
299 on free lists recognizable in O(1). */
301 Lisp_Object Vdead;
303 #ifdef GC_MALLOC_CHECK
305 enum mem_type allocated_mem_type;
306 int dont_register_blocks;
308 #endif /* GC_MALLOC_CHECK */
310 /* A node in the red-black tree describing allocated memory containing
311 Lisp data. Each such block is recorded with its start and end
312 address when it is allocated, and removed from the tree when it
313 is freed.
315 A red-black tree is a balanced binary tree with the following
316 properties:
318 1. Every node is either red or black.
319 2. Every leaf is black.
320 3. If a node is red, then both of its children are black.
321 4. Every simple path from a node to a descendant leaf contains
322 the same number of black nodes.
323 5. The root is always black.
325 When nodes are inserted into the tree, or deleted from the tree,
326 the tree is "fixed" so that these properties are always true.
328 A red-black tree with N internal nodes has height at most 2
329 log(N+1). Searches, insertions and deletions are done in O(log N).
330 Please see a text book about data structures for a detailed
331 description of red-black trees. Any book worth its salt should
332 describe them. */
334 struct mem_node
336 struct mem_node *left, *right, *parent;
338 /* Start and end of allocated region. */
339 void *start, *end;
341 /* Node color. */
342 enum {MEM_BLACK, MEM_RED} color;
344 /* Memory type. */
345 enum mem_type type;
348 /* Base address of stack. Set in main. */
350 Lisp_Object *stack_base;
352 /* Root of the tree describing allocated Lisp memory. */
354 static struct mem_node *mem_root;
356 /* Lowest and highest known address in the heap. */
358 static void *min_heap_address, *max_heap_address;
360 /* Sentinel node of the tree. */
362 static struct mem_node mem_z;
363 #define MEM_NIL &mem_z
365 static POINTER_TYPE *lisp_malloc P_ ((size_t, enum mem_type));
366 static struct Lisp_Vector *allocate_vectorlike P_ ((EMACS_INT, enum mem_type));
367 static void lisp_free P_ ((POINTER_TYPE *));
368 static void mark_stack P_ ((void));
369 static int live_vector_p P_ ((struct mem_node *, void *));
370 static int live_buffer_p P_ ((struct mem_node *, void *));
371 static int live_string_p P_ ((struct mem_node *, void *));
372 static int live_cons_p P_ ((struct mem_node *, void *));
373 static int live_symbol_p P_ ((struct mem_node *, void *));
374 static int live_float_p P_ ((struct mem_node *, void *));
375 static int live_misc_p P_ ((struct mem_node *, void *));
376 static void mark_maybe_object P_ ((Lisp_Object));
377 static void mark_memory P_ ((void *, void *));
378 static void mem_init P_ ((void));
379 static struct mem_node *mem_insert P_ ((void *, void *, enum mem_type));
380 static void mem_insert_fixup P_ ((struct mem_node *));
381 static void mem_rotate_left P_ ((struct mem_node *));
382 static void mem_rotate_right P_ ((struct mem_node *));
383 static void mem_delete P_ ((struct mem_node *));
384 static void mem_delete_fixup P_ ((struct mem_node *));
385 static INLINE struct mem_node *mem_find P_ ((void *));
387 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
388 static void check_gcpros P_ ((void));
389 #endif
391 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
393 /* Recording what needs to be marked for gc. */
395 struct gcpro *gcprolist;
397 /* Addresses of staticpro'd variables. */
399 #define NSTATICS 1280
400 Lisp_Object *staticvec[NSTATICS] = {0};
402 /* Index of next unused slot in staticvec. */
404 int staticidx = 0;
406 static POINTER_TYPE *pure_alloc P_ ((size_t, int));
409 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
410 ALIGNMENT must be a power of 2. */
412 #define ALIGN(SZ, ALIGNMENT) \
413 (((SZ) + (ALIGNMENT) - 1) & ~((ALIGNMENT) - 1))
417 /************************************************************************
418 Malloc
419 ************************************************************************/
421 /* Write STR to Vstandard_output plus some advice on how to free some
422 memory. Called when memory gets low. */
424 Lisp_Object
425 malloc_warning_1 (str)
426 Lisp_Object str;
428 Fprinc (str, Vstandard_output);
429 write_string ("\nKilling some buffers may delay running out of memory.\n", -1);
430 write_string ("However, certainly by the time you receive the 95% warning,\n", -1);
431 write_string ("you should clean up, kill this Emacs, and start a new one.", -1);
432 return Qnil;
436 /* Function malloc calls this if it finds we are near exhausting
437 storage. */
439 void
440 malloc_warning (str)
441 char *str;
443 pending_malloc_warning = str;
447 /* Display a malloc warning in buffer *Danger*. */
449 void
450 display_malloc_warning ()
452 register Lisp_Object val;
454 val = build_string (pending_malloc_warning);
455 pending_malloc_warning = 0;
456 internal_with_output_to_temp_buffer (" *Danger*", malloc_warning_1, val);
460 #ifdef DOUG_LEA_MALLOC
461 # define BYTES_USED (mallinfo ().arena)
462 #else
463 # define BYTES_USED _bytes_used
464 #endif
467 /* Called if malloc returns zero. */
469 void
470 memory_full ()
472 #ifndef SYSTEM_MALLOC
473 bytes_used_when_full = BYTES_USED;
474 #endif
476 /* The first time we get here, free the spare memory. */
477 if (spare_memory)
479 free (spare_memory);
480 spare_memory = 0;
483 /* This used to call error, but if we've run out of memory, we could
484 get infinite recursion trying to build the string. */
485 while (1)
486 Fsignal (Qnil, memory_signal_data);
490 /* Called if we can't allocate relocatable space for a buffer. */
492 void
493 buffer_memory_full ()
495 /* If buffers use the relocating allocator, no need to free
496 spare_memory, because we may have plenty of malloc space left
497 that we could get, and if we don't, the malloc that fails will
498 itself cause spare_memory to be freed. If buffers don't use the
499 relocating allocator, treat this like any other failing
500 malloc. */
502 #ifndef REL_ALLOC
503 memory_full ();
504 #endif
506 /* This used to call error, but if we've run out of memory, we could
507 get infinite recursion trying to build the string. */
508 while (1)
509 Fsignal (Qerror, memory_signal_data);
513 /* Like malloc but check for no memory and block interrupt input.. */
515 POINTER_TYPE *
516 xmalloc (size)
517 size_t size;
519 register POINTER_TYPE *val;
521 BLOCK_INPUT;
522 val = (POINTER_TYPE *) malloc (size);
523 UNBLOCK_INPUT;
525 if (!val && size)
526 memory_full ();
527 return val;
531 /* Like realloc but check for no memory and block interrupt input.. */
533 POINTER_TYPE *
534 xrealloc (block, size)
535 POINTER_TYPE *block;
536 size_t size;
538 register POINTER_TYPE *val;
540 BLOCK_INPUT;
541 /* We must call malloc explicitly when BLOCK is 0, since some
542 reallocs don't do this. */
543 if (! block)
544 val = (POINTER_TYPE *) malloc (size);
545 else
546 val = (POINTER_TYPE *) realloc (block, size);
547 UNBLOCK_INPUT;
549 if (!val && size) memory_full ();
550 return val;
554 /* Like free but block interrupt input.. */
556 void
557 xfree (block)
558 POINTER_TYPE *block;
560 BLOCK_INPUT;
561 free (block);
562 UNBLOCK_INPUT;
566 /* Like strdup, but uses xmalloc. */
568 char *
569 xstrdup (s)
570 char *s;
572 size_t len = strlen (s) + 1;
573 char *p = (char *) xmalloc (len);
574 bcopy (s, p, len);
575 return p;
579 /* Like malloc but used for allocating Lisp data. NBYTES is the
580 number of bytes to allocate, TYPE describes the intended use of the
581 allcated memory block (for strings, for conses, ...). */
583 static POINTER_TYPE *
584 lisp_malloc (nbytes, type)
585 size_t nbytes;
586 enum mem_type type;
588 register void *val;
590 BLOCK_INPUT;
592 #ifdef GC_MALLOC_CHECK
593 allocated_mem_type = type;
594 #endif
596 val = (void *) malloc (nbytes);
598 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
599 if (val && type != MEM_TYPE_NON_LISP)
600 mem_insert (val, (char *) val + nbytes, type);
601 #endif
603 UNBLOCK_INPUT;
604 if (!val && nbytes)
605 memory_full ();
606 return val;
610 /* Return a new buffer structure allocated from the heap with
611 a call to lisp_malloc. */
613 struct buffer *
614 allocate_buffer ()
616 struct buffer *b
617 = (struct buffer *) lisp_malloc (sizeof (struct buffer),
618 MEM_TYPE_BUFFER);
619 VALIDATE_LISP_STORAGE (b, sizeof *b);
620 return b;
624 /* Free BLOCK. This must be called to free memory allocated with a
625 call to lisp_malloc. */
627 static void
628 lisp_free (block)
629 POINTER_TYPE *block;
631 BLOCK_INPUT;
632 free (block);
633 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
634 mem_delete (mem_find (block));
635 #endif
636 UNBLOCK_INPUT;
640 /* Arranging to disable input signals while we're in malloc.
642 This only works with GNU malloc. To help out systems which can't
643 use GNU malloc, all the calls to malloc, realloc, and free
644 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
645 pairs; unfortunately, we have no idea what C library functions
646 might call malloc, so we can't really protect them unless you're
647 using GNU malloc. Fortunately, most of the major operating can use
648 GNU malloc. */
650 #ifndef SYSTEM_MALLOC
651 #ifndef DOUG_LEA_MALLOC
652 extern void * (*__malloc_hook) P_ ((size_t));
653 extern void * (*__realloc_hook) P_ ((void *, size_t));
654 extern void (*__free_hook) P_ ((void *));
655 /* Else declared in malloc.h, perhaps with an extra arg. */
656 #endif /* DOUG_LEA_MALLOC */
657 static void * (*old_malloc_hook) ();
658 static void * (*old_realloc_hook) ();
659 static void (*old_free_hook) ();
661 /* This function is used as the hook for free to call. */
663 static void
664 emacs_blocked_free (ptr)
665 void *ptr;
667 BLOCK_INPUT;
669 #ifdef GC_MALLOC_CHECK
670 if (ptr)
672 struct mem_node *m;
674 m = mem_find (ptr);
675 if (m == MEM_NIL || m->start != ptr)
677 fprintf (stderr,
678 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
679 abort ();
681 else
683 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
684 mem_delete (m);
687 #endif /* GC_MALLOC_CHECK */
689 __free_hook = old_free_hook;
690 free (ptr);
692 /* If we released our reserve (due to running out of memory),
693 and we have a fair amount free once again,
694 try to set aside another reserve in case we run out once more. */
695 if (spare_memory == 0
696 /* Verify there is enough space that even with the malloc
697 hysteresis this call won't run out again.
698 The code here is correct as long as SPARE_MEMORY
699 is substantially larger than the block size malloc uses. */
700 && (bytes_used_when_full
701 > BYTES_USED + max (malloc_hysteresis, 4) * SPARE_MEMORY))
702 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
704 __free_hook = emacs_blocked_free;
705 UNBLOCK_INPUT;
709 /* If we released our reserve (due to running out of memory),
710 and we have a fair amount free once again,
711 try to set aside another reserve in case we run out once more.
713 This is called when a relocatable block is freed in ralloc.c. */
715 void
716 refill_memory_reserve ()
718 if (spare_memory == 0)
719 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
723 /* This function is the malloc hook that Emacs uses. */
725 static void *
726 emacs_blocked_malloc (size)
727 size_t size;
729 void *value;
731 BLOCK_INPUT;
732 __malloc_hook = old_malloc_hook;
733 #ifdef DOUG_LEA_MALLOC
734 mallopt (M_TOP_PAD, malloc_hysteresis * 4096);
735 #else
736 __malloc_extra_blocks = malloc_hysteresis;
737 #endif
739 value = (void *) malloc (size);
741 #ifdef GC_MALLOC_CHECK
743 struct mem_node *m = mem_find (value);
744 if (m != MEM_NIL)
746 fprintf (stderr, "Malloc returned %p which is already in use\n",
747 value);
748 fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
749 m->start, m->end, (char *) m->end - (char *) m->start,
750 m->type);
751 abort ();
754 if (!dont_register_blocks)
756 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
757 allocated_mem_type = MEM_TYPE_NON_LISP;
760 #endif /* GC_MALLOC_CHECK */
762 __malloc_hook = emacs_blocked_malloc;
763 UNBLOCK_INPUT;
765 /* fprintf (stderr, "%p malloc\n", value); */
766 return value;
770 /* This function is the realloc hook that Emacs uses. */
772 static void *
773 emacs_blocked_realloc (ptr, size)
774 void *ptr;
775 size_t size;
777 void *value;
779 BLOCK_INPUT;
780 __realloc_hook = old_realloc_hook;
782 #ifdef GC_MALLOC_CHECK
783 if (ptr)
785 struct mem_node *m = mem_find (ptr);
786 if (m == MEM_NIL || m->start != ptr)
788 fprintf (stderr,
789 "Realloc of %p which wasn't allocated with malloc\n",
790 ptr);
791 abort ();
794 mem_delete (m);
797 /* fprintf (stderr, "%p -> realloc\n", ptr); */
799 /* Prevent malloc from registering blocks. */
800 dont_register_blocks = 1;
801 #endif /* GC_MALLOC_CHECK */
803 value = (void *) realloc (ptr, size);
805 #ifdef GC_MALLOC_CHECK
806 dont_register_blocks = 0;
809 struct mem_node *m = mem_find (value);
810 if (m != MEM_NIL)
812 fprintf (stderr, "Realloc returns memory that is already in use\n");
813 abort ();
816 /* Can't handle zero size regions in the red-black tree. */
817 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
820 /* fprintf (stderr, "%p <- realloc\n", value); */
821 #endif /* GC_MALLOC_CHECK */
823 __realloc_hook = emacs_blocked_realloc;
824 UNBLOCK_INPUT;
826 return value;
830 /* Called from main to set up malloc to use our hooks. */
832 void
833 uninterrupt_malloc ()
835 if (__free_hook != emacs_blocked_free)
836 old_free_hook = __free_hook;
837 __free_hook = emacs_blocked_free;
839 if (__malloc_hook != emacs_blocked_malloc)
840 old_malloc_hook = __malloc_hook;
841 __malloc_hook = emacs_blocked_malloc;
843 if (__realloc_hook != emacs_blocked_realloc)
844 old_realloc_hook = __realloc_hook;
845 __realloc_hook = emacs_blocked_realloc;
848 #endif /* not SYSTEM_MALLOC */
852 /***********************************************************************
853 Interval Allocation
854 ***********************************************************************/
856 /* Number of intervals allocated in an interval_block structure.
857 The 1020 is 1024 minus malloc overhead. */
859 #define INTERVAL_BLOCK_SIZE \
860 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
862 /* Intervals are allocated in chunks in form of an interval_block
863 structure. */
865 struct interval_block
867 struct interval_block *next;
868 struct interval intervals[INTERVAL_BLOCK_SIZE];
871 /* Current interval block. Its `next' pointer points to older
872 blocks. */
874 struct interval_block *interval_block;
876 /* Index in interval_block above of the next unused interval
877 structure. */
879 static int interval_block_index;
881 /* Number of free and live intervals. */
883 static int total_free_intervals, total_intervals;
885 /* List of free intervals. */
887 INTERVAL interval_free_list;
889 /* Total number of interval blocks now in use. */
891 int n_interval_blocks;
894 /* Initialize interval allocation. */
896 static void
897 init_intervals ()
899 interval_block
900 = (struct interval_block *) lisp_malloc (sizeof *interval_block,
901 MEM_TYPE_NON_LISP);
902 interval_block->next = 0;
903 bzero ((char *) interval_block->intervals, sizeof interval_block->intervals);
904 interval_block_index = 0;
905 interval_free_list = 0;
906 n_interval_blocks = 1;
910 /* Return a new interval. */
912 INTERVAL
913 make_interval ()
915 INTERVAL val;
917 if (interval_free_list)
919 val = interval_free_list;
920 interval_free_list = INTERVAL_PARENT (interval_free_list);
922 else
924 if (interval_block_index == INTERVAL_BLOCK_SIZE)
926 register struct interval_block *newi;
928 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
929 MEM_TYPE_NON_LISP);
931 VALIDATE_LISP_STORAGE (newi, sizeof *newi);
932 newi->next = interval_block;
933 interval_block = newi;
934 interval_block_index = 0;
935 n_interval_blocks++;
937 val = &interval_block->intervals[interval_block_index++];
939 consing_since_gc += sizeof (struct interval);
940 intervals_consed++;
941 RESET_INTERVAL (val);
942 return val;
946 /* Mark Lisp objects in interval I. */
948 static void
949 mark_interval (i, dummy)
950 register INTERVAL i;
951 Lisp_Object dummy;
953 if (XMARKBIT (i->plist))
954 abort ();
955 mark_object (&i->plist);
956 XMARK (i->plist);
960 /* Mark the interval tree rooted in TREE. Don't call this directly;
961 use the macro MARK_INTERVAL_TREE instead. */
963 static void
964 mark_interval_tree (tree)
965 register INTERVAL tree;
967 /* No need to test if this tree has been marked already; this
968 function is always called through the MARK_INTERVAL_TREE macro,
969 which takes care of that. */
971 /* XMARK expands to an assignment; the LHS of an assignment can't be
972 a cast. */
973 XMARK (tree->up.obj);
975 traverse_intervals_noorder (tree, mark_interval, Qnil);
979 /* Mark the interval tree rooted in I. */
981 #define MARK_INTERVAL_TREE(i) \
982 do { \
983 if (!NULL_INTERVAL_P (i) \
984 && ! XMARKBIT (i->up.obj)) \
985 mark_interval_tree (i); \
986 } while (0)
989 /* The oddity in the call to XUNMARK is necessary because XUNMARK
990 expands to an assignment to its argument, and most C compilers
991 don't support casts on the left operand of `='. */
993 #define UNMARK_BALANCE_INTERVALS(i) \
994 do { \
995 if (! NULL_INTERVAL_P (i)) \
997 XUNMARK ((i)->up.obj); \
998 (i) = balance_intervals (i); \
1000 } while (0)
1003 /* Number support. If NO_UNION_TYPE isn't in effect, we
1004 can't create number objects in macros. */
1005 #ifndef make_number
1006 Lisp_Object
1007 make_number (n)
1008 int n;
1010 Lisp_Object obj;
1011 obj.s.val = n;
1012 obj.s.type = Lisp_Int;
1013 return obj;
1015 #endif
1017 /***********************************************************************
1018 String Allocation
1019 ***********************************************************************/
1021 /* Lisp_Strings are allocated in string_block structures. When a new
1022 string_block is allocated, all the Lisp_Strings it contains are
1023 added to a free-list string_free_list. When a new Lisp_String is
1024 needed, it is taken from that list. During the sweep phase of GC,
1025 string_blocks that are entirely free are freed, except two which
1026 we keep.
1028 String data is allocated from sblock structures. Strings larger
1029 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1030 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1032 Sblocks consist internally of sdata structures, one for each
1033 Lisp_String. The sdata structure points to the Lisp_String it
1034 belongs to. The Lisp_String points back to the `u.data' member of
1035 its sdata structure.
1037 When a Lisp_String is freed during GC, it is put back on
1038 string_free_list, and its `data' member and its sdata's `string'
1039 pointer is set to null. The size of the string is recorded in the
1040 `u.nbytes' member of the sdata. So, sdata structures that are no
1041 longer used, can be easily recognized, and it's easy to compact the
1042 sblocks of small strings which we do in compact_small_strings. */
1044 /* Size in bytes of an sblock structure used for small strings. This
1045 is 8192 minus malloc overhead. */
1047 #define SBLOCK_SIZE 8188
1049 /* Strings larger than this are considered large strings. String data
1050 for large strings is allocated from individual sblocks. */
1052 #define LARGE_STRING_BYTES 1024
1054 /* Structure describing string memory sub-allocated from an sblock.
1055 This is where the contents of Lisp strings are stored. */
1057 struct sdata
1059 /* Back-pointer to the string this sdata belongs to. If null, this
1060 structure is free, and the NBYTES member of the union below
1061 contains the string's byte size (the same value that STRING_BYTES
1062 would return if STRING were non-null). If non-null, STRING_BYTES
1063 (STRING) is the size of the data, and DATA contains the string's
1064 contents. */
1065 struct Lisp_String *string;
1067 #ifdef GC_CHECK_STRING_BYTES
1069 EMACS_INT nbytes;
1070 unsigned char data[1];
1072 #define SDATA_NBYTES(S) (S)->nbytes
1073 #define SDATA_DATA(S) (S)->data
1075 #else /* not GC_CHECK_STRING_BYTES */
1077 union
1079 /* When STRING in non-null. */
1080 unsigned char data[1];
1082 /* When STRING is null. */
1083 EMACS_INT nbytes;
1084 } u;
1087 #define SDATA_NBYTES(S) (S)->u.nbytes
1088 #define SDATA_DATA(S) (S)->u.data
1090 #endif /* not GC_CHECK_STRING_BYTES */
1094 /* Structure describing a block of memory which is sub-allocated to
1095 obtain string data memory for strings. Blocks for small strings
1096 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1097 as large as needed. */
1099 struct sblock
1101 /* Next in list. */
1102 struct sblock *next;
1104 /* Pointer to the next free sdata block. This points past the end
1105 of the sblock if there isn't any space left in this block. */
1106 struct sdata *next_free;
1108 /* Start of data. */
1109 struct sdata first_data;
1112 /* Number of Lisp strings in a string_block structure. The 1020 is
1113 1024 minus malloc overhead. */
1115 #define STRINGS_IN_STRING_BLOCK \
1116 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1118 /* Structure describing a block from which Lisp_String structures
1119 are allocated. */
1121 struct string_block
1123 struct string_block *next;
1124 struct Lisp_String strings[STRINGS_IN_STRING_BLOCK];
1127 /* Head and tail of the list of sblock structures holding Lisp string
1128 data. We always allocate from current_sblock. The NEXT pointers
1129 in the sblock structures go from oldest_sblock to current_sblock. */
1131 static struct sblock *oldest_sblock, *current_sblock;
1133 /* List of sblocks for large strings. */
1135 static struct sblock *large_sblocks;
1137 /* List of string_block structures, and how many there are. */
1139 static struct string_block *string_blocks;
1140 static int n_string_blocks;
1142 /* Free-list of Lisp_Strings. */
1144 static struct Lisp_String *string_free_list;
1146 /* Number of live and free Lisp_Strings. */
1148 static int total_strings, total_free_strings;
1150 /* Number of bytes used by live strings. */
1152 static int total_string_size;
1154 /* Given a pointer to a Lisp_String S which is on the free-list
1155 string_free_list, return a pointer to its successor in the
1156 free-list. */
1158 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1160 /* Return a pointer to the sdata structure belonging to Lisp string S.
1161 S must be live, i.e. S->data must not be null. S->data is actually
1162 a pointer to the `u.data' member of its sdata structure; the
1163 structure starts at a constant offset in front of that. */
1165 #ifdef GC_CHECK_STRING_BYTES
1167 #define SDATA_OF_STRING(S) \
1168 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *) \
1169 - sizeof (EMACS_INT)))
1171 #else /* not GC_CHECK_STRING_BYTES */
1173 #define SDATA_OF_STRING(S) \
1174 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))
1176 #endif /* not GC_CHECK_STRING_BYTES */
1178 /* Value is the size of an sdata structure large enough to hold NBYTES
1179 bytes of string data. The value returned includes a terminating
1180 NUL byte, the size of the sdata structure, and padding. */
1182 #ifdef GC_CHECK_STRING_BYTES
1184 #define SDATA_SIZE(NBYTES) \
1185 ((sizeof (struct Lisp_String *) \
1186 + (NBYTES) + 1 \
1187 + sizeof (EMACS_INT) \
1188 + sizeof (EMACS_INT) - 1) \
1189 & ~(sizeof (EMACS_INT) - 1))
1191 #else /* not GC_CHECK_STRING_BYTES */
1193 #define SDATA_SIZE(NBYTES) \
1194 ((sizeof (struct Lisp_String *) \
1195 + (NBYTES) + 1 \
1196 + sizeof (EMACS_INT) - 1) \
1197 & ~(sizeof (EMACS_INT) - 1))
1199 #endif /* not GC_CHECK_STRING_BYTES */
1201 /* Initialize string allocation. Called from init_alloc_once. */
1203 void
1204 init_strings ()
1206 total_strings = total_free_strings = total_string_size = 0;
1207 oldest_sblock = current_sblock = large_sblocks = NULL;
1208 string_blocks = NULL;
1209 n_string_blocks = 0;
1210 string_free_list = NULL;
1214 #ifdef GC_CHECK_STRING_BYTES
1216 static int check_string_bytes_count;
1218 void check_string_bytes P_ ((int));
1219 void check_sblock P_ ((struct sblock *));
1221 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1224 /* Like GC_STRING_BYTES, but with debugging check. */
1227 string_bytes (s)
1228 struct Lisp_String *s;
1230 int nbytes = (s->size_byte < 0 ? s->size : s->size_byte) & ~MARKBIT;
1231 if (!PURE_POINTER_P (s)
1232 && s->data
1233 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1234 abort ();
1235 return nbytes;
1238 /* Check validity Lisp strings' string_bytes member in B. */
1240 void
1241 check_sblock (b)
1242 struct sblock *b;
1244 struct sdata *from, *end, *from_end;
1246 end = b->next_free;
1248 for (from = &b->first_data; from < end; from = from_end)
1250 /* Compute the next FROM here because copying below may
1251 overwrite data we need to compute it. */
1252 int nbytes;
1254 /* Check that the string size recorded in the string is the
1255 same as the one recorded in the sdata structure. */
1256 if (from->string)
1257 CHECK_STRING_BYTES (from->string);
1259 if (from->string)
1260 nbytes = GC_STRING_BYTES (from->string);
1261 else
1262 nbytes = SDATA_NBYTES (from);
1264 nbytes = SDATA_SIZE (nbytes);
1265 from_end = (struct sdata *) ((char *) from + nbytes);
1270 /* Check validity of Lisp strings' string_bytes member. ALL_P
1271 non-zero means check all strings, otherwise check only most
1272 recently allocated strings. Used for hunting a bug. */
1274 void
1275 check_string_bytes (all_p)
1276 int all_p;
1278 if (all_p)
1280 struct sblock *b;
1282 for (b = large_sblocks; b; b = b->next)
1284 struct Lisp_String *s = b->first_data.string;
1285 if (s)
1286 CHECK_STRING_BYTES (s);
1289 for (b = oldest_sblock; b; b = b->next)
1290 check_sblock (b);
1292 else
1293 check_sblock (current_sblock);
1296 #endif /* GC_CHECK_STRING_BYTES */
1299 /* Return a new Lisp_String. */
1301 static struct Lisp_String *
1302 allocate_string ()
1304 struct Lisp_String *s;
1306 /* If the free-list is empty, allocate a new string_block, and
1307 add all the Lisp_Strings in it to the free-list. */
1308 if (string_free_list == NULL)
1310 struct string_block *b;
1311 int i;
1313 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1314 VALIDATE_LISP_STORAGE (b, sizeof *b);
1315 bzero (b, sizeof *b);
1316 b->next = string_blocks;
1317 string_blocks = b;
1318 ++n_string_blocks;
1320 for (i = STRINGS_IN_STRING_BLOCK - 1; i >= 0; --i)
1322 s = b->strings + i;
1323 NEXT_FREE_LISP_STRING (s) = string_free_list;
1324 string_free_list = s;
1327 total_free_strings += STRINGS_IN_STRING_BLOCK;
1330 /* Pop a Lisp_String off the free-list. */
1331 s = string_free_list;
1332 string_free_list = NEXT_FREE_LISP_STRING (s);
1334 /* Probably not strictly necessary, but play it safe. */
1335 bzero (s, sizeof *s);
1337 --total_free_strings;
1338 ++total_strings;
1339 ++strings_consed;
1340 consing_since_gc += sizeof *s;
1342 #ifdef GC_CHECK_STRING_BYTES
1343 if (!noninteractive
1344 #ifdef macintosh
1345 && current_sblock
1346 #endif
1349 if (++check_string_bytes_count == 200)
1351 check_string_bytes_count = 0;
1352 check_string_bytes (1);
1354 else
1355 check_string_bytes (0);
1357 #endif /* GC_CHECK_STRING_BYTES */
1359 return s;
1363 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1364 plus a NUL byte at the end. Allocate an sdata structure for S, and
1365 set S->data to its `u.data' member. Store a NUL byte at the end of
1366 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1367 S->data if it was initially non-null. */
1369 void
1370 allocate_string_data (s, nchars, nbytes)
1371 struct Lisp_String *s;
1372 int nchars, nbytes;
1374 struct sdata *data, *old_data;
1375 struct sblock *b;
1376 int needed, old_nbytes;
1378 /* Determine the number of bytes needed to store NBYTES bytes
1379 of string data. */
1380 needed = SDATA_SIZE (nbytes);
1382 if (nbytes > LARGE_STRING_BYTES)
1384 size_t size = sizeof *b - sizeof (struct sdata) + needed;
1386 #ifdef DOUG_LEA_MALLOC
1387 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1388 because mapped region contents are not preserved in
1389 a dumped Emacs. */
1390 mallopt (M_MMAP_MAX, 0);
1391 #endif
1393 b = (struct sblock *) lisp_malloc (size, MEM_TYPE_NON_LISP);
1395 #ifdef DOUG_LEA_MALLOC
1396 /* Back to a reasonable maximum of mmap'ed areas. */
1397 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1398 #endif
1400 b->next_free = &b->first_data;
1401 b->first_data.string = NULL;
1402 b->next = large_sblocks;
1403 large_sblocks = b;
1405 else if (current_sblock == NULL
1406 || (((char *) current_sblock + SBLOCK_SIZE
1407 - (char *) current_sblock->next_free)
1408 < needed))
1410 /* Not enough room in the current sblock. */
1411 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1412 b->next_free = &b->first_data;
1413 b->first_data.string = NULL;
1414 b->next = NULL;
1416 if (current_sblock)
1417 current_sblock->next = b;
1418 else
1419 oldest_sblock = b;
1420 current_sblock = b;
1422 else
1423 b = current_sblock;
1425 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1426 old_nbytes = GC_STRING_BYTES (s);
1428 data = b->next_free;
1429 data->string = s;
1430 s->data = SDATA_DATA (data);
1431 #ifdef GC_CHECK_STRING_BYTES
1432 SDATA_NBYTES (data) = nbytes;
1433 #endif
1434 s->size = nchars;
1435 s->size_byte = nbytes;
1436 s->data[nbytes] = '\0';
1437 b->next_free = (struct sdata *) ((char *) data + needed);
1439 /* If S had already data assigned, mark that as free by setting its
1440 string back-pointer to null, and recording the size of the data
1441 in it. */
1442 if (old_data)
1444 SDATA_NBYTES (old_data) = old_nbytes;
1445 old_data->string = NULL;
1448 consing_since_gc += needed;
1452 /* Sweep and compact strings. */
1454 static void
1455 sweep_strings ()
1457 struct string_block *b, *next;
1458 struct string_block *live_blocks = NULL;
1460 string_free_list = NULL;
1461 total_strings = total_free_strings = 0;
1462 total_string_size = 0;
1464 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1465 for (b = string_blocks; b; b = next)
1467 int i, nfree = 0;
1468 struct Lisp_String *free_list_before = string_free_list;
1470 next = b->next;
1472 for (i = 0; i < STRINGS_IN_STRING_BLOCK; ++i)
1474 struct Lisp_String *s = b->strings + i;
1476 if (s->data)
1478 /* String was not on free-list before. */
1479 if (STRING_MARKED_P (s))
1481 /* String is live; unmark it and its intervals. */
1482 UNMARK_STRING (s);
1484 if (!NULL_INTERVAL_P (s->intervals))
1485 UNMARK_BALANCE_INTERVALS (s->intervals);
1487 ++total_strings;
1488 total_string_size += STRING_BYTES (s);
1490 else
1492 /* String is dead. Put it on the free-list. */
1493 struct sdata *data = SDATA_OF_STRING (s);
1495 /* Save the size of S in its sdata so that we know
1496 how large that is. Reset the sdata's string
1497 back-pointer so that we know it's free. */
1498 #ifdef GC_CHECK_STRING_BYTES
1499 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
1500 abort ();
1501 #else
1502 data->u.nbytes = GC_STRING_BYTES (s);
1503 #endif
1504 data->string = NULL;
1506 /* Reset the strings's `data' member so that we
1507 know it's free. */
1508 s->data = NULL;
1510 /* Put the string on the free-list. */
1511 NEXT_FREE_LISP_STRING (s) = string_free_list;
1512 string_free_list = s;
1513 ++nfree;
1516 else
1518 /* S was on the free-list before. Put it there again. */
1519 NEXT_FREE_LISP_STRING (s) = string_free_list;
1520 string_free_list = s;
1521 ++nfree;
1525 /* Free blocks that contain free Lisp_Strings only, except
1526 the first two of them. */
1527 if (nfree == STRINGS_IN_STRING_BLOCK
1528 && total_free_strings > STRINGS_IN_STRING_BLOCK)
1530 lisp_free (b);
1531 --n_string_blocks;
1532 string_free_list = free_list_before;
1534 else
1536 total_free_strings += nfree;
1537 b->next = live_blocks;
1538 live_blocks = b;
1542 string_blocks = live_blocks;
1543 free_large_strings ();
1544 compact_small_strings ();
1548 /* Free dead large strings. */
1550 static void
1551 free_large_strings ()
1553 struct sblock *b, *next;
1554 struct sblock *live_blocks = NULL;
1556 for (b = large_sblocks; b; b = next)
1558 next = b->next;
1560 if (b->first_data.string == NULL)
1561 lisp_free (b);
1562 else
1564 b->next = live_blocks;
1565 live_blocks = b;
1569 large_sblocks = live_blocks;
1573 /* Compact data of small strings. Free sblocks that don't contain
1574 data of live strings after compaction. */
1576 static void
1577 compact_small_strings ()
1579 struct sblock *b, *tb, *next;
1580 struct sdata *from, *to, *end, *tb_end;
1581 struct sdata *to_end, *from_end;
1583 /* TB is the sblock we copy to, TO is the sdata within TB we copy
1584 to, and TB_END is the end of TB. */
1585 tb = oldest_sblock;
1586 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1587 to = &tb->first_data;
1589 /* Step through the blocks from the oldest to the youngest. We
1590 expect that old blocks will stabilize over time, so that less
1591 copying will happen this way. */
1592 for (b = oldest_sblock; b; b = b->next)
1594 end = b->next_free;
1595 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
1597 for (from = &b->first_data; from < end; from = from_end)
1599 /* Compute the next FROM here because copying below may
1600 overwrite data we need to compute it. */
1601 int nbytes;
1603 #ifdef GC_CHECK_STRING_BYTES
1604 /* Check that the string size recorded in the string is the
1605 same as the one recorded in the sdata structure. */
1606 if (from->string
1607 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
1608 abort ();
1609 #endif /* GC_CHECK_STRING_BYTES */
1611 if (from->string)
1612 nbytes = GC_STRING_BYTES (from->string);
1613 else
1614 nbytes = SDATA_NBYTES (from);
1616 nbytes = SDATA_SIZE (nbytes);
1617 from_end = (struct sdata *) ((char *) from + nbytes);
1619 /* FROM->string non-null means it's alive. Copy its data. */
1620 if (from->string)
1622 /* If TB is full, proceed with the next sblock. */
1623 to_end = (struct sdata *) ((char *) to + nbytes);
1624 if (to_end > tb_end)
1626 tb->next_free = to;
1627 tb = tb->next;
1628 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1629 to = &tb->first_data;
1630 to_end = (struct sdata *) ((char *) to + nbytes);
1633 /* Copy, and update the string's `data' pointer. */
1634 if (from != to)
1636 xassert (tb != b || to <= from);
1637 safe_bcopy ((char *) from, (char *) to, nbytes);
1638 to->string->data = SDATA_DATA (to);
1641 /* Advance past the sdata we copied to. */
1642 to = to_end;
1647 /* The rest of the sblocks following TB don't contain live data, so
1648 we can free them. */
1649 for (b = tb->next; b; b = next)
1651 next = b->next;
1652 lisp_free (b);
1655 tb->next_free = to;
1656 tb->next = NULL;
1657 current_sblock = tb;
1661 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
1662 doc: /* Return a newly created string of length LENGTH, with each element being INIT.
1663 Both LENGTH and INIT must be numbers. */)
1664 (length, init)
1665 Lisp_Object length, init;
1667 register Lisp_Object val;
1668 register unsigned char *p, *end;
1669 int c, nbytes;
1671 CHECK_NATNUM (length);
1672 CHECK_NUMBER (init);
1674 c = XINT (init);
1675 if (SINGLE_BYTE_CHAR_P (c))
1677 nbytes = XINT (length);
1678 val = make_uninit_string (nbytes);
1679 p = XSTRING (val)->data;
1680 end = p + XSTRING (val)->size;
1681 while (p != end)
1682 *p++ = c;
1684 else
1686 unsigned char str[MAX_MULTIBYTE_LENGTH];
1687 int len = CHAR_STRING (c, str);
1689 nbytes = len * XINT (length);
1690 val = make_uninit_multibyte_string (XINT (length), nbytes);
1691 p = XSTRING (val)->data;
1692 end = p + nbytes;
1693 while (p != end)
1695 bcopy (str, p, len);
1696 p += len;
1700 *p = 0;
1701 return val;
1705 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
1706 doc: /* Return a new bool-vector of length LENGTH, using INIT for as each element.
1707 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
1708 (length, init)
1709 Lisp_Object length, init;
1711 register Lisp_Object val;
1712 struct Lisp_Bool_Vector *p;
1713 int real_init, i;
1714 int length_in_chars, length_in_elts, bits_per_value;
1716 CHECK_NATNUM (length);
1718 bits_per_value = sizeof (EMACS_INT) * BITS_PER_CHAR;
1720 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
1721 length_in_chars = ((XFASTINT (length) + BITS_PER_CHAR - 1) / BITS_PER_CHAR);
1723 /* We must allocate one more elements than LENGTH_IN_ELTS for the
1724 slot `size' of the struct Lisp_Bool_Vector. */
1725 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
1726 p = XBOOL_VECTOR (val);
1728 /* Get rid of any bits that would cause confusion. */
1729 p->vector_size = 0;
1730 XSETBOOL_VECTOR (val, p);
1731 p->size = XFASTINT (length);
1733 real_init = (NILP (init) ? 0 : -1);
1734 for (i = 0; i < length_in_chars ; i++)
1735 p->data[i] = real_init;
1737 /* Clear the extraneous bits in the last byte. */
1738 if (XINT (length) != length_in_chars * BITS_PER_CHAR)
1739 XBOOL_VECTOR (val)->data[length_in_chars - 1]
1740 &= (1 << (XINT (length) % BITS_PER_CHAR)) - 1;
1742 return val;
1746 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
1747 of characters from the contents. This string may be unibyte or
1748 multibyte, depending on the contents. */
1750 Lisp_Object
1751 make_string (contents, nbytes)
1752 char *contents;
1753 int nbytes;
1755 register Lisp_Object val;
1756 int nchars, multibyte_nbytes;
1758 parse_str_as_multibyte (contents, nbytes, &nchars, &multibyte_nbytes);
1759 if (nbytes == nchars || nbytes != multibyte_nbytes)
1760 /* CONTENTS contains no multibyte sequences or contains an invalid
1761 multibyte sequence. We must make unibyte string. */
1762 val = make_unibyte_string (contents, nbytes);
1763 else
1764 val = make_multibyte_string (contents, nchars, nbytes);
1765 return val;
1769 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
1771 Lisp_Object
1772 make_unibyte_string (contents, length)
1773 char *contents;
1774 int length;
1776 register Lisp_Object val;
1777 val = make_uninit_string (length);
1778 bcopy (contents, XSTRING (val)->data, length);
1779 SET_STRING_BYTES (XSTRING (val), -1);
1780 return val;
1784 /* Make a multibyte string from NCHARS characters occupying NBYTES
1785 bytes at CONTENTS. */
1787 Lisp_Object
1788 make_multibyte_string (contents, nchars, nbytes)
1789 char *contents;
1790 int nchars, nbytes;
1792 register Lisp_Object val;
1793 val = make_uninit_multibyte_string (nchars, nbytes);
1794 bcopy (contents, XSTRING (val)->data, nbytes);
1795 return val;
1799 /* Make a string from NCHARS characters occupying NBYTES bytes at
1800 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
1802 Lisp_Object
1803 make_string_from_bytes (contents, nchars, nbytes)
1804 char *contents;
1805 int nchars, nbytes;
1807 register Lisp_Object val;
1808 val = make_uninit_multibyte_string (nchars, nbytes);
1809 bcopy (contents, XSTRING (val)->data, nbytes);
1810 if (STRING_BYTES (XSTRING (val)) == XSTRING (val)->size)
1811 SET_STRING_BYTES (XSTRING (val), -1);
1812 return val;
1816 /* Make a string from NCHARS characters occupying NBYTES bytes at
1817 CONTENTS. The argument MULTIBYTE controls whether to label the
1818 string as multibyte. */
1820 Lisp_Object
1821 make_specified_string (contents, nchars, nbytes, multibyte)
1822 char *contents;
1823 int nchars, nbytes;
1824 int multibyte;
1826 register Lisp_Object val;
1827 val = make_uninit_multibyte_string (nchars, nbytes);
1828 bcopy (contents, XSTRING (val)->data, nbytes);
1829 if (!multibyte)
1830 SET_STRING_BYTES (XSTRING (val), -1);
1831 return val;
1835 /* Make a string from the data at STR, treating it as multibyte if the
1836 data warrants. */
1838 Lisp_Object
1839 build_string (str)
1840 char *str;
1842 return make_string (str, strlen (str));
1846 /* Return an unibyte Lisp_String set up to hold LENGTH characters
1847 occupying LENGTH bytes. */
1849 Lisp_Object
1850 make_uninit_string (length)
1851 int length;
1853 Lisp_Object val;
1854 val = make_uninit_multibyte_string (length, length);
1855 SET_STRING_BYTES (XSTRING (val), -1);
1856 return val;
1860 /* Return a multibyte Lisp_String set up to hold NCHARS characters
1861 which occupy NBYTES bytes. */
1863 Lisp_Object
1864 make_uninit_multibyte_string (nchars, nbytes)
1865 int nchars, nbytes;
1867 Lisp_Object string;
1868 struct Lisp_String *s;
1870 if (nchars < 0)
1871 abort ();
1873 s = allocate_string ();
1874 allocate_string_data (s, nchars, nbytes);
1875 XSETSTRING (string, s);
1876 string_chars_consed += nbytes;
1877 return string;
1882 /***********************************************************************
1883 Float Allocation
1884 ***********************************************************************/
1886 /* We store float cells inside of float_blocks, allocating a new
1887 float_block with malloc whenever necessary. Float cells reclaimed
1888 by GC are put on a free list to be reallocated before allocating
1889 any new float cells from the latest float_block.
1891 Each float_block is just under 1020 bytes long, since malloc really
1892 allocates in units of powers of two and uses 4 bytes for its own
1893 overhead. */
1895 #define FLOAT_BLOCK_SIZE \
1896 ((1020 - sizeof (struct float_block *)) / sizeof (struct Lisp_Float))
1898 struct float_block
1900 struct float_block *next;
1901 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
1904 /* Current float_block. */
1906 struct float_block *float_block;
1908 /* Index of first unused Lisp_Float in the current float_block. */
1910 int float_block_index;
1912 /* Total number of float blocks now in use. */
1914 int n_float_blocks;
1916 /* Free-list of Lisp_Floats. */
1918 struct Lisp_Float *float_free_list;
1921 /* Initialize float allocation. */
1923 void
1924 init_float ()
1926 float_block = (struct float_block *) lisp_malloc (sizeof *float_block,
1927 MEM_TYPE_FLOAT);
1928 float_block->next = 0;
1929 bzero ((char *) float_block->floats, sizeof float_block->floats);
1930 float_block_index = 0;
1931 float_free_list = 0;
1932 n_float_blocks = 1;
1936 /* Explicitly free a float cell by putting it on the free-list. */
1938 void
1939 free_float (ptr)
1940 struct Lisp_Float *ptr;
1942 *(struct Lisp_Float **)&ptr->data = float_free_list;
1943 #if GC_MARK_STACK
1944 ptr->type = Vdead;
1945 #endif
1946 float_free_list = ptr;
1950 /* Return a new float object with value FLOAT_VALUE. */
1952 Lisp_Object
1953 make_float (float_value)
1954 double float_value;
1956 register Lisp_Object val;
1958 if (float_free_list)
1960 /* We use the data field for chaining the free list
1961 so that we won't use the same field that has the mark bit. */
1962 XSETFLOAT (val, float_free_list);
1963 float_free_list = *(struct Lisp_Float **)&float_free_list->data;
1965 else
1967 if (float_block_index == FLOAT_BLOCK_SIZE)
1969 register struct float_block *new;
1971 new = (struct float_block *) lisp_malloc (sizeof *new,
1972 MEM_TYPE_FLOAT);
1973 VALIDATE_LISP_STORAGE (new, sizeof *new);
1974 new->next = float_block;
1975 float_block = new;
1976 float_block_index = 0;
1977 n_float_blocks++;
1979 XSETFLOAT (val, &float_block->floats[float_block_index++]);
1982 XFLOAT_DATA (val) = float_value;
1983 XSETFASTINT (XFLOAT (val)->type, 0); /* bug chasing -wsr */
1984 consing_since_gc += sizeof (struct Lisp_Float);
1985 floats_consed++;
1986 return val;
1991 /***********************************************************************
1992 Cons Allocation
1993 ***********************************************************************/
1995 /* We store cons cells inside of cons_blocks, allocating a new
1996 cons_block with malloc whenever necessary. Cons cells reclaimed by
1997 GC are put on a free list to be reallocated before allocating
1998 any new cons cells from the latest cons_block.
2000 Each cons_block is just under 1020 bytes long,
2001 since malloc really allocates in units of powers of two
2002 and uses 4 bytes for its own overhead. */
2004 #define CONS_BLOCK_SIZE \
2005 ((1020 - sizeof (struct cons_block *)) / sizeof (struct Lisp_Cons))
2007 struct cons_block
2009 struct cons_block *next;
2010 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2013 /* Current cons_block. */
2015 struct cons_block *cons_block;
2017 /* Index of first unused Lisp_Cons in the current block. */
2019 int cons_block_index;
2021 /* Free-list of Lisp_Cons structures. */
2023 struct Lisp_Cons *cons_free_list;
2025 /* Total number of cons blocks now in use. */
2027 int n_cons_blocks;
2030 /* Initialize cons allocation. */
2032 void
2033 init_cons ()
2035 cons_block = (struct cons_block *) lisp_malloc (sizeof *cons_block,
2036 MEM_TYPE_CONS);
2037 cons_block->next = 0;
2038 bzero ((char *) cons_block->conses, sizeof cons_block->conses);
2039 cons_block_index = 0;
2040 cons_free_list = 0;
2041 n_cons_blocks = 1;
2045 /* Explicitly free a cons cell by putting it on the free-list. */
2047 void
2048 free_cons (ptr)
2049 struct Lisp_Cons *ptr;
2051 *(struct Lisp_Cons **)&ptr->cdr = cons_free_list;
2052 #if GC_MARK_STACK
2053 ptr->car = Vdead;
2054 #endif
2055 cons_free_list = ptr;
2059 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2060 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2061 (car, cdr)
2062 Lisp_Object car, cdr;
2064 register Lisp_Object val;
2066 if (cons_free_list)
2068 /* We use the cdr for chaining the free list
2069 so that we won't use the same field that has the mark bit. */
2070 XSETCONS (val, cons_free_list);
2071 cons_free_list = *(struct Lisp_Cons **)&cons_free_list->cdr;
2073 else
2075 if (cons_block_index == CONS_BLOCK_SIZE)
2077 register struct cons_block *new;
2078 new = (struct cons_block *) lisp_malloc (sizeof *new,
2079 MEM_TYPE_CONS);
2080 VALIDATE_LISP_STORAGE (new, sizeof *new);
2081 new->next = cons_block;
2082 cons_block = new;
2083 cons_block_index = 0;
2084 n_cons_blocks++;
2086 XSETCONS (val, &cons_block->conses[cons_block_index++]);
2089 XSETCAR (val, car);
2090 XSETCDR (val, cdr);
2091 consing_since_gc += sizeof (struct Lisp_Cons);
2092 cons_cells_consed++;
2093 return val;
2097 /* Make a list of 2, 3, 4 or 5 specified objects. */
2099 Lisp_Object
2100 list2 (arg1, arg2)
2101 Lisp_Object arg1, arg2;
2103 return Fcons (arg1, Fcons (arg2, Qnil));
2107 Lisp_Object
2108 list3 (arg1, arg2, arg3)
2109 Lisp_Object arg1, arg2, arg3;
2111 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2115 Lisp_Object
2116 list4 (arg1, arg2, arg3, arg4)
2117 Lisp_Object arg1, arg2, arg3, arg4;
2119 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2123 Lisp_Object
2124 list5 (arg1, arg2, arg3, arg4, arg5)
2125 Lisp_Object arg1, arg2, arg3, arg4, arg5;
2127 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2128 Fcons (arg5, Qnil)))));
2132 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2133 doc: /* Return a newly created list with specified arguments as elements.
2134 Any number of arguments, even zero arguments, are allowed.
2135 usage: (list &rest OBJECTS) */)
2136 (nargs, args)
2137 int nargs;
2138 register Lisp_Object *args;
2140 register Lisp_Object val;
2141 val = Qnil;
2143 while (nargs > 0)
2145 nargs--;
2146 val = Fcons (args[nargs], val);
2148 return val;
2152 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2153 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2154 (length, init)
2155 register Lisp_Object length, init;
2157 register Lisp_Object val;
2158 register int size;
2160 CHECK_NATNUM (length);
2161 size = XFASTINT (length);
2163 val = Qnil;
2164 while (size > 0)
2166 val = Fcons (init, val);
2167 --size;
2169 if (size > 0)
2171 val = Fcons (init, val);
2172 --size;
2174 if (size > 0)
2176 val = Fcons (init, val);
2177 --size;
2179 if (size > 0)
2181 val = Fcons (init, val);
2182 --size;
2184 if (size > 0)
2186 val = Fcons (init, val);
2187 --size;
2193 QUIT;
2196 return val;
2201 /***********************************************************************
2202 Vector Allocation
2203 ***********************************************************************/
2205 /* Singly-linked list of all vectors. */
2207 struct Lisp_Vector *all_vectors;
2209 /* Total number of vector-like objects now in use. */
2211 int n_vectors;
2214 /* Value is a pointer to a newly allocated Lisp_Vector structure
2215 with room for LEN Lisp_Objects. */
2217 static struct Lisp_Vector *
2218 allocate_vectorlike (len, type)
2219 EMACS_INT len;
2220 enum mem_type type;
2222 struct Lisp_Vector *p;
2223 size_t nbytes;
2225 #ifdef DOUG_LEA_MALLOC
2226 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2227 because mapped region contents are not preserved in
2228 a dumped Emacs. */
2229 mallopt (M_MMAP_MAX, 0);
2230 #endif
2232 nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
2233 p = (struct Lisp_Vector *) lisp_malloc (nbytes, type);
2235 #ifdef DOUG_LEA_MALLOC
2236 /* Back to a reasonable maximum of mmap'ed areas. */
2237 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2238 #endif
2240 VALIDATE_LISP_STORAGE (p, 0);
2241 consing_since_gc += nbytes;
2242 vector_cells_consed += len;
2244 p->next = all_vectors;
2245 all_vectors = p;
2246 ++n_vectors;
2247 return p;
2251 /* Allocate a vector with NSLOTS slots. */
2253 struct Lisp_Vector *
2254 allocate_vector (nslots)
2255 EMACS_INT nslots;
2257 struct Lisp_Vector *v = allocate_vectorlike (nslots, MEM_TYPE_VECTOR);
2258 v->size = nslots;
2259 return v;
2263 /* Allocate other vector-like structures. */
2265 struct Lisp_Hash_Table *
2266 allocate_hash_table ()
2268 EMACS_INT len = VECSIZE (struct Lisp_Hash_Table);
2269 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_HASH_TABLE);
2270 EMACS_INT i;
2272 v->size = len;
2273 for (i = 0; i < len; ++i)
2274 v->contents[i] = Qnil;
2276 return (struct Lisp_Hash_Table *) v;
2280 struct window *
2281 allocate_window ()
2283 EMACS_INT len = VECSIZE (struct window);
2284 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_WINDOW);
2285 EMACS_INT i;
2287 for (i = 0; i < len; ++i)
2288 v->contents[i] = Qnil;
2289 v->size = len;
2291 return (struct window *) v;
2295 struct frame *
2296 allocate_frame ()
2298 EMACS_INT len = VECSIZE (struct frame);
2299 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_FRAME);
2300 EMACS_INT i;
2302 for (i = 0; i < len; ++i)
2303 v->contents[i] = make_number (0);
2304 v->size = len;
2305 return (struct frame *) v;
2309 struct Lisp_Process *
2310 allocate_process ()
2312 EMACS_INT len = VECSIZE (struct Lisp_Process);
2313 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_PROCESS);
2314 EMACS_INT i;
2316 for (i = 0; i < len; ++i)
2317 v->contents[i] = Qnil;
2318 v->size = len;
2320 return (struct Lisp_Process *) v;
2324 struct Lisp_Vector *
2325 allocate_other_vector (len)
2326 EMACS_INT len;
2328 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_VECTOR);
2329 EMACS_INT i;
2331 for (i = 0; i < len; ++i)
2332 v->contents[i] = Qnil;
2333 v->size = len;
2335 return v;
2339 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
2340 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
2341 See also the function `vector'. */)
2342 (length, init)
2343 register Lisp_Object length, init;
2345 Lisp_Object vector;
2346 register EMACS_INT sizei;
2347 register int index;
2348 register struct Lisp_Vector *p;
2350 CHECK_NATNUM (length);
2351 sizei = XFASTINT (length);
2353 p = allocate_vector (sizei);
2354 for (index = 0; index < sizei; index++)
2355 p->contents[index] = init;
2357 XSETVECTOR (vector, p);
2358 return vector;
2362 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
2363 doc: /* Return a newly created vector with specified arguments as elements.
2364 Any number of arguments, even zero arguments, are allowed.
2365 usage: (vector &rest OBJECTS) */)
2366 (nargs, args)
2367 register int nargs;
2368 Lisp_Object *args;
2370 register Lisp_Object len, val;
2371 register int index;
2372 register struct Lisp_Vector *p;
2374 XSETFASTINT (len, nargs);
2375 val = Fmake_vector (len, Qnil);
2376 p = XVECTOR (val);
2377 for (index = 0; index < nargs; index++)
2378 p->contents[index] = args[index];
2379 return val;
2383 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
2384 doc: /* Create a byte-code object with specified arguments as elements.
2385 The arguments should be the arglist, bytecode-string, constant vector,
2386 stack size, (optional) doc string, and (optional) interactive spec.
2387 The first four arguments are required; at most six have any
2388 significance.
2389 usage: (make-byte-code &rest ELEMENTS) */)
2390 (nargs, args)
2391 register int nargs;
2392 Lisp_Object *args;
2394 register Lisp_Object len, val;
2395 register int index;
2396 register struct Lisp_Vector *p;
2398 XSETFASTINT (len, nargs);
2399 if (!NILP (Vpurify_flag))
2400 val = make_pure_vector ((EMACS_INT) nargs);
2401 else
2402 val = Fmake_vector (len, Qnil);
2404 if (STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
2405 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
2406 earlier because they produced a raw 8-bit string for byte-code
2407 and now such a byte-code string is loaded as multibyte while
2408 raw 8-bit characters converted to multibyte form. Thus, now we
2409 must convert them back to the original unibyte form. */
2410 args[1] = Fstring_as_unibyte (args[1]);
2412 p = XVECTOR (val);
2413 for (index = 0; index < nargs; index++)
2415 if (!NILP (Vpurify_flag))
2416 args[index] = Fpurecopy (args[index]);
2417 p->contents[index] = args[index];
2419 XSETCOMPILED (val, p);
2420 return val;
2425 /***********************************************************************
2426 Symbol Allocation
2427 ***********************************************************************/
2429 /* Each symbol_block is just under 1020 bytes long, since malloc
2430 really allocates in units of powers of two and uses 4 bytes for its
2431 own overhead. */
2433 #define SYMBOL_BLOCK_SIZE \
2434 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
2436 struct symbol_block
2438 struct symbol_block *next;
2439 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
2442 /* Current symbol block and index of first unused Lisp_Symbol
2443 structure in it. */
2445 struct symbol_block *symbol_block;
2446 int symbol_block_index;
2448 /* List of free symbols. */
2450 struct Lisp_Symbol *symbol_free_list;
2452 /* Total number of symbol blocks now in use. */
2454 int n_symbol_blocks;
2457 /* Initialize symbol allocation. */
2459 void
2460 init_symbol ()
2462 symbol_block = (struct symbol_block *) lisp_malloc (sizeof *symbol_block,
2463 MEM_TYPE_SYMBOL);
2464 symbol_block->next = 0;
2465 bzero ((char *) symbol_block->symbols, sizeof symbol_block->symbols);
2466 symbol_block_index = 0;
2467 symbol_free_list = 0;
2468 n_symbol_blocks = 1;
2472 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
2473 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
2474 Its value and function definition are void, and its property list is nil. */)
2475 (name)
2476 Lisp_Object name;
2478 register Lisp_Object val;
2479 register struct Lisp_Symbol *p;
2481 CHECK_STRING (name);
2483 if (symbol_free_list)
2485 XSETSYMBOL (val, symbol_free_list);
2486 symbol_free_list = *(struct Lisp_Symbol **)&symbol_free_list->value;
2488 else
2490 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
2492 struct symbol_block *new;
2493 new = (struct symbol_block *) lisp_malloc (sizeof *new,
2494 MEM_TYPE_SYMBOL);
2495 VALIDATE_LISP_STORAGE (new, sizeof *new);
2496 new->next = symbol_block;
2497 symbol_block = new;
2498 symbol_block_index = 0;
2499 n_symbol_blocks++;
2501 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index++]);
2504 p = XSYMBOL (val);
2505 p->name = XSTRING (name);
2506 p->plist = Qnil;
2507 p->value = Qunbound;
2508 p->function = Qunbound;
2509 p->next = NULL;
2510 p->interned = SYMBOL_UNINTERNED;
2511 p->constant = 0;
2512 p->indirect_variable = 0;
2513 consing_since_gc += sizeof (struct Lisp_Symbol);
2514 symbols_consed++;
2515 return val;
2520 /***********************************************************************
2521 Marker (Misc) Allocation
2522 ***********************************************************************/
2524 /* Allocation of markers and other objects that share that structure.
2525 Works like allocation of conses. */
2527 #define MARKER_BLOCK_SIZE \
2528 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
2530 struct marker_block
2532 struct marker_block *next;
2533 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
2536 struct marker_block *marker_block;
2537 int marker_block_index;
2539 union Lisp_Misc *marker_free_list;
2541 /* Total number of marker blocks now in use. */
2543 int n_marker_blocks;
2545 void
2546 init_marker ()
2548 marker_block = (struct marker_block *) lisp_malloc (sizeof *marker_block,
2549 MEM_TYPE_MISC);
2550 marker_block->next = 0;
2551 bzero ((char *) marker_block->markers, sizeof marker_block->markers);
2552 marker_block_index = 0;
2553 marker_free_list = 0;
2554 n_marker_blocks = 1;
2557 /* Return a newly allocated Lisp_Misc object, with no substructure. */
2559 Lisp_Object
2560 allocate_misc ()
2562 Lisp_Object val;
2564 if (marker_free_list)
2566 XSETMISC (val, marker_free_list);
2567 marker_free_list = marker_free_list->u_free.chain;
2569 else
2571 if (marker_block_index == MARKER_BLOCK_SIZE)
2573 struct marker_block *new;
2574 new = (struct marker_block *) lisp_malloc (sizeof *new,
2575 MEM_TYPE_MISC);
2576 VALIDATE_LISP_STORAGE (new, sizeof *new);
2577 new->next = marker_block;
2578 marker_block = new;
2579 marker_block_index = 0;
2580 n_marker_blocks++;
2582 XSETMISC (val, &marker_block->markers[marker_block_index++]);
2585 consing_since_gc += sizeof (union Lisp_Misc);
2586 misc_objects_consed++;
2587 return val;
2590 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
2591 doc: /* Return a newly allocated marker which does not point at any place. */)
2594 register Lisp_Object val;
2595 register struct Lisp_Marker *p;
2597 val = allocate_misc ();
2598 XMISCTYPE (val) = Lisp_Misc_Marker;
2599 p = XMARKER (val);
2600 p->buffer = 0;
2601 p->bytepos = 0;
2602 p->charpos = 0;
2603 p->chain = Qnil;
2604 p->insertion_type = 0;
2605 return val;
2608 /* Put MARKER back on the free list after using it temporarily. */
2610 void
2611 free_marker (marker)
2612 Lisp_Object marker;
2614 unchain_marker (marker);
2616 XMISC (marker)->u_marker.type = Lisp_Misc_Free;
2617 XMISC (marker)->u_free.chain = marker_free_list;
2618 marker_free_list = XMISC (marker);
2620 total_free_markers++;
2624 /* Return a newly created vector or string with specified arguments as
2625 elements. If all the arguments are characters that can fit
2626 in a string of events, make a string; otherwise, make a vector.
2628 Any number of arguments, even zero arguments, are allowed. */
2630 Lisp_Object
2631 make_event_array (nargs, args)
2632 register int nargs;
2633 Lisp_Object *args;
2635 int i;
2637 for (i = 0; i < nargs; i++)
2638 /* The things that fit in a string
2639 are characters that are in 0...127,
2640 after discarding the meta bit and all the bits above it. */
2641 if (!INTEGERP (args[i])
2642 || (XUINT (args[i]) & ~(-CHAR_META)) >= 0200)
2643 return Fvector (nargs, args);
2645 /* Since the loop exited, we know that all the things in it are
2646 characters, so we can make a string. */
2648 Lisp_Object result;
2650 result = Fmake_string (make_number (nargs), make_number (0));
2651 for (i = 0; i < nargs; i++)
2653 XSTRING (result)->data[i] = XINT (args[i]);
2654 /* Move the meta bit to the right place for a string char. */
2655 if (XINT (args[i]) & CHAR_META)
2656 XSTRING (result)->data[i] |= 0x80;
2659 return result;
2665 /************************************************************************
2666 C Stack Marking
2667 ************************************************************************/
2669 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
2671 /* Conservative C stack marking requires a method to identify possibly
2672 live Lisp objects given a pointer value. We do this by keeping
2673 track of blocks of Lisp data that are allocated in a red-black tree
2674 (see also the comment of mem_node which is the type of nodes in
2675 that tree). Function lisp_malloc adds information for an allocated
2676 block to the red-black tree with calls to mem_insert, and function
2677 lisp_free removes it with mem_delete. Functions live_string_p etc
2678 call mem_find to lookup information about a given pointer in the
2679 tree, and use that to determine if the pointer points to a Lisp
2680 object or not. */
2682 /* Initialize this part of alloc.c. */
2684 static void
2685 mem_init ()
2687 mem_z.left = mem_z.right = MEM_NIL;
2688 mem_z.parent = NULL;
2689 mem_z.color = MEM_BLACK;
2690 mem_z.start = mem_z.end = NULL;
2691 mem_root = MEM_NIL;
2695 /* Value is a pointer to the mem_node containing START. Value is
2696 MEM_NIL if there is no node in the tree containing START. */
2698 static INLINE struct mem_node *
2699 mem_find (start)
2700 void *start;
2702 struct mem_node *p;
2704 if (start < min_heap_address || start > max_heap_address)
2705 return MEM_NIL;
2707 /* Make the search always successful to speed up the loop below. */
2708 mem_z.start = start;
2709 mem_z.end = (char *) start + 1;
2711 p = mem_root;
2712 while (start < p->start || start >= p->end)
2713 p = start < p->start ? p->left : p->right;
2714 return p;
2718 /* Insert a new node into the tree for a block of memory with start
2719 address START, end address END, and type TYPE. Value is a
2720 pointer to the node that was inserted. */
2722 static struct mem_node *
2723 mem_insert (start, end, type)
2724 void *start, *end;
2725 enum mem_type type;
2727 struct mem_node *c, *parent, *x;
2729 if (start < min_heap_address)
2730 min_heap_address = start;
2731 if (end > max_heap_address)
2732 max_heap_address = end;
2734 /* See where in the tree a node for START belongs. In this
2735 particular application, it shouldn't happen that a node is already
2736 present. For debugging purposes, let's check that. */
2737 c = mem_root;
2738 parent = NULL;
2740 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
2742 while (c != MEM_NIL)
2744 if (start >= c->start && start < c->end)
2745 abort ();
2746 parent = c;
2747 c = start < c->start ? c->left : c->right;
2750 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2752 while (c != MEM_NIL)
2754 parent = c;
2755 c = start < c->start ? c->left : c->right;
2758 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2760 /* Create a new node. */
2761 #ifdef GC_MALLOC_CHECK
2762 x = (struct mem_node *) _malloc_internal (sizeof *x);
2763 if (x == NULL)
2764 abort ();
2765 #else
2766 x = (struct mem_node *) xmalloc (sizeof *x);
2767 #endif
2768 x->start = start;
2769 x->end = end;
2770 x->type = type;
2771 x->parent = parent;
2772 x->left = x->right = MEM_NIL;
2773 x->color = MEM_RED;
2775 /* Insert it as child of PARENT or install it as root. */
2776 if (parent)
2778 if (start < parent->start)
2779 parent->left = x;
2780 else
2781 parent->right = x;
2783 else
2784 mem_root = x;
2786 /* Re-establish red-black tree properties. */
2787 mem_insert_fixup (x);
2789 return x;
2793 /* Re-establish the red-black properties of the tree, and thereby
2794 balance the tree, after node X has been inserted; X is always red. */
2796 static void
2797 mem_insert_fixup (x)
2798 struct mem_node *x;
2800 while (x != mem_root && x->parent->color == MEM_RED)
2802 /* X is red and its parent is red. This is a violation of
2803 red-black tree property #3. */
2805 if (x->parent == x->parent->parent->left)
2807 /* We're on the left side of our grandparent, and Y is our
2808 "uncle". */
2809 struct mem_node *y = x->parent->parent->right;
2811 if (y->color == MEM_RED)
2813 /* Uncle and parent are red but should be black because
2814 X is red. Change the colors accordingly and proceed
2815 with the grandparent. */
2816 x->parent->color = MEM_BLACK;
2817 y->color = MEM_BLACK;
2818 x->parent->parent->color = MEM_RED;
2819 x = x->parent->parent;
2821 else
2823 /* Parent and uncle have different colors; parent is
2824 red, uncle is black. */
2825 if (x == x->parent->right)
2827 x = x->parent;
2828 mem_rotate_left (x);
2831 x->parent->color = MEM_BLACK;
2832 x->parent->parent->color = MEM_RED;
2833 mem_rotate_right (x->parent->parent);
2836 else
2838 /* This is the symmetrical case of above. */
2839 struct mem_node *y = x->parent->parent->left;
2841 if (y->color == MEM_RED)
2843 x->parent->color = MEM_BLACK;
2844 y->color = MEM_BLACK;
2845 x->parent->parent->color = MEM_RED;
2846 x = x->parent->parent;
2848 else
2850 if (x == x->parent->left)
2852 x = x->parent;
2853 mem_rotate_right (x);
2856 x->parent->color = MEM_BLACK;
2857 x->parent->parent->color = MEM_RED;
2858 mem_rotate_left (x->parent->parent);
2863 /* The root may have been changed to red due to the algorithm. Set
2864 it to black so that property #5 is satisfied. */
2865 mem_root->color = MEM_BLACK;
2869 /* (x) (y)
2870 / \ / \
2871 a (y) ===> (x) c
2872 / \ / \
2873 b c a b */
2875 static void
2876 mem_rotate_left (x)
2877 struct mem_node *x;
2879 struct mem_node *y;
2881 /* Turn y's left sub-tree into x's right sub-tree. */
2882 y = x->right;
2883 x->right = y->left;
2884 if (y->left != MEM_NIL)
2885 y->left->parent = x;
2887 /* Y's parent was x's parent. */
2888 if (y != MEM_NIL)
2889 y->parent = x->parent;
2891 /* Get the parent to point to y instead of x. */
2892 if (x->parent)
2894 if (x == x->parent->left)
2895 x->parent->left = y;
2896 else
2897 x->parent->right = y;
2899 else
2900 mem_root = y;
2902 /* Put x on y's left. */
2903 y->left = x;
2904 if (x != MEM_NIL)
2905 x->parent = y;
2909 /* (x) (Y)
2910 / \ / \
2911 (y) c ===> a (x)
2912 / \ / \
2913 a b b c */
2915 static void
2916 mem_rotate_right (x)
2917 struct mem_node *x;
2919 struct mem_node *y = x->left;
2921 x->left = y->right;
2922 if (y->right != MEM_NIL)
2923 y->right->parent = x;
2925 if (y != MEM_NIL)
2926 y->parent = x->parent;
2927 if (x->parent)
2929 if (x == x->parent->right)
2930 x->parent->right = y;
2931 else
2932 x->parent->left = y;
2934 else
2935 mem_root = y;
2937 y->right = x;
2938 if (x != MEM_NIL)
2939 x->parent = y;
2943 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
2945 static void
2946 mem_delete (z)
2947 struct mem_node *z;
2949 struct mem_node *x, *y;
2951 if (!z || z == MEM_NIL)
2952 return;
2954 if (z->left == MEM_NIL || z->right == MEM_NIL)
2955 y = z;
2956 else
2958 y = z->right;
2959 while (y->left != MEM_NIL)
2960 y = y->left;
2963 if (y->left != MEM_NIL)
2964 x = y->left;
2965 else
2966 x = y->right;
2968 x->parent = y->parent;
2969 if (y->parent)
2971 if (y == y->parent->left)
2972 y->parent->left = x;
2973 else
2974 y->parent->right = x;
2976 else
2977 mem_root = x;
2979 if (y != z)
2981 z->start = y->start;
2982 z->end = y->end;
2983 z->type = y->type;
2986 if (y->color == MEM_BLACK)
2987 mem_delete_fixup (x);
2989 #ifdef GC_MALLOC_CHECK
2990 _free_internal (y);
2991 #else
2992 xfree (y);
2993 #endif
2997 /* Re-establish the red-black properties of the tree, after a
2998 deletion. */
3000 static void
3001 mem_delete_fixup (x)
3002 struct mem_node *x;
3004 while (x != mem_root && x->color == MEM_BLACK)
3006 if (x == x->parent->left)
3008 struct mem_node *w = x->parent->right;
3010 if (w->color == MEM_RED)
3012 w->color = MEM_BLACK;
3013 x->parent->color = MEM_RED;
3014 mem_rotate_left (x->parent);
3015 w = x->parent->right;
3018 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
3020 w->color = MEM_RED;
3021 x = x->parent;
3023 else
3025 if (w->right->color == MEM_BLACK)
3027 w->left->color = MEM_BLACK;
3028 w->color = MEM_RED;
3029 mem_rotate_right (w);
3030 w = x->parent->right;
3032 w->color = x->parent->color;
3033 x->parent->color = MEM_BLACK;
3034 w->right->color = MEM_BLACK;
3035 mem_rotate_left (x->parent);
3036 x = mem_root;
3039 else
3041 struct mem_node *w = x->parent->left;
3043 if (w->color == MEM_RED)
3045 w->color = MEM_BLACK;
3046 x->parent->color = MEM_RED;
3047 mem_rotate_right (x->parent);
3048 w = x->parent->left;
3051 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
3053 w->color = MEM_RED;
3054 x = x->parent;
3056 else
3058 if (w->left->color == MEM_BLACK)
3060 w->right->color = MEM_BLACK;
3061 w->color = MEM_RED;
3062 mem_rotate_left (w);
3063 w = x->parent->left;
3066 w->color = x->parent->color;
3067 x->parent->color = MEM_BLACK;
3068 w->left->color = MEM_BLACK;
3069 mem_rotate_right (x->parent);
3070 x = mem_root;
3075 x->color = MEM_BLACK;
3079 /* Value is non-zero if P is a pointer to a live Lisp string on
3080 the heap. M is a pointer to the mem_block for P. */
3082 static INLINE int
3083 live_string_p (m, p)
3084 struct mem_node *m;
3085 void *p;
3087 if (m->type == MEM_TYPE_STRING)
3089 struct string_block *b = (struct string_block *) m->start;
3090 int offset = (char *) p - (char *) &b->strings[0];
3092 /* P must point to the start of a Lisp_String structure, and it
3093 must not be on the free-list. */
3094 return (offset >= 0
3095 && offset % sizeof b->strings[0] == 0
3096 && ((struct Lisp_String *) p)->data != NULL);
3098 else
3099 return 0;
3103 /* Value is non-zero if P is a pointer to a live Lisp cons on
3104 the heap. M is a pointer to the mem_block for P. */
3106 static INLINE int
3107 live_cons_p (m, p)
3108 struct mem_node *m;
3109 void *p;
3111 if (m->type == MEM_TYPE_CONS)
3113 struct cons_block *b = (struct cons_block *) m->start;
3114 int offset = (char *) p - (char *) &b->conses[0];
3116 /* P must point to the start of a Lisp_Cons, not be
3117 one of the unused cells in the current cons block,
3118 and not be on the free-list. */
3119 return (offset >= 0
3120 && offset % sizeof b->conses[0] == 0
3121 && (b != cons_block
3122 || offset / sizeof b->conses[0] < cons_block_index)
3123 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
3125 else
3126 return 0;
3130 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3131 the heap. M is a pointer to the mem_block for P. */
3133 static INLINE int
3134 live_symbol_p (m, p)
3135 struct mem_node *m;
3136 void *p;
3138 if (m->type == MEM_TYPE_SYMBOL)
3140 struct symbol_block *b = (struct symbol_block *) m->start;
3141 int offset = (char *) p - (char *) &b->symbols[0];
3143 /* P must point to the start of a Lisp_Symbol, not be
3144 one of the unused cells in the current symbol block,
3145 and not be on the free-list. */
3146 return (offset >= 0
3147 && offset % sizeof b->symbols[0] == 0
3148 && (b != symbol_block
3149 || offset / sizeof b->symbols[0] < symbol_block_index)
3150 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
3152 else
3153 return 0;
3157 /* Value is non-zero if P is a pointer to a live Lisp float on
3158 the heap. M is a pointer to the mem_block for P. */
3160 static INLINE int
3161 live_float_p (m, p)
3162 struct mem_node *m;
3163 void *p;
3165 if (m->type == MEM_TYPE_FLOAT)
3167 struct float_block *b = (struct float_block *) m->start;
3168 int offset = (char *) p - (char *) &b->floats[0];
3170 /* P must point to the start of a Lisp_Float, not be
3171 one of the unused cells in the current float block,
3172 and not be on the free-list. */
3173 return (offset >= 0
3174 && offset % sizeof b->floats[0] == 0
3175 && (b != float_block
3176 || offset / sizeof b->floats[0] < float_block_index)
3177 && !EQ (((struct Lisp_Float *) p)->type, Vdead));
3179 else
3180 return 0;
3184 /* Value is non-zero if P is a pointer to a live Lisp Misc on
3185 the heap. M is a pointer to the mem_block for P. */
3187 static INLINE int
3188 live_misc_p (m, p)
3189 struct mem_node *m;
3190 void *p;
3192 if (m->type == MEM_TYPE_MISC)
3194 struct marker_block *b = (struct marker_block *) m->start;
3195 int offset = (char *) p - (char *) &b->markers[0];
3197 /* P must point to the start of a Lisp_Misc, not be
3198 one of the unused cells in the current misc block,
3199 and not be on the free-list. */
3200 return (offset >= 0
3201 && offset % sizeof b->markers[0] == 0
3202 && (b != marker_block
3203 || offset / sizeof b->markers[0] < marker_block_index)
3204 && ((union Lisp_Misc *) p)->u_marker.type != Lisp_Misc_Free);
3206 else
3207 return 0;
3211 /* Value is non-zero if P is a pointer to a live vector-like object.
3212 M is a pointer to the mem_block for P. */
3214 static INLINE int
3215 live_vector_p (m, p)
3216 struct mem_node *m;
3217 void *p;
3219 return (p == m->start
3220 && m->type >= MEM_TYPE_VECTOR
3221 && m->type <= MEM_TYPE_WINDOW);
3225 /* Value is non-zero of P is a pointer to a live buffer. M is a
3226 pointer to the mem_block for P. */
3228 static INLINE int
3229 live_buffer_p (m, p)
3230 struct mem_node *m;
3231 void *p;
3233 /* P must point to the start of the block, and the buffer
3234 must not have been killed. */
3235 return (m->type == MEM_TYPE_BUFFER
3236 && p == m->start
3237 && !NILP (((struct buffer *) p)->name));
3240 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
3242 #if GC_MARK_STACK
3244 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3246 /* Array of objects that are kept alive because the C stack contains
3247 a pattern that looks like a reference to them . */
3249 #define MAX_ZOMBIES 10
3250 static Lisp_Object zombies[MAX_ZOMBIES];
3252 /* Number of zombie objects. */
3254 static int nzombies;
3256 /* Number of garbage collections. */
3258 static int ngcs;
3260 /* Average percentage of zombies per collection. */
3262 static double avg_zombies;
3264 /* Max. number of live and zombie objects. */
3266 static int max_live, max_zombies;
3268 /* Average number of live objects per GC. */
3270 static double avg_live;
3272 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
3273 doc: /* Show information about live and zombie objects. */)
3276 Lisp_Object args[7];
3277 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d");
3278 args[1] = make_number (ngcs);
3279 args[2] = make_float (avg_live);
3280 args[3] = make_float (avg_zombies);
3281 args[4] = make_float (avg_zombies / avg_live / 100);
3282 args[5] = make_number (max_live);
3283 args[6] = make_number (max_zombies);
3284 return Fmessage (7, args);
3287 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3290 /* Mark OBJ if we can prove it's a Lisp_Object. */
3292 static INLINE void
3293 mark_maybe_object (obj)
3294 Lisp_Object obj;
3296 void *po = (void *) XPNTR (obj);
3297 struct mem_node *m = mem_find (po);
3299 if (m != MEM_NIL)
3301 int mark_p = 0;
3303 switch (XGCTYPE (obj))
3305 case Lisp_String:
3306 mark_p = (live_string_p (m, po)
3307 && !STRING_MARKED_P ((struct Lisp_String *) po));
3308 break;
3310 case Lisp_Cons:
3311 mark_p = (live_cons_p (m, po)
3312 && !XMARKBIT (XCONS (obj)->car));
3313 break;
3315 case Lisp_Symbol:
3316 mark_p = (live_symbol_p (m, po)
3317 && !XMARKBIT (XSYMBOL (obj)->plist));
3318 break;
3320 case Lisp_Float:
3321 mark_p = (live_float_p (m, po)
3322 && !XMARKBIT (XFLOAT (obj)->type));
3323 break;
3325 case Lisp_Vectorlike:
3326 /* Note: can't check GC_BUFFERP before we know it's a
3327 buffer because checking that dereferences the pointer
3328 PO which might point anywhere. */
3329 if (live_vector_p (m, po))
3330 mark_p = (!GC_SUBRP (obj)
3331 && !(XVECTOR (obj)->size & ARRAY_MARK_FLAG));
3332 else if (live_buffer_p (m, po))
3333 mark_p = GC_BUFFERP (obj) && !XMARKBIT (XBUFFER (obj)->name);
3334 break;
3336 case Lisp_Misc:
3337 if (live_misc_p (m, po))
3339 switch (XMISCTYPE (obj))
3341 case Lisp_Misc_Marker:
3342 mark_p = !XMARKBIT (XMARKER (obj)->chain);
3343 break;
3345 case Lisp_Misc_Buffer_Local_Value:
3346 case Lisp_Misc_Some_Buffer_Local_Value:
3347 mark_p = !XMARKBIT (XBUFFER_LOCAL_VALUE (obj)->realvalue);
3348 break;
3350 case Lisp_Misc_Overlay:
3351 mark_p = !XMARKBIT (XOVERLAY (obj)->plist);
3352 break;
3355 break;
3357 case Lisp_Int:
3358 case Lisp_Type_Limit:
3359 break;
3362 if (mark_p)
3364 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3365 if (nzombies < MAX_ZOMBIES)
3366 zombies[nzombies] = *p;
3367 ++nzombies;
3368 #endif
3369 mark_object (&obj);
3375 /* If P points to Lisp data, mark that as live if it isn't already
3376 marked. */
3378 static INLINE void
3379 mark_maybe_pointer (p)
3380 void *p;
3382 struct mem_node *m;
3384 /* Quickly rule out some values which can't point to Lisp data. We
3385 assume that Lisp data is aligned on even addresses. */
3386 if ((EMACS_INT) p & 1)
3387 return;
3389 m = mem_find (p);
3390 if (m != MEM_NIL)
3392 Lisp_Object obj = Qnil;
3394 switch (m->type)
3396 case MEM_TYPE_NON_LISP:
3397 /* Nothing to do; not a pointer to Lisp memory. */
3398 break;
3400 case MEM_TYPE_BUFFER:
3401 if (live_buffer_p (m, p)
3402 && !XMARKBIT (((struct buffer *) p)->name))
3403 XSETVECTOR (obj, p);
3404 break;
3406 case MEM_TYPE_CONS:
3407 if (live_cons_p (m, p)
3408 && !XMARKBIT (((struct Lisp_Cons *) p)->car))
3409 XSETCONS (obj, p);
3410 break;
3412 case MEM_TYPE_STRING:
3413 if (live_string_p (m, p)
3414 && !STRING_MARKED_P ((struct Lisp_String *) p))
3415 XSETSTRING (obj, p);
3416 break;
3418 case MEM_TYPE_MISC:
3419 if (live_misc_p (m, p))
3421 Lisp_Object tem;
3422 XSETMISC (tem, p);
3424 switch (XMISCTYPE (tem))
3426 case Lisp_Misc_Marker:
3427 if (!XMARKBIT (XMARKER (tem)->chain))
3428 obj = tem;
3429 break;
3431 case Lisp_Misc_Buffer_Local_Value:
3432 case Lisp_Misc_Some_Buffer_Local_Value:
3433 if (!XMARKBIT (XBUFFER_LOCAL_VALUE (tem)->realvalue))
3434 obj = tem;
3435 break;
3437 case Lisp_Misc_Overlay:
3438 if (!XMARKBIT (XOVERLAY (tem)->plist))
3439 obj = tem;
3440 break;
3443 break;
3445 case MEM_TYPE_SYMBOL:
3446 if (live_symbol_p (m, p)
3447 && !XMARKBIT (((struct Lisp_Symbol *) p)->plist))
3448 XSETSYMBOL (obj, p);
3449 break;
3451 case MEM_TYPE_FLOAT:
3452 if (live_float_p (m, p)
3453 && !XMARKBIT (((struct Lisp_Float *) p)->type))
3454 XSETFLOAT (obj, p);
3455 break;
3457 case MEM_TYPE_VECTOR:
3458 case MEM_TYPE_PROCESS:
3459 case MEM_TYPE_HASH_TABLE:
3460 case MEM_TYPE_FRAME:
3461 case MEM_TYPE_WINDOW:
3462 if (live_vector_p (m, p))
3464 Lisp_Object tem;
3465 XSETVECTOR (tem, p);
3466 if (!GC_SUBRP (tem)
3467 && !(XVECTOR (tem)->size & ARRAY_MARK_FLAG))
3468 obj = tem;
3470 break;
3472 default:
3473 abort ();
3476 if (!GC_NILP (obj))
3477 mark_object (&obj);
3482 /* Mark Lisp objects referenced from the address range START..END. */
3484 static void
3485 mark_memory (start, end)
3486 void *start, *end;
3488 Lisp_Object *p;
3489 void **pp;
3491 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3492 nzombies = 0;
3493 #endif
3495 /* Make START the pointer to the start of the memory region,
3496 if it isn't already. */
3497 if (end < start)
3499 void *tem = start;
3500 start = end;
3501 end = tem;
3504 /* Mark Lisp_Objects. */
3505 for (p = (Lisp_Object *) start; (void *) p < end; ++p)
3506 mark_maybe_object (*p);
3508 /* Mark Lisp data pointed to. This is necessary because, in some
3509 situations, the C compiler optimizes Lisp objects away, so that
3510 only a pointer to them remains. Example:
3512 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
3515 Lisp_Object obj = build_string ("test");
3516 struct Lisp_String *s = XSTRING (obj);
3517 Fgarbage_collect ();
3518 fprintf (stderr, "test `%s'\n", s->data);
3519 return Qnil;
3522 Here, `obj' isn't really used, and the compiler optimizes it
3523 away. The only reference to the life string is through the
3524 pointer `s'. */
3526 for (pp = (void **) start; (void *) pp < end; ++pp)
3527 mark_maybe_pointer (*pp);
3531 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
3533 static int setjmp_tested_p, longjmps_done;
3535 #define SETJMP_WILL_LIKELY_WORK "\
3537 Emacs garbage collector has been changed to use conservative stack\n\
3538 marking. Emacs has determined that the method it uses to do the\n\
3539 marking will likely work on your system, but this isn't sure.\n\
3541 If you are a system-programmer, or can get the help of a local wizard\n\
3542 who is, please take a look at the function mark_stack in alloc.c, and\n\
3543 verify that the methods used are appropriate for your system.\n\
3545 Please mail the result to <emacs-devel@gnu.org>.\n\
3548 #define SETJMP_WILL_NOT_WORK "\
3550 Emacs garbage collector has been changed to use conservative stack\n\
3551 marking. Emacs has determined that the default method it uses to do the\n\
3552 marking will not work on your system. We will need a system-dependent\n\
3553 solution for your system.\n\
3555 Please take a look at the function mark_stack in alloc.c, and\n\
3556 try to find a way to make it work on your system.\n\
3557 Please mail the result to <emacs-devel@gnu.org>.\n\
3561 /* Perform a quick check if it looks like setjmp saves registers in a
3562 jmp_buf. Print a message to stderr saying so. When this test
3563 succeeds, this is _not_ a proof that setjmp is sufficient for
3564 conservative stack marking. Only the sources or a disassembly
3565 can prove that. */
3567 static void
3568 test_setjmp ()
3570 char buf[10];
3571 register int x;
3572 jmp_buf jbuf;
3573 int result = 0;
3575 /* Arrange for X to be put in a register. */
3576 sprintf (buf, "1");
3577 x = strlen (buf);
3578 x = 2 * x - 1;
3580 setjmp (jbuf);
3581 if (longjmps_done == 1)
3583 /* Came here after the longjmp at the end of the function.
3585 If x == 1, the longjmp has restored the register to its
3586 value before the setjmp, and we can hope that setjmp
3587 saves all such registers in the jmp_buf, although that
3588 isn't sure.
3590 For other values of X, either something really strange is
3591 taking place, or the setjmp just didn't save the register. */
3593 if (x == 1)
3594 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
3595 else
3597 fprintf (stderr, SETJMP_WILL_NOT_WORK);
3598 exit (1);
3602 ++longjmps_done;
3603 x = 2;
3604 if (longjmps_done == 1)
3605 longjmp (jbuf, 1);
3608 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
3611 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
3613 /* Abort if anything GCPRO'd doesn't survive the GC. */
3615 static void
3616 check_gcpros ()
3618 struct gcpro *p;
3619 int i;
3621 for (p = gcprolist; p; p = p->next)
3622 for (i = 0; i < p->nvars; ++i)
3623 if (!survives_gc_p (p->var[i]))
3624 abort ();
3627 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3629 static void
3630 dump_zombies ()
3632 int i;
3634 fprintf (stderr, "\nZombies kept alive = %d:\n", nzombies);
3635 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
3637 fprintf (stderr, " %d = ", i);
3638 debug_print (zombies[i]);
3642 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3645 /* Mark live Lisp objects on the C stack.
3647 There are several system-dependent problems to consider when
3648 porting this to new architectures:
3650 Processor Registers
3652 We have to mark Lisp objects in CPU registers that can hold local
3653 variables or are used to pass parameters.
3655 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
3656 something that either saves relevant registers on the stack, or
3657 calls mark_maybe_object passing it each register's contents.
3659 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
3660 implementation assumes that calling setjmp saves registers we need
3661 to see in a jmp_buf which itself lies on the stack. This doesn't
3662 have to be true! It must be verified for each system, possibly
3663 by taking a look at the source code of setjmp.
3665 Stack Layout
3667 Architectures differ in the way their processor stack is organized.
3668 For example, the stack might look like this
3670 +----------------+
3671 | Lisp_Object | size = 4
3672 +----------------+
3673 | something else | size = 2
3674 +----------------+
3675 | Lisp_Object | size = 4
3676 +----------------+
3677 | ... |
3679 In such a case, not every Lisp_Object will be aligned equally. To
3680 find all Lisp_Object on the stack it won't be sufficient to walk
3681 the stack in steps of 4 bytes. Instead, two passes will be
3682 necessary, one starting at the start of the stack, and a second
3683 pass starting at the start of the stack + 2. Likewise, if the
3684 minimal alignment of Lisp_Objects on the stack is 1, four passes
3685 would be necessary, each one starting with one byte more offset
3686 from the stack start.
3688 The current code assumes by default that Lisp_Objects are aligned
3689 equally on the stack. */
3691 static void
3692 mark_stack ()
3694 int i;
3695 jmp_buf j;
3696 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
3697 void *end;
3699 /* This trick flushes the register windows so that all the state of
3700 the process is contained in the stack. */
3701 #ifdef sparc
3702 asm ("ta 3");
3703 #endif
3705 /* Save registers that we need to see on the stack. We need to see
3706 registers used to hold register variables and registers used to
3707 pass parameters. */
3708 #ifdef GC_SAVE_REGISTERS_ON_STACK
3709 GC_SAVE_REGISTERS_ON_STACK (end);
3710 #else /* not GC_SAVE_REGISTERS_ON_STACK */
3712 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
3713 setjmp will definitely work, test it
3714 and print a message with the result
3715 of the test. */
3716 if (!setjmp_tested_p)
3718 setjmp_tested_p = 1;
3719 test_setjmp ();
3721 #endif /* GC_SETJMP_WORKS */
3723 setjmp (j);
3724 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
3725 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
3727 /* This assumes that the stack is a contiguous region in memory. If
3728 that's not the case, something has to be done here to iterate
3729 over the stack segments. */
3730 #ifndef GC_LISP_OBJECT_ALIGNMENT
3731 #define GC_LISP_OBJECT_ALIGNMENT sizeof (Lisp_Object)
3732 #endif
3733 for (i = 0; i < sizeof (Lisp_Object); i += GC_LISP_OBJECT_ALIGNMENT)
3734 mark_memory ((char *) stack_base + i, end);
3736 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
3737 check_gcpros ();
3738 #endif
3742 #endif /* GC_MARK_STACK != 0 */
3746 /***********************************************************************
3747 Pure Storage Management
3748 ***********************************************************************/
3750 /* Allocate room for SIZE bytes from pure Lisp storage and return a
3751 pointer to it. TYPE is the Lisp type for which the memory is
3752 allocated. TYPE < 0 means it's not used for a Lisp object.
3754 If store_pure_type_info is set and TYPE is >= 0, the type of
3755 the allocated object is recorded in pure_types. */
3757 static POINTER_TYPE *
3758 pure_alloc (size, type)
3759 size_t size;
3760 int type;
3762 size_t nbytes;
3763 POINTER_TYPE *result;
3764 char *beg = purebeg;
3766 /* Give Lisp_Floats an extra alignment. */
3767 if (type == Lisp_Float)
3769 size_t alignment;
3770 #if defined __GNUC__ && __GNUC__ >= 2
3771 alignment = __alignof (struct Lisp_Float);
3772 #else
3773 alignment = sizeof (struct Lisp_Float);
3774 #endif
3775 pure_bytes_used = ALIGN (pure_bytes_used, alignment);
3778 nbytes = ALIGN (size, sizeof (EMACS_INT));
3780 if (pure_bytes_used + nbytes > pure_size)
3782 /* Don't allocate a large amount here,
3783 because it might get mmap'd and then its address
3784 might not be usable. */
3785 beg = purebeg = (char *) xmalloc (10000);
3786 pure_size = 10000;
3787 pure_bytes_used_before_overflow += pure_bytes_used;
3788 pure_bytes_used = 0;
3791 result = (POINTER_TYPE *) (beg + pure_bytes_used);
3792 pure_bytes_used += nbytes;
3793 return result;
3797 /* Signal an error if PURESIZE is too small. */
3799 void
3800 check_pure_size ()
3802 if (pure_bytes_used_before_overflow)
3803 error ("Pure Lisp storage overflow (approx. %d bytes needed)",
3804 (int) (pure_bytes_used + pure_bytes_used_before_overflow));
3808 /* Return a string allocated in pure space. DATA is a buffer holding
3809 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
3810 non-zero means make the result string multibyte.
3812 Must get an error if pure storage is full, since if it cannot hold
3813 a large string it may be able to hold conses that point to that
3814 string; then the string is not protected from gc. */
3816 Lisp_Object
3817 make_pure_string (data, nchars, nbytes, multibyte)
3818 char *data;
3819 int nchars, nbytes;
3820 int multibyte;
3822 Lisp_Object string;
3823 struct Lisp_String *s;
3825 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
3826 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
3827 s->size = nchars;
3828 s->size_byte = multibyte ? nbytes : -1;
3829 bcopy (data, s->data, nbytes);
3830 s->data[nbytes] = '\0';
3831 s->intervals = NULL_INTERVAL;
3832 XSETSTRING (string, s);
3833 return string;
3837 /* Return a cons allocated from pure space. Give it pure copies
3838 of CAR as car and CDR as cdr. */
3840 Lisp_Object
3841 pure_cons (car, cdr)
3842 Lisp_Object car, cdr;
3844 register Lisp_Object new;
3845 struct Lisp_Cons *p;
3847 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
3848 XSETCONS (new, p);
3849 XSETCAR (new, Fpurecopy (car));
3850 XSETCDR (new, Fpurecopy (cdr));
3851 return new;
3855 /* Value is a float object with value NUM allocated from pure space. */
3857 Lisp_Object
3858 make_pure_float (num)
3859 double num;
3861 register Lisp_Object new;
3862 struct Lisp_Float *p;
3864 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
3865 XSETFLOAT (new, p);
3866 XFLOAT_DATA (new) = num;
3867 return new;
3871 /* Return a vector with room for LEN Lisp_Objects allocated from
3872 pure space. */
3874 Lisp_Object
3875 make_pure_vector (len)
3876 EMACS_INT len;
3878 Lisp_Object new;
3879 struct Lisp_Vector *p;
3880 size_t size = sizeof *p + (len - 1) * sizeof (Lisp_Object);
3882 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
3883 XSETVECTOR (new, p);
3884 XVECTOR (new)->size = len;
3885 return new;
3889 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
3890 doc: /* Make a copy of OBJECT in pure storage.
3891 Recursively copies contents of vectors and cons cells.
3892 Does not copy symbols. Copies strings without text properties. */)
3893 (obj)
3894 register Lisp_Object obj;
3896 if (NILP (Vpurify_flag))
3897 return obj;
3899 if (PURE_POINTER_P (XPNTR (obj)))
3900 return obj;
3902 if (CONSP (obj))
3903 return pure_cons (XCAR (obj), XCDR (obj));
3904 else if (FLOATP (obj))
3905 return make_pure_float (XFLOAT_DATA (obj));
3906 else if (STRINGP (obj))
3907 return make_pure_string (XSTRING (obj)->data, XSTRING (obj)->size,
3908 STRING_BYTES (XSTRING (obj)),
3909 STRING_MULTIBYTE (obj));
3910 else if (COMPILEDP (obj) || VECTORP (obj))
3912 register struct Lisp_Vector *vec;
3913 register int i, size;
3915 size = XVECTOR (obj)->size;
3916 if (size & PSEUDOVECTOR_FLAG)
3917 size &= PSEUDOVECTOR_SIZE_MASK;
3918 vec = XVECTOR (make_pure_vector ((EMACS_INT) size));
3919 for (i = 0; i < size; i++)
3920 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
3921 if (COMPILEDP (obj))
3922 XSETCOMPILED (obj, vec);
3923 else
3924 XSETVECTOR (obj, vec);
3925 return obj;
3927 else if (MARKERP (obj))
3928 error ("Attempt to copy a marker to pure storage");
3930 return obj;
3935 /***********************************************************************
3936 Protection from GC
3937 ***********************************************************************/
3939 /* Put an entry in staticvec, pointing at the variable with address
3940 VARADDRESS. */
3942 void
3943 staticpro (varaddress)
3944 Lisp_Object *varaddress;
3946 staticvec[staticidx++] = varaddress;
3947 if (staticidx >= NSTATICS)
3948 abort ();
3951 struct catchtag
3953 Lisp_Object tag;
3954 Lisp_Object val;
3955 struct catchtag *next;
3958 struct backtrace
3960 struct backtrace *next;
3961 Lisp_Object *function;
3962 Lisp_Object *args; /* Points to vector of args. */
3963 int nargs; /* Length of vector. */
3964 /* If nargs is UNEVALLED, args points to slot holding list of
3965 unevalled args. */
3966 char evalargs;
3971 /***********************************************************************
3972 Protection from GC
3973 ***********************************************************************/
3975 /* Temporarily prevent garbage collection. */
3978 inhibit_garbage_collection ()
3980 int count = specpdl_ptr - specpdl;
3981 int nbits = min (VALBITS, BITS_PER_INT);
3983 specbind (Qgc_cons_threshold, make_number (((EMACS_INT) 1 << (nbits - 1)) - 1));
3984 return count;
3988 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
3989 doc: /* Reclaim storage for Lisp objects no longer needed.
3990 Returns info on amount of space in use:
3991 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
3992 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
3993 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)
3994 (USED-STRINGS . FREE-STRINGS))
3995 Garbage collection happens automatically if you cons more than
3996 `gc-cons-threshold' bytes of Lisp data since previous garbage collection. */)
3999 register struct gcpro *tail;
4000 register struct specbinding *bind;
4001 struct catchtag *catch;
4002 struct handler *handler;
4003 register struct backtrace *backlist;
4004 char stack_top_variable;
4005 register int i;
4006 int message_p;
4007 Lisp_Object total[8];
4008 int count = BINDING_STACK_SIZE ();
4010 /* Can't GC if pure storage overflowed because we can't determine
4011 if something is a pure object or not. */
4012 if (pure_bytes_used_before_overflow)
4013 return Qnil;
4015 /* In case user calls debug_print during GC,
4016 don't let that cause a recursive GC. */
4017 consing_since_gc = 0;
4019 /* Save what's currently displayed in the echo area. */
4020 message_p = push_message ();
4021 record_unwind_protect (push_message_unwind, Qnil);
4023 /* Save a copy of the contents of the stack, for debugging. */
4024 #if MAX_SAVE_STACK > 0
4025 if (NILP (Vpurify_flag))
4027 i = &stack_top_variable - stack_bottom;
4028 if (i < 0) i = -i;
4029 if (i < MAX_SAVE_STACK)
4031 if (stack_copy == 0)
4032 stack_copy = (char *) xmalloc (stack_copy_size = i);
4033 else if (stack_copy_size < i)
4034 stack_copy = (char *) xrealloc (stack_copy, (stack_copy_size = i));
4035 if (stack_copy)
4037 if ((EMACS_INT) (&stack_top_variable - stack_bottom) > 0)
4038 bcopy (stack_bottom, stack_copy, i);
4039 else
4040 bcopy (&stack_top_variable, stack_copy, i);
4044 #endif /* MAX_SAVE_STACK > 0 */
4046 if (garbage_collection_messages)
4047 message1_nolog ("Garbage collecting...");
4049 BLOCK_INPUT;
4051 shrink_regexp_cache ();
4053 /* Don't keep undo information around forever. */
4055 register struct buffer *nextb = all_buffers;
4057 while (nextb)
4059 /* If a buffer's undo list is Qt, that means that undo is
4060 turned off in that buffer. Calling truncate_undo_list on
4061 Qt tends to return NULL, which effectively turns undo back on.
4062 So don't call truncate_undo_list if undo_list is Qt. */
4063 if (! EQ (nextb->undo_list, Qt))
4064 nextb->undo_list
4065 = truncate_undo_list (nextb->undo_list, undo_limit,
4066 undo_strong_limit);
4068 /* Shrink buffer gaps, but skip indirect and dead buffers. */
4069 if (nextb->base_buffer == 0 && !NILP (nextb->name))
4071 /* If a buffer's gap size is more than 10% of the buffer
4072 size, or larger than 2000 bytes, then shrink it
4073 accordingly. Keep a minimum size of 20 bytes. */
4074 int size = min (2000, max (20, (nextb->text->z_byte / 10)));
4076 if (nextb->text->gap_size > size)
4078 struct buffer *save_current = current_buffer;
4079 current_buffer = nextb;
4080 make_gap (-(nextb->text->gap_size - size));
4081 current_buffer = save_current;
4085 nextb = nextb->next;
4089 gc_in_progress = 1;
4091 /* clear_marks (); */
4093 /* Mark all the special slots that serve as the roots of accessibility.
4095 Usually the special slots to mark are contained in particular structures.
4096 Then we know no slot is marked twice because the structures don't overlap.
4097 In some cases, the structures point to the slots to be marked.
4098 For these, we use MARKBIT to avoid double marking of the slot. */
4100 for (i = 0; i < staticidx; i++)
4101 mark_object (staticvec[i]);
4103 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
4104 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
4105 mark_stack ();
4106 #else
4107 for (tail = gcprolist; tail; tail = tail->next)
4108 for (i = 0; i < tail->nvars; i++)
4109 if (!XMARKBIT (tail->var[i]))
4111 /* Explicit casting prevents compiler warning about
4112 discarding the `volatile' qualifier. */
4113 mark_object ((Lisp_Object *)&tail->var[i]);
4114 XMARK (tail->var[i]);
4116 #endif
4118 mark_byte_stack ();
4119 for (bind = specpdl; bind != specpdl_ptr; bind++)
4121 mark_object (&bind->symbol);
4122 mark_object (&bind->old_value);
4124 for (catch = catchlist; catch; catch = catch->next)
4126 mark_object (&catch->tag);
4127 mark_object (&catch->val);
4129 for (handler = handlerlist; handler; handler = handler->next)
4131 mark_object (&handler->handler);
4132 mark_object (&handler->var);
4134 for (backlist = backtrace_list; backlist; backlist = backlist->next)
4136 if (!XMARKBIT (*backlist->function))
4138 mark_object (backlist->function);
4139 XMARK (*backlist->function);
4141 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
4142 i = 0;
4143 else
4144 i = backlist->nargs - 1;
4145 for (; i >= 0; i--)
4146 if (!XMARKBIT (backlist->args[i]))
4148 mark_object (&backlist->args[i]);
4149 XMARK (backlist->args[i]);
4152 mark_kboards ();
4154 /* Look thru every buffer's undo list
4155 for elements that update markers that were not marked,
4156 and delete them. */
4158 register struct buffer *nextb = all_buffers;
4160 while (nextb)
4162 /* If a buffer's undo list is Qt, that means that undo is
4163 turned off in that buffer. Calling truncate_undo_list on
4164 Qt tends to return NULL, which effectively turns undo back on.
4165 So don't call truncate_undo_list if undo_list is Qt. */
4166 if (! EQ (nextb->undo_list, Qt))
4168 Lisp_Object tail, prev;
4169 tail = nextb->undo_list;
4170 prev = Qnil;
4171 while (CONSP (tail))
4173 if (GC_CONSP (XCAR (tail))
4174 && GC_MARKERP (XCAR (XCAR (tail)))
4175 && ! XMARKBIT (XMARKER (XCAR (XCAR (tail)))->chain))
4177 if (NILP (prev))
4178 nextb->undo_list = tail = XCDR (tail);
4179 else
4181 tail = XCDR (tail);
4182 XSETCDR (prev, tail);
4185 else
4187 prev = tail;
4188 tail = XCDR (tail);
4193 nextb = nextb->next;
4197 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4198 mark_stack ();
4199 #endif
4201 gc_sweep ();
4203 /* Clear the mark bits that we set in certain root slots. */
4205 #if (GC_MARK_STACK == GC_USE_GCPROS_AS_BEFORE \
4206 || GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES)
4207 for (tail = gcprolist; tail; tail = tail->next)
4208 for (i = 0; i < tail->nvars; i++)
4209 XUNMARK (tail->var[i]);
4210 #endif
4212 unmark_byte_stack ();
4213 for (backlist = backtrace_list; backlist; backlist = backlist->next)
4215 XUNMARK (*backlist->function);
4216 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
4217 i = 0;
4218 else
4219 i = backlist->nargs - 1;
4220 for (; i >= 0; i--)
4221 XUNMARK (backlist->args[i]);
4223 XUNMARK (buffer_defaults.name);
4224 XUNMARK (buffer_local_symbols.name);
4226 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
4227 dump_zombies ();
4228 #endif
4230 UNBLOCK_INPUT;
4232 /* clear_marks (); */
4233 gc_in_progress = 0;
4235 consing_since_gc = 0;
4236 if (gc_cons_threshold < 10000)
4237 gc_cons_threshold = 10000;
4239 if (garbage_collection_messages)
4241 if (message_p || minibuf_level > 0)
4242 restore_message ();
4243 else
4244 message1_nolog ("Garbage collecting...done");
4247 unbind_to (count, Qnil);
4249 total[0] = Fcons (make_number (total_conses),
4250 make_number (total_free_conses));
4251 total[1] = Fcons (make_number (total_symbols),
4252 make_number (total_free_symbols));
4253 total[2] = Fcons (make_number (total_markers),
4254 make_number (total_free_markers));
4255 total[3] = make_number (total_string_size);
4256 total[4] = make_number (total_vector_size);
4257 total[5] = Fcons (make_number (total_floats),
4258 make_number (total_free_floats));
4259 total[6] = Fcons (make_number (total_intervals),
4260 make_number (total_free_intervals));
4261 total[7] = Fcons (make_number (total_strings),
4262 make_number (total_free_strings));
4264 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4266 /* Compute average percentage of zombies. */
4267 double nlive = 0;
4269 for (i = 0; i < 7; ++i)
4270 nlive += XFASTINT (XCAR (total[i]));
4272 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
4273 max_live = max (nlive, max_live);
4274 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
4275 max_zombies = max (nzombies, max_zombies);
4276 ++ngcs;
4278 #endif
4280 if (!NILP (Vpost_gc_hook))
4282 int count = inhibit_garbage_collection ();
4283 safe_run_hooks (Qpost_gc_hook);
4284 unbind_to (count, Qnil);
4287 return Flist (sizeof total / sizeof *total, total);
4291 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
4292 only interesting objects referenced from glyphs are strings. */
4294 static void
4295 mark_glyph_matrix (matrix)
4296 struct glyph_matrix *matrix;
4298 struct glyph_row *row = matrix->rows;
4299 struct glyph_row *end = row + matrix->nrows;
4301 for (; row < end; ++row)
4302 if (row->enabled_p)
4304 int area;
4305 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
4307 struct glyph *glyph = row->glyphs[area];
4308 struct glyph *end_glyph = glyph + row->used[area];
4310 for (; glyph < end_glyph; ++glyph)
4311 if (GC_STRINGP (glyph->object)
4312 && !STRING_MARKED_P (XSTRING (glyph->object)))
4313 mark_object (&glyph->object);
4319 /* Mark Lisp faces in the face cache C. */
4321 static void
4322 mark_face_cache (c)
4323 struct face_cache *c;
4325 if (c)
4327 int i, j;
4328 for (i = 0; i < c->used; ++i)
4330 struct face *face = FACE_FROM_ID (c->f, i);
4332 if (face)
4334 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
4335 mark_object (&face->lface[j]);
4342 #ifdef HAVE_WINDOW_SYSTEM
4344 /* Mark Lisp objects in image IMG. */
4346 static void
4347 mark_image (img)
4348 struct image *img;
4350 mark_object (&img->spec);
4352 if (!NILP (img->data.lisp_val))
4353 mark_object (&img->data.lisp_val);
4357 /* Mark Lisp objects in image cache of frame F. It's done this way so
4358 that we don't have to include xterm.h here. */
4360 static void
4361 mark_image_cache (f)
4362 struct frame *f;
4364 forall_images_in_image_cache (f, mark_image);
4367 #endif /* HAVE_X_WINDOWS */
4371 /* Mark reference to a Lisp_Object.
4372 If the object referred to has not been seen yet, recursively mark
4373 all the references contained in it. */
4375 #define LAST_MARKED_SIZE 500
4376 Lisp_Object *last_marked[LAST_MARKED_SIZE];
4377 int last_marked_index;
4379 void
4380 mark_object (argptr)
4381 Lisp_Object *argptr;
4383 Lisp_Object *objptr = argptr;
4384 register Lisp_Object obj;
4385 #ifdef GC_CHECK_MARKED_OBJECTS
4386 void *po;
4387 struct mem_node *m;
4388 #endif
4390 loop:
4391 obj = *objptr;
4392 loop2:
4393 XUNMARK (obj);
4395 if (PURE_POINTER_P (XPNTR (obj)))
4396 return;
4398 last_marked[last_marked_index++] = objptr;
4399 if (last_marked_index == LAST_MARKED_SIZE)
4400 last_marked_index = 0;
4402 /* Perform some sanity checks on the objects marked here. Abort if
4403 we encounter an object we know is bogus. This increases GC time
4404 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
4405 #ifdef GC_CHECK_MARKED_OBJECTS
4407 po = (void *) XPNTR (obj);
4409 /* Check that the object pointed to by PO is known to be a Lisp
4410 structure allocated from the heap. */
4411 #define CHECK_ALLOCATED() \
4412 do { \
4413 m = mem_find (po); \
4414 if (m == MEM_NIL) \
4415 abort (); \
4416 } while (0)
4418 /* Check that the object pointed to by PO is live, using predicate
4419 function LIVEP. */
4420 #define CHECK_LIVE(LIVEP) \
4421 do { \
4422 if (!LIVEP (m, po)) \
4423 abort (); \
4424 } while (0)
4426 /* Check both of the above conditions. */
4427 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
4428 do { \
4429 CHECK_ALLOCATED (); \
4430 CHECK_LIVE (LIVEP); \
4431 } while (0) \
4433 #else /* not GC_CHECK_MARKED_OBJECTS */
4435 #define CHECK_ALLOCATED() (void) 0
4436 #define CHECK_LIVE(LIVEP) (void) 0
4437 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
4439 #endif /* not GC_CHECK_MARKED_OBJECTS */
4441 switch (SWITCH_ENUM_CAST (XGCTYPE (obj)))
4443 case Lisp_String:
4445 register struct Lisp_String *ptr = XSTRING (obj);
4446 CHECK_ALLOCATED_AND_LIVE (live_string_p);
4447 MARK_INTERVAL_TREE (ptr->intervals);
4448 MARK_STRING (ptr);
4449 #ifdef GC_CHECK_STRING_BYTES
4450 /* Check that the string size recorded in the string is the
4451 same as the one recorded in the sdata structure. */
4452 CHECK_STRING_BYTES (ptr);
4453 #endif /* GC_CHECK_STRING_BYTES */
4455 break;
4457 case Lisp_Vectorlike:
4458 #ifdef GC_CHECK_MARKED_OBJECTS
4459 m = mem_find (po);
4460 if (m == MEM_NIL && !GC_SUBRP (obj)
4461 && po != &buffer_defaults
4462 && po != &buffer_local_symbols)
4463 abort ();
4464 #endif /* GC_CHECK_MARKED_OBJECTS */
4466 if (GC_BUFFERP (obj))
4468 if (!XMARKBIT (XBUFFER (obj)->name))
4470 #ifdef GC_CHECK_MARKED_OBJECTS
4471 if (po != &buffer_defaults && po != &buffer_local_symbols)
4473 struct buffer *b;
4474 for (b = all_buffers; b && b != po; b = b->next)
4476 if (b == NULL)
4477 abort ();
4479 #endif /* GC_CHECK_MARKED_OBJECTS */
4480 mark_buffer (obj);
4483 else if (GC_SUBRP (obj))
4484 break;
4485 else if (GC_COMPILEDP (obj))
4486 /* We could treat this just like a vector, but it is better to
4487 save the COMPILED_CONSTANTS element for last and avoid
4488 recursion there. */
4490 register struct Lisp_Vector *ptr = XVECTOR (obj);
4491 register EMACS_INT size = ptr->size;
4492 register int i;
4494 if (size & ARRAY_MARK_FLAG)
4495 break; /* Already marked */
4497 CHECK_LIVE (live_vector_p);
4498 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4499 size &= PSEUDOVECTOR_SIZE_MASK;
4500 for (i = 0; i < size; i++) /* and then mark its elements */
4502 if (i != COMPILED_CONSTANTS)
4503 mark_object (&ptr->contents[i]);
4505 /* This cast should be unnecessary, but some Mips compiler complains
4506 (MIPS-ABI + SysVR4, DC/OSx, etc). */
4507 objptr = (Lisp_Object *) &ptr->contents[COMPILED_CONSTANTS];
4508 goto loop;
4510 else if (GC_FRAMEP (obj))
4512 register struct frame *ptr = XFRAME (obj);
4513 register EMACS_INT size = ptr->size;
4515 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
4516 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4518 CHECK_LIVE (live_vector_p);
4519 mark_object (&ptr->name);
4520 mark_object (&ptr->icon_name);
4521 mark_object (&ptr->title);
4522 mark_object (&ptr->focus_frame);
4523 mark_object (&ptr->selected_window);
4524 mark_object (&ptr->minibuffer_window);
4525 mark_object (&ptr->param_alist);
4526 mark_object (&ptr->scroll_bars);
4527 mark_object (&ptr->condemned_scroll_bars);
4528 mark_object (&ptr->menu_bar_items);
4529 mark_object (&ptr->face_alist);
4530 mark_object (&ptr->menu_bar_vector);
4531 mark_object (&ptr->buffer_predicate);
4532 mark_object (&ptr->buffer_list);
4533 mark_object (&ptr->menu_bar_window);
4534 mark_object (&ptr->tool_bar_window);
4535 mark_face_cache (ptr->face_cache);
4536 #ifdef HAVE_WINDOW_SYSTEM
4537 mark_image_cache (ptr);
4538 mark_object (&ptr->tool_bar_items);
4539 mark_object (&ptr->desired_tool_bar_string);
4540 mark_object (&ptr->current_tool_bar_string);
4541 #endif /* HAVE_WINDOW_SYSTEM */
4543 else if (GC_BOOL_VECTOR_P (obj))
4545 register struct Lisp_Vector *ptr = XVECTOR (obj);
4547 if (ptr->size & ARRAY_MARK_FLAG)
4548 break; /* Already marked */
4549 CHECK_LIVE (live_vector_p);
4550 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4552 else if (GC_WINDOWP (obj))
4554 register struct Lisp_Vector *ptr = XVECTOR (obj);
4555 struct window *w = XWINDOW (obj);
4556 register EMACS_INT size = ptr->size;
4557 register int i;
4559 /* Stop if already marked. */
4560 if (size & ARRAY_MARK_FLAG)
4561 break;
4563 /* Mark it. */
4564 CHECK_LIVE (live_vector_p);
4565 ptr->size |= ARRAY_MARK_FLAG;
4567 /* There is no Lisp data above The member CURRENT_MATRIX in
4568 struct WINDOW. Stop marking when that slot is reached. */
4569 for (i = 0;
4570 (char *) &ptr->contents[i] < (char *) &w->current_matrix;
4571 i++)
4572 mark_object (&ptr->contents[i]);
4574 /* Mark glyphs for leaf windows. Marking window matrices is
4575 sufficient because frame matrices use the same glyph
4576 memory. */
4577 if (NILP (w->hchild)
4578 && NILP (w->vchild)
4579 && w->current_matrix)
4581 mark_glyph_matrix (w->current_matrix);
4582 mark_glyph_matrix (w->desired_matrix);
4585 else if (GC_HASH_TABLE_P (obj))
4587 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
4588 EMACS_INT size = h->size;
4590 /* Stop if already marked. */
4591 if (size & ARRAY_MARK_FLAG)
4592 break;
4594 /* Mark it. */
4595 CHECK_LIVE (live_vector_p);
4596 h->size |= ARRAY_MARK_FLAG;
4598 /* Mark contents. */
4599 /* Do not mark next_free or next_weak.
4600 Being in the next_weak chain
4601 should not keep the hash table alive.
4602 No need to mark `count' since it is an integer. */
4603 mark_object (&h->test);
4604 mark_object (&h->weak);
4605 mark_object (&h->rehash_size);
4606 mark_object (&h->rehash_threshold);
4607 mark_object (&h->hash);
4608 mark_object (&h->next);
4609 mark_object (&h->index);
4610 mark_object (&h->user_hash_function);
4611 mark_object (&h->user_cmp_function);
4613 /* If hash table is not weak, mark all keys and values.
4614 For weak tables, mark only the vector. */
4615 if (GC_NILP (h->weak))
4616 mark_object (&h->key_and_value);
4617 else
4618 XVECTOR (h->key_and_value)->size |= ARRAY_MARK_FLAG;
4621 else
4623 register struct Lisp_Vector *ptr = XVECTOR (obj);
4624 register EMACS_INT size = ptr->size;
4625 register int i;
4627 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
4628 CHECK_LIVE (live_vector_p);
4629 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4630 if (size & PSEUDOVECTOR_FLAG)
4631 size &= PSEUDOVECTOR_SIZE_MASK;
4633 for (i = 0; i < size; i++) /* and then mark its elements */
4634 mark_object (&ptr->contents[i]);
4636 break;
4638 case Lisp_Symbol:
4640 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
4641 struct Lisp_Symbol *ptrx;
4643 if (XMARKBIT (ptr->plist)) break;
4644 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
4645 XMARK (ptr->plist);
4646 mark_object ((Lisp_Object *) &ptr->value);
4647 mark_object (&ptr->function);
4648 mark_object (&ptr->plist);
4650 if (!PURE_POINTER_P (ptr->name))
4651 MARK_STRING (ptr->name);
4652 MARK_INTERVAL_TREE (ptr->name->intervals);
4654 /* Note that we do not mark the obarray of the symbol.
4655 It is safe not to do so because nothing accesses that
4656 slot except to check whether it is nil. */
4657 ptr = ptr->next;
4658 if (ptr)
4660 /* For the benefit of the last_marked log. */
4661 objptr = (Lisp_Object *)&XSYMBOL (obj)->next;
4662 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
4663 XSETSYMBOL (obj, ptrx);
4664 /* We can't goto loop here because *objptr doesn't contain an
4665 actual Lisp_Object with valid datatype field. */
4666 goto loop2;
4669 break;
4671 case Lisp_Misc:
4672 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
4673 switch (XMISCTYPE (obj))
4675 case Lisp_Misc_Marker:
4676 XMARK (XMARKER (obj)->chain);
4677 /* DO NOT mark thru the marker's chain.
4678 The buffer's markers chain does not preserve markers from gc;
4679 instead, markers are removed from the chain when freed by gc. */
4680 break;
4682 case Lisp_Misc_Buffer_Local_Value:
4683 case Lisp_Misc_Some_Buffer_Local_Value:
4685 register struct Lisp_Buffer_Local_Value *ptr
4686 = XBUFFER_LOCAL_VALUE (obj);
4687 if (XMARKBIT (ptr->realvalue)) break;
4688 XMARK (ptr->realvalue);
4689 /* If the cdr is nil, avoid recursion for the car. */
4690 if (EQ (ptr->cdr, Qnil))
4692 objptr = &ptr->realvalue;
4693 goto loop;
4695 mark_object (&ptr->realvalue);
4696 mark_object (&ptr->buffer);
4697 mark_object (&ptr->frame);
4698 objptr = &ptr->cdr;
4699 goto loop;
4702 case Lisp_Misc_Intfwd:
4703 case Lisp_Misc_Boolfwd:
4704 case Lisp_Misc_Objfwd:
4705 case Lisp_Misc_Buffer_Objfwd:
4706 case Lisp_Misc_Kboard_Objfwd:
4707 /* Don't bother with Lisp_Buffer_Objfwd,
4708 since all markable slots in current buffer marked anyway. */
4709 /* Don't need to do Lisp_Objfwd, since the places they point
4710 are protected with staticpro. */
4711 break;
4713 case Lisp_Misc_Overlay:
4715 struct Lisp_Overlay *ptr = XOVERLAY (obj);
4716 if (!XMARKBIT (ptr->plist))
4718 XMARK (ptr->plist);
4719 mark_object (&ptr->start);
4720 mark_object (&ptr->end);
4721 objptr = &ptr->plist;
4722 goto loop;
4725 break;
4727 default:
4728 abort ();
4730 break;
4732 case Lisp_Cons:
4734 register struct Lisp_Cons *ptr = XCONS (obj);
4735 if (XMARKBIT (ptr->car)) break;
4736 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
4737 XMARK (ptr->car);
4738 /* If the cdr is nil, avoid recursion for the car. */
4739 if (EQ (ptr->cdr, Qnil))
4741 objptr = &ptr->car;
4742 goto loop;
4744 mark_object (&ptr->car);
4745 objptr = &ptr->cdr;
4746 goto loop;
4749 case Lisp_Float:
4750 CHECK_ALLOCATED_AND_LIVE (live_float_p);
4751 XMARK (XFLOAT (obj)->type);
4752 break;
4754 case Lisp_Int:
4755 break;
4757 default:
4758 abort ();
4761 #undef CHECK_LIVE
4762 #undef CHECK_ALLOCATED
4763 #undef CHECK_ALLOCATED_AND_LIVE
4766 /* Mark the pointers in a buffer structure. */
4768 static void
4769 mark_buffer (buf)
4770 Lisp_Object buf;
4772 register struct buffer *buffer = XBUFFER (buf);
4773 register Lisp_Object *ptr;
4774 Lisp_Object base_buffer;
4776 /* This is the buffer's markbit */
4777 mark_object (&buffer->name);
4778 XMARK (buffer->name);
4780 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
4782 if (CONSP (buffer->undo_list))
4784 Lisp_Object tail;
4785 tail = buffer->undo_list;
4787 while (CONSP (tail))
4789 register struct Lisp_Cons *ptr = XCONS (tail);
4791 if (XMARKBIT (ptr->car))
4792 break;
4793 XMARK (ptr->car);
4794 if (GC_CONSP (ptr->car)
4795 && ! XMARKBIT (XCAR (ptr->car))
4796 && GC_MARKERP (XCAR (ptr->car)))
4798 XMARK (XCAR_AS_LVALUE (ptr->car));
4799 mark_object (&XCDR_AS_LVALUE (ptr->car));
4801 else
4802 mark_object (&ptr->car);
4804 if (CONSP (ptr->cdr))
4805 tail = ptr->cdr;
4806 else
4807 break;
4810 mark_object (&XCDR_AS_LVALUE (tail));
4812 else
4813 mark_object (&buffer->undo_list);
4815 for (ptr = &buffer->name + 1;
4816 (char *)ptr < (char *)buffer + sizeof (struct buffer);
4817 ptr++)
4818 mark_object (ptr);
4820 /* If this is an indirect buffer, mark its base buffer. */
4821 if (buffer->base_buffer && !XMARKBIT (buffer->base_buffer->name))
4823 XSETBUFFER (base_buffer, buffer->base_buffer);
4824 mark_buffer (base_buffer);
4829 /* Mark the pointers in the kboard objects. */
4831 static void
4832 mark_kboards ()
4834 KBOARD *kb;
4835 Lisp_Object *p;
4836 for (kb = all_kboards; kb; kb = kb->next_kboard)
4838 if (kb->kbd_macro_buffer)
4839 for (p = kb->kbd_macro_buffer; p < kb->kbd_macro_ptr; p++)
4840 mark_object (p);
4841 mark_object (&kb->Voverriding_terminal_local_map);
4842 mark_object (&kb->Vlast_command);
4843 mark_object (&kb->Vreal_last_command);
4844 mark_object (&kb->Vprefix_arg);
4845 mark_object (&kb->Vlast_prefix_arg);
4846 mark_object (&kb->kbd_queue);
4847 mark_object (&kb->defining_kbd_macro);
4848 mark_object (&kb->Vlast_kbd_macro);
4849 mark_object (&kb->Vsystem_key_alist);
4850 mark_object (&kb->system_key_syms);
4851 mark_object (&kb->Vdefault_minibuffer_frame);
4856 /* Value is non-zero if OBJ will survive the current GC because it's
4857 either marked or does not need to be marked to survive. */
4860 survives_gc_p (obj)
4861 Lisp_Object obj;
4863 int survives_p;
4865 switch (XGCTYPE (obj))
4867 case Lisp_Int:
4868 survives_p = 1;
4869 break;
4871 case Lisp_Symbol:
4872 survives_p = XMARKBIT (XSYMBOL (obj)->plist);
4873 break;
4875 case Lisp_Misc:
4876 switch (XMISCTYPE (obj))
4878 case Lisp_Misc_Marker:
4879 survives_p = XMARKBIT (obj);
4880 break;
4882 case Lisp_Misc_Buffer_Local_Value:
4883 case Lisp_Misc_Some_Buffer_Local_Value:
4884 survives_p = XMARKBIT (XBUFFER_LOCAL_VALUE (obj)->realvalue);
4885 break;
4887 case Lisp_Misc_Intfwd:
4888 case Lisp_Misc_Boolfwd:
4889 case Lisp_Misc_Objfwd:
4890 case Lisp_Misc_Buffer_Objfwd:
4891 case Lisp_Misc_Kboard_Objfwd:
4892 survives_p = 1;
4893 break;
4895 case Lisp_Misc_Overlay:
4896 survives_p = XMARKBIT (XOVERLAY (obj)->plist);
4897 break;
4899 default:
4900 abort ();
4902 break;
4904 case Lisp_String:
4906 struct Lisp_String *s = XSTRING (obj);
4907 survives_p = STRING_MARKED_P (s);
4909 break;
4911 case Lisp_Vectorlike:
4912 if (GC_BUFFERP (obj))
4913 survives_p = XMARKBIT (XBUFFER (obj)->name);
4914 else if (GC_SUBRP (obj))
4915 survives_p = 1;
4916 else
4917 survives_p = XVECTOR (obj)->size & ARRAY_MARK_FLAG;
4918 break;
4920 case Lisp_Cons:
4921 survives_p = XMARKBIT (XCAR (obj));
4922 break;
4924 case Lisp_Float:
4925 survives_p = XMARKBIT (XFLOAT (obj)->type);
4926 break;
4928 default:
4929 abort ();
4932 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
4937 /* Sweep: find all structures not marked, and free them. */
4939 static void
4940 gc_sweep ()
4942 /* Remove or mark entries in weak hash tables.
4943 This must be done before any object is unmarked. */
4944 sweep_weak_hash_tables ();
4946 sweep_strings ();
4947 #ifdef GC_CHECK_STRING_BYTES
4948 if (!noninteractive)
4949 check_string_bytes (1);
4950 #endif
4952 /* Put all unmarked conses on free list */
4954 register struct cons_block *cblk;
4955 struct cons_block **cprev = &cons_block;
4956 register int lim = cons_block_index;
4957 register int num_free = 0, num_used = 0;
4959 cons_free_list = 0;
4961 for (cblk = cons_block; cblk; cblk = *cprev)
4963 register int i;
4964 int this_free = 0;
4965 for (i = 0; i < lim; i++)
4966 if (!XMARKBIT (cblk->conses[i].car))
4968 this_free++;
4969 *(struct Lisp_Cons **)&cblk->conses[i].cdr = cons_free_list;
4970 cons_free_list = &cblk->conses[i];
4971 #if GC_MARK_STACK
4972 cons_free_list->car = Vdead;
4973 #endif
4975 else
4977 num_used++;
4978 XUNMARK (cblk->conses[i].car);
4980 lim = CONS_BLOCK_SIZE;
4981 /* If this block contains only free conses and we have already
4982 seen more than two blocks worth of free conses then deallocate
4983 this block. */
4984 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
4986 *cprev = cblk->next;
4987 /* Unhook from the free list. */
4988 cons_free_list = *(struct Lisp_Cons **) &cblk->conses[0].cdr;
4989 lisp_free (cblk);
4990 n_cons_blocks--;
4992 else
4994 num_free += this_free;
4995 cprev = &cblk->next;
4998 total_conses = num_used;
4999 total_free_conses = num_free;
5002 /* Put all unmarked floats on free list */
5004 register struct float_block *fblk;
5005 struct float_block **fprev = &float_block;
5006 register int lim = float_block_index;
5007 register int num_free = 0, num_used = 0;
5009 float_free_list = 0;
5011 for (fblk = float_block; fblk; fblk = *fprev)
5013 register int i;
5014 int this_free = 0;
5015 for (i = 0; i < lim; i++)
5016 if (!XMARKBIT (fblk->floats[i].type))
5018 this_free++;
5019 *(struct Lisp_Float **)&fblk->floats[i].data = float_free_list;
5020 float_free_list = &fblk->floats[i];
5021 #if GC_MARK_STACK
5022 float_free_list->type = Vdead;
5023 #endif
5025 else
5027 num_used++;
5028 XUNMARK (fblk->floats[i].type);
5030 lim = FLOAT_BLOCK_SIZE;
5031 /* If this block contains only free floats and we have already
5032 seen more than two blocks worth of free floats then deallocate
5033 this block. */
5034 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
5036 *fprev = fblk->next;
5037 /* Unhook from the free list. */
5038 float_free_list = *(struct Lisp_Float **) &fblk->floats[0].data;
5039 lisp_free (fblk);
5040 n_float_blocks--;
5042 else
5044 num_free += this_free;
5045 fprev = &fblk->next;
5048 total_floats = num_used;
5049 total_free_floats = num_free;
5052 /* Put all unmarked intervals on free list */
5054 register struct interval_block *iblk;
5055 struct interval_block **iprev = &interval_block;
5056 register int lim = interval_block_index;
5057 register int num_free = 0, num_used = 0;
5059 interval_free_list = 0;
5061 for (iblk = interval_block; iblk; iblk = *iprev)
5063 register int i;
5064 int this_free = 0;
5066 for (i = 0; i < lim; i++)
5068 if (! XMARKBIT (iblk->intervals[i].plist))
5070 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
5071 interval_free_list = &iblk->intervals[i];
5072 this_free++;
5074 else
5076 num_used++;
5077 XUNMARK (iblk->intervals[i].plist);
5080 lim = INTERVAL_BLOCK_SIZE;
5081 /* If this block contains only free intervals and we have already
5082 seen more than two blocks worth of free intervals then
5083 deallocate this block. */
5084 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
5086 *iprev = iblk->next;
5087 /* Unhook from the free list. */
5088 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
5089 lisp_free (iblk);
5090 n_interval_blocks--;
5092 else
5094 num_free += this_free;
5095 iprev = &iblk->next;
5098 total_intervals = num_used;
5099 total_free_intervals = num_free;
5102 /* Put all unmarked symbols on free list */
5104 register struct symbol_block *sblk;
5105 struct symbol_block **sprev = &symbol_block;
5106 register int lim = symbol_block_index;
5107 register int num_free = 0, num_used = 0;
5109 symbol_free_list = NULL;
5111 for (sblk = symbol_block; sblk; sblk = *sprev)
5113 int this_free = 0;
5114 struct Lisp_Symbol *sym = sblk->symbols;
5115 struct Lisp_Symbol *end = sym + lim;
5117 for (; sym < end; ++sym)
5119 /* Check if the symbol was created during loadup. In such a case
5120 it might be pointed to by pure bytecode which we don't trace,
5121 so we conservatively assume that it is live. */
5122 int pure_p = PURE_POINTER_P (sym->name);
5124 if (!XMARKBIT (sym->plist) && !pure_p)
5126 *(struct Lisp_Symbol **) &sym->value = symbol_free_list;
5127 symbol_free_list = sym;
5128 #if GC_MARK_STACK
5129 symbol_free_list->function = Vdead;
5130 #endif
5131 ++this_free;
5133 else
5135 ++num_used;
5136 if (!pure_p)
5137 UNMARK_STRING (sym->name);
5138 XUNMARK (sym->plist);
5142 lim = SYMBOL_BLOCK_SIZE;
5143 /* If this block contains only free symbols and we have already
5144 seen more than two blocks worth of free symbols then deallocate
5145 this block. */
5146 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
5148 *sprev = sblk->next;
5149 /* Unhook from the free list. */
5150 symbol_free_list = *(struct Lisp_Symbol **)&sblk->symbols[0].value;
5151 lisp_free (sblk);
5152 n_symbol_blocks--;
5154 else
5156 num_free += this_free;
5157 sprev = &sblk->next;
5160 total_symbols = num_used;
5161 total_free_symbols = num_free;
5164 /* Put all unmarked misc's on free list.
5165 For a marker, first unchain it from the buffer it points into. */
5167 register struct marker_block *mblk;
5168 struct marker_block **mprev = &marker_block;
5169 register int lim = marker_block_index;
5170 register int num_free = 0, num_used = 0;
5172 marker_free_list = 0;
5174 for (mblk = marker_block; mblk; mblk = *mprev)
5176 register int i;
5177 int this_free = 0;
5178 EMACS_INT already_free = -1;
5180 for (i = 0; i < lim; i++)
5182 Lisp_Object *markword;
5183 switch (mblk->markers[i].u_marker.type)
5185 case Lisp_Misc_Marker:
5186 markword = &mblk->markers[i].u_marker.chain;
5187 break;
5188 case Lisp_Misc_Buffer_Local_Value:
5189 case Lisp_Misc_Some_Buffer_Local_Value:
5190 markword = &mblk->markers[i].u_buffer_local_value.realvalue;
5191 break;
5192 case Lisp_Misc_Overlay:
5193 markword = &mblk->markers[i].u_overlay.plist;
5194 break;
5195 case Lisp_Misc_Free:
5196 /* If the object was already free, keep it
5197 on the free list. */
5198 markword = (Lisp_Object *) &already_free;
5199 break;
5200 default:
5201 markword = 0;
5202 break;
5204 if (markword && !XMARKBIT (*markword))
5206 Lisp_Object tem;
5207 if (mblk->markers[i].u_marker.type == Lisp_Misc_Marker)
5209 /* tem1 avoids Sun compiler bug */
5210 struct Lisp_Marker *tem1 = &mblk->markers[i].u_marker;
5211 XSETMARKER (tem, tem1);
5212 unchain_marker (tem);
5214 /* Set the type of the freed object to Lisp_Misc_Free.
5215 We could leave the type alone, since nobody checks it,
5216 but this might catch bugs faster. */
5217 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
5218 mblk->markers[i].u_free.chain = marker_free_list;
5219 marker_free_list = &mblk->markers[i];
5220 this_free++;
5222 else
5224 num_used++;
5225 if (markword)
5226 XUNMARK (*markword);
5229 lim = MARKER_BLOCK_SIZE;
5230 /* If this block contains only free markers and we have already
5231 seen more than two blocks worth of free markers then deallocate
5232 this block. */
5233 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
5235 *mprev = mblk->next;
5236 /* Unhook from the free list. */
5237 marker_free_list = mblk->markers[0].u_free.chain;
5238 lisp_free (mblk);
5239 n_marker_blocks--;
5241 else
5243 num_free += this_free;
5244 mprev = &mblk->next;
5248 total_markers = num_used;
5249 total_free_markers = num_free;
5252 /* Free all unmarked buffers */
5254 register struct buffer *buffer = all_buffers, *prev = 0, *next;
5256 while (buffer)
5257 if (!XMARKBIT (buffer->name))
5259 if (prev)
5260 prev->next = buffer->next;
5261 else
5262 all_buffers = buffer->next;
5263 next = buffer->next;
5264 lisp_free (buffer);
5265 buffer = next;
5267 else
5269 XUNMARK (buffer->name);
5270 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
5271 prev = buffer, buffer = buffer->next;
5275 /* Free all unmarked vectors */
5277 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
5278 total_vector_size = 0;
5280 while (vector)
5281 if (!(vector->size & ARRAY_MARK_FLAG))
5283 if (prev)
5284 prev->next = vector->next;
5285 else
5286 all_vectors = vector->next;
5287 next = vector->next;
5288 lisp_free (vector);
5289 n_vectors--;
5290 vector = next;
5293 else
5295 vector->size &= ~ARRAY_MARK_FLAG;
5296 if (vector->size & PSEUDOVECTOR_FLAG)
5297 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
5298 else
5299 total_vector_size += vector->size;
5300 prev = vector, vector = vector->next;
5304 #ifdef GC_CHECK_STRING_BYTES
5305 if (!noninteractive)
5306 check_string_bytes (1);
5307 #endif
5313 /* Debugging aids. */
5315 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
5316 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
5317 This may be helpful in debugging Emacs's memory usage.
5318 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
5321 Lisp_Object end;
5323 XSETINT (end, (EMACS_INT) sbrk (0) / 1024);
5325 return end;
5328 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
5329 doc: /* Return a list of counters that measure how much consing there has been.
5330 Each of these counters increments for a certain kind of object.
5331 The counters wrap around from the largest positive integer to zero.
5332 Garbage collection does not decrease them.
5333 The elements of the value are as follows:
5334 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
5335 All are in units of 1 = one object consed
5336 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
5337 objects consed.
5338 MISCS include overlays, markers, and some internal types.
5339 Frames, windows, buffers, and subprocesses count as vectors
5340 (but the contents of a buffer's text do not count here). */)
5343 Lisp_Object consed[8];
5345 consed[0] = make_number (min (MOST_POSITIVE_FIXNUM, cons_cells_consed));
5346 consed[1] = make_number (min (MOST_POSITIVE_FIXNUM, floats_consed));
5347 consed[2] = make_number (min (MOST_POSITIVE_FIXNUM, vector_cells_consed));
5348 consed[3] = make_number (min (MOST_POSITIVE_FIXNUM, symbols_consed));
5349 consed[4] = make_number (min (MOST_POSITIVE_FIXNUM, string_chars_consed));
5350 consed[5] = make_number (min (MOST_POSITIVE_FIXNUM, misc_objects_consed));
5351 consed[6] = make_number (min (MOST_POSITIVE_FIXNUM, intervals_consed));
5352 consed[7] = make_number (min (MOST_POSITIVE_FIXNUM, strings_consed));
5354 return Flist (8, consed);
5357 int suppress_checking;
5358 void
5359 die (msg, file, line)
5360 const char *msg;
5361 const char *file;
5362 int line;
5364 fprintf (stderr, "\r\nEmacs fatal error: %s:%d: %s\r\n",
5365 file, line, msg);
5366 abort ();
5369 /* Initialization */
5371 void
5372 init_alloc_once ()
5374 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
5375 purebeg = PUREBEG;
5376 pure_size = PURESIZE;
5377 pure_bytes_used = 0;
5378 pure_bytes_used_before_overflow = 0;
5380 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
5381 mem_init ();
5382 Vdead = make_pure_string ("DEAD", 4, 4, 0);
5383 #endif
5385 all_vectors = 0;
5386 ignore_warnings = 1;
5387 #ifdef DOUG_LEA_MALLOC
5388 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
5389 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
5390 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
5391 #endif
5392 init_strings ();
5393 init_cons ();
5394 init_symbol ();
5395 init_marker ();
5396 init_float ();
5397 init_intervals ();
5399 #ifdef REL_ALLOC
5400 malloc_hysteresis = 32;
5401 #else
5402 malloc_hysteresis = 0;
5403 #endif
5405 spare_memory = (char *) malloc (SPARE_MEMORY);
5407 ignore_warnings = 0;
5408 gcprolist = 0;
5409 byte_stack_list = 0;
5410 staticidx = 0;
5411 consing_since_gc = 0;
5412 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
5413 #ifdef VIRT_ADDR_VARIES
5414 malloc_sbrk_unused = 1<<22; /* A large number */
5415 malloc_sbrk_used = 100000; /* as reasonable as any number */
5416 #endif /* VIRT_ADDR_VARIES */
5419 void
5420 init_alloc ()
5422 gcprolist = 0;
5423 byte_stack_list = 0;
5424 #if GC_MARK_STACK
5425 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
5426 setjmp_tested_p = longjmps_done = 0;
5427 #endif
5428 #endif
5431 void
5432 syms_of_alloc ()
5434 DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold,
5435 doc: /* *Number of bytes of consing between garbage collections.
5436 Garbage collection can happen automatically once this many bytes have been
5437 allocated since the last garbage collection. All data types count.
5439 Garbage collection happens automatically only when `eval' is called.
5441 By binding this temporarily to a large number, you can effectively
5442 prevent garbage collection during a part of the program. */);
5444 DEFVAR_INT ("pure-bytes-used", &pure_bytes_used,
5445 doc: /* Number of bytes of sharable Lisp data allocated so far. */);
5447 DEFVAR_INT ("cons-cells-consed", &cons_cells_consed,
5448 doc: /* Number of cons cells that have been consed so far. */);
5450 DEFVAR_INT ("floats-consed", &floats_consed,
5451 doc: /* Number of floats that have been consed so far. */);
5453 DEFVAR_INT ("vector-cells-consed", &vector_cells_consed,
5454 doc: /* Number of vector cells that have been consed so far. */);
5456 DEFVAR_INT ("symbols-consed", &symbols_consed,
5457 doc: /* Number of symbols that have been consed so far. */);
5459 DEFVAR_INT ("string-chars-consed", &string_chars_consed,
5460 doc: /* Number of string characters that have been consed so far. */);
5462 DEFVAR_INT ("misc-objects-consed", &misc_objects_consed,
5463 doc: /* Number of miscellaneous objects that have been consed so far. */);
5465 DEFVAR_INT ("intervals-consed", &intervals_consed,
5466 doc: /* Number of intervals that have been consed so far. */);
5468 DEFVAR_INT ("strings-consed", &strings_consed,
5469 doc: /* Number of strings that have been consed so far. */);
5471 DEFVAR_LISP ("purify-flag", &Vpurify_flag,
5472 doc: /* Non-nil means loading Lisp code in order to dump an executable.
5473 This means that certain objects should be allocated in shared (pure) space. */);
5475 DEFVAR_INT ("undo-limit", &undo_limit,
5476 doc: /* Keep no more undo information once it exceeds this size.
5477 This limit is applied when garbage collection happens.
5478 The size is counted as the number of bytes occupied,
5479 which includes both saved text and other data. */);
5480 undo_limit = 20000;
5482 DEFVAR_INT ("undo-strong-limit", &undo_strong_limit,
5483 doc: /* Don't keep more than this much size of undo information.
5484 A command which pushes past this size is itself forgotten.
5485 This limit is applied when garbage collection happens.
5486 The size is counted as the number of bytes occupied,
5487 which includes both saved text and other data. */);
5488 undo_strong_limit = 30000;
5490 DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
5491 doc: /* Non-nil means display messages at start and end of garbage collection. */);
5492 garbage_collection_messages = 0;
5494 DEFVAR_LISP ("post-gc-hook", &Vpost_gc_hook,
5495 doc: /* Hook run after garbage collection has finished. */);
5496 Vpost_gc_hook = Qnil;
5497 Qpost_gc_hook = intern ("post-gc-hook");
5498 staticpro (&Qpost_gc_hook);
5500 /* We build this in advance because if we wait until we need it, we might
5501 not be able to allocate the memory to hold it. */
5502 memory_signal_data
5503 = Fcons (Qerror, Fcons (build_string ("Memory exhausted--use M-x save-some-buffers RET"), Qnil));
5504 staticpro (&memory_signal_data);
5506 staticpro (&Qgc_cons_threshold);
5507 Qgc_cons_threshold = intern ("gc-cons-threshold");
5509 staticpro (&Qchar_table_extra_slots);
5510 Qchar_table_extra_slots = intern ("char-table-extra-slots");
5512 defsubr (&Scons);
5513 defsubr (&Slist);
5514 defsubr (&Svector);
5515 defsubr (&Smake_byte_code);
5516 defsubr (&Smake_list);
5517 defsubr (&Smake_vector);
5518 defsubr (&Smake_string);
5519 defsubr (&Smake_bool_vector);
5520 defsubr (&Smake_symbol);
5521 defsubr (&Smake_marker);
5522 defsubr (&Spurecopy);
5523 defsubr (&Sgarbage_collect);
5524 defsubr (&Smemory_limit);
5525 defsubr (&Smemory_use_counts);
5527 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5528 defsubr (&Sgc_status);
5529 #endif