Merge from trunk
[emacs.git] / src / alloc.c
blob23debbdf2e80ee5ea2e1af461332faf95287b2b8
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, 2006, 2007, 2008, 2009, 2010
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21 #include <config.h>
22 #include <stdio.h>
23 #include <limits.h> /* For CHAR_BIT. */
24 #include <setjmp.h>
26 #ifdef ALLOC_DEBUG
27 #undef INLINE
28 #endif
30 #include <signal.h>
32 #ifdef HAVE_GTK_AND_PTHREAD
33 #include <pthread.h>
34 #endif
36 /* This file is part of the core Lisp implementation, and thus must
37 deal with the real data structures. If the Lisp implementation is
38 replaced, this file likely will not be used. */
40 #undef HIDE_LISP_IMPLEMENTATION
41 #include "lisp.h"
42 #include "process.h"
43 #include "intervals.h"
44 #include "puresize.h"
45 #include "buffer.h"
46 #include "window.h"
47 #include "keyboard.h"
48 #include "frame.h"
49 #include "blockinput.h"
50 #include "character.h"
51 #include "syssignal.h"
52 #include "termhooks.h" /* For struct terminal. */
53 #include <setjmp.h>
55 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
56 memory. Can do this only if using gmalloc.c. */
58 #if defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC
59 #undef GC_MALLOC_CHECK
60 #endif
62 #ifdef HAVE_UNISTD_H
63 #include <unistd.h>
64 #else
65 extern POINTER_TYPE *sbrk ();
66 #endif
68 #ifdef HAVE_FCNTL_H
69 #include <fcntl.h>
70 #endif
71 #ifndef O_WRONLY
72 #define O_WRONLY 1
73 #endif
75 #ifdef WINDOWSNT
76 #include <fcntl.h>
77 #include "w32.h"
78 #endif
80 #ifdef DOUG_LEA_MALLOC
82 #include <malloc.h>
83 /* malloc.h #defines this as size_t, at least in glibc2. */
84 #ifndef __malloc_size_t
85 #define __malloc_size_t int
86 #endif
88 /* Specify maximum number of areas to mmap. It would be nice to use a
89 value that explicitly means "no limit". */
91 #define MMAP_MAX_AREAS 100000000
93 #else /* not DOUG_LEA_MALLOC */
95 /* The following come from gmalloc.c. */
97 #define __malloc_size_t size_t
98 extern __malloc_size_t _bytes_used;
99 extern __malloc_size_t __malloc_extra_blocks;
101 #endif /* not DOUG_LEA_MALLOC */
103 #if ! defined (SYSTEM_MALLOC) && defined (HAVE_GTK_AND_PTHREAD)
105 /* When GTK uses the file chooser dialog, different backends can be loaded
106 dynamically. One such a backend is the Gnome VFS backend that gets loaded
107 if you run Gnome. That backend creates several threads and also allocates
108 memory with malloc.
110 If Emacs sets malloc hooks (! SYSTEM_MALLOC) and the emacs_blocked_*
111 functions below are called from malloc, there is a chance that one
112 of these threads preempts the Emacs main thread and the hook variables
113 end up in an inconsistent state. So we have a mutex to prevent that (note
114 that the backend handles concurrent access to malloc within its own threads
115 but Emacs code running in the main thread is not included in that control).
117 When UNBLOCK_INPUT is called, reinvoke_input_signal may be called. If this
118 happens in one of the backend threads we will have two threads that tries
119 to run Emacs code at once, and the code is not prepared for that.
120 To prevent that, we only call BLOCK/UNBLOCK from the main thread. */
122 static pthread_mutex_t alloc_mutex;
124 #define BLOCK_INPUT_ALLOC \
125 do \
127 if (pthread_equal (pthread_self (), main_thread)) \
128 BLOCK_INPUT; \
129 pthread_mutex_lock (&alloc_mutex); \
131 while (0)
132 #define UNBLOCK_INPUT_ALLOC \
133 do \
135 pthread_mutex_unlock (&alloc_mutex); \
136 if (pthread_equal (pthread_self (), main_thread)) \
137 UNBLOCK_INPUT; \
139 while (0)
141 #else /* SYSTEM_MALLOC || not HAVE_GTK_AND_PTHREAD */
143 #define BLOCK_INPUT_ALLOC BLOCK_INPUT
144 #define UNBLOCK_INPUT_ALLOC UNBLOCK_INPUT
146 #endif /* SYSTEM_MALLOC || not HAVE_GTK_AND_PTHREAD */
148 /* Value of _bytes_used, when spare_memory was freed. */
150 static __malloc_size_t bytes_used_when_full;
152 static __malloc_size_t bytes_used_when_reconsidered;
154 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
155 to a struct Lisp_String. */
157 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
158 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
159 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
161 #define VECTOR_MARK(V) ((V)->size |= ARRAY_MARK_FLAG)
162 #define VECTOR_UNMARK(V) ((V)->size &= ~ARRAY_MARK_FLAG)
163 #define VECTOR_MARKED_P(V) (((V)->size & ARRAY_MARK_FLAG) != 0)
165 /* Value is the number of bytes/chars of S, a pointer to a struct
166 Lisp_String. This must be used instead of STRING_BYTES (S) or
167 S->size during GC, because S->size contains the mark bit for
168 strings. */
170 #define GC_STRING_BYTES(S) (STRING_BYTES (S))
171 #define GC_STRING_CHARS(S) ((S)->size & ~ARRAY_MARK_FLAG)
173 /* Number of bytes of consing done since the last gc. */
175 int consing_since_gc;
177 /* Count the amount of consing of various sorts of space. */
179 EMACS_INT cons_cells_consed;
180 EMACS_INT floats_consed;
181 EMACS_INT vector_cells_consed;
182 EMACS_INT symbols_consed;
183 EMACS_INT string_chars_consed;
184 EMACS_INT misc_objects_consed;
185 EMACS_INT intervals_consed;
186 EMACS_INT strings_consed;
188 /* Minimum number of bytes of consing since GC before next GC. */
190 EMACS_INT gc_cons_threshold;
192 /* Similar minimum, computed from Vgc_cons_percentage. */
194 EMACS_INT gc_relative_threshold;
196 static Lisp_Object Vgc_cons_percentage;
198 /* Minimum number of bytes of consing since GC before next GC,
199 when memory is full. */
201 EMACS_INT memory_full_cons_threshold;
203 /* Nonzero during GC. */
205 int gc_in_progress;
207 /* Nonzero means abort if try to GC.
208 This is for code which is written on the assumption that
209 no GC will happen, so as to verify that assumption. */
211 int abort_on_gc;
213 /* Nonzero means display messages at beginning and end of GC. */
215 int garbage_collection_messages;
217 #ifndef VIRT_ADDR_VARIES
218 extern
219 #endif /* VIRT_ADDR_VARIES */
220 int malloc_sbrk_used;
222 #ifndef VIRT_ADDR_VARIES
223 extern
224 #endif /* VIRT_ADDR_VARIES */
225 int malloc_sbrk_unused;
227 /* Number of live and free conses etc. */
229 static int total_conses, total_markers, total_symbols, total_vector_size;
230 static int total_free_conses, total_free_markers, total_free_symbols;
231 static int total_free_floats, total_floats;
233 /* Points to memory space allocated as "spare", to be freed if we run
234 out of memory. We keep one large block, four cons-blocks, and
235 two string blocks. */
237 static char *spare_memory[7];
239 /* Amount of spare memory to keep in large reserve block. */
241 #define SPARE_MEMORY (1 << 14)
243 /* Number of extra blocks malloc should get when it needs more core. */
245 static int malloc_hysteresis;
247 /* Non-nil means defun should do purecopy on the function definition. */
249 Lisp_Object Vpurify_flag;
251 /* Non-nil means we are handling a memory-full error. */
253 Lisp_Object Vmemory_full;
255 /* Initialize it to a nonzero value to force it into data space
256 (rather than bss space). That way unexec will remap it into text
257 space (pure), on some systems. We have not implemented the
258 remapping on more recent systems because this is less important
259 nowadays than in the days of small memories and timesharing. */
261 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
262 #define PUREBEG (char *) pure
264 /* Pointer to the pure area, and its size. */
266 static char *purebeg;
267 static size_t pure_size;
269 /* Number of bytes of pure storage used before pure storage overflowed.
270 If this is non-zero, this implies that an overflow occurred. */
272 static size_t pure_bytes_used_before_overflow;
274 /* Value is non-zero if P points into pure space. */
276 #define PURE_POINTER_P(P) \
277 (((PNTR_COMPARISON_TYPE) (P) \
278 < (PNTR_COMPARISON_TYPE) ((char *) purebeg + pure_size)) \
279 && ((PNTR_COMPARISON_TYPE) (P) \
280 >= (PNTR_COMPARISON_TYPE) purebeg))
282 /* Total number of bytes allocated in pure storage. */
284 EMACS_INT pure_bytes_used;
286 /* Index in pure at which next pure Lisp object will be allocated.. */
288 static EMACS_INT pure_bytes_used_lisp;
290 /* Number of bytes allocated for non-Lisp objects in pure storage. */
292 static EMACS_INT pure_bytes_used_non_lisp;
294 /* If nonzero, this is a warning delivered by malloc and not yet
295 displayed. */
297 const char *pending_malloc_warning;
299 /* Pre-computed signal argument for use when memory is exhausted. */
301 Lisp_Object Vmemory_signal_data;
303 /* Maximum amount of C stack to save when a GC happens. */
305 #ifndef MAX_SAVE_STACK
306 #define MAX_SAVE_STACK 16000
307 #endif
309 /* Buffer in which we save a copy of the C stack at each GC. */
311 static char *stack_copy;
312 static int stack_copy_size;
314 /* Non-zero means ignore malloc warnings. Set during initialization.
315 Currently not used. */
317 static int ignore_warnings;
319 Lisp_Object Qgc_cons_threshold, Qchar_table_extra_slots;
321 /* Hook run after GC has finished. */
323 Lisp_Object Vpost_gc_hook, Qpost_gc_hook;
325 Lisp_Object Vgc_elapsed; /* accumulated elapsed time in GC */
326 EMACS_INT gcs_done; /* accumulated GCs */
328 static void mark_buffer (Lisp_Object);
329 static void mark_terminals (void);
330 extern void mark_kboards (void);
331 extern void mark_ttys (void);
332 extern void mark_backtrace (void);
333 static void gc_sweep (void);
334 static void mark_glyph_matrix (struct glyph_matrix *);
335 static void mark_face_cache (struct face_cache *);
337 #ifdef HAVE_WINDOW_SYSTEM
338 extern void mark_fringe_data (void);
339 #endif /* HAVE_WINDOW_SYSTEM */
341 static struct Lisp_String *allocate_string (void);
342 static void compact_small_strings (void);
343 static void free_large_strings (void);
344 static void sweep_strings (void);
346 extern int message_enable_multibyte;
348 /* When scanning the C stack for live Lisp objects, Emacs keeps track
349 of what memory allocated via lisp_malloc is intended for what
350 purpose. This enumeration specifies the type of memory. */
352 enum mem_type
354 MEM_TYPE_NON_LISP,
355 MEM_TYPE_BUFFER,
356 MEM_TYPE_CONS,
357 MEM_TYPE_STRING,
358 MEM_TYPE_MISC,
359 MEM_TYPE_SYMBOL,
360 MEM_TYPE_FLOAT,
361 /* We used to keep separate mem_types for subtypes of vectors such as
362 process, hash_table, frame, terminal, and window, but we never made
363 use of the distinction, so it only caused source-code complexity
364 and runtime slowdown. Minor but pointless. */
365 MEM_TYPE_VECTORLIKE
368 static POINTER_TYPE *lisp_align_malloc (size_t, enum mem_type);
369 static POINTER_TYPE *lisp_malloc (size_t, enum mem_type);
370 void refill_memory_reserve (void);
373 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
375 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
376 #include <stdio.h> /* For fprintf. */
377 #endif
379 /* A unique object in pure space used to make some Lisp objects
380 on free lists recognizable in O(1). */
382 static Lisp_Object Vdead;
384 #ifdef GC_MALLOC_CHECK
386 enum mem_type allocated_mem_type;
387 static int dont_register_blocks;
389 #endif /* GC_MALLOC_CHECK */
391 /* A node in the red-black tree describing allocated memory containing
392 Lisp data. Each such block is recorded with its start and end
393 address when it is allocated, and removed from the tree when it
394 is freed.
396 A red-black tree is a balanced binary tree with the following
397 properties:
399 1. Every node is either red or black.
400 2. Every leaf is black.
401 3. If a node is red, then both of its children are black.
402 4. Every simple path from a node to a descendant leaf contains
403 the same number of black nodes.
404 5. The root is always black.
406 When nodes are inserted into the tree, or deleted from the tree,
407 the tree is "fixed" so that these properties are always true.
409 A red-black tree with N internal nodes has height at most 2
410 log(N+1). Searches, insertions and deletions are done in O(log N).
411 Please see a text book about data structures for a detailed
412 description of red-black trees. Any book worth its salt should
413 describe them. */
415 struct mem_node
417 /* Children of this node. These pointers are never NULL. When there
418 is no child, the value is MEM_NIL, which points to a dummy node. */
419 struct mem_node *left, *right;
421 /* The parent of this node. In the root node, this is NULL. */
422 struct mem_node *parent;
424 /* Start and end of allocated region. */
425 void *start, *end;
427 /* Node color. */
428 enum {MEM_BLACK, MEM_RED} color;
430 /* Memory type. */
431 enum mem_type type;
434 /* Base address of stack. Set in main. */
436 Lisp_Object *stack_base;
438 /* Root of the tree describing allocated Lisp memory. */
440 static struct mem_node *mem_root;
442 /* Lowest and highest known address in the heap. */
444 static void *min_heap_address, *max_heap_address;
446 /* Sentinel node of the tree. */
448 static struct mem_node mem_z;
449 #define MEM_NIL &mem_z
451 static struct Lisp_Vector *allocate_vectorlike (EMACS_INT);
452 static void lisp_free (POINTER_TYPE *);
453 static void mark_stack (void);
454 static int live_vector_p (struct mem_node *, void *);
455 static int live_buffer_p (struct mem_node *, void *);
456 static int live_string_p (struct mem_node *, void *);
457 static int live_cons_p (struct mem_node *, void *);
458 static int live_symbol_p (struct mem_node *, void *);
459 static int live_float_p (struct mem_node *, void *);
460 static int live_misc_p (struct mem_node *, void *);
461 static void mark_maybe_object (Lisp_Object);
462 static void mark_memory (void *, void *, int);
463 static void mem_init (void);
464 static struct mem_node *mem_insert (void *, void *, enum mem_type);
465 static void mem_insert_fixup (struct mem_node *);
466 static void mem_rotate_left (struct mem_node *);
467 static void mem_rotate_right (struct mem_node *);
468 static void mem_delete (struct mem_node *);
469 static void mem_delete_fixup (struct mem_node *);
470 static INLINE struct mem_node *mem_find (void *);
473 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
474 static void check_gcpros (void);
475 #endif
477 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
479 /* Recording what needs to be marked for gc. */
481 struct gcpro *gcprolist;
483 /* Addresses of staticpro'd variables. Initialize it to a nonzero
484 value; otherwise some compilers put it into BSS. */
486 #define NSTATICS 0x640
487 static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
489 /* Index of next unused slot in staticvec. */
491 static int staticidx = 0;
493 static POINTER_TYPE *pure_alloc (size_t, int);
496 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
497 ALIGNMENT must be a power of 2. */
499 #define ALIGN(ptr, ALIGNMENT) \
500 ((POINTER_TYPE *) ((((EMACS_UINT)(ptr)) + (ALIGNMENT) - 1) \
501 & ~((ALIGNMENT) - 1)))
505 /************************************************************************
506 Malloc
507 ************************************************************************/
509 /* Function malloc calls this if it finds we are near exhausting storage. */
511 void
512 malloc_warning (const char *str)
514 pending_malloc_warning = str;
518 /* Display an already-pending malloc warning. */
520 void
521 display_malloc_warning (void)
523 call3 (intern ("display-warning"),
524 intern ("alloc"),
525 build_string (pending_malloc_warning),
526 intern ("emergency"));
527 pending_malloc_warning = 0;
531 #ifdef DOUG_LEA_MALLOC
532 # define BYTES_USED (mallinfo ().uordblks)
533 #else
534 # define BYTES_USED _bytes_used
535 #endif
537 /* Called if we can't allocate relocatable space for a buffer. */
539 void
540 buffer_memory_full (void)
542 /* If buffers use the relocating allocator, no need to free
543 spare_memory, because we may have plenty of malloc space left
544 that we could get, and if we don't, the malloc that fails will
545 itself cause spare_memory to be freed. If buffers don't use the
546 relocating allocator, treat this like any other failing
547 malloc. */
549 #ifndef REL_ALLOC
550 memory_full ();
551 #endif
553 /* This used to call error, but if we've run out of memory, we could
554 get infinite recursion trying to build the string. */
555 xsignal (Qnil, Vmemory_signal_data);
559 #ifdef XMALLOC_OVERRUN_CHECK
561 /* Check for overrun in malloc'ed buffers by wrapping a 16 byte header
562 and a 16 byte trailer around each block.
564 The header consists of 12 fixed bytes + a 4 byte integer contaning the
565 original block size, while the trailer consists of 16 fixed bytes.
567 The header is used to detect whether this block has been allocated
568 through these functions -- as it seems that some low-level libc
569 functions may bypass the malloc hooks.
573 #define XMALLOC_OVERRUN_CHECK_SIZE 16
575 static char xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE-4] =
576 { 0x9a, 0x9b, 0xae, 0xaf,
577 0xbf, 0xbe, 0xce, 0xcf,
578 0xea, 0xeb, 0xec, 0xed };
580 static char xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
581 { 0xaa, 0xab, 0xac, 0xad,
582 0xba, 0xbb, 0xbc, 0xbd,
583 0xca, 0xcb, 0xcc, 0xcd,
584 0xda, 0xdb, 0xdc, 0xdd };
586 /* Macros to insert and extract the block size in the header. */
588 #define XMALLOC_PUT_SIZE(ptr, size) \
589 (ptr[-1] = (size & 0xff), \
590 ptr[-2] = ((size >> 8) & 0xff), \
591 ptr[-3] = ((size >> 16) & 0xff), \
592 ptr[-4] = ((size >> 24) & 0xff))
594 #define XMALLOC_GET_SIZE(ptr) \
595 (size_t)((unsigned)(ptr[-1]) | \
596 ((unsigned)(ptr[-2]) << 8) | \
597 ((unsigned)(ptr[-3]) << 16) | \
598 ((unsigned)(ptr[-4]) << 24))
601 /* The call depth in overrun_check functions. For example, this might happen:
602 xmalloc()
603 overrun_check_malloc()
604 -> malloc -> (via hook)_-> emacs_blocked_malloc
605 -> overrun_check_malloc
606 call malloc (hooks are NULL, so real malloc is called).
607 malloc returns 10000.
608 add overhead, return 10016.
609 <- (back in overrun_check_malloc)
610 add overhead again, return 10032
611 xmalloc returns 10032.
613 (time passes).
615 xfree(10032)
616 overrun_check_free(10032)
617 decrease overhed
618 free(10016) <- crash, because 10000 is the original pointer. */
620 static int check_depth;
622 /* Like malloc, but wraps allocated block with header and trailer. */
624 POINTER_TYPE *
625 overrun_check_malloc (size)
626 size_t size;
628 register unsigned char *val;
629 size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
631 val = (unsigned char *) malloc (size + overhead);
632 if (val && check_depth == 1)
634 memcpy (val, xmalloc_overrun_check_header,
635 XMALLOC_OVERRUN_CHECK_SIZE - 4);
636 val += XMALLOC_OVERRUN_CHECK_SIZE;
637 XMALLOC_PUT_SIZE(val, size);
638 memcpy (val + size, xmalloc_overrun_check_trailer,
639 XMALLOC_OVERRUN_CHECK_SIZE);
641 --check_depth;
642 return (POINTER_TYPE *)val;
646 /* Like realloc, but checks old block for overrun, and wraps new block
647 with header and trailer. */
649 POINTER_TYPE *
650 overrun_check_realloc (block, size)
651 POINTER_TYPE *block;
652 size_t size;
654 register unsigned char *val = (unsigned char *)block;
655 size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
657 if (val
658 && check_depth == 1
659 && memcmp (xmalloc_overrun_check_header,
660 val - XMALLOC_OVERRUN_CHECK_SIZE,
661 XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
663 size_t osize = XMALLOC_GET_SIZE (val);
664 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
665 XMALLOC_OVERRUN_CHECK_SIZE))
666 abort ();
667 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
668 val -= XMALLOC_OVERRUN_CHECK_SIZE;
669 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE);
672 val = (unsigned char *) realloc ((POINTER_TYPE *)val, size + overhead);
674 if (val && check_depth == 1)
676 memcpy (val, xmalloc_overrun_check_header,
677 XMALLOC_OVERRUN_CHECK_SIZE - 4);
678 val += XMALLOC_OVERRUN_CHECK_SIZE;
679 XMALLOC_PUT_SIZE(val, size);
680 memcpy (val + size, xmalloc_overrun_check_trailer,
681 XMALLOC_OVERRUN_CHECK_SIZE);
683 --check_depth;
684 return (POINTER_TYPE *)val;
687 /* Like free, but checks block for overrun. */
689 void
690 overrun_check_free (block)
691 POINTER_TYPE *block;
693 unsigned char *val = (unsigned char *)block;
695 ++check_depth;
696 if (val
697 && check_depth == 1
698 && memcmp (xmalloc_overrun_check_header,
699 val - XMALLOC_OVERRUN_CHECK_SIZE,
700 XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
702 size_t osize = XMALLOC_GET_SIZE (val);
703 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
704 XMALLOC_OVERRUN_CHECK_SIZE))
705 abort ();
706 #ifdef XMALLOC_CLEAR_FREE_MEMORY
707 val -= XMALLOC_OVERRUN_CHECK_SIZE;
708 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_SIZE*2);
709 #else
710 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
711 val -= XMALLOC_OVERRUN_CHECK_SIZE;
712 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE);
713 #endif
716 free (val);
717 --check_depth;
720 #undef malloc
721 #undef realloc
722 #undef free
723 #define malloc overrun_check_malloc
724 #define realloc overrun_check_realloc
725 #define free overrun_check_free
726 #endif
728 #ifdef SYNC_INPUT
729 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
730 there's no need to block input around malloc. */
731 #define MALLOC_BLOCK_INPUT ((void)0)
732 #define MALLOC_UNBLOCK_INPUT ((void)0)
733 #else
734 #define MALLOC_BLOCK_INPUT BLOCK_INPUT
735 #define MALLOC_UNBLOCK_INPUT UNBLOCK_INPUT
736 #endif
738 /* Like malloc but check for no memory and block interrupt input.. */
740 POINTER_TYPE *
741 xmalloc (size_t size)
743 register POINTER_TYPE *val;
745 MALLOC_BLOCK_INPUT;
746 val = (POINTER_TYPE *) malloc (size);
747 MALLOC_UNBLOCK_INPUT;
749 if (!val && size)
750 memory_full ();
751 return val;
755 /* Like realloc but check for no memory and block interrupt input.. */
757 POINTER_TYPE *
758 xrealloc (POINTER_TYPE *block, size_t size)
760 register POINTER_TYPE *val;
762 MALLOC_BLOCK_INPUT;
763 /* We must call malloc explicitly when BLOCK is 0, since some
764 reallocs don't do this. */
765 if (! block)
766 val = (POINTER_TYPE *) malloc (size);
767 else
768 val = (POINTER_TYPE *) realloc (block, size);
769 MALLOC_UNBLOCK_INPUT;
771 if (!val && size) memory_full ();
772 return val;
776 /* Like free but block interrupt input. */
778 void
779 xfree (POINTER_TYPE *block)
781 if (!block)
782 return;
783 MALLOC_BLOCK_INPUT;
784 free (block);
785 MALLOC_UNBLOCK_INPUT;
786 /* We don't call refill_memory_reserve here
787 because that duplicates doing so in emacs_blocked_free
788 and the criterion should go there. */
792 /* Like strdup, but uses xmalloc. */
794 char *
795 xstrdup (const char *s)
797 size_t len = strlen (s) + 1;
798 char *p = (char *) xmalloc (len);
799 memcpy (p, s, len);
800 return p;
804 /* Unwind for SAFE_ALLOCA */
806 Lisp_Object
807 safe_alloca_unwind (Lisp_Object arg)
809 register struct Lisp_Save_Value *p = XSAVE_VALUE (arg);
811 p->dogc = 0;
812 xfree (p->pointer);
813 p->pointer = 0;
814 free_misc (arg);
815 return Qnil;
819 /* Like malloc but used for allocating Lisp data. NBYTES is the
820 number of bytes to allocate, TYPE describes the intended use of the
821 allcated memory block (for strings, for conses, ...). */
823 #ifndef USE_LSB_TAG
824 static void *lisp_malloc_loser;
825 #endif
827 static POINTER_TYPE *
828 lisp_malloc (size_t nbytes, enum mem_type type)
830 register void *val;
832 MALLOC_BLOCK_INPUT;
834 #ifdef GC_MALLOC_CHECK
835 allocated_mem_type = type;
836 #endif
838 val = (void *) malloc (nbytes);
840 #ifndef USE_LSB_TAG
841 /* If the memory just allocated cannot be addressed thru a Lisp
842 object's pointer, and it needs to be,
843 that's equivalent to running out of memory. */
844 if (val && type != MEM_TYPE_NON_LISP)
846 Lisp_Object tem;
847 XSETCONS (tem, (char *) val + nbytes - 1);
848 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
850 lisp_malloc_loser = val;
851 free (val);
852 val = 0;
855 #endif
857 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
858 if (val && type != MEM_TYPE_NON_LISP)
859 mem_insert (val, (char *) val + nbytes, type);
860 #endif
862 MALLOC_UNBLOCK_INPUT;
863 if (!val && nbytes)
864 memory_full ();
865 return val;
868 /* Free BLOCK. This must be called to free memory allocated with a
869 call to lisp_malloc. */
871 static void
872 lisp_free (POINTER_TYPE *block)
874 MALLOC_BLOCK_INPUT;
875 free (block);
876 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
877 mem_delete (mem_find (block));
878 #endif
879 MALLOC_UNBLOCK_INPUT;
882 /* Allocation of aligned blocks of memory to store Lisp data. */
883 /* The entry point is lisp_align_malloc which returns blocks of at most */
884 /* BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
886 /* Use posix_memalloc if the system has it and we're using the system's
887 malloc (because our gmalloc.c routines don't have posix_memalign although
888 its memalloc could be used). */
889 #if defined (HAVE_POSIX_MEMALIGN) && defined (SYSTEM_MALLOC)
890 #define USE_POSIX_MEMALIGN 1
891 #endif
893 /* BLOCK_ALIGN has to be a power of 2. */
894 #define BLOCK_ALIGN (1 << 10)
896 /* Padding to leave at the end of a malloc'd block. This is to give
897 malloc a chance to minimize the amount of memory wasted to alignment.
898 It should be tuned to the particular malloc library used.
899 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
900 posix_memalign on the other hand would ideally prefer a value of 4
901 because otherwise, there's 1020 bytes wasted between each ablocks.
902 In Emacs, testing shows that those 1020 can most of the time be
903 efficiently used by malloc to place other objects, so a value of 0 can
904 still preferable unless you have a lot of aligned blocks and virtually
905 nothing else. */
906 #define BLOCK_PADDING 0
907 #define BLOCK_BYTES \
908 (BLOCK_ALIGN - sizeof (struct ablock *) - BLOCK_PADDING)
910 /* Internal data structures and constants. */
912 #define ABLOCKS_SIZE 16
914 /* An aligned block of memory. */
915 struct ablock
917 union
919 char payload[BLOCK_BYTES];
920 struct ablock *next_free;
921 } x;
922 /* `abase' is the aligned base of the ablocks. */
923 /* It is overloaded to hold the virtual `busy' field that counts
924 the number of used ablock in the parent ablocks.
925 The first ablock has the `busy' field, the others have the `abase'
926 field. To tell the difference, we assume that pointers will have
927 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
928 is used to tell whether the real base of the parent ablocks is `abase'
929 (if not, the word before the first ablock holds a pointer to the
930 real base). */
931 struct ablocks *abase;
932 /* The padding of all but the last ablock is unused. The padding of
933 the last ablock in an ablocks is not allocated. */
934 #if BLOCK_PADDING
935 char padding[BLOCK_PADDING];
936 #endif
939 /* A bunch of consecutive aligned blocks. */
940 struct ablocks
942 struct ablock blocks[ABLOCKS_SIZE];
945 /* Size of the block requested from malloc or memalign. */
946 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
948 #define ABLOCK_ABASE(block) \
949 (((unsigned long) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
950 ? (struct ablocks *)(block) \
951 : (block)->abase)
953 /* Virtual `busy' field. */
954 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
956 /* Pointer to the (not necessarily aligned) malloc block. */
957 #ifdef USE_POSIX_MEMALIGN
958 #define ABLOCKS_BASE(abase) (abase)
959 #else
960 #define ABLOCKS_BASE(abase) \
961 (1 & (long) ABLOCKS_BUSY (abase) ? abase : ((void**)abase)[-1])
962 #endif
964 /* The list of free ablock. */
965 static struct ablock *free_ablock;
967 /* Allocate an aligned block of nbytes.
968 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
969 smaller or equal to BLOCK_BYTES. */
970 static POINTER_TYPE *
971 lisp_align_malloc (size_t nbytes, enum mem_type type)
973 void *base, *val;
974 struct ablocks *abase;
976 eassert (nbytes <= BLOCK_BYTES);
978 MALLOC_BLOCK_INPUT;
980 #ifdef GC_MALLOC_CHECK
981 allocated_mem_type = type;
982 #endif
984 if (!free_ablock)
986 int i;
987 EMACS_INT aligned; /* int gets warning casting to 64-bit pointer. */
989 #ifdef DOUG_LEA_MALLOC
990 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
991 because mapped region contents are not preserved in
992 a dumped Emacs. */
993 mallopt (M_MMAP_MAX, 0);
994 #endif
996 #ifdef USE_POSIX_MEMALIGN
998 int err = posix_memalign (&base, BLOCK_ALIGN, ABLOCKS_BYTES);
999 if (err)
1000 base = NULL;
1001 abase = base;
1003 #else
1004 base = malloc (ABLOCKS_BYTES);
1005 abase = ALIGN (base, BLOCK_ALIGN);
1006 #endif
1008 if (base == 0)
1010 MALLOC_UNBLOCK_INPUT;
1011 memory_full ();
1014 aligned = (base == abase);
1015 if (!aligned)
1016 ((void**)abase)[-1] = base;
1018 #ifdef DOUG_LEA_MALLOC
1019 /* Back to a reasonable maximum of mmap'ed areas. */
1020 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1021 #endif
1023 #ifndef USE_LSB_TAG
1024 /* If the memory just allocated cannot be addressed thru a Lisp
1025 object's pointer, and it needs to be, that's equivalent to
1026 running out of memory. */
1027 if (type != MEM_TYPE_NON_LISP)
1029 Lisp_Object tem;
1030 char *end = (char *) base + ABLOCKS_BYTES - 1;
1031 XSETCONS (tem, end);
1032 if ((char *) XCONS (tem) != end)
1034 lisp_malloc_loser = base;
1035 free (base);
1036 MALLOC_UNBLOCK_INPUT;
1037 memory_full ();
1040 #endif
1042 /* Initialize the blocks and put them on the free list.
1043 Is `base' was not properly aligned, we can't use the last block. */
1044 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1046 abase->blocks[i].abase = abase;
1047 abase->blocks[i].x.next_free = free_ablock;
1048 free_ablock = &abase->blocks[i];
1050 ABLOCKS_BUSY (abase) = (struct ablocks *) (long) aligned;
1052 eassert (0 == ((EMACS_UINT)abase) % BLOCK_ALIGN);
1053 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1054 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1055 eassert (ABLOCKS_BASE (abase) == base);
1056 eassert (aligned == (long) ABLOCKS_BUSY (abase));
1059 abase = ABLOCK_ABASE (free_ablock);
1060 ABLOCKS_BUSY (abase) = (struct ablocks *) (2 + (long) ABLOCKS_BUSY (abase));
1061 val = free_ablock;
1062 free_ablock = free_ablock->x.next_free;
1064 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1065 if (val && type != MEM_TYPE_NON_LISP)
1066 mem_insert (val, (char *) val + nbytes, type);
1067 #endif
1069 MALLOC_UNBLOCK_INPUT;
1070 if (!val && nbytes)
1071 memory_full ();
1073 eassert (0 == ((EMACS_UINT)val) % BLOCK_ALIGN);
1074 return val;
1077 static void
1078 lisp_align_free (POINTER_TYPE *block)
1080 struct ablock *ablock = block;
1081 struct ablocks *abase = ABLOCK_ABASE (ablock);
1083 MALLOC_BLOCK_INPUT;
1084 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1085 mem_delete (mem_find (block));
1086 #endif
1087 /* Put on free list. */
1088 ablock->x.next_free = free_ablock;
1089 free_ablock = ablock;
1090 /* Update busy count. */
1091 ABLOCKS_BUSY (abase) = (struct ablocks *) (-2 + (long) ABLOCKS_BUSY (abase));
1093 if (2 > (long) ABLOCKS_BUSY (abase))
1094 { /* All the blocks are free. */
1095 int i = 0, aligned = (long) ABLOCKS_BUSY (abase);
1096 struct ablock **tem = &free_ablock;
1097 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1099 while (*tem)
1101 if (*tem >= (struct ablock *) abase && *tem < atop)
1103 i++;
1104 *tem = (*tem)->x.next_free;
1106 else
1107 tem = &(*tem)->x.next_free;
1109 eassert ((aligned & 1) == aligned);
1110 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1111 #ifdef USE_POSIX_MEMALIGN
1112 eassert ((unsigned long)ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1113 #endif
1114 free (ABLOCKS_BASE (abase));
1116 MALLOC_UNBLOCK_INPUT;
1119 /* Return a new buffer structure allocated from the heap with
1120 a call to lisp_malloc. */
1122 struct buffer *
1123 allocate_buffer (void)
1125 struct buffer *b
1126 = (struct buffer *) lisp_malloc (sizeof (struct buffer),
1127 MEM_TYPE_BUFFER);
1128 b->size = sizeof (struct buffer) / sizeof (EMACS_INT);
1129 XSETPVECTYPE (b, PVEC_BUFFER);
1130 return b;
1134 #ifndef SYSTEM_MALLOC
1136 /* Arranging to disable input signals while we're in malloc.
1138 This only works with GNU malloc. To help out systems which can't
1139 use GNU malloc, all the calls to malloc, realloc, and free
1140 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
1141 pair; unfortunately, we have no idea what C library functions
1142 might call malloc, so we can't really protect them unless you're
1143 using GNU malloc. Fortunately, most of the major operating systems
1144 can use GNU malloc. */
1146 #ifndef SYNC_INPUT
1147 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
1148 there's no need to block input around malloc. */
1150 #ifndef DOUG_LEA_MALLOC
1151 extern void * (*__malloc_hook) (size_t, const void *);
1152 extern void * (*__realloc_hook) (void *, size_t, const void *);
1153 extern void (*__free_hook) (void *, const void *);
1154 /* Else declared in malloc.h, perhaps with an extra arg. */
1155 #endif /* DOUG_LEA_MALLOC */
1156 static void * (*old_malloc_hook) (size_t, const void *);
1157 static void * (*old_realloc_hook) (void *, size_t, const void*);
1158 static void (*old_free_hook) (void*, const void*);
1160 /* This function is used as the hook for free to call. */
1162 static void
1163 emacs_blocked_free (void *ptr, const void *ptr2)
1165 BLOCK_INPUT_ALLOC;
1167 #ifdef GC_MALLOC_CHECK
1168 if (ptr)
1170 struct mem_node *m;
1172 m = mem_find (ptr);
1173 if (m == MEM_NIL || m->start != ptr)
1175 fprintf (stderr,
1176 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
1177 abort ();
1179 else
1181 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
1182 mem_delete (m);
1185 #endif /* GC_MALLOC_CHECK */
1187 __free_hook = old_free_hook;
1188 free (ptr);
1190 /* If we released our reserve (due to running out of memory),
1191 and we have a fair amount free once again,
1192 try to set aside another reserve in case we run out once more. */
1193 if (! NILP (Vmemory_full)
1194 /* Verify there is enough space that even with the malloc
1195 hysteresis this call won't run out again.
1196 The code here is correct as long as SPARE_MEMORY
1197 is substantially larger than the block size malloc uses. */
1198 && (bytes_used_when_full
1199 > ((bytes_used_when_reconsidered = BYTES_USED)
1200 + max (malloc_hysteresis, 4) * SPARE_MEMORY)))
1201 refill_memory_reserve ();
1203 __free_hook = emacs_blocked_free;
1204 UNBLOCK_INPUT_ALLOC;
1208 /* This function is the malloc hook that Emacs uses. */
1210 static void *
1211 emacs_blocked_malloc (size_t size, const void *ptr)
1213 void *value;
1215 BLOCK_INPUT_ALLOC;
1216 __malloc_hook = old_malloc_hook;
1217 #ifdef DOUG_LEA_MALLOC
1218 /* Segfaults on my system. --lorentey */
1219 /* mallopt (M_TOP_PAD, malloc_hysteresis * 4096); */
1220 #else
1221 __malloc_extra_blocks = malloc_hysteresis;
1222 #endif
1224 value = (void *) malloc (size);
1226 #ifdef GC_MALLOC_CHECK
1228 struct mem_node *m = mem_find (value);
1229 if (m != MEM_NIL)
1231 fprintf (stderr, "Malloc returned %p which is already in use\n",
1232 value);
1233 fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
1234 m->start, m->end, (char *) m->end - (char *) m->start,
1235 m->type);
1236 abort ();
1239 if (!dont_register_blocks)
1241 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
1242 allocated_mem_type = MEM_TYPE_NON_LISP;
1245 #endif /* GC_MALLOC_CHECK */
1247 __malloc_hook = emacs_blocked_malloc;
1248 UNBLOCK_INPUT_ALLOC;
1250 /* fprintf (stderr, "%p malloc\n", value); */
1251 return value;
1255 /* This function is the realloc hook that Emacs uses. */
1257 static void *
1258 emacs_blocked_realloc (void *ptr, size_t size, const void *ptr2)
1260 void *value;
1262 BLOCK_INPUT_ALLOC;
1263 __realloc_hook = old_realloc_hook;
1265 #ifdef GC_MALLOC_CHECK
1266 if (ptr)
1268 struct mem_node *m = mem_find (ptr);
1269 if (m == MEM_NIL || m->start != ptr)
1271 fprintf (stderr,
1272 "Realloc of %p which wasn't allocated with malloc\n",
1273 ptr);
1274 abort ();
1277 mem_delete (m);
1280 /* fprintf (stderr, "%p -> realloc\n", ptr); */
1282 /* Prevent malloc from registering blocks. */
1283 dont_register_blocks = 1;
1284 #endif /* GC_MALLOC_CHECK */
1286 value = (void *) realloc (ptr, size);
1288 #ifdef GC_MALLOC_CHECK
1289 dont_register_blocks = 0;
1292 struct mem_node *m = mem_find (value);
1293 if (m != MEM_NIL)
1295 fprintf (stderr, "Realloc returns memory that is already in use\n");
1296 abort ();
1299 /* Can't handle zero size regions in the red-black tree. */
1300 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
1303 /* fprintf (stderr, "%p <- realloc\n", value); */
1304 #endif /* GC_MALLOC_CHECK */
1306 __realloc_hook = emacs_blocked_realloc;
1307 UNBLOCK_INPUT_ALLOC;
1309 return value;
1313 #ifdef HAVE_GTK_AND_PTHREAD
1314 /* Called from Fdump_emacs so that when the dumped Emacs starts, it has a
1315 normal malloc. Some thread implementations need this as they call
1316 malloc before main. The pthread_self call in BLOCK_INPUT_ALLOC then
1317 calls malloc because it is the first call, and we have an endless loop. */
1319 void
1320 reset_malloc_hooks ()
1322 __free_hook = old_free_hook;
1323 __malloc_hook = old_malloc_hook;
1324 __realloc_hook = old_realloc_hook;
1326 #endif /* HAVE_GTK_AND_PTHREAD */
1329 /* Called from main to set up malloc to use our hooks. */
1331 void
1332 uninterrupt_malloc (void)
1334 #ifdef HAVE_GTK_AND_PTHREAD
1335 #ifdef DOUG_LEA_MALLOC
1336 pthread_mutexattr_t attr;
1338 /* GLIBC has a faster way to do this, but lets keep it portable.
1339 This is according to the Single UNIX Specification. */
1340 pthread_mutexattr_init (&attr);
1341 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1342 pthread_mutex_init (&alloc_mutex, &attr);
1343 #else /* !DOUG_LEA_MALLOC */
1344 /* Some systems such as Solaris 2.6 don't have a recursive mutex,
1345 and the bundled gmalloc.c doesn't require it. */
1346 pthread_mutex_init (&alloc_mutex, NULL);
1347 #endif /* !DOUG_LEA_MALLOC */
1348 #endif /* HAVE_GTK_AND_PTHREAD */
1350 if (__free_hook != emacs_blocked_free)
1351 old_free_hook = __free_hook;
1352 __free_hook = emacs_blocked_free;
1354 if (__malloc_hook != emacs_blocked_malloc)
1355 old_malloc_hook = __malloc_hook;
1356 __malloc_hook = emacs_blocked_malloc;
1358 if (__realloc_hook != emacs_blocked_realloc)
1359 old_realloc_hook = __realloc_hook;
1360 __realloc_hook = emacs_blocked_realloc;
1363 #endif /* not SYNC_INPUT */
1364 #endif /* not SYSTEM_MALLOC */
1368 /***********************************************************************
1369 Interval Allocation
1370 ***********************************************************************/
1372 /* Number of intervals allocated in an interval_block structure.
1373 The 1020 is 1024 minus malloc overhead. */
1375 #define INTERVAL_BLOCK_SIZE \
1376 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1378 /* Intervals are allocated in chunks in form of an interval_block
1379 structure. */
1381 struct interval_block
1383 /* Place `intervals' first, to preserve alignment. */
1384 struct interval intervals[INTERVAL_BLOCK_SIZE];
1385 struct interval_block *next;
1388 /* Current interval block. Its `next' pointer points to older
1389 blocks. */
1391 static struct interval_block *interval_block;
1393 /* Index in interval_block above of the next unused interval
1394 structure. */
1396 static int interval_block_index;
1398 /* Number of free and live intervals. */
1400 static int total_free_intervals, total_intervals;
1402 /* List of free intervals. */
1404 INTERVAL interval_free_list;
1406 /* Total number of interval blocks now in use. */
1408 static int n_interval_blocks;
1411 /* Initialize interval allocation. */
1413 static void
1414 init_intervals (void)
1416 interval_block = NULL;
1417 interval_block_index = INTERVAL_BLOCK_SIZE;
1418 interval_free_list = 0;
1419 n_interval_blocks = 0;
1423 /* Return a new interval. */
1425 INTERVAL
1426 make_interval (void)
1428 INTERVAL val;
1430 /* eassert (!handling_signal); */
1432 MALLOC_BLOCK_INPUT;
1434 if (interval_free_list)
1436 val = interval_free_list;
1437 interval_free_list = INTERVAL_PARENT (interval_free_list);
1439 else
1441 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1443 register struct interval_block *newi;
1445 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
1446 MEM_TYPE_NON_LISP);
1448 newi->next = interval_block;
1449 interval_block = newi;
1450 interval_block_index = 0;
1451 n_interval_blocks++;
1453 val = &interval_block->intervals[interval_block_index++];
1456 MALLOC_UNBLOCK_INPUT;
1458 consing_since_gc += sizeof (struct interval);
1459 intervals_consed++;
1460 RESET_INTERVAL (val);
1461 val->gcmarkbit = 0;
1462 return val;
1466 /* Mark Lisp objects in interval I. */
1468 static void
1469 mark_interval (register INTERVAL i, Lisp_Object dummy)
1471 eassert (!i->gcmarkbit); /* Intervals are never shared. */
1472 i->gcmarkbit = 1;
1473 mark_object (i->plist);
1477 /* Mark the interval tree rooted in TREE. Don't call this directly;
1478 use the macro MARK_INTERVAL_TREE instead. */
1480 static void
1481 mark_interval_tree (register INTERVAL tree)
1483 /* No need to test if this tree has been marked already; this
1484 function is always called through the MARK_INTERVAL_TREE macro,
1485 which takes care of that. */
1487 traverse_intervals_noorder (tree, mark_interval, Qnil);
1491 /* Mark the interval tree rooted in I. */
1493 #define MARK_INTERVAL_TREE(i) \
1494 do { \
1495 if (!NULL_INTERVAL_P (i) && !i->gcmarkbit) \
1496 mark_interval_tree (i); \
1497 } while (0)
1500 #define UNMARK_BALANCE_INTERVALS(i) \
1501 do { \
1502 if (! NULL_INTERVAL_P (i)) \
1503 (i) = balance_intervals (i); \
1504 } while (0)
1507 /* Number support. If USE_LISP_UNION_TYPE is in effect, we
1508 can't create number objects in macros. */
1509 #ifndef make_number
1510 Lisp_Object
1511 make_number (EMACS_INT n)
1513 Lisp_Object obj;
1514 obj.s.val = n;
1515 obj.s.type = Lisp_Int;
1516 return obj;
1518 #endif
1520 /***********************************************************************
1521 String Allocation
1522 ***********************************************************************/
1524 /* Lisp_Strings are allocated in string_block structures. When a new
1525 string_block is allocated, all the Lisp_Strings it contains are
1526 added to a free-list string_free_list. When a new Lisp_String is
1527 needed, it is taken from that list. During the sweep phase of GC,
1528 string_blocks that are entirely free are freed, except two which
1529 we keep.
1531 String data is allocated from sblock structures. Strings larger
1532 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1533 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1535 Sblocks consist internally of sdata structures, one for each
1536 Lisp_String. The sdata structure points to the Lisp_String it
1537 belongs to. The Lisp_String points back to the `u.data' member of
1538 its sdata structure.
1540 When a Lisp_String is freed during GC, it is put back on
1541 string_free_list, and its `data' member and its sdata's `string'
1542 pointer is set to null. The size of the string is recorded in the
1543 `u.nbytes' member of the sdata. So, sdata structures that are no
1544 longer used, can be easily recognized, and it's easy to compact the
1545 sblocks of small strings which we do in compact_small_strings. */
1547 /* Size in bytes of an sblock structure used for small strings. This
1548 is 8192 minus malloc overhead. */
1550 #define SBLOCK_SIZE 8188
1552 /* Strings larger than this are considered large strings. String data
1553 for large strings is allocated from individual sblocks. */
1555 #define LARGE_STRING_BYTES 1024
1557 /* Structure describing string memory sub-allocated from an sblock.
1558 This is where the contents of Lisp strings are stored. */
1560 struct sdata
1562 /* Back-pointer to the string this sdata belongs to. If null, this
1563 structure is free, and the NBYTES member of the union below
1564 contains the string's byte size (the same value that STRING_BYTES
1565 would return if STRING were non-null). If non-null, STRING_BYTES
1566 (STRING) is the size of the data, and DATA contains the string's
1567 contents. */
1568 struct Lisp_String *string;
1570 #ifdef GC_CHECK_STRING_BYTES
1572 EMACS_INT nbytes;
1573 unsigned char data[1];
1575 #define SDATA_NBYTES(S) (S)->nbytes
1576 #define SDATA_DATA(S) (S)->data
1578 #else /* not GC_CHECK_STRING_BYTES */
1580 union
1582 /* When STRING in non-null. */
1583 unsigned char data[1];
1585 /* When STRING is null. */
1586 EMACS_INT nbytes;
1587 } u;
1590 #define SDATA_NBYTES(S) (S)->u.nbytes
1591 #define SDATA_DATA(S) (S)->u.data
1593 #endif /* not GC_CHECK_STRING_BYTES */
1597 /* Structure describing a block of memory which is sub-allocated to
1598 obtain string data memory for strings. Blocks for small strings
1599 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1600 as large as needed. */
1602 struct sblock
1604 /* Next in list. */
1605 struct sblock *next;
1607 /* Pointer to the next free sdata block. This points past the end
1608 of the sblock if there isn't any space left in this block. */
1609 struct sdata *next_free;
1611 /* Start of data. */
1612 struct sdata first_data;
1615 /* Number of Lisp strings in a string_block structure. The 1020 is
1616 1024 minus malloc overhead. */
1618 #define STRING_BLOCK_SIZE \
1619 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1621 /* Structure describing a block from which Lisp_String structures
1622 are allocated. */
1624 struct string_block
1626 /* Place `strings' first, to preserve alignment. */
1627 struct Lisp_String strings[STRING_BLOCK_SIZE];
1628 struct string_block *next;
1631 /* Head and tail of the list of sblock structures holding Lisp string
1632 data. We always allocate from current_sblock. The NEXT pointers
1633 in the sblock structures go from oldest_sblock to current_sblock. */
1635 static struct sblock *oldest_sblock, *current_sblock;
1637 /* List of sblocks for large strings. */
1639 static struct sblock *large_sblocks;
1641 /* List of string_block structures, and how many there are. */
1643 static struct string_block *string_blocks;
1644 static int n_string_blocks;
1646 /* Free-list of Lisp_Strings. */
1648 static struct Lisp_String *string_free_list;
1650 /* Number of live and free Lisp_Strings. */
1652 static int total_strings, total_free_strings;
1654 /* Number of bytes used by live strings. */
1656 static int total_string_size;
1658 /* Given a pointer to a Lisp_String S which is on the free-list
1659 string_free_list, return a pointer to its successor in the
1660 free-list. */
1662 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1664 /* Return a pointer to the sdata structure belonging to Lisp string S.
1665 S must be live, i.e. S->data must not be null. S->data is actually
1666 a pointer to the `u.data' member of its sdata structure; the
1667 structure starts at a constant offset in front of that. */
1669 #ifdef GC_CHECK_STRING_BYTES
1671 #define SDATA_OF_STRING(S) \
1672 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *) \
1673 - sizeof (EMACS_INT)))
1675 #else /* not GC_CHECK_STRING_BYTES */
1677 #define SDATA_OF_STRING(S) \
1678 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))
1680 #endif /* not GC_CHECK_STRING_BYTES */
1683 #ifdef GC_CHECK_STRING_OVERRUN
1685 /* We check for overrun in string data blocks by appending a small
1686 "cookie" after each allocated string data block, and check for the
1687 presence of this cookie during GC. */
1689 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1690 static char string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1691 { 0xde, 0xad, 0xbe, 0xef };
1693 #else
1694 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1695 #endif
1697 /* Value is the size of an sdata structure large enough to hold NBYTES
1698 bytes of string data. The value returned includes a terminating
1699 NUL byte, the size of the sdata structure, and padding. */
1701 #ifdef GC_CHECK_STRING_BYTES
1703 #define SDATA_SIZE(NBYTES) \
1704 ((sizeof (struct Lisp_String *) \
1705 + (NBYTES) + 1 \
1706 + sizeof (EMACS_INT) \
1707 + sizeof (EMACS_INT) - 1) \
1708 & ~(sizeof (EMACS_INT) - 1))
1710 #else /* not GC_CHECK_STRING_BYTES */
1712 #define SDATA_SIZE(NBYTES) \
1713 ((sizeof (struct Lisp_String *) \
1714 + (NBYTES) + 1 \
1715 + sizeof (EMACS_INT) - 1) \
1716 & ~(sizeof (EMACS_INT) - 1))
1718 #endif /* not GC_CHECK_STRING_BYTES */
1720 /* Extra bytes to allocate for each string. */
1722 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1724 /* Initialize string allocation. Called from init_alloc_once. */
1726 static void
1727 init_strings (void)
1729 total_strings = total_free_strings = total_string_size = 0;
1730 oldest_sblock = current_sblock = large_sblocks = NULL;
1731 string_blocks = NULL;
1732 n_string_blocks = 0;
1733 string_free_list = NULL;
1734 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1735 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1739 #ifdef GC_CHECK_STRING_BYTES
1741 static int check_string_bytes_count;
1743 static void check_string_bytes (int);
1744 static void check_sblock (struct sblock *);
1746 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1749 /* Like GC_STRING_BYTES, but with debugging check. */
1752 string_bytes (s)
1753 struct Lisp_String *s;
1755 int nbytes = (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1756 if (!PURE_POINTER_P (s)
1757 && s->data
1758 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1759 abort ();
1760 return nbytes;
1763 /* Check validity of Lisp strings' string_bytes member in B. */
1765 static void
1766 check_sblock (b)
1767 struct sblock *b;
1769 struct sdata *from, *end, *from_end;
1771 end = b->next_free;
1773 for (from = &b->first_data; from < end; from = from_end)
1775 /* Compute the next FROM here because copying below may
1776 overwrite data we need to compute it. */
1777 int nbytes;
1779 /* Check that the string size recorded in the string is the
1780 same as the one recorded in the sdata structure. */
1781 if (from->string)
1782 CHECK_STRING_BYTES (from->string);
1784 if (from->string)
1785 nbytes = GC_STRING_BYTES (from->string);
1786 else
1787 nbytes = SDATA_NBYTES (from);
1789 nbytes = SDATA_SIZE (nbytes);
1790 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1795 /* Check validity of Lisp strings' string_bytes member. ALL_P
1796 non-zero means check all strings, otherwise check only most
1797 recently allocated strings. Used for hunting a bug. */
1799 static void
1800 check_string_bytes (all_p)
1801 int all_p;
1803 if (all_p)
1805 struct sblock *b;
1807 for (b = large_sblocks; b; b = b->next)
1809 struct Lisp_String *s = b->first_data.string;
1810 if (s)
1811 CHECK_STRING_BYTES (s);
1814 for (b = oldest_sblock; b; b = b->next)
1815 check_sblock (b);
1817 else
1818 check_sblock (current_sblock);
1821 #endif /* GC_CHECK_STRING_BYTES */
1823 #ifdef GC_CHECK_STRING_FREE_LIST
1825 /* Walk through the string free list looking for bogus next pointers.
1826 This may catch buffer overrun from a previous string. */
1828 static void
1829 check_string_free_list ()
1831 struct Lisp_String *s;
1833 /* Pop a Lisp_String off the free-list. */
1834 s = string_free_list;
1835 while (s != NULL)
1837 if ((unsigned)s < 1024)
1838 abort();
1839 s = NEXT_FREE_LISP_STRING (s);
1842 #else
1843 #define check_string_free_list()
1844 #endif
1846 /* Return a new Lisp_String. */
1848 static struct Lisp_String *
1849 allocate_string (void)
1851 struct Lisp_String *s;
1853 /* eassert (!handling_signal); */
1855 MALLOC_BLOCK_INPUT;
1857 /* If the free-list is empty, allocate a new string_block, and
1858 add all the Lisp_Strings in it to the free-list. */
1859 if (string_free_list == NULL)
1861 struct string_block *b;
1862 int i;
1864 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1865 memset (b, 0, sizeof *b);
1866 b->next = string_blocks;
1867 string_blocks = b;
1868 ++n_string_blocks;
1870 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1872 s = b->strings + i;
1873 NEXT_FREE_LISP_STRING (s) = string_free_list;
1874 string_free_list = s;
1877 total_free_strings += STRING_BLOCK_SIZE;
1880 check_string_free_list ();
1882 /* Pop a Lisp_String off the free-list. */
1883 s = string_free_list;
1884 string_free_list = NEXT_FREE_LISP_STRING (s);
1886 MALLOC_UNBLOCK_INPUT;
1888 /* Probably not strictly necessary, but play it safe. */
1889 memset (s, 0, sizeof *s);
1891 --total_free_strings;
1892 ++total_strings;
1893 ++strings_consed;
1894 consing_since_gc += sizeof *s;
1896 #ifdef GC_CHECK_STRING_BYTES
1897 if (!noninteractive)
1899 if (++check_string_bytes_count == 200)
1901 check_string_bytes_count = 0;
1902 check_string_bytes (1);
1904 else
1905 check_string_bytes (0);
1907 #endif /* GC_CHECK_STRING_BYTES */
1909 return s;
1913 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1914 plus a NUL byte at the end. Allocate an sdata structure for S, and
1915 set S->data to its `u.data' member. Store a NUL byte at the end of
1916 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1917 S->data if it was initially non-null. */
1919 void
1920 allocate_string_data (struct Lisp_String *s, int nchars, int nbytes)
1922 struct sdata *data, *old_data;
1923 struct sblock *b;
1924 int needed, old_nbytes;
1926 /* Determine the number of bytes needed to store NBYTES bytes
1927 of string data. */
1928 needed = SDATA_SIZE (nbytes);
1929 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1930 old_nbytes = GC_STRING_BYTES (s);
1932 MALLOC_BLOCK_INPUT;
1934 if (nbytes > LARGE_STRING_BYTES)
1936 size_t size = sizeof *b - sizeof (struct sdata) + needed;
1938 #ifdef DOUG_LEA_MALLOC
1939 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1940 because mapped region contents are not preserved in
1941 a dumped Emacs.
1943 In case you think of allowing it in a dumped Emacs at the
1944 cost of not being able to re-dump, there's another reason:
1945 mmap'ed data typically have an address towards the top of the
1946 address space, which won't fit into an EMACS_INT (at least on
1947 32-bit systems with the current tagging scheme). --fx */
1948 mallopt (M_MMAP_MAX, 0);
1949 #endif
1951 b = (struct sblock *) lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
1953 #ifdef DOUG_LEA_MALLOC
1954 /* Back to a reasonable maximum of mmap'ed areas. */
1955 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1956 #endif
1958 b->next_free = &b->first_data;
1959 b->first_data.string = NULL;
1960 b->next = large_sblocks;
1961 large_sblocks = b;
1963 else if (current_sblock == NULL
1964 || (((char *) current_sblock + SBLOCK_SIZE
1965 - (char *) current_sblock->next_free)
1966 < (needed + GC_STRING_EXTRA)))
1968 /* Not enough room in the current sblock. */
1969 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1970 b->next_free = &b->first_data;
1971 b->first_data.string = NULL;
1972 b->next = NULL;
1974 if (current_sblock)
1975 current_sblock->next = b;
1976 else
1977 oldest_sblock = b;
1978 current_sblock = b;
1980 else
1981 b = current_sblock;
1983 data = b->next_free;
1984 b->next_free = (struct sdata *) ((char *) data + needed + GC_STRING_EXTRA);
1986 MALLOC_UNBLOCK_INPUT;
1988 data->string = s;
1989 s->data = SDATA_DATA (data);
1990 #ifdef GC_CHECK_STRING_BYTES
1991 SDATA_NBYTES (data) = nbytes;
1992 #endif
1993 s->size = nchars;
1994 s->size_byte = nbytes;
1995 s->data[nbytes] = '\0';
1996 #ifdef GC_CHECK_STRING_OVERRUN
1997 memcpy (data + needed, string_overrun_cookie, GC_STRING_OVERRUN_COOKIE_SIZE);
1998 #endif
2000 /* If S had already data assigned, mark that as free by setting its
2001 string back-pointer to null, and recording the size of the data
2002 in it. */
2003 if (old_data)
2005 SDATA_NBYTES (old_data) = old_nbytes;
2006 old_data->string = NULL;
2009 consing_since_gc += needed;
2013 /* Sweep and compact strings. */
2015 static void
2016 sweep_strings (void)
2018 struct string_block *b, *next;
2019 struct string_block *live_blocks = NULL;
2021 string_free_list = NULL;
2022 total_strings = total_free_strings = 0;
2023 total_string_size = 0;
2025 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
2026 for (b = string_blocks; b; b = next)
2028 int i, nfree = 0;
2029 struct Lisp_String *free_list_before = string_free_list;
2031 next = b->next;
2033 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
2035 struct Lisp_String *s = b->strings + i;
2037 if (s->data)
2039 /* String was not on free-list before. */
2040 if (STRING_MARKED_P (s))
2042 /* String is live; unmark it and its intervals. */
2043 UNMARK_STRING (s);
2045 if (!NULL_INTERVAL_P (s->intervals))
2046 UNMARK_BALANCE_INTERVALS (s->intervals);
2048 ++total_strings;
2049 total_string_size += STRING_BYTES (s);
2051 else
2053 /* String is dead. Put it on the free-list. */
2054 struct sdata *data = SDATA_OF_STRING (s);
2056 /* Save the size of S in its sdata so that we know
2057 how large that is. Reset the sdata's string
2058 back-pointer so that we know it's free. */
2059 #ifdef GC_CHECK_STRING_BYTES
2060 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
2061 abort ();
2062 #else
2063 data->u.nbytes = GC_STRING_BYTES (s);
2064 #endif
2065 data->string = NULL;
2067 /* Reset the strings's `data' member so that we
2068 know it's free. */
2069 s->data = NULL;
2071 /* Put the string on the free-list. */
2072 NEXT_FREE_LISP_STRING (s) = string_free_list;
2073 string_free_list = s;
2074 ++nfree;
2077 else
2079 /* S was on the free-list before. Put it there again. */
2080 NEXT_FREE_LISP_STRING (s) = string_free_list;
2081 string_free_list = s;
2082 ++nfree;
2086 /* Free blocks that contain free Lisp_Strings only, except
2087 the first two of them. */
2088 if (nfree == STRING_BLOCK_SIZE
2089 && total_free_strings > STRING_BLOCK_SIZE)
2091 lisp_free (b);
2092 --n_string_blocks;
2093 string_free_list = free_list_before;
2095 else
2097 total_free_strings += nfree;
2098 b->next = live_blocks;
2099 live_blocks = b;
2103 check_string_free_list ();
2105 string_blocks = live_blocks;
2106 free_large_strings ();
2107 compact_small_strings ();
2109 check_string_free_list ();
2113 /* Free dead large strings. */
2115 static void
2116 free_large_strings (void)
2118 struct sblock *b, *next;
2119 struct sblock *live_blocks = NULL;
2121 for (b = large_sblocks; b; b = next)
2123 next = b->next;
2125 if (b->first_data.string == NULL)
2126 lisp_free (b);
2127 else
2129 b->next = live_blocks;
2130 live_blocks = b;
2134 large_sblocks = live_blocks;
2138 /* Compact data of small strings. Free sblocks that don't contain
2139 data of live strings after compaction. */
2141 static void
2142 compact_small_strings (void)
2144 struct sblock *b, *tb, *next;
2145 struct sdata *from, *to, *end, *tb_end;
2146 struct sdata *to_end, *from_end;
2148 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2149 to, and TB_END is the end of TB. */
2150 tb = oldest_sblock;
2151 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2152 to = &tb->first_data;
2154 /* Step through the blocks from the oldest to the youngest. We
2155 expect that old blocks will stabilize over time, so that less
2156 copying will happen this way. */
2157 for (b = oldest_sblock; b; b = b->next)
2159 end = b->next_free;
2160 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2162 for (from = &b->first_data; from < end; from = from_end)
2164 /* Compute the next FROM here because copying below may
2165 overwrite data we need to compute it. */
2166 int nbytes;
2168 #ifdef GC_CHECK_STRING_BYTES
2169 /* Check that the string size recorded in the string is the
2170 same as the one recorded in the sdata structure. */
2171 if (from->string
2172 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
2173 abort ();
2174 #endif /* GC_CHECK_STRING_BYTES */
2176 if (from->string)
2177 nbytes = GC_STRING_BYTES (from->string);
2178 else
2179 nbytes = SDATA_NBYTES (from);
2181 if (nbytes > LARGE_STRING_BYTES)
2182 abort ();
2184 nbytes = SDATA_SIZE (nbytes);
2185 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
2187 #ifdef GC_CHECK_STRING_OVERRUN
2188 if (memcmp (string_overrun_cookie,
2189 (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
2190 GC_STRING_OVERRUN_COOKIE_SIZE))
2191 abort ();
2192 #endif
2194 /* FROM->string non-null means it's alive. Copy its data. */
2195 if (from->string)
2197 /* If TB is full, proceed with the next sblock. */
2198 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2199 if (to_end > tb_end)
2201 tb->next_free = to;
2202 tb = tb->next;
2203 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2204 to = &tb->first_data;
2205 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2208 /* Copy, and update the string's `data' pointer. */
2209 if (from != to)
2211 xassert (tb != b || to <= from);
2212 memmove (to, from, nbytes + GC_STRING_EXTRA);
2213 to->string->data = SDATA_DATA (to);
2216 /* Advance past the sdata we copied to. */
2217 to = to_end;
2222 /* The rest of the sblocks following TB don't contain live data, so
2223 we can free them. */
2224 for (b = tb->next; b; b = next)
2226 next = b->next;
2227 lisp_free (b);
2230 tb->next_free = to;
2231 tb->next = NULL;
2232 current_sblock = tb;
2236 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2237 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2238 LENGTH must be an integer.
2239 INIT must be an integer that represents a character. */)
2240 (Lisp_Object length, Lisp_Object init)
2242 register Lisp_Object val;
2243 register unsigned char *p, *end;
2244 int c, nbytes;
2246 CHECK_NATNUM (length);
2247 CHECK_NUMBER (init);
2249 c = XINT (init);
2250 if (ASCII_CHAR_P (c))
2252 nbytes = XINT (length);
2253 val = make_uninit_string (nbytes);
2254 p = SDATA (val);
2255 end = p + SCHARS (val);
2256 while (p != end)
2257 *p++ = c;
2259 else
2261 unsigned char str[MAX_MULTIBYTE_LENGTH];
2262 int len = CHAR_STRING (c, str);
2264 nbytes = len * XINT (length);
2265 val = make_uninit_multibyte_string (XINT (length), nbytes);
2266 p = SDATA (val);
2267 end = p + nbytes;
2268 while (p != end)
2270 memcpy (p, str, len);
2271 p += len;
2275 *p = 0;
2276 return val;
2280 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2281 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2282 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2283 (Lisp_Object length, Lisp_Object init)
2285 register Lisp_Object val;
2286 struct Lisp_Bool_Vector *p;
2287 int real_init, i;
2288 int length_in_chars, length_in_elts, bits_per_value;
2290 CHECK_NATNUM (length);
2292 bits_per_value = sizeof (EMACS_INT) * BOOL_VECTOR_BITS_PER_CHAR;
2294 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
2295 length_in_chars = ((XFASTINT (length) + BOOL_VECTOR_BITS_PER_CHAR - 1)
2296 / BOOL_VECTOR_BITS_PER_CHAR);
2298 /* We must allocate one more elements than LENGTH_IN_ELTS for the
2299 slot `size' of the struct Lisp_Bool_Vector. */
2300 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
2302 /* Get rid of any bits that would cause confusion. */
2303 XVECTOR (val)->size = 0; /* No Lisp_Object to trace in there. */
2304 /* Use XVECTOR (val) rather than `p' because p->size is not TRT. */
2305 XSETPVECTYPE (XVECTOR (val), PVEC_BOOL_VECTOR);
2307 p = XBOOL_VECTOR (val);
2308 p->size = XFASTINT (length);
2310 real_init = (NILP (init) ? 0 : -1);
2311 for (i = 0; i < length_in_chars ; i++)
2312 p->data[i] = real_init;
2314 /* Clear the extraneous bits in the last byte. */
2315 if (XINT (length) != length_in_chars * BOOL_VECTOR_BITS_PER_CHAR)
2316 p->data[length_in_chars - 1]
2317 &= (1 << (XINT (length) % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2319 return val;
2323 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2324 of characters from the contents. This string may be unibyte or
2325 multibyte, depending on the contents. */
2327 Lisp_Object
2328 make_string (const char *contents, int nbytes)
2330 register Lisp_Object val;
2331 int nchars, multibyte_nbytes;
2333 parse_str_as_multibyte (contents, nbytes, &nchars, &multibyte_nbytes);
2334 if (nbytes == nchars || nbytes != multibyte_nbytes)
2335 /* CONTENTS contains no multibyte sequences or contains an invalid
2336 multibyte sequence. We must make unibyte string. */
2337 val = make_unibyte_string (contents, nbytes);
2338 else
2339 val = make_multibyte_string (contents, nchars, nbytes);
2340 return val;
2344 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
2346 Lisp_Object
2347 make_unibyte_string (const char *contents, int length)
2349 register Lisp_Object val;
2350 val = make_uninit_string (length);
2351 memcpy (SDATA (val), contents, length);
2352 STRING_SET_UNIBYTE (val);
2353 return val;
2357 /* Make a multibyte string from NCHARS characters occupying NBYTES
2358 bytes at CONTENTS. */
2360 Lisp_Object
2361 make_multibyte_string (const char *contents, int nchars, int nbytes)
2363 register Lisp_Object val;
2364 val = make_uninit_multibyte_string (nchars, nbytes);
2365 memcpy (SDATA (val), contents, nbytes);
2366 return val;
2370 /* Make a string from NCHARS characters occupying NBYTES bytes at
2371 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2373 Lisp_Object
2374 make_string_from_bytes (const char *contents, int nchars, int nbytes)
2376 register Lisp_Object val;
2377 val = make_uninit_multibyte_string (nchars, nbytes);
2378 memcpy (SDATA (val), contents, nbytes);
2379 if (SBYTES (val) == SCHARS (val))
2380 STRING_SET_UNIBYTE (val);
2381 return val;
2385 /* Make a string from NCHARS characters occupying NBYTES bytes at
2386 CONTENTS. The argument MULTIBYTE controls whether to label the
2387 string as multibyte. If NCHARS is negative, it counts the number of
2388 characters by itself. */
2390 Lisp_Object
2391 make_specified_string (const char *contents, int nchars, int nbytes, int multibyte)
2393 register Lisp_Object val;
2395 if (nchars < 0)
2397 if (multibyte)
2398 nchars = multibyte_chars_in_text (contents, nbytes);
2399 else
2400 nchars = nbytes;
2402 val = make_uninit_multibyte_string (nchars, nbytes);
2403 memcpy (SDATA (val), contents, nbytes);
2404 if (!multibyte)
2405 STRING_SET_UNIBYTE (val);
2406 return val;
2410 /* Make a string from the data at STR, treating it as multibyte if the
2411 data warrants. */
2413 Lisp_Object
2414 build_string (const char *str)
2416 return make_string (str, strlen (str));
2420 /* Return an unibyte Lisp_String set up to hold LENGTH characters
2421 occupying LENGTH bytes. */
2423 Lisp_Object
2424 make_uninit_string (int length)
2426 Lisp_Object val;
2428 if (!length)
2429 return empty_unibyte_string;
2430 val = make_uninit_multibyte_string (length, length);
2431 STRING_SET_UNIBYTE (val);
2432 return val;
2436 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2437 which occupy NBYTES bytes. */
2439 Lisp_Object
2440 make_uninit_multibyte_string (int nchars, int nbytes)
2442 Lisp_Object string;
2443 struct Lisp_String *s;
2445 if (nchars < 0)
2446 abort ();
2447 if (!nbytes)
2448 return empty_multibyte_string;
2450 s = allocate_string ();
2451 allocate_string_data (s, nchars, nbytes);
2452 XSETSTRING (string, s);
2453 string_chars_consed += nbytes;
2454 return string;
2459 /***********************************************************************
2460 Float Allocation
2461 ***********************************************************************/
2463 /* We store float cells inside of float_blocks, allocating a new
2464 float_block with malloc whenever necessary. Float cells reclaimed
2465 by GC are put on a free list to be reallocated before allocating
2466 any new float cells from the latest float_block. */
2468 #define FLOAT_BLOCK_SIZE \
2469 (((BLOCK_BYTES - sizeof (struct float_block *) \
2470 /* The compiler might add padding at the end. */ \
2471 - (sizeof (struct Lisp_Float) - sizeof (int))) * CHAR_BIT) \
2472 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2474 #define GETMARKBIT(block,n) \
2475 (((block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2476 >> ((n) % (sizeof(int) * CHAR_BIT))) \
2477 & 1)
2479 #define SETMARKBIT(block,n) \
2480 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2481 |= 1 << ((n) % (sizeof(int) * CHAR_BIT))
2483 #define UNSETMARKBIT(block,n) \
2484 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2485 &= ~(1 << ((n) % (sizeof(int) * CHAR_BIT)))
2487 #define FLOAT_BLOCK(fptr) \
2488 ((struct float_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
2490 #define FLOAT_INDEX(fptr) \
2491 ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2493 struct float_block
2495 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2496 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2497 int gcmarkbits[1 + FLOAT_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
2498 struct float_block *next;
2501 #define FLOAT_MARKED_P(fptr) \
2502 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2504 #define FLOAT_MARK(fptr) \
2505 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2507 #define FLOAT_UNMARK(fptr) \
2508 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2510 /* Current float_block. */
2512 struct float_block *float_block;
2514 /* Index of first unused Lisp_Float in the current float_block. */
2516 int float_block_index;
2518 /* Total number of float blocks now in use. */
2520 int n_float_blocks;
2522 /* Free-list of Lisp_Floats. */
2524 struct Lisp_Float *float_free_list;
2527 /* Initialize float allocation. */
2529 static void
2530 init_float (void)
2532 float_block = NULL;
2533 float_block_index = FLOAT_BLOCK_SIZE; /* Force alloc of new float_block. */
2534 float_free_list = 0;
2535 n_float_blocks = 0;
2539 /* Return a new float object with value FLOAT_VALUE. */
2541 Lisp_Object
2542 make_float (double float_value)
2544 register Lisp_Object val;
2546 /* eassert (!handling_signal); */
2548 MALLOC_BLOCK_INPUT;
2550 if (float_free_list)
2552 /* We use the data field for chaining the free list
2553 so that we won't use the same field that has the mark bit. */
2554 XSETFLOAT (val, float_free_list);
2555 float_free_list = float_free_list->u.chain;
2557 else
2559 if (float_block_index == FLOAT_BLOCK_SIZE)
2561 register struct float_block *new;
2563 new = (struct float_block *) lisp_align_malloc (sizeof *new,
2564 MEM_TYPE_FLOAT);
2565 new->next = float_block;
2566 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2567 float_block = new;
2568 float_block_index = 0;
2569 n_float_blocks++;
2571 XSETFLOAT (val, &float_block->floats[float_block_index]);
2572 float_block_index++;
2575 MALLOC_UNBLOCK_INPUT;
2577 XFLOAT_INIT (val, float_value);
2578 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2579 consing_since_gc += sizeof (struct Lisp_Float);
2580 floats_consed++;
2581 return val;
2586 /***********************************************************************
2587 Cons Allocation
2588 ***********************************************************************/
2590 /* We store cons cells inside of cons_blocks, allocating a new
2591 cons_block with malloc whenever necessary. Cons cells reclaimed by
2592 GC are put on a free list to be reallocated before allocating
2593 any new cons cells from the latest cons_block. */
2595 #define CONS_BLOCK_SIZE \
2596 (((BLOCK_BYTES - sizeof (struct cons_block *)) * CHAR_BIT) \
2597 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2599 #define CONS_BLOCK(fptr) \
2600 ((struct cons_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
2602 #define CONS_INDEX(fptr) \
2603 ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2605 struct cons_block
2607 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2608 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2609 int gcmarkbits[1 + CONS_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
2610 struct cons_block *next;
2613 #define CONS_MARKED_P(fptr) \
2614 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2616 #define CONS_MARK(fptr) \
2617 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2619 #define CONS_UNMARK(fptr) \
2620 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2622 /* Current cons_block. */
2624 struct cons_block *cons_block;
2626 /* Index of first unused Lisp_Cons in the current block. */
2628 int cons_block_index;
2630 /* Free-list of Lisp_Cons structures. */
2632 struct Lisp_Cons *cons_free_list;
2634 /* Total number of cons blocks now in use. */
2636 static int n_cons_blocks;
2639 /* Initialize cons allocation. */
2641 static void
2642 init_cons (void)
2644 cons_block = NULL;
2645 cons_block_index = CONS_BLOCK_SIZE; /* Force alloc of new cons_block. */
2646 cons_free_list = 0;
2647 n_cons_blocks = 0;
2651 /* Explicitly free a cons cell by putting it on the free-list. */
2653 void
2654 free_cons (struct Lisp_Cons *ptr)
2656 ptr->u.chain = cons_free_list;
2657 #if GC_MARK_STACK
2658 ptr->car = Vdead;
2659 #endif
2660 cons_free_list = ptr;
2663 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2664 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2665 (Lisp_Object car, Lisp_Object cdr)
2667 register Lisp_Object val;
2669 /* eassert (!handling_signal); */
2671 MALLOC_BLOCK_INPUT;
2673 if (cons_free_list)
2675 /* We use the cdr for chaining the free list
2676 so that we won't use the same field that has the mark bit. */
2677 XSETCONS (val, cons_free_list);
2678 cons_free_list = cons_free_list->u.chain;
2680 else
2682 if (cons_block_index == CONS_BLOCK_SIZE)
2684 register struct cons_block *new;
2685 new = (struct cons_block *) lisp_align_malloc (sizeof *new,
2686 MEM_TYPE_CONS);
2687 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2688 new->next = cons_block;
2689 cons_block = new;
2690 cons_block_index = 0;
2691 n_cons_blocks++;
2693 XSETCONS (val, &cons_block->conses[cons_block_index]);
2694 cons_block_index++;
2697 MALLOC_UNBLOCK_INPUT;
2699 XSETCAR (val, car);
2700 XSETCDR (val, cdr);
2701 eassert (!CONS_MARKED_P (XCONS (val)));
2702 consing_since_gc += sizeof (struct Lisp_Cons);
2703 cons_cells_consed++;
2704 return val;
2707 /* Get an error now if there's any junk in the cons free list. */
2708 void
2709 check_cons_list (void)
2711 #ifdef GC_CHECK_CONS_LIST
2712 struct Lisp_Cons *tail = cons_free_list;
2714 while (tail)
2715 tail = tail->u.chain;
2716 #endif
2719 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2721 Lisp_Object
2722 list1 (Lisp_Object arg1)
2724 return Fcons (arg1, Qnil);
2727 Lisp_Object
2728 list2 (Lisp_Object arg1, Lisp_Object arg2)
2730 return Fcons (arg1, Fcons (arg2, Qnil));
2734 Lisp_Object
2735 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2737 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2741 Lisp_Object
2742 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2744 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2748 Lisp_Object
2749 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2751 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2752 Fcons (arg5, Qnil)))));
2756 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2757 doc: /* Return a newly created list with specified arguments as elements.
2758 Any number of arguments, even zero arguments, are allowed.
2759 usage: (list &rest OBJECTS) */)
2760 (int nargs, register Lisp_Object *args)
2762 register Lisp_Object val;
2763 val = Qnil;
2765 while (nargs > 0)
2767 nargs--;
2768 val = Fcons (args[nargs], val);
2770 return val;
2774 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2775 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2776 (register Lisp_Object length, Lisp_Object init)
2778 register Lisp_Object val;
2779 register int size;
2781 CHECK_NATNUM (length);
2782 size = XFASTINT (length);
2784 val = Qnil;
2785 while (size > 0)
2787 val = Fcons (init, val);
2788 --size;
2790 if (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;
2814 QUIT;
2817 return val;
2822 /***********************************************************************
2823 Vector Allocation
2824 ***********************************************************************/
2826 /* Singly-linked list of all vectors. */
2828 static struct Lisp_Vector *all_vectors;
2830 /* Total number of vector-like objects now in use. */
2832 static int n_vectors;
2835 /* Value is a pointer to a newly allocated Lisp_Vector structure
2836 with room for LEN Lisp_Objects. */
2838 static struct Lisp_Vector *
2839 allocate_vectorlike (EMACS_INT len)
2841 struct Lisp_Vector *p;
2842 size_t nbytes;
2844 MALLOC_BLOCK_INPUT;
2846 #ifdef DOUG_LEA_MALLOC
2847 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2848 because mapped region contents are not preserved in
2849 a dumped Emacs. */
2850 mallopt (M_MMAP_MAX, 0);
2851 #endif
2853 /* This gets triggered by code which I haven't bothered to fix. --Stef */
2854 /* eassert (!handling_signal); */
2856 nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
2857 p = (struct Lisp_Vector *) lisp_malloc (nbytes, MEM_TYPE_VECTORLIKE);
2859 #ifdef DOUG_LEA_MALLOC
2860 /* Back to a reasonable maximum of mmap'ed areas. */
2861 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2862 #endif
2864 consing_since_gc += nbytes;
2865 vector_cells_consed += len;
2867 p->next = all_vectors;
2868 all_vectors = p;
2870 MALLOC_UNBLOCK_INPUT;
2872 ++n_vectors;
2873 return p;
2877 /* Allocate a vector with NSLOTS slots. */
2879 struct Lisp_Vector *
2880 allocate_vector (EMACS_INT nslots)
2882 struct Lisp_Vector *v = allocate_vectorlike (nslots);
2883 v->size = nslots;
2884 return v;
2888 /* Allocate other vector-like structures. */
2890 struct Lisp_Vector *
2891 allocate_pseudovector (int memlen, int lisplen, EMACS_INT tag)
2893 struct Lisp_Vector *v = allocate_vectorlike (memlen);
2894 EMACS_INT i;
2896 /* Only the first lisplen slots will be traced normally by the GC. */
2897 v->size = lisplen;
2898 for (i = 0; i < lisplen; ++i)
2899 v->contents[i] = Qnil;
2901 XSETPVECTYPE (v, tag); /* Add the appropriate tag. */
2902 return v;
2905 struct Lisp_Hash_Table *
2906 allocate_hash_table (void)
2908 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table, count, PVEC_HASH_TABLE);
2912 struct window *
2913 allocate_window (void)
2915 return ALLOCATE_PSEUDOVECTOR(struct window, current_matrix, PVEC_WINDOW);
2919 struct terminal *
2920 allocate_terminal (void)
2922 struct terminal *t = ALLOCATE_PSEUDOVECTOR (struct terminal,
2923 next_terminal, PVEC_TERMINAL);
2924 /* Zero out the non-GC'd fields. FIXME: This should be made unnecessary. */
2925 memset (&t->next_terminal, 0,
2926 (char*) (t + 1) - (char*) &t->next_terminal);
2928 return t;
2931 struct frame *
2932 allocate_frame (void)
2934 struct frame *f = ALLOCATE_PSEUDOVECTOR (struct frame,
2935 face_cache, PVEC_FRAME);
2936 /* Zero out the non-GC'd fields. FIXME: This should be made unnecessary. */
2937 memset (&f->face_cache, 0,
2938 (char *) (f + 1) - (char *) &f->face_cache);
2939 return f;
2943 struct Lisp_Process *
2944 allocate_process (void)
2946 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
2950 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
2951 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
2952 See also the function `vector'. */)
2953 (register Lisp_Object length, Lisp_Object init)
2955 Lisp_Object vector;
2956 register EMACS_INT sizei;
2957 register int index;
2958 register struct Lisp_Vector *p;
2960 CHECK_NATNUM (length);
2961 sizei = XFASTINT (length);
2963 p = allocate_vector (sizei);
2964 for (index = 0; index < sizei; index++)
2965 p->contents[index] = init;
2967 XSETVECTOR (vector, p);
2968 return vector;
2972 /* Return a new `function vector' containing KIND as the first element,
2973 followed by NUM_NIL_SLOTS nil elements, and further elements copied from
2974 the vector PARAMS of length NUM_PARAMS (so the total length of the
2975 resulting vector is 1 + NUM_NIL_SLOTS + NUM_PARAMS).
2977 If NUM_PARAMS is zero, then PARAMS may be NULL.
2979 A `function vector', a.k.a. `funvec', is a funcallable vector in Emacs Lisp.
2980 See the function `funvec' for more detail. */
2982 Lisp_Object
2983 make_funvec (Lisp_Object kind, int num_nil_slots, int num_params,
2984 Lisp_Object *params)
2986 int param_index;
2987 Lisp_Object funvec;
2989 funvec = Fmake_vector (make_number (1 + num_nil_slots + num_params), Qnil);
2991 ASET (funvec, 0, kind);
2993 for (param_index = 0; param_index < num_params; param_index++)
2994 ASET (funvec, 1 + num_nil_slots + param_index, params[param_index]);
2996 XSETPVECTYPE (XVECTOR (funvec), PVEC_FUNVEC);
2997 XSETFUNVEC (funvec, XVECTOR (funvec));
2999 return funvec;
3003 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3004 doc: /* Return a newly created vector with specified arguments as elements.
3005 Any number of arguments, even zero arguments, are allowed.
3006 usage: (vector &rest OBJECTS) */)
3007 (register int nargs, Lisp_Object *args)
3009 register Lisp_Object len, val;
3010 register int index;
3011 register struct Lisp_Vector *p;
3013 XSETFASTINT (len, nargs);
3014 val = Fmake_vector (len, Qnil);
3015 p = XVECTOR (val);
3016 for (index = 0; index < nargs; index++)
3017 p->contents[index] = args[index];
3018 return val;
3022 DEFUN ("funvec", Ffunvec, Sfunvec, 1, MANY, 0,
3023 doc: /* Return a newly created `function vector' of type KIND.
3024 A `function vector', a.k.a. `funvec', is a funcallable vector in Emacs Lisp.
3025 KIND indicates the kind of funvec, and determines its behavior when called.
3026 The meaning of the remaining arguments depends on KIND. Currently
3027 implemented values of KIND, and their meaning, are:
3029 A list -- A byte-compiled function. See `make-byte-code' for the usual
3030 way to create byte-compiled functions.
3032 `curry' -- A curried function. Remaining arguments are a function to
3033 call, and arguments to prepend to user arguments at the
3034 time of the call; see the `curry' function.
3036 usage: (funvec KIND &rest PARAMS) */)
3037 (int nargs, Lisp_Object *args)
3039 return make_funvec (args[0], 0, nargs - 1, args + 1);
3043 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3044 doc: /* Create a byte-code object with specified arguments as elements.
3045 The arguments should be the arglist, bytecode-string, constant vector,
3046 stack size, (optional) doc string, and (optional) interactive spec.
3047 The first four arguments are required; at most six have any
3048 significance.
3049 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3050 (register int nargs, Lisp_Object *args)
3052 register Lisp_Object len, val;
3053 register int index;
3054 register struct Lisp_Vector *p;
3056 /* Make sure the arg-list is really a list, as that's what's used to
3057 distinguish a byte-compiled object from other funvecs. */
3058 CHECK_LIST (args[0]);
3060 XSETFASTINT (len, nargs);
3061 if (!NILP (Vpurify_flag))
3062 val = make_pure_vector ((EMACS_INT) nargs);
3063 else
3064 val = Fmake_vector (len, Qnil);
3066 if (nargs > 1 && STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
3067 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3068 earlier because they produced a raw 8-bit string for byte-code
3069 and now such a byte-code string is loaded as multibyte while
3070 raw 8-bit characters converted to multibyte form. Thus, now we
3071 must convert them back to the original unibyte form. */
3072 args[1] = Fstring_as_unibyte (args[1]);
3074 p = XVECTOR (val);
3075 for (index = 0; index < nargs; index++)
3077 if (!NILP (Vpurify_flag))
3078 args[index] = Fpurecopy (args[index]);
3079 p->contents[index] = args[index];
3081 XSETPVECTYPE (p, PVEC_FUNVEC);
3082 XSETFUNVEC (val, p);
3083 return val;
3088 /***********************************************************************
3089 Symbol Allocation
3090 ***********************************************************************/
3092 /* Each symbol_block is just under 1020 bytes long, since malloc
3093 really allocates in units of powers of two and uses 4 bytes for its
3094 own overhead. */
3096 #define SYMBOL_BLOCK_SIZE \
3097 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
3099 struct symbol_block
3101 /* Place `symbols' first, to preserve alignment. */
3102 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3103 struct symbol_block *next;
3106 /* Current symbol block and index of first unused Lisp_Symbol
3107 structure in it. */
3109 static struct symbol_block *symbol_block;
3110 static int symbol_block_index;
3112 /* List of free symbols. */
3114 static struct Lisp_Symbol *symbol_free_list;
3116 /* Total number of symbol blocks now in use. */
3118 static int n_symbol_blocks;
3121 /* Initialize symbol allocation. */
3123 static void
3124 init_symbol (void)
3126 symbol_block = NULL;
3127 symbol_block_index = SYMBOL_BLOCK_SIZE;
3128 symbol_free_list = 0;
3129 n_symbol_blocks = 0;
3133 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3134 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3135 Its value and function definition are void, and its property list is nil. */)
3136 (Lisp_Object name)
3138 register Lisp_Object val;
3139 register struct Lisp_Symbol *p;
3141 CHECK_STRING (name);
3143 /* eassert (!handling_signal); */
3145 MALLOC_BLOCK_INPUT;
3147 if (symbol_free_list)
3149 XSETSYMBOL (val, symbol_free_list);
3150 symbol_free_list = symbol_free_list->next;
3152 else
3154 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3156 struct symbol_block *new;
3157 new = (struct symbol_block *) lisp_malloc (sizeof *new,
3158 MEM_TYPE_SYMBOL);
3159 new->next = symbol_block;
3160 symbol_block = new;
3161 symbol_block_index = 0;
3162 n_symbol_blocks++;
3164 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index]);
3165 symbol_block_index++;
3168 MALLOC_UNBLOCK_INPUT;
3170 p = XSYMBOL (val);
3171 p->xname = name;
3172 p->plist = Qnil;
3173 p->redirect = SYMBOL_PLAINVAL;
3174 SET_SYMBOL_VAL (p, Qunbound);
3175 p->function = Qunbound;
3176 p->next = NULL;
3177 p->gcmarkbit = 0;
3178 p->interned = SYMBOL_UNINTERNED;
3179 p->constant = 0;
3180 p->declared_special = 0;
3181 consing_since_gc += sizeof (struct Lisp_Symbol);
3182 symbols_consed++;
3183 return val;
3188 /***********************************************************************
3189 Marker (Misc) Allocation
3190 ***********************************************************************/
3192 /* Allocation of markers and other objects that share that structure.
3193 Works like allocation of conses. */
3195 #define MARKER_BLOCK_SIZE \
3196 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
3198 struct marker_block
3200 /* Place `markers' first, to preserve alignment. */
3201 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
3202 struct marker_block *next;
3205 static struct marker_block *marker_block;
3206 static int marker_block_index;
3208 static union Lisp_Misc *marker_free_list;
3210 /* Total number of marker blocks now in use. */
3212 static int n_marker_blocks;
3214 static void
3215 init_marker (void)
3217 marker_block = NULL;
3218 marker_block_index = MARKER_BLOCK_SIZE;
3219 marker_free_list = 0;
3220 n_marker_blocks = 0;
3223 /* Return a newly allocated Lisp_Misc object, with no substructure. */
3225 Lisp_Object
3226 allocate_misc (void)
3228 Lisp_Object val;
3230 /* eassert (!handling_signal); */
3232 MALLOC_BLOCK_INPUT;
3234 if (marker_free_list)
3236 XSETMISC (val, marker_free_list);
3237 marker_free_list = marker_free_list->u_free.chain;
3239 else
3241 if (marker_block_index == MARKER_BLOCK_SIZE)
3243 struct marker_block *new;
3244 new = (struct marker_block *) lisp_malloc (sizeof *new,
3245 MEM_TYPE_MISC);
3246 new->next = marker_block;
3247 marker_block = new;
3248 marker_block_index = 0;
3249 n_marker_blocks++;
3250 total_free_markers += MARKER_BLOCK_SIZE;
3252 XSETMISC (val, &marker_block->markers[marker_block_index]);
3253 marker_block_index++;
3256 MALLOC_UNBLOCK_INPUT;
3258 --total_free_markers;
3259 consing_since_gc += sizeof (union Lisp_Misc);
3260 misc_objects_consed++;
3261 XMISCANY (val)->gcmarkbit = 0;
3262 return val;
3265 /* Free a Lisp_Misc object */
3267 void
3268 free_misc (Lisp_Object misc)
3270 XMISCTYPE (misc) = Lisp_Misc_Free;
3271 XMISC (misc)->u_free.chain = marker_free_list;
3272 marker_free_list = XMISC (misc);
3274 total_free_markers++;
3277 /* Return a Lisp_Misc_Save_Value object containing POINTER and
3278 INTEGER. This is used to package C values to call record_unwind_protect.
3279 The unwind function can get the C values back using XSAVE_VALUE. */
3281 Lisp_Object
3282 make_save_value (void *pointer, 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. */)
3298 (void)
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 (Lisp_Object marker)
3319 unchain_marker (XMARKER (marker));
3320 free_misc (marker);
3324 /* Return a newly created vector or string with specified arguments as
3325 elements. If all the arguments are characters that can fit
3326 in a string of events, make a string; otherwise, make a vector.
3328 Any number of arguments, even zero arguments, are allowed. */
3330 Lisp_Object
3331 make_event_array (register int nargs, Lisp_Object *args)
3333 int i;
3335 for (i = 0; i < nargs; i++)
3336 /* The things that fit in a string
3337 are characters that are in 0...127,
3338 after discarding the meta bit and all the bits above it. */
3339 if (!INTEGERP (args[i])
3340 || (XUINT (args[i]) & ~(-CHAR_META)) >= 0200)
3341 return Fvector (nargs, args);
3343 /* Since the loop exited, we know that all the things in it are
3344 characters, so we can make a string. */
3346 Lisp_Object result;
3348 result = Fmake_string (make_number (nargs), make_number (0));
3349 for (i = 0; i < nargs; i++)
3351 SSET (result, i, XINT (args[i]));
3352 /* Move the meta bit to the right place for a string char. */
3353 if (XINT (args[i]) & CHAR_META)
3354 SSET (result, i, SREF (result, i) | 0x80);
3357 return result;
3363 /************************************************************************
3364 Memory Full Handling
3365 ************************************************************************/
3368 /* Called if malloc returns zero. */
3370 void
3371 memory_full (void)
3373 int i;
3375 Vmemory_full = Qt;
3377 memory_full_cons_threshold = sizeof (struct cons_block);
3379 /* The first time we get here, free the spare memory. */
3380 for (i = 0; i < sizeof (spare_memory) / sizeof (char *); i++)
3381 if (spare_memory[i])
3383 if (i == 0)
3384 free (spare_memory[i]);
3385 else if (i >= 1 && i <= 4)
3386 lisp_align_free (spare_memory[i]);
3387 else
3388 lisp_free (spare_memory[i]);
3389 spare_memory[i] = 0;
3392 /* Record the space now used. When it decreases substantially,
3393 we can refill the memory reserve. */
3394 #ifndef SYSTEM_MALLOC
3395 bytes_used_when_full = BYTES_USED;
3396 #endif
3398 /* This used to call error, but if we've run out of memory, we could
3399 get infinite recursion trying to build the string. */
3400 xsignal (Qnil, Vmemory_signal_data);
3403 /* If we released our reserve (due to running out of memory),
3404 and we have a fair amount free once again,
3405 try to set aside another reserve in case we run out once more.
3407 This is called when a relocatable block is freed in ralloc.c,
3408 and also directly from this file, in case we're not using ralloc.c. */
3410 void
3411 refill_memory_reserve (void)
3413 #ifndef SYSTEM_MALLOC
3414 if (spare_memory[0] == 0)
3415 spare_memory[0] = (char *) malloc ((size_t) SPARE_MEMORY);
3416 if (spare_memory[1] == 0)
3417 spare_memory[1] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3418 MEM_TYPE_CONS);
3419 if (spare_memory[2] == 0)
3420 spare_memory[2] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3421 MEM_TYPE_CONS);
3422 if (spare_memory[3] == 0)
3423 spare_memory[3] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3424 MEM_TYPE_CONS);
3425 if (spare_memory[4] == 0)
3426 spare_memory[4] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3427 MEM_TYPE_CONS);
3428 if (spare_memory[5] == 0)
3429 spare_memory[5] = (char *) lisp_malloc (sizeof (struct string_block),
3430 MEM_TYPE_STRING);
3431 if (spare_memory[6] == 0)
3432 spare_memory[6] = (char *) lisp_malloc (sizeof (struct string_block),
3433 MEM_TYPE_STRING);
3434 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
3435 Vmemory_full = Qnil;
3436 #endif
3439 /************************************************************************
3440 C Stack Marking
3441 ************************************************************************/
3443 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
3445 /* Conservative C stack marking requires a method to identify possibly
3446 live Lisp objects given a pointer value. We do this by keeping
3447 track of blocks of Lisp data that are allocated in a red-black tree
3448 (see also the comment of mem_node which is the type of nodes in
3449 that tree). Function lisp_malloc adds information for an allocated
3450 block to the red-black tree with calls to mem_insert, and function
3451 lisp_free removes it with mem_delete. Functions live_string_p etc
3452 call mem_find to lookup information about a given pointer in the
3453 tree, and use that to determine if the pointer points to a Lisp
3454 object or not. */
3456 /* Initialize this part of alloc.c. */
3458 static void
3459 mem_init (void)
3461 mem_z.left = mem_z.right = MEM_NIL;
3462 mem_z.parent = NULL;
3463 mem_z.color = MEM_BLACK;
3464 mem_z.start = mem_z.end = NULL;
3465 mem_root = MEM_NIL;
3469 /* Value is a pointer to the mem_node containing START. Value is
3470 MEM_NIL if there is no node in the tree containing START. */
3472 static INLINE struct mem_node *
3473 mem_find (void *start)
3475 struct mem_node *p;
3477 if (start < min_heap_address || start > max_heap_address)
3478 return MEM_NIL;
3480 /* Make the search always successful to speed up the loop below. */
3481 mem_z.start = start;
3482 mem_z.end = (char *) start + 1;
3484 p = mem_root;
3485 while (start < p->start || start >= p->end)
3486 p = start < p->start ? p->left : p->right;
3487 return p;
3491 /* Insert a new node into the tree for a block of memory with start
3492 address START, end address END, and type TYPE. Value is a
3493 pointer to the node that was inserted. */
3495 static struct mem_node *
3496 mem_insert (void *start, void *end, enum mem_type type)
3498 struct mem_node *c, *parent, *x;
3500 if (min_heap_address == NULL || start < min_heap_address)
3501 min_heap_address = start;
3502 if (max_heap_address == NULL || end > max_heap_address)
3503 max_heap_address = end;
3505 /* See where in the tree a node for START belongs. In this
3506 particular application, it shouldn't happen that a node is already
3507 present. For debugging purposes, let's check that. */
3508 c = mem_root;
3509 parent = NULL;
3511 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
3513 while (c != MEM_NIL)
3515 if (start >= c->start && start < c->end)
3516 abort ();
3517 parent = c;
3518 c = start < c->start ? c->left : c->right;
3521 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3523 while (c != MEM_NIL)
3525 parent = c;
3526 c = start < c->start ? c->left : c->right;
3529 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3531 /* Create a new node. */
3532 #ifdef GC_MALLOC_CHECK
3533 x = (struct mem_node *) _malloc_internal (sizeof *x);
3534 if (x == NULL)
3535 abort ();
3536 #else
3537 x = (struct mem_node *) xmalloc (sizeof *x);
3538 #endif
3539 x->start = start;
3540 x->end = end;
3541 x->type = type;
3542 x->parent = parent;
3543 x->left = x->right = MEM_NIL;
3544 x->color = MEM_RED;
3546 /* Insert it as child of PARENT or install it as root. */
3547 if (parent)
3549 if (start < parent->start)
3550 parent->left = x;
3551 else
3552 parent->right = x;
3554 else
3555 mem_root = x;
3557 /* Re-establish red-black tree properties. */
3558 mem_insert_fixup (x);
3560 return x;
3564 /* Re-establish the red-black properties of the tree, and thereby
3565 balance the tree, after node X has been inserted; X is always red. */
3567 static void
3568 mem_insert_fixup (struct mem_node *x)
3570 while (x != mem_root && x->parent->color == MEM_RED)
3572 /* X is red and its parent is red. This is a violation of
3573 red-black tree property #3. */
3575 if (x->parent == x->parent->parent->left)
3577 /* We're on the left side of our grandparent, and Y is our
3578 "uncle". */
3579 struct mem_node *y = x->parent->parent->right;
3581 if (y->color == MEM_RED)
3583 /* Uncle and parent are red but should be black because
3584 X is red. Change the colors accordingly and proceed
3585 with the grandparent. */
3586 x->parent->color = MEM_BLACK;
3587 y->color = MEM_BLACK;
3588 x->parent->parent->color = MEM_RED;
3589 x = x->parent->parent;
3591 else
3593 /* Parent and uncle have different colors; parent is
3594 red, uncle is black. */
3595 if (x == x->parent->right)
3597 x = x->parent;
3598 mem_rotate_left (x);
3601 x->parent->color = MEM_BLACK;
3602 x->parent->parent->color = MEM_RED;
3603 mem_rotate_right (x->parent->parent);
3606 else
3608 /* This is the symmetrical case of above. */
3609 struct mem_node *y = x->parent->parent->left;
3611 if (y->color == MEM_RED)
3613 x->parent->color = MEM_BLACK;
3614 y->color = MEM_BLACK;
3615 x->parent->parent->color = MEM_RED;
3616 x = x->parent->parent;
3618 else
3620 if (x == x->parent->left)
3622 x = x->parent;
3623 mem_rotate_right (x);
3626 x->parent->color = MEM_BLACK;
3627 x->parent->parent->color = MEM_RED;
3628 mem_rotate_left (x->parent->parent);
3633 /* The root may have been changed to red due to the algorithm. Set
3634 it to black so that property #5 is satisfied. */
3635 mem_root->color = MEM_BLACK;
3639 /* (x) (y)
3640 / \ / \
3641 a (y) ===> (x) c
3642 / \ / \
3643 b c a b */
3645 static void
3646 mem_rotate_left (struct mem_node *x)
3648 struct mem_node *y;
3650 /* Turn y's left sub-tree into x's right sub-tree. */
3651 y = x->right;
3652 x->right = y->left;
3653 if (y->left != MEM_NIL)
3654 y->left->parent = x;
3656 /* Y's parent was x's parent. */
3657 if (y != MEM_NIL)
3658 y->parent = x->parent;
3660 /* Get the parent to point to y instead of x. */
3661 if (x->parent)
3663 if (x == x->parent->left)
3664 x->parent->left = y;
3665 else
3666 x->parent->right = y;
3668 else
3669 mem_root = y;
3671 /* Put x on y's left. */
3672 y->left = x;
3673 if (x != MEM_NIL)
3674 x->parent = y;
3678 /* (x) (Y)
3679 / \ / \
3680 (y) c ===> a (x)
3681 / \ / \
3682 a b b c */
3684 static void
3685 mem_rotate_right (struct mem_node *x)
3687 struct mem_node *y = x->left;
3689 x->left = y->right;
3690 if (y->right != MEM_NIL)
3691 y->right->parent = x;
3693 if (y != MEM_NIL)
3694 y->parent = x->parent;
3695 if (x->parent)
3697 if (x == x->parent->right)
3698 x->parent->right = y;
3699 else
3700 x->parent->left = y;
3702 else
3703 mem_root = y;
3705 y->right = x;
3706 if (x != MEM_NIL)
3707 x->parent = y;
3711 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
3713 static void
3714 mem_delete (struct mem_node *z)
3716 struct mem_node *x, *y;
3718 if (!z || z == MEM_NIL)
3719 return;
3721 if (z->left == MEM_NIL || z->right == MEM_NIL)
3722 y = z;
3723 else
3725 y = z->right;
3726 while (y->left != MEM_NIL)
3727 y = y->left;
3730 if (y->left != MEM_NIL)
3731 x = y->left;
3732 else
3733 x = y->right;
3735 x->parent = y->parent;
3736 if (y->parent)
3738 if (y == y->parent->left)
3739 y->parent->left = x;
3740 else
3741 y->parent->right = x;
3743 else
3744 mem_root = x;
3746 if (y != z)
3748 z->start = y->start;
3749 z->end = y->end;
3750 z->type = y->type;
3753 if (y->color == MEM_BLACK)
3754 mem_delete_fixup (x);
3756 #ifdef GC_MALLOC_CHECK
3757 _free_internal (y);
3758 #else
3759 xfree (y);
3760 #endif
3764 /* Re-establish the red-black properties of the tree, after a
3765 deletion. */
3767 static void
3768 mem_delete_fixup (struct mem_node *x)
3770 while (x != mem_root && x->color == MEM_BLACK)
3772 if (x == x->parent->left)
3774 struct mem_node *w = x->parent->right;
3776 if (w->color == MEM_RED)
3778 w->color = MEM_BLACK;
3779 x->parent->color = MEM_RED;
3780 mem_rotate_left (x->parent);
3781 w = x->parent->right;
3784 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
3786 w->color = MEM_RED;
3787 x = x->parent;
3789 else
3791 if (w->right->color == MEM_BLACK)
3793 w->left->color = MEM_BLACK;
3794 w->color = MEM_RED;
3795 mem_rotate_right (w);
3796 w = x->parent->right;
3798 w->color = x->parent->color;
3799 x->parent->color = MEM_BLACK;
3800 w->right->color = MEM_BLACK;
3801 mem_rotate_left (x->parent);
3802 x = mem_root;
3805 else
3807 struct mem_node *w = x->parent->left;
3809 if (w->color == MEM_RED)
3811 w->color = MEM_BLACK;
3812 x->parent->color = MEM_RED;
3813 mem_rotate_right (x->parent);
3814 w = x->parent->left;
3817 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
3819 w->color = MEM_RED;
3820 x = x->parent;
3822 else
3824 if (w->left->color == MEM_BLACK)
3826 w->right->color = MEM_BLACK;
3827 w->color = MEM_RED;
3828 mem_rotate_left (w);
3829 w = x->parent->left;
3832 w->color = x->parent->color;
3833 x->parent->color = MEM_BLACK;
3834 w->left->color = MEM_BLACK;
3835 mem_rotate_right (x->parent);
3836 x = mem_root;
3841 x->color = MEM_BLACK;
3845 /* Value is non-zero if P is a pointer to a live Lisp string on
3846 the heap. M is a pointer to the mem_block for P. */
3848 static INLINE int
3849 live_string_p (struct mem_node *m, void *p)
3851 if (m->type == MEM_TYPE_STRING)
3853 struct string_block *b = (struct string_block *) m->start;
3854 int offset = (char *) p - (char *) &b->strings[0];
3856 /* P must point to the start of a Lisp_String structure, and it
3857 must not be on the free-list. */
3858 return (offset >= 0
3859 && offset % sizeof b->strings[0] == 0
3860 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
3861 && ((struct Lisp_String *) p)->data != NULL);
3863 else
3864 return 0;
3868 /* Value is non-zero if P is a pointer to a live Lisp cons on
3869 the heap. M is a pointer to the mem_block for P. */
3871 static INLINE int
3872 live_cons_p (struct mem_node *m, void *p)
3874 if (m->type == MEM_TYPE_CONS)
3876 struct cons_block *b = (struct cons_block *) m->start;
3877 int offset = (char *) p - (char *) &b->conses[0];
3879 /* P must point to the start of a Lisp_Cons, not be
3880 one of the unused cells in the current cons block,
3881 and not be on the free-list. */
3882 return (offset >= 0
3883 && offset % sizeof b->conses[0] == 0
3884 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
3885 && (b != cons_block
3886 || offset / sizeof b->conses[0] < cons_block_index)
3887 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
3889 else
3890 return 0;
3894 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3895 the heap. M is a pointer to the mem_block for P. */
3897 static INLINE int
3898 live_symbol_p (struct mem_node *m, void *p)
3900 if (m->type == MEM_TYPE_SYMBOL)
3902 struct symbol_block *b = (struct symbol_block *) m->start;
3903 int offset = (char *) p - (char *) &b->symbols[0];
3905 /* P must point to the start of a Lisp_Symbol, not be
3906 one of the unused cells in the current symbol block,
3907 and not be on the free-list. */
3908 return (offset >= 0
3909 && offset % sizeof b->symbols[0] == 0
3910 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
3911 && (b != symbol_block
3912 || offset / sizeof b->symbols[0] < symbol_block_index)
3913 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
3915 else
3916 return 0;
3920 /* Value is non-zero if P is a pointer to a live Lisp float on
3921 the heap. M is a pointer to the mem_block for P. */
3923 static INLINE int
3924 live_float_p (struct mem_node *m, void *p)
3926 if (m->type == MEM_TYPE_FLOAT)
3928 struct float_block *b = (struct float_block *) m->start;
3929 int offset = (char *) p - (char *) &b->floats[0];
3931 /* P must point to the start of a Lisp_Float and not be
3932 one of the unused cells in the current float block. */
3933 return (offset >= 0
3934 && offset % sizeof b->floats[0] == 0
3935 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
3936 && (b != float_block
3937 || offset / sizeof b->floats[0] < float_block_index));
3939 else
3940 return 0;
3944 /* Value is non-zero if P is a pointer to a live Lisp Misc on
3945 the heap. M is a pointer to the mem_block for P. */
3947 static INLINE int
3948 live_misc_p (struct mem_node *m, void *p)
3950 if (m->type == MEM_TYPE_MISC)
3952 struct marker_block *b = (struct marker_block *) m->start;
3953 int offset = (char *) p - (char *) &b->markers[0];
3955 /* P must point to the start of a Lisp_Misc, not be
3956 one of the unused cells in the current misc block,
3957 and not be on the free-list. */
3958 return (offset >= 0
3959 && offset % sizeof b->markers[0] == 0
3960 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
3961 && (b != marker_block
3962 || offset / sizeof b->markers[0] < marker_block_index)
3963 && ((union Lisp_Misc *) p)->u_any.type != Lisp_Misc_Free);
3965 else
3966 return 0;
3970 /* Value is non-zero if P is a pointer to a live vector-like object.
3971 M is a pointer to the mem_block for P. */
3973 static INLINE int
3974 live_vector_p (struct mem_node *m, void *p)
3976 return (p == m->start && m->type == MEM_TYPE_VECTORLIKE);
3980 /* Value is non-zero if P is a pointer to a live buffer. M is a
3981 pointer to the mem_block for P. */
3983 static INLINE int
3984 live_buffer_p (struct mem_node *m, void *p)
3986 /* P must point to the start of the block, and the buffer
3987 must not have been killed. */
3988 return (m->type == MEM_TYPE_BUFFER
3989 && p == m->start
3990 && !NILP (((struct buffer *) p)->name));
3993 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
3995 #if GC_MARK_STACK
3997 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3999 /* Array of objects that are kept alive because the C stack contains
4000 a pattern that looks like a reference to them . */
4002 #define MAX_ZOMBIES 10
4003 static Lisp_Object zombies[MAX_ZOMBIES];
4005 /* Number of zombie objects. */
4007 static int nzombies;
4009 /* Number of garbage collections. */
4011 static int ngcs;
4013 /* Average percentage of zombies per collection. */
4015 static double avg_zombies;
4017 /* Max. number of live and zombie objects. */
4019 static int max_live, max_zombies;
4021 /* Average number of live objects per GC. */
4023 static double avg_live;
4025 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
4026 doc: /* Show information about live and zombie objects. */)
4027 (void)
4029 Lisp_Object args[8], zombie_list = Qnil;
4030 int i;
4031 for (i = 0; i < nzombies; i++)
4032 zombie_list = Fcons (zombies[i], zombie_list);
4033 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
4034 args[1] = make_number (ngcs);
4035 args[2] = make_float (avg_live);
4036 args[3] = make_float (avg_zombies);
4037 args[4] = make_float (avg_zombies / avg_live / 100);
4038 args[5] = make_number (max_live);
4039 args[6] = make_number (max_zombies);
4040 args[7] = zombie_list;
4041 return Fmessage (8, args);
4044 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4047 /* Mark OBJ if we can prove it's a Lisp_Object. */
4049 static INLINE void
4050 mark_maybe_object (Lisp_Object obj)
4052 void *po = (void *) XPNTR (obj);
4053 struct mem_node *m = mem_find (po);
4055 if (m != MEM_NIL)
4057 int mark_p = 0;
4059 switch (XTYPE (obj))
4061 case Lisp_String:
4062 mark_p = (live_string_p (m, po)
4063 && !STRING_MARKED_P ((struct Lisp_String *) po));
4064 break;
4066 case Lisp_Cons:
4067 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4068 break;
4070 case Lisp_Symbol:
4071 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4072 break;
4074 case Lisp_Float:
4075 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4076 break;
4078 case Lisp_Vectorlike:
4079 /* Note: can't check BUFFERP before we know it's a
4080 buffer because checking that dereferences the pointer
4081 PO which might point anywhere. */
4082 if (live_vector_p (m, po))
4083 mark_p = !SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4084 else if (live_buffer_p (m, po))
4085 mark_p = BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4086 break;
4088 case Lisp_Misc:
4089 mark_p = (live_misc_p (m, po) && !XMISCANY (obj)->gcmarkbit);
4090 break;
4092 default:
4093 break;
4096 if (mark_p)
4098 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4099 if (nzombies < MAX_ZOMBIES)
4100 zombies[nzombies] = obj;
4101 ++nzombies;
4102 #endif
4103 mark_object (obj);
4109 /* If P points to Lisp data, mark that as live if it isn't already
4110 marked. */
4112 static INLINE void
4113 mark_maybe_pointer (void *p)
4115 struct mem_node *m;
4117 /* Quickly rule out some values which can't point to Lisp data. */
4118 if ((EMACS_INT) p %
4119 #ifdef USE_LSB_TAG
4120 8 /* USE_LSB_TAG needs Lisp data to be aligned on multiples of 8. */
4121 #else
4122 2 /* We assume that Lisp data is aligned on even addresses. */
4123 #endif
4125 return;
4127 m = mem_find (p);
4128 if (m != MEM_NIL)
4130 Lisp_Object obj = Qnil;
4132 switch (m->type)
4134 case MEM_TYPE_NON_LISP:
4135 /* Nothing to do; not a pointer to Lisp memory. */
4136 break;
4138 case MEM_TYPE_BUFFER:
4139 if (live_buffer_p (m, p) && !VECTOR_MARKED_P((struct buffer *)p))
4140 XSETVECTOR (obj, p);
4141 break;
4143 case MEM_TYPE_CONS:
4144 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4145 XSETCONS (obj, p);
4146 break;
4148 case MEM_TYPE_STRING:
4149 if (live_string_p (m, p)
4150 && !STRING_MARKED_P ((struct Lisp_String *) p))
4151 XSETSTRING (obj, p);
4152 break;
4154 case MEM_TYPE_MISC:
4155 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4156 XSETMISC (obj, p);
4157 break;
4159 case MEM_TYPE_SYMBOL:
4160 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4161 XSETSYMBOL (obj, p);
4162 break;
4164 case MEM_TYPE_FLOAT:
4165 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4166 XSETFLOAT (obj, p);
4167 break;
4169 case MEM_TYPE_VECTORLIKE:
4170 if (live_vector_p (m, p))
4172 Lisp_Object tem;
4173 XSETVECTOR (tem, p);
4174 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4175 obj = tem;
4177 break;
4179 default:
4180 abort ();
4183 if (!NILP (obj))
4184 mark_object (obj);
4189 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4190 or END+OFFSET..START. */
4192 static void
4193 mark_memory (void *start, void *end, int offset)
4195 Lisp_Object *p;
4196 void **pp;
4198 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4199 nzombies = 0;
4200 #endif
4202 /* Make START the pointer to the start of the memory region,
4203 if it isn't already. */
4204 if (end < start)
4206 void *tem = start;
4207 start = end;
4208 end = tem;
4211 /* Mark Lisp_Objects. */
4212 for (p = (Lisp_Object *) ((char *) start + offset); (void *) p < end; ++p)
4213 mark_maybe_object (*p);
4215 /* Mark Lisp data pointed to. This is necessary because, in some
4216 situations, the C compiler optimizes Lisp objects away, so that
4217 only a pointer to them remains. Example:
4219 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4222 Lisp_Object obj = build_string ("test");
4223 struct Lisp_String *s = XSTRING (obj);
4224 Fgarbage_collect ();
4225 fprintf (stderr, "test `%s'\n", s->data);
4226 return Qnil;
4229 Here, `obj' isn't really used, and the compiler optimizes it
4230 away. The only reference to the life string is through the
4231 pointer `s'. */
4233 for (pp = (void **) ((char *) start + offset); (void *) pp < end; ++pp)
4234 mark_maybe_pointer (*pp);
4237 /* setjmp will work with GCC unless NON_SAVING_SETJMP is defined in
4238 the GCC system configuration. In gcc 3.2, the only systems for
4239 which this is so are i386-sco5 non-ELF, i386-sysv3 (maybe included
4240 by others?) and ns32k-pc532-min. */
4242 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4244 static int setjmp_tested_p, longjmps_done;
4246 #define SETJMP_WILL_LIKELY_WORK "\
4248 Emacs garbage collector has been changed to use conservative stack\n\
4249 marking. Emacs has determined that the method it uses to do the\n\
4250 marking will likely work on your system, but this isn't sure.\n\
4252 If you are a system-programmer, or can get the help of a local wizard\n\
4253 who is, please take a look at the function mark_stack in alloc.c, and\n\
4254 verify that the methods used are appropriate for your system.\n\
4256 Please mail the result to <emacs-devel@gnu.org>.\n\
4259 #define SETJMP_WILL_NOT_WORK "\
4261 Emacs garbage collector has been changed to use conservative stack\n\
4262 marking. Emacs has determined that the default method it uses to do the\n\
4263 marking will not work on your system. We will need a system-dependent\n\
4264 solution for your system.\n\
4266 Please take a look at the function mark_stack in alloc.c, and\n\
4267 try to find a way to make it work on your system.\n\
4269 Note that you may get false negatives, depending on the compiler.\n\
4270 In particular, you need to use -O with GCC for this test.\n\
4272 Please mail the result to <emacs-devel@gnu.org>.\n\
4276 /* Perform a quick check if it looks like setjmp saves registers in a
4277 jmp_buf. Print a message to stderr saying so. When this test
4278 succeeds, this is _not_ a proof that setjmp is sufficient for
4279 conservative stack marking. Only the sources or a disassembly
4280 can prove that. */
4282 static void
4283 test_setjmp ()
4285 char buf[10];
4286 register int x;
4287 jmp_buf jbuf;
4288 int result = 0;
4290 /* Arrange for X to be put in a register. */
4291 sprintf (buf, "1");
4292 x = strlen (buf);
4293 x = 2 * x - 1;
4295 setjmp (jbuf);
4296 if (longjmps_done == 1)
4298 /* Came here after the longjmp at the end of the function.
4300 If x == 1, the longjmp has restored the register to its
4301 value before the setjmp, and we can hope that setjmp
4302 saves all such registers in the jmp_buf, although that
4303 isn't sure.
4305 For other values of X, either something really strange is
4306 taking place, or the setjmp just didn't save the register. */
4308 if (x == 1)
4309 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4310 else
4312 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4313 exit (1);
4317 ++longjmps_done;
4318 x = 2;
4319 if (longjmps_done == 1)
4320 longjmp (jbuf, 1);
4323 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4326 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4328 /* Abort if anything GCPRO'd doesn't survive the GC. */
4330 static void
4331 check_gcpros ()
4333 struct gcpro *p;
4334 int i;
4336 for (p = gcprolist; p; p = p->next)
4337 for (i = 0; i < p->nvars; ++i)
4338 if (!survives_gc_p (p->var[i]))
4339 /* FIXME: It's not necessarily a bug. It might just be that the
4340 GCPRO is unnecessary or should release the object sooner. */
4341 abort ();
4344 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4346 static void
4347 dump_zombies ()
4349 int i;
4351 fprintf (stderr, "\nZombies kept alive = %d:\n", nzombies);
4352 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
4354 fprintf (stderr, " %d = ", i);
4355 debug_print (zombies[i]);
4359 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4362 /* Mark live Lisp objects on the C stack.
4364 There are several system-dependent problems to consider when
4365 porting this to new architectures:
4367 Processor Registers
4369 We have to mark Lisp objects in CPU registers that can hold local
4370 variables or are used to pass parameters.
4372 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4373 something that either saves relevant registers on the stack, or
4374 calls mark_maybe_object passing it each register's contents.
4376 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4377 implementation assumes that calling setjmp saves registers we need
4378 to see in a jmp_buf which itself lies on the stack. This doesn't
4379 have to be true! It must be verified for each system, possibly
4380 by taking a look at the source code of setjmp.
4382 Stack Layout
4384 Architectures differ in the way their processor stack is organized.
4385 For example, the stack might look like this
4387 +----------------+
4388 | Lisp_Object | size = 4
4389 +----------------+
4390 | something else | size = 2
4391 +----------------+
4392 | Lisp_Object | size = 4
4393 +----------------+
4394 | ... |
4396 In such a case, not every Lisp_Object will be aligned equally. To
4397 find all Lisp_Object on the stack it won't be sufficient to walk
4398 the stack in steps of 4 bytes. Instead, two passes will be
4399 necessary, one starting at the start of the stack, and a second
4400 pass starting at the start of the stack + 2. Likewise, if the
4401 minimal alignment of Lisp_Objects on the stack is 1, four passes
4402 would be necessary, each one starting with one byte more offset
4403 from the stack start.
4405 The current code assumes by default that Lisp_Objects are aligned
4406 equally on the stack. */
4408 static void
4409 mark_stack (void)
4411 int i;
4412 /* jmp_buf may not be aligned enough on darwin-ppc64 */
4413 union aligned_jmpbuf {
4414 Lisp_Object o;
4415 jmp_buf j;
4416 } j;
4417 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
4418 void *end;
4420 /* This trick flushes the register windows so that all the state of
4421 the process is contained in the stack. */
4422 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
4423 needed on ia64 too. See mach_dep.c, where it also says inline
4424 assembler doesn't work with relevant proprietary compilers. */
4425 #ifdef __sparc__
4426 #if defined (__sparc64__) && defined (__FreeBSD__)
4427 /* FreeBSD does not have a ta 3 handler. */
4428 asm ("flushw");
4429 #else
4430 asm ("ta 3");
4431 #endif
4432 #endif
4434 /* Save registers that we need to see on the stack. We need to see
4435 registers used to hold register variables and registers used to
4436 pass parameters. */
4437 #ifdef GC_SAVE_REGISTERS_ON_STACK
4438 GC_SAVE_REGISTERS_ON_STACK (end);
4439 #else /* not GC_SAVE_REGISTERS_ON_STACK */
4441 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
4442 setjmp will definitely work, test it
4443 and print a message with the result
4444 of the test. */
4445 if (!setjmp_tested_p)
4447 setjmp_tested_p = 1;
4448 test_setjmp ();
4450 #endif /* GC_SETJMP_WORKS */
4452 setjmp (j.j);
4453 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
4454 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
4456 /* This assumes that the stack is a contiguous region in memory. If
4457 that's not the case, something has to be done here to iterate
4458 over the stack segments. */
4459 #ifndef GC_LISP_OBJECT_ALIGNMENT
4460 #ifdef __GNUC__
4461 #define GC_LISP_OBJECT_ALIGNMENT __alignof__ (Lisp_Object)
4462 #else
4463 #define GC_LISP_OBJECT_ALIGNMENT sizeof (Lisp_Object)
4464 #endif
4465 #endif
4466 for (i = 0; i < sizeof (Lisp_Object); i += GC_LISP_OBJECT_ALIGNMENT)
4467 mark_memory (stack_base, end, i);
4468 /* Allow for marking a secondary stack, like the register stack on the
4469 ia64. */
4470 #ifdef GC_MARK_SECONDARY_STACK
4471 GC_MARK_SECONDARY_STACK ();
4472 #endif
4474 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4475 check_gcpros ();
4476 #endif
4479 #endif /* GC_MARK_STACK != 0 */
4482 /* Determine whether it is safe to access memory at address P. */
4483 static int
4484 valid_pointer_p (void *p)
4486 #ifdef WINDOWSNT
4487 return w32_valid_pointer_p (p, 16);
4488 #else
4489 int fd;
4491 /* Obviously, we cannot just access it (we would SEGV trying), so we
4492 trick the o/s to tell us whether p is a valid pointer.
4493 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4494 not validate p in that case. */
4496 if ((fd = emacs_open ("__Valid__Lisp__Object__", O_CREAT | O_WRONLY | O_TRUNC, 0666)) >= 0)
4498 int valid = (emacs_write (fd, (char *)p, 16) == 16);
4499 emacs_close (fd);
4500 unlink ("__Valid__Lisp__Object__");
4501 return valid;
4504 return -1;
4505 #endif
4508 /* Return 1 if OBJ is a valid lisp object.
4509 Return 0 if OBJ is NOT a valid lisp object.
4510 Return -1 if we cannot validate OBJ.
4511 This function can be quite slow,
4512 so it should only be used in code for manual debugging. */
4515 valid_lisp_object_p (Lisp_Object obj)
4517 void *p;
4518 #if GC_MARK_STACK
4519 struct mem_node *m;
4520 #endif
4522 if (INTEGERP (obj))
4523 return 1;
4525 p = (void *) XPNTR (obj);
4526 if (PURE_POINTER_P (p))
4527 return 1;
4529 #if !GC_MARK_STACK
4530 return valid_pointer_p (p);
4531 #else
4533 m = mem_find (p);
4535 if (m == MEM_NIL)
4537 int valid = valid_pointer_p (p);
4538 if (valid <= 0)
4539 return valid;
4541 if (SUBRP (obj))
4542 return 1;
4544 return 0;
4547 switch (m->type)
4549 case MEM_TYPE_NON_LISP:
4550 return 0;
4552 case MEM_TYPE_BUFFER:
4553 return live_buffer_p (m, p);
4555 case MEM_TYPE_CONS:
4556 return live_cons_p (m, p);
4558 case MEM_TYPE_STRING:
4559 return live_string_p (m, p);
4561 case MEM_TYPE_MISC:
4562 return live_misc_p (m, p);
4564 case MEM_TYPE_SYMBOL:
4565 return live_symbol_p (m, p);
4567 case MEM_TYPE_FLOAT:
4568 return live_float_p (m, p);
4570 case MEM_TYPE_VECTORLIKE:
4571 return live_vector_p (m, p);
4573 default:
4574 break;
4577 return 0;
4578 #endif
4584 /***********************************************************************
4585 Pure Storage Management
4586 ***********************************************************************/
4588 /* Allocate room for SIZE bytes from pure Lisp storage and return a
4589 pointer to it. TYPE is the Lisp type for which the memory is
4590 allocated. TYPE < 0 means it's not used for a Lisp object. */
4592 static POINTER_TYPE *
4593 pure_alloc (size_t size, int type)
4595 POINTER_TYPE *result;
4596 #ifdef USE_LSB_TAG
4597 size_t alignment = (1 << GCTYPEBITS);
4598 #else
4599 size_t alignment = sizeof (EMACS_INT);
4601 /* Give Lisp_Floats an extra alignment. */
4602 if (type == Lisp_Float)
4604 #if defined __GNUC__ && __GNUC__ >= 2
4605 alignment = __alignof (struct Lisp_Float);
4606 #else
4607 alignment = sizeof (struct Lisp_Float);
4608 #endif
4610 #endif
4612 again:
4613 if (type >= 0)
4615 /* Allocate space for a Lisp object from the beginning of the free
4616 space with taking account of alignment. */
4617 result = ALIGN (purebeg + pure_bytes_used_lisp, alignment);
4618 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
4620 else
4622 /* Allocate space for a non-Lisp object from the end of the free
4623 space. */
4624 pure_bytes_used_non_lisp += size;
4625 result = purebeg + pure_size - pure_bytes_used_non_lisp;
4627 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
4629 if (pure_bytes_used <= pure_size)
4630 return result;
4632 /* Don't allocate a large amount here,
4633 because it might get mmap'd and then its address
4634 might not be usable. */
4635 purebeg = (char *) xmalloc (10000);
4636 pure_size = 10000;
4637 pure_bytes_used_before_overflow += pure_bytes_used - size;
4638 pure_bytes_used = 0;
4639 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
4640 goto again;
4644 /* Print a warning if PURESIZE is too small. */
4646 void
4647 check_pure_size (void)
4649 if (pure_bytes_used_before_overflow)
4650 message ("emacs:0:Pure Lisp storage overflow (approx. %d bytes needed)",
4651 (int) (pure_bytes_used + pure_bytes_used_before_overflow));
4655 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
4656 the non-Lisp data pool of the pure storage, and return its start
4657 address. Return NULL if not found. */
4659 static char *
4660 find_string_data_in_pure (const char *data, int nbytes)
4662 int i, skip, bm_skip[256], last_char_skip, infinity, start, start_max;
4663 const unsigned char *p;
4664 char *non_lisp_beg;
4666 if (pure_bytes_used_non_lisp < nbytes + 1)
4667 return NULL;
4669 /* Set up the Boyer-Moore table. */
4670 skip = nbytes + 1;
4671 for (i = 0; i < 256; i++)
4672 bm_skip[i] = skip;
4674 p = (const unsigned char *) data;
4675 while (--skip > 0)
4676 bm_skip[*p++] = skip;
4678 last_char_skip = bm_skip['\0'];
4680 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
4681 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
4683 /* See the comments in the function `boyer_moore' (search.c) for the
4684 use of `infinity'. */
4685 infinity = pure_bytes_used_non_lisp + 1;
4686 bm_skip['\0'] = infinity;
4688 p = (const unsigned char *) non_lisp_beg + nbytes;
4689 start = 0;
4692 /* Check the last character (== '\0'). */
4695 start += bm_skip[*(p + start)];
4697 while (start <= start_max);
4699 if (start < infinity)
4700 /* Couldn't find the last character. */
4701 return NULL;
4703 /* No less than `infinity' means we could find the last
4704 character at `p[start - infinity]'. */
4705 start -= infinity;
4707 /* Check the remaining characters. */
4708 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
4709 /* Found. */
4710 return non_lisp_beg + start;
4712 start += last_char_skip;
4714 while (start <= start_max);
4716 return NULL;
4720 /* Return a string allocated in pure space. DATA is a buffer holding
4721 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
4722 non-zero means make the result string multibyte.
4724 Must get an error if pure storage is full, since if it cannot hold
4725 a large string it may be able to hold conses that point to that
4726 string; then the string is not protected from gc. */
4728 Lisp_Object
4729 make_pure_string (const char *data, int nchars, int nbytes, int multibyte)
4731 Lisp_Object string;
4732 struct Lisp_String *s;
4734 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
4735 s->data = find_string_data_in_pure (data, nbytes);
4736 if (s->data == NULL)
4738 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
4739 memcpy (s->data, data, nbytes);
4740 s->data[nbytes] = '\0';
4742 s->size = nchars;
4743 s->size_byte = multibyte ? nbytes : -1;
4744 s->intervals = NULL_INTERVAL;
4745 XSETSTRING (string, s);
4746 return string;
4749 /* Return a string a string allocated in pure space. Do not allocate
4750 the string data, just point to DATA. */
4752 Lisp_Object
4753 make_pure_c_string (const char *data)
4755 Lisp_Object string;
4756 struct Lisp_String *s;
4757 int nchars = strlen (data);
4759 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
4760 s->size = nchars;
4761 s->size_byte = -1;
4762 s->data = (unsigned char *) data;
4763 s->intervals = NULL_INTERVAL;
4764 XSETSTRING (string, s);
4765 return string;
4768 /* Return a cons allocated from pure space. Give it pure copies
4769 of CAR as car and CDR as cdr. */
4771 Lisp_Object
4772 pure_cons (Lisp_Object car, Lisp_Object cdr)
4774 register Lisp_Object new;
4775 struct Lisp_Cons *p;
4777 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
4778 XSETCONS (new, p);
4779 XSETCAR (new, Fpurecopy (car));
4780 XSETCDR (new, Fpurecopy (cdr));
4781 return new;
4785 /* Value is a float object with value NUM allocated from pure space. */
4787 static Lisp_Object
4788 make_pure_float (double num)
4790 register Lisp_Object new;
4791 struct Lisp_Float *p;
4793 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
4794 XSETFLOAT (new, p);
4795 XFLOAT_INIT (new, num);
4796 return new;
4800 /* Return a vector with room for LEN Lisp_Objects allocated from
4801 pure space. */
4803 Lisp_Object
4804 make_pure_vector (EMACS_INT len)
4806 Lisp_Object new;
4807 struct Lisp_Vector *p;
4808 size_t size = sizeof *p + (len - 1) * sizeof (Lisp_Object);
4810 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
4811 XSETVECTOR (new, p);
4812 XVECTOR (new)->size = len;
4813 return new;
4817 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
4818 doc: /* Make a copy of object OBJ in pure storage.
4819 Recursively copies contents of vectors and cons cells.
4820 Does not copy symbols. Copies strings without text properties. */)
4821 (register Lisp_Object obj)
4823 if (NILP (Vpurify_flag))
4824 return obj;
4826 if (PURE_POINTER_P (XPNTR (obj)))
4827 return obj;
4829 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
4831 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
4832 if (!NILP (tmp))
4833 return tmp;
4836 if (CONSP (obj))
4837 obj = pure_cons (XCAR (obj), XCDR (obj));
4838 else if (FLOATP (obj))
4839 obj = make_pure_float (XFLOAT_DATA (obj));
4840 else if (STRINGP (obj))
4841 obj = make_pure_string (SDATA (obj), SCHARS (obj),
4842 SBYTES (obj),
4843 STRING_MULTIBYTE (obj));
4844 else if (FUNVECP (obj) || VECTORP (obj))
4846 register struct Lisp_Vector *vec;
4847 register int i;
4848 EMACS_INT size;
4850 size = XVECTOR (obj)->size;
4851 if (size & PSEUDOVECTOR_FLAG)
4852 size &= PSEUDOVECTOR_SIZE_MASK;
4853 vec = XVECTOR (make_pure_vector (size));
4854 for (i = 0; i < size; i++)
4855 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
4856 if (FUNVECP (obj))
4858 XSETPVECTYPE (vec, PVEC_FUNVEC);
4859 XSETFUNVEC (obj, vec);
4861 else
4862 XSETVECTOR (obj, vec);
4864 else if (MARKERP (obj))
4865 error ("Attempt to copy a marker to pure storage");
4866 else
4867 /* Not purified, don't hash-cons. */
4868 return obj;
4870 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
4871 Fputhash (obj, obj, Vpurify_flag);
4873 return obj;
4878 /***********************************************************************
4879 Protection from GC
4880 ***********************************************************************/
4882 /* Put an entry in staticvec, pointing at the variable with address
4883 VARADDRESS. */
4885 void
4886 staticpro (Lisp_Object *varaddress)
4888 staticvec[staticidx++] = varaddress;
4889 if (staticidx >= NSTATICS)
4890 abort ();
4894 /***********************************************************************
4895 Protection from GC
4896 ***********************************************************************/
4898 /* Temporarily prevent garbage collection. */
4901 inhibit_garbage_collection (void)
4903 int count = SPECPDL_INDEX ();
4904 int nbits = min (VALBITS, BITS_PER_INT);
4906 specbind (Qgc_cons_threshold, make_number (((EMACS_INT) 1 << (nbits - 1)) - 1));
4907 return count;
4911 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
4912 doc: /* Reclaim storage for Lisp objects no longer needed.
4913 Garbage collection happens automatically if you cons more than
4914 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
4915 `garbage-collect' normally returns a list with info on amount of space in use:
4916 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
4917 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
4918 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)
4919 (USED-STRINGS . FREE-STRINGS))
4920 However, if there was overflow in pure space, `garbage-collect'
4921 returns nil, because real GC can't be done. */)
4922 (void)
4924 register struct specbinding *bind;
4925 struct catchtag *catch;
4926 struct handler *handler;
4927 char stack_top_variable;
4928 register int i;
4929 int message_p;
4930 Lisp_Object total[8];
4931 int count = SPECPDL_INDEX ();
4932 EMACS_TIME t1, t2, t3;
4934 if (abort_on_gc)
4935 abort ();
4937 /* Can't GC if pure storage overflowed because we can't determine
4938 if something is a pure object or not. */
4939 if (pure_bytes_used_before_overflow)
4940 return Qnil;
4942 CHECK_CONS_LIST ();
4944 /* Don't keep undo information around forever.
4945 Do this early on, so it is no problem if the user quits. */
4947 register struct buffer *nextb = all_buffers;
4949 while (nextb)
4951 /* If a buffer's undo list is Qt, that means that undo is
4952 turned off in that buffer. Calling truncate_undo_list on
4953 Qt tends to return NULL, which effectively turns undo back on.
4954 So don't call truncate_undo_list if undo_list is Qt. */
4955 if (! NILP (nextb->name) && ! EQ (nextb->undo_list, Qt))
4956 truncate_undo_list (nextb);
4958 /* Shrink buffer gaps, but skip indirect and dead buffers. */
4959 if (nextb->base_buffer == 0 && !NILP (nextb->name)
4960 && ! nextb->text->inhibit_shrinking)
4962 /* If a buffer's gap size is more than 10% of the buffer
4963 size, or larger than 2000 bytes, then shrink it
4964 accordingly. Keep a minimum size of 20 bytes. */
4965 int size = min (2000, max (20, (nextb->text->z_byte / 10)));
4967 if (nextb->text->gap_size > size)
4969 struct buffer *save_current = current_buffer;
4970 current_buffer = nextb;
4971 make_gap (-(nextb->text->gap_size - size));
4972 current_buffer = save_current;
4976 nextb = nextb->next;
4980 EMACS_GET_TIME (t1);
4982 /* In case user calls debug_print during GC,
4983 don't let that cause a recursive GC. */
4984 consing_since_gc = 0;
4986 /* Save what's currently displayed in the echo area. */
4987 message_p = push_message ();
4988 record_unwind_protect (pop_message_unwind, Qnil);
4990 /* Save a copy of the contents of the stack, for debugging. */
4991 #if MAX_SAVE_STACK > 0
4992 if (NILP (Vpurify_flag))
4994 i = &stack_top_variable - stack_bottom;
4995 if (i < 0) i = -i;
4996 if (i < MAX_SAVE_STACK)
4998 if (stack_copy == 0)
4999 stack_copy = (char *) xmalloc (stack_copy_size = i);
5000 else if (stack_copy_size < i)
5001 stack_copy = (char *) xrealloc (stack_copy, (stack_copy_size = i));
5002 if (stack_copy)
5004 if ((EMACS_INT) (&stack_top_variable - stack_bottom) > 0)
5005 memcpy (stack_copy, stack_bottom, i);
5006 else
5007 memcpy (stack_copy, &stack_top_variable, i);
5011 #endif /* MAX_SAVE_STACK > 0 */
5013 if (garbage_collection_messages)
5014 message1_nolog ("Garbage collecting...");
5016 BLOCK_INPUT;
5018 shrink_regexp_cache ();
5020 gc_in_progress = 1;
5022 /* clear_marks (); */
5024 /* Mark all the special slots that serve as the roots of accessibility. */
5026 for (i = 0; i < staticidx; i++)
5027 mark_object (*staticvec[i]);
5029 for (bind = specpdl; bind != specpdl_ptr; bind++)
5031 mark_object (bind->symbol);
5032 mark_object (bind->old_value);
5034 mark_terminals ();
5035 mark_kboards ();
5036 mark_ttys ();
5038 #ifdef USE_GTK
5040 extern void xg_mark_data (void);
5041 xg_mark_data ();
5043 #endif
5045 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
5046 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
5047 mark_stack ();
5048 #else
5050 register struct gcpro *tail;
5051 for (tail = gcprolist; tail; tail = tail->next)
5052 for (i = 0; i < tail->nvars; i++)
5053 mark_object (tail->var[i]);
5055 #endif
5057 mark_byte_stack ();
5058 for (catch = catchlist; catch; catch = catch->next)
5060 mark_object (catch->tag);
5061 mark_object (catch->val);
5063 for (handler = handlerlist; handler; handler = handler->next)
5065 mark_object (handler->handler);
5066 mark_object (handler->var);
5068 mark_backtrace ();
5070 #ifdef HAVE_WINDOW_SYSTEM
5071 mark_fringe_data ();
5072 #endif
5074 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5075 mark_stack ();
5076 #endif
5078 /* Everything is now marked, except for the things that require special
5079 finalization, i.e. the undo_list.
5080 Look thru every buffer's undo list
5081 for elements that update markers that were not marked,
5082 and delete them. */
5084 register struct buffer *nextb = all_buffers;
5086 while (nextb)
5088 /* If a buffer's undo list is Qt, that means that undo is
5089 turned off in that buffer. Calling truncate_undo_list on
5090 Qt tends to return NULL, which effectively turns undo back on.
5091 So don't call truncate_undo_list if undo_list is Qt. */
5092 if (! EQ (nextb->undo_list, Qt))
5094 Lisp_Object tail, prev;
5095 tail = nextb->undo_list;
5096 prev = Qnil;
5097 while (CONSP (tail))
5099 if (CONSP (XCAR (tail))
5100 && MARKERP (XCAR (XCAR (tail)))
5101 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5103 if (NILP (prev))
5104 nextb->undo_list = tail = XCDR (tail);
5105 else
5107 tail = XCDR (tail);
5108 XSETCDR (prev, tail);
5111 else
5113 prev = tail;
5114 tail = XCDR (tail);
5118 /* Now that we have stripped the elements that need not be in the
5119 undo_list any more, we can finally mark the list. */
5120 mark_object (nextb->undo_list);
5122 nextb = nextb->next;
5126 gc_sweep ();
5128 /* Clear the mark bits that we set in certain root slots. */
5130 unmark_byte_stack ();
5131 VECTOR_UNMARK (&buffer_defaults);
5132 VECTOR_UNMARK (&buffer_local_symbols);
5134 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
5135 dump_zombies ();
5136 #endif
5138 UNBLOCK_INPUT;
5140 CHECK_CONS_LIST ();
5142 /* clear_marks (); */
5143 gc_in_progress = 0;
5145 consing_since_gc = 0;
5146 if (gc_cons_threshold < 10000)
5147 gc_cons_threshold = 10000;
5149 if (FLOATP (Vgc_cons_percentage))
5150 { /* Set gc_cons_combined_threshold. */
5151 EMACS_INT total = 0;
5153 total += total_conses * sizeof (struct Lisp_Cons);
5154 total += total_symbols * sizeof (struct Lisp_Symbol);
5155 total += total_markers * sizeof (union Lisp_Misc);
5156 total += total_string_size;
5157 total += total_vector_size * sizeof (Lisp_Object);
5158 total += total_floats * sizeof (struct Lisp_Float);
5159 total += total_intervals * sizeof (struct interval);
5160 total += total_strings * sizeof (struct Lisp_String);
5162 gc_relative_threshold = total * XFLOAT_DATA (Vgc_cons_percentage);
5164 else
5165 gc_relative_threshold = 0;
5167 if (garbage_collection_messages)
5169 if (message_p || minibuf_level > 0)
5170 restore_message ();
5171 else
5172 message1_nolog ("Garbage collecting...done");
5175 unbind_to (count, Qnil);
5177 total[0] = Fcons (make_number (total_conses),
5178 make_number (total_free_conses));
5179 total[1] = Fcons (make_number (total_symbols),
5180 make_number (total_free_symbols));
5181 total[2] = Fcons (make_number (total_markers),
5182 make_number (total_free_markers));
5183 total[3] = make_number (total_string_size);
5184 total[4] = make_number (total_vector_size);
5185 total[5] = Fcons (make_number (total_floats),
5186 make_number (total_free_floats));
5187 total[6] = Fcons (make_number (total_intervals),
5188 make_number (total_free_intervals));
5189 total[7] = Fcons (make_number (total_strings),
5190 make_number (total_free_strings));
5192 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5194 /* Compute average percentage of zombies. */
5195 double nlive = 0;
5197 for (i = 0; i < 7; ++i)
5198 if (CONSP (total[i]))
5199 nlive += XFASTINT (XCAR (total[i]));
5201 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
5202 max_live = max (nlive, max_live);
5203 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
5204 max_zombies = max (nzombies, max_zombies);
5205 ++ngcs;
5207 #endif
5209 if (!NILP (Vpost_gc_hook))
5211 int count = inhibit_garbage_collection ();
5212 safe_run_hooks (Qpost_gc_hook);
5213 unbind_to (count, Qnil);
5216 /* Accumulate statistics. */
5217 EMACS_GET_TIME (t2);
5218 EMACS_SUB_TIME (t3, t2, t1);
5219 if (FLOATP (Vgc_elapsed))
5220 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed) +
5221 EMACS_SECS (t3) +
5222 EMACS_USECS (t3) * 1.0e-6);
5223 gcs_done++;
5225 return Flist (sizeof total / sizeof *total, total);
5229 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5230 only interesting objects referenced from glyphs are strings. */
5232 static void
5233 mark_glyph_matrix (struct glyph_matrix *matrix)
5235 struct glyph_row *row = matrix->rows;
5236 struct glyph_row *end = row + matrix->nrows;
5238 for (; row < end; ++row)
5239 if (row->enabled_p)
5241 int area;
5242 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
5244 struct glyph *glyph = row->glyphs[area];
5245 struct glyph *end_glyph = glyph + row->used[area];
5247 for (; glyph < end_glyph; ++glyph)
5248 if (STRINGP (glyph->object)
5249 && !STRING_MARKED_P (XSTRING (glyph->object)))
5250 mark_object (glyph->object);
5256 /* Mark Lisp faces in the face cache C. */
5258 static void
5259 mark_face_cache (struct face_cache *c)
5261 if (c)
5263 int i, j;
5264 for (i = 0; i < c->used; ++i)
5266 struct face *face = FACE_FROM_ID (c->f, i);
5268 if (face)
5270 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
5271 mark_object (face->lface[j]);
5279 /* Mark reference to a Lisp_Object.
5280 If the object referred to has not been seen yet, recursively mark
5281 all the references contained in it. */
5283 #define LAST_MARKED_SIZE 500
5284 static Lisp_Object last_marked[LAST_MARKED_SIZE];
5285 int last_marked_index;
5287 /* For debugging--call abort when we cdr down this many
5288 links of a list, in mark_object. In debugging,
5289 the call to abort will hit a breakpoint.
5290 Normally this is zero and the check never goes off. */
5291 static int mark_object_loop_halt;
5293 static void
5294 mark_vectorlike (struct Lisp_Vector *ptr)
5296 register EMACS_INT size = ptr->size;
5297 register int i;
5299 eassert (!VECTOR_MARKED_P (ptr));
5300 VECTOR_MARK (ptr); /* Else mark it */
5301 if (size & PSEUDOVECTOR_FLAG)
5302 size &= PSEUDOVECTOR_SIZE_MASK;
5304 /* Note that this size is not the memory-footprint size, but only
5305 the number of Lisp_Object fields that we should trace.
5306 The distinction is used e.g. by Lisp_Process which places extra
5307 non-Lisp_Object fields at the end of the structure. */
5308 for (i = 0; i < size; i++) /* and then mark its elements */
5309 mark_object (ptr->contents[i]);
5312 /* Like mark_vectorlike but optimized for char-tables (and
5313 sub-char-tables) assuming that the contents are mostly integers or
5314 symbols. */
5316 static void
5317 mark_char_table (struct Lisp_Vector *ptr)
5319 register EMACS_INT size = ptr->size & PSEUDOVECTOR_SIZE_MASK;
5320 register int i;
5322 eassert (!VECTOR_MARKED_P (ptr));
5323 VECTOR_MARK (ptr);
5324 for (i = 0; i < size; i++)
5326 Lisp_Object val = ptr->contents[i];
5328 if (INTEGERP (val) || SYMBOLP (val) && XSYMBOL (val)->gcmarkbit)
5329 continue;
5330 if (SUB_CHAR_TABLE_P (val))
5332 if (! VECTOR_MARKED_P (XVECTOR (val)))
5333 mark_char_table (XVECTOR (val));
5335 else
5336 mark_object (val);
5340 void
5341 mark_object (Lisp_Object arg)
5343 register Lisp_Object obj = arg;
5344 #ifdef GC_CHECK_MARKED_OBJECTS
5345 void *po;
5346 struct mem_node *m;
5347 #endif
5348 int cdr_count = 0;
5350 loop:
5352 if (PURE_POINTER_P (XPNTR (obj)))
5353 return;
5355 last_marked[last_marked_index++] = obj;
5356 if (last_marked_index == LAST_MARKED_SIZE)
5357 last_marked_index = 0;
5359 /* Perform some sanity checks on the objects marked here. Abort if
5360 we encounter an object we know is bogus. This increases GC time
5361 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
5362 #ifdef GC_CHECK_MARKED_OBJECTS
5364 po = (void *) XPNTR (obj);
5366 /* Check that the object pointed to by PO is known to be a Lisp
5367 structure allocated from the heap. */
5368 #define CHECK_ALLOCATED() \
5369 do { \
5370 m = mem_find (po); \
5371 if (m == MEM_NIL) \
5372 abort (); \
5373 } while (0)
5375 /* Check that the object pointed to by PO is live, using predicate
5376 function LIVEP. */
5377 #define CHECK_LIVE(LIVEP) \
5378 do { \
5379 if (!LIVEP (m, po)) \
5380 abort (); \
5381 } while (0)
5383 /* Check both of the above conditions. */
5384 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
5385 do { \
5386 CHECK_ALLOCATED (); \
5387 CHECK_LIVE (LIVEP); \
5388 } while (0) \
5390 #else /* not GC_CHECK_MARKED_OBJECTS */
5392 #define CHECK_ALLOCATED() (void) 0
5393 #define CHECK_LIVE(LIVEP) (void) 0
5394 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
5396 #endif /* not GC_CHECK_MARKED_OBJECTS */
5398 switch (SWITCH_ENUM_CAST (XTYPE (obj)))
5400 case Lisp_String:
5402 register struct Lisp_String *ptr = XSTRING (obj);
5403 if (STRING_MARKED_P (ptr))
5404 break;
5405 CHECK_ALLOCATED_AND_LIVE (live_string_p);
5406 MARK_INTERVAL_TREE (ptr->intervals);
5407 MARK_STRING (ptr);
5408 #ifdef GC_CHECK_STRING_BYTES
5409 /* Check that the string size recorded in the string is the
5410 same as the one recorded in the sdata structure. */
5411 CHECK_STRING_BYTES (ptr);
5412 #endif /* GC_CHECK_STRING_BYTES */
5414 break;
5416 case Lisp_Vectorlike:
5417 if (VECTOR_MARKED_P (XVECTOR (obj)))
5418 break;
5419 #ifdef GC_CHECK_MARKED_OBJECTS
5420 m = mem_find (po);
5421 if (m == MEM_NIL && !SUBRP (obj)
5422 && po != &buffer_defaults
5423 && po != &buffer_local_symbols)
5424 abort ();
5425 #endif /* GC_CHECK_MARKED_OBJECTS */
5427 if (BUFFERP (obj))
5429 #ifdef GC_CHECK_MARKED_OBJECTS
5430 if (po != &buffer_defaults && po != &buffer_local_symbols)
5432 struct buffer *b;
5433 for (b = all_buffers; b && b != po; b = b->next)
5435 if (b == NULL)
5436 abort ();
5438 #endif /* GC_CHECK_MARKED_OBJECTS */
5439 mark_buffer (obj);
5441 else if (SUBRP (obj))
5442 break;
5443 else if (FUNVECP (obj) && FUNVEC_COMPILED_P (obj))
5444 /* We could treat this just like a vector, but it is better to
5445 save the COMPILED_CONSTANTS element for last and avoid
5446 recursion there. */
5448 register struct Lisp_Vector *ptr = XVECTOR (obj);
5449 register EMACS_INT size = ptr->size;
5450 register int i;
5452 CHECK_LIVE (live_vector_p);
5453 VECTOR_MARK (ptr); /* Else mark it */
5454 size &= PSEUDOVECTOR_SIZE_MASK;
5455 for (i = 0; i < size; i++) /* and then mark its elements */
5457 if (i != COMPILED_CONSTANTS)
5458 mark_object (ptr->contents[i]);
5460 obj = ptr->contents[COMPILED_CONSTANTS];
5461 goto loop;
5463 else if (FRAMEP (obj))
5465 register struct frame *ptr = XFRAME (obj);
5466 mark_vectorlike (XVECTOR (obj));
5467 mark_face_cache (ptr->face_cache);
5469 else if (WINDOWP (obj))
5471 register struct Lisp_Vector *ptr = XVECTOR (obj);
5472 struct window *w = XWINDOW (obj);
5473 mark_vectorlike (ptr);
5474 /* Mark glyphs for leaf windows. Marking window matrices is
5475 sufficient because frame matrices use the same glyph
5476 memory. */
5477 if (NILP (w->hchild)
5478 && NILP (w->vchild)
5479 && w->current_matrix)
5481 mark_glyph_matrix (w->current_matrix);
5482 mark_glyph_matrix (w->desired_matrix);
5485 else if (HASH_TABLE_P (obj))
5487 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
5488 mark_vectorlike ((struct Lisp_Vector *)h);
5489 /* If hash table is not weak, mark all keys and values.
5490 For weak tables, mark only the vector. */
5491 if (NILP (h->weak))
5492 mark_object (h->key_and_value);
5493 else
5494 VECTOR_MARK (XVECTOR (h->key_and_value));
5496 else if (CHAR_TABLE_P (obj))
5497 mark_char_table (XVECTOR (obj));
5498 else
5499 mark_vectorlike (XVECTOR (obj));
5500 break;
5502 case Lisp_Symbol:
5504 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
5505 struct Lisp_Symbol *ptrx;
5507 if (ptr->gcmarkbit)
5508 break;
5509 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
5510 ptr->gcmarkbit = 1;
5511 mark_object (ptr->function);
5512 mark_object (ptr->plist);
5513 switch (ptr->redirect)
5515 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
5516 case SYMBOL_VARALIAS:
5518 Lisp_Object tem;
5519 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
5520 mark_object (tem);
5521 break;
5523 case SYMBOL_LOCALIZED:
5525 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
5526 /* If the value is forwarded to a buffer or keyboard field,
5527 these are marked when we see the corresponding object.
5528 And if it's forwarded to a C variable, either it's not
5529 a Lisp_Object var, or it's staticpro'd already. */
5530 mark_object (blv->where);
5531 mark_object (blv->valcell);
5532 mark_object (blv->defcell);
5533 break;
5535 case SYMBOL_FORWARDED:
5536 /* If the value is forwarded to a buffer or keyboard field,
5537 these are marked when we see the corresponding object.
5538 And if it's forwarded to a C variable, either it's not
5539 a Lisp_Object var, or it's staticpro'd already. */
5540 break;
5541 default: abort ();
5543 if (!PURE_POINTER_P (XSTRING (ptr->xname)))
5544 MARK_STRING (XSTRING (ptr->xname));
5545 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr->xname));
5547 ptr = ptr->next;
5548 if (ptr)
5550 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
5551 XSETSYMBOL (obj, ptrx);
5552 goto loop;
5555 break;
5557 case Lisp_Misc:
5558 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
5559 if (XMISCANY (obj)->gcmarkbit)
5560 break;
5561 XMISCANY (obj)->gcmarkbit = 1;
5563 switch (XMISCTYPE (obj))
5566 case Lisp_Misc_Marker:
5567 /* DO NOT mark thru the marker's chain.
5568 The buffer's markers chain does not preserve markers from gc;
5569 instead, markers are removed from the chain when freed by gc. */
5570 break;
5572 case Lisp_Misc_Save_Value:
5573 #if GC_MARK_STACK
5575 register struct Lisp_Save_Value *ptr = XSAVE_VALUE (obj);
5576 /* If DOGC is set, POINTER is the address of a memory
5577 area containing INTEGER potential Lisp_Objects. */
5578 if (ptr->dogc)
5580 Lisp_Object *p = (Lisp_Object *) ptr->pointer;
5581 int nelt;
5582 for (nelt = ptr->integer; nelt > 0; nelt--, p++)
5583 mark_maybe_object (*p);
5586 #endif
5587 break;
5589 case Lisp_Misc_Overlay:
5591 struct Lisp_Overlay *ptr = XOVERLAY (obj);
5592 mark_object (ptr->start);
5593 mark_object (ptr->end);
5594 mark_object (ptr->plist);
5595 if (ptr->next)
5597 XSETMISC (obj, ptr->next);
5598 goto loop;
5601 break;
5603 default:
5604 abort ();
5606 break;
5608 case Lisp_Cons:
5610 register struct Lisp_Cons *ptr = XCONS (obj);
5611 if (CONS_MARKED_P (ptr))
5612 break;
5613 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
5614 CONS_MARK (ptr);
5615 /* If the cdr is nil, avoid recursion for the car. */
5616 if (EQ (ptr->u.cdr, Qnil))
5618 obj = ptr->car;
5619 cdr_count = 0;
5620 goto loop;
5622 mark_object (ptr->car);
5623 obj = ptr->u.cdr;
5624 cdr_count++;
5625 if (cdr_count == mark_object_loop_halt)
5626 abort ();
5627 goto loop;
5630 case Lisp_Float:
5631 CHECK_ALLOCATED_AND_LIVE (live_float_p);
5632 FLOAT_MARK (XFLOAT (obj));
5633 break;
5635 case_Lisp_Int:
5636 break;
5638 default:
5639 abort ();
5642 #undef CHECK_LIVE
5643 #undef CHECK_ALLOCATED
5644 #undef CHECK_ALLOCATED_AND_LIVE
5647 /* Mark the pointers in a buffer structure. */
5649 static void
5650 mark_buffer (Lisp_Object buf)
5652 register struct buffer *buffer = XBUFFER (buf);
5653 register Lisp_Object *ptr, tmp;
5654 Lisp_Object base_buffer;
5656 eassert (!VECTOR_MARKED_P (buffer));
5657 VECTOR_MARK (buffer);
5659 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
5661 /* For now, we just don't mark the undo_list. It's done later in
5662 a special way just before the sweep phase, and after stripping
5663 some of its elements that are not needed any more. */
5665 if (buffer->overlays_before)
5667 XSETMISC (tmp, buffer->overlays_before);
5668 mark_object (tmp);
5670 if (buffer->overlays_after)
5672 XSETMISC (tmp, buffer->overlays_after);
5673 mark_object (tmp);
5676 /* buffer-local Lisp variables start at `undo_list',
5677 tho only the ones from `name' on are GC'd normally. */
5678 for (ptr = &buffer->name;
5679 (char *)ptr < (char *)buffer + sizeof (struct buffer);
5680 ptr++)
5681 mark_object (*ptr);
5683 /* If this is an indirect buffer, mark its base buffer. */
5684 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5686 XSETBUFFER (base_buffer, buffer->base_buffer);
5687 mark_buffer (base_buffer);
5691 /* Mark the Lisp pointers in the terminal objects.
5692 Called by the Fgarbage_collector. */
5694 static void
5695 mark_terminals (void)
5697 struct terminal *t;
5698 for (t = terminal_list; t; t = t->next_terminal)
5700 eassert (t->name != NULL);
5701 if (!VECTOR_MARKED_P (t))
5703 #ifdef HAVE_WINDOW_SYSTEM
5704 mark_image_cache (t->image_cache);
5705 #endif /* HAVE_WINDOW_SYSTEM */
5706 mark_vectorlike ((struct Lisp_Vector *)t);
5713 /* Value is non-zero if OBJ will survive the current GC because it's
5714 either marked or does not need to be marked to survive. */
5717 survives_gc_p (Lisp_Object obj)
5719 int survives_p;
5721 switch (XTYPE (obj))
5723 case_Lisp_Int:
5724 survives_p = 1;
5725 break;
5727 case Lisp_Symbol:
5728 survives_p = XSYMBOL (obj)->gcmarkbit;
5729 break;
5731 case Lisp_Misc:
5732 survives_p = XMISCANY (obj)->gcmarkbit;
5733 break;
5735 case Lisp_String:
5736 survives_p = STRING_MARKED_P (XSTRING (obj));
5737 break;
5739 case Lisp_Vectorlike:
5740 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
5741 break;
5743 case Lisp_Cons:
5744 survives_p = CONS_MARKED_P (XCONS (obj));
5745 break;
5747 case Lisp_Float:
5748 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
5749 break;
5751 default:
5752 abort ();
5755 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
5760 /* Sweep: find all structures not marked, and free them. */
5762 static void
5763 gc_sweep (void)
5765 /* Remove or mark entries in weak hash tables.
5766 This must be done before any object is unmarked. */
5767 sweep_weak_hash_tables ();
5769 sweep_strings ();
5770 #ifdef GC_CHECK_STRING_BYTES
5771 if (!noninteractive)
5772 check_string_bytes (1);
5773 #endif
5775 /* Put all unmarked conses on free list */
5777 register struct cons_block *cblk;
5778 struct cons_block **cprev = &cons_block;
5779 register int lim = cons_block_index;
5780 register int num_free = 0, num_used = 0;
5782 cons_free_list = 0;
5784 for (cblk = cons_block; cblk; cblk = *cprev)
5786 register int i = 0;
5787 int this_free = 0;
5788 int ilim = (lim + BITS_PER_INT - 1) / BITS_PER_INT;
5790 /* Scan the mark bits an int at a time. */
5791 for (i = 0; i <= ilim; i++)
5793 if (cblk->gcmarkbits[i] == -1)
5795 /* Fast path - all cons cells for this int are marked. */
5796 cblk->gcmarkbits[i] = 0;
5797 num_used += BITS_PER_INT;
5799 else
5801 /* Some cons cells for this int are not marked.
5802 Find which ones, and free them. */
5803 int start, pos, stop;
5805 start = i * BITS_PER_INT;
5806 stop = lim - start;
5807 if (stop > BITS_PER_INT)
5808 stop = BITS_PER_INT;
5809 stop += start;
5811 for (pos = start; pos < stop; pos++)
5813 if (!CONS_MARKED_P (&cblk->conses[pos]))
5815 this_free++;
5816 cblk->conses[pos].u.chain = cons_free_list;
5817 cons_free_list = &cblk->conses[pos];
5818 #if GC_MARK_STACK
5819 cons_free_list->car = Vdead;
5820 #endif
5822 else
5824 num_used++;
5825 CONS_UNMARK (&cblk->conses[pos]);
5831 lim = CONS_BLOCK_SIZE;
5832 /* If this block contains only free conses and we have already
5833 seen more than two blocks worth of free conses then deallocate
5834 this block. */
5835 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
5837 *cprev = cblk->next;
5838 /* Unhook from the free list. */
5839 cons_free_list = cblk->conses[0].u.chain;
5840 lisp_align_free (cblk);
5841 n_cons_blocks--;
5843 else
5845 num_free += this_free;
5846 cprev = &cblk->next;
5849 total_conses = num_used;
5850 total_free_conses = num_free;
5853 /* Put all unmarked floats on free list */
5855 register struct float_block *fblk;
5856 struct float_block **fprev = &float_block;
5857 register int lim = float_block_index;
5858 register int num_free = 0, num_used = 0;
5860 float_free_list = 0;
5862 for (fblk = float_block; fblk; fblk = *fprev)
5864 register int i;
5865 int this_free = 0;
5866 for (i = 0; i < lim; i++)
5867 if (!FLOAT_MARKED_P (&fblk->floats[i]))
5869 this_free++;
5870 fblk->floats[i].u.chain = float_free_list;
5871 float_free_list = &fblk->floats[i];
5873 else
5875 num_used++;
5876 FLOAT_UNMARK (&fblk->floats[i]);
5878 lim = FLOAT_BLOCK_SIZE;
5879 /* If this block contains only free floats and we have already
5880 seen more than two blocks worth of free floats then deallocate
5881 this block. */
5882 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
5884 *fprev = fblk->next;
5885 /* Unhook from the free list. */
5886 float_free_list = fblk->floats[0].u.chain;
5887 lisp_align_free (fblk);
5888 n_float_blocks--;
5890 else
5892 num_free += this_free;
5893 fprev = &fblk->next;
5896 total_floats = num_used;
5897 total_free_floats = num_free;
5900 /* Put all unmarked intervals on free list */
5902 register struct interval_block *iblk;
5903 struct interval_block **iprev = &interval_block;
5904 register int lim = interval_block_index;
5905 register int num_free = 0, num_used = 0;
5907 interval_free_list = 0;
5909 for (iblk = interval_block; iblk; iblk = *iprev)
5911 register int i;
5912 int this_free = 0;
5914 for (i = 0; i < lim; i++)
5916 if (!iblk->intervals[i].gcmarkbit)
5918 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
5919 interval_free_list = &iblk->intervals[i];
5920 this_free++;
5922 else
5924 num_used++;
5925 iblk->intervals[i].gcmarkbit = 0;
5928 lim = INTERVAL_BLOCK_SIZE;
5929 /* If this block contains only free intervals and we have already
5930 seen more than two blocks worth of free intervals then
5931 deallocate this block. */
5932 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
5934 *iprev = iblk->next;
5935 /* Unhook from the free list. */
5936 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
5937 lisp_free (iblk);
5938 n_interval_blocks--;
5940 else
5942 num_free += this_free;
5943 iprev = &iblk->next;
5946 total_intervals = num_used;
5947 total_free_intervals = num_free;
5950 /* Put all unmarked symbols on free list */
5952 register struct symbol_block *sblk;
5953 struct symbol_block **sprev = &symbol_block;
5954 register int lim = symbol_block_index;
5955 register int num_free = 0, num_used = 0;
5957 symbol_free_list = NULL;
5959 for (sblk = symbol_block; sblk; sblk = *sprev)
5961 int this_free = 0;
5962 struct Lisp_Symbol *sym = sblk->symbols;
5963 struct Lisp_Symbol *end = sym + lim;
5965 for (; sym < end; ++sym)
5967 /* Check if the symbol was created during loadup. In such a case
5968 it might be pointed to by pure bytecode which we don't trace,
5969 so we conservatively assume that it is live. */
5970 int pure_p = PURE_POINTER_P (XSTRING (sym->xname));
5972 if (!sym->gcmarkbit && !pure_p)
5974 if (sym->redirect == SYMBOL_LOCALIZED)
5975 xfree (SYMBOL_BLV (sym));
5976 sym->next = symbol_free_list;
5977 symbol_free_list = sym;
5978 #if GC_MARK_STACK
5979 symbol_free_list->function = Vdead;
5980 #endif
5981 ++this_free;
5983 else
5985 ++num_used;
5986 if (!pure_p)
5987 UNMARK_STRING (XSTRING (sym->xname));
5988 sym->gcmarkbit = 0;
5992 lim = SYMBOL_BLOCK_SIZE;
5993 /* If this block contains only free symbols and we have already
5994 seen more than two blocks worth of free symbols then deallocate
5995 this block. */
5996 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
5998 *sprev = sblk->next;
5999 /* Unhook from the free list. */
6000 symbol_free_list = sblk->symbols[0].next;
6001 lisp_free (sblk);
6002 n_symbol_blocks--;
6004 else
6006 num_free += this_free;
6007 sprev = &sblk->next;
6010 total_symbols = num_used;
6011 total_free_symbols = num_free;
6014 /* Put all unmarked misc's on free list.
6015 For a marker, first unchain it from the buffer it points into. */
6017 register struct marker_block *mblk;
6018 struct marker_block **mprev = &marker_block;
6019 register int lim = marker_block_index;
6020 register int num_free = 0, num_used = 0;
6022 marker_free_list = 0;
6024 for (mblk = marker_block; mblk; mblk = *mprev)
6026 register int i;
6027 int this_free = 0;
6029 for (i = 0; i < lim; i++)
6031 if (!mblk->markers[i].u_any.gcmarkbit)
6033 if (mblk->markers[i].u_any.type == Lisp_Misc_Marker)
6034 unchain_marker (&mblk->markers[i].u_marker);
6035 /* Set the type of the freed object to Lisp_Misc_Free.
6036 We could leave the type alone, since nobody checks it,
6037 but this might catch bugs faster. */
6038 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
6039 mblk->markers[i].u_free.chain = marker_free_list;
6040 marker_free_list = &mblk->markers[i];
6041 this_free++;
6043 else
6045 num_used++;
6046 mblk->markers[i].u_any.gcmarkbit = 0;
6049 lim = MARKER_BLOCK_SIZE;
6050 /* If this block contains only free markers and we have already
6051 seen more than two blocks worth of free markers then deallocate
6052 this block. */
6053 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6055 *mprev = mblk->next;
6056 /* Unhook from the free list. */
6057 marker_free_list = mblk->markers[0].u_free.chain;
6058 lisp_free (mblk);
6059 n_marker_blocks--;
6061 else
6063 num_free += this_free;
6064 mprev = &mblk->next;
6068 total_markers = num_used;
6069 total_free_markers = num_free;
6072 /* Free all unmarked buffers */
6074 register struct buffer *buffer = all_buffers, *prev = 0, *next;
6076 while (buffer)
6077 if (!VECTOR_MARKED_P (buffer))
6079 if (prev)
6080 prev->next = buffer->next;
6081 else
6082 all_buffers = buffer->next;
6083 next = buffer->next;
6084 lisp_free (buffer);
6085 buffer = next;
6087 else
6089 VECTOR_UNMARK (buffer);
6090 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
6091 prev = buffer, buffer = buffer->next;
6095 /* Free all unmarked vectors */
6097 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
6098 total_vector_size = 0;
6100 while (vector)
6101 if (!VECTOR_MARKED_P (vector))
6103 if (prev)
6104 prev->next = vector->next;
6105 else
6106 all_vectors = vector->next;
6107 next = vector->next;
6108 lisp_free (vector);
6109 n_vectors--;
6110 vector = next;
6113 else
6115 VECTOR_UNMARK (vector);
6116 if (vector->size & PSEUDOVECTOR_FLAG)
6117 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
6118 else
6119 total_vector_size += vector->size;
6120 prev = vector, vector = vector->next;
6124 #ifdef GC_CHECK_STRING_BYTES
6125 if (!noninteractive)
6126 check_string_bytes (1);
6127 #endif
6133 /* Debugging aids. */
6135 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
6136 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6137 This may be helpful in debugging Emacs's memory usage.
6138 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6139 (void)
6141 Lisp_Object end;
6143 XSETINT (end, (EMACS_INT) sbrk (0) / 1024);
6145 return end;
6148 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
6149 doc: /* Return a list of counters that measure how much consing there has been.
6150 Each of these counters increments for a certain kind of object.
6151 The counters wrap around from the largest positive integer to zero.
6152 Garbage collection does not decrease them.
6153 The elements of the value are as follows:
6154 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6155 All are in units of 1 = one object consed
6156 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6157 objects consed.
6158 MISCS include overlays, markers, and some internal types.
6159 Frames, windows, buffers, and subprocesses count as vectors
6160 (but the contents of a buffer's text do not count here). */)
6161 (void)
6163 Lisp_Object consed[8];
6165 consed[0] = make_number (min (MOST_POSITIVE_FIXNUM, cons_cells_consed));
6166 consed[1] = make_number (min (MOST_POSITIVE_FIXNUM, floats_consed));
6167 consed[2] = make_number (min (MOST_POSITIVE_FIXNUM, vector_cells_consed));
6168 consed[3] = make_number (min (MOST_POSITIVE_FIXNUM, symbols_consed));
6169 consed[4] = make_number (min (MOST_POSITIVE_FIXNUM, string_chars_consed));
6170 consed[5] = make_number (min (MOST_POSITIVE_FIXNUM, misc_objects_consed));
6171 consed[6] = make_number (min (MOST_POSITIVE_FIXNUM, intervals_consed));
6172 consed[7] = make_number (min (MOST_POSITIVE_FIXNUM, strings_consed));
6174 return Flist (8, consed);
6177 int suppress_checking;
6179 void
6180 die (const char *msg, const char *file, int line)
6182 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: %s\r\n",
6183 file, line, msg);
6184 abort ();
6187 /* Initialization */
6189 void
6190 init_alloc_once (void)
6192 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
6193 purebeg = PUREBEG;
6194 pure_size = PURESIZE;
6195 pure_bytes_used = 0;
6196 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
6197 pure_bytes_used_before_overflow = 0;
6199 /* Initialize the list of free aligned blocks. */
6200 free_ablock = NULL;
6202 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
6203 mem_init ();
6204 Vdead = make_pure_string ("DEAD", 4, 4, 0);
6205 #endif
6207 all_vectors = 0;
6208 ignore_warnings = 1;
6209 #ifdef DOUG_LEA_MALLOC
6210 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
6211 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
6212 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
6213 #endif
6214 init_strings ();
6215 init_cons ();
6216 init_symbol ();
6217 init_marker ();
6218 init_float ();
6219 init_intervals ();
6220 init_weak_hash_tables ();
6222 #ifdef REL_ALLOC
6223 malloc_hysteresis = 32;
6224 #else
6225 malloc_hysteresis = 0;
6226 #endif
6228 refill_memory_reserve ();
6230 ignore_warnings = 0;
6231 gcprolist = 0;
6232 byte_stack_list = 0;
6233 staticidx = 0;
6234 consing_since_gc = 0;
6235 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
6236 gc_relative_threshold = 0;
6238 #ifdef VIRT_ADDR_VARIES
6239 malloc_sbrk_unused = 1<<22; /* A large number */
6240 malloc_sbrk_used = 100000; /* as reasonable as any number */
6241 #endif /* VIRT_ADDR_VARIES */
6244 void
6245 init_alloc (void)
6247 gcprolist = 0;
6248 byte_stack_list = 0;
6249 #if GC_MARK_STACK
6250 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
6251 setjmp_tested_p = longjmps_done = 0;
6252 #endif
6253 #endif
6254 Vgc_elapsed = make_float (0.0);
6255 gcs_done = 0;
6258 void
6259 syms_of_alloc (void)
6261 DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold,
6262 doc: /* *Number of bytes of consing between garbage collections.
6263 Garbage collection can happen automatically once this many bytes have been
6264 allocated since the last garbage collection. All data types count.
6266 Garbage collection happens automatically only when `eval' is called.
6268 By binding this temporarily to a large number, you can effectively
6269 prevent garbage collection during a part of the program.
6270 See also `gc-cons-percentage'. */);
6272 DEFVAR_LISP ("gc-cons-percentage", &Vgc_cons_percentage,
6273 doc: /* *Portion of the heap used for allocation.
6274 Garbage collection can happen automatically once this portion of the heap
6275 has been allocated since the last garbage collection.
6276 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
6277 Vgc_cons_percentage = make_float (0.1);
6279 DEFVAR_INT ("pure-bytes-used", &pure_bytes_used,
6280 doc: /* Number of bytes of sharable Lisp data allocated so far. */);
6282 DEFVAR_INT ("cons-cells-consed", &cons_cells_consed,
6283 doc: /* Number of cons cells that have been consed so far. */);
6285 DEFVAR_INT ("floats-consed", &floats_consed,
6286 doc: /* Number of floats that have been consed so far. */);
6288 DEFVAR_INT ("vector-cells-consed", &vector_cells_consed,
6289 doc: /* Number of vector cells that have been consed so far. */);
6291 DEFVAR_INT ("symbols-consed", &symbols_consed,
6292 doc: /* Number of symbols that have been consed so far. */);
6294 DEFVAR_INT ("string-chars-consed", &string_chars_consed,
6295 doc: /* Number of string characters that have been consed so far. */);
6297 DEFVAR_INT ("misc-objects-consed", &misc_objects_consed,
6298 doc: /* Number of miscellaneous objects that have been consed so far. */);
6300 DEFVAR_INT ("intervals-consed", &intervals_consed,
6301 doc: /* Number of intervals that have been consed so far. */);
6303 DEFVAR_INT ("strings-consed", &strings_consed,
6304 doc: /* Number of strings that have been consed so far. */);
6306 DEFVAR_LISP ("purify-flag", &Vpurify_flag,
6307 doc: /* Non-nil means loading Lisp code in order to dump an executable.
6308 This means that certain objects should be allocated in shared (pure) space.
6309 It can also be set to a hash-table, in which case this table is used to
6310 do hash-consing of the objects allocated to pure space. */);
6312 DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
6313 doc: /* Non-nil means display messages at start and end of garbage collection. */);
6314 garbage_collection_messages = 0;
6316 DEFVAR_LISP ("post-gc-hook", &Vpost_gc_hook,
6317 doc: /* Hook run after garbage collection has finished. */);
6318 Vpost_gc_hook = Qnil;
6319 Qpost_gc_hook = intern_c_string ("post-gc-hook");
6320 staticpro (&Qpost_gc_hook);
6322 DEFVAR_LISP ("memory-signal-data", &Vmemory_signal_data,
6323 doc: /* Precomputed `signal' argument for memory-full error. */);
6324 /* We build this in advance because if we wait until we need it, we might
6325 not be able to allocate the memory to hold it. */
6326 Vmemory_signal_data
6327 = pure_cons (Qerror,
6328 pure_cons (make_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"), Qnil));
6330 DEFVAR_LISP ("memory-full", &Vmemory_full,
6331 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
6332 Vmemory_full = Qnil;
6334 staticpro (&Qgc_cons_threshold);
6335 Qgc_cons_threshold = intern_c_string ("gc-cons-threshold");
6337 staticpro (&Qchar_table_extra_slots);
6338 Qchar_table_extra_slots = intern_c_string ("char-table-extra-slots");
6340 DEFVAR_LISP ("gc-elapsed", &Vgc_elapsed,
6341 doc: /* Accumulated time elapsed in garbage collections.
6342 The time is in seconds as a floating point value. */);
6343 DEFVAR_INT ("gcs-done", &gcs_done,
6344 doc: /* Accumulated number of garbage collections done. */);
6346 defsubr (&Scons);
6347 defsubr (&Slist);
6348 defsubr (&Svector);
6349 defsubr (&Sfunvec);
6350 defsubr (&Smake_byte_code);
6351 defsubr (&Smake_list);
6352 defsubr (&Smake_vector);
6353 defsubr (&Smake_string);
6354 defsubr (&Smake_bool_vector);
6355 defsubr (&Smake_symbol);
6356 defsubr (&Smake_marker);
6357 defsubr (&Spurecopy);
6358 defsubr (&Sgarbage_collect);
6359 defsubr (&Smemory_limit);
6360 defsubr (&Smemory_use_counts);
6362 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
6363 defsubr (&Sgc_status);
6364 #endif
6367 /* arch-tag: 6695ca10-e3c5-4c2c-8bc3-ed26a7dda857
6368 (do not change this comment) */