Merge from trunk
[emacs.git] / src / alloc.c
blob0ca702fe0cd3bf229d6441bc27f5fb4594db6de1
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
2 Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2011
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 #include <config.h>
21 #include <stdio.h>
22 #include <limits.h> /* For CHAR_BIT. */
23 #include <setjmp.h>
25 #ifdef ALLOC_DEBUG
26 #undef INLINE
27 #endif
29 #include <signal.h>
31 #ifdef HAVE_GTK_AND_PTHREAD
32 #include <pthread.h>
33 #endif
35 /* This file is part of the core Lisp implementation, and thus must
36 deal with the real data structures. If the Lisp implementation is
37 replaced, this file likely will not be used. */
39 #undef HIDE_LISP_IMPLEMENTATION
40 #include "lisp.h"
41 #include "process.h"
42 #include "intervals.h"
43 #include "puresize.h"
44 #include "buffer.h"
45 #include "window.h"
46 #include "keyboard.h"
47 #include "frame.h"
48 #include "blockinput.h"
49 #include "character.h"
50 #include "syssignal.h"
51 #include "termhooks.h" /* For struct terminal. */
52 #include <setjmp.h>
54 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
55 memory. Can do this only if using gmalloc.c. */
57 #if defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC
58 #undef GC_MALLOC_CHECK
59 #endif
61 #include <unistd.h>
62 #ifndef HAVE_UNISTD_H
63 extern POINTER_TYPE *sbrk ();
64 #endif
66 #include <fcntl.h>
68 #ifdef WINDOWSNT
69 #include "w32.h"
70 #endif
72 #ifdef DOUG_LEA_MALLOC
74 #include <malloc.h>
75 /* malloc.h #defines this as size_t, at least in glibc2. */
76 #ifndef __malloc_size_t
77 #define __malloc_size_t int
78 #endif
80 /* Specify maximum number of areas to mmap. It would be nice to use a
81 value that explicitly means "no limit". */
83 #define MMAP_MAX_AREAS 100000000
85 #else /* not DOUG_LEA_MALLOC */
87 /* The following come from gmalloc.c. */
89 #define __malloc_size_t size_t
90 extern __malloc_size_t _bytes_used;
91 extern __malloc_size_t __malloc_extra_blocks;
93 #endif /* not DOUG_LEA_MALLOC */
95 #if ! defined SYSTEM_MALLOC && ! defined SYNC_INPUT
96 #ifdef HAVE_GTK_AND_PTHREAD
98 /* When GTK uses the file chooser dialog, different backends can be loaded
99 dynamically. One such a backend is the Gnome VFS backend that gets loaded
100 if you run Gnome. That backend creates several threads and also allocates
101 memory with malloc.
103 If Emacs sets malloc hooks (! SYSTEM_MALLOC) and the emacs_blocked_*
104 functions below are called from malloc, there is a chance that one
105 of these threads preempts the Emacs main thread and the hook variables
106 end up in an inconsistent state. So we have a mutex to prevent that (note
107 that the backend handles concurrent access to malloc within its own threads
108 but Emacs code running in the main thread is not included in that control).
110 When UNBLOCK_INPUT is called, reinvoke_input_signal may be called. If this
111 happens in one of the backend threads we will have two threads that tries
112 to run Emacs code at once, and the code is not prepared for that.
113 To prevent that, we only call BLOCK/UNBLOCK from the main thread. */
115 static pthread_mutex_t alloc_mutex;
117 #define BLOCK_INPUT_ALLOC \
118 do \
120 if (pthread_equal (pthread_self (), main_thread)) \
121 BLOCK_INPUT; \
122 pthread_mutex_lock (&alloc_mutex); \
124 while (0)
125 #define UNBLOCK_INPUT_ALLOC \
126 do \
128 pthread_mutex_unlock (&alloc_mutex); \
129 if (pthread_equal (pthread_self (), main_thread)) \
130 UNBLOCK_INPUT; \
132 while (0)
134 #else /* ! defined HAVE_GTK_AND_PTHREAD */
136 #define BLOCK_INPUT_ALLOC BLOCK_INPUT
137 #define UNBLOCK_INPUT_ALLOC UNBLOCK_INPUT
139 #endif /* ! defined HAVE_GTK_AND_PTHREAD */
140 #endif /* ! defined SYSTEM_MALLOC && ! defined SYNC_INPUT */
142 /* Value of _bytes_used, when spare_memory was freed. */
144 static __malloc_size_t bytes_used_when_full;
146 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
147 to a struct Lisp_String. */
149 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
150 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
151 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
153 #define VECTOR_MARK(V) ((V)->size |= ARRAY_MARK_FLAG)
154 #define VECTOR_UNMARK(V) ((V)->size &= ~ARRAY_MARK_FLAG)
155 #define VECTOR_MARKED_P(V) (((V)->size & ARRAY_MARK_FLAG) != 0)
157 /* Value is the number of bytes of S, a pointer to a struct Lisp_String.
158 Be careful during GC, because S->size contains the mark bit for
159 strings. */
161 #define GC_STRING_BYTES(S) (STRING_BYTES (S))
163 /* Global variables. */
164 struct emacs_globals globals;
166 /* Number of bytes of consing done since the last gc. */
168 int consing_since_gc;
170 /* Similar minimum, computed from Vgc_cons_percentage. */
172 EMACS_INT gc_relative_threshold;
174 /* Minimum number of bytes of consing since GC before next GC,
175 when memory is full. */
177 EMACS_INT memory_full_cons_threshold;
179 /* Nonzero during GC. */
181 int gc_in_progress;
183 /* Nonzero means abort if try to GC.
184 This is for code which is written on the assumption that
185 no GC will happen, so as to verify that assumption. */
187 int abort_on_gc;
189 /* Number of live and free conses etc. */
191 static int total_conses, total_markers, total_symbols, total_vector_size;
192 static int total_free_conses, total_free_markers, total_free_symbols;
193 static int total_free_floats, total_floats;
195 /* Points to memory space allocated as "spare", to be freed if we run
196 out of memory. We keep one large block, four cons-blocks, and
197 two string blocks. */
199 static char *spare_memory[7];
201 /* Amount of spare memory to keep in large reserve block. */
203 #define SPARE_MEMORY (1 << 14)
205 /* Number of extra blocks malloc should get when it needs more core. */
207 static int malloc_hysteresis;
209 /* Initialize it to a nonzero value to force it into data space
210 (rather than bss space). That way unexec will remap it into text
211 space (pure), on some systems. We have not implemented the
212 remapping on more recent systems because this is less important
213 nowadays than in the days of small memories and timesharing. */
215 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
216 #define PUREBEG (char *) pure
218 /* Pointer to the pure area, and its size. */
220 static char *purebeg;
221 static size_t pure_size;
223 /* Number of bytes of pure storage used before pure storage overflowed.
224 If this is non-zero, this implies that an overflow occurred. */
226 static size_t pure_bytes_used_before_overflow;
228 /* Value is non-zero if P points into pure space. */
230 #define PURE_POINTER_P(P) \
231 (((PNTR_COMPARISON_TYPE) (P) \
232 < (PNTR_COMPARISON_TYPE) ((char *) purebeg + pure_size)) \
233 && ((PNTR_COMPARISON_TYPE) (P) \
234 >= (PNTR_COMPARISON_TYPE) purebeg))
236 /* Index in pure at which next pure Lisp object will be allocated.. */
238 static EMACS_INT pure_bytes_used_lisp;
240 /* Number of bytes allocated for non-Lisp objects in pure storage. */
242 static EMACS_INT pure_bytes_used_non_lisp;
244 /* If nonzero, this is a warning delivered by malloc and not yet
245 displayed. */
247 const char *pending_malloc_warning;
249 /* Maximum amount of C stack to save when a GC happens. */
251 #ifndef MAX_SAVE_STACK
252 #define MAX_SAVE_STACK 16000
253 #endif
255 /* Buffer in which we save a copy of the C stack at each GC. */
257 static char *stack_copy;
258 static int stack_copy_size;
260 /* Non-zero means ignore malloc warnings. Set during initialization.
261 Currently not used. */
263 static int ignore_warnings;
265 Lisp_Object Qgc_cons_threshold, Qchar_table_extra_slots;
267 /* Hook run after GC has finished. */
269 Lisp_Object Qpost_gc_hook;
271 static void mark_buffer (Lisp_Object);
272 static void mark_terminals (void);
273 static void gc_sweep (void);
274 static void mark_glyph_matrix (struct glyph_matrix *);
275 static void mark_face_cache (struct face_cache *);
277 static struct Lisp_String *allocate_string (void);
278 static void compact_small_strings (void);
279 static void free_large_strings (void);
280 static void sweep_strings (void);
282 extern int message_enable_multibyte;
284 /* When scanning the C stack for live Lisp objects, Emacs keeps track
285 of what memory allocated via lisp_malloc is intended for what
286 purpose. This enumeration specifies the type of memory. */
288 enum mem_type
290 MEM_TYPE_NON_LISP,
291 MEM_TYPE_BUFFER,
292 MEM_TYPE_CONS,
293 MEM_TYPE_STRING,
294 MEM_TYPE_MISC,
295 MEM_TYPE_SYMBOL,
296 MEM_TYPE_FLOAT,
297 /* We used to keep separate mem_types for subtypes of vectors such as
298 process, hash_table, frame, terminal, and window, but we never made
299 use of the distinction, so it only caused source-code complexity
300 and runtime slowdown. Minor but pointless. */
301 MEM_TYPE_VECTORLIKE
304 static POINTER_TYPE *lisp_align_malloc (size_t, enum mem_type);
305 static POINTER_TYPE *lisp_malloc (size_t, enum mem_type);
308 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
310 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
311 #include <stdio.h> /* For fprintf. */
312 #endif
314 /* A unique object in pure space used to make some Lisp objects
315 on free lists recognizable in O(1). */
317 static Lisp_Object Vdead;
319 #ifdef GC_MALLOC_CHECK
321 enum mem_type allocated_mem_type;
322 static int dont_register_blocks;
324 #endif /* GC_MALLOC_CHECK */
326 /* A node in the red-black tree describing allocated memory containing
327 Lisp data. Each such block is recorded with its start and end
328 address when it is allocated, and removed from the tree when it
329 is freed.
331 A red-black tree is a balanced binary tree with the following
332 properties:
334 1. Every node is either red or black.
335 2. Every leaf is black.
336 3. If a node is red, then both of its children are black.
337 4. Every simple path from a node to a descendant leaf contains
338 the same number of black nodes.
339 5. The root is always black.
341 When nodes are inserted into the tree, or deleted from the tree,
342 the tree is "fixed" so that these properties are always true.
344 A red-black tree with N internal nodes has height at most 2
345 log(N+1). Searches, insertions and deletions are done in O(log N).
346 Please see a text book about data structures for a detailed
347 description of red-black trees. Any book worth its salt should
348 describe them. */
350 struct mem_node
352 /* Children of this node. These pointers are never NULL. When there
353 is no child, the value is MEM_NIL, which points to a dummy node. */
354 struct mem_node *left, *right;
356 /* The parent of this node. In the root node, this is NULL. */
357 struct mem_node *parent;
359 /* Start and end of allocated region. */
360 void *start, *end;
362 /* Node color. */
363 enum {MEM_BLACK, MEM_RED} color;
365 /* Memory type. */
366 enum mem_type type;
369 /* Base address of stack. Set in main. */
371 Lisp_Object *stack_base;
373 /* Root of the tree describing allocated Lisp memory. */
375 static struct mem_node *mem_root;
377 /* Lowest and highest known address in the heap. */
379 static void *min_heap_address, *max_heap_address;
381 /* Sentinel node of the tree. */
383 static struct mem_node mem_z;
384 #define MEM_NIL &mem_z
386 static struct Lisp_Vector *allocate_vectorlike (EMACS_INT);
387 static void lisp_free (POINTER_TYPE *);
388 static void mark_stack (void);
389 static int live_vector_p (struct mem_node *, void *);
390 static int live_buffer_p (struct mem_node *, void *);
391 static int live_string_p (struct mem_node *, void *);
392 static int live_cons_p (struct mem_node *, void *);
393 static int live_symbol_p (struct mem_node *, void *);
394 static int live_float_p (struct mem_node *, void *);
395 static int live_misc_p (struct mem_node *, void *);
396 static void mark_maybe_object (Lisp_Object);
397 static void mark_memory (void *, void *, int);
398 static void mem_init (void);
399 static struct mem_node *mem_insert (void *, void *, enum mem_type);
400 static void mem_insert_fixup (struct mem_node *);
401 static void mem_rotate_left (struct mem_node *);
402 static void mem_rotate_right (struct mem_node *);
403 static void mem_delete (struct mem_node *);
404 static void mem_delete_fixup (struct mem_node *);
405 static INLINE struct mem_node *mem_find (void *);
408 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
409 static void check_gcpros (void);
410 #endif
412 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
414 /* Recording what needs to be marked for gc. */
416 struct gcpro *gcprolist;
418 /* Addresses of staticpro'd variables. Initialize it to a nonzero
419 value; otherwise some compilers put it into BSS. */
421 #define NSTATICS 0x640
422 static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
424 /* Index of next unused slot in staticvec. */
426 static int staticidx = 0;
428 static POINTER_TYPE *pure_alloc (size_t, int);
431 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
432 ALIGNMENT must be a power of 2. */
434 #define ALIGN(ptr, ALIGNMENT) \
435 ((POINTER_TYPE *) ((((EMACS_UINT)(ptr)) + (ALIGNMENT) - 1) \
436 & ~((ALIGNMENT) - 1)))
440 /************************************************************************
441 Malloc
442 ************************************************************************/
444 /* Function malloc calls this if it finds we are near exhausting storage. */
446 void
447 malloc_warning (const char *str)
449 pending_malloc_warning = str;
453 /* Display an already-pending malloc warning. */
455 void
456 display_malloc_warning (void)
458 call3 (intern ("display-warning"),
459 intern ("alloc"),
460 build_string (pending_malloc_warning),
461 intern ("emergency"));
462 pending_malloc_warning = 0;
466 #ifdef DOUG_LEA_MALLOC
467 # define BYTES_USED (mallinfo ().uordblks)
468 #else
469 # define BYTES_USED _bytes_used
470 #endif
472 /* Called if we can't allocate relocatable space for a buffer. */
474 void
475 buffer_memory_full (void)
477 /* If buffers use the relocating allocator, no need to free
478 spare_memory, because we may have plenty of malloc space left
479 that we could get, and if we don't, the malloc that fails will
480 itself cause spare_memory to be freed. If buffers don't use the
481 relocating allocator, treat this like any other failing
482 malloc. */
484 #ifndef REL_ALLOC
485 memory_full ();
486 #endif
488 /* This used to call error, but if we've run out of memory, we could
489 get infinite recursion trying to build the string. */
490 xsignal (Qnil, Vmemory_signal_data);
494 #ifdef XMALLOC_OVERRUN_CHECK
496 /* Check for overrun in malloc'ed buffers by wrapping a 16 byte header
497 and a 16 byte trailer around each block.
499 The header consists of 12 fixed bytes + a 4 byte integer contaning the
500 original block size, while the trailer consists of 16 fixed bytes.
502 The header is used to detect whether this block has been allocated
503 through these functions -- as it seems that some low-level libc
504 functions may bypass the malloc hooks.
508 #define XMALLOC_OVERRUN_CHECK_SIZE 16
510 static char xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE-4] =
511 { 0x9a, 0x9b, 0xae, 0xaf,
512 0xbf, 0xbe, 0xce, 0xcf,
513 0xea, 0xeb, 0xec, 0xed };
515 static char xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
516 { 0xaa, 0xab, 0xac, 0xad,
517 0xba, 0xbb, 0xbc, 0xbd,
518 0xca, 0xcb, 0xcc, 0xcd,
519 0xda, 0xdb, 0xdc, 0xdd };
521 /* Macros to insert and extract the block size in the header. */
523 #define XMALLOC_PUT_SIZE(ptr, size) \
524 (ptr[-1] = (size & 0xff), \
525 ptr[-2] = ((size >> 8) & 0xff), \
526 ptr[-3] = ((size >> 16) & 0xff), \
527 ptr[-4] = ((size >> 24) & 0xff))
529 #define XMALLOC_GET_SIZE(ptr) \
530 (size_t)((unsigned)(ptr[-1]) | \
531 ((unsigned)(ptr[-2]) << 8) | \
532 ((unsigned)(ptr[-3]) << 16) | \
533 ((unsigned)(ptr[-4]) << 24))
536 /* The call depth in overrun_check functions. For example, this might happen:
537 xmalloc()
538 overrun_check_malloc()
539 -> malloc -> (via hook)_-> emacs_blocked_malloc
540 -> overrun_check_malloc
541 call malloc (hooks are NULL, so real malloc is called).
542 malloc returns 10000.
543 add overhead, return 10016.
544 <- (back in overrun_check_malloc)
545 add overhead again, return 10032
546 xmalloc returns 10032.
548 (time passes).
550 xfree(10032)
551 overrun_check_free(10032)
552 decrease overhed
553 free(10016) <- crash, because 10000 is the original pointer. */
555 static int check_depth;
557 /* Like malloc, but wraps allocated block with header and trailer. */
559 POINTER_TYPE *
560 overrun_check_malloc (size)
561 size_t size;
563 register unsigned char *val;
564 size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
566 val = (unsigned char *) malloc (size + overhead);
567 if (val && check_depth == 1)
569 memcpy (val, xmalloc_overrun_check_header,
570 XMALLOC_OVERRUN_CHECK_SIZE - 4);
571 val += XMALLOC_OVERRUN_CHECK_SIZE;
572 XMALLOC_PUT_SIZE(val, size);
573 memcpy (val + size, xmalloc_overrun_check_trailer,
574 XMALLOC_OVERRUN_CHECK_SIZE);
576 --check_depth;
577 return (POINTER_TYPE *)val;
581 /* Like realloc, but checks old block for overrun, and wraps new block
582 with header and trailer. */
584 POINTER_TYPE *
585 overrun_check_realloc (block, size)
586 POINTER_TYPE *block;
587 size_t size;
589 register unsigned char *val = (unsigned char *)block;
590 size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
592 if (val
593 && check_depth == 1
594 && memcmp (xmalloc_overrun_check_header,
595 val - XMALLOC_OVERRUN_CHECK_SIZE,
596 XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
598 size_t osize = XMALLOC_GET_SIZE (val);
599 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
600 XMALLOC_OVERRUN_CHECK_SIZE))
601 abort ();
602 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
603 val -= XMALLOC_OVERRUN_CHECK_SIZE;
604 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE);
607 val = (unsigned char *) realloc ((POINTER_TYPE *)val, size + overhead);
609 if (val && check_depth == 1)
611 memcpy (val, xmalloc_overrun_check_header,
612 XMALLOC_OVERRUN_CHECK_SIZE - 4);
613 val += XMALLOC_OVERRUN_CHECK_SIZE;
614 XMALLOC_PUT_SIZE(val, size);
615 memcpy (val + size, xmalloc_overrun_check_trailer,
616 XMALLOC_OVERRUN_CHECK_SIZE);
618 --check_depth;
619 return (POINTER_TYPE *)val;
622 /* Like free, but checks block for overrun. */
624 void
625 overrun_check_free (block)
626 POINTER_TYPE *block;
628 unsigned char *val = (unsigned char *)block;
630 ++check_depth;
631 if (val
632 && check_depth == 1
633 && memcmp (xmalloc_overrun_check_header,
634 val - XMALLOC_OVERRUN_CHECK_SIZE,
635 XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
637 size_t osize = XMALLOC_GET_SIZE (val);
638 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
639 XMALLOC_OVERRUN_CHECK_SIZE))
640 abort ();
641 #ifdef XMALLOC_CLEAR_FREE_MEMORY
642 val -= XMALLOC_OVERRUN_CHECK_SIZE;
643 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_SIZE*2);
644 #else
645 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
646 val -= XMALLOC_OVERRUN_CHECK_SIZE;
647 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE);
648 #endif
651 free (val);
652 --check_depth;
655 #undef malloc
656 #undef realloc
657 #undef free
658 #define malloc overrun_check_malloc
659 #define realloc overrun_check_realloc
660 #define free overrun_check_free
661 #endif
663 #ifdef SYNC_INPUT
664 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
665 there's no need to block input around malloc. */
666 #define MALLOC_BLOCK_INPUT ((void)0)
667 #define MALLOC_UNBLOCK_INPUT ((void)0)
668 #else
669 #define MALLOC_BLOCK_INPUT BLOCK_INPUT
670 #define MALLOC_UNBLOCK_INPUT UNBLOCK_INPUT
671 #endif
673 /* Like malloc but check for no memory and block interrupt input.. */
675 POINTER_TYPE *
676 xmalloc (size_t size)
678 register POINTER_TYPE *val;
680 MALLOC_BLOCK_INPUT;
681 val = (POINTER_TYPE *) malloc (size);
682 MALLOC_UNBLOCK_INPUT;
684 if (!val && size)
685 memory_full ();
686 return val;
690 /* Like realloc but check for no memory and block interrupt input.. */
692 POINTER_TYPE *
693 xrealloc (POINTER_TYPE *block, size_t size)
695 register POINTER_TYPE *val;
697 MALLOC_BLOCK_INPUT;
698 /* We must call malloc explicitly when BLOCK is 0, since some
699 reallocs don't do this. */
700 if (! block)
701 val = (POINTER_TYPE *) malloc (size);
702 else
703 val = (POINTER_TYPE *) realloc (block, size);
704 MALLOC_UNBLOCK_INPUT;
706 if (!val && size) memory_full ();
707 return val;
711 /* Like free but block interrupt input. */
713 void
714 xfree (POINTER_TYPE *block)
716 if (!block)
717 return;
718 MALLOC_BLOCK_INPUT;
719 free (block);
720 MALLOC_UNBLOCK_INPUT;
721 /* We don't call refill_memory_reserve here
722 because that duplicates doing so in emacs_blocked_free
723 and the criterion should go there. */
727 /* Like strdup, but uses xmalloc. */
729 char *
730 xstrdup (const char *s)
732 size_t len = strlen (s) + 1;
733 char *p = (char *) xmalloc (len);
734 memcpy (p, s, len);
735 return p;
739 /* Unwind for SAFE_ALLOCA */
741 Lisp_Object
742 safe_alloca_unwind (Lisp_Object arg)
744 register struct Lisp_Save_Value *p = XSAVE_VALUE (arg);
746 p->dogc = 0;
747 xfree (p->pointer);
748 p->pointer = 0;
749 free_misc (arg);
750 return Qnil;
754 /* Like malloc but used for allocating Lisp data. NBYTES is the
755 number of bytes to allocate, TYPE describes the intended use of the
756 allcated memory block (for strings, for conses, ...). */
758 #ifndef USE_LSB_TAG
759 static void *lisp_malloc_loser;
760 #endif
762 static POINTER_TYPE *
763 lisp_malloc (size_t nbytes, enum mem_type type)
765 register void *val;
767 MALLOC_BLOCK_INPUT;
769 #ifdef GC_MALLOC_CHECK
770 allocated_mem_type = type;
771 #endif
773 val = (void *) malloc (nbytes);
775 #ifndef USE_LSB_TAG
776 /* If the memory just allocated cannot be addressed thru a Lisp
777 object's pointer, and it needs to be,
778 that's equivalent to running out of memory. */
779 if (val && type != MEM_TYPE_NON_LISP)
781 Lisp_Object tem;
782 XSETCONS (tem, (char *) val + nbytes - 1);
783 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
785 lisp_malloc_loser = val;
786 free (val);
787 val = 0;
790 #endif
792 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
793 if (val && type != MEM_TYPE_NON_LISP)
794 mem_insert (val, (char *) val + nbytes, type);
795 #endif
797 MALLOC_UNBLOCK_INPUT;
798 if (!val && nbytes)
799 memory_full ();
800 return val;
803 /* Free BLOCK. This must be called to free memory allocated with a
804 call to lisp_malloc. */
806 static void
807 lisp_free (POINTER_TYPE *block)
809 MALLOC_BLOCK_INPUT;
810 free (block);
811 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
812 mem_delete (mem_find (block));
813 #endif
814 MALLOC_UNBLOCK_INPUT;
817 /* Allocation of aligned blocks of memory to store Lisp data. */
818 /* The entry point is lisp_align_malloc which returns blocks of at most */
819 /* BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
821 /* Use posix_memalloc if the system has it and we're using the system's
822 malloc (because our gmalloc.c routines don't have posix_memalign although
823 its memalloc could be used). */
824 #if defined (HAVE_POSIX_MEMALIGN) && defined (SYSTEM_MALLOC)
825 #define USE_POSIX_MEMALIGN 1
826 #endif
828 /* BLOCK_ALIGN has to be a power of 2. */
829 #define BLOCK_ALIGN (1 << 10)
831 /* Padding to leave at the end of a malloc'd block. This is to give
832 malloc a chance to minimize the amount of memory wasted to alignment.
833 It should be tuned to the particular malloc library used.
834 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
835 posix_memalign on the other hand would ideally prefer a value of 4
836 because otherwise, there's 1020 bytes wasted between each ablocks.
837 In Emacs, testing shows that those 1020 can most of the time be
838 efficiently used by malloc to place other objects, so a value of 0 can
839 still preferable unless you have a lot of aligned blocks and virtually
840 nothing else. */
841 #define BLOCK_PADDING 0
842 #define BLOCK_BYTES \
843 (BLOCK_ALIGN - sizeof (struct ablock *) - BLOCK_PADDING)
845 /* Internal data structures and constants. */
847 #define ABLOCKS_SIZE 16
849 /* An aligned block of memory. */
850 struct ablock
852 union
854 char payload[BLOCK_BYTES];
855 struct ablock *next_free;
856 } x;
857 /* `abase' is the aligned base of the ablocks. */
858 /* It is overloaded to hold the virtual `busy' field that counts
859 the number of used ablock in the parent ablocks.
860 The first ablock has the `busy' field, the others have the `abase'
861 field. To tell the difference, we assume that pointers will have
862 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
863 is used to tell whether the real base of the parent ablocks is `abase'
864 (if not, the word before the first ablock holds a pointer to the
865 real base). */
866 struct ablocks *abase;
867 /* The padding of all but the last ablock is unused. The padding of
868 the last ablock in an ablocks is not allocated. */
869 #if BLOCK_PADDING
870 char padding[BLOCK_PADDING];
871 #endif
874 /* A bunch of consecutive aligned blocks. */
875 struct ablocks
877 struct ablock blocks[ABLOCKS_SIZE];
880 /* Size of the block requested from malloc or memalign. */
881 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
883 #define ABLOCK_ABASE(block) \
884 (((unsigned long) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
885 ? (struct ablocks *)(block) \
886 : (block)->abase)
888 /* Virtual `busy' field. */
889 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
891 /* Pointer to the (not necessarily aligned) malloc block. */
892 #ifdef USE_POSIX_MEMALIGN
893 #define ABLOCKS_BASE(abase) (abase)
894 #else
895 #define ABLOCKS_BASE(abase) \
896 (1 & (long) ABLOCKS_BUSY (abase) ? abase : ((void**)abase)[-1])
897 #endif
899 /* The list of free ablock. */
900 static struct ablock *free_ablock;
902 /* Allocate an aligned block of nbytes.
903 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
904 smaller or equal to BLOCK_BYTES. */
905 static POINTER_TYPE *
906 lisp_align_malloc (size_t nbytes, enum mem_type type)
908 void *base, *val;
909 struct ablocks *abase;
911 eassert (nbytes <= BLOCK_BYTES);
913 MALLOC_BLOCK_INPUT;
915 #ifdef GC_MALLOC_CHECK
916 allocated_mem_type = type;
917 #endif
919 if (!free_ablock)
921 int i;
922 EMACS_INT aligned; /* int gets warning casting to 64-bit pointer. */
924 #ifdef DOUG_LEA_MALLOC
925 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
926 because mapped region contents are not preserved in
927 a dumped Emacs. */
928 mallopt (M_MMAP_MAX, 0);
929 #endif
931 #ifdef USE_POSIX_MEMALIGN
933 int err = posix_memalign (&base, BLOCK_ALIGN, ABLOCKS_BYTES);
934 if (err)
935 base = NULL;
936 abase = base;
938 #else
939 base = malloc (ABLOCKS_BYTES);
940 abase = ALIGN (base, BLOCK_ALIGN);
941 #endif
943 if (base == 0)
945 MALLOC_UNBLOCK_INPUT;
946 memory_full ();
949 aligned = (base == abase);
950 if (!aligned)
951 ((void**)abase)[-1] = base;
953 #ifdef DOUG_LEA_MALLOC
954 /* Back to a reasonable maximum of mmap'ed areas. */
955 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
956 #endif
958 #ifndef USE_LSB_TAG
959 /* If the memory just allocated cannot be addressed thru a Lisp
960 object's pointer, and it needs to be, that's equivalent to
961 running out of memory. */
962 if (type != MEM_TYPE_NON_LISP)
964 Lisp_Object tem;
965 char *end = (char *) base + ABLOCKS_BYTES - 1;
966 XSETCONS (tem, end);
967 if ((char *) XCONS (tem) != end)
969 lisp_malloc_loser = base;
970 free (base);
971 MALLOC_UNBLOCK_INPUT;
972 memory_full ();
975 #endif
977 /* Initialize the blocks and put them on the free list.
978 Is `base' was not properly aligned, we can't use the last block. */
979 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
981 abase->blocks[i].abase = abase;
982 abase->blocks[i].x.next_free = free_ablock;
983 free_ablock = &abase->blocks[i];
985 ABLOCKS_BUSY (abase) = (struct ablocks *) (long) aligned;
987 eassert (0 == ((EMACS_UINT)abase) % BLOCK_ALIGN);
988 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
989 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
990 eassert (ABLOCKS_BASE (abase) == base);
991 eassert (aligned == (long) ABLOCKS_BUSY (abase));
994 abase = ABLOCK_ABASE (free_ablock);
995 ABLOCKS_BUSY (abase) = (struct ablocks *) (2 + (long) ABLOCKS_BUSY (abase));
996 val = free_ablock;
997 free_ablock = free_ablock->x.next_free;
999 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1000 if (val && type != MEM_TYPE_NON_LISP)
1001 mem_insert (val, (char *) val + nbytes, type);
1002 #endif
1004 MALLOC_UNBLOCK_INPUT;
1005 if (!val && nbytes)
1006 memory_full ();
1008 eassert (0 == ((EMACS_UINT)val) % BLOCK_ALIGN);
1009 return val;
1012 static void
1013 lisp_align_free (POINTER_TYPE *block)
1015 struct ablock *ablock = block;
1016 struct ablocks *abase = ABLOCK_ABASE (ablock);
1018 MALLOC_BLOCK_INPUT;
1019 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1020 mem_delete (mem_find (block));
1021 #endif
1022 /* Put on free list. */
1023 ablock->x.next_free = free_ablock;
1024 free_ablock = ablock;
1025 /* Update busy count. */
1026 ABLOCKS_BUSY (abase) = (struct ablocks *) (-2 + (long) ABLOCKS_BUSY (abase));
1028 if (2 > (long) ABLOCKS_BUSY (abase))
1029 { /* All the blocks are free. */
1030 int i = 0, aligned = (long) ABLOCKS_BUSY (abase);
1031 struct ablock **tem = &free_ablock;
1032 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1034 while (*tem)
1036 if (*tem >= (struct ablock *) abase && *tem < atop)
1038 i++;
1039 *tem = (*tem)->x.next_free;
1041 else
1042 tem = &(*tem)->x.next_free;
1044 eassert ((aligned & 1) == aligned);
1045 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1046 #ifdef USE_POSIX_MEMALIGN
1047 eassert ((unsigned long)ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1048 #endif
1049 free (ABLOCKS_BASE (abase));
1051 MALLOC_UNBLOCK_INPUT;
1054 /* Return a new buffer structure allocated from the heap with
1055 a call to lisp_malloc. */
1057 struct buffer *
1058 allocate_buffer (void)
1060 struct buffer *b
1061 = (struct buffer *) lisp_malloc (sizeof (struct buffer),
1062 MEM_TYPE_BUFFER);
1063 b->size = sizeof (struct buffer) / sizeof (EMACS_INT);
1064 XSETPVECTYPE (b, PVEC_BUFFER);
1065 return b;
1069 #ifndef SYSTEM_MALLOC
1071 /* Arranging to disable input signals while we're in malloc.
1073 This only works with GNU malloc. To help out systems which can't
1074 use GNU malloc, all the calls to malloc, realloc, and free
1075 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
1076 pair; unfortunately, we have no idea what C library functions
1077 might call malloc, so we can't really protect them unless you're
1078 using GNU malloc. Fortunately, most of the major operating systems
1079 can use GNU malloc. */
1081 #ifndef SYNC_INPUT
1082 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
1083 there's no need to block input around malloc. */
1085 #ifndef DOUG_LEA_MALLOC
1086 extern void * (*__malloc_hook) (size_t, const void *);
1087 extern void * (*__realloc_hook) (void *, size_t, const void *);
1088 extern void (*__free_hook) (void *, const void *);
1089 /* Else declared in malloc.h, perhaps with an extra arg. */
1090 #endif /* DOUG_LEA_MALLOC */
1091 static void * (*old_malloc_hook) (size_t, const void *);
1092 static void * (*old_realloc_hook) (void *, size_t, const void*);
1093 static void (*old_free_hook) (void*, const void*);
1095 static __malloc_size_t bytes_used_when_reconsidered;
1097 /* This function is used as the hook for free to call. */
1099 static void
1100 emacs_blocked_free (void *ptr, const void *ptr2)
1102 BLOCK_INPUT_ALLOC;
1104 #ifdef GC_MALLOC_CHECK
1105 if (ptr)
1107 struct mem_node *m;
1109 m = mem_find (ptr);
1110 if (m == MEM_NIL || m->start != ptr)
1112 fprintf (stderr,
1113 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
1114 abort ();
1116 else
1118 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
1119 mem_delete (m);
1122 #endif /* GC_MALLOC_CHECK */
1124 __free_hook = old_free_hook;
1125 free (ptr);
1127 /* If we released our reserve (due to running out of memory),
1128 and we have a fair amount free once again,
1129 try to set aside another reserve in case we run out once more. */
1130 if (! NILP (Vmemory_full)
1131 /* Verify there is enough space that even with the malloc
1132 hysteresis this call won't run out again.
1133 The code here is correct as long as SPARE_MEMORY
1134 is substantially larger than the block size malloc uses. */
1135 && (bytes_used_when_full
1136 > ((bytes_used_when_reconsidered = BYTES_USED)
1137 + max (malloc_hysteresis, 4) * SPARE_MEMORY)))
1138 refill_memory_reserve ();
1140 __free_hook = emacs_blocked_free;
1141 UNBLOCK_INPUT_ALLOC;
1145 /* This function is the malloc hook that Emacs uses. */
1147 static void *
1148 emacs_blocked_malloc (size_t size, const void *ptr)
1150 void *value;
1152 BLOCK_INPUT_ALLOC;
1153 __malloc_hook = old_malloc_hook;
1154 #ifdef DOUG_LEA_MALLOC
1155 /* Segfaults on my system. --lorentey */
1156 /* mallopt (M_TOP_PAD, malloc_hysteresis * 4096); */
1157 #else
1158 __malloc_extra_blocks = malloc_hysteresis;
1159 #endif
1161 value = (void *) malloc (size);
1163 #ifdef GC_MALLOC_CHECK
1165 struct mem_node *m = mem_find (value);
1166 if (m != MEM_NIL)
1168 fprintf (stderr, "Malloc returned %p which is already in use\n",
1169 value);
1170 fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
1171 m->start, m->end, (char *) m->end - (char *) m->start,
1172 m->type);
1173 abort ();
1176 if (!dont_register_blocks)
1178 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
1179 allocated_mem_type = MEM_TYPE_NON_LISP;
1182 #endif /* GC_MALLOC_CHECK */
1184 __malloc_hook = emacs_blocked_malloc;
1185 UNBLOCK_INPUT_ALLOC;
1187 /* fprintf (stderr, "%p malloc\n", value); */
1188 return value;
1192 /* This function is the realloc hook that Emacs uses. */
1194 static void *
1195 emacs_blocked_realloc (void *ptr, size_t size, const void *ptr2)
1197 void *value;
1199 BLOCK_INPUT_ALLOC;
1200 __realloc_hook = old_realloc_hook;
1202 #ifdef GC_MALLOC_CHECK
1203 if (ptr)
1205 struct mem_node *m = mem_find (ptr);
1206 if (m == MEM_NIL || m->start != ptr)
1208 fprintf (stderr,
1209 "Realloc of %p which wasn't allocated with malloc\n",
1210 ptr);
1211 abort ();
1214 mem_delete (m);
1217 /* fprintf (stderr, "%p -> realloc\n", ptr); */
1219 /* Prevent malloc from registering blocks. */
1220 dont_register_blocks = 1;
1221 #endif /* GC_MALLOC_CHECK */
1223 value = (void *) realloc (ptr, size);
1225 #ifdef GC_MALLOC_CHECK
1226 dont_register_blocks = 0;
1229 struct mem_node *m = mem_find (value);
1230 if (m != MEM_NIL)
1232 fprintf (stderr, "Realloc returns memory that is already in use\n");
1233 abort ();
1236 /* Can't handle zero size regions in the red-black tree. */
1237 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
1240 /* fprintf (stderr, "%p <- realloc\n", value); */
1241 #endif /* GC_MALLOC_CHECK */
1243 __realloc_hook = emacs_blocked_realloc;
1244 UNBLOCK_INPUT_ALLOC;
1246 return value;
1250 #ifdef HAVE_GTK_AND_PTHREAD
1251 /* Called from Fdump_emacs so that when the dumped Emacs starts, it has a
1252 normal malloc. Some thread implementations need this as they call
1253 malloc before main. The pthread_self call in BLOCK_INPUT_ALLOC then
1254 calls malloc because it is the first call, and we have an endless loop. */
1256 void
1257 reset_malloc_hooks ()
1259 __free_hook = old_free_hook;
1260 __malloc_hook = old_malloc_hook;
1261 __realloc_hook = old_realloc_hook;
1263 #endif /* HAVE_GTK_AND_PTHREAD */
1266 /* Called from main to set up malloc to use our hooks. */
1268 void
1269 uninterrupt_malloc (void)
1271 #ifdef HAVE_GTK_AND_PTHREAD
1272 #ifdef DOUG_LEA_MALLOC
1273 pthread_mutexattr_t attr;
1275 /* GLIBC has a faster way to do this, but lets keep it portable.
1276 This is according to the Single UNIX Specification. */
1277 pthread_mutexattr_init (&attr);
1278 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1279 pthread_mutex_init (&alloc_mutex, &attr);
1280 #else /* !DOUG_LEA_MALLOC */
1281 /* Some systems such as Solaris 2.6 don't have a recursive mutex,
1282 and the bundled gmalloc.c doesn't require it. */
1283 pthread_mutex_init (&alloc_mutex, NULL);
1284 #endif /* !DOUG_LEA_MALLOC */
1285 #endif /* HAVE_GTK_AND_PTHREAD */
1287 if (__free_hook != emacs_blocked_free)
1288 old_free_hook = __free_hook;
1289 __free_hook = emacs_blocked_free;
1291 if (__malloc_hook != emacs_blocked_malloc)
1292 old_malloc_hook = __malloc_hook;
1293 __malloc_hook = emacs_blocked_malloc;
1295 if (__realloc_hook != emacs_blocked_realloc)
1296 old_realloc_hook = __realloc_hook;
1297 __realloc_hook = emacs_blocked_realloc;
1300 #endif /* not SYNC_INPUT */
1301 #endif /* not SYSTEM_MALLOC */
1305 /***********************************************************************
1306 Interval Allocation
1307 ***********************************************************************/
1309 /* Number of intervals allocated in an interval_block structure.
1310 The 1020 is 1024 minus malloc overhead. */
1312 #define INTERVAL_BLOCK_SIZE \
1313 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1315 /* Intervals are allocated in chunks in form of an interval_block
1316 structure. */
1318 struct interval_block
1320 /* Place `intervals' first, to preserve alignment. */
1321 struct interval intervals[INTERVAL_BLOCK_SIZE];
1322 struct interval_block *next;
1325 /* Current interval block. Its `next' pointer points to older
1326 blocks. */
1328 static struct interval_block *interval_block;
1330 /* Index in interval_block above of the next unused interval
1331 structure. */
1333 static int interval_block_index;
1335 /* Number of free and live intervals. */
1337 static int total_free_intervals, total_intervals;
1339 /* List of free intervals. */
1341 INTERVAL interval_free_list;
1343 /* Total number of interval blocks now in use. */
1345 static int n_interval_blocks;
1348 /* Initialize interval allocation. */
1350 static void
1351 init_intervals (void)
1353 interval_block = NULL;
1354 interval_block_index = INTERVAL_BLOCK_SIZE;
1355 interval_free_list = 0;
1356 n_interval_blocks = 0;
1360 /* Return a new interval. */
1362 INTERVAL
1363 make_interval (void)
1365 INTERVAL val;
1367 /* eassert (!handling_signal); */
1369 MALLOC_BLOCK_INPUT;
1371 if (interval_free_list)
1373 val = interval_free_list;
1374 interval_free_list = INTERVAL_PARENT (interval_free_list);
1376 else
1378 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1380 register struct interval_block *newi;
1382 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
1383 MEM_TYPE_NON_LISP);
1385 newi->next = interval_block;
1386 interval_block = newi;
1387 interval_block_index = 0;
1388 n_interval_blocks++;
1390 val = &interval_block->intervals[interval_block_index++];
1393 MALLOC_UNBLOCK_INPUT;
1395 consing_since_gc += sizeof (struct interval);
1396 intervals_consed++;
1397 RESET_INTERVAL (val);
1398 val->gcmarkbit = 0;
1399 return val;
1403 /* Mark Lisp objects in interval I. */
1405 static void
1406 mark_interval (register INTERVAL i, Lisp_Object dummy)
1408 eassert (!i->gcmarkbit); /* Intervals are never shared. */
1409 i->gcmarkbit = 1;
1410 mark_object (i->plist);
1414 /* Mark the interval tree rooted in TREE. Don't call this directly;
1415 use the macro MARK_INTERVAL_TREE instead. */
1417 static void
1418 mark_interval_tree (register INTERVAL tree)
1420 /* No need to test if this tree has been marked already; this
1421 function is always called through the MARK_INTERVAL_TREE macro,
1422 which takes care of that. */
1424 traverse_intervals_noorder (tree, mark_interval, Qnil);
1428 /* Mark the interval tree rooted in I. */
1430 #define MARK_INTERVAL_TREE(i) \
1431 do { \
1432 if (!NULL_INTERVAL_P (i) && !i->gcmarkbit) \
1433 mark_interval_tree (i); \
1434 } while (0)
1437 #define UNMARK_BALANCE_INTERVALS(i) \
1438 do { \
1439 if (! NULL_INTERVAL_P (i)) \
1440 (i) = balance_intervals (i); \
1441 } while (0)
1444 /* Number support. If USE_LISP_UNION_TYPE is in effect, we
1445 can't create number objects in macros. */
1446 #ifndef make_number
1447 Lisp_Object
1448 make_number (EMACS_INT n)
1450 Lisp_Object obj;
1451 obj.s.val = n;
1452 obj.s.type = Lisp_Int;
1453 return obj;
1455 #endif
1457 /***********************************************************************
1458 String Allocation
1459 ***********************************************************************/
1461 /* Lisp_Strings are allocated in string_block structures. When a new
1462 string_block is allocated, all the Lisp_Strings it contains are
1463 added to a free-list string_free_list. When a new Lisp_String is
1464 needed, it is taken from that list. During the sweep phase of GC,
1465 string_blocks that are entirely free are freed, except two which
1466 we keep.
1468 String data is allocated from sblock structures. Strings larger
1469 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1470 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1472 Sblocks consist internally of sdata structures, one for each
1473 Lisp_String. The sdata structure points to the Lisp_String it
1474 belongs to. The Lisp_String points back to the `u.data' member of
1475 its sdata structure.
1477 When a Lisp_String is freed during GC, it is put back on
1478 string_free_list, and its `data' member and its sdata's `string'
1479 pointer is set to null. The size of the string is recorded in the
1480 `u.nbytes' member of the sdata. So, sdata structures that are no
1481 longer used, can be easily recognized, and it's easy to compact the
1482 sblocks of small strings which we do in compact_small_strings. */
1484 /* Size in bytes of an sblock structure used for small strings. This
1485 is 8192 minus malloc overhead. */
1487 #define SBLOCK_SIZE 8188
1489 /* Strings larger than this are considered large strings. String data
1490 for large strings is allocated from individual sblocks. */
1492 #define LARGE_STRING_BYTES 1024
1494 /* Structure describing string memory sub-allocated from an sblock.
1495 This is where the contents of Lisp strings are stored. */
1497 struct sdata
1499 /* Back-pointer to the string this sdata belongs to. If null, this
1500 structure is free, and the NBYTES member of the union below
1501 contains the string's byte size (the same value that STRING_BYTES
1502 would return if STRING were non-null). If non-null, STRING_BYTES
1503 (STRING) is the size of the data, and DATA contains the string's
1504 contents. */
1505 struct Lisp_String *string;
1507 #ifdef GC_CHECK_STRING_BYTES
1509 EMACS_INT nbytes;
1510 unsigned char data[1];
1512 #define SDATA_NBYTES(S) (S)->nbytes
1513 #define SDATA_DATA(S) (S)->data
1515 #else /* not GC_CHECK_STRING_BYTES */
1517 union
1519 /* When STRING in non-null. */
1520 unsigned char data[1];
1522 /* When STRING is null. */
1523 EMACS_INT nbytes;
1524 } u;
1527 #define SDATA_NBYTES(S) (S)->u.nbytes
1528 #define SDATA_DATA(S) (S)->u.data
1530 #endif /* not GC_CHECK_STRING_BYTES */
1534 /* Structure describing a block of memory which is sub-allocated to
1535 obtain string data memory for strings. Blocks for small strings
1536 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1537 as large as needed. */
1539 struct sblock
1541 /* Next in list. */
1542 struct sblock *next;
1544 /* Pointer to the next free sdata block. This points past the end
1545 of the sblock if there isn't any space left in this block. */
1546 struct sdata *next_free;
1548 /* Start of data. */
1549 struct sdata first_data;
1552 /* Number of Lisp strings in a string_block structure. The 1020 is
1553 1024 minus malloc overhead. */
1555 #define STRING_BLOCK_SIZE \
1556 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1558 /* Structure describing a block from which Lisp_String structures
1559 are allocated. */
1561 struct string_block
1563 /* Place `strings' first, to preserve alignment. */
1564 struct Lisp_String strings[STRING_BLOCK_SIZE];
1565 struct string_block *next;
1568 /* Head and tail of the list of sblock structures holding Lisp string
1569 data. We always allocate from current_sblock. The NEXT pointers
1570 in the sblock structures go from oldest_sblock to current_sblock. */
1572 static struct sblock *oldest_sblock, *current_sblock;
1574 /* List of sblocks for large strings. */
1576 static struct sblock *large_sblocks;
1578 /* List of string_block structures, and how many there are. */
1580 static struct string_block *string_blocks;
1581 static int n_string_blocks;
1583 /* Free-list of Lisp_Strings. */
1585 static struct Lisp_String *string_free_list;
1587 /* Number of live and free Lisp_Strings. */
1589 static int total_strings, total_free_strings;
1591 /* Number of bytes used by live strings. */
1593 static EMACS_INT total_string_size;
1595 /* Given a pointer to a Lisp_String S which is on the free-list
1596 string_free_list, return a pointer to its successor in the
1597 free-list. */
1599 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1601 /* Return a pointer to the sdata structure belonging to Lisp string S.
1602 S must be live, i.e. S->data must not be null. S->data is actually
1603 a pointer to the `u.data' member of its sdata structure; the
1604 structure starts at a constant offset in front of that. */
1606 #ifdef GC_CHECK_STRING_BYTES
1608 #define SDATA_OF_STRING(S) \
1609 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *) \
1610 - sizeof (EMACS_INT)))
1612 #else /* not GC_CHECK_STRING_BYTES */
1614 #define SDATA_OF_STRING(S) \
1615 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))
1617 #endif /* not GC_CHECK_STRING_BYTES */
1620 #ifdef GC_CHECK_STRING_OVERRUN
1622 /* We check for overrun in string data blocks by appending a small
1623 "cookie" after each allocated string data block, and check for the
1624 presence of this cookie during GC. */
1626 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1627 static char string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1628 { 0xde, 0xad, 0xbe, 0xef };
1630 #else
1631 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1632 #endif
1634 /* Value is the size of an sdata structure large enough to hold NBYTES
1635 bytes of string data. The value returned includes a terminating
1636 NUL byte, the size of the sdata structure, and padding. */
1638 #ifdef GC_CHECK_STRING_BYTES
1640 #define SDATA_SIZE(NBYTES) \
1641 ((sizeof (struct Lisp_String *) \
1642 + (NBYTES) + 1 \
1643 + sizeof (EMACS_INT) \
1644 + sizeof (EMACS_INT) - 1) \
1645 & ~(sizeof (EMACS_INT) - 1))
1647 #else /* not GC_CHECK_STRING_BYTES */
1649 #define SDATA_SIZE(NBYTES) \
1650 ((sizeof (struct Lisp_String *) \
1651 + (NBYTES) + 1 \
1652 + sizeof (EMACS_INT) - 1) \
1653 & ~(sizeof (EMACS_INT) - 1))
1655 #endif /* not GC_CHECK_STRING_BYTES */
1657 /* Extra bytes to allocate for each string. */
1659 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1661 /* Initialize string allocation. Called from init_alloc_once. */
1663 static void
1664 init_strings (void)
1666 total_strings = total_free_strings = total_string_size = 0;
1667 oldest_sblock = current_sblock = large_sblocks = NULL;
1668 string_blocks = NULL;
1669 n_string_blocks = 0;
1670 string_free_list = NULL;
1671 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1672 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1676 #ifdef GC_CHECK_STRING_BYTES
1678 static int check_string_bytes_count;
1680 static void check_string_bytes (int);
1681 static void check_sblock (struct sblock *);
1683 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1686 /* Like GC_STRING_BYTES, but with debugging check. */
1688 EMACS_INT
1689 string_bytes (struct Lisp_String *s)
1691 EMACS_INT nbytes =
1692 (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1694 if (!PURE_POINTER_P (s)
1695 && s->data
1696 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1697 abort ();
1698 return nbytes;
1701 /* Check validity of Lisp strings' string_bytes member in B. */
1703 static void
1704 check_sblock (b)
1705 struct sblock *b;
1707 struct sdata *from, *end, *from_end;
1709 end = b->next_free;
1711 for (from = &b->first_data; from < end; from = from_end)
1713 /* Compute the next FROM here because copying below may
1714 overwrite data we need to compute it. */
1715 EMACS_INT nbytes;
1717 /* Check that the string size recorded in the string is the
1718 same as the one recorded in the sdata structure. */
1719 if (from->string)
1720 CHECK_STRING_BYTES (from->string);
1722 if (from->string)
1723 nbytes = GC_STRING_BYTES (from->string);
1724 else
1725 nbytes = SDATA_NBYTES (from);
1727 nbytes = SDATA_SIZE (nbytes);
1728 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1733 /* Check validity of Lisp strings' string_bytes member. ALL_P
1734 non-zero means check all strings, otherwise check only most
1735 recently allocated strings. Used for hunting a bug. */
1737 static void
1738 check_string_bytes (all_p)
1739 int all_p;
1741 if (all_p)
1743 struct sblock *b;
1745 for (b = large_sblocks; b; b = b->next)
1747 struct Lisp_String *s = b->first_data.string;
1748 if (s)
1749 CHECK_STRING_BYTES (s);
1752 for (b = oldest_sblock; b; b = b->next)
1753 check_sblock (b);
1755 else
1756 check_sblock (current_sblock);
1759 #endif /* GC_CHECK_STRING_BYTES */
1761 #ifdef GC_CHECK_STRING_FREE_LIST
1763 /* Walk through the string free list looking for bogus next pointers.
1764 This may catch buffer overrun from a previous string. */
1766 static void
1767 check_string_free_list ()
1769 struct Lisp_String *s;
1771 /* Pop a Lisp_String off the free-list. */
1772 s = string_free_list;
1773 while (s != NULL)
1775 if ((unsigned long)s < 1024)
1776 abort();
1777 s = NEXT_FREE_LISP_STRING (s);
1780 #else
1781 #define check_string_free_list()
1782 #endif
1784 /* Return a new Lisp_String. */
1786 static struct Lisp_String *
1787 allocate_string (void)
1789 struct Lisp_String *s;
1791 /* eassert (!handling_signal); */
1793 MALLOC_BLOCK_INPUT;
1795 /* If the free-list is empty, allocate a new string_block, and
1796 add all the Lisp_Strings in it to the free-list. */
1797 if (string_free_list == NULL)
1799 struct string_block *b;
1800 int i;
1802 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1803 memset (b, 0, sizeof *b);
1804 b->next = string_blocks;
1805 string_blocks = b;
1806 ++n_string_blocks;
1808 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1810 s = b->strings + i;
1811 NEXT_FREE_LISP_STRING (s) = string_free_list;
1812 string_free_list = s;
1815 total_free_strings += STRING_BLOCK_SIZE;
1818 check_string_free_list ();
1820 /* Pop a Lisp_String off the free-list. */
1821 s = string_free_list;
1822 string_free_list = NEXT_FREE_LISP_STRING (s);
1824 MALLOC_UNBLOCK_INPUT;
1826 /* Probably not strictly necessary, but play it safe. */
1827 memset (s, 0, sizeof *s);
1829 --total_free_strings;
1830 ++total_strings;
1831 ++strings_consed;
1832 consing_since_gc += sizeof *s;
1834 #ifdef GC_CHECK_STRING_BYTES
1835 if (!noninteractive)
1837 if (++check_string_bytes_count == 200)
1839 check_string_bytes_count = 0;
1840 check_string_bytes (1);
1842 else
1843 check_string_bytes (0);
1845 #endif /* GC_CHECK_STRING_BYTES */
1847 return s;
1851 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1852 plus a NUL byte at the end. Allocate an sdata structure for S, and
1853 set S->data to its `u.data' member. Store a NUL byte at the end of
1854 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1855 S->data if it was initially non-null. */
1857 void
1858 allocate_string_data (struct Lisp_String *s,
1859 EMACS_INT nchars, EMACS_INT nbytes)
1861 struct sdata *data, *old_data;
1862 struct sblock *b;
1863 EMACS_INT needed, old_nbytes;
1865 /* Determine the number of bytes needed to store NBYTES bytes
1866 of string data. */
1867 needed = SDATA_SIZE (nbytes);
1868 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1869 old_nbytes = GC_STRING_BYTES (s);
1871 MALLOC_BLOCK_INPUT;
1873 if (nbytes > LARGE_STRING_BYTES)
1875 size_t size = sizeof *b - sizeof (struct sdata) + needed;
1877 #ifdef DOUG_LEA_MALLOC
1878 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1879 because mapped region contents are not preserved in
1880 a dumped Emacs.
1882 In case you think of allowing it in a dumped Emacs at the
1883 cost of not being able to re-dump, there's another reason:
1884 mmap'ed data typically have an address towards the top of the
1885 address space, which won't fit into an EMACS_INT (at least on
1886 32-bit systems with the current tagging scheme). --fx */
1887 mallopt (M_MMAP_MAX, 0);
1888 #endif
1890 b = (struct sblock *) lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
1892 #ifdef DOUG_LEA_MALLOC
1893 /* Back to a reasonable maximum of mmap'ed areas. */
1894 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1895 #endif
1897 b->next_free = &b->first_data;
1898 b->first_data.string = NULL;
1899 b->next = large_sblocks;
1900 large_sblocks = b;
1902 else if (current_sblock == NULL
1903 || (((char *) current_sblock + SBLOCK_SIZE
1904 - (char *) current_sblock->next_free)
1905 < (needed + GC_STRING_EXTRA)))
1907 /* Not enough room in the current sblock. */
1908 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1909 b->next_free = &b->first_data;
1910 b->first_data.string = NULL;
1911 b->next = NULL;
1913 if (current_sblock)
1914 current_sblock->next = b;
1915 else
1916 oldest_sblock = b;
1917 current_sblock = b;
1919 else
1920 b = current_sblock;
1922 data = b->next_free;
1923 b->next_free = (struct sdata *) ((char *) data + needed + GC_STRING_EXTRA);
1925 MALLOC_UNBLOCK_INPUT;
1927 data->string = s;
1928 s->data = SDATA_DATA (data);
1929 #ifdef GC_CHECK_STRING_BYTES
1930 SDATA_NBYTES (data) = nbytes;
1931 #endif
1932 s->size = nchars;
1933 s->size_byte = nbytes;
1934 s->data[nbytes] = '\0';
1935 #ifdef GC_CHECK_STRING_OVERRUN
1936 memcpy (data + needed, string_overrun_cookie, GC_STRING_OVERRUN_COOKIE_SIZE);
1937 #endif
1939 /* If S had already data assigned, mark that as free by setting its
1940 string back-pointer to null, and recording the size of the data
1941 in it. */
1942 if (old_data)
1944 SDATA_NBYTES (old_data) = old_nbytes;
1945 old_data->string = NULL;
1948 consing_since_gc += needed;
1952 /* Sweep and compact strings. */
1954 static void
1955 sweep_strings (void)
1957 struct string_block *b, *next;
1958 struct string_block *live_blocks = NULL;
1960 string_free_list = NULL;
1961 total_strings = total_free_strings = 0;
1962 total_string_size = 0;
1964 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1965 for (b = string_blocks; b; b = next)
1967 int i, nfree = 0;
1968 struct Lisp_String *free_list_before = string_free_list;
1970 next = b->next;
1972 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
1974 struct Lisp_String *s = b->strings + i;
1976 if (s->data)
1978 /* String was not on free-list before. */
1979 if (STRING_MARKED_P (s))
1981 /* String is live; unmark it and its intervals. */
1982 UNMARK_STRING (s);
1984 if (!NULL_INTERVAL_P (s->intervals))
1985 UNMARK_BALANCE_INTERVALS (s->intervals);
1987 ++total_strings;
1988 total_string_size += STRING_BYTES (s);
1990 else
1992 /* String is dead. Put it on the free-list. */
1993 struct sdata *data = SDATA_OF_STRING (s);
1995 /* Save the size of S in its sdata so that we know
1996 how large that is. Reset the sdata's string
1997 back-pointer so that we know it's free. */
1998 #ifdef GC_CHECK_STRING_BYTES
1999 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
2000 abort ();
2001 #else
2002 data->u.nbytes = GC_STRING_BYTES (s);
2003 #endif
2004 data->string = NULL;
2006 /* Reset the strings's `data' member so that we
2007 know it's free. */
2008 s->data = NULL;
2010 /* Put the string on the free-list. */
2011 NEXT_FREE_LISP_STRING (s) = string_free_list;
2012 string_free_list = s;
2013 ++nfree;
2016 else
2018 /* S was on the free-list before. Put it there again. */
2019 NEXT_FREE_LISP_STRING (s) = string_free_list;
2020 string_free_list = s;
2021 ++nfree;
2025 /* Free blocks that contain free Lisp_Strings only, except
2026 the first two of them. */
2027 if (nfree == STRING_BLOCK_SIZE
2028 && total_free_strings > STRING_BLOCK_SIZE)
2030 lisp_free (b);
2031 --n_string_blocks;
2032 string_free_list = free_list_before;
2034 else
2036 total_free_strings += nfree;
2037 b->next = live_blocks;
2038 live_blocks = b;
2042 check_string_free_list ();
2044 string_blocks = live_blocks;
2045 free_large_strings ();
2046 compact_small_strings ();
2048 check_string_free_list ();
2052 /* Free dead large strings. */
2054 static void
2055 free_large_strings (void)
2057 struct sblock *b, *next;
2058 struct sblock *live_blocks = NULL;
2060 for (b = large_sblocks; b; b = next)
2062 next = b->next;
2064 if (b->first_data.string == NULL)
2065 lisp_free (b);
2066 else
2068 b->next = live_blocks;
2069 live_blocks = b;
2073 large_sblocks = live_blocks;
2077 /* Compact data of small strings. Free sblocks that don't contain
2078 data of live strings after compaction. */
2080 static void
2081 compact_small_strings (void)
2083 struct sblock *b, *tb, *next;
2084 struct sdata *from, *to, *end, *tb_end;
2085 struct sdata *to_end, *from_end;
2087 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2088 to, and TB_END is the end of TB. */
2089 tb = oldest_sblock;
2090 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2091 to = &tb->first_data;
2093 /* Step through the blocks from the oldest to the youngest. We
2094 expect that old blocks will stabilize over time, so that less
2095 copying will happen this way. */
2096 for (b = oldest_sblock; b; b = b->next)
2098 end = b->next_free;
2099 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2101 for (from = &b->first_data; from < end; from = from_end)
2103 /* Compute the next FROM here because copying below may
2104 overwrite data we need to compute it. */
2105 EMACS_INT nbytes;
2107 #ifdef GC_CHECK_STRING_BYTES
2108 /* Check that the string size recorded in the string is the
2109 same as the one recorded in the sdata structure. */
2110 if (from->string
2111 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
2112 abort ();
2113 #endif /* GC_CHECK_STRING_BYTES */
2115 if (from->string)
2116 nbytes = GC_STRING_BYTES (from->string);
2117 else
2118 nbytes = SDATA_NBYTES (from);
2120 if (nbytes > LARGE_STRING_BYTES)
2121 abort ();
2123 nbytes = SDATA_SIZE (nbytes);
2124 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
2126 #ifdef GC_CHECK_STRING_OVERRUN
2127 if (memcmp (string_overrun_cookie,
2128 (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
2129 GC_STRING_OVERRUN_COOKIE_SIZE))
2130 abort ();
2131 #endif
2133 /* FROM->string non-null means it's alive. Copy its data. */
2134 if (from->string)
2136 /* If TB is full, proceed with the next sblock. */
2137 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2138 if (to_end > tb_end)
2140 tb->next_free = to;
2141 tb = tb->next;
2142 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2143 to = &tb->first_data;
2144 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2147 /* Copy, and update the string's `data' pointer. */
2148 if (from != to)
2150 xassert (tb != b || to <= from);
2151 memmove (to, from, nbytes + GC_STRING_EXTRA);
2152 to->string->data = SDATA_DATA (to);
2155 /* Advance past the sdata we copied to. */
2156 to = to_end;
2161 /* The rest of the sblocks following TB don't contain live data, so
2162 we can free them. */
2163 for (b = tb->next; b; b = next)
2165 next = b->next;
2166 lisp_free (b);
2169 tb->next_free = to;
2170 tb->next = NULL;
2171 current_sblock = tb;
2175 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2176 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2177 LENGTH must be an integer.
2178 INIT must be an integer that represents a character. */)
2179 (Lisp_Object length, Lisp_Object init)
2181 register Lisp_Object val;
2182 register unsigned char *p, *end;
2183 int c;
2184 EMACS_INT nbytes;
2186 CHECK_NATNUM (length);
2187 CHECK_NUMBER (init);
2189 c = XINT (init);
2190 if (ASCII_CHAR_P (c))
2192 nbytes = XINT (length);
2193 val = make_uninit_string (nbytes);
2194 p = SDATA (val);
2195 end = p + SCHARS (val);
2196 while (p != end)
2197 *p++ = c;
2199 else
2201 unsigned char str[MAX_MULTIBYTE_LENGTH];
2202 int len = CHAR_STRING (c, str);
2203 EMACS_INT string_len = XINT (length);
2205 if (string_len > MOST_POSITIVE_FIXNUM / len)
2206 error ("Maximum string size exceeded");
2207 nbytes = len * string_len;
2208 val = make_uninit_multibyte_string (string_len, nbytes);
2209 p = SDATA (val);
2210 end = p + nbytes;
2211 while (p != end)
2213 memcpy (p, str, len);
2214 p += len;
2218 *p = 0;
2219 return val;
2223 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2224 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2225 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2226 (Lisp_Object length, Lisp_Object init)
2228 register Lisp_Object val;
2229 struct Lisp_Bool_Vector *p;
2230 int real_init, i;
2231 EMACS_INT length_in_chars, length_in_elts;
2232 int bits_per_value;
2234 CHECK_NATNUM (length);
2236 bits_per_value = sizeof (EMACS_INT) * BOOL_VECTOR_BITS_PER_CHAR;
2238 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
2239 length_in_chars = ((XFASTINT (length) + BOOL_VECTOR_BITS_PER_CHAR - 1)
2240 / BOOL_VECTOR_BITS_PER_CHAR);
2242 /* We must allocate one more elements than LENGTH_IN_ELTS for the
2243 slot `size' of the struct Lisp_Bool_Vector. */
2244 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
2246 /* Get rid of any bits that would cause confusion. */
2247 XVECTOR (val)->size = 0; /* No Lisp_Object to trace in there. */
2248 /* Use XVECTOR (val) rather than `p' because p->size is not TRT. */
2249 XSETPVECTYPE (XVECTOR (val), PVEC_BOOL_VECTOR);
2251 p = XBOOL_VECTOR (val);
2252 p->size = XFASTINT (length);
2254 real_init = (NILP (init) ? 0 : -1);
2255 for (i = 0; i < length_in_chars ; i++)
2256 p->data[i] = real_init;
2258 /* Clear the extraneous bits in the last byte. */
2259 if (XINT (length) != length_in_chars * BOOL_VECTOR_BITS_PER_CHAR)
2260 p->data[length_in_chars - 1]
2261 &= (1 << (XINT (length) % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2263 return val;
2267 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2268 of characters from the contents. This string may be unibyte or
2269 multibyte, depending on the contents. */
2271 Lisp_Object
2272 make_string (const char *contents, EMACS_INT nbytes)
2274 register Lisp_Object val;
2275 EMACS_INT nchars, multibyte_nbytes;
2277 parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
2278 &nchars, &multibyte_nbytes);
2279 if (nbytes == nchars || nbytes != multibyte_nbytes)
2280 /* CONTENTS contains no multibyte sequences or contains an invalid
2281 multibyte sequence. We must make unibyte string. */
2282 val = make_unibyte_string (contents, nbytes);
2283 else
2284 val = make_multibyte_string (contents, nchars, nbytes);
2285 return val;
2289 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
2291 Lisp_Object
2292 make_unibyte_string (const char *contents, EMACS_INT length)
2294 register Lisp_Object val;
2295 val = make_uninit_string (length);
2296 memcpy (SDATA (val), contents, length);
2297 return val;
2301 /* Make a multibyte string from NCHARS characters occupying NBYTES
2302 bytes at CONTENTS. */
2304 Lisp_Object
2305 make_multibyte_string (const char *contents,
2306 EMACS_INT nchars, EMACS_INT nbytes)
2308 register Lisp_Object val;
2309 val = make_uninit_multibyte_string (nchars, nbytes);
2310 memcpy (SDATA (val), contents, nbytes);
2311 return val;
2315 /* Make a string from NCHARS characters occupying NBYTES bytes at
2316 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2318 Lisp_Object
2319 make_string_from_bytes (const char *contents,
2320 EMACS_INT nchars, EMACS_INT nbytes)
2322 register Lisp_Object val;
2323 val = make_uninit_multibyte_string (nchars, nbytes);
2324 memcpy (SDATA (val), contents, nbytes);
2325 if (SBYTES (val) == SCHARS (val))
2326 STRING_SET_UNIBYTE (val);
2327 return val;
2331 /* Make a string from NCHARS characters occupying NBYTES bytes at
2332 CONTENTS. The argument MULTIBYTE controls whether to label the
2333 string as multibyte. If NCHARS is negative, it counts the number of
2334 characters by itself. */
2336 Lisp_Object
2337 make_specified_string (const char *contents,
2338 EMACS_INT nchars, EMACS_INT nbytes, int multibyte)
2340 register Lisp_Object val;
2342 if (nchars < 0)
2344 if (multibyte)
2345 nchars = multibyte_chars_in_text ((const unsigned char *) contents,
2346 nbytes);
2347 else
2348 nchars = nbytes;
2350 val = make_uninit_multibyte_string (nchars, nbytes);
2351 memcpy (SDATA (val), contents, nbytes);
2352 if (!multibyte)
2353 STRING_SET_UNIBYTE (val);
2354 return val;
2358 /* Make a string from the data at STR, treating it as multibyte if the
2359 data warrants. */
2361 Lisp_Object
2362 build_string (const char *str)
2364 return make_string (str, strlen (str));
2368 /* Return an unibyte Lisp_String set up to hold LENGTH characters
2369 occupying LENGTH bytes. */
2371 Lisp_Object
2372 make_uninit_string (EMACS_INT length)
2374 Lisp_Object val;
2376 if (!length)
2377 return empty_unibyte_string;
2378 val = make_uninit_multibyte_string (length, length);
2379 STRING_SET_UNIBYTE (val);
2380 return val;
2384 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2385 which occupy NBYTES bytes. */
2387 Lisp_Object
2388 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2390 Lisp_Object string;
2391 struct Lisp_String *s;
2393 if (nchars < 0)
2394 abort ();
2395 if (!nbytes)
2396 return empty_multibyte_string;
2398 s = allocate_string ();
2399 allocate_string_data (s, nchars, nbytes);
2400 XSETSTRING (string, s);
2401 string_chars_consed += nbytes;
2402 return string;
2407 /***********************************************************************
2408 Float Allocation
2409 ***********************************************************************/
2411 /* We store float cells inside of float_blocks, allocating a new
2412 float_block with malloc whenever necessary. Float cells reclaimed
2413 by GC are put on a free list to be reallocated before allocating
2414 any new float cells from the latest float_block. */
2416 #define FLOAT_BLOCK_SIZE \
2417 (((BLOCK_BYTES - sizeof (struct float_block *) \
2418 /* The compiler might add padding at the end. */ \
2419 - (sizeof (struct Lisp_Float) - sizeof (int))) * CHAR_BIT) \
2420 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2422 #define GETMARKBIT(block,n) \
2423 (((block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2424 >> ((n) % (sizeof(int) * CHAR_BIT))) \
2425 & 1)
2427 #define SETMARKBIT(block,n) \
2428 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2429 |= 1 << ((n) % (sizeof(int) * CHAR_BIT))
2431 #define UNSETMARKBIT(block,n) \
2432 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2433 &= ~(1 << ((n) % (sizeof(int) * CHAR_BIT)))
2435 #define FLOAT_BLOCK(fptr) \
2436 ((struct float_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
2438 #define FLOAT_INDEX(fptr) \
2439 ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2441 struct float_block
2443 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2444 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2445 int gcmarkbits[1 + FLOAT_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
2446 struct float_block *next;
2449 #define FLOAT_MARKED_P(fptr) \
2450 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2452 #define FLOAT_MARK(fptr) \
2453 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2455 #define FLOAT_UNMARK(fptr) \
2456 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2458 /* Current float_block. */
2460 struct float_block *float_block;
2462 /* Index of first unused Lisp_Float in the current float_block. */
2464 int float_block_index;
2466 /* Total number of float blocks now in use. */
2468 int n_float_blocks;
2470 /* Free-list of Lisp_Floats. */
2472 struct Lisp_Float *float_free_list;
2475 /* Initialize float allocation. */
2477 static void
2478 init_float (void)
2480 float_block = NULL;
2481 float_block_index = FLOAT_BLOCK_SIZE; /* Force alloc of new float_block. */
2482 float_free_list = 0;
2483 n_float_blocks = 0;
2487 /* Return a new float object with value FLOAT_VALUE. */
2489 Lisp_Object
2490 make_float (double float_value)
2492 register Lisp_Object val;
2494 /* eassert (!handling_signal); */
2496 MALLOC_BLOCK_INPUT;
2498 if (float_free_list)
2500 /* We use the data field for chaining the free list
2501 so that we won't use the same field that has the mark bit. */
2502 XSETFLOAT (val, float_free_list);
2503 float_free_list = float_free_list->u.chain;
2505 else
2507 if (float_block_index == FLOAT_BLOCK_SIZE)
2509 register struct float_block *new;
2511 new = (struct float_block *) lisp_align_malloc (sizeof *new,
2512 MEM_TYPE_FLOAT);
2513 new->next = float_block;
2514 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2515 float_block = new;
2516 float_block_index = 0;
2517 n_float_blocks++;
2519 XSETFLOAT (val, &float_block->floats[float_block_index]);
2520 float_block_index++;
2523 MALLOC_UNBLOCK_INPUT;
2525 XFLOAT_INIT (val, float_value);
2526 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2527 consing_since_gc += sizeof (struct Lisp_Float);
2528 floats_consed++;
2529 return val;
2534 /***********************************************************************
2535 Cons Allocation
2536 ***********************************************************************/
2538 /* We store cons cells inside of cons_blocks, allocating a new
2539 cons_block with malloc whenever necessary. Cons cells reclaimed by
2540 GC are put on a free list to be reallocated before allocating
2541 any new cons cells from the latest cons_block. */
2543 #define CONS_BLOCK_SIZE \
2544 (((BLOCK_BYTES - sizeof (struct cons_block *)) * CHAR_BIT) \
2545 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2547 #define CONS_BLOCK(fptr) \
2548 ((struct cons_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
2550 #define CONS_INDEX(fptr) \
2551 ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2553 struct cons_block
2555 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2556 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2557 int gcmarkbits[1 + CONS_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
2558 struct cons_block *next;
2561 #define CONS_MARKED_P(fptr) \
2562 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2564 #define CONS_MARK(fptr) \
2565 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2567 #define CONS_UNMARK(fptr) \
2568 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2570 /* Current cons_block. */
2572 struct cons_block *cons_block;
2574 /* Index of first unused Lisp_Cons in the current block. */
2576 int cons_block_index;
2578 /* Free-list of Lisp_Cons structures. */
2580 struct Lisp_Cons *cons_free_list;
2582 /* Total number of cons blocks now in use. */
2584 static int n_cons_blocks;
2587 /* Initialize cons allocation. */
2589 static void
2590 init_cons (void)
2592 cons_block = NULL;
2593 cons_block_index = CONS_BLOCK_SIZE; /* Force alloc of new cons_block. */
2594 cons_free_list = 0;
2595 n_cons_blocks = 0;
2599 /* Explicitly free a cons cell by putting it on the free-list. */
2601 void
2602 free_cons (struct Lisp_Cons *ptr)
2604 ptr->u.chain = cons_free_list;
2605 #if GC_MARK_STACK
2606 ptr->car = Vdead;
2607 #endif
2608 cons_free_list = ptr;
2611 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2612 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2613 (Lisp_Object car, Lisp_Object cdr)
2615 register Lisp_Object val;
2617 /* eassert (!handling_signal); */
2619 MALLOC_BLOCK_INPUT;
2621 if (cons_free_list)
2623 /* We use the cdr for chaining the free list
2624 so that we won't use the same field that has the mark bit. */
2625 XSETCONS (val, cons_free_list);
2626 cons_free_list = cons_free_list->u.chain;
2628 else
2630 if (cons_block_index == CONS_BLOCK_SIZE)
2632 register struct cons_block *new;
2633 new = (struct cons_block *) lisp_align_malloc (sizeof *new,
2634 MEM_TYPE_CONS);
2635 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2636 new->next = cons_block;
2637 cons_block = new;
2638 cons_block_index = 0;
2639 n_cons_blocks++;
2641 XSETCONS (val, &cons_block->conses[cons_block_index]);
2642 cons_block_index++;
2645 MALLOC_UNBLOCK_INPUT;
2647 XSETCAR (val, car);
2648 XSETCDR (val, cdr);
2649 eassert (!CONS_MARKED_P (XCONS (val)));
2650 consing_since_gc += sizeof (struct Lisp_Cons);
2651 cons_cells_consed++;
2652 return val;
2655 #ifdef GC_CHECK_CONS_LIST
2656 /* Get an error now if there's any junk in the cons free list. */
2657 void
2658 check_cons_list (void)
2660 struct Lisp_Cons *tail = cons_free_list;
2662 while (tail)
2663 tail = tail->u.chain;
2665 #endif
2667 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2669 Lisp_Object
2670 list1 (Lisp_Object arg1)
2672 return Fcons (arg1, Qnil);
2675 Lisp_Object
2676 list2 (Lisp_Object arg1, Lisp_Object arg2)
2678 return Fcons (arg1, Fcons (arg2, Qnil));
2682 Lisp_Object
2683 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2685 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2689 Lisp_Object
2690 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2692 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2696 Lisp_Object
2697 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2699 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2700 Fcons (arg5, Qnil)))));
2704 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2705 doc: /* Return a newly created list with specified arguments as elements.
2706 Any number of arguments, even zero arguments, are allowed.
2707 usage: (list &rest OBJECTS) */)
2708 (int nargs, register Lisp_Object *args)
2710 register Lisp_Object val;
2711 val = Qnil;
2713 while (nargs > 0)
2715 nargs--;
2716 val = Fcons (args[nargs], val);
2718 return val;
2722 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2723 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2724 (register Lisp_Object length, Lisp_Object init)
2726 register Lisp_Object val;
2727 register EMACS_INT size;
2729 CHECK_NATNUM (length);
2730 size = XFASTINT (length);
2732 val = Qnil;
2733 while (size > 0)
2735 val = Fcons (init, val);
2736 --size;
2738 if (size > 0)
2740 val = Fcons (init, val);
2741 --size;
2743 if (size > 0)
2745 val = Fcons (init, val);
2746 --size;
2748 if (size > 0)
2750 val = Fcons (init, val);
2751 --size;
2753 if (size > 0)
2755 val = Fcons (init, val);
2756 --size;
2762 QUIT;
2765 return val;
2770 /***********************************************************************
2771 Vector Allocation
2772 ***********************************************************************/
2774 /* Singly-linked list of all vectors. */
2776 static struct Lisp_Vector *all_vectors;
2778 /* Total number of vector-like objects now in use. */
2780 static int n_vectors;
2783 /* Value is a pointer to a newly allocated Lisp_Vector structure
2784 with room for LEN Lisp_Objects. */
2786 static struct Lisp_Vector *
2787 allocate_vectorlike (EMACS_INT len)
2789 struct Lisp_Vector *p;
2790 size_t nbytes;
2792 MALLOC_BLOCK_INPUT;
2794 #ifdef DOUG_LEA_MALLOC
2795 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2796 because mapped region contents are not preserved in
2797 a dumped Emacs. */
2798 mallopt (M_MMAP_MAX, 0);
2799 #endif
2801 /* This gets triggered by code which I haven't bothered to fix. --Stef */
2802 /* eassert (!handling_signal); */
2804 nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
2805 p = (struct Lisp_Vector *) lisp_malloc (nbytes, MEM_TYPE_VECTORLIKE);
2807 #ifdef DOUG_LEA_MALLOC
2808 /* Back to a reasonable maximum of mmap'ed areas. */
2809 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2810 #endif
2812 consing_since_gc += nbytes;
2813 vector_cells_consed += len;
2815 p->next = all_vectors;
2816 all_vectors = p;
2818 MALLOC_UNBLOCK_INPUT;
2820 ++n_vectors;
2821 return p;
2825 /* Allocate a vector with NSLOTS slots. */
2827 struct Lisp_Vector *
2828 allocate_vector (EMACS_INT nslots)
2830 struct Lisp_Vector *v = allocate_vectorlike (nslots);
2831 v->size = nslots;
2832 return v;
2836 /* Allocate other vector-like structures. */
2838 struct Lisp_Vector *
2839 allocate_pseudovector (int memlen, int lisplen, EMACS_INT tag)
2841 struct Lisp_Vector *v = allocate_vectorlike (memlen);
2842 EMACS_INT i;
2844 /* Only the first lisplen slots will be traced normally by the GC. */
2845 v->size = lisplen;
2846 for (i = 0; i < lisplen; ++i)
2847 v->contents[i] = Qnil;
2849 XSETPVECTYPE (v, tag); /* Add the appropriate tag. */
2850 return v;
2853 struct Lisp_Hash_Table *
2854 allocate_hash_table (void)
2856 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table, count, PVEC_HASH_TABLE);
2860 struct window *
2861 allocate_window (void)
2863 return ALLOCATE_PSEUDOVECTOR(struct window, current_matrix, PVEC_WINDOW);
2867 struct terminal *
2868 allocate_terminal (void)
2870 struct terminal *t = ALLOCATE_PSEUDOVECTOR (struct terminal,
2871 next_terminal, PVEC_TERMINAL);
2872 /* Zero out the non-GC'd fields. FIXME: This should be made unnecessary. */
2873 memset (&t->next_terminal, 0,
2874 (char*) (t + 1) - (char*) &t->next_terminal);
2876 return t;
2879 struct frame *
2880 allocate_frame (void)
2882 struct frame *f = ALLOCATE_PSEUDOVECTOR (struct frame,
2883 face_cache, PVEC_FRAME);
2884 /* Zero out the non-GC'd fields. FIXME: This should be made unnecessary. */
2885 memset (&f->face_cache, 0,
2886 (char *) (f + 1) - (char *) &f->face_cache);
2887 return f;
2891 struct Lisp_Process *
2892 allocate_process (void)
2894 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
2898 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
2899 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
2900 See also the function `vector'. */)
2901 (register Lisp_Object length, Lisp_Object init)
2903 Lisp_Object vector;
2904 register EMACS_INT sizei;
2905 register EMACS_INT i;
2906 register struct Lisp_Vector *p;
2908 CHECK_NATNUM (length);
2909 sizei = XFASTINT (length);
2911 p = allocate_vector (sizei);
2912 for (i = 0; i < sizei; i++)
2913 p->contents[i] = init;
2915 XSETVECTOR (vector, p);
2916 return vector;
2920 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
2921 doc: /* Return a newly created vector with specified arguments as elements.
2922 Any number of arguments, even zero arguments, are allowed.
2923 usage: (vector &rest OBJECTS) */)
2924 (register int nargs, Lisp_Object *args)
2926 register Lisp_Object len, val;
2927 register int i;
2928 register struct Lisp_Vector *p;
2930 XSETFASTINT (len, nargs);
2931 val = Fmake_vector (len, Qnil);
2932 p = XVECTOR (val);
2933 for (i = 0; i < nargs; i++)
2934 p->contents[i] = args[i];
2935 return val;
2939 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
2940 doc: /* Create a byte-code object with specified arguments as elements.
2941 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
2942 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
2943 and (optional) INTERACTIVE-SPEC.
2944 The first four arguments are required; at most six have any
2945 significance.
2946 The ARGLIST can be either like the one of `lambda', in which case the arguments
2947 will be dynamically bound before executing the byte code, or it can be an
2948 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
2949 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
2950 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
2951 argument to catch the left-over arguments. If such an integer is used, the
2952 arguments will not be dynamically bound but will be instead pushed on the
2953 stack before executing the byte-code.
2954 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
2955 (register int nargs, Lisp_Object *args)
2957 register Lisp_Object len, val;
2958 register int i;
2959 register struct Lisp_Vector *p;
2961 XSETFASTINT (len, nargs);
2962 if (!NILP (Vpurify_flag))
2963 val = make_pure_vector ((EMACS_INT) nargs);
2964 else
2965 val = Fmake_vector (len, Qnil);
2967 if (nargs > 1 && STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
2968 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
2969 earlier because they produced a raw 8-bit string for byte-code
2970 and now such a byte-code string is loaded as multibyte while
2971 raw 8-bit characters converted to multibyte form. Thus, now we
2972 must convert them back to the original unibyte form. */
2973 args[1] = Fstring_as_unibyte (args[1]);
2975 p = XVECTOR (val);
2976 for (i = 0; i < nargs; i++)
2978 if (!NILP (Vpurify_flag))
2979 args[i] = Fpurecopy (args[i]);
2980 p->contents[i] = args[i];
2982 XSETPVECTYPE (p, PVEC_COMPILED);
2983 XSETCOMPILED (val, p);
2984 return val;
2989 /***********************************************************************
2990 Symbol Allocation
2991 ***********************************************************************/
2993 /* Each symbol_block is just under 1020 bytes long, since malloc
2994 really allocates in units of powers of two and uses 4 bytes for its
2995 own overhead. */
2997 #define SYMBOL_BLOCK_SIZE \
2998 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
3000 struct symbol_block
3002 /* Place `symbols' first, to preserve alignment. */
3003 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3004 struct symbol_block *next;
3007 /* Current symbol block and index of first unused Lisp_Symbol
3008 structure in it. */
3010 static struct symbol_block *symbol_block;
3011 static int symbol_block_index;
3013 /* List of free symbols. */
3015 static struct Lisp_Symbol *symbol_free_list;
3017 /* Total number of symbol blocks now in use. */
3019 static int n_symbol_blocks;
3022 /* Initialize symbol allocation. */
3024 static void
3025 init_symbol (void)
3027 symbol_block = NULL;
3028 symbol_block_index = SYMBOL_BLOCK_SIZE;
3029 symbol_free_list = 0;
3030 n_symbol_blocks = 0;
3034 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3035 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3036 Its value and function definition are void, and its property list is nil. */)
3037 (Lisp_Object name)
3039 register Lisp_Object val;
3040 register struct Lisp_Symbol *p;
3042 CHECK_STRING (name);
3044 /* eassert (!handling_signal); */
3046 MALLOC_BLOCK_INPUT;
3048 if (symbol_free_list)
3050 XSETSYMBOL (val, symbol_free_list);
3051 symbol_free_list = symbol_free_list->next;
3053 else
3055 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3057 struct symbol_block *new;
3058 new = (struct symbol_block *) lisp_malloc (sizeof *new,
3059 MEM_TYPE_SYMBOL);
3060 new->next = symbol_block;
3061 symbol_block = new;
3062 symbol_block_index = 0;
3063 n_symbol_blocks++;
3065 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index]);
3066 symbol_block_index++;
3069 MALLOC_UNBLOCK_INPUT;
3071 p = XSYMBOL (val);
3072 p->xname = name;
3073 p->plist = Qnil;
3074 p->redirect = SYMBOL_PLAINVAL;
3075 SET_SYMBOL_VAL (p, Qunbound);
3076 p->function = Qunbound;
3077 p->next = NULL;
3078 p->gcmarkbit = 0;
3079 p->interned = SYMBOL_UNINTERNED;
3080 p->constant = 0;
3081 p->declared_special = 0;
3082 consing_since_gc += sizeof (struct Lisp_Symbol);
3083 symbols_consed++;
3084 return val;
3089 /***********************************************************************
3090 Marker (Misc) Allocation
3091 ***********************************************************************/
3093 /* Allocation of markers and other objects that share that structure.
3094 Works like allocation of conses. */
3096 #define MARKER_BLOCK_SIZE \
3097 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
3099 struct marker_block
3101 /* Place `markers' first, to preserve alignment. */
3102 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
3103 struct marker_block *next;
3106 static struct marker_block *marker_block;
3107 static int marker_block_index;
3109 static union Lisp_Misc *marker_free_list;
3111 /* Total number of marker blocks now in use. */
3113 static int n_marker_blocks;
3115 static void
3116 init_marker (void)
3118 marker_block = NULL;
3119 marker_block_index = MARKER_BLOCK_SIZE;
3120 marker_free_list = 0;
3121 n_marker_blocks = 0;
3124 /* Return a newly allocated Lisp_Misc object, with no substructure. */
3126 Lisp_Object
3127 allocate_misc (void)
3129 Lisp_Object val;
3131 /* eassert (!handling_signal); */
3133 MALLOC_BLOCK_INPUT;
3135 if (marker_free_list)
3137 XSETMISC (val, marker_free_list);
3138 marker_free_list = marker_free_list->u_free.chain;
3140 else
3142 if (marker_block_index == MARKER_BLOCK_SIZE)
3144 struct marker_block *new;
3145 new = (struct marker_block *) lisp_malloc (sizeof *new,
3146 MEM_TYPE_MISC);
3147 new->next = marker_block;
3148 marker_block = new;
3149 marker_block_index = 0;
3150 n_marker_blocks++;
3151 total_free_markers += MARKER_BLOCK_SIZE;
3153 XSETMISC (val, &marker_block->markers[marker_block_index]);
3154 marker_block_index++;
3157 MALLOC_UNBLOCK_INPUT;
3159 --total_free_markers;
3160 consing_since_gc += sizeof (union Lisp_Misc);
3161 misc_objects_consed++;
3162 XMISCANY (val)->gcmarkbit = 0;
3163 return val;
3166 /* Free a Lisp_Misc object */
3168 void
3169 free_misc (Lisp_Object misc)
3171 XMISCTYPE (misc) = Lisp_Misc_Free;
3172 XMISC (misc)->u_free.chain = marker_free_list;
3173 marker_free_list = XMISC (misc);
3175 total_free_markers++;
3178 /* Return a Lisp_Misc_Save_Value object containing POINTER and
3179 INTEGER. This is used to package C values to call record_unwind_protect.
3180 The unwind function can get the C values back using XSAVE_VALUE. */
3182 Lisp_Object
3183 make_save_value (void *pointer, int integer)
3185 register Lisp_Object val;
3186 register struct Lisp_Save_Value *p;
3188 val = allocate_misc ();
3189 XMISCTYPE (val) = Lisp_Misc_Save_Value;
3190 p = XSAVE_VALUE (val);
3191 p->pointer = pointer;
3192 p->integer = integer;
3193 p->dogc = 0;
3194 return val;
3197 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3198 doc: /* Return a newly allocated marker which does not point at any place. */)
3199 (void)
3201 register Lisp_Object val;
3202 register struct Lisp_Marker *p;
3204 val = allocate_misc ();
3205 XMISCTYPE (val) = Lisp_Misc_Marker;
3206 p = XMARKER (val);
3207 p->buffer = 0;
3208 p->bytepos = 0;
3209 p->charpos = 0;
3210 p->next = NULL;
3211 p->insertion_type = 0;
3212 return val;
3215 /* Put MARKER back on the free list after using it temporarily. */
3217 void
3218 free_marker (Lisp_Object marker)
3220 unchain_marker (XMARKER (marker));
3221 free_misc (marker);
3225 /* Return a newly created vector or string with specified arguments as
3226 elements. If all the arguments are characters that can fit
3227 in a string of events, make a string; otherwise, make a vector.
3229 Any number of arguments, even zero arguments, are allowed. */
3231 Lisp_Object
3232 make_event_array (register int nargs, Lisp_Object *args)
3234 int i;
3236 for (i = 0; i < nargs; i++)
3237 /* The things that fit in a string
3238 are characters that are in 0...127,
3239 after discarding the meta bit and all the bits above it. */
3240 if (!INTEGERP (args[i])
3241 || (XUINT (args[i]) & ~(-CHAR_META)) >= 0200)
3242 return Fvector (nargs, args);
3244 /* Since the loop exited, we know that all the things in it are
3245 characters, so we can make a string. */
3247 Lisp_Object result;
3249 result = Fmake_string (make_number (nargs), make_number (0));
3250 for (i = 0; i < nargs; i++)
3252 SSET (result, i, XINT (args[i]));
3253 /* Move the meta bit to the right place for a string char. */
3254 if (XINT (args[i]) & CHAR_META)
3255 SSET (result, i, SREF (result, i) | 0x80);
3258 return result;
3264 /************************************************************************
3265 Memory Full Handling
3266 ************************************************************************/
3269 /* Called if malloc returns zero. */
3271 void
3272 memory_full (void)
3274 int i;
3276 Vmemory_full = Qt;
3278 memory_full_cons_threshold = sizeof (struct cons_block);
3280 /* The first time we get here, free the spare memory. */
3281 for (i = 0; i < sizeof (spare_memory) / sizeof (char *); i++)
3282 if (spare_memory[i])
3284 if (i == 0)
3285 free (spare_memory[i]);
3286 else if (i >= 1 && i <= 4)
3287 lisp_align_free (spare_memory[i]);
3288 else
3289 lisp_free (spare_memory[i]);
3290 spare_memory[i] = 0;
3293 /* Record the space now used. When it decreases substantially,
3294 we can refill the memory reserve. */
3295 #ifndef SYSTEM_MALLOC
3296 bytes_used_when_full = BYTES_USED;
3297 #endif
3299 /* This used to call error, but if we've run out of memory, we could
3300 get infinite recursion trying to build the string. */
3301 xsignal (Qnil, Vmemory_signal_data);
3304 /* If we released our reserve (due to running out of memory),
3305 and we have a fair amount free once again,
3306 try to set aside another reserve in case we run out once more.
3308 This is called when a relocatable block is freed in ralloc.c,
3309 and also directly from this file, in case we're not using ralloc.c. */
3311 void
3312 refill_memory_reserve (void)
3314 #ifndef SYSTEM_MALLOC
3315 if (spare_memory[0] == 0)
3316 spare_memory[0] = (char *) malloc ((size_t) SPARE_MEMORY);
3317 if (spare_memory[1] == 0)
3318 spare_memory[1] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3319 MEM_TYPE_CONS);
3320 if (spare_memory[2] == 0)
3321 spare_memory[2] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3322 MEM_TYPE_CONS);
3323 if (spare_memory[3] == 0)
3324 spare_memory[3] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3325 MEM_TYPE_CONS);
3326 if (spare_memory[4] == 0)
3327 spare_memory[4] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3328 MEM_TYPE_CONS);
3329 if (spare_memory[5] == 0)
3330 spare_memory[5] = (char *) lisp_malloc (sizeof (struct string_block),
3331 MEM_TYPE_STRING);
3332 if (spare_memory[6] == 0)
3333 spare_memory[6] = (char *) lisp_malloc (sizeof (struct string_block),
3334 MEM_TYPE_STRING);
3335 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
3336 Vmemory_full = Qnil;
3337 #endif
3340 /************************************************************************
3341 C Stack Marking
3342 ************************************************************************/
3344 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
3346 /* Conservative C stack marking requires a method to identify possibly
3347 live Lisp objects given a pointer value. We do this by keeping
3348 track of blocks of Lisp data that are allocated in a red-black tree
3349 (see also the comment of mem_node which is the type of nodes in
3350 that tree). Function lisp_malloc adds information for an allocated
3351 block to the red-black tree with calls to mem_insert, and function
3352 lisp_free removes it with mem_delete. Functions live_string_p etc
3353 call mem_find to lookup information about a given pointer in the
3354 tree, and use that to determine if the pointer points to a Lisp
3355 object or not. */
3357 /* Initialize this part of alloc.c. */
3359 static void
3360 mem_init (void)
3362 mem_z.left = mem_z.right = MEM_NIL;
3363 mem_z.parent = NULL;
3364 mem_z.color = MEM_BLACK;
3365 mem_z.start = mem_z.end = NULL;
3366 mem_root = MEM_NIL;
3370 /* Value is a pointer to the mem_node containing START. Value is
3371 MEM_NIL if there is no node in the tree containing START. */
3373 static INLINE struct mem_node *
3374 mem_find (void *start)
3376 struct mem_node *p;
3378 if (start < min_heap_address || start > max_heap_address)
3379 return MEM_NIL;
3381 /* Make the search always successful to speed up the loop below. */
3382 mem_z.start = start;
3383 mem_z.end = (char *) start + 1;
3385 p = mem_root;
3386 while (start < p->start || start >= p->end)
3387 p = start < p->start ? p->left : p->right;
3388 return p;
3392 /* Insert a new node into the tree for a block of memory with start
3393 address START, end address END, and type TYPE. Value is a
3394 pointer to the node that was inserted. */
3396 static struct mem_node *
3397 mem_insert (void *start, void *end, enum mem_type type)
3399 struct mem_node *c, *parent, *x;
3401 if (min_heap_address == NULL || start < min_heap_address)
3402 min_heap_address = start;
3403 if (max_heap_address == NULL || end > max_heap_address)
3404 max_heap_address = end;
3406 /* See where in the tree a node for START belongs. In this
3407 particular application, it shouldn't happen that a node is already
3408 present. For debugging purposes, let's check that. */
3409 c = mem_root;
3410 parent = NULL;
3412 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
3414 while (c != MEM_NIL)
3416 if (start >= c->start && start < c->end)
3417 abort ();
3418 parent = c;
3419 c = start < c->start ? c->left : c->right;
3422 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3424 while (c != MEM_NIL)
3426 parent = c;
3427 c = start < c->start ? c->left : c->right;
3430 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3432 /* Create a new node. */
3433 #ifdef GC_MALLOC_CHECK
3434 x = (struct mem_node *) _malloc_internal (sizeof *x);
3435 if (x == NULL)
3436 abort ();
3437 #else
3438 x = (struct mem_node *) xmalloc (sizeof *x);
3439 #endif
3440 x->start = start;
3441 x->end = end;
3442 x->type = type;
3443 x->parent = parent;
3444 x->left = x->right = MEM_NIL;
3445 x->color = MEM_RED;
3447 /* Insert it as child of PARENT or install it as root. */
3448 if (parent)
3450 if (start < parent->start)
3451 parent->left = x;
3452 else
3453 parent->right = x;
3455 else
3456 mem_root = x;
3458 /* Re-establish red-black tree properties. */
3459 mem_insert_fixup (x);
3461 return x;
3465 /* Re-establish the red-black properties of the tree, and thereby
3466 balance the tree, after node X has been inserted; X is always red. */
3468 static void
3469 mem_insert_fixup (struct mem_node *x)
3471 while (x != mem_root && x->parent->color == MEM_RED)
3473 /* X is red and its parent is red. This is a violation of
3474 red-black tree property #3. */
3476 if (x->parent == x->parent->parent->left)
3478 /* We're on the left side of our grandparent, and Y is our
3479 "uncle". */
3480 struct mem_node *y = x->parent->parent->right;
3482 if (y->color == MEM_RED)
3484 /* Uncle and parent are red but should be black because
3485 X is red. Change the colors accordingly and proceed
3486 with the grandparent. */
3487 x->parent->color = MEM_BLACK;
3488 y->color = MEM_BLACK;
3489 x->parent->parent->color = MEM_RED;
3490 x = x->parent->parent;
3492 else
3494 /* Parent and uncle have different colors; parent is
3495 red, uncle is black. */
3496 if (x == x->parent->right)
3498 x = x->parent;
3499 mem_rotate_left (x);
3502 x->parent->color = MEM_BLACK;
3503 x->parent->parent->color = MEM_RED;
3504 mem_rotate_right (x->parent->parent);
3507 else
3509 /* This is the symmetrical case of above. */
3510 struct mem_node *y = x->parent->parent->left;
3512 if (y->color == MEM_RED)
3514 x->parent->color = MEM_BLACK;
3515 y->color = MEM_BLACK;
3516 x->parent->parent->color = MEM_RED;
3517 x = x->parent->parent;
3519 else
3521 if (x == x->parent->left)
3523 x = x->parent;
3524 mem_rotate_right (x);
3527 x->parent->color = MEM_BLACK;
3528 x->parent->parent->color = MEM_RED;
3529 mem_rotate_left (x->parent->parent);
3534 /* The root may have been changed to red due to the algorithm. Set
3535 it to black so that property #5 is satisfied. */
3536 mem_root->color = MEM_BLACK;
3540 /* (x) (y)
3541 / \ / \
3542 a (y) ===> (x) c
3543 / \ / \
3544 b c a b */
3546 static void
3547 mem_rotate_left (struct mem_node *x)
3549 struct mem_node *y;
3551 /* Turn y's left sub-tree into x's right sub-tree. */
3552 y = x->right;
3553 x->right = y->left;
3554 if (y->left != MEM_NIL)
3555 y->left->parent = x;
3557 /* Y's parent was x's parent. */
3558 if (y != MEM_NIL)
3559 y->parent = x->parent;
3561 /* Get the parent to point to y instead of x. */
3562 if (x->parent)
3564 if (x == x->parent->left)
3565 x->parent->left = y;
3566 else
3567 x->parent->right = y;
3569 else
3570 mem_root = y;
3572 /* Put x on y's left. */
3573 y->left = x;
3574 if (x != MEM_NIL)
3575 x->parent = y;
3579 /* (x) (Y)
3580 / \ / \
3581 (y) c ===> a (x)
3582 / \ / \
3583 a b b c */
3585 static void
3586 mem_rotate_right (struct mem_node *x)
3588 struct mem_node *y = x->left;
3590 x->left = y->right;
3591 if (y->right != MEM_NIL)
3592 y->right->parent = x;
3594 if (y != MEM_NIL)
3595 y->parent = x->parent;
3596 if (x->parent)
3598 if (x == x->parent->right)
3599 x->parent->right = y;
3600 else
3601 x->parent->left = y;
3603 else
3604 mem_root = y;
3606 y->right = x;
3607 if (x != MEM_NIL)
3608 x->parent = y;
3612 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
3614 static void
3615 mem_delete (struct mem_node *z)
3617 struct mem_node *x, *y;
3619 if (!z || z == MEM_NIL)
3620 return;
3622 if (z->left == MEM_NIL || z->right == MEM_NIL)
3623 y = z;
3624 else
3626 y = z->right;
3627 while (y->left != MEM_NIL)
3628 y = y->left;
3631 if (y->left != MEM_NIL)
3632 x = y->left;
3633 else
3634 x = y->right;
3636 x->parent = y->parent;
3637 if (y->parent)
3639 if (y == y->parent->left)
3640 y->parent->left = x;
3641 else
3642 y->parent->right = x;
3644 else
3645 mem_root = x;
3647 if (y != z)
3649 z->start = y->start;
3650 z->end = y->end;
3651 z->type = y->type;
3654 if (y->color == MEM_BLACK)
3655 mem_delete_fixup (x);
3657 #ifdef GC_MALLOC_CHECK
3658 _free_internal (y);
3659 #else
3660 xfree (y);
3661 #endif
3665 /* Re-establish the red-black properties of the tree, after a
3666 deletion. */
3668 static void
3669 mem_delete_fixup (struct mem_node *x)
3671 while (x != mem_root && x->color == MEM_BLACK)
3673 if (x == x->parent->left)
3675 struct mem_node *w = x->parent->right;
3677 if (w->color == MEM_RED)
3679 w->color = MEM_BLACK;
3680 x->parent->color = MEM_RED;
3681 mem_rotate_left (x->parent);
3682 w = x->parent->right;
3685 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
3687 w->color = MEM_RED;
3688 x = x->parent;
3690 else
3692 if (w->right->color == MEM_BLACK)
3694 w->left->color = MEM_BLACK;
3695 w->color = MEM_RED;
3696 mem_rotate_right (w);
3697 w = x->parent->right;
3699 w->color = x->parent->color;
3700 x->parent->color = MEM_BLACK;
3701 w->right->color = MEM_BLACK;
3702 mem_rotate_left (x->parent);
3703 x = mem_root;
3706 else
3708 struct mem_node *w = x->parent->left;
3710 if (w->color == MEM_RED)
3712 w->color = MEM_BLACK;
3713 x->parent->color = MEM_RED;
3714 mem_rotate_right (x->parent);
3715 w = x->parent->left;
3718 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
3720 w->color = MEM_RED;
3721 x = x->parent;
3723 else
3725 if (w->left->color == MEM_BLACK)
3727 w->right->color = MEM_BLACK;
3728 w->color = MEM_RED;
3729 mem_rotate_left (w);
3730 w = x->parent->left;
3733 w->color = x->parent->color;
3734 x->parent->color = MEM_BLACK;
3735 w->left->color = MEM_BLACK;
3736 mem_rotate_right (x->parent);
3737 x = mem_root;
3742 x->color = MEM_BLACK;
3746 /* Value is non-zero if P is a pointer to a live Lisp string on
3747 the heap. M is a pointer to the mem_block for P. */
3749 static INLINE int
3750 live_string_p (struct mem_node *m, void *p)
3752 if (m->type == MEM_TYPE_STRING)
3754 struct string_block *b = (struct string_block *) m->start;
3755 ptrdiff_t offset = (char *) p - (char *) &b->strings[0];
3757 /* P must point to the start of a Lisp_String structure, and it
3758 must not be on the free-list. */
3759 return (offset >= 0
3760 && offset % sizeof b->strings[0] == 0
3761 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
3762 && ((struct Lisp_String *) p)->data != NULL);
3764 else
3765 return 0;
3769 /* Value is non-zero if P is a pointer to a live Lisp cons on
3770 the heap. M is a pointer to the mem_block for P. */
3772 static INLINE int
3773 live_cons_p (struct mem_node *m, void *p)
3775 if (m->type == MEM_TYPE_CONS)
3777 struct cons_block *b = (struct cons_block *) m->start;
3778 ptrdiff_t offset = (char *) p - (char *) &b->conses[0];
3780 /* P must point to the start of a Lisp_Cons, not be
3781 one of the unused cells in the current cons block,
3782 and not be on the free-list. */
3783 return (offset >= 0
3784 && offset % sizeof b->conses[0] == 0
3785 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
3786 && (b != cons_block
3787 || offset / sizeof b->conses[0] < cons_block_index)
3788 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
3790 else
3791 return 0;
3795 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3796 the heap. M is a pointer to the mem_block for P. */
3798 static INLINE int
3799 live_symbol_p (struct mem_node *m, void *p)
3801 if (m->type == MEM_TYPE_SYMBOL)
3803 struct symbol_block *b = (struct symbol_block *) m->start;
3804 ptrdiff_t offset = (char *) p - (char *) &b->symbols[0];
3806 /* P must point to the start of a Lisp_Symbol, not be
3807 one of the unused cells in the current symbol block,
3808 and not be on the free-list. */
3809 return (offset >= 0
3810 && offset % sizeof b->symbols[0] == 0
3811 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
3812 && (b != symbol_block
3813 || offset / sizeof b->symbols[0] < symbol_block_index)
3814 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
3816 else
3817 return 0;
3821 /* Value is non-zero if P is a pointer to a live Lisp float on
3822 the heap. M is a pointer to the mem_block for P. */
3824 static INLINE int
3825 live_float_p (struct mem_node *m, void *p)
3827 if (m->type == MEM_TYPE_FLOAT)
3829 struct float_block *b = (struct float_block *) m->start;
3830 ptrdiff_t offset = (char *) p - (char *) &b->floats[0];
3832 /* P must point to the start of a Lisp_Float and not be
3833 one of the unused cells in the current float block. */
3834 return (offset >= 0
3835 && offset % sizeof b->floats[0] == 0
3836 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
3837 && (b != float_block
3838 || offset / sizeof b->floats[0] < float_block_index));
3840 else
3841 return 0;
3845 /* Value is non-zero if P is a pointer to a live Lisp Misc on
3846 the heap. M is a pointer to the mem_block for P. */
3848 static INLINE int
3849 live_misc_p (struct mem_node *m, void *p)
3851 if (m->type == MEM_TYPE_MISC)
3853 struct marker_block *b = (struct marker_block *) m->start;
3854 ptrdiff_t offset = (char *) p - (char *) &b->markers[0];
3856 /* P must point to the start of a Lisp_Misc, not be
3857 one of the unused cells in the current misc block,
3858 and not be on the free-list. */
3859 return (offset >= 0
3860 && offset % sizeof b->markers[0] == 0
3861 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
3862 && (b != marker_block
3863 || offset / sizeof b->markers[0] < marker_block_index)
3864 && ((union Lisp_Misc *) p)->u_any.type != Lisp_Misc_Free);
3866 else
3867 return 0;
3871 /* Value is non-zero if P is a pointer to a live vector-like object.
3872 M is a pointer to the mem_block for P. */
3874 static INLINE int
3875 live_vector_p (struct mem_node *m, void *p)
3877 return (p == m->start && m->type == MEM_TYPE_VECTORLIKE);
3881 /* Value is non-zero if P is a pointer to a live buffer. M is a
3882 pointer to the mem_block for P. */
3884 static INLINE int
3885 live_buffer_p (struct mem_node *m, void *p)
3887 /* P must point to the start of the block, and the buffer
3888 must not have been killed. */
3889 return (m->type == MEM_TYPE_BUFFER
3890 && p == m->start
3891 && !NILP (((struct buffer *) p)->BUFFER_INTERNAL_FIELD (name)));
3894 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
3896 #if GC_MARK_STACK
3898 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3900 /* Array of objects that are kept alive because the C stack contains
3901 a pattern that looks like a reference to them . */
3903 #define MAX_ZOMBIES 10
3904 static Lisp_Object zombies[MAX_ZOMBIES];
3906 /* Number of zombie objects. */
3908 static int nzombies;
3910 /* Number of garbage collections. */
3912 static int ngcs;
3914 /* Average percentage of zombies per collection. */
3916 static double avg_zombies;
3918 /* Max. number of live and zombie objects. */
3920 static int max_live, max_zombies;
3922 /* Average number of live objects per GC. */
3924 static double avg_live;
3926 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
3927 doc: /* Show information about live and zombie objects. */)
3928 (void)
3930 Lisp_Object args[8], zombie_list = Qnil;
3931 int i;
3932 for (i = 0; i < nzombies; i++)
3933 zombie_list = Fcons (zombies[i], zombie_list);
3934 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
3935 args[1] = make_number (ngcs);
3936 args[2] = make_float (avg_live);
3937 args[3] = make_float (avg_zombies);
3938 args[4] = make_float (avg_zombies / avg_live / 100);
3939 args[5] = make_number (max_live);
3940 args[6] = make_number (max_zombies);
3941 args[7] = zombie_list;
3942 return Fmessage (8, args);
3945 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3948 /* Mark OBJ if we can prove it's a Lisp_Object. */
3950 static INLINE void
3951 mark_maybe_object (Lisp_Object obj)
3953 void *po;
3954 struct mem_node *m;
3956 if (INTEGERP (obj))
3957 return;
3959 po = (void *) XPNTR (obj);
3960 m = mem_find (po);
3962 if (m != MEM_NIL)
3964 int mark_p = 0;
3966 switch (XTYPE (obj))
3968 case Lisp_String:
3969 mark_p = (live_string_p (m, po)
3970 && !STRING_MARKED_P ((struct Lisp_String *) po));
3971 break;
3973 case Lisp_Cons:
3974 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
3975 break;
3977 case Lisp_Symbol:
3978 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
3979 break;
3981 case Lisp_Float:
3982 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
3983 break;
3985 case Lisp_Vectorlike:
3986 /* Note: can't check BUFFERP before we know it's a
3987 buffer because checking that dereferences the pointer
3988 PO which might point anywhere. */
3989 if (live_vector_p (m, po))
3990 mark_p = !SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
3991 else if (live_buffer_p (m, po))
3992 mark_p = BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
3993 break;
3995 case Lisp_Misc:
3996 mark_p = (live_misc_p (m, po) && !XMISCANY (obj)->gcmarkbit);
3997 break;
3999 default:
4000 break;
4003 if (mark_p)
4005 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4006 if (nzombies < MAX_ZOMBIES)
4007 zombies[nzombies] = obj;
4008 ++nzombies;
4009 #endif
4010 mark_object (obj);
4016 /* If P points to Lisp data, mark that as live if it isn't already
4017 marked. */
4019 static INLINE void
4020 mark_maybe_pointer (void *p)
4022 struct mem_node *m;
4024 /* Quickly rule out some values which can't point to Lisp data. */
4025 if ((EMACS_INT) p %
4026 #ifdef USE_LSB_TAG
4027 8 /* USE_LSB_TAG needs Lisp data to be aligned on multiples of 8. */
4028 #else
4029 2 /* We assume that Lisp data is aligned on even addresses. */
4030 #endif
4032 return;
4034 m = mem_find (p);
4035 if (m != MEM_NIL)
4037 Lisp_Object obj = Qnil;
4039 switch (m->type)
4041 case MEM_TYPE_NON_LISP:
4042 /* Nothing to do; not a pointer to Lisp memory. */
4043 break;
4045 case MEM_TYPE_BUFFER:
4046 if (live_buffer_p (m, p) && !VECTOR_MARKED_P((struct buffer *)p))
4047 XSETVECTOR (obj, p);
4048 break;
4050 case MEM_TYPE_CONS:
4051 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4052 XSETCONS (obj, p);
4053 break;
4055 case MEM_TYPE_STRING:
4056 if (live_string_p (m, p)
4057 && !STRING_MARKED_P ((struct Lisp_String *) p))
4058 XSETSTRING (obj, p);
4059 break;
4061 case MEM_TYPE_MISC:
4062 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4063 XSETMISC (obj, p);
4064 break;
4066 case MEM_TYPE_SYMBOL:
4067 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4068 XSETSYMBOL (obj, p);
4069 break;
4071 case MEM_TYPE_FLOAT:
4072 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4073 XSETFLOAT (obj, p);
4074 break;
4076 case MEM_TYPE_VECTORLIKE:
4077 if (live_vector_p (m, p))
4079 Lisp_Object tem;
4080 XSETVECTOR (tem, p);
4081 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4082 obj = tem;
4084 break;
4086 default:
4087 abort ();
4090 if (!NILP (obj))
4091 mark_object (obj);
4096 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4097 or END+OFFSET..START. */
4099 static void
4100 mark_memory (void *start, void *end, int offset)
4102 Lisp_Object *p;
4103 void **pp;
4105 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4106 nzombies = 0;
4107 #endif
4109 /* Make START the pointer to the start of the memory region,
4110 if it isn't already. */
4111 if (end < start)
4113 void *tem = start;
4114 start = end;
4115 end = tem;
4118 /* Mark Lisp_Objects. */
4119 for (p = (Lisp_Object *) ((char *) start + offset); (void *) p < end; ++p)
4120 mark_maybe_object (*p);
4122 /* Mark Lisp data pointed to. This is necessary because, in some
4123 situations, the C compiler optimizes Lisp objects away, so that
4124 only a pointer to them remains. Example:
4126 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4129 Lisp_Object obj = build_string ("test");
4130 struct Lisp_String *s = XSTRING (obj);
4131 Fgarbage_collect ();
4132 fprintf (stderr, "test `%s'\n", s->data);
4133 return Qnil;
4136 Here, `obj' isn't really used, and the compiler optimizes it
4137 away. The only reference to the life string is through the
4138 pointer `s'. */
4140 for (pp = (void **) ((char *) start + offset); (void *) pp < end; ++pp)
4141 mark_maybe_pointer (*pp);
4144 /* setjmp will work with GCC unless NON_SAVING_SETJMP is defined in
4145 the GCC system configuration. In gcc 3.2, the only systems for
4146 which this is so are i386-sco5 non-ELF, i386-sysv3 (maybe included
4147 by others?) and ns32k-pc532-min. */
4149 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4151 static int setjmp_tested_p, longjmps_done;
4153 #define SETJMP_WILL_LIKELY_WORK "\
4155 Emacs garbage collector has been changed to use conservative stack\n\
4156 marking. Emacs has determined that the method it uses to do the\n\
4157 marking will likely work on your system, but this isn't sure.\n\
4159 If you are a system-programmer, or can get the help of a local wizard\n\
4160 who is, please take a look at the function mark_stack in alloc.c, and\n\
4161 verify that the methods used are appropriate for your system.\n\
4163 Please mail the result to <emacs-devel@gnu.org>.\n\
4166 #define SETJMP_WILL_NOT_WORK "\
4168 Emacs garbage collector has been changed to use conservative stack\n\
4169 marking. Emacs has determined that the default method it uses to do the\n\
4170 marking will not work on your system. We will need a system-dependent\n\
4171 solution for your system.\n\
4173 Please take a look at the function mark_stack in alloc.c, and\n\
4174 try to find a way to make it work on your system.\n\
4176 Note that you may get false negatives, depending on the compiler.\n\
4177 In particular, you need to use -O with GCC for this test.\n\
4179 Please mail the result to <emacs-devel@gnu.org>.\n\
4183 /* Perform a quick check if it looks like setjmp saves registers in a
4184 jmp_buf. Print a message to stderr saying so. When this test
4185 succeeds, this is _not_ a proof that setjmp is sufficient for
4186 conservative stack marking. Only the sources or a disassembly
4187 can prove that. */
4189 static void
4190 test_setjmp (void)
4192 char buf[10];
4193 register int x;
4194 jmp_buf jbuf;
4195 int result = 0;
4197 /* Arrange for X to be put in a register. */
4198 sprintf (buf, "1");
4199 x = strlen (buf);
4200 x = 2 * x - 1;
4202 setjmp (jbuf);
4203 if (longjmps_done == 1)
4205 /* Came here after the longjmp at the end of the function.
4207 If x == 1, the longjmp has restored the register to its
4208 value before the setjmp, and we can hope that setjmp
4209 saves all such registers in the jmp_buf, although that
4210 isn't sure.
4212 For other values of X, either something really strange is
4213 taking place, or the setjmp just didn't save the register. */
4215 if (x == 1)
4216 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4217 else
4219 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4220 exit (1);
4224 ++longjmps_done;
4225 x = 2;
4226 if (longjmps_done == 1)
4227 longjmp (jbuf, 1);
4230 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4233 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4235 /* Abort if anything GCPRO'd doesn't survive the GC. */
4237 static void
4238 check_gcpros (void)
4240 struct gcpro *p;
4241 int i;
4243 for (p = gcprolist; p; p = p->next)
4244 for (i = 0; i < p->nvars; ++i)
4245 if (!survives_gc_p (p->var[i]))
4246 /* FIXME: It's not necessarily a bug. It might just be that the
4247 GCPRO is unnecessary or should release the object sooner. */
4248 abort ();
4251 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4253 static void
4254 dump_zombies (void)
4256 int i;
4258 fprintf (stderr, "\nZombies kept alive = %d:\n", nzombies);
4259 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
4261 fprintf (stderr, " %d = ", i);
4262 debug_print (zombies[i]);
4266 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4269 /* Mark live Lisp objects on the C stack.
4271 There are several system-dependent problems to consider when
4272 porting this to new architectures:
4274 Processor Registers
4276 We have to mark Lisp objects in CPU registers that can hold local
4277 variables or are used to pass parameters.
4279 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4280 something that either saves relevant registers on the stack, or
4281 calls mark_maybe_object passing it each register's contents.
4283 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4284 implementation assumes that calling setjmp saves registers we need
4285 to see in a jmp_buf which itself lies on the stack. This doesn't
4286 have to be true! It must be verified for each system, possibly
4287 by taking a look at the source code of setjmp.
4289 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4290 can use it as a machine independent method to store all registers
4291 to the stack. In this case the macros described in the previous
4292 two paragraphs are not used.
4294 Stack Layout
4296 Architectures differ in the way their processor stack is organized.
4297 For example, the stack might look like this
4299 +----------------+
4300 | Lisp_Object | size = 4
4301 +----------------+
4302 | something else | size = 2
4303 +----------------+
4304 | Lisp_Object | size = 4
4305 +----------------+
4306 | ... |
4308 In such a case, not every Lisp_Object will be aligned equally. To
4309 find all Lisp_Object on the stack it won't be sufficient to walk
4310 the stack in steps of 4 bytes. Instead, two passes will be
4311 necessary, one starting at the start of the stack, and a second
4312 pass starting at the start of the stack + 2. Likewise, if the
4313 minimal alignment of Lisp_Objects on the stack is 1, four passes
4314 would be necessary, each one starting with one byte more offset
4315 from the stack start.
4317 The current code assumes by default that Lisp_Objects are aligned
4318 equally on the stack. */
4320 static void
4321 mark_stack (void)
4323 int i;
4324 void *end;
4326 #ifdef HAVE___BUILTIN_UNWIND_INIT
4327 /* Force callee-saved registers and register windows onto the stack.
4328 This is the preferred method if available, obviating the need for
4329 machine dependent methods. */
4330 __builtin_unwind_init ();
4331 end = &end;
4332 #else /* not HAVE___BUILTIN_UNWIND_INIT */
4333 #ifndef GC_SAVE_REGISTERS_ON_STACK
4334 /* jmp_buf may not be aligned enough on darwin-ppc64 */
4335 union aligned_jmpbuf {
4336 Lisp_Object o;
4337 jmp_buf j;
4338 } j;
4339 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
4340 #endif
4341 /* This trick flushes the register windows so that all the state of
4342 the process is contained in the stack. */
4343 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
4344 needed on ia64 too. See mach_dep.c, where it also says inline
4345 assembler doesn't work with relevant proprietary compilers. */
4346 #ifdef __sparc__
4347 #if defined (__sparc64__) && defined (__FreeBSD__)
4348 /* FreeBSD does not have a ta 3 handler. */
4349 asm ("flushw");
4350 #else
4351 asm ("ta 3");
4352 #endif
4353 #endif
4355 /* Save registers that we need to see on the stack. We need to see
4356 registers used to hold register variables and registers used to
4357 pass parameters. */
4358 #ifdef GC_SAVE_REGISTERS_ON_STACK
4359 GC_SAVE_REGISTERS_ON_STACK (end);
4360 #else /* not GC_SAVE_REGISTERS_ON_STACK */
4362 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
4363 setjmp will definitely work, test it
4364 and print a message with the result
4365 of the test. */
4366 if (!setjmp_tested_p)
4368 setjmp_tested_p = 1;
4369 test_setjmp ();
4371 #endif /* GC_SETJMP_WORKS */
4373 setjmp (j.j);
4374 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
4375 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
4376 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
4378 /* This assumes that the stack is a contiguous region in memory. If
4379 that's not the case, something has to be done here to iterate
4380 over the stack segments. */
4381 #ifndef GC_LISP_OBJECT_ALIGNMENT
4382 #ifdef __GNUC__
4383 #define GC_LISP_OBJECT_ALIGNMENT __alignof__ (Lisp_Object)
4384 #else
4385 #define GC_LISP_OBJECT_ALIGNMENT sizeof (Lisp_Object)
4386 #endif
4387 #endif
4388 for (i = 0; i < sizeof (Lisp_Object); i += GC_LISP_OBJECT_ALIGNMENT)
4389 mark_memory (stack_base, end, i);
4390 /* Allow for marking a secondary stack, like the register stack on the
4391 ia64. */
4392 #ifdef GC_MARK_SECONDARY_STACK
4393 GC_MARK_SECONDARY_STACK ();
4394 #endif
4396 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4397 check_gcpros ();
4398 #endif
4401 #endif /* GC_MARK_STACK != 0 */
4404 /* Determine whether it is safe to access memory at address P. */
4405 static int
4406 valid_pointer_p (void *p)
4408 #ifdef WINDOWSNT
4409 return w32_valid_pointer_p (p, 16);
4410 #else
4411 int fd;
4413 /* Obviously, we cannot just access it (we would SEGV trying), so we
4414 trick the o/s to tell us whether p is a valid pointer.
4415 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4416 not validate p in that case. */
4418 if ((fd = emacs_open ("__Valid__Lisp__Object__", O_CREAT | O_WRONLY | O_TRUNC, 0666)) >= 0)
4420 int valid = (emacs_write (fd, (char *)p, 16) == 16);
4421 emacs_close (fd);
4422 unlink ("__Valid__Lisp__Object__");
4423 return valid;
4426 return -1;
4427 #endif
4430 /* Return 1 if OBJ is a valid lisp object.
4431 Return 0 if OBJ is NOT a valid lisp object.
4432 Return -1 if we cannot validate OBJ.
4433 This function can be quite slow,
4434 so it should only be used in code for manual debugging. */
4437 valid_lisp_object_p (Lisp_Object obj)
4439 void *p;
4440 #if GC_MARK_STACK
4441 struct mem_node *m;
4442 #endif
4444 if (INTEGERP (obj))
4445 return 1;
4447 p = (void *) XPNTR (obj);
4448 if (PURE_POINTER_P (p))
4449 return 1;
4451 #if !GC_MARK_STACK
4452 return valid_pointer_p (p);
4453 #else
4455 m = mem_find (p);
4457 if (m == MEM_NIL)
4459 int valid = valid_pointer_p (p);
4460 if (valid <= 0)
4461 return valid;
4463 if (SUBRP (obj))
4464 return 1;
4466 return 0;
4469 switch (m->type)
4471 case MEM_TYPE_NON_LISP:
4472 return 0;
4474 case MEM_TYPE_BUFFER:
4475 return live_buffer_p (m, p);
4477 case MEM_TYPE_CONS:
4478 return live_cons_p (m, p);
4480 case MEM_TYPE_STRING:
4481 return live_string_p (m, p);
4483 case MEM_TYPE_MISC:
4484 return live_misc_p (m, p);
4486 case MEM_TYPE_SYMBOL:
4487 return live_symbol_p (m, p);
4489 case MEM_TYPE_FLOAT:
4490 return live_float_p (m, p);
4492 case MEM_TYPE_VECTORLIKE:
4493 return live_vector_p (m, p);
4495 default:
4496 break;
4499 return 0;
4500 #endif
4506 /***********************************************************************
4507 Pure Storage Management
4508 ***********************************************************************/
4510 /* Allocate room for SIZE bytes from pure Lisp storage and return a
4511 pointer to it. TYPE is the Lisp type for which the memory is
4512 allocated. TYPE < 0 means it's not used for a Lisp object. */
4514 static POINTER_TYPE *
4515 pure_alloc (size_t size, int type)
4517 POINTER_TYPE *result;
4518 #ifdef USE_LSB_TAG
4519 size_t alignment = (1 << GCTYPEBITS);
4520 #else
4521 size_t alignment = sizeof (EMACS_INT);
4523 /* Give Lisp_Floats an extra alignment. */
4524 if (type == Lisp_Float)
4526 #if defined __GNUC__ && __GNUC__ >= 2
4527 alignment = __alignof (struct Lisp_Float);
4528 #else
4529 alignment = sizeof (struct Lisp_Float);
4530 #endif
4532 #endif
4534 again:
4535 if (type >= 0)
4537 /* Allocate space for a Lisp object from the beginning of the free
4538 space with taking account of alignment. */
4539 result = ALIGN (purebeg + pure_bytes_used_lisp, alignment);
4540 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
4542 else
4544 /* Allocate space for a non-Lisp object from the end of the free
4545 space. */
4546 pure_bytes_used_non_lisp += size;
4547 result = purebeg + pure_size - pure_bytes_used_non_lisp;
4549 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
4551 if (pure_bytes_used <= pure_size)
4552 return result;
4554 /* Don't allocate a large amount here,
4555 because it might get mmap'd and then its address
4556 might not be usable. */
4557 purebeg = (char *) xmalloc (10000);
4558 pure_size = 10000;
4559 pure_bytes_used_before_overflow += pure_bytes_used - size;
4560 pure_bytes_used = 0;
4561 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
4562 goto again;
4566 /* Print a warning if PURESIZE is too small. */
4568 void
4569 check_pure_size (void)
4571 if (pure_bytes_used_before_overflow)
4572 message ("emacs:0:Pure Lisp storage overflow (approx. %d bytes needed)",
4573 (int) (pure_bytes_used + pure_bytes_used_before_overflow));
4577 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
4578 the non-Lisp data pool of the pure storage, and return its start
4579 address. Return NULL if not found. */
4581 static char *
4582 find_string_data_in_pure (const char *data, EMACS_INT nbytes)
4584 int i;
4585 EMACS_INT skip, bm_skip[256], last_char_skip, infinity, start, start_max;
4586 const unsigned char *p;
4587 char *non_lisp_beg;
4589 if (pure_bytes_used_non_lisp < nbytes + 1)
4590 return NULL;
4592 /* Set up the Boyer-Moore table. */
4593 skip = nbytes + 1;
4594 for (i = 0; i < 256; i++)
4595 bm_skip[i] = skip;
4597 p = (const unsigned char *) data;
4598 while (--skip > 0)
4599 bm_skip[*p++] = skip;
4601 last_char_skip = bm_skip['\0'];
4603 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
4604 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
4606 /* See the comments in the function `boyer_moore' (search.c) for the
4607 use of `infinity'. */
4608 infinity = pure_bytes_used_non_lisp + 1;
4609 bm_skip['\0'] = infinity;
4611 p = (const unsigned char *) non_lisp_beg + nbytes;
4612 start = 0;
4615 /* Check the last character (== '\0'). */
4618 start += bm_skip[*(p + start)];
4620 while (start <= start_max);
4622 if (start < infinity)
4623 /* Couldn't find the last character. */
4624 return NULL;
4626 /* No less than `infinity' means we could find the last
4627 character at `p[start - infinity]'. */
4628 start -= infinity;
4630 /* Check the remaining characters. */
4631 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
4632 /* Found. */
4633 return non_lisp_beg + start;
4635 start += last_char_skip;
4637 while (start <= start_max);
4639 return NULL;
4643 /* Return a string allocated in pure space. DATA is a buffer holding
4644 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
4645 non-zero means make the result string multibyte.
4647 Must get an error if pure storage is full, since if it cannot hold
4648 a large string it may be able to hold conses that point to that
4649 string; then the string is not protected from gc. */
4651 Lisp_Object
4652 make_pure_string (const char *data,
4653 EMACS_INT nchars, EMACS_INT nbytes, int multibyte)
4655 Lisp_Object string;
4656 struct Lisp_String *s;
4658 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
4659 s->data = (unsigned char *) find_string_data_in_pure (data, nbytes);
4660 if (s->data == NULL)
4662 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
4663 memcpy (s->data, data, nbytes);
4664 s->data[nbytes] = '\0';
4666 s->size = nchars;
4667 s->size_byte = multibyte ? nbytes : -1;
4668 s->intervals = NULL_INTERVAL;
4669 XSETSTRING (string, s);
4670 return string;
4673 /* Return a string a string allocated in pure space. Do not allocate
4674 the string data, just point to DATA. */
4676 Lisp_Object
4677 make_pure_c_string (const char *data)
4679 Lisp_Object string;
4680 struct Lisp_String *s;
4681 EMACS_INT nchars = strlen (data);
4683 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
4684 s->size = nchars;
4685 s->size_byte = -1;
4686 s->data = (unsigned char *) data;
4687 s->intervals = NULL_INTERVAL;
4688 XSETSTRING (string, s);
4689 return string;
4692 /* Return a cons allocated from pure space. Give it pure copies
4693 of CAR as car and CDR as cdr. */
4695 Lisp_Object
4696 pure_cons (Lisp_Object car, Lisp_Object cdr)
4698 register Lisp_Object new;
4699 struct Lisp_Cons *p;
4701 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
4702 XSETCONS (new, p);
4703 XSETCAR (new, Fpurecopy (car));
4704 XSETCDR (new, Fpurecopy (cdr));
4705 return new;
4709 /* Value is a float object with value NUM allocated from pure space. */
4711 static Lisp_Object
4712 make_pure_float (double num)
4714 register Lisp_Object new;
4715 struct Lisp_Float *p;
4717 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
4718 XSETFLOAT (new, p);
4719 XFLOAT_INIT (new, num);
4720 return new;
4724 /* Return a vector with room for LEN Lisp_Objects allocated from
4725 pure space. */
4727 Lisp_Object
4728 make_pure_vector (EMACS_INT len)
4730 Lisp_Object new;
4731 struct Lisp_Vector *p;
4732 size_t size = sizeof *p + (len - 1) * sizeof (Lisp_Object);
4734 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
4735 XSETVECTOR (new, p);
4736 XVECTOR (new)->size = len;
4737 return new;
4741 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
4742 doc: /* Make a copy of object OBJ in pure storage.
4743 Recursively copies contents of vectors and cons cells.
4744 Does not copy symbols. Copies strings without text properties. */)
4745 (register Lisp_Object obj)
4747 if (NILP (Vpurify_flag))
4748 return obj;
4750 if (PURE_POINTER_P (XPNTR (obj)))
4751 return obj;
4753 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
4755 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
4756 if (!NILP (tmp))
4757 return tmp;
4760 if (CONSP (obj))
4761 obj = pure_cons (XCAR (obj), XCDR (obj));
4762 else if (FLOATP (obj))
4763 obj = make_pure_float (XFLOAT_DATA (obj));
4764 else if (STRINGP (obj))
4765 obj = make_pure_string (SSDATA (obj), SCHARS (obj),
4766 SBYTES (obj),
4767 STRING_MULTIBYTE (obj));
4768 else if (COMPILEDP (obj) || VECTORP (obj))
4770 register struct Lisp_Vector *vec;
4771 register EMACS_INT i;
4772 EMACS_INT size;
4774 size = XVECTOR (obj)->size;
4775 if (size & PSEUDOVECTOR_FLAG)
4776 size &= PSEUDOVECTOR_SIZE_MASK;
4777 vec = XVECTOR (make_pure_vector (size));
4778 for (i = 0; i < size; i++)
4779 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
4780 if (COMPILEDP (obj))
4782 XSETPVECTYPE (vec, PVEC_COMPILED);
4783 XSETCOMPILED (obj, vec);
4785 else
4786 XSETVECTOR (obj, vec);
4788 else if (MARKERP (obj))
4789 error ("Attempt to copy a marker to pure storage");
4790 else
4791 /* Not purified, don't hash-cons. */
4792 return obj;
4794 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
4795 Fputhash (obj, obj, Vpurify_flag);
4797 return obj;
4802 /***********************************************************************
4803 Protection from GC
4804 ***********************************************************************/
4806 /* Put an entry in staticvec, pointing at the variable with address
4807 VARADDRESS. */
4809 void
4810 staticpro (Lisp_Object *varaddress)
4812 staticvec[staticidx++] = varaddress;
4813 if (staticidx >= NSTATICS)
4814 abort ();
4818 /***********************************************************************
4819 Protection from GC
4820 ***********************************************************************/
4822 /* Temporarily prevent garbage collection. */
4825 inhibit_garbage_collection (void)
4827 int count = SPECPDL_INDEX ();
4828 int nbits = min (VALBITS, BITS_PER_INT);
4830 specbind (Qgc_cons_threshold, make_number (((EMACS_INT) 1 << (nbits - 1)) - 1));
4831 return count;
4835 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
4836 doc: /* Reclaim storage for Lisp objects no longer needed.
4837 Garbage collection happens automatically if you cons more than
4838 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
4839 `garbage-collect' normally returns a list with info on amount of space in use:
4840 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
4841 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
4842 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)
4843 (USED-STRINGS . FREE-STRINGS))
4844 However, if there was overflow in pure space, `garbage-collect'
4845 returns nil, because real GC can't be done. */)
4846 (void)
4848 register struct specbinding *bind;
4849 char stack_top_variable;
4850 register int i;
4851 int message_p;
4852 Lisp_Object total[8];
4853 int count = SPECPDL_INDEX ();
4854 EMACS_TIME t1, t2, t3;
4856 if (abort_on_gc)
4857 abort ();
4859 /* Can't GC if pure storage overflowed because we can't determine
4860 if something is a pure object or not. */
4861 if (pure_bytes_used_before_overflow)
4862 return Qnil;
4864 CHECK_CONS_LIST ();
4866 /* Don't keep undo information around forever.
4867 Do this early on, so it is no problem if the user quits. */
4869 register struct buffer *nextb = all_buffers;
4871 while (nextb)
4873 /* If a buffer's undo list is Qt, that means that undo is
4874 turned off in that buffer. Calling truncate_undo_list on
4875 Qt tends to return NULL, which effectively turns undo back on.
4876 So don't call truncate_undo_list if undo_list is Qt. */
4877 if (! NILP (nextb->BUFFER_INTERNAL_FIELD (name)) && ! EQ (nextb->BUFFER_INTERNAL_FIELD (undo_list), Qt))
4878 truncate_undo_list (nextb);
4880 /* Shrink buffer gaps, but skip indirect and dead buffers. */
4881 if (nextb->base_buffer == 0 && !NILP (nextb->BUFFER_INTERNAL_FIELD (name))
4882 && ! nextb->text->inhibit_shrinking)
4884 /* If a buffer's gap size is more than 10% of the buffer
4885 size, or larger than 2000 bytes, then shrink it
4886 accordingly. Keep a minimum size of 20 bytes. */
4887 int size = min (2000, max (20, (nextb->text->z_byte / 10)));
4889 if (nextb->text->gap_size > size)
4891 struct buffer *save_current = current_buffer;
4892 current_buffer = nextb;
4893 make_gap (-(nextb->text->gap_size - size));
4894 current_buffer = save_current;
4898 nextb = nextb->next;
4902 EMACS_GET_TIME (t1);
4904 /* In case user calls debug_print during GC,
4905 don't let that cause a recursive GC. */
4906 consing_since_gc = 0;
4908 /* Save what's currently displayed in the echo area. */
4909 message_p = push_message ();
4910 record_unwind_protect (pop_message_unwind, Qnil);
4912 /* Save a copy of the contents of the stack, for debugging. */
4913 #if MAX_SAVE_STACK > 0
4914 if (NILP (Vpurify_flag))
4916 i = &stack_top_variable - stack_bottom;
4917 if (i < 0) i = -i;
4918 if (i < MAX_SAVE_STACK)
4920 if (stack_copy == 0)
4921 stack_copy = (char *) xmalloc (stack_copy_size = i);
4922 else if (stack_copy_size < i)
4923 stack_copy = (char *) xrealloc (stack_copy, (stack_copy_size = i));
4924 if (stack_copy)
4926 if ((EMACS_INT) (&stack_top_variable - stack_bottom) > 0)
4927 memcpy (stack_copy, stack_bottom, i);
4928 else
4929 memcpy (stack_copy, &stack_top_variable, i);
4933 #endif /* MAX_SAVE_STACK > 0 */
4935 if (garbage_collection_messages)
4936 message1_nolog ("Garbage collecting...");
4938 BLOCK_INPUT;
4940 shrink_regexp_cache ();
4942 gc_in_progress = 1;
4944 /* clear_marks (); */
4946 /* Mark all the special slots that serve as the roots of accessibility. */
4948 for (i = 0; i < staticidx; i++)
4949 mark_object (*staticvec[i]);
4951 for (bind = specpdl; bind != specpdl_ptr; bind++)
4953 mark_object (bind->symbol);
4954 mark_object (bind->old_value);
4956 mark_terminals ();
4957 mark_kboards ();
4958 mark_ttys ();
4960 #ifdef USE_GTK
4962 extern void xg_mark_data (void);
4963 xg_mark_data ();
4965 #endif
4967 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
4968 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
4969 mark_stack ();
4970 #else
4972 register struct gcpro *tail;
4973 for (tail = gcprolist; tail; tail = tail->next)
4974 for (i = 0; i < tail->nvars; i++)
4975 mark_object (tail->var[i]);
4977 mark_byte_stack ();
4979 struct catchtag *catch;
4980 struct handler *handler;
4982 for (catch = catchlist; catch; catch = catch->next)
4984 mark_object (catch->tag);
4985 mark_object (catch->val);
4987 for (handler = handlerlist; handler; handler = handler->next)
4989 mark_object (handler->handler);
4990 mark_object (handler->var);
4993 mark_backtrace ();
4994 #endif
4996 #ifdef HAVE_WINDOW_SYSTEM
4997 mark_fringe_data ();
4998 #endif
5000 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5001 mark_stack ();
5002 #endif
5004 /* Everything is now marked, except for the things that require special
5005 finalization, i.e. the undo_list.
5006 Look thru every buffer's undo list
5007 for elements that update markers that were not marked,
5008 and delete them. */
5010 register struct buffer *nextb = all_buffers;
5012 while (nextb)
5014 /* If a buffer's undo list is Qt, that means that undo is
5015 turned off in that buffer. Calling truncate_undo_list on
5016 Qt tends to return NULL, which effectively turns undo back on.
5017 So don't call truncate_undo_list if undo_list is Qt. */
5018 if (! EQ (nextb->BUFFER_INTERNAL_FIELD (undo_list), Qt))
5020 Lisp_Object tail, prev;
5021 tail = nextb->BUFFER_INTERNAL_FIELD (undo_list);
5022 prev = Qnil;
5023 while (CONSP (tail))
5025 if (CONSP (XCAR (tail))
5026 && MARKERP (XCAR (XCAR (tail)))
5027 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5029 if (NILP (prev))
5030 nextb->BUFFER_INTERNAL_FIELD (undo_list) = tail = XCDR (tail);
5031 else
5033 tail = XCDR (tail);
5034 XSETCDR (prev, tail);
5037 else
5039 prev = tail;
5040 tail = XCDR (tail);
5044 /* Now that we have stripped the elements that need not be in the
5045 undo_list any more, we can finally mark the list. */
5046 mark_object (nextb->BUFFER_INTERNAL_FIELD (undo_list));
5048 nextb = nextb->next;
5052 gc_sweep ();
5054 /* Clear the mark bits that we set in certain root slots. */
5056 unmark_byte_stack ();
5057 VECTOR_UNMARK (&buffer_defaults);
5058 VECTOR_UNMARK (&buffer_local_symbols);
5060 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
5061 dump_zombies ();
5062 #endif
5064 UNBLOCK_INPUT;
5066 CHECK_CONS_LIST ();
5068 /* clear_marks (); */
5069 gc_in_progress = 0;
5071 consing_since_gc = 0;
5072 if (gc_cons_threshold < 10000)
5073 gc_cons_threshold = 10000;
5075 if (FLOATP (Vgc_cons_percentage))
5076 { /* Set gc_cons_combined_threshold. */
5077 EMACS_INT tot = 0;
5079 tot += total_conses * sizeof (struct Lisp_Cons);
5080 tot += total_symbols * sizeof (struct Lisp_Symbol);
5081 tot += total_markers * sizeof (union Lisp_Misc);
5082 tot += total_string_size;
5083 tot += total_vector_size * sizeof (Lisp_Object);
5084 tot += total_floats * sizeof (struct Lisp_Float);
5085 tot += total_intervals * sizeof (struct interval);
5086 tot += total_strings * sizeof (struct Lisp_String);
5088 gc_relative_threshold = tot * XFLOAT_DATA (Vgc_cons_percentage);
5090 else
5091 gc_relative_threshold = 0;
5093 if (garbage_collection_messages)
5095 if (message_p || minibuf_level > 0)
5096 restore_message ();
5097 else
5098 message1_nolog ("Garbage collecting...done");
5101 unbind_to (count, Qnil);
5103 total[0] = Fcons (make_number (total_conses),
5104 make_number (total_free_conses));
5105 total[1] = Fcons (make_number (total_symbols),
5106 make_number (total_free_symbols));
5107 total[2] = Fcons (make_number (total_markers),
5108 make_number (total_free_markers));
5109 total[3] = make_number (total_string_size);
5110 total[4] = make_number (total_vector_size);
5111 total[5] = Fcons (make_number (total_floats),
5112 make_number (total_free_floats));
5113 total[6] = Fcons (make_number (total_intervals),
5114 make_number (total_free_intervals));
5115 total[7] = Fcons (make_number (total_strings),
5116 make_number (total_free_strings));
5118 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5120 /* Compute average percentage of zombies. */
5121 double nlive = 0;
5123 for (i = 0; i < 7; ++i)
5124 if (CONSP (total[i]))
5125 nlive += XFASTINT (XCAR (total[i]));
5127 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
5128 max_live = max (nlive, max_live);
5129 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
5130 max_zombies = max (nzombies, max_zombies);
5131 ++ngcs;
5133 #endif
5135 if (!NILP (Vpost_gc_hook))
5137 int gc_count = inhibit_garbage_collection ();
5138 safe_run_hooks (Qpost_gc_hook);
5139 unbind_to (gc_count, Qnil);
5142 /* Accumulate statistics. */
5143 EMACS_GET_TIME (t2);
5144 EMACS_SUB_TIME (t3, t2, t1);
5145 if (FLOATP (Vgc_elapsed))
5146 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed) +
5147 EMACS_SECS (t3) +
5148 EMACS_USECS (t3) * 1.0e-6);
5149 gcs_done++;
5151 return Flist (sizeof total / sizeof *total, total);
5155 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5156 only interesting objects referenced from glyphs are strings. */
5158 static void
5159 mark_glyph_matrix (struct glyph_matrix *matrix)
5161 struct glyph_row *row = matrix->rows;
5162 struct glyph_row *end = row + matrix->nrows;
5164 for (; row < end; ++row)
5165 if (row->enabled_p)
5167 int area;
5168 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
5170 struct glyph *glyph = row->glyphs[area];
5171 struct glyph *end_glyph = glyph + row->used[area];
5173 for (; glyph < end_glyph; ++glyph)
5174 if (STRINGP (glyph->object)
5175 && !STRING_MARKED_P (XSTRING (glyph->object)))
5176 mark_object (glyph->object);
5182 /* Mark Lisp faces in the face cache C. */
5184 static void
5185 mark_face_cache (struct face_cache *c)
5187 if (c)
5189 int i, j;
5190 for (i = 0; i < c->used; ++i)
5192 struct face *face = FACE_FROM_ID (c->f, i);
5194 if (face)
5196 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
5197 mark_object (face->lface[j]);
5205 /* Mark reference to a Lisp_Object.
5206 If the object referred to has not been seen yet, recursively mark
5207 all the references contained in it. */
5209 #define LAST_MARKED_SIZE 500
5210 static Lisp_Object last_marked[LAST_MARKED_SIZE];
5211 int last_marked_index;
5213 /* For debugging--call abort when we cdr down this many
5214 links of a list, in mark_object. In debugging,
5215 the call to abort will hit a breakpoint.
5216 Normally this is zero and the check never goes off. */
5217 static int mark_object_loop_halt;
5219 static void
5220 mark_vectorlike (struct Lisp_Vector *ptr)
5222 register EMACS_UINT size = ptr->size;
5223 register EMACS_UINT i;
5225 eassert (!VECTOR_MARKED_P (ptr));
5226 VECTOR_MARK (ptr); /* Else mark it */
5227 if (size & PSEUDOVECTOR_FLAG)
5228 size &= PSEUDOVECTOR_SIZE_MASK;
5230 /* Note that this size is not the memory-footprint size, but only
5231 the number of Lisp_Object fields that we should trace.
5232 The distinction is used e.g. by Lisp_Process which places extra
5233 non-Lisp_Object fields at the end of the structure. */
5234 for (i = 0; i < size; i++) /* and then mark its elements */
5235 mark_object (ptr->contents[i]);
5238 /* Like mark_vectorlike but optimized for char-tables (and
5239 sub-char-tables) assuming that the contents are mostly integers or
5240 symbols. */
5242 static void
5243 mark_char_table (struct Lisp_Vector *ptr)
5245 register EMACS_UINT size = ptr->size & PSEUDOVECTOR_SIZE_MASK;
5246 register EMACS_UINT i;
5248 eassert (!VECTOR_MARKED_P (ptr));
5249 VECTOR_MARK (ptr);
5250 for (i = 0; i < size; i++)
5252 Lisp_Object val = ptr->contents[i];
5254 if (INTEGERP (val) || (SYMBOLP (val) && XSYMBOL (val)->gcmarkbit))
5255 continue;
5256 if (SUB_CHAR_TABLE_P (val))
5258 if (! VECTOR_MARKED_P (XVECTOR (val)))
5259 mark_char_table (XVECTOR (val));
5261 else
5262 mark_object (val);
5266 void
5267 mark_object (Lisp_Object arg)
5269 register Lisp_Object obj = arg;
5270 #ifdef GC_CHECK_MARKED_OBJECTS
5271 void *po;
5272 struct mem_node *m;
5273 #endif
5274 int cdr_count = 0;
5276 loop:
5278 if (PURE_POINTER_P (XPNTR (obj)))
5279 return;
5281 last_marked[last_marked_index++] = obj;
5282 if (last_marked_index == LAST_MARKED_SIZE)
5283 last_marked_index = 0;
5285 /* Perform some sanity checks on the objects marked here. Abort if
5286 we encounter an object we know is bogus. This increases GC time
5287 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
5288 #ifdef GC_CHECK_MARKED_OBJECTS
5290 po = (void *) XPNTR (obj);
5292 /* Check that the object pointed to by PO is known to be a Lisp
5293 structure allocated from the heap. */
5294 #define CHECK_ALLOCATED() \
5295 do { \
5296 m = mem_find (po); \
5297 if (m == MEM_NIL) \
5298 abort (); \
5299 } while (0)
5301 /* Check that the object pointed to by PO is live, using predicate
5302 function LIVEP. */
5303 #define CHECK_LIVE(LIVEP) \
5304 do { \
5305 if (!LIVEP (m, po)) \
5306 abort (); \
5307 } while (0)
5309 /* Check both of the above conditions. */
5310 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
5311 do { \
5312 CHECK_ALLOCATED (); \
5313 CHECK_LIVE (LIVEP); \
5314 } while (0) \
5316 #else /* not GC_CHECK_MARKED_OBJECTS */
5318 #define CHECK_LIVE(LIVEP) (void) 0
5319 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
5321 #endif /* not GC_CHECK_MARKED_OBJECTS */
5323 switch (SWITCH_ENUM_CAST (XTYPE (obj)))
5325 case Lisp_String:
5327 register struct Lisp_String *ptr = XSTRING (obj);
5328 if (STRING_MARKED_P (ptr))
5329 break;
5330 CHECK_ALLOCATED_AND_LIVE (live_string_p);
5331 MARK_INTERVAL_TREE (ptr->intervals);
5332 MARK_STRING (ptr);
5333 #ifdef GC_CHECK_STRING_BYTES
5334 /* Check that the string size recorded in the string is the
5335 same as the one recorded in the sdata structure. */
5336 CHECK_STRING_BYTES (ptr);
5337 #endif /* GC_CHECK_STRING_BYTES */
5339 break;
5341 case Lisp_Vectorlike:
5342 if (VECTOR_MARKED_P (XVECTOR (obj)))
5343 break;
5344 #ifdef GC_CHECK_MARKED_OBJECTS
5345 m = mem_find (po);
5346 if (m == MEM_NIL && !SUBRP (obj)
5347 && po != &buffer_defaults
5348 && po != &buffer_local_symbols)
5349 abort ();
5350 #endif /* GC_CHECK_MARKED_OBJECTS */
5352 if (BUFFERP (obj))
5354 #ifdef GC_CHECK_MARKED_OBJECTS
5355 if (po != &buffer_defaults && po != &buffer_local_symbols)
5357 struct buffer *b;
5358 for (b = all_buffers; b && b != po; b = b->next)
5360 if (b == NULL)
5361 abort ();
5363 #endif /* GC_CHECK_MARKED_OBJECTS */
5364 mark_buffer (obj);
5366 else if (SUBRP (obj))
5367 break;
5368 else if (COMPILEDP (obj))
5369 /* We could treat this just like a vector, but it is better to
5370 save the COMPILED_CONSTANTS element for last and avoid
5371 recursion there. */
5373 register struct Lisp_Vector *ptr = XVECTOR (obj);
5374 register EMACS_UINT size = ptr->size;
5375 register EMACS_UINT i;
5377 CHECK_LIVE (live_vector_p);
5378 VECTOR_MARK (ptr); /* Else mark it */
5379 size &= PSEUDOVECTOR_SIZE_MASK;
5380 for (i = 0; i < size; i++) /* and then mark its elements */
5382 if (i != COMPILED_CONSTANTS)
5383 mark_object (ptr->contents[i]);
5385 obj = ptr->contents[COMPILED_CONSTANTS];
5386 goto loop;
5388 else if (FRAMEP (obj))
5390 register struct frame *ptr = XFRAME (obj);
5391 mark_vectorlike (XVECTOR (obj));
5392 mark_face_cache (ptr->face_cache);
5394 else if (WINDOWP (obj))
5396 register struct Lisp_Vector *ptr = XVECTOR (obj);
5397 struct window *w = XWINDOW (obj);
5398 mark_vectorlike (ptr);
5399 /* Mark glyphs for leaf windows. Marking window matrices is
5400 sufficient because frame matrices use the same glyph
5401 memory. */
5402 if (NILP (w->hchild)
5403 && NILP (w->vchild)
5404 && w->current_matrix)
5406 mark_glyph_matrix (w->current_matrix);
5407 mark_glyph_matrix (w->desired_matrix);
5410 else if (HASH_TABLE_P (obj))
5412 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
5413 mark_vectorlike ((struct Lisp_Vector *)h);
5414 /* If hash table is not weak, mark all keys and values.
5415 For weak tables, mark only the vector. */
5416 if (NILP (h->weak))
5417 mark_object (h->key_and_value);
5418 else
5419 VECTOR_MARK (XVECTOR (h->key_and_value));
5421 else if (CHAR_TABLE_P (obj))
5422 mark_char_table (XVECTOR (obj));
5423 else
5424 mark_vectorlike (XVECTOR (obj));
5425 break;
5427 case Lisp_Symbol:
5429 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
5430 struct Lisp_Symbol *ptrx;
5432 if (ptr->gcmarkbit)
5433 break;
5434 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
5435 ptr->gcmarkbit = 1;
5436 mark_object (ptr->function);
5437 mark_object (ptr->plist);
5438 switch (ptr->redirect)
5440 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
5441 case SYMBOL_VARALIAS:
5443 Lisp_Object tem;
5444 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
5445 mark_object (tem);
5446 break;
5448 case SYMBOL_LOCALIZED:
5450 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
5451 /* If the value is forwarded to a buffer or keyboard field,
5452 these are marked when we see the corresponding object.
5453 And if it's forwarded to a C variable, either it's not
5454 a Lisp_Object var, or it's staticpro'd already. */
5455 mark_object (blv->where);
5456 mark_object (blv->valcell);
5457 mark_object (blv->defcell);
5458 break;
5460 case SYMBOL_FORWARDED:
5461 /* If the value is forwarded to a buffer or keyboard field,
5462 these are marked when we see the corresponding object.
5463 And if it's forwarded to a C variable, either it's not
5464 a Lisp_Object var, or it's staticpro'd already. */
5465 break;
5466 default: abort ();
5468 if (!PURE_POINTER_P (XSTRING (ptr->xname)))
5469 MARK_STRING (XSTRING (ptr->xname));
5470 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr->xname));
5472 ptr = ptr->next;
5473 if (ptr)
5475 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
5476 XSETSYMBOL (obj, ptrx);
5477 goto loop;
5480 break;
5482 case Lisp_Misc:
5483 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
5484 if (XMISCANY (obj)->gcmarkbit)
5485 break;
5486 XMISCANY (obj)->gcmarkbit = 1;
5488 switch (XMISCTYPE (obj))
5491 case Lisp_Misc_Marker:
5492 /* DO NOT mark thru the marker's chain.
5493 The buffer's markers chain does not preserve markers from gc;
5494 instead, markers are removed from the chain when freed by gc. */
5495 break;
5497 case Lisp_Misc_Save_Value:
5498 #if GC_MARK_STACK
5500 register struct Lisp_Save_Value *ptr = XSAVE_VALUE (obj);
5501 /* If DOGC is set, POINTER is the address of a memory
5502 area containing INTEGER potential Lisp_Objects. */
5503 if (ptr->dogc)
5505 Lisp_Object *p = (Lisp_Object *) ptr->pointer;
5506 int nelt;
5507 for (nelt = ptr->integer; nelt > 0; nelt--, p++)
5508 mark_maybe_object (*p);
5511 #endif
5512 break;
5514 case Lisp_Misc_Overlay:
5516 struct Lisp_Overlay *ptr = XOVERLAY (obj);
5517 mark_object (ptr->start);
5518 mark_object (ptr->end);
5519 mark_object (ptr->plist);
5520 if (ptr->next)
5522 XSETMISC (obj, ptr->next);
5523 goto loop;
5526 break;
5528 default:
5529 abort ();
5531 break;
5533 case Lisp_Cons:
5535 register struct Lisp_Cons *ptr = XCONS (obj);
5536 if (CONS_MARKED_P (ptr))
5537 break;
5538 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
5539 CONS_MARK (ptr);
5540 /* If the cdr is nil, avoid recursion for the car. */
5541 if (EQ (ptr->u.cdr, Qnil))
5543 obj = ptr->car;
5544 cdr_count = 0;
5545 goto loop;
5547 mark_object (ptr->car);
5548 obj = ptr->u.cdr;
5549 cdr_count++;
5550 if (cdr_count == mark_object_loop_halt)
5551 abort ();
5552 goto loop;
5555 case Lisp_Float:
5556 CHECK_ALLOCATED_AND_LIVE (live_float_p);
5557 FLOAT_MARK (XFLOAT (obj));
5558 break;
5560 case_Lisp_Int:
5561 break;
5563 default:
5564 abort ();
5567 #undef CHECK_LIVE
5568 #undef CHECK_ALLOCATED
5569 #undef CHECK_ALLOCATED_AND_LIVE
5572 /* Mark the pointers in a buffer structure. */
5574 static void
5575 mark_buffer (Lisp_Object buf)
5577 register struct buffer *buffer = XBUFFER (buf);
5578 register Lisp_Object *ptr, tmp;
5579 Lisp_Object base_buffer;
5581 eassert (!VECTOR_MARKED_P (buffer));
5582 VECTOR_MARK (buffer);
5584 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
5586 /* For now, we just don't mark the undo_list. It's done later in
5587 a special way just before the sweep phase, and after stripping
5588 some of its elements that are not needed any more. */
5590 if (buffer->overlays_before)
5592 XSETMISC (tmp, buffer->overlays_before);
5593 mark_object (tmp);
5595 if (buffer->overlays_after)
5597 XSETMISC (tmp, buffer->overlays_after);
5598 mark_object (tmp);
5601 /* buffer-local Lisp variables start at `undo_list',
5602 tho only the ones from `name' on are GC'd normally. */
5603 for (ptr = &buffer->BUFFER_INTERNAL_FIELD (name);
5604 (char *)ptr < (char *)buffer + sizeof (struct buffer);
5605 ptr++)
5606 mark_object (*ptr);
5608 /* If this is an indirect buffer, mark its base buffer. */
5609 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5611 XSETBUFFER (base_buffer, buffer->base_buffer);
5612 mark_buffer (base_buffer);
5616 /* Mark the Lisp pointers in the terminal objects.
5617 Called by the Fgarbage_collector. */
5619 static void
5620 mark_terminals (void)
5622 struct terminal *t;
5623 for (t = terminal_list; t; t = t->next_terminal)
5625 eassert (t->name != NULL);
5626 #ifdef HAVE_WINDOW_SYSTEM
5627 /* If a terminal object is reachable from a stacpro'ed object,
5628 it might have been marked already. Make sure the image cache
5629 gets marked. */
5630 mark_image_cache (t->image_cache);
5631 #endif /* HAVE_WINDOW_SYSTEM */
5632 if (!VECTOR_MARKED_P (t))
5633 mark_vectorlike ((struct Lisp_Vector *)t);
5639 /* Value is non-zero if OBJ will survive the current GC because it's
5640 either marked or does not need to be marked to survive. */
5643 survives_gc_p (Lisp_Object obj)
5645 int survives_p;
5647 switch (XTYPE (obj))
5649 case_Lisp_Int:
5650 survives_p = 1;
5651 break;
5653 case Lisp_Symbol:
5654 survives_p = XSYMBOL (obj)->gcmarkbit;
5655 break;
5657 case Lisp_Misc:
5658 survives_p = XMISCANY (obj)->gcmarkbit;
5659 break;
5661 case Lisp_String:
5662 survives_p = STRING_MARKED_P (XSTRING (obj));
5663 break;
5665 case Lisp_Vectorlike:
5666 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
5667 break;
5669 case Lisp_Cons:
5670 survives_p = CONS_MARKED_P (XCONS (obj));
5671 break;
5673 case Lisp_Float:
5674 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
5675 break;
5677 default:
5678 abort ();
5681 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
5686 /* Sweep: find all structures not marked, and free them. */
5688 static void
5689 gc_sweep (void)
5691 /* Remove or mark entries in weak hash tables.
5692 This must be done before any object is unmarked. */
5693 sweep_weak_hash_tables ();
5695 sweep_strings ();
5696 #ifdef GC_CHECK_STRING_BYTES
5697 if (!noninteractive)
5698 check_string_bytes (1);
5699 #endif
5701 /* Put all unmarked conses on free list */
5703 register struct cons_block *cblk;
5704 struct cons_block **cprev = &cons_block;
5705 register int lim = cons_block_index;
5706 register int num_free = 0, num_used = 0;
5708 cons_free_list = 0;
5710 for (cblk = cons_block; cblk; cblk = *cprev)
5712 register int i = 0;
5713 int this_free = 0;
5714 int ilim = (lim + BITS_PER_INT - 1) / BITS_PER_INT;
5716 /* Scan the mark bits an int at a time. */
5717 for (i = 0; i <= ilim; i++)
5719 if (cblk->gcmarkbits[i] == -1)
5721 /* Fast path - all cons cells for this int are marked. */
5722 cblk->gcmarkbits[i] = 0;
5723 num_used += BITS_PER_INT;
5725 else
5727 /* Some cons cells for this int are not marked.
5728 Find which ones, and free them. */
5729 int start, pos, stop;
5731 start = i * BITS_PER_INT;
5732 stop = lim - start;
5733 if (stop > BITS_PER_INT)
5734 stop = BITS_PER_INT;
5735 stop += start;
5737 for (pos = start; pos < stop; pos++)
5739 if (!CONS_MARKED_P (&cblk->conses[pos]))
5741 this_free++;
5742 cblk->conses[pos].u.chain = cons_free_list;
5743 cons_free_list = &cblk->conses[pos];
5744 #if GC_MARK_STACK
5745 cons_free_list->car = Vdead;
5746 #endif
5748 else
5750 num_used++;
5751 CONS_UNMARK (&cblk->conses[pos]);
5757 lim = CONS_BLOCK_SIZE;
5758 /* If this block contains only free conses and we have already
5759 seen more than two blocks worth of free conses then deallocate
5760 this block. */
5761 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
5763 *cprev = cblk->next;
5764 /* Unhook from the free list. */
5765 cons_free_list = cblk->conses[0].u.chain;
5766 lisp_align_free (cblk);
5767 n_cons_blocks--;
5769 else
5771 num_free += this_free;
5772 cprev = &cblk->next;
5775 total_conses = num_used;
5776 total_free_conses = num_free;
5779 /* Put all unmarked floats on free list */
5781 register struct float_block *fblk;
5782 struct float_block **fprev = &float_block;
5783 register int lim = float_block_index;
5784 register int num_free = 0, num_used = 0;
5786 float_free_list = 0;
5788 for (fblk = float_block; fblk; fblk = *fprev)
5790 register int i;
5791 int this_free = 0;
5792 for (i = 0; i < lim; i++)
5793 if (!FLOAT_MARKED_P (&fblk->floats[i]))
5795 this_free++;
5796 fblk->floats[i].u.chain = float_free_list;
5797 float_free_list = &fblk->floats[i];
5799 else
5801 num_used++;
5802 FLOAT_UNMARK (&fblk->floats[i]);
5804 lim = FLOAT_BLOCK_SIZE;
5805 /* If this block contains only free floats and we have already
5806 seen more than two blocks worth of free floats then deallocate
5807 this block. */
5808 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
5810 *fprev = fblk->next;
5811 /* Unhook from the free list. */
5812 float_free_list = fblk->floats[0].u.chain;
5813 lisp_align_free (fblk);
5814 n_float_blocks--;
5816 else
5818 num_free += this_free;
5819 fprev = &fblk->next;
5822 total_floats = num_used;
5823 total_free_floats = num_free;
5826 /* Put all unmarked intervals on free list */
5828 register struct interval_block *iblk;
5829 struct interval_block **iprev = &interval_block;
5830 register int lim = interval_block_index;
5831 register int num_free = 0, num_used = 0;
5833 interval_free_list = 0;
5835 for (iblk = interval_block; iblk; iblk = *iprev)
5837 register int i;
5838 int this_free = 0;
5840 for (i = 0; i < lim; i++)
5842 if (!iblk->intervals[i].gcmarkbit)
5844 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
5845 interval_free_list = &iblk->intervals[i];
5846 this_free++;
5848 else
5850 num_used++;
5851 iblk->intervals[i].gcmarkbit = 0;
5854 lim = INTERVAL_BLOCK_SIZE;
5855 /* If this block contains only free intervals and we have already
5856 seen more than two blocks worth of free intervals then
5857 deallocate this block. */
5858 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
5860 *iprev = iblk->next;
5861 /* Unhook from the free list. */
5862 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
5863 lisp_free (iblk);
5864 n_interval_blocks--;
5866 else
5868 num_free += this_free;
5869 iprev = &iblk->next;
5872 total_intervals = num_used;
5873 total_free_intervals = num_free;
5876 /* Put all unmarked symbols on free list */
5878 register struct symbol_block *sblk;
5879 struct symbol_block **sprev = &symbol_block;
5880 register int lim = symbol_block_index;
5881 register int num_free = 0, num_used = 0;
5883 symbol_free_list = NULL;
5885 for (sblk = symbol_block; sblk; sblk = *sprev)
5887 int this_free = 0;
5888 struct Lisp_Symbol *sym = sblk->symbols;
5889 struct Lisp_Symbol *end = sym + lim;
5891 for (; sym < end; ++sym)
5893 /* Check if the symbol was created during loadup. In such a case
5894 it might be pointed to by pure bytecode which we don't trace,
5895 so we conservatively assume that it is live. */
5896 int pure_p = PURE_POINTER_P (XSTRING (sym->xname));
5898 if (!sym->gcmarkbit && !pure_p)
5900 if (sym->redirect == SYMBOL_LOCALIZED)
5901 xfree (SYMBOL_BLV (sym));
5902 sym->next = symbol_free_list;
5903 symbol_free_list = sym;
5904 #if GC_MARK_STACK
5905 symbol_free_list->function = Vdead;
5906 #endif
5907 ++this_free;
5909 else
5911 ++num_used;
5912 if (!pure_p)
5913 UNMARK_STRING (XSTRING (sym->xname));
5914 sym->gcmarkbit = 0;
5918 lim = SYMBOL_BLOCK_SIZE;
5919 /* If this block contains only free symbols and we have already
5920 seen more than two blocks worth of free symbols then deallocate
5921 this block. */
5922 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
5924 *sprev = sblk->next;
5925 /* Unhook from the free list. */
5926 symbol_free_list = sblk->symbols[0].next;
5927 lisp_free (sblk);
5928 n_symbol_blocks--;
5930 else
5932 num_free += this_free;
5933 sprev = &sblk->next;
5936 total_symbols = num_used;
5937 total_free_symbols = num_free;
5940 /* Put all unmarked misc's on free list.
5941 For a marker, first unchain it from the buffer it points into. */
5943 register struct marker_block *mblk;
5944 struct marker_block **mprev = &marker_block;
5945 register int lim = marker_block_index;
5946 register int num_free = 0, num_used = 0;
5948 marker_free_list = 0;
5950 for (mblk = marker_block; mblk; mblk = *mprev)
5952 register int i;
5953 int this_free = 0;
5955 for (i = 0; i < lim; i++)
5957 if (!mblk->markers[i].u_any.gcmarkbit)
5959 if (mblk->markers[i].u_any.type == Lisp_Misc_Marker)
5960 unchain_marker (&mblk->markers[i].u_marker);
5961 /* Set the type of the freed object to Lisp_Misc_Free.
5962 We could leave the type alone, since nobody checks it,
5963 but this might catch bugs faster. */
5964 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
5965 mblk->markers[i].u_free.chain = marker_free_list;
5966 marker_free_list = &mblk->markers[i];
5967 this_free++;
5969 else
5971 num_used++;
5972 mblk->markers[i].u_any.gcmarkbit = 0;
5975 lim = MARKER_BLOCK_SIZE;
5976 /* If this block contains only free markers and we have already
5977 seen more than two blocks worth of free markers then deallocate
5978 this block. */
5979 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
5981 *mprev = mblk->next;
5982 /* Unhook from the free list. */
5983 marker_free_list = mblk->markers[0].u_free.chain;
5984 lisp_free (mblk);
5985 n_marker_blocks--;
5987 else
5989 num_free += this_free;
5990 mprev = &mblk->next;
5994 total_markers = num_used;
5995 total_free_markers = num_free;
5998 /* Free all unmarked buffers */
6000 register struct buffer *buffer = all_buffers, *prev = 0, *next;
6002 while (buffer)
6003 if (!VECTOR_MARKED_P (buffer))
6005 if (prev)
6006 prev->next = buffer->next;
6007 else
6008 all_buffers = buffer->next;
6009 next = buffer->next;
6010 lisp_free (buffer);
6011 buffer = next;
6013 else
6015 VECTOR_UNMARK (buffer);
6016 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
6017 prev = buffer, buffer = buffer->next;
6021 /* Free all unmarked vectors */
6023 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
6024 total_vector_size = 0;
6026 while (vector)
6027 if (!VECTOR_MARKED_P (vector))
6029 if (prev)
6030 prev->next = vector->next;
6031 else
6032 all_vectors = vector->next;
6033 next = vector->next;
6034 lisp_free (vector);
6035 n_vectors--;
6036 vector = next;
6039 else
6041 VECTOR_UNMARK (vector);
6042 if (vector->size & PSEUDOVECTOR_FLAG)
6043 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
6044 else
6045 total_vector_size += vector->size;
6046 prev = vector, vector = vector->next;
6050 #ifdef GC_CHECK_STRING_BYTES
6051 if (!noninteractive)
6052 check_string_bytes (1);
6053 #endif
6059 /* Debugging aids. */
6061 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
6062 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6063 This may be helpful in debugging Emacs's memory usage.
6064 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6065 (void)
6067 Lisp_Object end;
6069 XSETINT (end, (EMACS_INT) (char *) sbrk (0) / 1024);
6071 return end;
6074 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
6075 doc: /* Return a list of counters that measure how much consing there has been.
6076 Each of these counters increments for a certain kind of object.
6077 The counters wrap around from the largest positive integer to zero.
6078 Garbage collection does not decrease them.
6079 The elements of the value are as follows:
6080 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6081 All are in units of 1 = one object consed
6082 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6083 objects consed.
6084 MISCS include overlays, markers, and some internal types.
6085 Frames, windows, buffers, and subprocesses count as vectors
6086 (but the contents of a buffer's text do not count here). */)
6087 (void)
6089 Lisp_Object consed[8];
6091 consed[0] = make_number (min (MOST_POSITIVE_FIXNUM, cons_cells_consed));
6092 consed[1] = make_number (min (MOST_POSITIVE_FIXNUM, floats_consed));
6093 consed[2] = make_number (min (MOST_POSITIVE_FIXNUM, vector_cells_consed));
6094 consed[3] = make_number (min (MOST_POSITIVE_FIXNUM, symbols_consed));
6095 consed[4] = make_number (min (MOST_POSITIVE_FIXNUM, string_chars_consed));
6096 consed[5] = make_number (min (MOST_POSITIVE_FIXNUM, misc_objects_consed));
6097 consed[6] = make_number (min (MOST_POSITIVE_FIXNUM, intervals_consed));
6098 consed[7] = make_number (min (MOST_POSITIVE_FIXNUM, strings_consed));
6100 return Flist (8, consed);
6103 int suppress_checking;
6105 void
6106 die (const char *msg, const char *file, int line)
6108 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: %s\r\n",
6109 file, line, msg);
6110 abort ();
6113 /* Initialization */
6115 void
6116 init_alloc_once (void)
6118 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
6119 purebeg = PUREBEG;
6120 pure_size = PURESIZE;
6121 pure_bytes_used = 0;
6122 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
6123 pure_bytes_used_before_overflow = 0;
6125 /* Initialize the list of free aligned blocks. */
6126 free_ablock = NULL;
6128 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
6129 mem_init ();
6130 Vdead = make_pure_string ("DEAD", 4, 4, 0);
6131 #endif
6133 all_vectors = 0;
6134 ignore_warnings = 1;
6135 #ifdef DOUG_LEA_MALLOC
6136 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
6137 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
6138 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
6139 #endif
6140 init_strings ();
6141 init_cons ();
6142 init_symbol ();
6143 init_marker ();
6144 init_float ();
6145 init_intervals ();
6146 init_weak_hash_tables ();
6148 #ifdef REL_ALLOC
6149 malloc_hysteresis = 32;
6150 #else
6151 malloc_hysteresis = 0;
6152 #endif
6154 refill_memory_reserve ();
6156 ignore_warnings = 0;
6157 gcprolist = 0;
6158 byte_stack_list = 0;
6159 staticidx = 0;
6160 consing_since_gc = 0;
6161 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
6162 gc_relative_threshold = 0;
6165 void
6166 init_alloc (void)
6168 gcprolist = 0;
6169 byte_stack_list = 0;
6170 #if GC_MARK_STACK
6171 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
6172 setjmp_tested_p = longjmps_done = 0;
6173 #endif
6174 #endif
6175 Vgc_elapsed = make_float (0.0);
6176 gcs_done = 0;
6179 void
6180 syms_of_alloc (void)
6182 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
6183 doc: /* *Number of bytes of consing between garbage collections.
6184 Garbage collection can happen automatically once this many bytes have been
6185 allocated since the last garbage collection. All data types count.
6187 Garbage collection happens automatically only when `eval' is called.
6189 By binding this temporarily to a large number, you can effectively
6190 prevent garbage collection during a part of the program.
6191 See also `gc-cons-percentage'. */);
6193 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
6194 doc: /* *Portion of the heap used for allocation.
6195 Garbage collection can happen automatically once this portion of the heap
6196 has been allocated since the last garbage collection.
6197 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
6198 Vgc_cons_percentage = make_float (0.1);
6200 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
6201 doc: /* Number of bytes of sharable Lisp data allocated so far. */);
6203 DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
6204 doc: /* Number of cons cells that have been consed so far. */);
6206 DEFVAR_INT ("floats-consed", floats_consed,
6207 doc: /* Number of floats that have been consed so far. */);
6209 DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
6210 doc: /* Number of vector cells that have been consed so far. */);
6212 DEFVAR_INT ("symbols-consed", symbols_consed,
6213 doc: /* Number of symbols that have been consed so far. */);
6215 DEFVAR_INT ("string-chars-consed", string_chars_consed,
6216 doc: /* Number of string characters that have been consed so far. */);
6218 DEFVAR_INT ("misc-objects-consed", misc_objects_consed,
6219 doc: /* Number of miscellaneous objects that have been consed so far. */);
6221 DEFVAR_INT ("intervals-consed", intervals_consed,
6222 doc: /* Number of intervals that have been consed so far. */);
6224 DEFVAR_INT ("strings-consed", strings_consed,
6225 doc: /* Number of strings that have been consed so far. */);
6227 DEFVAR_LISP ("purify-flag", Vpurify_flag,
6228 doc: /* Non-nil means loading Lisp code in order to dump an executable.
6229 This means that certain objects should be allocated in shared (pure) space.
6230 It can also be set to a hash-table, in which case this table is used to
6231 do hash-consing of the objects allocated to pure space. */);
6233 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
6234 doc: /* Non-nil means display messages at start and end of garbage collection. */);
6235 garbage_collection_messages = 0;
6237 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
6238 doc: /* Hook run after garbage collection has finished. */);
6239 Vpost_gc_hook = Qnil;
6240 Qpost_gc_hook = intern_c_string ("post-gc-hook");
6241 staticpro (&Qpost_gc_hook);
6243 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
6244 doc: /* Precomputed `signal' argument for memory-full error. */);
6245 /* We build this in advance because if we wait until we need it, we might
6246 not be able to allocate the memory to hold it. */
6247 Vmemory_signal_data
6248 = pure_cons (Qerror,
6249 pure_cons (make_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"), Qnil));
6251 DEFVAR_LISP ("memory-full", Vmemory_full,
6252 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
6253 Vmemory_full = Qnil;
6255 staticpro (&Qgc_cons_threshold);
6256 Qgc_cons_threshold = intern_c_string ("gc-cons-threshold");
6258 staticpro (&Qchar_table_extra_slots);
6259 Qchar_table_extra_slots = intern_c_string ("char-table-extra-slots");
6261 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
6262 doc: /* Accumulated time elapsed in garbage collections.
6263 The time is in seconds as a floating point value. */);
6264 DEFVAR_INT ("gcs-done", gcs_done,
6265 doc: /* Accumulated number of garbage collections done. */);
6267 defsubr (&Scons);
6268 defsubr (&Slist);
6269 defsubr (&Svector);
6270 defsubr (&Smake_byte_code);
6271 defsubr (&Smake_list);
6272 defsubr (&Smake_vector);
6273 defsubr (&Smake_string);
6274 defsubr (&Smake_bool_vector);
6275 defsubr (&Smake_symbol);
6276 defsubr (&Smake_marker);
6277 defsubr (&Spurecopy);
6278 defsubr (&Sgarbage_collect);
6279 defsubr (&Smemory_limit);
6280 defsubr (&Smemory_use_counts);
6282 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
6283 defsubr (&Sgc_status);
6284 #endif