*** empty log message ***
[emacs.git] / src / alloc.c
blobfb352bd56d8381ffe800be0a6778cf88c5e952bb
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
2 Copyright (C) 1985, 1986, 1988, 1993, 1994, 1995, 1997, 1998, 1999,
3 2000, 2001, 2002, 2003, 2004, 2005 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>
24 #include <limits.h> /* For CHAR_BIT. */
26 #ifdef ALLOC_DEBUG
27 #undef INLINE
28 #endif
30 /* Note that this declares bzero on OSF/1. How dumb. */
32 #include <signal.h>
34 #ifdef HAVE_GTK_AND_PTHREAD
35 #include <pthread.h>
36 #endif
38 /* This file is part of the core Lisp implementation, and thus must
39 deal with the real data structures. If the Lisp implementation is
40 replaced, this file likely will not be used. */
42 #undef HIDE_LISP_IMPLEMENTATION
43 #include "lisp.h"
44 #include "process.h"
45 #include "intervals.h"
46 #include "puresize.h"
47 #include "buffer.h"
48 #include "window.h"
49 #include "keyboard.h"
50 #include "frame.h"
51 #include "blockinput.h"
52 #include "charset.h"
53 #include "syssignal.h"
54 #include <setjmp.h>
56 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
57 memory. Can do this only if using gmalloc.c. */
59 #if defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC
60 #undef GC_MALLOC_CHECK
61 #endif
63 #ifdef HAVE_UNISTD_H
64 #include <unistd.h>
65 #else
66 extern POINTER_TYPE *sbrk ();
67 #endif
69 #ifdef DOUG_LEA_MALLOC
71 #include <malloc.h>
72 /* malloc.h #defines this as size_t, at least in glibc2. */
73 #ifndef __malloc_size_t
74 #define __malloc_size_t int
75 #endif
77 /* Specify maximum number of areas to mmap. It would be nice to use a
78 value that explicitly means "no limit". */
80 #define MMAP_MAX_AREAS 100000000
82 #else /* not DOUG_LEA_MALLOC */
84 /* The following come from gmalloc.c. */
86 #define __malloc_size_t size_t
87 extern __malloc_size_t _bytes_used;
88 extern __malloc_size_t __malloc_extra_blocks;
90 #endif /* not DOUG_LEA_MALLOC */
92 #if ! defined (SYSTEM_MALLOC) && defined (HAVE_GTK_AND_PTHREAD)
94 /* When GTK uses the file chooser dialog, different backends can be loaded
95 dynamically. One such a backend is the Gnome VFS backend that gets loaded
96 if you run Gnome. That backend creates several threads and also allocates
97 memory with malloc.
99 If Emacs sets malloc hooks (! SYSTEM_MALLOC) and the emacs_blocked_*
100 functions below are called from malloc, there is a chance that one
101 of these threads preempts the Emacs main thread and the hook variables
102 end up in an inconsistent state. So we have a mutex to prevent that (note
103 that the backend handles concurrent access to malloc within its own threads
104 but Emacs code running in the main thread is not included in that control).
106 When UNBLOCK_INPUT is called, reinvoke_input_signal may be called. If this
107 happens in one of the backend threads we will have two threads that tries
108 to run Emacs code at once, and the code is not prepared for that.
109 To prevent that, we only call BLOCK/UNBLOCK from the main thread. */
111 static pthread_mutex_t alloc_mutex;
113 #define BLOCK_INPUT_ALLOC \
114 do \
116 pthread_mutex_lock (&alloc_mutex); \
117 if (pthread_self () == main_thread) \
118 BLOCK_INPUT; \
120 while (0)
121 #define UNBLOCK_INPUT_ALLOC \
122 do \
124 if (pthread_self () == main_thread) \
125 UNBLOCK_INPUT; \
126 pthread_mutex_unlock (&alloc_mutex); \
128 while (0)
130 #else /* SYSTEM_MALLOC || not HAVE_GTK_AND_PTHREAD */
132 #define BLOCK_INPUT_ALLOC BLOCK_INPUT
133 #define UNBLOCK_INPUT_ALLOC UNBLOCK_INPUT
135 #endif /* SYSTEM_MALLOC || not HAVE_GTK_AND_PTHREAD */
137 /* Value of _bytes_used, when spare_memory was freed. */
139 static __malloc_size_t bytes_used_when_full;
141 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
142 to a struct Lisp_String. */
144 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
145 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
146 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
148 #define VECTOR_MARK(V) ((V)->size |= ARRAY_MARK_FLAG)
149 #define VECTOR_UNMARK(V) ((V)->size &= ~ARRAY_MARK_FLAG)
150 #define VECTOR_MARKED_P(V) (((V)->size & ARRAY_MARK_FLAG) != 0)
152 /* Value is the number of bytes/chars of S, a pointer to a struct
153 Lisp_String. This must be used instead of STRING_BYTES (S) or
154 S->size during GC, because S->size contains the mark bit for
155 strings. */
157 #define GC_STRING_BYTES(S) (STRING_BYTES (S))
158 #define GC_STRING_CHARS(S) ((S)->size & ~ARRAY_MARK_FLAG)
160 /* Number of bytes of consing done since the last gc. */
162 int consing_since_gc;
164 /* Count the amount of consing of various sorts of space. */
166 EMACS_INT cons_cells_consed;
167 EMACS_INT floats_consed;
168 EMACS_INT vector_cells_consed;
169 EMACS_INT symbols_consed;
170 EMACS_INT string_chars_consed;
171 EMACS_INT misc_objects_consed;
172 EMACS_INT intervals_consed;
173 EMACS_INT strings_consed;
175 /* Number of bytes of consing since GC before another GC should be done. */
177 EMACS_INT gc_cons_threshold;
179 /* Nonzero during GC. */
181 int gc_in_progress;
183 /* Nonzero means abort if try to GC.
184 This is for code which is written on the assumption that
185 no GC will happen, so as to verify that assumption. */
187 int abort_on_gc;
189 /* Nonzero means display messages at beginning and end of GC. */
191 int garbage_collection_messages;
193 #ifndef VIRT_ADDR_VARIES
194 extern
195 #endif /* VIRT_ADDR_VARIES */
196 int malloc_sbrk_used;
198 #ifndef VIRT_ADDR_VARIES
199 extern
200 #endif /* VIRT_ADDR_VARIES */
201 int malloc_sbrk_unused;
203 /* Number of live and free conses etc. */
205 static int total_conses, total_markers, total_symbols, total_vector_size;
206 static int total_free_conses, total_free_markers, total_free_symbols;
207 static int total_free_floats, total_floats;
209 /* Points to memory space allocated as "spare", to be freed if we run
210 out of memory. */
212 static char *spare_memory;
214 /* Amount of spare memory to keep in reserve. */
216 #define SPARE_MEMORY (1 << 14)
218 /* Number of extra blocks malloc should get when it needs more core. */
220 static int malloc_hysteresis;
222 /* Non-nil means defun should do purecopy on the function definition. */
224 Lisp_Object Vpurify_flag;
226 /* Non-nil means we are handling a memory-full error. */
228 Lisp_Object Vmemory_full;
230 #ifndef HAVE_SHM
232 /* Initialize it to a nonzero value to force it into data space
233 (rather than bss space). That way unexec will remap it into text
234 space (pure), on some systems. We have not implemented the
235 remapping on more recent systems because this is less important
236 nowadays than in the days of small memories and timesharing. */
238 EMACS_INT pure[PURESIZE / sizeof (EMACS_INT)] = {1,};
239 #define PUREBEG (char *) pure
241 #else /* HAVE_SHM */
243 #define pure PURE_SEG_BITS /* Use shared memory segment */
244 #define PUREBEG (char *)PURE_SEG_BITS
246 #endif /* HAVE_SHM */
248 /* Pointer to the pure area, and its size. */
250 static char *purebeg;
251 static size_t pure_size;
253 /* Number of bytes of pure storage used before pure storage overflowed.
254 If this is non-zero, this implies that an overflow occurred. */
256 static size_t pure_bytes_used_before_overflow;
258 /* Value is non-zero if P points into pure space. */
260 #define PURE_POINTER_P(P) \
261 (((PNTR_COMPARISON_TYPE) (P) \
262 < (PNTR_COMPARISON_TYPE) ((char *) purebeg + pure_size)) \
263 && ((PNTR_COMPARISON_TYPE) (P) \
264 >= (PNTR_COMPARISON_TYPE) purebeg))
266 /* Index in pure at which next pure object will be allocated.. */
268 EMACS_INT pure_bytes_used;
270 /* If nonzero, this is a warning delivered by malloc and not yet
271 displayed. */
273 char *pending_malloc_warning;
275 /* Pre-computed signal argument for use when memory is exhausted. */
277 Lisp_Object Vmemory_signal_data;
279 /* Maximum amount of C stack to save when a GC happens. */
281 #ifndef MAX_SAVE_STACK
282 #define MAX_SAVE_STACK 16000
283 #endif
285 /* Buffer in which we save a copy of the C stack at each GC. */
287 char *stack_copy;
288 int stack_copy_size;
290 /* Non-zero means ignore malloc warnings. Set during initialization.
291 Currently not used. */
293 int ignore_warnings;
295 Lisp_Object Qgc_cons_threshold, Qchar_table_extra_slots;
297 /* Hook run after GC has finished. */
299 Lisp_Object Vpost_gc_hook, Qpost_gc_hook;
301 Lisp_Object Vgc_elapsed; /* accumulated elapsed time in GC */
302 EMACS_INT gcs_done; /* accumulated GCs */
304 static void mark_buffer P_ ((Lisp_Object));
305 extern void mark_kboards P_ ((void));
306 extern void mark_backtrace P_ ((void));
307 static void gc_sweep P_ ((void));
308 static void mark_glyph_matrix P_ ((struct glyph_matrix *));
309 static void mark_face_cache P_ ((struct face_cache *));
311 #ifdef HAVE_WINDOW_SYSTEM
312 extern void mark_fringe_data P_ ((void));
313 static void mark_image P_ ((struct image *));
314 static void mark_image_cache P_ ((struct frame *));
315 #endif /* HAVE_WINDOW_SYSTEM */
317 static struct Lisp_String *allocate_string P_ ((void));
318 static void compact_small_strings P_ ((void));
319 static void free_large_strings P_ ((void));
320 static void sweep_strings P_ ((void));
322 extern int message_enable_multibyte;
324 /* When scanning the C stack for live Lisp objects, Emacs keeps track
325 of what memory allocated via lisp_malloc is intended for what
326 purpose. This enumeration specifies the type of memory. */
328 enum mem_type
330 MEM_TYPE_NON_LISP,
331 MEM_TYPE_BUFFER,
332 MEM_TYPE_CONS,
333 MEM_TYPE_STRING,
334 MEM_TYPE_MISC,
335 MEM_TYPE_SYMBOL,
336 MEM_TYPE_FLOAT,
337 /* Keep the following vector-like types together, with
338 MEM_TYPE_WINDOW being the last, and MEM_TYPE_VECTOR the
339 first. Or change the code of live_vector_p, for instance. */
340 MEM_TYPE_VECTOR,
341 MEM_TYPE_PROCESS,
342 MEM_TYPE_HASH_TABLE,
343 MEM_TYPE_FRAME,
344 MEM_TYPE_WINDOW
347 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
349 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
350 #include <stdio.h> /* For fprintf. */
351 #endif
353 /* A unique object in pure space used to make some Lisp objects
354 on free lists recognizable in O(1). */
356 Lisp_Object Vdead;
358 #ifdef GC_MALLOC_CHECK
360 enum mem_type allocated_mem_type;
361 int dont_register_blocks;
363 #endif /* GC_MALLOC_CHECK */
365 /* A node in the red-black tree describing allocated memory containing
366 Lisp data. Each such block is recorded with its start and end
367 address when it is allocated, and removed from the tree when it
368 is freed.
370 A red-black tree is a balanced binary tree with the following
371 properties:
373 1. Every node is either red or black.
374 2. Every leaf is black.
375 3. If a node is red, then both of its children are black.
376 4. Every simple path from a node to a descendant leaf contains
377 the same number of black nodes.
378 5. The root is always black.
380 When nodes are inserted into the tree, or deleted from the tree,
381 the tree is "fixed" so that these properties are always true.
383 A red-black tree with N internal nodes has height at most 2
384 log(N+1). Searches, insertions and deletions are done in O(log N).
385 Please see a text book about data structures for a detailed
386 description of red-black trees. Any book worth its salt should
387 describe them. */
389 struct mem_node
391 /* Children of this node. These pointers are never NULL. When there
392 is no child, the value is MEM_NIL, which points to a dummy node. */
393 struct mem_node *left, *right;
395 /* The parent of this node. In the root node, this is NULL. */
396 struct mem_node *parent;
398 /* Start and end of allocated region. */
399 void *start, *end;
401 /* Node color. */
402 enum {MEM_BLACK, MEM_RED} color;
404 /* Memory type. */
405 enum mem_type type;
408 /* Base address of stack. Set in main. */
410 Lisp_Object *stack_base;
412 /* Root of the tree describing allocated Lisp memory. */
414 static struct mem_node *mem_root;
416 /* Lowest and highest known address in the heap. */
418 static void *min_heap_address, *max_heap_address;
420 /* Sentinel node of the tree. */
422 static struct mem_node mem_z;
423 #define MEM_NIL &mem_z
425 static POINTER_TYPE *lisp_malloc P_ ((size_t, enum mem_type));
426 static struct Lisp_Vector *allocate_vectorlike P_ ((EMACS_INT, enum mem_type));
427 static void lisp_free P_ ((POINTER_TYPE *));
428 static void mark_stack P_ ((void));
429 static int live_vector_p P_ ((struct mem_node *, void *));
430 static int live_buffer_p P_ ((struct mem_node *, void *));
431 static int live_string_p P_ ((struct mem_node *, void *));
432 static int live_cons_p P_ ((struct mem_node *, void *));
433 static int live_symbol_p P_ ((struct mem_node *, void *));
434 static int live_float_p P_ ((struct mem_node *, void *));
435 static int live_misc_p P_ ((struct mem_node *, void *));
436 static void mark_maybe_object P_ ((Lisp_Object));
437 static void mark_memory P_ ((void *, void *));
438 static void mem_init P_ ((void));
439 static struct mem_node *mem_insert P_ ((void *, void *, enum mem_type));
440 static void mem_insert_fixup P_ ((struct mem_node *));
441 static void mem_rotate_left P_ ((struct mem_node *));
442 static void mem_rotate_right P_ ((struct mem_node *));
443 static void mem_delete P_ ((struct mem_node *));
444 static void mem_delete_fixup P_ ((struct mem_node *));
445 static INLINE struct mem_node *mem_find P_ ((void *));
447 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
448 static void check_gcpros P_ ((void));
449 #endif
451 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
453 /* Recording what needs to be marked for gc. */
455 struct gcpro *gcprolist;
457 /* Addresses of staticpro'd variables. Initialize it to a nonzero
458 value; otherwise some compilers put it into BSS. */
460 #define NSTATICS 1280
461 Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
463 /* Index of next unused slot in staticvec. */
465 int staticidx = 0;
467 static POINTER_TYPE *pure_alloc P_ ((size_t, int));
470 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
471 ALIGNMENT must be a power of 2. */
473 #define ALIGN(ptr, ALIGNMENT) \
474 ((POINTER_TYPE *) ((((EMACS_UINT)(ptr)) + (ALIGNMENT) - 1) \
475 & ~((ALIGNMENT) - 1)))
479 /************************************************************************
480 Malloc
481 ************************************************************************/
483 /* Function malloc calls this if it finds we are near exhausting storage. */
485 void
486 malloc_warning (str)
487 char *str;
489 pending_malloc_warning = str;
493 /* Display an already-pending malloc warning. */
495 void
496 display_malloc_warning ()
498 call3 (intern ("display-warning"),
499 intern ("alloc"),
500 build_string (pending_malloc_warning),
501 intern ("emergency"));
502 pending_malloc_warning = 0;
506 #ifdef DOUG_LEA_MALLOC
507 # define BYTES_USED (mallinfo ().arena)
508 #else
509 # define BYTES_USED _bytes_used
510 #endif
513 /* Called if malloc returns zero. */
515 void
516 memory_full ()
518 Vmemory_full = Qt;
520 #ifndef SYSTEM_MALLOC
521 bytes_used_when_full = BYTES_USED;
522 #endif
524 /* The first time we get here, free the spare memory. */
525 if (spare_memory)
527 free (spare_memory);
528 spare_memory = 0;
531 /* This used to call error, but if we've run out of memory, we could
532 get infinite recursion trying to build the string. */
533 while (1)
534 Fsignal (Qnil, Vmemory_signal_data);
538 /* Called if we can't allocate relocatable space for a buffer. */
540 void
541 buffer_memory_full ()
543 /* If buffers use the relocating allocator, no need to free
544 spare_memory, because we may have plenty of malloc space left
545 that we could get, and if we don't, the malloc that fails will
546 itself cause spare_memory to be freed. If buffers don't use the
547 relocating allocator, treat this like any other failing
548 malloc. */
550 #ifndef REL_ALLOC
551 memory_full ();
552 #endif
554 Vmemory_full = Qt;
556 /* This used to call error, but if we've run out of memory, we could
557 get infinite recursion trying to build the string. */
558 while (1)
559 Fsignal (Qnil, Vmemory_signal_data);
563 #ifdef XMALLOC_OVERRUN_CHECK
565 /* Check for overrun in malloc'ed buffers by wrapping a 16 byte header
566 and a 16 byte trailer around each block.
568 The header consists of 12 fixed bytes + a 4 byte integer contaning the
569 original block size, while the trailer consists of 16 fixed bytes.
571 The header is used to detect whether this block has been allocated
572 through these functions -- as it seems that some low-level libc
573 functions may bypass the malloc hooks.
577 #define XMALLOC_OVERRUN_CHECK_SIZE 16
579 static char xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE-4] =
580 { 0x9a, 0x9b, 0xae, 0xaf,
581 0xbf, 0xbe, 0xce, 0xcf,
582 0xea, 0xeb, 0xec, 0xed };
584 static char xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
585 { 0xaa, 0xab, 0xac, 0xad,
586 0xba, 0xbb, 0xbc, 0xbd,
587 0xca, 0xcb, 0xcc, 0xcd,
588 0xda, 0xdb, 0xdc, 0xdd };
590 /* Macros to insert and extract the block size in the header. */
592 #define XMALLOC_PUT_SIZE(ptr, size) \
593 (ptr[-1] = (size & 0xff), \
594 ptr[-2] = ((size >> 8) & 0xff), \
595 ptr[-3] = ((size >> 16) & 0xff), \
596 ptr[-4] = ((size >> 24) & 0xff))
598 #define XMALLOC_GET_SIZE(ptr) \
599 (size_t)((unsigned)(ptr[-1]) | \
600 ((unsigned)(ptr[-2]) << 8) | \
601 ((unsigned)(ptr[-3]) << 16) | \
602 ((unsigned)(ptr[-4]) << 24))
605 /* The call depth in overrun_check functions. For example, this might happen:
606 xmalloc()
607 overrun_check_malloc()
608 -> malloc -> (via hook)_-> emacs_blocked_malloc
609 -> overrun_check_malloc
610 call malloc (hooks are NULL, so real malloc is called).
611 malloc returns 10000.
612 add overhead, return 10016.
613 <- (back in overrun_check_malloc)
614 add overhead again, return 10032
615 xmalloc returns 10032.
617 (time passes).
619 xfree(10032)
620 overrun_check_free(10032)
621 decrease overhed
622 free(10016) <- crash, because 10000 is the original pointer. */
624 static int check_depth;
626 /* Like malloc, but wraps allocated block with header and trailer. */
628 POINTER_TYPE *
629 overrun_check_malloc (size)
630 size_t size;
632 register unsigned char *val;
633 size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
635 val = (unsigned char *) malloc (size + overhead);
636 if (val && check_depth == 1)
638 bcopy (xmalloc_overrun_check_header, val, XMALLOC_OVERRUN_CHECK_SIZE - 4);
639 val += XMALLOC_OVERRUN_CHECK_SIZE;
640 XMALLOC_PUT_SIZE(val, size);
641 bcopy (xmalloc_overrun_check_trailer, val + size, XMALLOC_OVERRUN_CHECK_SIZE);
643 --check_depth;
644 return (POINTER_TYPE *)val;
648 /* Like realloc, but checks old block for overrun, and wraps new block
649 with header and trailer. */
651 POINTER_TYPE *
652 overrun_check_realloc (block, size)
653 POINTER_TYPE *block;
654 size_t size;
656 register unsigned char *val = (unsigned char *)block;
657 size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
659 if (val
660 && check_depth == 1
661 && bcmp (xmalloc_overrun_check_header,
662 val - XMALLOC_OVERRUN_CHECK_SIZE,
663 XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
665 size_t osize = XMALLOC_GET_SIZE (val);
666 if (bcmp (xmalloc_overrun_check_trailer,
667 val + osize,
668 XMALLOC_OVERRUN_CHECK_SIZE))
669 abort ();
670 bzero (val + osize, XMALLOC_OVERRUN_CHECK_SIZE);
671 val -= XMALLOC_OVERRUN_CHECK_SIZE;
672 bzero (val, XMALLOC_OVERRUN_CHECK_SIZE);
675 val = (unsigned char *) realloc ((POINTER_TYPE *)val, size + overhead);
677 if (val && check_depth == 1)
679 bcopy (xmalloc_overrun_check_header, val, XMALLOC_OVERRUN_CHECK_SIZE - 4);
680 val += XMALLOC_OVERRUN_CHECK_SIZE;
681 XMALLOC_PUT_SIZE(val, size);
682 bcopy (xmalloc_overrun_check_trailer, val + size, XMALLOC_OVERRUN_CHECK_SIZE);
684 --check_depth;
685 return (POINTER_TYPE *)val;
688 /* Like free, but checks block for overrun. */
690 void
691 overrun_check_free (block)
692 POINTER_TYPE *block;
694 unsigned char *val = (unsigned char *)block;
696 ++check_depth;
697 if (val
698 && check_depth == 1
699 && bcmp (xmalloc_overrun_check_header,
700 val - XMALLOC_OVERRUN_CHECK_SIZE,
701 XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
703 size_t osize = XMALLOC_GET_SIZE (val);
704 if (bcmp (xmalloc_overrun_check_trailer,
705 val + osize,
706 XMALLOC_OVERRUN_CHECK_SIZE))
707 abort ();
708 #ifdef XMALLOC_CLEAR_FREE_MEMORY
709 val -= XMALLOC_OVERRUN_CHECK_SIZE;
710 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_SIZE*2);
711 #else
712 bzero (val + osize, XMALLOC_OVERRUN_CHECK_SIZE);
713 val -= XMALLOC_OVERRUN_CHECK_SIZE;
714 bzero (val, XMALLOC_OVERRUN_CHECK_SIZE);
715 #endif
718 free (val);
719 --check_depth;
722 #undef malloc
723 #undef realloc
724 #undef free
725 #define malloc overrun_check_malloc
726 #define realloc overrun_check_realloc
727 #define free overrun_check_free
728 #endif
731 /* Like malloc but check for no memory and block interrupt input.. */
733 POINTER_TYPE *
734 xmalloc (size)
735 size_t size;
737 register POINTER_TYPE *val;
739 BLOCK_INPUT;
740 val = (POINTER_TYPE *) malloc (size);
741 UNBLOCK_INPUT;
743 if (!val && size)
744 memory_full ();
745 return val;
749 /* Like realloc but check for no memory and block interrupt input.. */
751 POINTER_TYPE *
752 xrealloc (block, size)
753 POINTER_TYPE *block;
754 size_t size;
756 register POINTER_TYPE *val;
758 BLOCK_INPUT;
759 /* We must call malloc explicitly when BLOCK is 0, since some
760 reallocs don't do this. */
761 if (! block)
762 val = (POINTER_TYPE *) malloc (size);
763 else
764 val = (POINTER_TYPE *) realloc (block, size);
765 UNBLOCK_INPUT;
767 if (!val && size) memory_full ();
768 return val;
772 /* Like free but block interrupt input. */
774 void
775 xfree (block)
776 POINTER_TYPE *block;
778 BLOCK_INPUT;
779 free (block);
780 UNBLOCK_INPUT;
784 /* Like strdup, but uses xmalloc. */
786 char *
787 xstrdup (s)
788 const char *s;
790 size_t len = strlen (s) + 1;
791 char *p = (char *) xmalloc (len);
792 bcopy (s, p, len);
793 return p;
797 /* Unwind for SAFE_ALLOCA */
799 Lisp_Object
800 safe_alloca_unwind (arg)
801 Lisp_Object arg;
803 register struct Lisp_Save_Value *p = XSAVE_VALUE (arg);
805 p->dogc = 0;
806 xfree (p->pointer);
807 p->pointer = 0;
808 free_misc (arg);
809 return Qnil;
813 /* Like malloc but used for allocating Lisp data. NBYTES is the
814 number of bytes to allocate, TYPE describes the intended use of the
815 allcated memory block (for strings, for conses, ...). */
817 #ifndef USE_LSB_TAG
818 static void *lisp_malloc_loser;
819 #endif
821 static POINTER_TYPE *
822 lisp_malloc (nbytes, type)
823 size_t nbytes;
824 enum mem_type type;
826 register void *val;
828 BLOCK_INPUT;
830 #ifdef GC_MALLOC_CHECK
831 allocated_mem_type = type;
832 #endif
834 val = (void *) malloc (nbytes);
836 #ifndef USE_LSB_TAG
837 /* If the memory just allocated cannot be addressed thru a Lisp
838 object's pointer, and it needs to be,
839 that's equivalent to running out of memory. */
840 if (val && type != MEM_TYPE_NON_LISP)
842 Lisp_Object tem;
843 XSETCONS (tem, (char *) val + nbytes - 1);
844 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
846 lisp_malloc_loser = val;
847 free (val);
848 val = 0;
851 #endif
853 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
854 if (val && type != MEM_TYPE_NON_LISP)
855 mem_insert (val, (char *) val + nbytes, type);
856 #endif
858 UNBLOCK_INPUT;
859 if (!val && nbytes)
860 memory_full ();
861 return val;
864 /* Free BLOCK. This must be called to free memory allocated with a
865 call to lisp_malloc. */
867 static void
868 lisp_free (block)
869 POINTER_TYPE *block;
871 BLOCK_INPUT;
872 free (block);
873 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
874 mem_delete (mem_find (block));
875 #endif
876 UNBLOCK_INPUT;
879 /* Allocation of aligned blocks of memory to store Lisp data. */
880 /* The entry point is lisp_align_malloc which returns blocks of at most */
881 /* BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
884 /* BLOCK_ALIGN has to be a power of 2. */
885 #define BLOCK_ALIGN (1 << 10)
887 /* Padding to leave at the end of a malloc'd block. This is to give
888 malloc a chance to minimize the amount of memory wasted to alignment.
889 It should be tuned to the particular malloc library used.
890 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
891 posix_memalign on the other hand would ideally prefer a value of 4
892 because otherwise, there's 1020 bytes wasted between each ablocks.
893 In Emacs, testing shows that those 1020 can most of the time be
894 efficiently used by malloc to place other objects, so a value of 0 can
895 still preferable unless you have a lot of aligned blocks and virtually
896 nothing else. */
897 #define BLOCK_PADDING 0
898 #define BLOCK_BYTES \
899 (BLOCK_ALIGN - sizeof (struct ablock *) - BLOCK_PADDING)
901 /* Internal data structures and constants. */
903 #define ABLOCKS_SIZE 16
905 /* An aligned block of memory. */
906 struct ablock
908 union
910 char payload[BLOCK_BYTES];
911 struct ablock *next_free;
912 } x;
913 /* `abase' is the aligned base of the ablocks. */
914 /* It is overloaded to hold the virtual `busy' field that counts
915 the number of used ablock in the parent ablocks.
916 The first ablock has the `busy' field, the others have the `abase'
917 field. To tell the difference, we assume that pointers will have
918 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
919 is used to tell whether the real base of the parent ablocks is `abase'
920 (if not, the word before the first ablock holds a pointer to the
921 real base). */
922 struct ablocks *abase;
923 /* The padding of all but the last ablock is unused. The padding of
924 the last ablock in an ablocks is not allocated. */
925 #if BLOCK_PADDING
926 char padding[BLOCK_PADDING];
927 #endif
930 /* A bunch of consecutive aligned blocks. */
931 struct ablocks
933 struct ablock blocks[ABLOCKS_SIZE];
936 /* Size of the block requested from malloc or memalign. */
937 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
939 #define ABLOCK_ABASE(block) \
940 (((unsigned long) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
941 ? (struct ablocks *)(block) \
942 : (block)->abase)
944 /* Virtual `busy' field. */
945 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
947 /* Pointer to the (not necessarily aligned) malloc block. */
948 #ifdef HAVE_POSIX_MEMALIGN
949 #define ABLOCKS_BASE(abase) (abase)
950 #else
951 #define ABLOCKS_BASE(abase) \
952 (1 & (long) ABLOCKS_BUSY (abase) ? abase : ((void**)abase)[-1])
953 #endif
955 /* The list of free ablock. */
956 static struct ablock *free_ablock;
958 /* Allocate an aligned block of nbytes.
959 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
960 smaller or equal to BLOCK_BYTES. */
961 static POINTER_TYPE *
962 lisp_align_malloc (nbytes, type)
963 size_t nbytes;
964 enum mem_type type;
966 void *base, *val;
967 struct ablocks *abase;
969 eassert (nbytes <= BLOCK_BYTES);
971 BLOCK_INPUT;
973 #ifdef GC_MALLOC_CHECK
974 allocated_mem_type = type;
975 #endif
977 if (!free_ablock)
979 int i;
980 EMACS_INT aligned; /* int gets warning casting to 64-bit pointer. */
982 #ifdef DOUG_LEA_MALLOC
983 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
984 because mapped region contents are not preserved in
985 a dumped Emacs. */
986 mallopt (M_MMAP_MAX, 0);
987 #endif
989 #ifdef HAVE_POSIX_MEMALIGN
991 int err = posix_memalign (&base, BLOCK_ALIGN, ABLOCKS_BYTES);
992 if (err)
993 base = NULL;
994 abase = base;
996 #else
997 base = malloc (ABLOCKS_BYTES);
998 abase = ALIGN (base, BLOCK_ALIGN);
999 #endif
1001 if (base == 0)
1003 UNBLOCK_INPUT;
1004 memory_full ();
1007 aligned = (base == abase);
1008 if (!aligned)
1009 ((void**)abase)[-1] = base;
1011 #ifdef DOUG_LEA_MALLOC
1012 /* Back to a reasonable maximum of mmap'ed areas. */
1013 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1014 #endif
1016 #ifndef USE_LSB_TAG
1017 /* If the memory just allocated cannot be addressed thru a Lisp
1018 object's pointer, and it needs to be, that's equivalent to
1019 running out of memory. */
1020 if (type != MEM_TYPE_NON_LISP)
1022 Lisp_Object tem;
1023 char *end = (char *) base + ABLOCKS_BYTES - 1;
1024 XSETCONS (tem, end);
1025 if ((char *) XCONS (tem) != end)
1027 lisp_malloc_loser = base;
1028 free (base);
1029 UNBLOCK_INPUT;
1030 memory_full ();
1033 #endif
1035 /* Initialize the blocks and put them on the free list.
1036 Is `base' was not properly aligned, we can't use the last block. */
1037 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1039 abase->blocks[i].abase = abase;
1040 abase->blocks[i].x.next_free = free_ablock;
1041 free_ablock = &abase->blocks[i];
1043 ABLOCKS_BUSY (abase) = (struct ablocks *) (long) aligned;
1045 eassert (0 == ((EMACS_UINT)abase) % BLOCK_ALIGN);
1046 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1047 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1048 eassert (ABLOCKS_BASE (abase) == base);
1049 eassert (aligned == (long) ABLOCKS_BUSY (abase));
1052 abase = ABLOCK_ABASE (free_ablock);
1053 ABLOCKS_BUSY (abase) = (struct ablocks *) (2 + (long) ABLOCKS_BUSY (abase));
1054 val = free_ablock;
1055 free_ablock = free_ablock->x.next_free;
1057 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1058 if (val && type != MEM_TYPE_NON_LISP)
1059 mem_insert (val, (char *) val + nbytes, type);
1060 #endif
1062 UNBLOCK_INPUT;
1063 if (!val && nbytes)
1064 memory_full ();
1066 eassert (0 == ((EMACS_UINT)val) % BLOCK_ALIGN);
1067 return val;
1070 static void
1071 lisp_align_free (block)
1072 POINTER_TYPE *block;
1074 struct ablock *ablock = block;
1075 struct ablocks *abase = ABLOCK_ABASE (ablock);
1077 BLOCK_INPUT;
1078 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1079 mem_delete (mem_find (block));
1080 #endif
1081 /* Put on free list. */
1082 ablock->x.next_free = free_ablock;
1083 free_ablock = ablock;
1084 /* Update busy count. */
1085 ABLOCKS_BUSY (abase) = (struct ablocks *) (-2 + (long) ABLOCKS_BUSY (abase));
1087 if (2 > (long) ABLOCKS_BUSY (abase))
1088 { /* All the blocks are free. */
1089 int i = 0, aligned = (long) ABLOCKS_BUSY (abase);
1090 struct ablock **tem = &free_ablock;
1091 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1093 while (*tem)
1095 if (*tem >= (struct ablock *) abase && *tem < atop)
1097 i++;
1098 *tem = (*tem)->x.next_free;
1100 else
1101 tem = &(*tem)->x.next_free;
1103 eassert ((aligned & 1) == aligned);
1104 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1105 free (ABLOCKS_BASE (abase));
1107 UNBLOCK_INPUT;
1110 /* Return a new buffer structure allocated from the heap with
1111 a call to lisp_malloc. */
1113 struct buffer *
1114 allocate_buffer ()
1116 struct buffer *b
1117 = (struct buffer *) lisp_malloc (sizeof (struct buffer),
1118 MEM_TYPE_BUFFER);
1119 return b;
1123 #ifndef SYSTEM_MALLOC
1125 /* If we released our reserve (due to running out of memory),
1126 and we have a fair amount free once again,
1127 try to set aside another reserve in case we run out once more.
1129 This is called when a relocatable block is freed in ralloc.c. */
1131 void
1132 refill_memory_reserve ()
1134 if (spare_memory == 0)
1135 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
1139 /* Arranging to disable input signals while we're in malloc.
1141 This only works with GNU malloc. To help out systems which can't
1142 use GNU malloc, all the calls to malloc, realloc, and free
1143 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
1144 pair; unfortunately, we have no idea what C library functions
1145 might call malloc, so we can't really protect them unless you're
1146 using GNU malloc. Fortunately, most of the major operating systems
1147 can use GNU malloc. */
1149 #ifndef SYNC_INPUT
1151 #ifndef DOUG_LEA_MALLOC
1152 extern void * (*__malloc_hook) P_ ((size_t));
1153 extern void * (*__realloc_hook) P_ ((void *, size_t));
1154 extern void (*__free_hook) P_ ((void *));
1155 /* Else declared in malloc.h, perhaps with an extra arg. */
1156 #endif /* DOUG_LEA_MALLOC */
1157 static void * (*old_malloc_hook) ();
1158 static void * (*old_realloc_hook) ();
1159 static void (*old_free_hook) ();
1161 /* This function is used as the hook for free to call. */
1163 static void
1164 emacs_blocked_free (ptr)
1165 void *ptr;
1167 BLOCK_INPUT_ALLOC;
1169 #ifdef GC_MALLOC_CHECK
1170 if (ptr)
1172 struct mem_node *m;
1174 m = mem_find (ptr);
1175 if (m == MEM_NIL || m->start != ptr)
1177 fprintf (stderr,
1178 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
1179 abort ();
1181 else
1183 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
1184 mem_delete (m);
1187 #endif /* GC_MALLOC_CHECK */
1189 __free_hook = old_free_hook;
1190 free (ptr);
1192 /* If we released our reserve (due to running out of memory),
1193 and we have a fair amount free once again,
1194 try to set aside another reserve in case we run out once more. */
1195 if (spare_memory == 0
1196 /* Verify there is enough space that even with the malloc
1197 hysteresis this call won't run out again.
1198 The code here is correct as long as SPARE_MEMORY
1199 is substantially larger than the block size malloc uses. */
1200 && (bytes_used_when_full
1201 > BYTES_USED + max (malloc_hysteresis, 4) * SPARE_MEMORY))
1202 spare_memory = (char *) malloc ((size_t) SPARE_MEMORY);
1204 __free_hook = emacs_blocked_free;
1205 UNBLOCK_INPUT_ALLOC;
1209 /* This function is the malloc hook that Emacs uses. */
1211 static void *
1212 emacs_blocked_malloc (size)
1213 size_t size;
1215 void *value;
1217 BLOCK_INPUT_ALLOC;
1218 __malloc_hook = old_malloc_hook;
1219 #ifdef DOUG_LEA_MALLOC
1220 mallopt (M_TOP_PAD, malloc_hysteresis * 4096);
1221 #else
1222 __malloc_extra_blocks = malloc_hysteresis;
1223 #endif
1225 value = (void *) malloc (size);
1227 #ifdef GC_MALLOC_CHECK
1229 struct mem_node *m = mem_find (value);
1230 if (m != MEM_NIL)
1232 fprintf (stderr, "Malloc returned %p which is already in use\n",
1233 value);
1234 fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
1235 m->start, m->end, (char *) m->end - (char *) m->start,
1236 m->type);
1237 abort ();
1240 if (!dont_register_blocks)
1242 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
1243 allocated_mem_type = MEM_TYPE_NON_LISP;
1246 #endif /* GC_MALLOC_CHECK */
1248 __malloc_hook = emacs_blocked_malloc;
1249 UNBLOCK_INPUT_ALLOC;
1251 /* fprintf (stderr, "%p malloc\n", value); */
1252 return value;
1256 /* This function is the realloc hook that Emacs uses. */
1258 static void *
1259 emacs_blocked_realloc (ptr, size)
1260 void *ptr;
1261 size_t size;
1263 void *value;
1265 BLOCK_INPUT_ALLOC;
1266 __realloc_hook = old_realloc_hook;
1268 #ifdef GC_MALLOC_CHECK
1269 if (ptr)
1271 struct mem_node *m = mem_find (ptr);
1272 if (m == MEM_NIL || m->start != ptr)
1274 fprintf (stderr,
1275 "Realloc of %p which wasn't allocated with malloc\n",
1276 ptr);
1277 abort ();
1280 mem_delete (m);
1283 /* fprintf (stderr, "%p -> realloc\n", ptr); */
1285 /* Prevent malloc from registering blocks. */
1286 dont_register_blocks = 1;
1287 #endif /* GC_MALLOC_CHECK */
1289 value = (void *) realloc (ptr, size);
1291 #ifdef GC_MALLOC_CHECK
1292 dont_register_blocks = 0;
1295 struct mem_node *m = mem_find (value);
1296 if (m != MEM_NIL)
1298 fprintf (stderr, "Realloc returns memory that is already in use\n");
1299 abort ();
1302 /* Can't handle zero size regions in the red-black tree. */
1303 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
1306 /* fprintf (stderr, "%p <- realloc\n", value); */
1307 #endif /* GC_MALLOC_CHECK */
1309 __realloc_hook = emacs_blocked_realloc;
1310 UNBLOCK_INPUT_ALLOC;
1312 return value;
1316 #ifdef HAVE_GTK_AND_PTHREAD
1317 /* Called from Fdump_emacs so that when the dumped Emacs starts, it has a
1318 normal malloc. Some thread implementations need this as they call
1319 malloc before main. The pthread_self call in BLOCK_INPUT_ALLOC then
1320 calls malloc because it is the first call, and we have an endless loop. */
1322 void
1323 reset_malloc_hooks ()
1325 __free_hook = 0;
1326 __malloc_hook = 0;
1327 __realloc_hook = 0;
1329 #endif /* HAVE_GTK_AND_PTHREAD */
1332 /* Called from main to set up malloc to use our hooks. */
1334 void
1335 uninterrupt_malloc ()
1337 #ifdef HAVE_GTK_AND_PTHREAD
1338 pthread_mutexattr_t attr;
1340 /* GLIBC has a faster way to do this, but lets keep it portable.
1341 This is according to the Single UNIX Specification. */
1342 pthread_mutexattr_init (&attr);
1343 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1344 pthread_mutex_init (&alloc_mutex, &attr);
1345 #endif /* HAVE_GTK_AND_PTHREAD */
1347 if (__free_hook != emacs_blocked_free)
1348 old_free_hook = __free_hook;
1349 __free_hook = emacs_blocked_free;
1351 if (__malloc_hook != emacs_blocked_malloc)
1352 old_malloc_hook = __malloc_hook;
1353 __malloc_hook = emacs_blocked_malloc;
1355 if (__realloc_hook != emacs_blocked_realloc)
1356 old_realloc_hook = __realloc_hook;
1357 __realloc_hook = emacs_blocked_realloc;
1360 #endif /* not SYNC_INPUT */
1361 #endif /* not SYSTEM_MALLOC */
1365 /***********************************************************************
1366 Interval Allocation
1367 ***********************************************************************/
1369 /* Number of intervals allocated in an interval_block structure.
1370 The 1020 is 1024 minus malloc overhead. */
1372 #define INTERVAL_BLOCK_SIZE \
1373 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1375 /* Intervals are allocated in chunks in form of an interval_block
1376 structure. */
1378 struct interval_block
1380 /* Place `intervals' first, to preserve alignment. */
1381 struct interval intervals[INTERVAL_BLOCK_SIZE];
1382 struct interval_block *next;
1385 /* Current interval block. Its `next' pointer points to older
1386 blocks. */
1388 struct interval_block *interval_block;
1390 /* Index in interval_block above of the next unused interval
1391 structure. */
1393 static int interval_block_index;
1395 /* Number of free and live intervals. */
1397 static int total_free_intervals, total_intervals;
1399 /* List of free intervals. */
1401 INTERVAL interval_free_list;
1403 /* Total number of interval blocks now in use. */
1405 int n_interval_blocks;
1408 /* Initialize interval allocation. */
1410 static void
1411 init_intervals ()
1413 interval_block = NULL;
1414 interval_block_index = INTERVAL_BLOCK_SIZE;
1415 interval_free_list = 0;
1416 n_interval_blocks = 0;
1420 /* Return a new interval. */
1422 INTERVAL
1423 make_interval ()
1425 INTERVAL val;
1427 if (interval_free_list)
1429 val = interval_free_list;
1430 interval_free_list = INTERVAL_PARENT (interval_free_list);
1432 else
1434 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1436 register struct interval_block *newi;
1438 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
1439 MEM_TYPE_NON_LISP);
1441 newi->next = interval_block;
1442 interval_block = newi;
1443 interval_block_index = 0;
1444 n_interval_blocks++;
1446 val = &interval_block->intervals[interval_block_index++];
1448 consing_since_gc += sizeof (struct interval);
1449 intervals_consed++;
1450 RESET_INTERVAL (val);
1451 val->gcmarkbit = 0;
1452 return val;
1456 /* Mark Lisp objects in interval I. */
1458 static void
1459 mark_interval (i, dummy)
1460 register INTERVAL i;
1461 Lisp_Object dummy;
1463 eassert (!i->gcmarkbit); /* Intervals are never shared. */
1464 i->gcmarkbit = 1;
1465 mark_object (i->plist);
1469 /* Mark the interval tree rooted in TREE. Don't call this directly;
1470 use the macro MARK_INTERVAL_TREE instead. */
1472 static void
1473 mark_interval_tree (tree)
1474 register INTERVAL tree;
1476 /* No need to test if this tree has been marked already; this
1477 function is always called through the MARK_INTERVAL_TREE macro,
1478 which takes care of that. */
1480 traverse_intervals_noorder (tree, mark_interval, Qnil);
1484 /* Mark the interval tree rooted in I. */
1486 #define MARK_INTERVAL_TREE(i) \
1487 do { \
1488 if (!NULL_INTERVAL_P (i) && !i->gcmarkbit) \
1489 mark_interval_tree (i); \
1490 } while (0)
1493 #define UNMARK_BALANCE_INTERVALS(i) \
1494 do { \
1495 if (! NULL_INTERVAL_P (i)) \
1496 (i) = balance_intervals (i); \
1497 } while (0)
1500 /* Number support. If NO_UNION_TYPE isn't in effect, we
1501 can't create number objects in macros. */
1502 #ifndef make_number
1503 Lisp_Object
1504 make_number (n)
1505 EMACS_INT n;
1507 Lisp_Object obj;
1508 obj.s.val = n;
1509 obj.s.type = Lisp_Int;
1510 return obj;
1512 #endif
1514 /***********************************************************************
1515 String Allocation
1516 ***********************************************************************/
1518 /* Lisp_Strings are allocated in string_block structures. When a new
1519 string_block is allocated, all the Lisp_Strings it contains are
1520 added to a free-list string_free_list. When a new Lisp_String is
1521 needed, it is taken from that list. During the sweep phase of GC,
1522 string_blocks that are entirely free are freed, except two which
1523 we keep.
1525 String data is allocated from sblock structures. Strings larger
1526 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1527 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1529 Sblocks consist internally of sdata structures, one for each
1530 Lisp_String. The sdata structure points to the Lisp_String it
1531 belongs to. The Lisp_String points back to the `u.data' member of
1532 its sdata structure.
1534 When a Lisp_String is freed during GC, it is put back on
1535 string_free_list, and its `data' member and its sdata's `string'
1536 pointer is set to null. The size of the string is recorded in the
1537 `u.nbytes' member of the sdata. So, sdata structures that are no
1538 longer used, can be easily recognized, and it's easy to compact the
1539 sblocks of small strings which we do in compact_small_strings. */
1541 /* Size in bytes of an sblock structure used for small strings. This
1542 is 8192 minus malloc overhead. */
1544 #define SBLOCK_SIZE 8188
1546 /* Strings larger than this are considered large strings. String data
1547 for large strings is allocated from individual sblocks. */
1549 #define LARGE_STRING_BYTES 1024
1551 /* Structure describing string memory sub-allocated from an sblock.
1552 This is where the contents of Lisp strings are stored. */
1554 struct sdata
1556 /* Back-pointer to the string this sdata belongs to. If null, this
1557 structure is free, and the NBYTES member of the union below
1558 contains the string's byte size (the same value that STRING_BYTES
1559 would return if STRING were non-null). If non-null, STRING_BYTES
1560 (STRING) is the size of the data, and DATA contains the string's
1561 contents. */
1562 struct Lisp_String *string;
1564 #ifdef GC_CHECK_STRING_BYTES
1566 EMACS_INT nbytes;
1567 unsigned char data[1];
1569 #define SDATA_NBYTES(S) (S)->nbytes
1570 #define SDATA_DATA(S) (S)->data
1572 #else /* not GC_CHECK_STRING_BYTES */
1574 union
1576 /* When STRING in non-null. */
1577 unsigned char data[1];
1579 /* When STRING is null. */
1580 EMACS_INT nbytes;
1581 } u;
1584 #define SDATA_NBYTES(S) (S)->u.nbytes
1585 #define SDATA_DATA(S) (S)->u.data
1587 #endif /* not GC_CHECK_STRING_BYTES */
1591 /* Structure describing a block of memory which is sub-allocated to
1592 obtain string data memory for strings. Blocks for small strings
1593 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1594 as large as needed. */
1596 struct sblock
1598 /* Next in list. */
1599 struct sblock *next;
1601 /* Pointer to the next free sdata block. This points past the end
1602 of the sblock if there isn't any space left in this block. */
1603 struct sdata *next_free;
1605 /* Start of data. */
1606 struct sdata first_data;
1609 /* Number of Lisp strings in a string_block structure. The 1020 is
1610 1024 minus malloc overhead. */
1612 #define STRING_BLOCK_SIZE \
1613 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1615 /* Structure describing a block from which Lisp_String structures
1616 are allocated. */
1618 struct string_block
1620 /* Place `strings' first, to preserve alignment. */
1621 struct Lisp_String strings[STRING_BLOCK_SIZE];
1622 struct string_block *next;
1625 /* Head and tail of the list of sblock structures holding Lisp string
1626 data. We always allocate from current_sblock. The NEXT pointers
1627 in the sblock structures go from oldest_sblock to current_sblock. */
1629 static struct sblock *oldest_sblock, *current_sblock;
1631 /* List of sblocks for large strings. */
1633 static struct sblock *large_sblocks;
1635 /* List of string_block structures, and how many there are. */
1637 static struct string_block *string_blocks;
1638 static int n_string_blocks;
1640 /* Free-list of Lisp_Strings. */
1642 static struct Lisp_String *string_free_list;
1644 /* Number of live and free Lisp_Strings. */
1646 static int total_strings, total_free_strings;
1648 /* Number of bytes used by live strings. */
1650 static int total_string_size;
1652 /* Given a pointer to a Lisp_String S which is on the free-list
1653 string_free_list, return a pointer to its successor in the
1654 free-list. */
1656 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1658 /* Return a pointer to the sdata structure belonging to Lisp string S.
1659 S must be live, i.e. S->data must not be null. S->data is actually
1660 a pointer to the `u.data' member of its sdata structure; the
1661 structure starts at a constant offset in front of that. */
1663 #ifdef GC_CHECK_STRING_BYTES
1665 #define SDATA_OF_STRING(S) \
1666 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *) \
1667 - sizeof (EMACS_INT)))
1669 #else /* not GC_CHECK_STRING_BYTES */
1671 #define SDATA_OF_STRING(S) \
1672 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))
1674 #endif /* not GC_CHECK_STRING_BYTES */
1677 #ifdef GC_CHECK_STRING_OVERRUN
1679 /* We check for overrun in string data blocks by appending a small
1680 "cookie" after each allocated string data block, and check for the
1681 presense of this cookie during GC. */
1683 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1684 static char string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1685 { 0xde, 0xad, 0xbe, 0xef };
1687 #else
1688 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1689 #endif
1691 /* Value is the size of an sdata structure large enough to hold NBYTES
1692 bytes of string data. The value returned includes a terminating
1693 NUL byte, the size of the sdata structure, and padding. */
1695 #ifdef GC_CHECK_STRING_BYTES
1697 #define SDATA_SIZE(NBYTES) \
1698 ((sizeof (struct Lisp_String *) \
1699 + (NBYTES) + 1 \
1700 + sizeof (EMACS_INT) \
1701 + sizeof (EMACS_INT) - 1) \
1702 & ~(sizeof (EMACS_INT) - 1))
1704 #else /* not GC_CHECK_STRING_BYTES */
1706 #define SDATA_SIZE(NBYTES) \
1707 ((sizeof (struct Lisp_String *) \
1708 + (NBYTES) + 1 \
1709 + sizeof (EMACS_INT) - 1) \
1710 & ~(sizeof (EMACS_INT) - 1))
1712 #endif /* not GC_CHECK_STRING_BYTES */
1714 /* Extra bytes to allocate for each string. */
1716 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1718 /* Initialize string allocation. Called from init_alloc_once. */
1720 void
1721 init_strings ()
1723 total_strings = total_free_strings = total_string_size = 0;
1724 oldest_sblock = current_sblock = large_sblocks = NULL;
1725 string_blocks = NULL;
1726 n_string_blocks = 0;
1727 string_free_list = NULL;
1731 #ifdef GC_CHECK_STRING_BYTES
1733 static int check_string_bytes_count;
1735 void check_string_bytes P_ ((int));
1736 void check_sblock P_ ((struct sblock *));
1738 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1741 /* Like GC_STRING_BYTES, but with debugging check. */
1744 string_bytes (s)
1745 struct Lisp_String *s;
1747 int nbytes = (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1748 if (!PURE_POINTER_P (s)
1749 && s->data
1750 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1751 abort ();
1752 return nbytes;
1755 /* Check validity of Lisp strings' string_bytes member in B. */
1757 void
1758 check_sblock (b)
1759 struct sblock *b;
1761 struct sdata *from, *end, *from_end;
1763 end = b->next_free;
1765 for (from = &b->first_data; from < end; from = from_end)
1767 /* Compute the next FROM here because copying below may
1768 overwrite data we need to compute it. */
1769 int nbytes;
1771 /* Check that the string size recorded in the string is the
1772 same as the one recorded in the sdata structure. */
1773 if (from->string)
1774 CHECK_STRING_BYTES (from->string);
1776 if (from->string)
1777 nbytes = GC_STRING_BYTES (from->string);
1778 else
1779 nbytes = SDATA_NBYTES (from);
1781 nbytes = SDATA_SIZE (nbytes);
1782 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1787 /* Check validity of Lisp strings' string_bytes member. ALL_P
1788 non-zero means check all strings, otherwise check only most
1789 recently allocated strings. Used for hunting a bug. */
1791 void
1792 check_string_bytes (all_p)
1793 int all_p;
1795 if (all_p)
1797 struct sblock *b;
1799 for (b = large_sblocks; b; b = b->next)
1801 struct Lisp_String *s = b->first_data.string;
1802 if (s)
1803 CHECK_STRING_BYTES (s);
1806 for (b = oldest_sblock; b; b = b->next)
1807 check_sblock (b);
1809 else
1810 check_sblock (current_sblock);
1813 #endif /* GC_CHECK_STRING_BYTES */
1815 #ifdef GC_CHECK_STRING_FREE_LIST
1817 /* Walk through the string free list looking for bogus next pointers.
1818 This may catch buffer overrun from a previous string. */
1820 static void
1821 check_string_free_list ()
1823 struct Lisp_String *s;
1825 /* Pop a Lisp_String off the free-list. */
1826 s = string_free_list;
1827 while (s != NULL)
1829 if ((unsigned)s < 1024)
1830 abort();
1831 s = NEXT_FREE_LISP_STRING (s);
1834 #else
1835 #define check_string_free_list()
1836 #endif
1838 /* Return a new Lisp_String. */
1840 static struct Lisp_String *
1841 allocate_string ()
1843 struct Lisp_String *s;
1845 /* If the free-list is empty, allocate a new string_block, and
1846 add all the Lisp_Strings in it to the free-list. */
1847 if (string_free_list == NULL)
1849 struct string_block *b;
1850 int i;
1852 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1853 bzero (b, sizeof *b);
1854 b->next = string_blocks;
1855 string_blocks = b;
1856 ++n_string_blocks;
1858 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1860 s = b->strings + i;
1861 NEXT_FREE_LISP_STRING (s) = string_free_list;
1862 string_free_list = s;
1865 total_free_strings += STRING_BLOCK_SIZE;
1868 check_string_free_list ();
1870 /* Pop a Lisp_String off the free-list. */
1871 s = string_free_list;
1872 string_free_list = NEXT_FREE_LISP_STRING (s);
1874 /* Probably not strictly necessary, but play it safe. */
1875 bzero (s, sizeof *s);
1877 --total_free_strings;
1878 ++total_strings;
1879 ++strings_consed;
1880 consing_since_gc += sizeof *s;
1882 #ifdef GC_CHECK_STRING_BYTES
1883 if (!noninteractive
1884 #ifdef MAC_OS8
1885 && current_sblock
1886 #endif
1889 if (++check_string_bytes_count == 200)
1891 check_string_bytes_count = 0;
1892 check_string_bytes (1);
1894 else
1895 check_string_bytes (0);
1897 #endif /* GC_CHECK_STRING_BYTES */
1899 return s;
1903 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1904 plus a NUL byte at the end. Allocate an sdata structure for S, and
1905 set S->data to its `u.data' member. Store a NUL byte at the end of
1906 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1907 S->data if it was initially non-null. */
1909 void
1910 allocate_string_data (s, nchars, nbytes)
1911 struct Lisp_String *s;
1912 int nchars, nbytes;
1914 struct sdata *data, *old_data;
1915 struct sblock *b;
1916 int needed, old_nbytes;
1918 /* Determine the number of bytes needed to store NBYTES bytes
1919 of string data. */
1920 needed = SDATA_SIZE (nbytes);
1922 if (nbytes > LARGE_STRING_BYTES)
1924 size_t size = sizeof *b - sizeof (struct sdata) + needed;
1926 #ifdef DOUG_LEA_MALLOC
1927 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1928 because mapped region contents are not preserved in
1929 a dumped Emacs.
1931 In case you think of allowing it in a dumped Emacs at the
1932 cost of not being able to re-dump, there's another reason:
1933 mmap'ed data typically have an address towards the top of the
1934 address space, which won't fit into an EMACS_INT (at least on
1935 32-bit systems with the current tagging scheme). --fx */
1936 BLOCK_INPUT;
1937 mallopt (M_MMAP_MAX, 0);
1938 UNBLOCK_INPUT;
1939 #endif
1941 b = (struct sblock *) lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
1943 #ifdef DOUG_LEA_MALLOC
1944 /* Back to a reasonable maximum of mmap'ed areas. */
1945 BLOCK_INPUT;
1946 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1947 UNBLOCK_INPUT;
1948 #endif
1950 b->next_free = &b->first_data;
1951 b->first_data.string = NULL;
1952 b->next = large_sblocks;
1953 large_sblocks = b;
1955 else if (current_sblock == NULL
1956 || (((char *) current_sblock + SBLOCK_SIZE
1957 - (char *) current_sblock->next_free)
1958 < (needed + GC_STRING_EXTRA)))
1960 /* Not enough room in the current sblock. */
1961 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1962 b->next_free = &b->first_data;
1963 b->first_data.string = NULL;
1964 b->next = NULL;
1966 if (current_sblock)
1967 current_sblock->next = b;
1968 else
1969 oldest_sblock = b;
1970 current_sblock = b;
1972 else
1973 b = current_sblock;
1975 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1976 old_nbytes = GC_STRING_BYTES (s);
1978 data = b->next_free;
1979 data->string = s;
1980 s->data = SDATA_DATA (data);
1981 #ifdef GC_CHECK_STRING_BYTES
1982 SDATA_NBYTES (data) = nbytes;
1983 #endif
1984 s->size = nchars;
1985 s->size_byte = nbytes;
1986 s->data[nbytes] = '\0';
1987 #ifdef GC_CHECK_STRING_OVERRUN
1988 bcopy (string_overrun_cookie, (char *) data + needed,
1989 GC_STRING_OVERRUN_COOKIE_SIZE);
1990 #endif
1991 b->next_free = (struct sdata *) ((char *) data + needed + GC_STRING_EXTRA);
1993 /* If S had already data assigned, mark that as free by setting its
1994 string back-pointer to null, and recording the size of the data
1995 in it. */
1996 if (old_data)
1998 SDATA_NBYTES (old_data) = old_nbytes;
1999 old_data->string = NULL;
2002 consing_since_gc += needed;
2006 /* Sweep and compact strings. */
2008 static void
2009 sweep_strings ()
2011 struct string_block *b, *next;
2012 struct string_block *live_blocks = NULL;
2014 string_free_list = NULL;
2015 total_strings = total_free_strings = 0;
2016 total_string_size = 0;
2018 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
2019 for (b = string_blocks; b; b = next)
2021 int i, nfree = 0;
2022 struct Lisp_String *free_list_before = string_free_list;
2024 next = b->next;
2026 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
2028 struct Lisp_String *s = b->strings + i;
2030 if (s->data)
2032 /* String was not on free-list before. */
2033 if (STRING_MARKED_P (s))
2035 /* String is live; unmark it and its intervals. */
2036 UNMARK_STRING (s);
2038 if (!NULL_INTERVAL_P (s->intervals))
2039 UNMARK_BALANCE_INTERVALS (s->intervals);
2041 ++total_strings;
2042 total_string_size += STRING_BYTES (s);
2044 else
2046 /* String is dead. Put it on the free-list. */
2047 struct sdata *data = SDATA_OF_STRING (s);
2049 /* Save the size of S in its sdata so that we know
2050 how large that is. Reset the sdata's string
2051 back-pointer so that we know it's free. */
2052 #ifdef GC_CHECK_STRING_BYTES
2053 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
2054 abort ();
2055 #else
2056 data->u.nbytes = GC_STRING_BYTES (s);
2057 #endif
2058 data->string = NULL;
2060 /* Reset the strings's `data' member so that we
2061 know it's free. */
2062 s->data = NULL;
2064 /* Put the string on the free-list. */
2065 NEXT_FREE_LISP_STRING (s) = string_free_list;
2066 string_free_list = s;
2067 ++nfree;
2070 else
2072 /* S was on the free-list before. Put it there again. */
2073 NEXT_FREE_LISP_STRING (s) = string_free_list;
2074 string_free_list = s;
2075 ++nfree;
2079 /* Free blocks that contain free Lisp_Strings only, except
2080 the first two of them. */
2081 if (nfree == STRING_BLOCK_SIZE
2082 && total_free_strings > STRING_BLOCK_SIZE)
2084 lisp_free (b);
2085 --n_string_blocks;
2086 string_free_list = free_list_before;
2088 else
2090 total_free_strings += nfree;
2091 b->next = live_blocks;
2092 live_blocks = b;
2096 check_string_free_list ();
2098 string_blocks = live_blocks;
2099 free_large_strings ();
2100 compact_small_strings ();
2102 check_string_free_list ();
2106 /* Free dead large strings. */
2108 static void
2109 free_large_strings ()
2111 struct sblock *b, *next;
2112 struct sblock *live_blocks = NULL;
2114 for (b = large_sblocks; b; b = next)
2116 next = b->next;
2118 if (b->first_data.string == NULL)
2119 lisp_free (b);
2120 else
2122 b->next = live_blocks;
2123 live_blocks = b;
2127 large_sblocks = live_blocks;
2131 /* Compact data of small strings. Free sblocks that don't contain
2132 data of live strings after compaction. */
2134 static void
2135 compact_small_strings ()
2137 struct sblock *b, *tb, *next;
2138 struct sdata *from, *to, *end, *tb_end;
2139 struct sdata *to_end, *from_end;
2141 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2142 to, and TB_END is the end of TB. */
2143 tb = oldest_sblock;
2144 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2145 to = &tb->first_data;
2147 /* Step through the blocks from the oldest to the youngest. We
2148 expect that old blocks will stabilize over time, so that less
2149 copying will happen this way. */
2150 for (b = oldest_sblock; b; b = b->next)
2152 end = b->next_free;
2153 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2155 for (from = &b->first_data; from < end; from = from_end)
2157 /* Compute the next FROM here because copying below may
2158 overwrite data we need to compute it. */
2159 int nbytes;
2161 #ifdef GC_CHECK_STRING_BYTES
2162 /* Check that the string size recorded in the string is the
2163 same as the one recorded in the sdata structure. */
2164 if (from->string
2165 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
2166 abort ();
2167 #endif /* GC_CHECK_STRING_BYTES */
2169 if (from->string)
2170 nbytes = GC_STRING_BYTES (from->string);
2171 else
2172 nbytes = SDATA_NBYTES (from);
2174 if (nbytes > LARGE_STRING_BYTES)
2175 abort ();
2177 nbytes = SDATA_SIZE (nbytes);
2178 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
2180 #ifdef GC_CHECK_STRING_OVERRUN
2181 if (bcmp (string_overrun_cookie,
2182 ((char *) from_end) - GC_STRING_OVERRUN_COOKIE_SIZE,
2183 GC_STRING_OVERRUN_COOKIE_SIZE))
2184 abort ();
2185 #endif
2187 /* FROM->string non-null means it's alive. Copy its data. */
2188 if (from->string)
2190 /* If TB is full, proceed with the next sblock. */
2191 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2192 if (to_end > tb_end)
2194 tb->next_free = to;
2195 tb = tb->next;
2196 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2197 to = &tb->first_data;
2198 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2201 /* Copy, and update the string's `data' pointer. */
2202 if (from != to)
2204 xassert (tb != b || to <= from);
2205 safe_bcopy ((char *) from, (char *) to, nbytes + GC_STRING_EXTRA);
2206 to->string->data = SDATA_DATA (to);
2209 /* Advance past the sdata we copied to. */
2210 to = to_end;
2215 /* The rest of the sblocks following TB don't contain live data, so
2216 we can free them. */
2217 for (b = tb->next; b; b = next)
2219 next = b->next;
2220 lisp_free (b);
2223 tb->next_free = to;
2224 tb->next = NULL;
2225 current_sblock = tb;
2229 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2230 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2231 LENGTH must be an integer.
2232 INIT must be an integer that represents a character. */)
2233 (length, init)
2234 Lisp_Object length, init;
2236 register Lisp_Object val;
2237 register unsigned char *p, *end;
2238 int c, nbytes;
2240 CHECK_NATNUM (length);
2241 CHECK_NUMBER (init);
2243 c = XINT (init);
2244 if (SINGLE_BYTE_CHAR_P (c))
2246 nbytes = XINT (length);
2247 val = make_uninit_string (nbytes);
2248 p = SDATA (val);
2249 end = p + SCHARS (val);
2250 while (p != end)
2251 *p++ = c;
2253 else
2255 unsigned char str[MAX_MULTIBYTE_LENGTH];
2256 int len = CHAR_STRING (c, str);
2258 nbytes = len * XINT (length);
2259 val = make_uninit_multibyte_string (XINT (length), nbytes);
2260 p = SDATA (val);
2261 end = p + nbytes;
2262 while (p != end)
2264 bcopy (str, p, len);
2265 p += len;
2269 *p = 0;
2270 return val;
2274 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2275 doc: /* Return a new bool-vector of length LENGTH, using INIT for as each element.
2276 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2277 (length, init)
2278 Lisp_Object length, init;
2280 register Lisp_Object val;
2281 struct Lisp_Bool_Vector *p;
2282 int real_init, i;
2283 int length_in_chars, length_in_elts, bits_per_value;
2285 CHECK_NATNUM (length);
2287 bits_per_value = sizeof (EMACS_INT) * BOOL_VECTOR_BITS_PER_CHAR;
2289 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
2290 length_in_chars = ((XFASTINT (length) + BOOL_VECTOR_BITS_PER_CHAR - 1)
2291 / BOOL_VECTOR_BITS_PER_CHAR);
2293 /* We must allocate one more elements than LENGTH_IN_ELTS for the
2294 slot `size' of the struct Lisp_Bool_Vector. */
2295 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
2296 p = XBOOL_VECTOR (val);
2298 /* Get rid of any bits that would cause confusion. */
2299 p->vector_size = 0;
2300 XSETBOOL_VECTOR (val, p);
2301 p->size = XFASTINT (length);
2303 real_init = (NILP (init) ? 0 : -1);
2304 for (i = 0; i < length_in_chars ; i++)
2305 p->data[i] = real_init;
2307 /* Clear the extraneous bits in the last byte. */
2308 if (XINT (length) != length_in_chars * BOOL_VECTOR_BITS_PER_CHAR)
2309 XBOOL_VECTOR (val)->data[length_in_chars - 1]
2310 &= (1 << (XINT (length) % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2312 return val;
2316 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2317 of characters from the contents. This string may be unibyte or
2318 multibyte, depending on the contents. */
2320 Lisp_Object
2321 make_string (contents, nbytes)
2322 const char *contents;
2323 int nbytes;
2325 register Lisp_Object val;
2326 int nchars, multibyte_nbytes;
2328 parse_str_as_multibyte (contents, nbytes, &nchars, &multibyte_nbytes);
2329 if (nbytes == nchars || nbytes != multibyte_nbytes)
2330 /* CONTENTS contains no multibyte sequences or contains an invalid
2331 multibyte sequence. We must make unibyte string. */
2332 val = make_unibyte_string (contents, nbytes);
2333 else
2334 val = make_multibyte_string (contents, nchars, nbytes);
2335 return val;
2339 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
2341 Lisp_Object
2342 make_unibyte_string (contents, length)
2343 const char *contents;
2344 int length;
2346 register Lisp_Object val;
2347 val = make_uninit_string (length);
2348 bcopy (contents, SDATA (val), length);
2349 STRING_SET_UNIBYTE (val);
2350 return val;
2354 /* Make a multibyte string from NCHARS characters occupying NBYTES
2355 bytes at CONTENTS. */
2357 Lisp_Object
2358 make_multibyte_string (contents, nchars, nbytes)
2359 const char *contents;
2360 int nchars, nbytes;
2362 register Lisp_Object val;
2363 val = make_uninit_multibyte_string (nchars, nbytes);
2364 bcopy (contents, SDATA (val), nbytes);
2365 return val;
2369 /* Make a string from NCHARS characters occupying NBYTES bytes at
2370 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2372 Lisp_Object
2373 make_string_from_bytes (contents, nchars, nbytes)
2374 const char *contents;
2375 int nchars, nbytes;
2377 register Lisp_Object val;
2378 val = make_uninit_multibyte_string (nchars, nbytes);
2379 bcopy (contents, SDATA (val), nbytes);
2380 if (SBYTES (val) == SCHARS (val))
2381 STRING_SET_UNIBYTE (val);
2382 return val;
2386 /* Make a string from NCHARS characters occupying NBYTES bytes at
2387 CONTENTS. The argument MULTIBYTE controls whether to label the
2388 string as multibyte. If NCHARS is negative, it counts the number of
2389 characters by itself. */
2391 Lisp_Object
2392 make_specified_string (contents, nchars, nbytes, multibyte)
2393 const char *contents;
2394 int nchars, nbytes;
2395 int multibyte;
2397 register Lisp_Object val;
2399 if (nchars < 0)
2401 if (multibyte)
2402 nchars = multibyte_chars_in_text (contents, nbytes);
2403 else
2404 nchars = nbytes;
2406 val = make_uninit_multibyte_string (nchars, nbytes);
2407 bcopy (contents, SDATA (val), nbytes);
2408 if (!multibyte)
2409 STRING_SET_UNIBYTE (val);
2410 return val;
2414 /* Make a string from the data at STR, treating it as multibyte if the
2415 data warrants. */
2417 Lisp_Object
2418 build_string (str)
2419 const char *str;
2421 return make_string (str, strlen (str));
2425 /* Return an unibyte Lisp_String set up to hold LENGTH characters
2426 occupying LENGTH bytes. */
2428 Lisp_Object
2429 make_uninit_string (length)
2430 int length;
2432 Lisp_Object val;
2433 val = make_uninit_multibyte_string (length, length);
2434 STRING_SET_UNIBYTE (val);
2435 return val;
2439 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2440 which occupy NBYTES bytes. */
2442 Lisp_Object
2443 make_uninit_multibyte_string (nchars, nbytes)
2444 int nchars, nbytes;
2446 Lisp_Object string;
2447 struct Lisp_String *s;
2449 if (nchars < 0)
2450 abort ();
2452 s = allocate_string ();
2453 allocate_string_data (s, nchars, nbytes);
2454 XSETSTRING (string, s);
2455 string_chars_consed += nbytes;
2456 return string;
2461 /***********************************************************************
2462 Float Allocation
2463 ***********************************************************************/
2465 /* We store float cells inside of float_blocks, allocating a new
2466 float_block with malloc whenever necessary. Float cells reclaimed
2467 by GC are put on a free list to be reallocated before allocating
2468 any new float cells from the latest float_block. */
2470 #define FLOAT_BLOCK_SIZE \
2471 (((BLOCK_BYTES - sizeof (struct float_block *) \
2472 /* The compiler might add padding at the end. */ \
2473 - (sizeof (struct Lisp_Float) - sizeof (int))) * CHAR_BIT) \
2474 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2476 #define GETMARKBIT(block,n) \
2477 (((block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2478 >> ((n) % (sizeof(int) * CHAR_BIT))) \
2479 & 1)
2481 #define SETMARKBIT(block,n) \
2482 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2483 |= 1 << ((n) % (sizeof(int) * CHAR_BIT))
2485 #define UNSETMARKBIT(block,n) \
2486 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2487 &= ~(1 << ((n) % (sizeof(int) * CHAR_BIT)))
2489 #define FLOAT_BLOCK(fptr) \
2490 ((struct float_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
2492 #define FLOAT_INDEX(fptr) \
2493 ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2495 struct float_block
2497 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2498 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2499 int gcmarkbits[1 + FLOAT_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
2500 struct float_block *next;
2503 #define FLOAT_MARKED_P(fptr) \
2504 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2506 #define FLOAT_MARK(fptr) \
2507 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2509 #define FLOAT_UNMARK(fptr) \
2510 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2512 /* Current float_block. */
2514 struct float_block *float_block;
2516 /* Index of first unused Lisp_Float in the current float_block. */
2518 int float_block_index;
2520 /* Total number of float blocks now in use. */
2522 int n_float_blocks;
2524 /* Free-list of Lisp_Floats. */
2526 struct Lisp_Float *float_free_list;
2529 /* Initialize float allocation. */
2531 void
2532 init_float ()
2534 float_block = NULL;
2535 float_block_index = FLOAT_BLOCK_SIZE; /* Force alloc of new float_block. */
2536 float_free_list = 0;
2537 n_float_blocks = 0;
2541 /* Explicitly free a float cell by putting it on the free-list. */
2543 void
2544 free_float (ptr)
2545 struct Lisp_Float *ptr;
2547 *(struct Lisp_Float **)&ptr->data = float_free_list;
2548 float_free_list = ptr;
2552 /* Return a new float object with value FLOAT_VALUE. */
2554 Lisp_Object
2555 make_float (float_value)
2556 double float_value;
2558 register Lisp_Object val;
2560 if (float_free_list)
2562 /* We use the data field for chaining the free list
2563 so that we won't use the same field that has the mark bit. */
2564 XSETFLOAT (val, float_free_list);
2565 float_free_list = *(struct Lisp_Float **)&float_free_list->data;
2567 else
2569 if (float_block_index == FLOAT_BLOCK_SIZE)
2571 register struct float_block *new;
2573 new = (struct float_block *) lisp_align_malloc (sizeof *new,
2574 MEM_TYPE_FLOAT);
2575 new->next = float_block;
2576 bzero ((char *) new->gcmarkbits, sizeof new->gcmarkbits);
2577 float_block = new;
2578 float_block_index = 0;
2579 n_float_blocks++;
2581 XSETFLOAT (val, &float_block->floats[float_block_index]);
2582 float_block_index++;
2585 XFLOAT_DATA (val) = float_value;
2586 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2587 consing_since_gc += sizeof (struct Lisp_Float);
2588 floats_consed++;
2589 return val;
2594 /***********************************************************************
2595 Cons Allocation
2596 ***********************************************************************/
2598 /* We store cons cells inside of cons_blocks, allocating a new
2599 cons_block with malloc whenever necessary. Cons cells reclaimed by
2600 GC are put on a free list to be reallocated before allocating
2601 any new cons cells from the latest cons_block. */
2603 #define CONS_BLOCK_SIZE \
2604 (((BLOCK_BYTES - sizeof (struct cons_block *)) * CHAR_BIT) \
2605 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2607 #define CONS_BLOCK(fptr) \
2608 ((struct cons_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
2610 #define CONS_INDEX(fptr) \
2611 ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2613 struct cons_block
2615 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2616 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2617 int gcmarkbits[1 + CONS_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
2618 struct cons_block *next;
2621 #define CONS_MARKED_P(fptr) \
2622 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2624 #define CONS_MARK(fptr) \
2625 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2627 #define CONS_UNMARK(fptr) \
2628 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2630 /* Current cons_block. */
2632 struct cons_block *cons_block;
2634 /* Index of first unused Lisp_Cons in the current block. */
2636 int cons_block_index;
2638 /* Free-list of Lisp_Cons structures. */
2640 struct Lisp_Cons *cons_free_list;
2642 /* Total number of cons blocks now in use. */
2644 int n_cons_blocks;
2647 /* Initialize cons allocation. */
2649 void
2650 init_cons ()
2652 cons_block = NULL;
2653 cons_block_index = CONS_BLOCK_SIZE; /* Force alloc of new cons_block. */
2654 cons_free_list = 0;
2655 n_cons_blocks = 0;
2659 /* Explicitly free a cons cell by putting it on the free-list. */
2661 void
2662 free_cons (ptr)
2663 struct Lisp_Cons *ptr;
2665 *(struct Lisp_Cons **)&ptr->cdr = cons_free_list;
2666 #if GC_MARK_STACK
2667 ptr->car = Vdead;
2668 #endif
2669 cons_free_list = ptr;
2672 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2673 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2674 (car, cdr)
2675 Lisp_Object car, cdr;
2677 register Lisp_Object val;
2679 if (cons_free_list)
2681 /* We use the cdr for chaining the free list
2682 so that we won't use the same field that has the mark bit. */
2683 XSETCONS (val, cons_free_list);
2684 cons_free_list = *(struct Lisp_Cons **)&cons_free_list->cdr;
2686 else
2688 if (cons_block_index == CONS_BLOCK_SIZE)
2690 register struct cons_block *new;
2691 new = (struct cons_block *) lisp_align_malloc (sizeof *new,
2692 MEM_TYPE_CONS);
2693 bzero ((char *) new->gcmarkbits, sizeof new->gcmarkbits);
2694 new->next = cons_block;
2695 cons_block = new;
2696 cons_block_index = 0;
2697 n_cons_blocks++;
2699 XSETCONS (val, &cons_block->conses[cons_block_index]);
2700 cons_block_index++;
2703 XSETCAR (val, car);
2704 XSETCDR (val, cdr);
2705 eassert (!CONS_MARKED_P (XCONS (val)));
2706 consing_since_gc += sizeof (struct Lisp_Cons);
2707 cons_cells_consed++;
2708 return val;
2711 /* Get an error now if there's any junk in the cons free list. */
2712 void
2713 check_cons_list ()
2715 #ifdef GC_CHECK_CONS_LIST
2716 struct Lisp_Cons *tail = cons_free_list;
2718 while (tail)
2719 tail = *(struct Lisp_Cons **)&tail->cdr;
2720 #endif
2723 /* Make a list of 2, 3, 4 or 5 specified objects. */
2725 Lisp_Object
2726 list2 (arg1, arg2)
2727 Lisp_Object arg1, arg2;
2729 return Fcons (arg1, Fcons (arg2, Qnil));
2733 Lisp_Object
2734 list3 (arg1, arg2, arg3)
2735 Lisp_Object arg1, arg2, arg3;
2737 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2741 Lisp_Object
2742 list4 (arg1, arg2, arg3, arg4)
2743 Lisp_Object arg1, arg2, arg3, arg4;
2745 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2749 Lisp_Object
2750 list5 (arg1, arg2, arg3, arg4, arg5)
2751 Lisp_Object arg1, arg2, arg3, arg4, arg5;
2753 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2754 Fcons (arg5, Qnil)))));
2758 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2759 doc: /* Return a newly created list with specified arguments as elements.
2760 Any number of arguments, even zero arguments, are allowed.
2761 usage: (list &rest OBJECTS) */)
2762 (nargs, args)
2763 int nargs;
2764 register Lisp_Object *args;
2766 register Lisp_Object val;
2767 val = Qnil;
2769 while (nargs > 0)
2771 nargs--;
2772 val = Fcons (args[nargs], val);
2774 return val;
2778 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2779 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2780 (length, init)
2781 register Lisp_Object length, init;
2783 register Lisp_Object val;
2784 register int size;
2786 CHECK_NATNUM (length);
2787 size = XFASTINT (length);
2789 val = Qnil;
2790 while (size > 0)
2792 val = Fcons (init, val);
2793 --size;
2795 if (size > 0)
2797 val = Fcons (init, val);
2798 --size;
2800 if (size > 0)
2802 val = Fcons (init, val);
2803 --size;
2805 if (size > 0)
2807 val = Fcons (init, val);
2808 --size;
2810 if (size > 0)
2812 val = Fcons (init, val);
2813 --size;
2819 QUIT;
2822 return val;
2827 /***********************************************************************
2828 Vector Allocation
2829 ***********************************************************************/
2831 /* Singly-linked list of all vectors. */
2833 struct Lisp_Vector *all_vectors;
2835 /* Total number of vector-like objects now in use. */
2837 int n_vectors;
2840 /* Value is a pointer to a newly allocated Lisp_Vector structure
2841 with room for LEN Lisp_Objects. */
2843 static struct Lisp_Vector *
2844 allocate_vectorlike (len, type)
2845 EMACS_INT len;
2846 enum mem_type type;
2848 struct Lisp_Vector *p;
2849 size_t nbytes;
2851 #ifdef DOUG_LEA_MALLOC
2852 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2853 because mapped region contents are not preserved in
2854 a dumped Emacs. */
2855 BLOCK_INPUT;
2856 mallopt (M_MMAP_MAX, 0);
2857 UNBLOCK_INPUT;
2858 #endif
2860 nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
2861 p = (struct Lisp_Vector *) lisp_malloc (nbytes, type);
2863 #ifdef DOUG_LEA_MALLOC
2864 /* Back to a reasonable maximum of mmap'ed areas. */
2865 BLOCK_INPUT;
2866 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2867 UNBLOCK_INPUT;
2868 #endif
2870 consing_since_gc += nbytes;
2871 vector_cells_consed += len;
2873 p->next = all_vectors;
2874 all_vectors = p;
2875 ++n_vectors;
2876 return p;
2880 /* Allocate a vector with NSLOTS slots. */
2882 struct Lisp_Vector *
2883 allocate_vector (nslots)
2884 EMACS_INT nslots;
2886 struct Lisp_Vector *v = allocate_vectorlike (nslots, MEM_TYPE_VECTOR);
2887 v->size = nslots;
2888 return v;
2892 /* Allocate other vector-like structures. */
2894 struct Lisp_Hash_Table *
2895 allocate_hash_table ()
2897 EMACS_INT len = VECSIZE (struct Lisp_Hash_Table);
2898 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_HASH_TABLE);
2899 EMACS_INT i;
2901 v->size = len;
2902 for (i = 0; i < len; ++i)
2903 v->contents[i] = Qnil;
2905 return (struct Lisp_Hash_Table *) v;
2909 struct window *
2910 allocate_window ()
2912 EMACS_INT len = VECSIZE (struct window);
2913 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_WINDOW);
2914 EMACS_INT i;
2916 for (i = 0; i < len; ++i)
2917 v->contents[i] = Qnil;
2918 v->size = len;
2920 return (struct window *) v;
2924 struct frame *
2925 allocate_frame ()
2927 EMACS_INT len = VECSIZE (struct frame);
2928 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_FRAME);
2929 EMACS_INT i;
2931 for (i = 0; i < len; ++i)
2932 v->contents[i] = make_number (0);
2933 v->size = len;
2934 return (struct frame *) v;
2938 struct Lisp_Process *
2939 allocate_process ()
2941 EMACS_INT len = VECSIZE (struct Lisp_Process);
2942 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_PROCESS);
2943 EMACS_INT i;
2945 for (i = 0; i < len; ++i)
2946 v->contents[i] = Qnil;
2947 v->size = len;
2949 return (struct Lisp_Process *) v;
2953 struct Lisp_Vector *
2954 allocate_other_vector (len)
2955 EMACS_INT len;
2957 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_VECTOR);
2958 EMACS_INT i;
2960 for (i = 0; i < len; ++i)
2961 v->contents[i] = Qnil;
2962 v->size = len;
2964 return v;
2968 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
2969 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
2970 See also the function `vector'. */)
2971 (length, init)
2972 register Lisp_Object length, init;
2974 Lisp_Object vector;
2975 register EMACS_INT sizei;
2976 register int index;
2977 register struct Lisp_Vector *p;
2979 CHECK_NATNUM (length);
2980 sizei = XFASTINT (length);
2982 p = allocate_vector (sizei);
2983 for (index = 0; index < sizei; index++)
2984 p->contents[index] = init;
2986 XSETVECTOR (vector, p);
2987 return vector;
2991 DEFUN ("make-char-table", Fmake_char_table, Smake_char_table, 1, 2, 0,
2992 doc: /* Return a newly created char-table, with purpose PURPOSE.
2993 Each element is initialized to INIT, which defaults to nil.
2994 PURPOSE should be a symbol which has a `char-table-extra-slots' property.
2995 The property's value should be an integer between 0 and 10. */)
2996 (purpose, init)
2997 register Lisp_Object purpose, init;
2999 Lisp_Object vector;
3000 Lisp_Object n;
3001 CHECK_SYMBOL (purpose);
3002 n = Fget (purpose, Qchar_table_extra_slots);
3003 CHECK_NUMBER (n);
3004 if (XINT (n) < 0 || XINT (n) > 10)
3005 args_out_of_range (n, Qnil);
3006 /* Add 2 to the size for the defalt and parent slots. */
3007 vector = Fmake_vector (make_number (CHAR_TABLE_STANDARD_SLOTS + XINT (n)),
3008 init);
3009 XCHAR_TABLE (vector)->top = Qt;
3010 XCHAR_TABLE (vector)->parent = Qnil;
3011 XCHAR_TABLE (vector)->purpose = purpose;
3012 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
3013 return vector;
3017 /* Return a newly created sub char table with slots initialized by INIT.
3018 Since a sub char table does not appear as a top level Emacs Lisp
3019 object, we don't need a Lisp interface to make it. */
3021 Lisp_Object
3022 make_sub_char_table (init)
3023 Lisp_Object init;
3025 Lisp_Object vector
3026 = Fmake_vector (make_number (SUB_CHAR_TABLE_STANDARD_SLOTS), init);
3027 XCHAR_TABLE (vector)->top = Qnil;
3028 XCHAR_TABLE (vector)->defalt = Qnil;
3029 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
3030 return vector;
3034 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3035 doc: /* Return a newly created vector with specified arguments as elements.
3036 Any number of arguments, even zero arguments, are allowed.
3037 usage: (vector &rest OBJECTS) */)
3038 (nargs, args)
3039 register int nargs;
3040 Lisp_Object *args;
3042 register Lisp_Object len, val;
3043 register int index;
3044 register struct Lisp_Vector *p;
3046 XSETFASTINT (len, nargs);
3047 val = Fmake_vector (len, Qnil);
3048 p = XVECTOR (val);
3049 for (index = 0; index < nargs; index++)
3050 p->contents[index] = args[index];
3051 return val;
3055 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3056 doc: /* Create a byte-code object with specified arguments as elements.
3057 The arguments should be the arglist, bytecode-string, constant vector,
3058 stack size, (optional) doc string, and (optional) interactive spec.
3059 The first four arguments are required; at most six have any
3060 significance.
3061 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3062 (nargs, args)
3063 register int nargs;
3064 Lisp_Object *args;
3066 register Lisp_Object len, val;
3067 register int index;
3068 register struct Lisp_Vector *p;
3070 XSETFASTINT (len, nargs);
3071 if (!NILP (Vpurify_flag))
3072 val = make_pure_vector ((EMACS_INT) nargs);
3073 else
3074 val = Fmake_vector (len, Qnil);
3076 if (STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
3077 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3078 earlier because they produced a raw 8-bit string for byte-code
3079 and now such a byte-code string is loaded as multibyte while
3080 raw 8-bit characters converted to multibyte form. Thus, now we
3081 must convert them back to the original unibyte form. */
3082 args[1] = Fstring_as_unibyte (args[1]);
3084 p = XVECTOR (val);
3085 for (index = 0; index < nargs; index++)
3087 if (!NILP (Vpurify_flag))
3088 args[index] = Fpurecopy (args[index]);
3089 p->contents[index] = args[index];
3091 XSETCOMPILED (val, p);
3092 return val;
3097 /***********************************************************************
3098 Symbol Allocation
3099 ***********************************************************************/
3101 /* Each symbol_block is just under 1020 bytes long, since malloc
3102 really allocates in units of powers of two and uses 4 bytes for its
3103 own overhead. */
3105 #define SYMBOL_BLOCK_SIZE \
3106 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
3108 struct symbol_block
3110 /* Place `symbols' first, to preserve alignment. */
3111 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3112 struct symbol_block *next;
3115 /* Current symbol block and index of first unused Lisp_Symbol
3116 structure in it. */
3118 struct symbol_block *symbol_block;
3119 int symbol_block_index;
3121 /* List of free symbols. */
3123 struct Lisp_Symbol *symbol_free_list;
3125 /* Total number of symbol blocks now in use. */
3127 int n_symbol_blocks;
3130 /* Initialize symbol allocation. */
3132 void
3133 init_symbol ()
3135 symbol_block = NULL;
3136 symbol_block_index = SYMBOL_BLOCK_SIZE;
3137 symbol_free_list = 0;
3138 n_symbol_blocks = 0;
3142 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3143 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3144 Its value and function definition are void, and its property list is nil. */)
3145 (name)
3146 Lisp_Object name;
3148 register Lisp_Object val;
3149 register struct Lisp_Symbol *p;
3151 CHECK_STRING (name);
3153 if (symbol_free_list)
3155 XSETSYMBOL (val, symbol_free_list);
3156 symbol_free_list = *(struct Lisp_Symbol **)&symbol_free_list->value;
3158 else
3160 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3162 struct symbol_block *new;
3163 new = (struct symbol_block *) lisp_malloc (sizeof *new,
3164 MEM_TYPE_SYMBOL);
3165 new->next = symbol_block;
3166 symbol_block = new;
3167 symbol_block_index = 0;
3168 n_symbol_blocks++;
3170 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index]);
3171 symbol_block_index++;
3174 p = XSYMBOL (val);
3175 p->xname = name;
3176 p->plist = Qnil;
3177 p->value = Qunbound;
3178 p->function = Qunbound;
3179 p->next = NULL;
3180 p->gcmarkbit = 0;
3181 p->interned = SYMBOL_UNINTERNED;
3182 p->constant = 0;
3183 p->indirect_variable = 0;
3184 consing_since_gc += sizeof (struct Lisp_Symbol);
3185 symbols_consed++;
3186 return val;
3191 /***********************************************************************
3192 Marker (Misc) Allocation
3193 ***********************************************************************/
3195 /* Allocation of markers and other objects that share that structure.
3196 Works like allocation of conses. */
3198 #define MARKER_BLOCK_SIZE \
3199 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
3201 struct marker_block
3203 /* Place `markers' first, to preserve alignment. */
3204 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
3205 struct marker_block *next;
3208 struct marker_block *marker_block;
3209 int marker_block_index;
3211 union Lisp_Misc *marker_free_list;
3213 /* Total number of marker blocks now in use. */
3215 int n_marker_blocks;
3217 void
3218 init_marker ()
3220 marker_block = NULL;
3221 marker_block_index = MARKER_BLOCK_SIZE;
3222 marker_free_list = 0;
3223 n_marker_blocks = 0;
3226 /* Return a newly allocated Lisp_Misc object, with no substructure. */
3228 Lisp_Object
3229 allocate_misc ()
3231 Lisp_Object val;
3233 if (marker_free_list)
3235 XSETMISC (val, marker_free_list);
3236 marker_free_list = marker_free_list->u_free.chain;
3238 else
3240 if (marker_block_index == MARKER_BLOCK_SIZE)
3242 struct marker_block *new;
3243 new = (struct marker_block *) lisp_malloc (sizeof *new,
3244 MEM_TYPE_MISC);
3245 new->next = marker_block;
3246 marker_block = new;
3247 marker_block_index = 0;
3248 n_marker_blocks++;
3249 total_free_markers += MARKER_BLOCK_SIZE;
3251 XSETMISC (val, &marker_block->markers[marker_block_index]);
3252 marker_block_index++;
3255 --total_free_markers;
3256 consing_since_gc += sizeof (union Lisp_Misc);
3257 misc_objects_consed++;
3258 XMARKER (val)->gcmarkbit = 0;
3259 return val;
3262 /* Free a Lisp_Misc object */
3264 void
3265 free_misc (misc)
3266 Lisp_Object misc;
3268 XMISC (misc)->u_marker.type = Lisp_Misc_Free;
3269 XMISC (misc)->u_free.chain = marker_free_list;
3270 marker_free_list = XMISC (misc);
3272 total_free_markers++;
3275 /* Return a Lisp_Misc_Save_Value object containing POINTER and
3276 INTEGER. This is used to package C values to call record_unwind_protect.
3277 The unwind function can get the C values back using XSAVE_VALUE. */
3279 Lisp_Object
3280 make_save_value (pointer, integer)
3281 void *pointer;
3282 int integer;
3284 register Lisp_Object val;
3285 register struct Lisp_Save_Value *p;
3287 val = allocate_misc ();
3288 XMISCTYPE (val) = Lisp_Misc_Save_Value;
3289 p = XSAVE_VALUE (val);
3290 p->pointer = pointer;
3291 p->integer = integer;
3292 p->dogc = 0;
3293 return val;
3296 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3297 doc: /* Return a newly allocated marker which does not point at any place. */)
3300 register Lisp_Object val;
3301 register struct Lisp_Marker *p;
3303 val = allocate_misc ();
3304 XMISCTYPE (val) = Lisp_Misc_Marker;
3305 p = XMARKER (val);
3306 p->buffer = 0;
3307 p->bytepos = 0;
3308 p->charpos = 0;
3309 p->next = NULL;
3310 p->insertion_type = 0;
3311 return val;
3314 /* Put MARKER back on the free list after using it temporarily. */
3316 void
3317 free_marker (marker)
3318 Lisp_Object marker;
3320 unchain_marker (XMARKER (marker));
3321 free_misc (marker);
3325 /* Return a newly created vector or string with specified arguments as
3326 elements. If all the arguments are characters that can fit
3327 in a string of events, make a string; otherwise, make a vector.
3329 Any number of arguments, even zero arguments, are allowed. */
3331 Lisp_Object
3332 make_event_array (nargs, args)
3333 register int nargs;
3334 Lisp_Object *args;
3336 int i;
3338 for (i = 0; i < nargs; i++)
3339 /* The things that fit in a string
3340 are characters that are in 0...127,
3341 after discarding the meta bit and all the bits above it. */
3342 if (!INTEGERP (args[i])
3343 || (XUINT (args[i]) & ~(-CHAR_META)) >= 0200)
3344 return Fvector (nargs, args);
3346 /* Since the loop exited, we know that all the things in it are
3347 characters, so we can make a string. */
3349 Lisp_Object result;
3351 result = Fmake_string (make_number (nargs), make_number (0));
3352 for (i = 0; i < nargs; i++)
3354 SSET (result, i, XINT (args[i]));
3355 /* Move the meta bit to the right place for a string char. */
3356 if (XINT (args[i]) & CHAR_META)
3357 SSET (result, i, SREF (result, i) | 0x80);
3360 return result;
3366 /************************************************************************
3367 C Stack Marking
3368 ************************************************************************/
3370 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
3372 /* Conservative C stack marking requires a method to identify possibly
3373 live Lisp objects given a pointer value. We do this by keeping
3374 track of blocks of Lisp data that are allocated in a red-black tree
3375 (see also the comment of mem_node which is the type of nodes in
3376 that tree). Function lisp_malloc adds information for an allocated
3377 block to the red-black tree with calls to mem_insert, and function
3378 lisp_free removes it with mem_delete. Functions live_string_p etc
3379 call mem_find to lookup information about a given pointer in the
3380 tree, and use that to determine if the pointer points to a Lisp
3381 object or not. */
3383 /* Initialize this part of alloc.c. */
3385 static void
3386 mem_init ()
3388 mem_z.left = mem_z.right = MEM_NIL;
3389 mem_z.parent = NULL;
3390 mem_z.color = MEM_BLACK;
3391 mem_z.start = mem_z.end = NULL;
3392 mem_root = MEM_NIL;
3396 /* Value is a pointer to the mem_node containing START. Value is
3397 MEM_NIL if there is no node in the tree containing START. */
3399 static INLINE struct mem_node *
3400 mem_find (start)
3401 void *start;
3403 struct mem_node *p;
3405 if (start < min_heap_address || start > max_heap_address)
3406 return MEM_NIL;
3408 /* Make the search always successful to speed up the loop below. */
3409 mem_z.start = start;
3410 mem_z.end = (char *) start + 1;
3412 p = mem_root;
3413 while (start < p->start || start >= p->end)
3414 p = start < p->start ? p->left : p->right;
3415 return p;
3419 /* Insert a new node into the tree for a block of memory with start
3420 address START, end address END, and type TYPE. Value is a
3421 pointer to the node that was inserted. */
3423 static struct mem_node *
3424 mem_insert (start, end, type)
3425 void *start, *end;
3426 enum mem_type type;
3428 struct mem_node *c, *parent, *x;
3430 if (start < min_heap_address)
3431 min_heap_address = start;
3432 if (end > max_heap_address)
3433 max_heap_address = end;
3435 /* See where in the tree a node for START belongs. In this
3436 particular application, it shouldn't happen that a node is already
3437 present. For debugging purposes, let's check that. */
3438 c = mem_root;
3439 parent = NULL;
3441 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
3443 while (c != MEM_NIL)
3445 if (start >= c->start && start < c->end)
3446 abort ();
3447 parent = c;
3448 c = start < c->start ? c->left : c->right;
3451 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3453 while (c != MEM_NIL)
3455 parent = c;
3456 c = start < c->start ? c->left : c->right;
3459 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3461 /* Create a new node. */
3462 #ifdef GC_MALLOC_CHECK
3463 x = (struct mem_node *) _malloc_internal (sizeof *x);
3464 if (x == NULL)
3465 abort ();
3466 #else
3467 x = (struct mem_node *) xmalloc (sizeof *x);
3468 #endif
3469 x->start = start;
3470 x->end = end;
3471 x->type = type;
3472 x->parent = parent;
3473 x->left = x->right = MEM_NIL;
3474 x->color = MEM_RED;
3476 /* Insert it as child of PARENT or install it as root. */
3477 if (parent)
3479 if (start < parent->start)
3480 parent->left = x;
3481 else
3482 parent->right = x;
3484 else
3485 mem_root = x;
3487 /* Re-establish red-black tree properties. */
3488 mem_insert_fixup (x);
3490 return x;
3494 /* Re-establish the red-black properties of the tree, and thereby
3495 balance the tree, after node X has been inserted; X is always red. */
3497 static void
3498 mem_insert_fixup (x)
3499 struct mem_node *x;
3501 while (x != mem_root && x->parent->color == MEM_RED)
3503 /* X is red and its parent is red. This is a violation of
3504 red-black tree property #3. */
3506 if (x->parent == x->parent->parent->left)
3508 /* We're on the left side of our grandparent, and Y is our
3509 "uncle". */
3510 struct mem_node *y = x->parent->parent->right;
3512 if (y->color == MEM_RED)
3514 /* Uncle and parent are red but should be black because
3515 X is red. Change the colors accordingly and proceed
3516 with the grandparent. */
3517 x->parent->color = MEM_BLACK;
3518 y->color = MEM_BLACK;
3519 x->parent->parent->color = MEM_RED;
3520 x = x->parent->parent;
3522 else
3524 /* Parent and uncle have different colors; parent is
3525 red, uncle is black. */
3526 if (x == x->parent->right)
3528 x = x->parent;
3529 mem_rotate_left (x);
3532 x->parent->color = MEM_BLACK;
3533 x->parent->parent->color = MEM_RED;
3534 mem_rotate_right (x->parent->parent);
3537 else
3539 /* This is the symmetrical case of above. */
3540 struct mem_node *y = x->parent->parent->left;
3542 if (y->color == MEM_RED)
3544 x->parent->color = MEM_BLACK;
3545 y->color = MEM_BLACK;
3546 x->parent->parent->color = MEM_RED;
3547 x = x->parent->parent;
3549 else
3551 if (x == x->parent->left)
3553 x = x->parent;
3554 mem_rotate_right (x);
3557 x->parent->color = MEM_BLACK;
3558 x->parent->parent->color = MEM_RED;
3559 mem_rotate_left (x->parent->parent);
3564 /* The root may have been changed to red due to the algorithm. Set
3565 it to black so that property #5 is satisfied. */
3566 mem_root->color = MEM_BLACK;
3570 /* (x) (y)
3571 / \ / \
3572 a (y) ===> (x) c
3573 / \ / \
3574 b c a b */
3576 static void
3577 mem_rotate_left (x)
3578 struct mem_node *x;
3580 struct mem_node *y;
3582 /* Turn y's left sub-tree into x's right sub-tree. */
3583 y = x->right;
3584 x->right = y->left;
3585 if (y->left != MEM_NIL)
3586 y->left->parent = x;
3588 /* Y's parent was x's parent. */
3589 if (y != MEM_NIL)
3590 y->parent = x->parent;
3592 /* Get the parent to point to y instead of x. */
3593 if (x->parent)
3595 if (x == x->parent->left)
3596 x->parent->left = y;
3597 else
3598 x->parent->right = y;
3600 else
3601 mem_root = y;
3603 /* Put x on y's left. */
3604 y->left = x;
3605 if (x != MEM_NIL)
3606 x->parent = y;
3610 /* (x) (Y)
3611 / \ / \
3612 (y) c ===> a (x)
3613 / \ / \
3614 a b b c */
3616 static void
3617 mem_rotate_right (x)
3618 struct mem_node *x;
3620 struct mem_node *y = x->left;
3622 x->left = y->right;
3623 if (y->right != MEM_NIL)
3624 y->right->parent = x;
3626 if (y != MEM_NIL)
3627 y->parent = x->parent;
3628 if (x->parent)
3630 if (x == x->parent->right)
3631 x->parent->right = y;
3632 else
3633 x->parent->left = y;
3635 else
3636 mem_root = y;
3638 y->right = x;
3639 if (x != MEM_NIL)
3640 x->parent = y;
3644 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
3646 static void
3647 mem_delete (z)
3648 struct mem_node *z;
3650 struct mem_node *x, *y;
3652 if (!z || z == MEM_NIL)
3653 return;
3655 if (z->left == MEM_NIL || z->right == MEM_NIL)
3656 y = z;
3657 else
3659 y = z->right;
3660 while (y->left != MEM_NIL)
3661 y = y->left;
3664 if (y->left != MEM_NIL)
3665 x = y->left;
3666 else
3667 x = y->right;
3669 x->parent = y->parent;
3670 if (y->parent)
3672 if (y == y->parent->left)
3673 y->parent->left = x;
3674 else
3675 y->parent->right = x;
3677 else
3678 mem_root = x;
3680 if (y != z)
3682 z->start = y->start;
3683 z->end = y->end;
3684 z->type = y->type;
3687 if (y->color == MEM_BLACK)
3688 mem_delete_fixup (x);
3690 #ifdef GC_MALLOC_CHECK
3691 _free_internal (y);
3692 #else
3693 xfree (y);
3694 #endif
3698 /* Re-establish the red-black properties of the tree, after a
3699 deletion. */
3701 static void
3702 mem_delete_fixup (x)
3703 struct mem_node *x;
3705 while (x != mem_root && x->color == MEM_BLACK)
3707 if (x == x->parent->left)
3709 struct mem_node *w = x->parent->right;
3711 if (w->color == MEM_RED)
3713 w->color = MEM_BLACK;
3714 x->parent->color = MEM_RED;
3715 mem_rotate_left (x->parent);
3716 w = x->parent->right;
3719 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
3721 w->color = MEM_RED;
3722 x = x->parent;
3724 else
3726 if (w->right->color == MEM_BLACK)
3728 w->left->color = MEM_BLACK;
3729 w->color = MEM_RED;
3730 mem_rotate_right (w);
3731 w = x->parent->right;
3733 w->color = x->parent->color;
3734 x->parent->color = MEM_BLACK;
3735 w->right->color = MEM_BLACK;
3736 mem_rotate_left (x->parent);
3737 x = mem_root;
3740 else
3742 struct mem_node *w = x->parent->left;
3744 if (w->color == MEM_RED)
3746 w->color = MEM_BLACK;
3747 x->parent->color = MEM_RED;
3748 mem_rotate_right (x->parent);
3749 w = x->parent->left;
3752 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
3754 w->color = MEM_RED;
3755 x = x->parent;
3757 else
3759 if (w->left->color == MEM_BLACK)
3761 w->right->color = MEM_BLACK;
3762 w->color = MEM_RED;
3763 mem_rotate_left (w);
3764 w = x->parent->left;
3767 w->color = x->parent->color;
3768 x->parent->color = MEM_BLACK;
3769 w->left->color = MEM_BLACK;
3770 mem_rotate_right (x->parent);
3771 x = mem_root;
3776 x->color = MEM_BLACK;
3780 /* Value is non-zero if P is a pointer to a live Lisp string on
3781 the heap. M is a pointer to the mem_block for P. */
3783 static INLINE int
3784 live_string_p (m, p)
3785 struct mem_node *m;
3786 void *p;
3788 if (m->type == MEM_TYPE_STRING)
3790 struct string_block *b = (struct string_block *) m->start;
3791 int offset = (char *) p - (char *) &b->strings[0];
3793 /* P must point to the start of a Lisp_String structure, and it
3794 must not be on the free-list. */
3795 return (offset >= 0
3796 && offset % sizeof b->strings[0] == 0
3797 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
3798 && ((struct Lisp_String *) p)->data != NULL);
3800 else
3801 return 0;
3805 /* Value is non-zero if P is a pointer to a live Lisp cons on
3806 the heap. M is a pointer to the mem_block for P. */
3808 static INLINE int
3809 live_cons_p (m, p)
3810 struct mem_node *m;
3811 void *p;
3813 if (m->type == MEM_TYPE_CONS)
3815 struct cons_block *b = (struct cons_block *) m->start;
3816 int offset = (char *) p - (char *) &b->conses[0];
3818 /* P must point to the start of a Lisp_Cons, not be
3819 one of the unused cells in the current cons block,
3820 and not be on the free-list. */
3821 return (offset >= 0
3822 && offset % sizeof b->conses[0] == 0
3823 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
3824 && (b != cons_block
3825 || offset / sizeof b->conses[0] < cons_block_index)
3826 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
3828 else
3829 return 0;
3833 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3834 the heap. M is a pointer to the mem_block for P. */
3836 static INLINE int
3837 live_symbol_p (m, p)
3838 struct mem_node *m;
3839 void *p;
3841 if (m->type == MEM_TYPE_SYMBOL)
3843 struct symbol_block *b = (struct symbol_block *) m->start;
3844 int offset = (char *) p - (char *) &b->symbols[0];
3846 /* P must point to the start of a Lisp_Symbol, not be
3847 one of the unused cells in the current symbol block,
3848 and not be on the free-list. */
3849 return (offset >= 0
3850 && offset % sizeof b->symbols[0] == 0
3851 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
3852 && (b != symbol_block
3853 || offset / sizeof b->symbols[0] < symbol_block_index)
3854 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
3856 else
3857 return 0;
3861 /* Value is non-zero if P is a pointer to a live Lisp float on
3862 the heap. M is a pointer to the mem_block for P. */
3864 static INLINE int
3865 live_float_p (m, p)
3866 struct mem_node *m;
3867 void *p;
3869 if (m->type == MEM_TYPE_FLOAT)
3871 struct float_block *b = (struct float_block *) m->start;
3872 int offset = (char *) p - (char *) &b->floats[0];
3874 /* P must point to the start of a Lisp_Float and not be
3875 one of the unused cells in the current float block. */
3876 return (offset >= 0
3877 && offset % sizeof b->floats[0] == 0
3878 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
3879 && (b != float_block
3880 || offset / sizeof b->floats[0] < float_block_index));
3882 else
3883 return 0;
3887 /* Value is non-zero if P is a pointer to a live Lisp Misc on
3888 the heap. M is a pointer to the mem_block for P. */
3890 static INLINE int
3891 live_misc_p (m, p)
3892 struct mem_node *m;
3893 void *p;
3895 if (m->type == MEM_TYPE_MISC)
3897 struct marker_block *b = (struct marker_block *) m->start;
3898 int offset = (char *) p - (char *) &b->markers[0];
3900 /* P must point to the start of a Lisp_Misc, not be
3901 one of the unused cells in the current misc block,
3902 and not be on the free-list. */
3903 return (offset >= 0
3904 && offset % sizeof b->markers[0] == 0
3905 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
3906 && (b != marker_block
3907 || offset / sizeof b->markers[0] < marker_block_index)
3908 && ((union Lisp_Misc *) p)->u_marker.type != Lisp_Misc_Free);
3910 else
3911 return 0;
3915 /* Value is non-zero if P is a pointer to a live vector-like object.
3916 M is a pointer to the mem_block for P. */
3918 static INLINE int
3919 live_vector_p (m, p)
3920 struct mem_node *m;
3921 void *p;
3923 return (p == m->start
3924 && m->type >= MEM_TYPE_VECTOR
3925 && m->type <= MEM_TYPE_WINDOW);
3929 /* Value is non-zero if P is a pointer to a live buffer. M is a
3930 pointer to the mem_block for P. */
3932 static INLINE int
3933 live_buffer_p (m, p)
3934 struct mem_node *m;
3935 void *p;
3937 /* P must point to the start of the block, and the buffer
3938 must not have been killed. */
3939 return (m->type == MEM_TYPE_BUFFER
3940 && p == m->start
3941 && !NILP (((struct buffer *) p)->name));
3944 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
3946 #if GC_MARK_STACK
3948 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3950 /* Array of objects that are kept alive because the C stack contains
3951 a pattern that looks like a reference to them . */
3953 #define MAX_ZOMBIES 10
3954 static Lisp_Object zombies[MAX_ZOMBIES];
3956 /* Number of zombie objects. */
3958 static int nzombies;
3960 /* Number of garbage collections. */
3962 static int ngcs;
3964 /* Average percentage of zombies per collection. */
3966 static double avg_zombies;
3968 /* Max. number of live and zombie objects. */
3970 static int max_live, max_zombies;
3972 /* Average number of live objects per GC. */
3974 static double avg_live;
3976 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
3977 doc: /* Show information about live and zombie objects. */)
3980 Lisp_Object args[8], zombie_list = Qnil;
3981 int i;
3982 for (i = 0; i < nzombies; i++)
3983 zombie_list = Fcons (zombies[i], zombie_list);
3984 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
3985 args[1] = make_number (ngcs);
3986 args[2] = make_float (avg_live);
3987 args[3] = make_float (avg_zombies);
3988 args[4] = make_float (avg_zombies / avg_live / 100);
3989 args[5] = make_number (max_live);
3990 args[6] = make_number (max_zombies);
3991 args[7] = zombie_list;
3992 return Fmessage (8, args);
3995 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3998 /* Mark OBJ if we can prove it's a Lisp_Object. */
4000 static INLINE void
4001 mark_maybe_object (obj)
4002 Lisp_Object obj;
4004 void *po = (void *) XPNTR (obj);
4005 struct mem_node *m = mem_find (po);
4007 if (m != MEM_NIL)
4009 int mark_p = 0;
4011 switch (XGCTYPE (obj))
4013 case Lisp_String:
4014 mark_p = (live_string_p (m, po)
4015 && !STRING_MARKED_P ((struct Lisp_String *) po));
4016 break;
4018 case Lisp_Cons:
4019 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4020 break;
4022 case Lisp_Symbol:
4023 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4024 break;
4026 case Lisp_Float:
4027 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4028 break;
4030 case Lisp_Vectorlike:
4031 /* Note: can't check GC_BUFFERP before we know it's a
4032 buffer because checking that dereferences the pointer
4033 PO which might point anywhere. */
4034 if (live_vector_p (m, po))
4035 mark_p = !GC_SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4036 else if (live_buffer_p (m, po))
4037 mark_p = GC_BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4038 break;
4040 case Lisp_Misc:
4041 mark_p = (live_misc_p (m, po) && !XMARKER (obj)->gcmarkbit);
4042 break;
4044 case Lisp_Int:
4045 case Lisp_Type_Limit:
4046 break;
4049 if (mark_p)
4051 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4052 if (nzombies < MAX_ZOMBIES)
4053 zombies[nzombies] = obj;
4054 ++nzombies;
4055 #endif
4056 mark_object (obj);
4062 /* If P points to Lisp data, mark that as live if it isn't already
4063 marked. */
4065 static INLINE void
4066 mark_maybe_pointer (p)
4067 void *p;
4069 struct mem_node *m;
4071 /* Quickly rule out some values which can't point to Lisp data. We
4072 assume that Lisp data is aligned on even addresses. */
4073 if ((EMACS_INT) p & 1)
4074 return;
4076 m = mem_find (p);
4077 if (m != MEM_NIL)
4079 Lisp_Object obj = Qnil;
4081 switch (m->type)
4083 case MEM_TYPE_NON_LISP:
4084 /* Nothing to do; not a pointer to Lisp memory. */
4085 break;
4087 case MEM_TYPE_BUFFER:
4088 if (live_buffer_p (m, p) && !VECTOR_MARKED_P((struct buffer *)p))
4089 XSETVECTOR (obj, p);
4090 break;
4092 case MEM_TYPE_CONS:
4093 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4094 XSETCONS (obj, p);
4095 break;
4097 case MEM_TYPE_STRING:
4098 if (live_string_p (m, p)
4099 && !STRING_MARKED_P ((struct Lisp_String *) p))
4100 XSETSTRING (obj, p);
4101 break;
4103 case MEM_TYPE_MISC:
4104 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4105 XSETMISC (obj, p);
4106 break;
4108 case MEM_TYPE_SYMBOL:
4109 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4110 XSETSYMBOL (obj, p);
4111 break;
4113 case MEM_TYPE_FLOAT:
4114 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4115 XSETFLOAT (obj, p);
4116 break;
4118 case MEM_TYPE_VECTOR:
4119 case MEM_TYPE_PROCESS:
4120 case MEM_TYPE_HASH_TABLE:
4121 case MEM_TYPE_FRAME:
4122 case MEM_TYPE_WINDOW:
4123 if (live_vector_p (m, p))
4125 Lisp_Object tem;
4126 XSETVECTOR (tem, p);
4127 if (!GC_SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4128 obj = tem;
4130 break;
4132 default:
4133 abort ();
4136 if (!GC_NILP (obj))
4137 mark_object (obj);
4142 /* Mark Lisp objects referenced from the address range START..END. */
4144 static void
4145 mark_memory (start, end)
4146 void *start, *end;
4148 Lisp_Object *p;
4149 void **pp;
4151 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4152 nzombies = 0;
4153 #endif
4155 /* Make START the pointer to the start of the memory region,
4156 if it isn't already. */
4157 if (end < start)
4159 void *tem = start;
4160 start = end;
4161 end = tem;
4164 /* Mark Lisp_Objects. */
4165 for (p = (Lisp_Object *) start; (void *) p < end; ++p)
4166 mark_maybe_object (*p);
4168 /* Mark Lisp data pointed to. This is necessary because, in some
4169 situations, the C compiler optimizes Lisp objects away, so that
4170 only a pointer to them remains. Example:
4172 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4175 Lisp_Object obj = build_string ("test");
4176 struct Lisp_String *s = XSTRING (obj);
4177 Fgarbage_collect ();
4178 fprintf (stderr, "test `%s'\n", s->data);
4179 return Qnil;
4182 Here, `obj' isn't really used, and the compiler optimizes it
4183 away. The only reference to the life string is through the
4184 pointer `s'. */
4186 for (pp = (void **) start; (void *) pp < end; ++pp)
4187 mark_maybe_pointer (*pp);
4190 /* setjmp will work with GCC unless NON_SAVING_SETJMP is defined in
4191 the GCC system configuration. In gcc 3.2, the only systems for
4192 which this is so are i386-sco5 non-ELF, i386-sysv3 (maybe included
4193 by others?) and ns32k-pc532-min. */
4195 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4197 static int setjmp_tested_p, longjmps_done;
4199 #define SETJMP_WILL_LIKELY_WORK "\
4201 Emacs garbage collector has been changed to use conservative stack\n\
4202 marking. Emacs has determined that the method it uses to do the\n\
4203 marking will likely work on your system, but this isn't sure.\n\
4205 If you are a system-programmer, or can get the help of a local wizard\n\
4206 who is, please take a look at the function mark_stack in alloc.c, and\n\
4207 verify that the methods used are appropriate for your system.\n\
4209 Please mail the result to <emacs-devel@gnu.org>.\n\
4212 #define SETJMP_WILL_NOT_WORK "\
4214 Emacs garbage collector has been changed to use conservative stack\n\
4215 marking. Emacs has determined that the default method it uses to do the\n\
4216 marking will not work on your system. We will need a system-dependent\n\
4217 solution for your system.\n\
4219 Please take a look at the function mark_stack in alloc.c, and\n\
4220 try to find a way to make it work on your system.\n\
4222 Note that you may get false negatives, depending on the compiler.\n\
4223 In particular, you need to use -O with GCC for this test.\n\
4225 Please mail the result to <emacs-devel@gnu.org>.\n\
4229 /* Perform a quick check if it looks like setjmp saves registers in a
4230 jmp_buf. Print a message to stderr saying so. When this test
4231 succeeds, this is _not_ a proof that setjmp is sufficient for
4232 conservative stack marking. Only the sources or a disassembly
4233 can prove that. */
4235 static void
4236 test_setjmp ()
4238 char buf[10];
4239 register int x;
4240 jmp_buf jbuf;
4241 int result = 0;
4243 /* Arrange for X to be put in a register. */
4244 sprintf (buf, "1");
4245 x = strlen (buf);
4246 x = 2 * x - 1;
4248 setjmp (jbuf);
4249 if (longjmps_done == 1)
4251 /* Came here after the longjmp at the end of the function.
4253 If x == 1, the longjmp has restored the register to its
4254 value before the setjmp, and we can hope that setjmp
4255 saves all such registers in the jmp_buf, although that
4256 isn't sure.
4258 For other values of X, either something really strange is
4259 taking place, or the setjmp just didn't save the register. */
4261 if (x == 1)
4262 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4263 else
4265 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4266 exit (1);
4270 ++longjmps_done;
4271 x = 2;
4272 if (longjmps_done == 1)
4273 longjmp (jbuf, 1);
4276 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4279 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4281 /* Abort if anything GCPRO'd doesn't survive the GC. */
4283 static void
4284 check_gcpros ()
4286 struct gcpro *p;
4287 int i;
4289 for (p = gcprolist; p; p = p->next)
4290 for (i = 0; i < p->nvars; ++i)
4291 if (!survives_gc_p (p->var[i]))
4292 /* FIXME: It's not necessarily a bug. It might just be that the
4293 GCPRO is unnecessary or should release the object sooner. */
4294 abort ();
4297 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4299 static void
4300 dump_zombies ()
4302 int i;
4304 fprintf (stderr, "\nZombies kept alive = %d:\n", nzombies);
4305 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
4307 fprintf (stderr, " %d = ", i);
4308 debug_print (zombies[i]);
4312 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4315 /* Mark live Lisp objects on the C stack.
4317 There are several system-dependent problems to consider when
4318 porting this to new architectures:
4320 Processor Registers
4322 We have to mark Lisp objects in CPU registers that can hold local
4323 variables or are used to pass parameters.
4325 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4326 something that either saves relevant registers on the stack, or
4327 calls mark_maybe_object passing it each register's contents.
4329 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4330 implementation assumes that calling setjmp saves registers we need
4331 to see in a jmp_buf which itself lies on the stack. This doesn't
4332 have to be true! It must be verified for each system, possibly
4333 by taking a look at the source code of setjmp.
4335 Stack Layout
4337 Architectures differ in the way their processor stack is organized.
4338 For example, the stack might look like this
4340 +----------------+
4341 | Lisp_Object | size = 4
4342 +----------------+
4343 | something else | size = 2
4344 +----------------+
4345 | Lisp_Object | size = 4
4346 +----------------+
4347 | ... |
4349 In such a case, not every Lisp_Object will be aligned equally. To
4350 find all Lisp_Object on the stack it won't be sufficient to walk
4351 the stack in steps of 4 bytes. Instead, two passes will be
4352 necessary, one starting at the start of the stack, and a second
4353 pass starting at the start of the stack + 2. Likewise, if the
4354 minimal alignment of Lisp_Objects on the stack is 1, four passes
4355 would be necessary, each one starting with one byte more offset
4356 from the stack start.
4358 The current code assumes by default that Lisp_Objects are aligned
4359 equally on the stack. */
4361 static void
4362 mark_stack ()
4364 int i;
4365 jmp_buf j;
4366 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
4367 void *end;
4369 /* This trick flushes the register windows so that all the state of
4370 the process is contained in the stack. */
4371 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
4372 needed on ia64 too. See mach_dep.c, where it also says inline
4373 assembler doesn't work with relevant proprietary compilers. */
4374 #ifdef sparc
4375 asm ("ta 3");
4376 #endif
4378 /* Save registers that we need to see on the stack. We need to see
4379 registers used to hold register variables and registers used to
4380 pass parameters. */
4381 #ifdef GC_SAVE_REGISTERS_ON_STACK
4382 GC_SAVE_REGISTERS_ON_STACK (end);
4383 #else /* not GC_SAVE_REGISTERS_ON_STACK */
4385 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
4386 setjmp will definitely work, test it
4387 and print a message with the result
4388 of the test. */
4389 if (!setjmp_tested_p)
4391 setjmp_tested_p = 1;
4392 test_setjmp ();
4394 #endif /* GC_SETJMP_WORKS */
4396 setjmp (j);
4397 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
4398 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
4400 /* This assumes that the stack is a contiguous region in memory. If
4401 that's not the case, something has to be done here to iterate
4402 over the stack segments. */
4403 #ifndef GC_LISP_OBJECT_ALIGNMENT
4404 #ifdef __GNUC__
4405 #define GC_LISP_OBJECT_ALIGNMENT __alignof__ (Lisp_Object)
4406 #else
4407 #define GC_LISP_OBJECT_ALIGNMENT sizeof (Lisp_Object)
4408 #endif
4409 #endif
4410 for (i = 0; i < sizeof (Lisp_Object); i += GC_LISP_OBJECT_ALIGNMENT)
4411 mark_memory ((char *) stack_base + i, end);
4412 /* Allow for marking a secondary stack, like the register stack on the
4413 ia64. */
4414 #ifdef GC_MARK_SECONDARY_STACK
4415 GC_MARK_SECONDARY_STACK ();
4416 #endif
4418 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4419 check_gcpros ();
4420 #endif
4424 #endif /* GC_MARK_STACK != 0 */
4428 /***********************************************************************
4429 Pure Storage Management
4430 ***********************************************************************/
4432 /* Allocate room for SIZE bytes from pure Lisp storage and return a
4433 pointer to it. TYPE is the Lisp type for which the memory is
4434 allocated. TYPE < 0 means it's not used for a Lisp object.
4436 If store_pure_type_info is set and TYPE is >= 0, the type of
4437 the allocated object is recorded in pure_types. */
4439 static POINTER_TYPE *
4440 pure_alloc (size, type)
4441 size_t size;
4442 int type;
4444 POINTER_TYPE *result;
4445 #ifdef USE_LSB_TAG
4446 size_t alignment = (1 << GCTYPEBITS);
4447 #else
4448 size_t alignment = sizeof (EMACS_INT);
4450 /* Give Lisp_Floats an extra alignment. */
4451 if (type == Lisp_Float)
4453 #if defined __GNUC__ && __GNUC__ >= 2
4454 alignment = __alignof (struct Lisp_Float);
4455 #else
4456 alignment = sizeof (struct Lisp_Float);
4457 #endif
4459 #endif
4461 again:
4462 result = ALIGN (purebeg + pure_bytes_used, alignment);
4463 pure_bytes_used = ((char *)result - (char *)purebeg) + size;
4465 if (pure_bytes_used <= pure_size)
4466 return result;
4468 /* Don't allocate a large amount here,
4469 because it might get mmap'd and then its address
4470 might not be usable. */
4471 purebeg = (char *) xmalloc (10000);
4472 pure_size = 10000;
4473 pure_bytes_used_before_overflow += pure_bytes_used - size;
4474 pure_bytes_used = 0;
4475 goto again;
4479 /* Print a warning if PURESIZE is too small. */
4481 void
4482 check_pure_size ()
4484 if (pure_bytes_used_before_overflow)
4485 message ("Pure Lisp storage overflow (approx. %d bytes needed)",
4486 (int) (pure_bytes_used + pure_bytes_used_before_overflow));
4490 /* Return a string allocated in pure space. DATA is a buffer holding
4491 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
4492 non-zero means make the result string multibyte.
4494 Must get an error if pure storage is full, since if it cannot hold
4495 a large string it may be able to hold conses that point to that
4496 string; then the string is not protected from gc. */
4498 Lisp_Object
4499 make_pure_string (data, nchars, nbytes, multibyte)
4500 char *data;
4501 int nchars, nbytes;
4502 int multibyte;
4504 Lisp_Object string;
4505 struct Lisp_String *s;
4507 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
4508 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
4509 s->size = nchars;
4510 s->size_byte = multibyte ? nbytes : -1;
4511 bcopy (data, s->data, nbytes);
4512 s->data[nbytes] = '\0';
4513 s->intervals = NULL_INTERVAL;
4514 XSETSTRING (string, s);
4515 return string;
4519 /* Return a cons allocated from pure space. Give it pure copies
4520 of CAR as car and CDR as cdr. */
4522 Lisp_Object
4523 pure_cons (car, cdr)
4524 Lisp_Object car, cdr;
4526 register Lisp_Object new;
4527 struct Lisp_Cons *p;
4529 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
4530 XSETCONS (new, p);
4531 XSETCAR (new, Fpurecopy (car));
4532 XSETCDR (new, Fpurecopy (cdr));
4533 return new;
4537 /* Value is a float object with value NUM allocated from pure space. */
4539 Lisp_Object
4540 make_pure_float (num)
4541 double num;
4543 register Lisp_Object new;
4544 struct Lisp_Float *p;
4546 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
4547 XSETFLOAT (new, p);
4548 XFLOAT_DATA (new) = num;
4549 return new;
4553 /* Return a vector with room for LEN Lisp_Objects allocated from
4554 pure space. */
4556 Lisp_Object
4557 make_pure_vector (len)
4558 EMACS_INT len;
4560 Lisp_Object new;
4561 struct Lisp_Vector *p;
4562 size_t size = sizeof *p + (len - 1) * sizeof (Lisp_Object);
4564 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
4565 XSETVECTOR (new, p);
4566 XVECTOR (new)->size = len;
4567 return new;
4571 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
4572 doc: /* Make a copy of OBJECT in pure storage.
4573 Recursively copies contents of vectors and cons cells.
4574 Does not copy symbols. Copies strings without text properties. */)
4575 (obj)
4576 register Lisp_Object obj;
4578 if (NILP (Vpurify_flag))
4579 return obj;
4581 if (PURE_POINTER_P (XPNTR (obj)))
4582 return obj;
4584 if (CONSP (obj))
4585 return pure_cons (XCAR (obj), XCDR (obj));
4586 else if (FLOATP (obj))
4587 return make_pure_float (XFLOAT_DATA (obj));
4588 else if (STRINGP (obj))
4589 return make_pure_string (SDATA (obj), SCHARS (obj),
4590 SBYTES (obj),
4591 STRING_MULTIBYTE (obj));
4592 else if (COMPILEDP (obj) || VECTORP (obj))
4594 register struct Lisp_Vector *vec;
4595 register int i;
4596 EMACS_INT size;
4598 size = XVECTOR (obj)->size;
4599 if (size & PSEUDOVECTOR_FLAG)
4600 size &= PSEUDOVECTOR_SIZE_MASK;
4601 vec = XVECTOR (make_pure_vector (size));
4602 for (i = 0; i < size; i++)
4603 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
4604 if (COMPILEDP (obj))
4605 XSETCOMPILED (obj, vec);
4606 else
4607 XSETVECTOR (obj, vec);
4608 return obj;
4610 else if (MARKERP (obj))
4611 error ("Attempt to copy a marker to pure storage");
4613 return obj;
4618 /***********************************************************************
4619 Protection from GC
4620 ***********************************************************************/
4622 /* Put an entry in staticvec, pointing at the variable with address
4623 VARADDRESS. */
4625 void
4626 staticpro (varaddress)
4627 Lisp_Object *varaddress;
4629 staticvec[staticidx++] = varaddress;
4630 if (staticidx >= NSTATICS)
4631 abort ();
4634 struct catchtag
4636 Lisp_Object tag;
4637 Lisp_Object val;
4638 struct catchtag *next;
4642 /***********************************************************************
4643 Protection from GC
4644 ***********************************************************************/
4646 /* Temporarily prevent garbage collection. */
4649 inhibit_garbage_collection ()
4651 int count = SPECPDL_INDEX ();
4652 int nbits = min (VALBITS, BITS_PER_INT);
4654 specbind (Qgc_cons_threshold, make_number (((EMACS_INT) 1 << (nbits - 1)) - 1));
4655 return count;
4659 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
4660 doc: /* Reclaim storage for Lisp objects no longer needed.
4661 Garbage collection happens automatically if you cons more than
4662 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
4663 `garbage-collect' normally returns a list with info on amount of space in use:
4664 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
4665 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
4666 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)
4667 (USED-STRINGS . FREE-STRINGS))
4668 However, if there was overflow in pure space, `garbage-collect'
4669 returns nil, because real GC can't be done. */)
4672 register struct specbinding *bind;
4673 struct catchtag *catch;
4674 struct handler *handler;
4675 char stack_top_variable;
4676 register int i;
4677 int message_p;
4678 Lisp_Object total[8];
4679 int count = SPECPDL_INDEX ();
4680 EMACS_TIME t1, t2, t3;
4682 if (abort_on_gc)
4683 abort ();
4685 /* Can't GC if pure storage overflowed because we can't determine
4686 if something is a pure object or not. */
4687 if (pure_bytes_used_before_overflow)
4688 return Qnil;
4690 CHECK_CONS_LIST ();
4692 /* Don't keep undo information around forever.
4693 Do this early on, so it is no problem if the user quits. */
4695 register struct buffer *nextb = all_buffers;
4697 while (nextb)
4699 /* If a buffer's undo list is Qt, that means that undo is
4700 turned off in that buffer. Calling truncate_undo_list on
4701 Qt tends to return NULL, which effectively turns undo back on.
4702 So don't call truncate_undo_list if undo_list is Qt. */
4703 if (! NILP (nextb->name) && ! EQ (nextb->undo_list, Qt))
4704 truncate_undo_list (nextb);
4706 /* Shrink buffer gaps, but skip indirect and dead buffers. */
4707 if (nextb->base_buffer == 0 && !NILP (nextb->name))
4709 /* If a buffer's gap size is more than 10% of the buffer
4710 size, or larger than 2000 bytes, then shrink it
4711 accordingly. Keep a minimum size of 20 bytes. */
4712 int size = min (2000, max (20, (nextb->text->z_byte / 10)));
4714 if (nextb->text->gap_size > size)
4716 struct buffer *save_current = current_buffer;
4717 current_buffer = nextb;
4718 make_gap (-(nextb->text->gap_size - size));
4719 current_buffer = save_current;
4723 nextb = nextb->next;
4727 EMACS_GET_TIME (t1);
4729 /* In case user calls debug_print during GC,
4730 don't let that cause a recursive GC. */
4731 consing_since_gc = 0;
4733 /* Save what's currently displayed in the echo area. */
4734 message_p = push_message ();
4735 record_unwind_protect (pop_message_unwind, Qnil);
4737 /* Save a copy of the contents of the stack, for debugging. */
4738 #if MAX_SAVE_STACK > 0
4739 if (NILP (Vpurify_flag))
4741 i = &stack_top_variable - stack_bottom;
4742 if (i < 0) i = -i;
4743 if (i < MAX_SAVE_STACK)
4745 if (stack_copy == 0)
4746 stack_copy = (char *) xmalloc (stack_copy_size = i);
4747 else if (stack_copy_size < i)
4748 stack_copy = (char *) xrealloc (stack_copy, (stack_copy_size = i));
4749 if (stack_copy)
4751 if ((EMACS_INT) (&stack_top_variable - stack_bottom) > 0)
4752 bcopy (stack_bottom, stack_copy, i);
4753 else
4754 bcopy (&stack_top_variable, stack_copy, i);
4758 #endif /* MAX_SAVE_STACK > 0 */
4760 if (garbage_collection_messages)
4761 message1_nolog ("Garbage collecting...");
4763 BLOCK_INPUT;
4765 shrink_regexp_cache ();
4767 gc_in_progress = 1;
4769 /* clear_marks (); */
4771 /* Mark all the special slots that serve as the roots of accessibility. */
4773 for (i = 0; i < staticidx; i++)
4774 mark_object (*staticvec[i]);
4776 for (bind = specpdl; bind != specpdl_ptr; bind++)
4778 mark_object (bind->symbol);
4779 mark_object (bind->old_value);
4781 mark_kboards ();
4783 #ifdef USE_GTK
4785 extern void xg_mark_data ();
4786 xg_mark_data ();
4788 #endif
4790 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
4791 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
4792 mark_stack ();
4793 #else
4795 register struct gcpro *tail;
4796 for (tail = gcprolist; tail; tail = tail->next)
4797 for (i = 0; i < tail->nvars; i++)
4798 mark_object (tail->var[i]);
4800 #endif
4802 mark_byte_stack ();
4803 for (catch = catchlist; catch; catch = catch->next)
4805 mark_object (catch->tag);
4806 mark_object (catch->val);
4808 for (handler = handlerlist; handler; handler = handler->next)
4810 mark_object (handler->handler);
4811 mark_object (handler->var);
4813 mark_backtrace ();
4815 #ifdef HAVE_WINDOW_SYSTEM
4816 mark_fringe_data ();
4817 #endif
4819 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4820 mark_stack ();
4821 #endif
4823 /* Everything is now marked, except for the things that require special
4824 finalization, i.e. the undo_list.
4825 Look thru every buffer's undo list
4826 for elements that update markers that were not marked,
4827 and delete them. */
4829 register struct buffer *nextb = all_buffers;
4831 while (nextb)
4833 /* If a buffer's undo list is Qt, that means that undo is
4834 turned off in that buffer. Calling truncate_undo_list on
4835 Qt tends to return NULL, which effectively turns undo back on.
4836 So don't call truncate_undo_list if undo_list is Qt. */
4837 if (! EQ (nextb->undo_list, Qt))
4839 Lisp_Object tail, prev;
4840 tail = nextb->undo_list;
4841 prev = Qnil;
4842 while (CONSP (tail))
4844 if (GC_CONSP (XCAR (tail))
4845 && GC_MARKERP (XCAR (XCAR (tail)))
4846 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
4848 if (NILP (prev))
4849 nextb->undo_list = tail = XCDR (tail);
4850 else
4852 tail = XCDR (tail);
4853 XSETCDR (prev, tail);
4856 else
4858 prev = tail;
4859 tail = XCDR (tail);
4863 /* Now that we have stripped the elements that need not be in the
4864 undo_list any more, we can finally mark the list. */
4865 mark_object (nextb->undo_list);
4867 nextb = nextb->next;
4871 gc_sweep ();
4873 /* Clear the mark bits that we set in certain root slots. */
4875 unmark_byte_stack ();
4876 VECTOR_UNMARK (&buffer_defaults);
4877 VECTOR_UNMARK (&buffer_local_symbols);
4879 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
4880 dump_zombies ();
4881 #endif
4883 UNBLOCK_INPUT;
4885 CHECK_CONS_LIST ();
4887 /* clear_marks (); */
4888 gc_in_progress = 0;
4890 consing_since_gc = 0;
4891 if (gc_cons_threshold < 10000)
4892 gc_cons_threshold = 10000;
4894 if (garbage_collection_messages)
4896 if (message_p || minibuf_level > 0)
4897 restore_message ();
4898 else
4899 message1_nolog ("Garbage collecting...done");
4902 unbind_to (count, Qnil);
4904 total[0] = Fcons (make_number (total_conses),
4905 make_number (total_free_conses));
4906 total[1] = Fcons (make_number (total_symbols),
4907 make_number (total_free_symbols));
4908 total[2] = Fcons (make_number (total_markers),
4909 make_number (total_free_markers));
4910 total[3] = make_number (total_string_size);
4911 total[4] = make_number (total_vector_size);
4912 total[5] = Fcons (make_number (total_floats),
4913 make_number (total_free_floats));
4914 total[6] = Fcons (make_number (total_intervals),
4915 make_number (total_free_intervals));
4916 total[7] = Fcons (make_number (total_strings),
4917 make_number (total_free_strings));
4919 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4921 /* Compute average percentage of zombies. */
4922 double nlive = 0;
4924 for (i = 0; i < 7; ++i)
4925 if (CONSP (total[i]))
4926 nlive += XFASTINT (XCAR (total[i]));
4928 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
4929 max_live = max (nlive, max_live);
4930 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
4931 max_zombies = max (nzombies, max_zombies);
4932 ++ngcs;
4934 #endif
4936 if (!NILP (Vpost_gc_hook))
4938 int count = inhibit_garbage_collection ();
4939 safe_run_hooks (Qpost_gc_hook);
4940 unbind_to (count, Qnil);
4943 /* Accumulate statistics. */
4944 EMACS_GET_TIME (t2);
4945 EMACS_SUB_TIME (t3, t2, t1);
4946 if (FLOATP (Vgc_elapsed))
4947 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed) +
4948 EMACS_SECS (t3) +
4949 EMACS_USECS (t3) * 1.0e-6);
4950 gcs_done++;
4952 return Flist (sizeof total / sizeof *total, total);
4956 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
4957 only interesting objects referenced from glyphs are strings. */
4959 static void
4960 mark_glyph_matrix (matrix)
4961 struct glyph_matrix *matrix;
4963 struct glyph_row *row = matrix->rows;
4964 struct glyph_row *end = row + matrix->nrows;
4966 for (; row < end; ++row)
4967 if (row->enabled_p)
4969 int area;
4970 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
4972 struct glyph *glyph = row->glyphs[area];
4973 struct glyph *end_glyph = glyph + row->used[area];
4975 for (; glyph < end_glyph; ++glyph)
4976 if (GC_STRINGP (glyph->object)
4977 && !STRING_MARKED_P (XSTRING (glyph->object)))
4978 mark_object (glyph->object);
4984 /* Mark Lisp faces in the face cache C. */
4986 static void
4987 mark_face_cache (c)
4988 struct face_cache *c;
4990 if (c)
4992 int i, j;
4993 for (i = 0; i < c->used; ++i)
4995 struct face *face = FACE_FROM_ID (c->f, i);
4997 if (face)
4999 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
5000 mark_object (face->lface[j]);
5007 #ifdef HAVE_WINDOW_SYSTEM
5009 /* Mark Lisp objects in image IMG. */
5011 static void
5012 mark_image (img)
5013 struct image *img;
5015 mark_object (img->spec);
5017 if (!NILP (img->data.lisp_val))
5018 mark_object (img->data.lisp_val);
5022 /* Mark Lisp objects in image cache of frame F. It's done this way so
5023 that we don't have to include xterm.h here. */
5025 static void
5026 mark_image_cache (f)
5027 struct frame *f;
5029 forall_images_in_image_cache (f, mark_image);
5032 #endif /* HAVE_X_WINDOWS */
5036 /* Mark reference to a Lisp_Object.
5037 If the object referred to has not been seen yet, recursively mark
5038 all the references contained in it. */
5040 #define LAST_MARKED_SIZE 500
5041 Lisp_Object last_marked[LAST_MARKED_SIZE];
5042 int last_marked_index;
5044 /* For debugging--call abort when we cdr down this many
5045 links of a list, in mark_object. In debugging,
5046 the call to abort will hit a breakpoint.
5047 Normally this is zero and the check never goes off. */
5048 int mark_object_loop_halt;
5050 void
5051 mark_object (arg)
5052 Lisp_Object arg;
5054 register Lisp_Object obj = arg;
5055 #ifdef GC_CHECK_MARKED_OBJECTS
5056 void *po;
5057 struct mem_node *m;
5058 #endif
5059 int cdr_count = 0;
5061 loop:
5063 if (PURE_POINTER_P (XPNTR (obj)))
5064 return;
5066 last_marked[last_marked_index++] = obj;
5067 if (last_marked_index == LAST_MARKED_SIZE)
5068 last_marked_index = 0;
5070 /* Perform some sanity checks on the objects marked here. Abort if
5071 we encounter an object we know is bogus. This increases GC time
5072 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
5073 #ifdef GC_CHECK_MARKED_OBJECTS
5075 po = (void *) XPNTR (obj);
5077 /* Check that the object pointed to by PO is known to be a Lisp
5078 structure allocated from the heap. */
5079 #define CHECK_ALLOCATED() \
5080 do { \
5081 m = mem_find (po); \
5082 if (m == MEM_NIL) \
5083 abort (); \
5084 } while (0)
5086 /* Check that the object pointed to by PO is live, using predicate
5087 function LIVEP. */
5088 #define CHECK_LIVE(LIVEP) \
5089 do { \
5090 if (!LIVEP (m, po)) \
5091 abort (); \
5092 } while (0)
5094 /* Check both of the above conditions. */
5095 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
5096 do { \
5097 CHECK_ALLOCATED (); \
5098 CHECK_LIVE (LIVEP); \
5099 } while (0) \
5101 #else /* not GC_CHECK_MARKED_OBJECTS */
5103 #define CHECK_ALLOCATED() (void) 0
5104 #define CHECK_LIVE(LIVEP) (void) 0
5105 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
5107 #endif /* not GC_CHECK_MARKED_OBJECTS */
5109 switch (SWITCH_ENUM_CAST (XGCTYPE (obj)))
5111 case Lisp_String:
5113 register struct Lisp_String *ptr = XSTRING (obj);
5114 CHECK_ALLOCATED_AND_LIVE (live_string_p);
5115 MARK_INTERVAL_TREE (ptr->intervals);
5116 MARK_STRING (ptr);
5117 #ifdef GC_CHECK_STRING_BYTES
5118 /* Check that the string size recorded in the string is the
5119 same as the one recorded in the sdata structure. */
5120 CHECK_STRING_BYTES (ptr);
5121 #endif /* GC_CHECK_STRING_BYTES */
5123 break;
5125 case Lisp_Vectorlike:
5126 #ifdef GC_CHECK_MARKED_OBJECTS
5127 m = mem_find (po);
5128 if (m == MEM_NIL && !GC_SUBRP (obj)
5129 && po != &buffer_defaults
5130 && po != &buffer_local_symbols)
5131 abort ();
5132 #endif /* GC_CHECK_MARKED_OBJECTS */
5134 if (GC_BUFFERP (obj))
5136 if (!VECTOR_MARKED_P (XBUFFER (obj)))
5138 #ifdef GC_CHECK_MARKED_OBJECTS
5139 if (po != &buffer_defaults && po != &buffer_local_symbols)
5141 struct buffer *b;
5142 for (b = all_buffers; b && b != po; b = b->next)
5144 if (b == NULL)
5145 abort ();
5147 #endif /* GC_CHECK_MARKED_OBJECTS */
5148 mark_buffer (obj);
5151 else if (GC_SUBRP (obj))
5152 break;
5153 else if (GC_COMPILEDP (obj))
5154 /* We could treat this just like a vector, but it is better to
5155 save the COMPILED_CONSTANTS element for last and avoid
5156 recursion there. */
5158 register struct Lisp_Vector *ptr = XVECTOR (obj);
5159 register EMACS_INT size = ptr->size;
5160 register int i;
5162 if (VECTOR_MARKED_P (ptr))
5163 break; /* Already marked */
5165 CHECK_LIVE (live_vector_p);
5166 VECTOR_MARK (ptr); /* Else mark it */
5167 size &= PSEUDOVECTOR_SIZE_MASK;
5168 for (i = 0; i < size; i++) /* and then mark its elements */
5170 if (i != COMPILED_CONSTANTS)
5171 mark_object (ptr->contents[i]);
5173 obj = ptr->contents[COMPILED_CONSTANTS];
5174 goto loop;
5176 else if (GC_FRAMEP (obj))
5178 register struct frame *ptr = XFRAME (obj);
5180 if (VECTOR_MARKED_P (ptr)) break; /* Already marked */
5181 VECTOR_MARK (ptr); /* Else mark it */
5183 CHECK_LIVE (live_vector_p);
5184 mark_object (ptr->name);
5185 mark_object (ptr->icon_name);
5186 mark_object (ptr->title);
5187 mark_object (ptr->focus_frame);
5188 mark_object (ptr->selected_window);
5189 mark_object (ptr->minibuffer_window);
5190 mark_object (ptr->param_alist);
5191 mark_object (ptr->scroll_bars);
5192 mark_object (ptr->condemned_scroll_bars);
5193 mark_object (ptr->menu_bar_items);
5194 mark_object (ptr->face_alist);
5195 mark_object (ptr->menu_bar_vector);
5196 mark_object (ptr->buffer_predicate);
5197 mark_object (ptr->buffer_list);
5198 mark_object (ptr->menu_bar_window);
5199 mark_object (ptr->tool_bar_window);
5200 mark_face_cache (ptr->face_cache);
5201 #ifdef HAVE_WINDOW_SYSTEM
5202 mark_image_cache (ptr);
5203 mark_object (ptr->tool_bar_items);
5204 mark_object (ptr->desired_tool_bar_string);
5205 mark_object (ptr->current_tool_bar_string);
5206 #endif /* HAVE_WINDOW_SYSTEM */
5208 else if (GC_BOOL_VECTOR_P (obj))
5210 register struct Lisp_Vector *ptr = XVECTOR (obj);
5212 if (VECTOR_MARKED_P (ptr))
5213 break; /* Already marked */
5214 CHECK_LIVE (live_vector_p);
5215 VECTOR_MARK (ptr); /* Else mark it */
5217 else if (GC_WINDOWP (obj))
5219 register struct Lisp_Vector *ptr = XVECTOR (obj);
5220 struct window *w = XWINDOW (obj);
5221 register int i;
5223 /* Stop if already marked. */
5224 if (VECTOR_MARKED_P (ptr))
5225 break;
5227 /* Mark it. */
5228 CHECK_LIVE (live_vector_p);
5229 VECTOR_MARK (ptr);
5231 /* There is no Lisp data above The member CURRENT_MATRIX in
5232 struct WINDOW. Stop marking when that slot is reached. */
5233 for (i = 0;
5234 (char *) &ptr->contents[i] < (char *) &w->current_matrix;
5235 i++)
5236 mark_object (ptr->contents[i]);
5238 /* Mark glyphs for leaf windows. Marking window matrices is
5239 sufficient because frame matrices use the same glyph
5240 memory. */
5241 if (NILP (w->hchild)
5242 && NILP (w->vchild)
5243 && w->current_matrix)
5245 mark_glyph_matrix (w->current_matrix);
5246 mark_glyph_matrix (w->desired_matrix);
5249 else if (GC_HASH_TABLE_P (obj))
5251 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
5253 /* Stop if already marked. */
5254 if (VECTOR_MARKED_P (h))
5255 break;
5257 /* Mark it. */
5258 CHECK_LIVE (live_vector_p);
5259 VECTOR_MARK (h);
5261 /* Mark contents. */
5262 /* Do not mark next_free or next_weak.
5263 Being in the next_weak chain
5264 should not keep the hash table alive.
5265 No need to mark `count' since it is an integer. */
5266 mark_object (h->test);
5267 mark_object (h->weak);
5268 mark_object (h->rehash_size);
5269 mark_object (h->rehash_threshold);
5270 mark_object (h->hash);
5271 mark_object (h->next);
5272 mark_object (h->index);
5273 mark_object (h->user_hash_function);
5274 mark_object (h->user_cmp_function);
5276 /* If hash table is not weak, mark all keys and values.
5277 For weak tables, mark only the vector. */
5278 if (GC_NILP (h->weak))
5279 mark_object (h->key_and_value);
5280 else
5281 VECTOR_MARK (XVECTOR (h->key_and_value));
5283 else
5285 register struct Lisp_Vector *ptr = XVECTOR (obj);
5286 register EMACS_INT size = ptr->size;
5287 register int i;
5289 if (VECTOR_MARKED_P (ptr)) break; /* Already marked */
5290 CHECK_LIVE (live_vector_p);
5291 VECTOR_MARK (ptr); /* Else mark it */
5292 if (size & PSEUDOVECTOR_FLAG)
5293 size &= PSEUDOVECTOR_SIZE_MASK;
5295 for (i = 0; i < size; i++) /* and then mark its elements */
5296 mark_object (ptr->contents[i]);
5298 break;
5300 case Lisp_Symbol:
5302 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
5303 struct Lisp_Symbol *ptrx;
5305 if (ptr->gcmarkbit) break;
5306 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
5307 ptr->gcmarkbit = 1;
5308 mark_object (ptr->value);
5309 mark_object (ptr->function);
5310 mark_object (ptr->plist);
5312 if (!PURE_POINTER_P (XSTRING (ptr->xname)))
5313 MARK_STRING (XSTRING (ptr->xname));
5314 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr->xname));
5316 /* Note that we do not mark the obarray of the symbol.
5317 It is safe not to do so because nothing accesses that
5318 slot except to check whether it is nil. */
5319 ptr = ptr->next;
5320 if (ptr)
5322 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
5323 XSETSYMBOL (obj, ptrx);
5324 goto loop;
5327 break;
5329 case Lisp_Misc:
5330 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
5331 if (XMARKER (obj)->gcmarkbit)
5332 break;
5333 XMARKER (obj)->gcmarkbit = 1;
5335 switch (XMISCTYPE (obj))
5337 case Lisp_Misc_Buffer_Local_Value:
5338 case Lisp_Misc_Some_Buffer_Local_Value:
5340 register struct Lisp_Buffer_Local_Value *ptr
5341 = XBUFFER_LOCAL_VALUE (obj);
5342 /* If the cdr is nil, avoid recursion for the car. */
5343 if (EQ (ptr->cdr, Qnil))
5345 obj = ptr->realvalue;
5346 goto loop;
5348 mark_object (ptr->realvalue);
5349 mark_object (ptr->buffer);
5350 mark_object (ptr->frame);
5351 obj = ptr->cdr;
5352 goto loop;
5355 case Lisp_Misc_Marker:
5356 /* DO NOT mark thru the marker's chain.
5357 The buffer's markers chain does not preserve markers from gc;
5358 instead, markers are removed from the chain when freed by gc. */
5359 break;
5361 case Lisp_Misc_Intfwd:
5362 case Lisp_Misc_Boolfwd:
5363 case Lisp_Misc_Objfwd:
5364 case Lisp_Misc_Buffer_Objfwd:
5365 case Lisp_Misc_Kboard_Objfwd:
5366 /* Don't bother with Lisp_Buffer_Objfwd,
5367 since all markable slots in current buffer marked anyway. */
5368 /* Don't need to do Lisp_Objfwd, since the places they point
5369 are protected with staticpro. */
5370 break;
5372 case Lisp_Misc_Save_Value:
5373 #if GC_MARK_STACK
5375 register struct Lisp_Save_Value *ptr = XSAVE_VALUE (obj);
5376 /* If DOGC is set, POINTER is the address of a memory
5377 area containing INTEGER potential Lisp_Objects. */
5378 if (ptr->dogc)
5380 Lisp_Object *p = (Lisp_Object *) ptr->pointer;
5381 int nelt;
5382 for (nelt = ptr->integer; nelt > 0; nelt--, p++)
5383 mark_maybe_object (*p);
5386 #endif
5387 break;
5389 case Lisp_Misc_Overlay:
5391 struct Lisp_Overlay *ptr = XOVERLAY (obj);
5392 mark_object (ptr->start);
5393 mark_object (ptr->end);
5394 mark_object (ptr->plist);
5395 if (ptr->next)
5397 XSETMISC (obj, ptr->next);
5398 goto loop;
5401 break;
5403 default:
5404 abort ();
5406 break;
5408 case Lisp_Cons:
5410 register struct Lisp_Cons *ptr = XCONS (obj);
5411 if (CONS_MARKED_P (ptr)) break;
5412 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
5413 CONS_MARK (ptr);
5414 /* If the cdr is nil, avoid recursion for the car. */
5415 if (EQ (ptr->cdr, Qnil))
5417 obj = ptr->car;
5418 cdr_count = 0;
5419 goto loop;
5421 mark_object (ptr->car);
5422 obj = ptr->cdr;
5423 cdr_count++;
5424 if (cdr_count == mark_object_loop_halt)
5425 abort ();
5426 goto loop;
5429 case Lisp_Float:
5430 CHECK_ALLOCATED_AND_LIVE (live_float_p);
5431 FLOAT_MARK (XFLOAT (obj));
5432 break;
5434 case Lisp_Int:
5435 break;
5437 default:
5438 abort ();
5441 #undef CHECK_LIVE
5442 #undef CHECK_ALLOCATED
5443 #undef CHECK_ALLOCATED_AND_LIVE
5446 /* Mark the pointers in a buffer structure. */
5448 static void
5449 mark_buffer (buf)
5450 Lisp_Object buf;
5452 register struct buffer *buffer = XBUFFER (buf);
5453 register Lisp_Object *ptr, tmp;
5454 Lisp_Object base_buffer;
5456 VECTOR_MARK (buffer);
5458 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
5460 /* For now, we just don't mark the undo_list. It's done later in
5461 a special way just before the sweep phase, and after stripping
5462 some of its elements that are not needed any more. */
5464 if (buffer->overlays_before)
5466 XSETMISC (tmp, buffer->overlays_before);
5467 mark_object (tmp);
5469 if (buffer->overlays_after)
5471 XSETMISC (tmp, buffer->overlays_after);
5472 mark_object (tmp);
5475 for (ptr = &buffer->name;
5476 (char *)ptr < (char *)buffer + sizeof (struct buffer);
5477 ptr++)
5478 mark_object (*ptr);
5480 /* If this is an indirect buffer, mark its base buffer. */
5481 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5483 XSETBUFFER (base_buffer, buffer->base_buffer);
5484 mark_buffer (base_buffer);
5489 /* Value is non-zero if OBJ will survive the current GC because it's
5490 either marked or does not need to be marked to survive. */
5493 survives_gc_p (obj)
5494 Lisp_Object obj;
5496 int survives_p;
5498 switch (XGCTYPE (obj))
5500 case Lisp_Int:
5501 survives_p = 1;
5502 break;
5504 case Lisp_Symbol:
5505 survives_p = XSYMBOL (obj)->gcmarkbit;
5506 break;
5508 case Lisp_Misc:
5509 survives_p = XMARKER (obj)->gcmarkbit;
5510 break;
5512 case Lisp_String:
5513 survives_p = STRING_MARKED_P (XSTRING (obj));
5514 break;
5516 case Lisp_Vectorlike:
5517 survives_p = GC_SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
5518 break;
5520 case Lisp_Cons:
5521 survives_p = CONS_MARKED_P (XCONS (obj));
5522 break;
5524 case Lisp_Float:
5525 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
5526 break;
5528 default:
5529 abort ();
5532 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
5537 /* Sweep: find all structures not marked, and free them. */
5539 static void
5540 gc_sweep ()
5542 /* Remove or mark entries in weak hash tables.
5543 This must be done before any object is unmarked. */
5544 sweep_weak_hash_tables ();
5546 sweep_strings ();
5547 #ifdef GC_CHECK_STRING_BYTES
5548 if (!noninteractive)
5549 check_string_bytes (1);
5550 #endif
5552 /* Put all unmarked conses on free list */
5554 register struct cons_block *cblk;
5555 struct cons_block **cprev = &cons_block;
5556 register int lim = cons_block_index;
5557 register int num_free = 0, num_used = 0;
5559 cons_free_list = 0;
5561 for (cblk = cons_block; cblk; cblk = *cprev)
5563 register int i;
5564 int this_free = 0;
5565 for (i = 0; i < lim; i++)
5566 if (!CONS_MARKED_P (&cblk->conses[i]))
5568 this_free++;
5569 *(struct Lisp_Cons **)&cblk->conses[i].cdr = cons_free_list;
5570 cons_free_list = &cblk->conses[i];
5571 #if GC_MARK_STACK
5572 cons_free_list->car = Vdead;
5573 #endif
5575 else
5577 num_used++;
5578 CONS_UNMARK (&cblk->conses[i]);
5580 lim = CONS_BLOCK_SIZE;
5581 /* If this block contains only free conses and we have already
5582 seen more than two blocks worth of free conses then deallocate
5583 this block. */
5584 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
5586 *cprev = cblk->next;
5587 /* Unhook from the free list. */
5588 cons_free_list = *(struct Lisp_Cons **) &cblk->conses[0].cdr;
5589 lisp_align_free (cblk);
5590 n_cons_blocks--;
5592 else
5594 num_free += this_free;
5595 cprev = &cblk->next;
5598 total_conses = num_used;
5599 total_free_conses = num_free;
5602 /* Put all unmarked floats on free list */
5604 register struct float_block *fblk;
5605 struct float_block **fprev = &float_block;
5606 register int lim = float_block_index;
5607 register int num_free = 0, num_used = 0;
5609 float_free_list = 0;
5611 for (fblk = float_block; fblk; fblk = *fprev)
5613 register int i;
5614 int this_free = 0;
5615 for (i = 0; i < lim; i++)
5616 if (!FLOAT_MARKED_P (&fblk->floats[i]))
5618 this_free++;
5619 *(struct Lisp_Float **)&fblk->floats[i].data = float_free_list;
5620 float_free_list = &fblk->floats[i];
5622 else
5624 num_used++;
5625 FLOAT_UNMARK (&fblk->floats[i]);
5627 lim = FLOAT_BLOCK_SIZE;
5628 /* If this block contains only free floats and we have already
5629 seen more than two blocks worth of free floats then deallocate
5630 this block. */
5631 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
5633 *fprev = fblk->next;
5634 /* Unhook from the free list. */
5635 float_free_list = *(struct Lisp_Float **) &fblk->floats[0].data;
5636 lisp_align_free (fblk);
5637 n_float_blocks--;
5639 else
5641 num_free += this_free;
5642 fprev = &fblk->next;
5645 total_floats = num_used;
5646 total_free_floats = num_free;
5649 /* Put all unmarked intervals on free list */
5651 register struct interval_block *iblk;
5652 struct interval_block **iprev = &interval_block;
5653 register int lim = interval_block_index;
5654 register int num_free = 0, num_used = 0;
5656 interval_free_list = 0;
5658 for (iblk = interval_block; iblk; iblk = *iprev)
5660 register int i;
5661 int this_free = 0;
5663 for (i = 0; i < lim; i++)
5665 if (!iblk->intervals[i].gcmarkbit)
5667 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
5668 interval_free_list = &iblk->intervals[i];
5669 this_free++;
5671 else
5673 num_used++;
5674 iblk->intervals[i].gcmarkbit = 0;
5677 lim = INTERVAL_BLOCK_SIZE;
5678 /* If this block contains only free intervals and we have already
5679 seen more than two blocks worth of free intervals then
5680 deallocate this block. */
5681 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
5683 *iprev = iblk->next;
5684 /* Unhook from the free list. */
5685 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
5686 lisp_free (iblk);
5687 n_interval_blocks--;
5689 else
5691 num_free += this_free;
5692 iprev = &iblk->next;
5695 total_intervals = num_used;
5696 total_free_intervals = num_free;
5699 /* Put all unmarked symbols on free list */
5701 register struct symbol_block *sblk;
5702 struct symbol_block **sprev = &symbol_block;
5703 register int lim = symbol_block_index;
5704 register int num_free = 0, num_used = 0;
5706 symbol_free_list = NULL;
5708 for (sblk = symbol_block; sblk; sblk = *sprev)
5710 int this_free = 0;
5711 struct Lisp_Symbol *sym = sblk->symbols;
5712 struct Lisp_Symbol *end = sym + lim;
5714 for (; sym < end; ++sym)
5716 /* Check if the symbol was created during loadup. In such a case
5717 it might be pointed to by pure bytecode which we don't trace,
5718 so we conservatively assume that it is live. */
5719 int pure_p = PURE_POINTER_P (XSTRING (sym->xname));
5721 if (!sym->gcmarkbit && !pure_p)
5723 *(struct Lisp_Symbol **) &sym->value = symbol_free_list;
5724 symbol_free_list = sym;
5725 #if GC_MARK_STACK
5726 symbol_free_list->function = Vdead;
5727 #endif
5728 ++this_free;
5730 else
5732 ++num_used;
5733 if (!pure_p)
5734 UNMARK_STRING (XSTRING (sym->xname));
5735 sym->gcmarkbit = 0;
5739 lim = SYMBOL_BLOCK_SIZE;
5740 /* If this block contains only free symbols and we have already
5741 seen more than two blocks worth of free symbols then deallocate
5742 this block. */
5743 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
5745 *sprev = sblk->next;
5746 /* Unhook from the free list. */
5747 symbol_free_list = *(struct Lisp_Symbol **)&sblk->symbols[0].value;
5748 lisp_free (sblk);
5749 n_symbol_blocks--;
5751 else
5753 num_free += this_free;
5754 sprev = &sblk->next;
5757 total_symbols = num_used;
5758 total_free_symbols = num_free;
5761 /* Put all unmarked misc's on free list.
5762 For a marker, first unchain it from the buffer it points into. */
5764 register struct marker_block *mblk;
5765 struct marker_block **mprev = &marker_block;
5766 register int lim = marker_block_index;
5767 register int num_free = 0, num_used = 0;
5769 marker_free_list = 0;
5771 for (mblk = marker_block; mblk; mblk = *mprev)
5773 register int i;
5774 int this_free = 0;
5776 for (i = 0; i < lim; i++)
5778 if (!mblk->markers[i].u_marker.gcmarkbit)
5780 if (mblk->markers[i].u_marker.type == Lisp_Misc_Marker)
5781 unchain_marker (&mblk->markers[i].u_marker);
5782 /* Set the type of the freed object to Lisp_Misc_Free.
5783 We could leave the type alone, since nobody checks it,
5784 but this might catch bugs faster. */
5785 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
5786 mblk->markers[i].u_free.chain = marker_free_list;
5787 marker_free_list = &mblk->markers[i];
5788 this_free++;
5790 else
5792 num_used++;
5793 mblk->markers[i].u_marker.gcmarkbit = 0;
5796 lim = MARKER_BLOCK_SIZE;
5797 /* If this block contains only free markers and we have already
5798 seen more than two blocks worth of free markers then deallocate
5799 this block. */
5800 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
5802 *mprev = mblk->next;
5803 /* Unhook from the free list. */
5804 marker_free_list = mblk->markers[0].u_free.chain;
5805 lisp_free (mblk);
5806 n_marker_blocks--;
5808 else
5810 num_free += this_free;
5811 mprev = &mblk->next;
5815 total_markers = num_used;
5816 total_free_markers = num_free;
5819 /* Free all unmarked buffers */
5821 register struct buffer *buffer = all_buffers, *prev = 0, *next;
5823 while (buffer)
5824 if (!VECTOR_MARKED_P (buffer))
5826 if (prev)
5827 prev->next = buffer->next;
5828 else
5829 all_buffers = buffer->next;
5830 next = buffer->next;
5831 lisp_free (buffer);
5832 buffer = next;
5834 else
5836 VECTOR_UNMARK (buffer);
5837 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
5838 prev = buffer, buffer = buffer->next;
5842 /* Free all unmarked vectors */
5844 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
5845 total_vector_size = 0;
5847 while (vector)
5848 if (!VECTOR_MARKED_P (vector))
5850 if (prev)
5851 prev->next = vector->next;
5852 else
5853 all_vectors = vector->next;
5854 next = vector->next;
5855 lisp_free (vector);
5856 n_vectors--;
5857 vector = next;
5860 else
5862 VECTOR_UNMARK (vector);
5863 if (vector->size & PSEUDOVECTOR_FLAG)
5864 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
5865 else
5866 total_vector_size += vector->size;
5867 prev = vector, vector = vector->next;
5871 #ifdef GC_CHECK_STRING_BYTES
5872 if (!noninteractive)
5873 check_string_bytes (1);
5874 #endif
5880 /* Debugging aids. */
5882 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
5883 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
5884 This may be helpful in debugging Emacs's memory usage.
5885 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
5888 Lisp_Object end;
5890 XSETINT (end, (EMACS_INT) sbrk (0) / 1024);
5892 return end;
5895 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
5896 doc: /* Return a list of counters that measure how much consing there has been.
5897 Each of these counters increments for a certain kind of object.
5898 The counters wrap around from the largest positive integer to zero.
5899 Garbage collection does not decrease them.
5900 The elements of the value are as follows:
5901 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
5902 All are in units of 1 = one object consed
5903 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
5904 objects consed.
5905 MISCS include overlays, markers, and some internal types.
5906 Frames, windows, buffers, and subprocesses count as vectors
5907 (but the contents of a buffer's text do not count here). */)
5910 Lisp_Object consed[8];
5912 consed[0] = make_number (min (MOST_POSITIVE_FIXNUM, cons_cells_consed));
5913 consed[1] = make_number (min (MOST_POSITIVE_FIXNUM, floats_consed));
5914 consed[2] = make_number (min (MOST_POSITIVE_FIXNUM, vector_cells_consed));
5915 consed[3] = make_number (min (MOST_POSITIVE_FIXNUM, symbols_consed));
5916 consed[4] = make_number (min (MOST_POSITIVE_FIXNUM, string_chars_consed));
5917 consed[5] = make_number (min (MOST_POSITIVE_FIXNUM, misc_objects_consed));
5918 consed[6] = make_number (min (MOST_POSITIVE_FIXNUM, intervals_consed));
5919 consed[7] = make_number (min (MOST_POSITIVE_FIXNUM, strings_consed));
5921 return Flist (8, consed);
5924 int suppress_checking;
5925 void
5926 die (msg, file, line)
5927 const char *msg;
5928 const char *file;
5929 int line;
5931 fprintf (stderr, "\r\nEmacs fatal error: %s:%d: %s\r\n",
5932 file, line, msg);
5933 abort ();
5936 /* Initialization */
5938 void
5939 init_alloc_once ()
5941 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
5942 purebeg = PUREBEG;
5943 pure_size = PURESIZE;
5944 pure_bytes_used = 0;
5945 pure_bytes_used_before_overflow = 0;
5947 /* Initialize the list of free aligned blocks. */
5948 free_ablock = NULL;
5950 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
5951 mem_init ();
5952 Vdead = make_pure_string ("DEAD", 4, 4, 0);
5953 #endif
5955 all_vectors = 0;
5956 ignore_warnings = 1;
5957 #ifdef DOUG_LEA_MALLOC
5958 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
5959 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
5960 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
5961 #endif
5962 init_strings ();
5963 init_cons ();
5964 init_symbol ();
5965 init_marker ();
5966 init_float ();
5967 init_intervals ();
5969 #ifdef REL_ALLOC
5970 malloc_hysteresis = 32;
5971 #else
5972 malloc_hysteresis = 0;
5973 #endif
5975 spare_memory = (char *) malloc (SPARE_MEMORY);
5977 ignore_warnings = 0;
5978 gcprolist = 0;
5979 byte_stack_list = 0;
5980 staticidx = 0;
5981 consing_since_gc = 0;
5982 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
5983 #ifdef VIRT_ADDR_VARIES
5984 malloc_sbrk_unused = 1<<22; /* A large number */
5985 malloc_sbrk_used = 100000; /* as reasonable as any number */
5986 #endif /* VIRT_ADDR_VARIES */
5989 void
5990 init_alloc ()
5992 gcprolist = 0;
5993 byte_stack_list = 0;
5994 #if GC_MARK_STACK
5995 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
5996 setjmp_tested_p = longjmps_done = 0;
5997 #endif
5998 #endif
5999 Vgc_elapsed = make_float (0.0);
6000 gcs_done = 0;
6003 void
6004 syms_of_alloc ()
6006 DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold,
6007 doc: /* *Number of bytes of consing between garbage collections.
6008 Garbage collection can happen automatically once this many bytes have been
6009 allocated since the last garbage collection. All data types count.
6011 Garbage collection happens automatically only when `eval' is called.
6013 By binding this temporarily to a large number, you can effectively
6014 prevent garbage collection during a part of the program. */);
6016 DEFVAR_INT ("pure-bytes-used", &pure_bytes_used,
6017 doc: /* Number of bytes of sharable Lisp data allocated so far. */);
6019 DEFVAR_INT ("cons-cells-consed", &cons_cells_consed,
6020 doc: /* Number of cons cells that have been consed so far. */);
6022 DEFVAR_INT ("floats-consed", &floats_consed,
6023 doc: /* Number of floats that have been consed so far. */);
6025 DEFVAR_INT ("vector-cells-consed", &vector_cells_consed,
6026 doc: /* Number of vector cells that have been consed so far. */);
6028 DEFVAR_INT ("symbols-consed", &symbols_consed,
6029 doc: /* Number of symbols that have been consed so far. */);
6031 DEFVAR_INT ("string-chars-consed", &string_chars_consed,
6032 doc: /* Number of string characters that have been consed so far. */);
6034 DEFVAR_INT ("misc-objects-consed", &misc_objects_consed,
6035 doc: /* Number of miscellaneous objects that have been consed so far. */);
6037 DEFVAR_INT ("intervals-consed", &intervals_consed,
6038 doc: /* Number of intervals that have been consed so far. */);
6040 DEFVAR_INT ("strings-consed", &strings_consed,
6041 doc: /* Number of strings that have been consed so far. */);
6043 DEFVAR_LISP ("purify-flag", &Vpurify_flag,
6044 doc: /* Non-nil means loading Lisp code in order to dump an executable.
6045 This means that certain objects should be allocated in shared (pure) space. */);
6047 DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
6048 doc: /* Non-nil means display messages at start and end of garbage collection. */);
6049 garbage_collection_messages = 0;
6051 DEFVAR_LISP ("post-gc-hook", &Vpost_gc_hook,
6052 doc: /* Hook run after garbage collection has finished. */);
6053 Vpost_gc_hook = Qnil;
6054 Qpost_gc_hook = intern ("post-gc-hook");
6055 staticpro (&Qpost_gc_hook);
6057 DEFVAR_LISP ("memory-signal-data", &Vmemory_signal_data,
6058 doc: /* Precomputed `signal' argument for memory-full error. */);
6059 /* We build this in advance because if we wait until we need it, we might
6060 not be able to allocate the memory to hold it. */
6061 Vmemory_signal_data
6062 = list2 (Qerror,
6063 build_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
6065 DEFVAR_LISP ("memory-full", &Vmemory_full,
6066 doc: /* Non-nil means we are handling a memory-full error. */);
6067 Vmemory_full = Qnil;
6069 staticpro (&Qgc_cons_threshold);
6070 Qgc_cons_threshold = intern ("gc-cons-threshold");
6072 staticpro (&Qchar_table_extra_slots);
6073 Qchar_table_extra_slots = intern ("char-table-extra-slots");
6075 DEFVAR_LISP ("gc-elapsed", &Vgc_elapsed,
6076 doc: /* Accumulated time elapsed in garbage collections.
6077 The time is in seconds as a floating point value. */);
6078 DEFVAR_INT ("gcs-done", &gcs_done,
6079 doc: /* Accumulated number of garbage collections done. */);
6081 defsubr (&Scons);
6082 defsubr (&Slist);
6083 defsubr (&Svector);
6084 defsubr (&Smake_byte_code);
6085 defsubr (&Smake_list);
6086 defsubr (&Smake_vector);
6087 defsubr (&Smake_char_table);
6088 defsubr (&Smake_string);
6089 defsubr (&Smake_bool_vector);
6090 defsubr (&Smake_symbol);
6091 defsubr (&Smake_marker);
6092 defsubr (&Spurecopy);
6093 defsubr (&Sgarbage_collect);
6094 defsubr (&Smemory_limit);
6095 defsubr (&Smemory_use_counts);
6097 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
6098 defsubr (&Sgc_status);
6099 #endif
6102 /* arch-tag: 6695ca10-e3c5-4c2c-8bc3-ed26a7dda857
6103 (do not change this comment) */