typo
[emacs.git] / src / alloc.c
blob36ad645612dc5aaf16b712a6c82acd21a755d73c
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 #include <signal.h>
27 #ifdef HAVE_PTHREAD
28 #include <pthread.h>
29 #endif
31 /* This file is part of the core Lisp implementation, and thus must
32 deal with the real data structures. If the Lisp implementation is
33 replaced, this file likely will not be used. */
35 #undef HIDE_LISP_IMPLEMENTATION
36 #include "lisp.h"
37 #include "process.h"
38 #include "intervals.h"
39 #include "puresize.h"
40 #include "buffer.h"
41 #include "window.h"
42 #include "keyboard.h"
43 #include "frame.h"
44 #include "blockinput.h"
45 #include "character.h"
46 #include "syssignal.h"
47 #include "termhooks.h" /* For struct terminal. */
48 #include <setjmp.h>
50 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
51 memory. Can do this only if using gmalloc.c. */
53 #if defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC
54 #undef GC_MALLOC_CHECK
55 #endif
57 #include <unistd.h>
58 #ifndef HAVE_UNISTD_H
59 extern POINTER_TYPE *sbrk ();
60 #endif
62 #include <fcntl.h>
64 #ifdef WINDOWSNT
65 #include "w32.h"
66 #endif
68 #ifdef DOUG_LEA_MALLOC
70 #include <malloc.h>
72 /* Specify maximum number of areas to mmap. It would be nice to use a
73 value that explicitly means "no limit". */
75 #define MMAP_MAX_AREAS 100000000
77 #else /* not DOUG_LEA_MALLOC */
79 /* The following come from gmalloc.c. */
81 extern size_t _bytes_used;
82 extern size_t __malloc_extra_blocks;
84 #endif /* not DOUG_LEA_MALLOC */
86 #if ! defined SYSTEM_MALLOC && ! defined SYNC_INPUT
87 #ifdef HAVE_PTHREAD
89 /* When GTK uses the file chooser dialog, different backends can be loaded
90 dynamically. One such a backend is the Gnome VFS backend that gets loaded
91 if you run Gnome. That backend creates several threads and also allocates
92 memory with malloc.
94 Also, gconf and gsettings may create several threads.
96 If Emacs sets malloc hooks (! SYSTEM_MALLOC) and the emacs_blocked_*
97 functions below are called from malloc, there is a chance that one
98 of these threads preempts the Emacs main thread and the hook variables
99 end up in an inconsistent state. So we have a mutex to prevent that (note
100 that the backend handles concurrent access to malloc within its own threads
101 but Emacs code running in the main thread is not included in that control).
103 When UNBLOCK_INPUT is called, reinvoke_input_signal may be called. If this
104 happens in one of the backend threads we will have two threads that tries
105 to run Emacs code at once, and the code is not prepared for that.
106 To prevent that, we only call BLOCK/UNBLOCK from the main thread. */
108 static pthread_mutex_t alloc_mutex;
110 #define BLOCK_INPUT_ALLOC \
111 do \
113 if (pthread_equal (pthread_self (), main_thread)) \
114 BLOCK_INPUT; \
115 pthread_mutex_lock (&alloc_mutex); \
117 while (0)
118 #define UNBLOCK_INPUT_ALLOC \
119 do \
121 pthread_mutex_unlock (&alloc_mutex); \
122 if (pthread_equal (pthread_self (), main_thread)) \
123 UNBLOCK_INPUT; \
125 while (0)
127 #else /* ! defined HAVE_PTHREAD */
129 #define BLOCK_INPUT_ALLOC BLOCK_INPUT
130 #define UNBLOCK_INPUT_ALLOC UNBLOCK_INPUT
132 #endif /* ! defined HAVE_PTHREAD */
133 #endif /* ! defined SYSTEM_MALLOC && ! defined SYNC_INPUT */
135 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
136 to a struct Lisp_String. */
138 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
139 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
140 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
142 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
143 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
144 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
146 /* Value is the number of bytes of S, a pointer to a struct Lisp_String.
147 Be careful during GC, because S->size contains the mark bit for
148 strings. */
150 #define GC_STRING_BYTES(S) (STRING_BYTES (S))
152 /* Global variables. */
153 struct emacs_globals globals;
155 /* Number of bytes of consing done since the last gc. */
157 EMACS_INT consing_since_gc;
159 /* Similar minimum, computed from Vgc_cons_percentage. */
161 EMACS_INT gc_relative_threshold;
163 /* Minimum number of bytes of consing since GC before next GC,
164 when memory is full. */
166 EMACS_INT memory_full_cons_threshold;
168 /* Nonzero during GC. */
170 int gc_in_progress;
172 /* Nonzero means abort if try to GC.
173 This is for code which is written on the assumption that
174 no GC will happen, so as to verify that assumption. */
176 int abort_on_gc;
178 /* Number of live and free conses etc. */
180 static EMACS_INT total_conses, total_markers, total_symbols, total_vector_size;
181 static EMACS_INT total_free_conses, total_free_markers, total_free_symbols;
182 static EMACS_INT total_free_floats, total_floats;
184 /* Points to memory space allocated as "spare", to be freed if we run
185 out of memory. We keep one large block, four cons-blocks, and
186 two string blocks. */
188 static char *spare_memory[7];
190 /* Amount of spare memory to keep in large reserve block, or to see
191 whether this much is available when malloc fails on a larger request. */
193 #define SPARE_MEMORY (1 << 14)
195 /* Number of extra blocks malloc should get when it needs more core. */
197 static int malloc_hysteresis;
199 /* Initialize it to a nonzero value to force it into data space
200 (rather than bss space). That way unexec will remap it into text
201 space (pure), on some systems. We have not implemented the
202 remapping on more recent systems because this is less important
203 nowadays than in the days of small memories and timesharing. */
205 #ifndef VIRT_ADDR_VARIES
206 static
207 #endif
208 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
209 #define PUREBEG (char *) pure
211 /* Pointer to the pure area, and its size. */
213 static char *purebeg;
214 static ptrdiff_t pure_size;
216 /* Number of bytes of pure storage used before pure storage overflowed.
217 If this is non-zero, this implies that an overflow occurred. */
219 static ptrdiff_t pure_bytes_used_before_overflow;
221 /* Value is non-zero if P points into pure space. */
223 #define PURE_POINTER_P(P) \
224 (((PNTR_COMPARISON_TYPE) (P) \
225 < (PNTR_COMPARISON_TYPE) ((char *) purebeg + pure_size)) \
226 && ((PNTR_COMPARISON_TYPE) (P) \
227 >= (PNTR_COMPARISON_TYPE) purebeg))
229 /* Index in pure at which next pure Lisp object will be allocated.. */
231 static EMACS_INT pure_bytes_used_lisp;
233 /* Number of bytes allocated for non-Lisp objects in pure storage. */
235 static EMACS_INT pure_bytes_used_non_lisp;
237 /* If nonzero, this is a warning delivered by malloc and not yet
238 displayed. */
240 const char *pending_malloc_warning;
242 /* Maximum amount of C stack to save when a GC happens. */
244 #ifndef MAX_SAVE_STACK
245 #define MAX_SAVE_STACK 16000
246 #endif
248 /* Buffer in which we save a copy of the C stack at each GC. */
250 #if MAX_SAVE_STACK > 0
251 static char *stack_copy;
252 static ptrdiff_t stack_copy_size;
253 #endif
255 /* Non-zero means ignore malloc warnings. Set during initialization.
256 Currently not used. */
258 static int ignore_warnings;
260 static Lisp_Object Qgc_cons_threshold;
261 Lisp_Object Qchar_table_extra_slots;
263 /* Hook run after GC has finished. */
265 static Lisp_Object Qpost_gc_hook;
267 static void mark_buffer (Lisp_Object);
268 static void mark_terminals (void);
269 static void gc_sweep (void);
270 static void mark_glyph_matrix (struct glyph_matrix *);
271 static void mark_face_cache (struct face_cache *);
273 #if !defined REL_ALLOC || defined SYSTEM_MALLOC
274 static void refill_memory_reserve (void);
275 #endif
276 static struct Lisp_String *allocate_string (void);
277 static void compact_small_strings (void);
278 static void free_large_strings (void);
279 static void sweep_strings (void);
280 static void free_misc (Lisp_Object);
282 /* When scanning the C stack for live Lisp objects, Emacs keeps track
283 of what memory allocated via lisp_malloc is intended for what
284 purpose. This enumeration specifies the type of memory. */
286 enum mem_type
288 MEM_TYPE_NON_LISP,
289 MEM_TYPE_BUFFER,
290 MEM_TYPE_CONS,
291 MEM_TYPE_STRING,
292 MEM_TYPE_MISC,
293 MEM_TYPE_SYMBOL,
294 MEM_TYPE_FLOAT,
295 /* We used to keep separate mem_types for subtypes of vectors such as
296 process, hash_table, frame, terminal, and window, but we never made
297 use of the distinction, so it only caused source-code complexity
298 and runtime slowdown. Minor but pointless. */
299 MEM_TYPE_VECTORLIKE
302 static POINTER_TYPE *lisp_align_malloc (size_t, enum mem_type);
303 static POINTER_TYPE *lisp_malloc (size_t, enum mem_type);
306 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
308 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
309 #include <stdio.h> /* For fprintf. */
310 #endif
312 /* A unique object in pure space used to make some Lisp objects
313 on free lists recognizable in O(1). */
315 static Lisp_Object Vdead;
317 #ifdef GC_MALLOC_CHECK
319 enum mem_type allocated_mem_type;
320 static int dont_register_blocks;
322 #endif /* GC_MALLOC_CHECK */
324 /* A node in the red-black tree describing allocated memory containing
325 Lisp data. Each such block is recorded with its start and end
326 address when it is allocated, and removed from the tree when it
327 is freed.
329 A red-black tree is a balanced binary tree with the following
330 properties:
332 1. Every node is either red or black.
333 2. Every leaf is black.
334 3. If a node is red, then both of its children are black.
335 4. Every simple path from a node to a descendant leaf contains
336 the same number of black nodes.
337 5. The root is always black.
339 When nodes are inserted into the tree, or deleted from the tree,
340 the tree is "fixed" so that these properties are always true.
342 A red-black tree with N internal nodes has height at most 2
343 log(N+1). Searches, insertions and deletions are done in O(log N).
344 Please see a text book about data structures for a detailed
345 description of red-black trees. Any book worth its salt should
346 describe them. */
348 struct mem_node
350 /* Children of this node. These pointers are never NULL. When there
351 is no child, the value is MEM_NIL, which points to a dummy node. */
352 struct mem_node *left, *right;
354 /* The parent of this node. In the root node, this is NULL. */
355 struct mem_node *parent;
357 /* Start and end of allocated region. */
358 void *start, *end;
360 /* Node color. */
361 enum {MEM_BLACK, MEM_RED} color;
363 /* Memory type. */
364 enum mem_type type;
367 /* Base address of stack. Set in main. */
369 Lisp_Object *stack_base;
371 /* Root of the tree describing allocated Lisp memory. */
373 static struct mem_node *mem_root;
375 /* Lowest and highest known address in the heap. */
377 static void *min_heap_address, *max_heap_address;
379 /* Sentinel node of the tree. */
381 static struct mem_node mem_z;
382 #define MEM_NIL &mem_z
384 static struct Lisp_Vector *allocate_vectorlike (EMACS_INT);
385 static void lisp_free (POINTER_TYPE *);
386 static void mark_stack (void);
387 static int live_vector_p (struct mem_node *, void *);
388 static int live_buffer_p (struct mem_node *, void *);
389 static int live_string_p (struct mem_node *, void *);
390 static int live_cons_p (struct mem_node *, void *);
391 static int live_symbol_p (struct mem_node *, void *);
392 static int live_float_p (struct mem_node *, void *);
393 static int live_misc_p (struct mem_node *, void *);
394 static void mark_maybe_object (Lisp_Object);
395 static void mark_memory (void *, void *, int);
396 static void mem_init (void);
397 static struct mem_node *mem_insert (void *, void *, enum mem_type);
398 static void mem_insert_fixup (struct mem_node *);
399 static void mem_rotate_left (struct mem_node *);
400 static void mem_rotate_right (struct mem_node *);
401 static void mem_delete (struct mem_node *);
402 static void mem_delete_fixup (struct mem_node *);
403 static inline struct mem_node *mem_find (void *);
406 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
407 static void check_gcpros (void);
408 #endif
410 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
412 /* Recording what needs to be marked for gc. */
414 struct gcpro *gcprolist;
416 /* Addresses of staticpro'd variables. Initialize it to a nonzero
417 value; otherwise some compilers put it into BSS. */
419 #define NSTATICS 0x640
420 static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
422 /* Index of next unused slot in staticvec. */
424 static int staticidx = 0;
426 static POINTER_TYPE *pure_alloc (size_t, int);
429 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
430 ALIGNMENT must be a power of 2. */
432 #define ALIGN(ptr, ALIGNMENT) \
433 ((POINTER_TYPE *) ((((uintptr_t) (ptr)) + (ALIGNMENT) - 1) \
434 & ~((ALIGNMENT) - 1)))
438 /************************************************************************
439 Malloc
440 ************************************************************************/
442 /* Function malloc calls this if it finds we are near exhausting storage. */
444 void
445 malloc_warning (const char *str)
447 pending_malloc_warning = str;
451 /* Display an already-pending malloc warning. */
453 void
454 display_malloc_warning (void)
456 call3 (intern ("display-warning"),
457 intern ("alloc"),
458 build_string (pending_malloc_warning),
459 intern ("emergency"));
460 pending_malloc_warning = 0;
463 /* Called if we can't allocate relocatable space for a buffer. */
465 void
466 buffer_memory_full (EMACS_INT nbytes)
468 /* If buffers use the relocating allocator, no need to free
469 spare_memory, because we may have plenty of malloc space left
470 that we could get, and if we don't, the malloc that fails will
471 itself cause spare_memory to be freed. If buffers don't use the
472 relocating allocator, treat this like any other failing
473 malloc. */
475 #ifndef REL_ALLOC
476 memory_full (nbytes);
477 #endif
479 /* This used to call error, but if we've run out of memory, we could
480 get infinite recursion trying to build the string. */
481 xsignal (Qnil, Vmemory_signal_data);
485 #ifndef XMALLOC_OVERRUN_CHECK
486 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
487 #else
489 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
490 around each block.
492 The header consists of 16 fixed bytes followed by sizeof (size_t) bytes
493 containing the original block size in little-endian order,
494 while the trailer consists of 16 fixed bytes.
496 The header is used to detect whether this block has been allocated
497 through these functions -- as it seems that some low-level libc
498 functions may bypass the malloc hooks.
502 #define XMALLOC_OVERRUN_CHECK_SIZE 16
503 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
504 (2 * XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t))
506 static char const xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE] =
507 { '\x9a', '\x9b', '\xae', '\xaf',
508 '\xbf', '\xbe', '\xce', '\xcf',
509 '\xea', '\xeb', '\xec', '\xed',
510 '\xdf', '\xde', '\x9c', '\x9d' };
512 static char const xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
513 { '\xaa', '\xab', '\xac', '\xad',
514 '\xba', '\xbb', '\xbc', '\xbd',
515 '\xca', '\xcb', '\xcc', '\xcd',
516 '\xda', '\xdb', '\xdc', '\xdd' };
518 /* Insert and extract the block size in the header. */
520 static void
521 xmalloc_put_size (unsigned char *ptr, size_t size)
523 int i;
524 for (i = 0; i < sizeof (size_t); i++)
526 *--ptr = size & (1 << CHAR_BIT) - 1;
527 size >>= CHAR_BIT;
531 static size_t
532 xmalloc_get_size (unsigned char *ptr)
534 size_t size = 0;
535 int i;
536 ptr -= sizeof (size_t);
537 for (i = 0; i < sizeof (size_t); i++)
539 size <<= CHAR_BIT;
540 size += *ptr++;
542 return size;
546 /* The call depth in overrun_check functions. For example, this might happen:
547 xmalloc()
548 overrun_check_malloc()
549 -> malloc -> (via hook)_-> emacs_blocked_malloc
550 -> overrun_check_malloc
551 call malloc (hooks are NULL, so real malloc is called).
552 malloc returns 10000.
553 add overhead, return 10016.
554 <- (back in overrun_check_malloc)
555 add overhead again, return 10032
556 xmalloc returns 10032.
558 (time passes).
560 xfree(10032)
561 overrun_check_free(10032)
562 decrease overhead
563 free(10016) <- crash, because 10000 is the original pointer. */
565 static ptrdiff_t check_depth;
567 /* Like malloc, but wraps allocated block with header and trailer. */
569 static POINTER_TYPE *
570 overrun_check_malloc (size_t size)
572 register unsigned char *val;
573 int overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_OVERHEAD : 0;
574 if (SIZE_MAX - overhead < size)
575 abort ();
577 val = (unsigned char *) malloc (size + overhead);
578 if (val && check_depth == 1)
580 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
581 val += XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t);
582 xmalloc_put_size (val, size);
583 memcpy (val + size, xmalloc_overrun_check_trailer,
584 XMALLOC_OVERRUN_CHECK_SIZE);
586 --check_depth;
587 return (POINTER_TYPE *)val;
591 /* Like realloc, but checks old block for overrun, and wraps new block
592 with header and trailer. */
594 static POINTER_TYPE *
595 overrun_check_realloc (POINTER_TYPE *block, size_t size)
597 register unsigned char *val = (unsigned char *) block;
598 int overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_OVERHEAD : 0;
599 if (SIZE_MAX - overhead < size)
600 abort ();
602 if (val
603 && check_depth == 1
604 && memcmp (xmalloc_overrun_check_header,
605 val - XMALLOC_OVERRUN_CHECK_SIZE - sizeof (size_t),
606 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
608 size_t osize = xmalloc_get_size (val);
609 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
610 XMALLOC_OVERRUN_CHECK_SIZE))
611 abort ();
612 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
613 val -= XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t);
614 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t));
617 val = (unsigned char *) realloc ((POINTER_TYPE *)val, size + overhead);
619 if (val && check_depth == 1)
621 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
622 val += XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t);
623 xmalloc_put_size (val, size);
624 memcpy (val + size, xmalloc_overrun_check_trailer,
625 XMALLOC_OVERRUN_CHECK_SIZE);
627 --check_depth;
628 return (POINTER_TYPE *)val;
631 /* Like free, but checks block for overrun. */
633 static void
634 overrun_check_free (POINTER_TYPE *block)
636 unsigned char *val = (unsigned char *) block;
638 ++check_depth;
639 if (val
640 && check_depth == 1
641 && memcmp (xmalloc_overrun_check_header,
642 val - XMALLOC_OVERRUN_CHECK_SIZE - sizeof (size_t),
643 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
645 size_t osize = xmalloc_get_size (val);
646 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
647 XMALLOC_OVERRUN_CHECK_SIZE))
648 abort ();
649 #ifdef XMALLOC_CLEAR_FREE_MEMORY
650 val -= XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t);
651 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_OVERHEAD);
652 #else
653 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
654 val -= XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t);
655 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t));
656 #endif
659 free (val);
660 --check_depth;
663 #undef malloc
664 #undef realloc
665 #undef free
666 #define malloc overrun_check_malloc
667 #define realloc overrun_check_realloc
668 #define free overrun_check_free
669 #endif
671 #ifdef SYNC_INPUT
672 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
673 there's no need to block input around malloc. */
674 #define MALLOC_BLOCK_INPUT ((void)0)
675 #define MALLOC_UNBLOCK_INPUT ((void)0)
676 #else
677 #define MALLOC_BLOCK_INPUT BLOCK_INPUT
678 #define MALLOC_UNBLOCK_INPUT UNBLOCK_INPUT
679 #endif
681 /* Like malloc but check for no memory and block interrupt input.. */
683 POINTER_TYPE *
684 xmalloc (size_t size)
686 register POINTER_TYPE *val;
688 MALLOC_BLOCK_INPUT;
689 val = (POINTER_TYPE *) malloc (size);
690 MALLOC_UNBLOCK_INPUT;
692 if (!val && size)
693 memory_full (size);
694 return val;
698 /* Like realloc but check for no memory and block interrupt input.. */
700 POINTER_TYPE *
701 xrealloc (POINTER_TYPE *block, size_t size)
703 register POINTER_TYPE *val;
705 MALLOC_BLOCK_INPUT;
706 /* We must call malloc explicitly when BLOCK is 0, since some
707 reallocs don't do this. */
708 if (! block)
709 val = (POINTER_TYPE *) malloc (size);
710 else
711 val = (POINTER_TYPE *) realloc (block, size);
712 MALLOC_UNBLOCK_INPUT;
714 if (!val && size)
715 memory_full (size);
716 return val;
720 /* Like free but block interrupt input. */
722 void
723 xfree (POINTER_TYPE *block)
725 if (!block)
726 return;
727 MALLOC_BLOCK_INPUT;
728 free (block);
729 MALLOC_UNBLOCK_INPUT;
730 /* We don't call refill_memory_reserve here
731 because that duplicates doing so in emacs_blocked_free
732 and the criterion should go there. */
736 /* Like strdup, but uses xmalloc. */
738 char *
739 xstrdup (const char *s)
741 size_t len = strlen (s) + 1;
742 char *p = (char *) xmalloc (len);
743 memcpy (p, s, len);
744 return p;
748 /* Unwind for SAFE_ALLOCA */
750 Lisp_Object
751 safe_alloca_unwind (Lisp_Object arg)
753 register struct Lisp_Save_Value *p = XSAVE_VALUE (arg);
755 p->dogc = 0;
756 xfree (p->pointer);
757 p->pointer = 0;
758 free_misc (arg);
759 return Qnil;
763 /* Like malloc but used for allocating Lisp data. NBYTES is the
764 number of bytes to allocate, TYPE describes the intended use of the
765 allcated memory block (for strings, for conses, ...). */
767 #ifndef USE_LSB_TAG
768 static void *lisp_malloc_loser;
769 #endif
771 static POINTER_TYPE *
772 lisp_malloc (size_t nbytes, enum mem_type type)
774 register void *val;
776 MALLOC_BLOCK_INPUT;
778 #ifdef GC_MALLOC_CHECK
779 allocated_mem_type = type;
780 #endif
782 val = (void *) malloc (nbytes);
784 #ifndef USE_LSB_TAG
785 /* If the memory just allocated cannot be addressed thru a Lisp
786 object's pointer, and it needs to be,
787 that's equivalent to running out of memory. */
788 if (val && type != MEM_TYPE_NON_LISP)
790 Lisp_Object tem;
791 XSETCONS (tem, (char *) val + nbytes - 1);
792 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
794 lisp_malloc_loser = val;
795 free (val);
796 val = 0;
799 #endif
801 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
802 if (val && type != MEM_TYPE_NON_LISP)
803 mem_insert (val, (char *) val + nbytes, type);
804 #endif
806 MALLOC_UNBLOCK_INPUT;
807 if (!val && nbytes)
808 memory_full (nbytes);
809 return val;
812 /* Free BLOCK. This must be called to free memory allocated with a
813 call to lisp_malloc. */
815 static void
816 lisp_free (POINTER_TYPE *block)
818 MALLOC_BLOCK_INPUT;
819 free (block);
820 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
821 mem_delete (mem_find (block));
822 #endif
823 MALLOC_UNBLOCK_INPUT;
826 /* Allocation of aligned blocks of memory to store Lisp data. */
827 /* The entry point is lisp_align_malloc which returns blocks of at most */
828 /* BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
830 /* Use posix_memalloc if the system has it and we're using the system's
831 malloc (because our gmalloc.c routines don't have posix_memalign although
832 its memalloc could be used). */
833 #if defined (HAVE_POSIX_MEMALIGN) && defined (SYSTEM_MALLOC)
834 #define USE_POSIX_MEMALIGN 1
835 #endif
837 /* BLOCK_ALIGN has to be a power of 2. */
838 #define BLOCK_ALIGN (1 << 10)
840 /* Padding to leave at the end of a malloc'd block. This is to give
841 malloc a chance to minimize the amount of memory wasted to alignment.
842 It should be tuned to the particular malloc library used.
843 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
844 posix_memalign on the other hand would ideally prefer a value of 4
845 because otherwise, there's 1020 bytes wasted between each ablocks.
846 In Emacs, testing shows that those 1020 can most of the time be
847 efficiently used by malloc to place other objects, so a value of 0 can
848 still preferable unless you have a lot of aligned blocks and virtually
849 nothing else. */
850 #define BLOCK_PADDING 0
851 #define BLOCK_BYTES \
852 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
854 /* Internal data structures and constants. */
856 #define ABLOCKS_SIZE 16
858 /* An aligned block of memory. */
859 struct ablock
861 union
863 char payload[BLOCK_BYTES];
864 struct ablock *next_free;
865 } x;
866 /* `abase' is the aligned base of the ablocks. */
867 /* It is overloaded to hold the virtual `busy' field that counts
868 the number of used ablock in the parent ablocks.
869 The first ablock has the `busy' field, the others have the `abase'
870 field. To tell the difference, we assume that pointers will have
871 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
872 is used to tell whether the real base of the parent ablocks is `abase'
873 (if not, the word before the first ablock holds a pointer to the
874 real base). */
875 struct ablocks *abase;
876 /* The padding of all but the last ablock is unused. The padding of
877 the last ablock in an ablocks is not allocated. */
878 #if BLOCK_PADDING
879 char padding[BLOCK_PADDING];
880 #endif
883 /* A bunch of consecutive aligned blocks. */
884 struct ablocks
886 struct ablock blocks[ABLOCKS_SIZE];
889 /* Size of the block requested from malloc or memalign. */
890 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
892 #define ABLOCK_ABASE(block) \
893 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
894 ? (struct ablocks *)(block) \
895 : (block)->abase)
897 /* Virtual `busy' field. */
898 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
900 /* Pointer to the (not necessarily aligned) malloc block. */
901 #ifdef USE_POSIX_MEMALIGN
902 #define ABLOCKS_BASE(abase) (abase)
903 #else
904 #define ABLOCKS_BASE(abase) \
905 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void**)abase)[-1])
906 #endif
908 /* The list of free ablock. */
909 static struct ablock *free_ablock;
911 /* Allocate an aligned block of nbytes.
912 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
913 smaller or equal to BLOCK_BYTES. */
914 static POINTER_TYPE *
915 lisp_align_malloc (size_t nbytes, enum mem_type type)
917 void *base, *val;
918 struct ablocks *abase;
920 eassert (nbytes <= BLOCK_BYTES);
922 MALLOC_BLOCK_INPUT;
924 #ifdef GC_MALLOC_CHECK
925 allocated_mem_type = type;
926 #endif
928 if (!free_ablock)
930 int i;
931 intptr_t aligned; /* int gets warning casting to 64-bit pointer. */
933 #ifdef DOUG_LEA_MALLOC
934 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
935 because mapped region contents are not preserved in
936 a dumped Emacs. */
937 mallopt (M_MMAP_MAX, 0);
938 #endif
940 #ifdef USE_POSIX_MEMALIGN
942 int err = posix_memalign (&base, BLOCK_ALIGN, ABLOCKS_BYTES);
943 if (err)
944 base = NULL;
945 abase = base;
947 #else
948 base = malloc (ABLOCKS_BYTES);
949 abase = ALIGN (base, BLOCK_ALIGN);
950 #endif
952 if (base == 0)
954 MALLOC_UNBLOCK_INPUT;
955 memory_full (ABLOCKS_BYTES);
958 aligned = (base == abase);
959 if (!aligned)
960 ((void**)abase)[-1] = base;
962 #ifdef DOUG_LEA_MALLOC
963 /* Back to a reasonable maximum of mmap'ed areas. */
964 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
965 #endif
967 #ifndef USE_LSB_TAG
968 /* If the memory just allocated cannot be addressed thru a Lisp
969 object's pointer, and it needs to be, that's equivalent to
970 running out of memory. */
971 if (type != MEM_TYPE_NON_LISP)
973 Lisp_Object tem;
974 char *end = (char *) base + ABLOCKS_BYTES - 1;
975 XSETCONS (tem, end);
976 if ((char *) XCONS (tem) != end)
978 lisp_malloc_loser = base;
979 free (base);
980 MALLOC_UNBLOCK_INPUT;
981 memory_full (SIZE_MAX);
984 #endif
986 /* Initialize the blocks and put them on the free list.
987 Is `base' was not properly aligned, we can't use the last block. */
988 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
990 abase->blocks[i].abase = abase;
991 abase->blocks[i].x.next_free = free_ablock;
992 free_ablock = &abase->blocks[i];
994 ABLOCKS_BUSY (abase) = (struct ablocks *) aligned;
996 eassert (0 == ((uintptr_t) abase) % BLOCK_ALIGN);
997 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
998 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
999 eassert (ABLOCKS_BASE (abase) == base);
1000 eassert (aligned == (intptr_t) ABLOCKS_BUSY (abase));
1003 abase = ABLOCK_ABASE (free_ablock);
1004 ABLOCKS_BUSY (abase) =
1005 (struct ablocks *) (2 + (intptr_t) ABLOCKS_BUSY (abase));
1006 val = free_ablock;
1007 free_ablock = free_ablock->x.next_free;
1009 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1010 if (type != MEM_TYPE_NON_LISP)
1011 mem_insert (val, (char *) val + nbytes, type);
1012 #endif
1014 MALLOC_UNBLOCK_INPUT;
1016 eassert (0 == ((uintptr_t) val) % BLOCK_ALIGN);
1017 return val;
1020 static void
1021 lisp_align_free (POINTER_TYPE *block)
1023 struct ablock *ablock = block;
1024 struct ablocks *abase = ABLOCK_ABASE (ablock);
1026 MALLOC_BLOCK_INPUT;
1027 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1028 mem_delete (mem_find (block));
1029 #endif
1030 /* Put on free list. */
1031 ablock->x.next_free = free_ablock;
1032 free_ablock = ablock;
1033 /* Update busy count. */
1034 ABLOCKS_BUSY (abase) =
1035 (struct ablocks *) (-2 + (intptr_t) ABLOCKS_BUSY (abase));
1037 if (2 > (intptr_t) ABLOCKS_BUSY (abase))
1038 { /* All the blocks are free. */
1039 int i = 0, aligned = (intptr_t) ABLOCKS_BUSY (abase);
1040 struct ablock **tem = &free_ablock;
1041 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1043 while (*tem)
1045 if (*tem >= (struct ablock *) abase && *tem < atop)
1047 i++;
1048 *tem = (*tem)->x.next_free;
1050 else
1051 tem = &(*tem)->x.next_free;
1053 eassert ((aligned & 1) == aligned);
1054 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1055 #ifdef USE_POSIX_MEMALIGN
1056 eassert ((uintptr_t) ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1057 #endif
1058 free (ABLOCKS_BASE (abase));
1060 MALLOC_UNBLOCK_INPUT;
1063 /* Return a new buffer structure allocated from the heap with
1064 a call to lisp_malloc. */
1066 struct buffer *
1067 allocate_buffer (void)
1069 struct buffer *b
1070 = (struct buffer *) lisp_malloc (sizeof (struct buffer),
1071 MEM_TYPE_BUFFER);
1072 XSETPVECTYPESIZE (b, PVEC_BUFFER,
1073 ((sizeof (struct buffer) + sizeof (EMACS_INT) - 1)
1074 / sizeof (EMACS_INT)));
1075 return b;
1079 #ifndef SYSTEM_MALLOC
1081 /* Arranging to disable input signals while we're in malloc.
1083 This only works with GNU malloc. To help out systems which can't
1084 use GNU malloc, all the calls to malloc, realloc, and free
1085 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
1086 pair; unfortunately, we have no idea what C library functions
1087 might call malloc, so we can't really protect them unless you're
1088 using GNU malloc. Fortunately, most of the major operating systems
1089 can use GNU malloc. */
1091 #ifndef SYNC_INPUT
1092 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
1093 there's no need to block input around malloc. */
1095 #ifndef DOUG_LEA_MALLOC
1096 extern void * (*__malloc_hook) (size_t, const void *);
1097 extern void * (*__realloc_hook) (void *, size_t, const void *);
1098 extern void (*__free_hook) (void *, const void *);
1099 /* Else declared in malloc.h, perhaps with an extra arg. */
1100 #endif /* DOUG_LEA_MALLOC */
1101 static void * (*old_malloc_hook) (size_t, const void *);
1102 static void * (*old_realloc_hook) (void *, size_t, const void*);
1103 static void (*old_free_hook) (void*, const void*);
1105 #ifdef DOUG_LEA_MALLOC
1106 # define BYTES_USED (mallinfo ().uordblks)
1107 #else
1108 # define BYTES_USED _bytes_used
1109 #endif
1111 static size_t bytes_used_when_reconsidered;
1113 /* Value of _bytes_used, when spare_memory was freed. */
1115 static size_t bytes_used_when_full;
1117 /* This function is used as the hook for free to call. */
1119 static void
1120 emacs_blocked_free (void *ptr, const void *ptr2)
1122 BLOCK_INPUT_ALLOC;
1124 #ifdef GC_MALLOC_CHECK
1125 if (ptr)
1127 struct mem_node *m;
1129 m = mem_find (ptr);
1130 if (m == MEM_NIL || m->start != ptr)
1132 fprintf (stderr,
1133 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
1134 abort ();
1136 else
1138 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
1139 mem_delete (m);
1142 #endif /* GC_MALLOC_CHECK */
1144 __free_hook = old_free_hook;
1145 free (ptr);
1147 /* If we released our reserve (due to running out of memory),
1148 and we have a fair amount free once again,
1149 try to set aside another reserve in case we run out once more. */
1150 if (! NILP (Vmemory_full)
1151 /* Verify there is enough space that even with the malloc
1152 hysteresis this call won't run out again.
1153 The code here is correct as long as SPARE_MEMORY
1154 is substantially larger than the block size malloc uses. */
1155 && (bytes_used_when_full
1156 > ((bytes_used_when_reconsidered = BYTES_USED)
1157 + max (malloc_hysteresis, 4) * SPARE_MEMORY)))
1158 refill_memory_reserve ();
1160 __free_hook = emacs_blocked_free;
1161 UNBLOCK_INPUT_ALLOC;
1165 /* This function is the malloc hook that Emacs uses. */
1167 static void *
1168 emacs_blocked_malloc (size_t size, const void *ptr)
1170 void *value;
1172 BLOCK_INPUT_ALLOC;
1173 __malloc_hook = old_malloc_hook;
1174 #ifdef DOUG_LEA_MALLOC
1175 /* Segfaults on my system. --lorentey */
1176 /* mallopt (M_TOP_PAD, malloc_hysteresis * 4096); */
1177 #else
1178 __malloc_extra_blocks = malloc_hysteresis;
1179 #endif
1181 value = (void *) malloc (size);
1183 #ifdef GC_MALLOC_CHECK
1185 struct mem_node *m = mem_find (value);
1186 if (m != MEM_NIL)
1188 fprintf (stderr, "Malloc returned %p which is already in use\n",
1189 value);
1190 fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
1191 m->start, m->end, (char *) m->end - (char *) m->start,
1192 m->type);
1193 abort ();
1196 if (!dont_register_blocks)
1198 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
1199 allocated_mem_type = MEM_TYPE_NON_LISP;
1202 #endif /* GC_MALLOC_CHECK */
1204 __malloc_hook = emacs_blocked_malloc;
1205 UNBLOCK_INPUT_ALLOC;
1207 /* fprintf (stderr, "%p malloc\n", value); */
1208 return value;
1212 /* This function is the realloc hook that Emacs uses. */
1214 static void *
1215 emacs_blocked_realloc (void *ptr, size_t size, const void *ptr2)
1217 void *value;
1219 BLOCK_INPUT_ALLOC;
1220 __realloc_hook = old_realloc_hook;
1222 #ifdef GC_MALLOC_CHECK
1223 if (ptr)
1225 struct mem_node *m = mem_find (ptr);
1226 if (m == MEM_NIL || m->start != ptr)
1228 fprintf (stderr,
1229 "Realloc of %p which wasn't allocated with malloc\n",
1230 ptr);
1231 abort ();
1234 mem_delete (m);
1237 /* fprintf (stderr, "%p -> realloc\n", ptr); */
1239 /* Prevent malloc from registering blocks. */
1240 dont_register_blocks = 1;
1241 #endif /* GC_MALLOC_CHECK */
1243 value = (void *) realloc (ptr, size);
1245 #ifdef GC_MALLOC_CHECK
1246 dont_register_blocks = 0;
1249 struct mem_node *m = mem_find (value);
1250 if (m != MEM_NIL)
1252 fprintf (stderr, "Realloc returns memory that is already in use\n");
1253 abort ();
1256 /* Can't handle zero size regions in the red-black tree. */
1257 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
1260 /* fprintf (stderr, "%p <- realloc\n", value); */
1261 #endif /* GC_MALLOC_CHECK */
1263 __realloc_hook = emacs_blocked_realloc;
1264 UNBLOCK_INPUT_ALLOC;
1266 return value;
1270 #ifdef HAVE_PTHREAD
1271 /* Called from Fdump_emacs so that when the dumped Emacs starts, it has a
1272 normal malloc. Some thread implementations need this as they call
1273 malloc before main. The pthread_self call in BLOCK_INPUT_ALLOC then
1274 calls malloc because it is the first call, and we have an endless loop. */
1276 void
1277 reset_malloc_hooks (void)
1279 __free_hook = old_free_hook;
1280 __malloc_hook = old_malloc_hook;
1281 __realloc_hook = old_realloc_hook;
1283 #endif /* HAVE_PTHREAD */
1286 /* Called from main to set up malloc to use our hooks. */
1288 void
1289 uninterrupt_malloc (void)
1291 #ifdef HAVE_PTHREAD
1292 #ifdef DOUG_LEA_MALLOC
1293 pthread_mutexattr_t attr;
1295 /* GLIBC has a faster way to do this, but lets keep it portable.
1296 This is according to the Single UNIX Specification. */
1297 pthread_mutexattr_init (&attr);
1298 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1299 pthread_mutex_init (&alloc_mutex, &attr);
1300 #else /* !DOUG_LEA_MALLOC */
1301 /* Some systems such as Solaris 2.6 don't have a recursive mutex,
1302 and the bundled gmalloc.c doesn't require it. */
1303 pthread_mutex_init (&alloc_mutex, NULL);
1304 #endif /* !DOUG_LEA_MALLOC */
1305 #endif /* HAVE_PTHREAD */
1307 if (__free_hook != emacs_blocked_free)
1308 old_free_hook = __free_hook;
1309 __free_hook = emacs_blocked_free;
1311 if (__malloc_hook != emacs_blocked_malloc)
1312 old_malloc_hook = __malloc_hook;
1313 __malloc_hook = emacs_blocked_malloc;
1315 if (__realloc_hook != emacs_blocked_realloc)
1316 old_realloc_hook = __realloc_hook;
1317 __realloc_hook = emacs_blocked_realloc;
1320 #endif /* not SYNC_INPUT */
1321 #endif /* not SYSTEM_MALLOC */
1325 /***********************************************************************
1326 Interval Allocation
1327 ***********************************************************************/
1329 /* Number of intervals allocated in an interval_block structure.
1330 The 1020 is 1024 minus malloc overhead. */
1332 #define INTERVAL_BLOCK_SIZE \
1333 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1335 /* Intervals are allocated in chunks in form of an interval_block
1336 structure. */
1338 struct interval_block
1340 /* Place `intervals' first, to preserve alignment. */
1341 struct interval intervals[INTERVAL_BLOCK_SIZE];
1342 struct interval_block *next;
1345 /* Current interval block. Its `next' pointer points to older
1346 blocks. */
1348 static struct interval_block *interval_block;
1350 /* Index in interval_block above of the next unused interval
1351 structure. */
1353 static int interval_block_index;
1355 /* Number of free and live intervals. */
1357 static EMACS_INT total_free_intervals, total_intervals;
1359 /* List of free intervals. */
1361 static INTERVAL interval_free_list;
1364 /* Initialize interval allocation. */
1366 static void
1367 init_intervals (void)
1369 interval_block = NULL;
1370 interval_block_index = INTERVAL_BLOCK_SIZE;
1371 interval_free_list = 0;
1375 /* Return a new interval. */
1377 INTERVAL
1378 make_interval (void)
1380 INTERVAL val;
1382 /* eassert (!handling_signal); */
1384 MALLOC_BLOCK_INPUT;
1386 if (interval_free_list)
1388 val = interval_free_list;
1389 interval_free_list = INTERVAL_PARENT (interval_free_list);
1391 else
1393 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1395 register struct interval_block *newi;
1397 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
1398 MEM_TYPE_NON_LISP);
1400 newi->next = interval_block;
1401 interval_block = newi;
1402 interval_block_index = 0;
1404 val = &interval_block->intervals[interval_block_index++];
1407 MALLOC_UNBLOCK_INPUT;
1409 consing_since_gc += sizeof (struct interval);
1410 intervals_consed++;
1411 RESET_INTERVAL (val);
1412 val->gcmarkbit = 0;
1413 return val;
1417 /* Mark Lisp objects in interval I. */
1419 static void
1420 mark_interval (register INTERVAL i, Lisp_Object dummy)
1422 eassert (!i->gcmarkbit); /* Intervals are never shared. */
1423 i->gcmarkbit = 1;
1424 mark_object (i->plist);
1428 /* Mark the interval tree rooted in TREE. Don't call this directly;
1429 use the macro MARK_INTERVAL_TREE instead. */
1431 static void
1432 mark_interval_tree (register INTERVAL tree)
1434 /* No need to test if this tree has been marked already; this
1435 function is always called through the MARK_INTERVAL_TREE macro,
1436 which takes care of that. */
1438 traverse_intervals_noorder (tree, mark_interval, Qnil);
1442 /* Mark the interval tree rooted in I. */
1444 #define MARK_INTERVAL_TREE(i) \
1445 do { \
1446 if (!NULL_INTERVAL_P (i) && !i->gcmarkbit) \
1447 mark_interval_tree (i); \
1448 } while (0)
1451 #define UNMARK_BALANCE_INTERVALS(i) \
1452 do { \
1453 if (! NULL_INTERVAL_P (i)) \
1454 (i) = balance_intervals (i); \
1455 } while (0)
1458 /* Number support. If USE_LISP_UNION_TYPE is in effect, we
1459 can't create number objects in macros. */
1460 #ifndef make_number
1461 Lisp_Object
1462 make_number (EMACS_INT n)
1464 Lisp_Object obj;
1465 obj.s.val = n;
1466 obj.s.type = Lisp_Int;
1467 return obj;
1469 #endif
1471 /***********************************************************************
1472 String Allocation
1473 ***********************************************************************/
1475 /* Lisp_Strings are allocated in string_block structures. When a new
1476 string_block is allocated, all the Lisp_Strings it contains are
1477 added to a free-list string_free_list. When a new Lisp_String is
1478 needed, it is taken from that list. During the sweep phase of GC,
1479 string_blocks that are entirely free are freed, except two which
1480 we keep.
1482 String data is allocated from sblock structures. Strings larger
1483 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1484 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1486 Sblocks consist internally of sdata structures, one for each
1487 Lisp_String. The sdata structure points to the Lisp_String it
1488 belongs to. The Lisp_String points back to the `u.data' member of
1489 its sdata structure.
1491 When a Lisp_String is freed during GC, it is put back on
1492 string_free_list, and its `data' member and its sdata's `string'
1493 pointer is set to null. The size of the string is recorded in the
1494 `u.nbytes' member of the sdata. So, sdata structures that are no
1495 longer used, can be easily recognized, and it's easy to compact the
1496 sblocks of small strings which we do in compact_small_strings. */
1498 /* Size in bytes of an sblock structure used for small strings. This
1499 is 8192 minus malloc overhead. */
1501 #define SBLOCK_SIZE 8188
1503 /* Strings larger than this are considered large strings. String data
1504 for large strings is allocated from individual sblocks. */
1506 #define LARGE_STRING_BYTES 1024
1508 /* Structure describing string memory sub-allocated from an sblock.
1509 This is where the contents of Lisp strings are stored. */
1511 struct sdata
1513 /* Back-pointer to the string this sdata belongs to. If null, this
1514 structure is free, and the NBYTES member of the union below
1515 contains the string's byte size (the same value that STRING_BYTES
1516 would return if STRING were non-null). If non-null, STRING_BYTES
1517 (STRING) is the size of the data, and DATA contains the string's
1518 contents. */
1519 struct Lisp_String *string;
1521 #ifdef GC_CHECK_STRING_BYTES
1523 EMACS_INT nbytes;
1524 unsigned char data[1];
1526 #define SDATA_NBYTES(S) (S)->nbytes
1527 #define SDATA_DATA(S) (S)->data
1528 #define SDATA_SELECTOR(member) member
1530 #else /* not GC_CHECK_STRING_BYTES */
1532 union
1534 /* When STRING is non-null. */
1535 unsigned char data[1];
1537 /* When STRING is null. */
1538 EMACS_INT nbytes;
1539 } u;
1541 #define SDATA_NBYTES(S) (S)->u.nbytes
1542 #define SDATA_DATA(S) (S)->u.data
1543 #define SDATA_SELECTOR(member) u.member
1545 #endif /* not GC_CHECK_STRING_BYTES */
1547 #define SDATA_DATA_OFFSET offsetof (struct sdata, SDATA_SELECTOR (data))
1551 /* Structure describing a block of memory which is sub-allocated to
1552 obtain string data memory for strings. Blocks for small strings
1553 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1554 as large as needed. */
1556 struct sblock
1558 /* Next in list. */
1559 struct sblock *next;
1561 /* Pointer to the next free sdata block. This points past the end
1562 of the sblock if there isn't any space left in this block. */
1563 struct sdata *next_free;
1565 /* Start of data. */
1566 struct sdata first_data;
1569 /* Number of Lisp strings in a string_block structure. The 1020 is
1570 1024 minus malloc overhead. */
1572 #define STRING_BLOCK_SIZE \
1573 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1575 /* Structure describing a block from which Lisp_String structures
1576 are allocated. */
1578 struct string_block
1580 /* Place `strings' first, to preserve alignment. */
1581 struct Lisp_String strings[STRING_BLOCK_SIZE];
1582 struct string_block *next;
1585 /* Head and tail of the list of sblock structures holding Lisp string
1586 data. We always allocate from current_sblock. The NEXT pointers
1587 in the sblock structures go from oldest_sblock to current_sblock. */
1589 static struct sblock *oldest_sblock, *current_sblock;
1591 /* List of sblocks for large strings. */
1593 static struct sblock *large_sblocks;
1595 /* List of string_block structures. */
1597 static struct string_block *string_blocks;
1599 /* Free-list of Lisp_Strings. */
1601 static struct Lisp_String *string_free_list;
1603 /* Number of live and free Lisp_Strings. */
1605 static EMACS_INT total_strings, total_free_strings;
1607 /* Number of bytes used by live strings. */
1609 static EMACS_INT total_string_size;
1611 /* Given a pointer to a Lisp_String S which is on the free-list
1612 string_free_list, return a pointer to its successor in the
1613 free-list. */
1615 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1617 /* Return a pointer to the sdata structure belonging to Lisp string S.
1618 S must be live, i.e. S->data must not be null. S->data is actually
1619 a pointer to the `u.data' member of its sdata structure; the
1620 structure starts at a constant offset in front of that. */
1622 #define SDATA_OF_STRING(S) ((struct sdata *) ((S)->data - SDATA_DATA_OFFSET))
1625 #ifdef GC_CHECK_STRING_OVERRUN
1627 /* We check for overrun in string data blocks by appending a small
1628 "cookie" after each allocated string data block, and check for the
1629 presence of this cookie during GC. */
1631 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1632 static char const string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1633 { '\xde', '\xad', '\xbe', '\xef' };
1635 #else
1636 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1637 #endif
1639 /* Value is the size of an sdata structure large enough to hold NBYTES
1640 bytes of string data. The value returned includes a terminating
1641 NUL byte, the size of the sdata structure, and padding. */
1643 #ifdef GC_CHECK_STRING_BYTES
1645 #define SDATA_SIZE(NBYTES) \
1646 ((SDATA_DATA_OFFSET \
1647 + (NBYTES) + 1 \
1648 + sizeof (EMACS_INT) - 1) \
1649 & ~(sizeof (EMACS_INT) - 1))
1651 #else /* not GC_CHECK_STRING_BYTES */
1653 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1654 less than the size of that member. The 'max' is not needed when
1655 SDATA_DATA_OFFSET is a multiple of sizeof (EMACS_INT), because then the
1656 alignment code reserves enough space. */
1658 #define SDATA_SIZE(NBYTES) \
1659 ((SDATA_DATA_OFFSET \
1660 + (SDATA_DATA_OFFSET % sizeof (EMACS_INT) == 0 \
1661 ? NBYTES \
1662 : max (NBYTES, sizeof (EMACS_INT) - 1)) \
1663 + 1 \
1664 + sizeof (EMACS_INT) - 1) \
1665 & ~(sizeof (EMACS_INT) - 1))
1667 #endif /* not GC_CHECK_STRING_BYTES */
1669 /* Extra bytes to allocate for each string. */
1671 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1673 /* Exact bound on the number of bytes in a string, not counting the
1674 terminating null. A string cannot contain more bytes than
1675 STRING_BYTES_BOUND, nor can it be so long that the size_t
1676 arithmetic in allocate_string_data would overflow while it is
1677 calculating a value to be passed to malloc. */
1678 #define STRING_BYTES_MAX \
1679 min (STRING_BYTES_BOUND, \
1680 ((SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD \
1681 - GC_STRING_EXTRA \
1682 - offsetof (struct sblock, first_data) \
1683 - SDATA_DATA_OFFSET) \
1684 & ~(sizeof (EMACS_INT) - 1)))
1686 /* Initialize string allocation. Called from init_alloc_once. */
1688 static void
1689 init_strings (void)
1691 total_strings = total_free_strings = total_string_size = 0;
1692 oldest_sblock = current_sblock = large_sblocks = NULL;
1693 string_blocks = NULL;
1694 string_free_list = NULL;
1695 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1696 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1700 #ifdef GC_CHECK_STRING_BYTES
1702 static int check_string_bytes_count;
1704 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1707 /* Like GC_STRING_BYTES, but with debugging check. */
1709 EMACS_INT
1710 string_bytes (struct Lisp_String *s)
1712 EMACS_INT nbytes =
1713 (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1715 if (!PURE_POINTER_P (s)
1716 && s->data
1717 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1718 abort ();
1719 return nbytes;
1722 /* Check validity of Lisp strings' string_bytes member in B. */
1724 static void
1725 check_sblock (struct sblock *b)
1727 struct sdata *from, *end, *from_end;
1729 end = b->next_free;
1731 for (from = &b->first_data; from < end; from = from_end)
1733 /* Compute the next FROM here because copying below may
1734 overwrite data we need to compute it. */
1735 EMACS_INT nbytes;
1737 /* Check that the string size recorded in the string is the
1738 same as the one recorded in the sdata structure. */
1739 if (from->string)
1740 CHECK_STRING_BYTES (from->string);
1742 if (from->string)
1743 nbytes = GC_STRING_BYTES (from->string);
1744 else
1745 nbytes = SDATA_NBYTES (from);
1747 nbytes = SDATA_SIZE (nbytes);
1748 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1753 /* Check validity of Lisp strings' string_bytes member. ALL_P
1754 non-zero means check all strings, otherwise check only most
1755 recently allocated strings. Used for hunting a bug. */
1757 static void
1758 check_string_bytes (int all_p)
1760 if (all_p)
1762 struct sblock *b;
1764 for (b = large_sblocks; b; b = b->next)
1766 struct Lisp_String *s = b->first_data.string;
1767 if (s)
1768 CHECK_STRING_BYTES (s);
1771 for (b = oldest_sblock; b; b = b->next)
1772 check_sblock (b);
1774 else
1775 check_sblock (current_sblock);
1778 #endif /* GC_CHECK_STRING_BYTES */
1780 #ifdef GC_CHECK_STRING_FREE_LIST
1782 /* Walk through the string free list looking for bogus next pointers.
1783 This may catch buffer overrun from a previous string. */
1785 static void
1786 check_string_free_list (void)
1788 struct Lisp_String *s;
1790 /* Pop a Lisp_String off the free-list. */
1791 s = string_free_list;
1792 while (s != NULL)
1794 if ((uintptr_t) s < 1024)
1795 abort();
1796 s = NEXT_FREE_LISP_STRING (s);
1799 #else
1800 #define check_string_free_list()
1801 #endif
1803 /* Return a new Lisp_String. */
1805 static struct Lisp_String *
1806 allocate_string (void)
1808 struct Lisp_String *s;
1810 /* eassert (!handling_signal); */
1812 MALLOC_BLOCK_INPUT;
1814 /* If the free-list is empty, allocate a new string_block, and
1815 add all the Lisp_Strings in it to the free-list. */
1816 if (string_free_list == NULL)
1818 struct string_block *b;
1819 int i;
1821 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1822 memset (b, 0, sizeof *b);
1823 b->next = string_blocks;
1824 string_blocks = b;
1826 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1828 s = b->strings + i;
1829 NEXT_FREE_LISP_STRING (s) = string_free_list;
1830 string_free_list = s;
1833 total_free_strings += STRING_BLOCK_SIZE;
1836 check_string_free_list ();
1838 /* Pop a Lisp_String off the free-list. */
1839 s = string_free_list;
1840 string_free_list = NEXT_FREE_LISP_STRING (s);
1842 MALLOC_UNBLOCK_INPUT;
1844 /* Probably not strictly necessary, but play it safe. */
1845 memset (s, 0, sizeof *s);
1847 --total_free_strings;
1848 ++total_strings;
1849 ++strings_consed;
1850 consing_since_gc += sizeof *s;
1852 #ifdef GC_CHECK_STRING_BYTES
1853 if (!noninteractive)
1855 if (++check_string_bytes_count == 200)
1857 check_string_bytes_count = 0;
1858 check_string_bytes (1);
1860 else
1861 check_string_bytes (0);
1863 #endif /* GC_CHECK_STRING_BYTES */
1865 return s;
1869 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1870 plus a NUL byte at the end. Allocate an sdata structure for S, and
1871 set S->data to its `u.data' member. Store a NUL byte at the end of
1872 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1873 S->data if it was initially non-null. */
1875 void
1876 allocate_string_data (struct Lisp_String *s,
1877 EMACS_INT nchars, EMACS_INT nbytes)
1879 struct sdata *data, *old_data;
1880 struct sblock *b;
1881 EMACS_INT needed, old_nbytes;
1883 if (STRING_BYTES_MAX < nbytes)
1884 string_overflow ();
1886 /* Determine the number of bytes needed to store NBYTES bytes
1887 of string data. */
1888 needed = SDATA_SIZE (nbytes);
1889 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1890 old_nbytes = GC_STRING_BYTES (s);
1892 MALLOC_BLOCK_INPUT;
1894 if (nbytes > LARGE_STRING_BYTES)
1896 size_t size = offsetof (struct sblock, first_data) + needed;
1898 #ifdef DOUG_LEA_MALLOC
1899 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1900 because mapped region contents are not preserved in
1901 a dumped Emacs.
1903 In case you think of allowing it in a dumped Emacs at the
1904 cost of not being able to re-dump, there's another reason:
1905 mmap'ed data typically have an address towards the top of the
1906 address space, which won't fit into an EMACS_INT (at least on
1907 32-bit systems with the current tagging scheme). --fx */
1908 mallopt (M_MMAP_MAX, 0);
1909 #endif
1911 b = (struct sblock *) lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
1913 #ifdef DOUG_LEA_MALLOC
1914 /* Back to a reasonable maximum of mmap'ed areas. */
1915 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1916 #endif
1918 b->next_free = &b->first_data;
1919 b->first_data.string = NULL;
1920 b->next = large_sblocks;
1921 large_sblocks = b;
1923 else if (current_sblock == NULL
1924 || (((char *) current_sblock + SBLOCK_SIZE
1925 - (char *) current_sblock->next_free)
1926 < (needed + GC_STRING_EXTRA)))
1928 /* Not enough room in the current sblock. */
1929 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
1930 b->next_free = &b->first_data;
1931 b->first_data.string = NULL;
1932 b->next = NULL;
1934 if (current_sblock)
1935 current_sblock->next = b;
1936 else
1937 oldest_sblock = b;
1938 current_sblock = b;
1940 else
1941 b = current_sblock;
1943 data = b->next_free;
1944 b->next_free = (struct sdata *) ((char *) data + needed + GC_STRING_EXTRA);
1946 MALLOC_UNBLOCK_INPUT;
1948 data->string = s;
1949 s->data = SDATA_DATA (data);
1950 #ifdef GC_CHECK_STRING_BYTES
1951 SDATA_NBYTES (data) = nbytes;
1952 #endif
1953 s->size = nchars;
1954 s->size_byte = nbytes;
1955 s->data[nbytes] = '\0';
1956 #ifdef GC_CHECK_STRING_OVERRUN
1957 memcpy ((char *) data + needed, string_overrun_cookie,
1958 GC_STRING_OVERRUN_COOKIE_SIZE);
1959 #endif
1961 /* If S had already data assigned, mark that as free by setting its
1962 string back-pointer to null, and recording the size of the data
1963 in it. */
1964 if (old_data)
1966 SDATA_NBYTES (old_data) = old_nbytes;
1967 old_data->string = NULL;
1970 consing_since_gc += needed;
1974 /* Sweep and compact strings. */
1976 static void
1977 sweep_strings (void)
1979 struct string_block *b, *next;
1980 struct string_block *live_blocks = NULL;
1982 string_free_list = NULL;
1983 total_strings = total_free_strings = 0;
1984 total_string_size = 0;
1986 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1987 for (b = string_blocks; b; b = next)
1989 int i, nfree = 0;
1990 struct Lisp_String *free_list_before = string_free_list;
1992 next = b->next;
1994 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
1996 struct Lisp_String *s = b->strings + i;
1998 if (s->data)
2000 /* String was not on free-list before. */
2001 if (STRING_MARKED_P (s))
2003 /* String is live; unmark it and its intervals. */
2004 UNMARK_STRING (s);
2006 if (!NULL_INTERVAL_P (s->intervals))
2007 UNMARK_BALANCE_INTERVALS (s->intervals);
2009 ++total_strings;
2010 total_string_size += STRING_BYTES (s);
2012 else
2014 /* String is dead. Put it on the free-list. */
2015 struct sdata *data = SDATA_OF_STRING (s);
2017 /* Save the size of S in its sdata so that we know
2018 how large that is. Reset the sdata's string
2019 back-pointer so that we know it's free. */
2020 #ifdef GC_CHECK_STRING_BYTES
2021 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
2022 abort ();
2023 #else
2024 data->u.nbytes = GC_STRING_BYTES (s);
2025 #endif
2026 data->string = NULL;
2028 /* Reset the strings's `data' member so that we
2029 know it's free. */
2030 s->data = NULL;
2032 /* Put the string on the free-list. */
2033 NEXT_FREE_LISP_STRING (s) = string_free_list;
2034 string_free_list = s;
2035 ++nfree;
2038 else
2040 /* S was on the free-list before. Put it there again. */
2041 NEXT_FREE_LISP_STRING (s) = string_free_list;
2042 string_free_list = s;
2043 ++nfree;
2047 /* Free blocks that contain free Lisp_Strings only, except
2048 the first two of them. */
2049 if (nfree == STRING_BLOCK_SIZE
2050 && total_free_strings > STRING_BLOCK_SIZE)
2052 lisp_free (b);
2053 string_free_list = free_list_before;
2055 else
2057 total_free_strings += nfree;
2058 b->next = live_blocks;
2059 live_blocks = b;
2063 check_string_free_list ();
2065 string_blocks = live_blocks;
2066 free_large_strings ();
2067 compact_small_strings ();
2069 check_string_free_list ();
2073 /* Free dead large strings. */
2075 static void
2076 free_large_strings (void)
2078 struct sblock *b, *next;
2079 struct sblock *live_blocks = NULL;
2081 for (b = large_sblocks; b; b = next)
2083 next = b->next;
2085 if (b->first_data.string == NULL)
2086 lisp_free (b);
2087 else
2089 b->next = live_blocks;
2090 live_blocks = b;
2094 large_sblocks = live_blocks;
2098 /* Compact data of small strings. Free sblocks that don't contain
2099 data of live strings after compaction. */
2101 static void
2102 compact_small_strings (void)
2104 struct sblock *b, *tb, *next;
2105 struct sdata *from, *to, *end, *tb_end;
2106 struct sdata *to_end, *from_end;
2108 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2109 to, and TB_END is the end of TB. */
2110 tb = oldest_sblock;
2111 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2112 to = &tb->first_data;
2114 /* Step through the blocks from the oldest to the youngest. We
2115 expect that old blocks will stabilize over time, so that less
2116 copying will happen this way. */
2117 for (b = oldest_sblock; b; b = b->next)
2119 end = b->next_free;
2120 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2122 for (from = &b->first_data; from < end; from = from_end)
2124 /* Compute the next FROM here because copying below may
2125 overwrite data we need to compute it. */
2126 EMACS_INT nbytes;
2128 #ifdef GC_CHECK_STRING_BYTES
2129 /* Check that the string size recorded in the string is the
2130 same as the one recorded in the sdata structure. */
2131 if (from->string
2132 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
2133 abort ();
2134 #endif /* GC_CHECK_STRING_BYTES */
2136 if (from->string)
2137 nbytes = GC_STRING_BYTES (from->string);
2138 else
2139 nbytes = SDATA_NBYTES (from);
2141 if (nbytes > LARGE_STRING_BYTES)
2142 abort ();
2144 nbytes = SDATA_SIZE (nbytes);
2145 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
2147 #ifdef GC_CHECK_STRING_OVERRUN
2148 if (memcmp (string_overrun_cookie,
2149 (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
2150 GC_STRING_OVERRUN_COOKIE_SIZE))
2151 abort ();
2152 #endif
2154 /* FROM->string non-null means it's alive. Copy its data. */
2155 if (from->string)
2157 /* If TB is full, proceed with the next sblock. */
2158 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2159 if (to_end > tb_end)
2161 tb->next_free = to;
2162 tb = tb->next;
2163 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2164 to = &tb->first_data;
2165 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2168 /* Copy, and update the string's `data' pointer. */
2169 if (from != to)
2171 xassert (tb != b || to < from);
2172 memmove (to, from, nbytes + GC_STRING_EXTRA);
2173 to->string->data = SDATA_DATA (to);
2176 /* Advance past the sdata we copied to. */
2177 to = to_end;
2182 /* The rest of the sblocks following TB don't contain live data, so
2183 we can free them. */
2184 for (b = tb->next; b; b = next)
2186 next = b->next;
2187 lisp_free (b);
2190 tb->next_free = to;
2191 tb->next = NULL;
2192 current_sblock = tb;
2195 void
2196 string_overflow (void)
2198 error ("Maximum string size exceeded");
2201 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2202 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2203 LENGTH must be an integer.
2204 INIT must be an integer that represents a character. */)
2205 (Lisp_Object length, Lisp_Object init)
2207 register Lisp_Object val;
2208 register unsigned char *p, *end;
2209 int c;
2210 EMACS_INT nbytes;
2212 CHECK_NATNUM (length);
2213 CHECK_CHARACTER (init);
2215 c = XFASTINT (init);
2216 if (ASCII_CHAR_P (c))
2218 nbytes = XINT (length);
2219 val = make_uninit_string (nbytes);
2220 p = SDATA (val);
2221 end = p + SCHARS (val);
2222 while (p != end)
2223 *p++ = c;
2225 else
2227 unsigned char str[MAX_MULTIBYTE_LENGTH];
2228 int len = CHAR_STRING (c, str);
2229 EMACS_INT string_len = XINT (length);
2231 if (string_len > STRING_BYTES_MAX / len)
2232 string_overflow ();
2233 nbytes = len * string_len;
2234 val = make_uninit_multibyte_string (string_len, nbytes);
2235 p = SDATA (val);
2236 end = p + nbytes;
2237 while (p != end)
2239 memcpy (p, str, len);
2240 p += len;
2244 *p = 0;
2245 return val;
2249 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2250 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2251 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2252 (Lisp_Object length, Lisp_Object init)
2254 register Lisp_Object val;
2255 struct Lisp_Bool_Vector *p;
2256 EMACS_INT length_in_chars, length_in_elts;
2257 int bits_per_value;
2259 CHECK_NATNUM (length);
2261 bits_per_value = sizeof (EMACS_INT) * BOOL_VECTOR_BITS_PER_CHAR;
2263 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
2264 length_in_chars = ((XFASTINT (length) + BOOL_VECTOR_BITS_PER_CHAR - 1)
2265 / BOOL_VECTOR_BITS_PER_CHAR);
2267 /* We must allocate one more elements than LENGTH_IN_ELTS for the
2268 slot `size' of the struct Lisp_Bool_Vector. */
2269 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
2271 /* No Lisp_Object to trace in there. */
2272 XSETPVECTYPESIZE (XVECTOR (val), PVEC_BOOL_VECTOR, 0);
2274 p = XBOOL_VECTOR (val);
2275 p->size = XFASTINT (length);
2277 if (length_in_chars)
2279 memset (p->data, ! NILP (init) ? -1 : 0, length_in_chars);
2281 /* Clear any extraneous bits in the last byte. */
2282 p->data[length_in_chars - 1]
2283 &= (1 << (XINT (length) % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2286 return val;
2290 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2291 of characters from the contents. This string may be unibyte or
2292 multibyte, depending on the contents. */
2294 Lisp_Object
2295 make_string (const char *contents, EMACS_INT nbytes)
2297 register Lisp_Object val;
2298 EMACS_INT nchars, multibyte_nbytes;
2300 parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
2301 &nchars, &multibyte_nbytes);
2302 if (nbytes == nchars || nbytes != multibyte_nbytes)
2303 /* CONTENTS contains no multibyte sequences or contains an invalid
2304 multibyte sequence. We must make unibyte string. */
2305 val = make_unibyte_string (contents, nbytes);
2306 else
2307 val = make_multibyte_string (contents, nchars, nbytes);
2308 return val;
2312 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
2314 Lisp_Object
2315 make_unibyte_string (const char *contents, EMACS_INT length)
2317 register Lisp_Object val;
2318 val = make_uninit_string (length);
2319 memcpy (SDATA (val), contents, length);
2320 return val;
2324 /* Make a multibyte string from NCHARS characters occupying NBYTES
2325 bytes at CONTENTS. */
2327 Lisp_Object
2328 make_multibyte_string (const char *contents,
2329 EMACS_INT nchars, EMACS_INT nbytes)
2331 register Lisp_Object val;
2332 val = make_uninit_multibyte_string (nchars, nbytes);
2333 memcpy (SDATA (val), contents, nbytes);
2334 return val;
2338 /* Make a string from NCHARS characters occupying NBYTES bytes at
2339 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2341 Lisp_Object
2342 make_string_from_bytes (const char *contents,
2343 EMACS_INT nchars, EMACS_INT nbytes)
2345 register Lisp_Object val;
2346 val = make_uninit_multibyte_string (nchars, nbytes);
2347 memcpy (SDATA (val), contents, nbytes);
2348 if (SBYTES (val) == SCHARS (val))
2349 STRING_SET_UNIBYTE (val);
2350 return val;
2354 /* Make a string from NCHARS characters occupying NBYTES bytes at
2355 CONTENTS. The argument MULTIBYTE controls whether to label the
2356 string as multibyte. If NCHARS is negative, it counts the number of
2357 characters by itself. */
2359 Lisp_Object
2360 make_specified_string (const char *contents,
2361 EMACS_INT nchars, EMACS_INT nbytes, int multibyte)
2363 register Lisp_Object val;
2365 if (nchars < 0)
2367 if (multibyte)
2368 nchars = multibyte_chars_in_text ((const unsigned char *) contents,
2369 nbytes);
2370 else
2371 nchars = nbytes;
2373 val = make_uninit_multibyte_string (nchars, nbytes);
2374 memcpy (SDATA (val), contents, nbytes);
2375 if (!multibyte)
2376 STRING_SET_UNIBYTE (val);
2377 return val;
2381 /* Make a string from the data at STR, treating it as multibyte if the
2382 data warrants. */
2384 Lisp_Object
2385 build_string (const char *str)
2387 return make_string (str, strlen (str));
2391 /* Return an unibyte Lisp_String set up to hold LENGTH characters
2392 occupying LENGTH bytes. */
2394 Lisp_Object
2395 make_uninit_string (EMACS_INT length)
2397 Lisp_Object val;
2399 if (!length)
2400 return empty_unibyte_string;
2401 val = make_uninit_multibyte_string (length, length);
2402 STRING_SET_UNIBYTE (val);
2403 return val;
2407 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2408 which occupy NBYTES bytes. */
2410 Lisp_Object
2411 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2413 Lisp_Object string;
2414 struct Lisp_String *s;
2416 if (nchars < 0)
2417 abort ();
2418 if (!nbytes)
2419 return empty_multibyte_string;
2421 s = allocate_string ();
2422 allocate_string_data (s, nchars, nbytes);
2423 XSETSTRING (string, s);
2424 string_chars_consed += nbytes;
2425 return string;
2430 /***********************************************************************
2431 Float Allocation
2432 ***********************************************************************/
2434 /* We store float cells inside of float_blocks, allocating a new
2435 float_block with malloc whenever necessary. Float cells reclaimed
2436 by GC are put on a free list to be reallocated before allocating
2437 any new float cells from the latest float_block. */
2439 #define FLOAT_BLOCK_SIZE \
2440 (((BLOCK_BYTES - sizeof (struct float_block *) \
2441 /* The compiler might add padding at the end. */ \
2442 - (sizeof (struct Lisp_Float) - sizeof (int))) * CHAR_BIT) \
2443 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2445 #define GETMARKBIT(block,n) \
2446 (((block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2447 >> ((n) % (sizeof(int) * CHAR_BIT))) \
2448 & 1)
2450 #define SETMARKBIT(block,n) \
2451 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2452 |= 1 << ((n) % (sizeof(int) * CHAR_BIT))
2454 #define UNSETMARKBIT(block,n) \
2455 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2456 &= ~(1 << ((n) % (sizeof(int) * CHAR_BIT)))
2458 #define FLOAT_BLOCK(fptr) \
2459 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2461 #define FLOAT_INDEX(fptr) \
2462 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2464 struct float_block
2466 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2467 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2468 int gcmarkbits[1 + FLOAT_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
2469 struct float_block *next;
2472 #define FLOAT_MARKED_P(fptr) \
2473 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2475 #define FLOAT_MARK(fptr) \
2476 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2478 #define FLOAT_UNMARK(fptr) \
2479 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2481 /* Current float_block. */
2483 static struct float_block *float_block;
2485 /* Index of first unused Lisp_Float in the current float_block. */
2487 static int float_block_index;
2489 /* Free-list of Lisp_Floats. */
2491 static struct Lisp_Float *float_free_list;
2494 /* Initialize float allocation. */
2496 static void
2497 init_float (void)
2499 float_block = NULL;
2500 float_block_index = FLOAT_BLOCK_SIZE; /* Force alloc of new float_block. */
2501 float_free_list = 0;
2505 /* Return a new float object with value FLOAT_VALUE. */
2507 Lisp_Object
2508 make_float (double float_value)
2510 register Lisp_Object val;
2512 /* eassert (!handling_signal); */
2514 MALLOC_BLOCK_INPUT;
2516 if (float_free_list)
2518 /* We use the data field for chaining the free list
2519 so that we won't use the same field that has the mark bit. */
2520 XSETFLOAT (val, float_free_list);
2521 float_free_list = float_free_list->u.chain;
2523 else
2525 if (float_block_index == FLOAT_BLOCK_SIZE)
2527 register struct float_block *new;
2529 new = (struct float_block *) lisp_align_malloc (sizeof *new,
2530 MEM_TYPE_FLOAT);
2531 new->next = float_block;
2532 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2533 float_block = new;
2534 float_block_index = 0;
2536 XSETFLOAT (val, &float_block->floats[float_block_index]);
2537 float_block_index++;
2540 MALLOC_UNBLOCK_INPUT;
2542 XFLOAT_INIT (val, float_value);
2543 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2544 consing_since_gc += sizeof (struct Lisp_Float);
2545 floats_consed++;
2546 return val;
2551 /***********************************************************************
2552 Cons Allocation
2553 ***********************************************************************/
2555 /* We store cons cells inside of cons_blocks, allocating a new
2556 cons_block with malloc whenever necessary. Cons cells reclaimed by
2557 GC are put on a free list to be reallocated before allocating
2558 any new cons cells from the latest cons_block. */
2560 #define CONS_BLOCK_SIZE \
2561 (((BLOCK_BYTES - sizeof (struct cons_block *)) * CHAR_BIT) \
2562 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2564 #define CONS_BLOCK(fptr) \
2565 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2567 #define CONS_INDEX(fptr) \
2568 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2570 struct cons_block
2572 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2573 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2574 int gcmarkbits[1 + CONS_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
2575 struct cons_block *next;
2578 #define CONS_MARKED_P(fptr) \
2579 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2581 #define CONS_MARK(fptr) \
2582 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2584 #define CONS_UNMARK(fptr) \
2585 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2587 /* Current cons_block. */
2589 static struct cons_block *cons_block;
2591 /* Index of first unused Lisp_Cons in the current block. */
2593 static int cons_block_index;
2595 /* Free-list of Lisp_Cons structures. */
2597 static struct Lisp_Cons *cons_free_list;
2600 /* Initialize cons allocation. */
2602 static void
2603 init_cons (void)
2605 cons_block = NULL;
2606 cons_block_index = CONS_BLOCK_SIZE; /* Force alloc of new cons_block. */
2607 cons_free_list = 0;
2611 /* Explicitly free a cons cell by putting it on the free-list. */
2613 void
2614 free_cons (struct Lisp_Cons *ptr)
2616 ptr->u.chain = cons_free_list;
2617 #if GC_MARK_STACK
2618 ptr->car = Vdead;
2619 #endif
2620 cons_free_list = ptr;
2623 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2624 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2625 (Lisp_Object car, Lisp_Object cdr)
2627 register Lisp_Object val;
2629 /* eassert (!handling_signal); */
2631 MALLOC_BLOCK_INPUT;
2633 if (cons_free_list)
2635 /* We use the cdr for chaining the free list
2636 so that we won't use the same field that has the mark bit. */
2637 XSETCONS (val, cons_free_list);
2638 cons_free_list = cons_free_list->u.chain;
2640 else
2642 if (cons_block_index == CONS_BLOCK_SIZE)
2644 register struct cons_block *new;
2645 new = (struct cons_block *) lisp_align_malloc (sizeof *new,
2646 MEM_TYPE_CONS);
2647 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2648 new->next = cons_block;
2649 cons_block = new;
2650 cons_block_index = 0;
2652 XSETCONS (val, &cons_block->conses[cons_block_index]);
2653 cons_block_index++;
2656 MALLOC_UNBLOCK_INPUT;
2658 XSETCAR (val, car);
2659 XSETCDR (val, cdr);
2660 eassert (!CONS_MARKED_P (XCONS (val)));
2661 consing_since_gc += sizeof (struct Lisp_Cons);
2662 cons_cells_consed++;
2663 return val;
2666 #ifdef GC_CHECK_CONS_LIST
2667 /* Get an error now if there's any junk in the cons free list. */
2668 void
2669 check_cons_list (void)
2671 struct Lisp_Cons *tail = cons_free_list;
2673 while (tail)
2674 tail = tail->u.chain;
2676 #endif
2678 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2680 Lisp_Object
2681 list1 (Lisp_Object arg1)
2683 return Fcons (arg1, Qnil);
2686 Lisp_Object
2687 list2 (Lisp_Object arg1, Lisp_Object arg2)
2689 return Fcons (arg1, Fcons (arg2, Qnil));
2693 Lisp_Object
2694 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2696 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2700 Lisp_Object
2701 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2703 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2707 Lisp_Object
2708 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2710 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2711 Fcons (arg5, Qnil)))));
2715 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2716 doc: /* Return a newly created list with specified arguments as elements.
2717 Any number of arguments, even zero arguments, are allowed.
2718 usage: (list &rest OBJECTS) */)
2719 (ptrdiff_t nargs, Lisp_Object *args)
2721 register Lisp_Object val;
2722 val = Qnil;
2724 while (nargs > 0)
2726 nargs--;
2727 val = Fcons (args[nargs], val);
2729 return val;
2733 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2734 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2735 (register Lisp_Object length, Lisp_Object init)
2737 register Lisp_Object val;
2738 register EMACS_INT size;
2740 CHECK_NATNUM (length);
2741 size = XFASTINT (length);
2743 val = Qnil;
2744 while (size > 0)
2746 val = Fcons (init, val);
2747 --size;
2749 if (size > 0)
2751 val = Fcons (init, val);
2752 --size;
2754 if (size > 0)
2756 val = Fcons (init, val);
2757 --size;
2759 if (size > 0)
2761 val = Fcons (init, val);
2762 --size;
2764 if (size > 0)
2766 val = Fcons (init, val);
2767 --size;
2773 QUIT;
2776 return val;
2781 /***********************************************************************
2782 Vector Allocation
2783 ***********************************************************************/
2785 /* Singly-linked list of all vectors. */
2787 static struct Lisp_Vector *all_vectors;
2789 /* Handy constants for vectorlike objects. */
2790 enum
2792 header_size = offsetof (struct Lisp_Vector, contents),
2793 word_size = sizeof (Lisp_Object)
2796 /* Value is a pointer to a newly allocated Lisp_Vector structure
2797 with room for LEN Lisp_Objects. */
2799 static struct Lisp_Vector *
2800 allocate_vectorlike (EMACS_INT len)
2802 struct Lisp_Vector *p;
2803 size_t nbytes;
2805 MALLOC_BLOCK_INPUT;
2807 #ifdef DOUG_LEA_MALLOC
2808 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2809 because mapped region contents are not preserved in
2810 a dumped Emacs. */
2811 mallopt (M_MMAP_MAX, 0);
2812 #endif
2814 /* This gets triggered by code which I haven't bothered to fix. --Stef */
2815 /* eassert (!handling_signal); */
2817 nbytes = header_size + len * word_size;
2818 p = (struct Lisp_Vector *) lisp_malloc (nbytes, MEM_TYPE_VECTORLIKE);
2820 #ifdef DOUG_LEA_MALLOC
2821 /* Back to a reasonable maximum of mmap'ed areas. */
2822 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2823 #endif
2825 consing_since_gc += nbytes;
2826 vector_cells_consed += len;
2828 p->header.next.vector = all_vectors;
2829 all_vectors = p;
2831 MALLOC_UNBLOCK_INPUT;
2833 return p;
2837 /* Allocate a vector with LEN slots. */
2839 struct Lisp_Vector *
2840 allocate_vector (EMACS_INT len)
2842 struct Lisp_Vector *v;
2843 ptrdiff_t nbytes_max = min (PTRDIFF_MAX, SIZE_MAX);
2845 if (min ((nbytes_max - header_size) / word_size, MOST_POSITIVE_FIXNUM) < len)
2846 memory_full (SIZE_MAX);
2847 v = allocate_vectorlike (len);
2848 v->header.size = len;
2849 return v;
2853 /* Allocate other vector-like structures. */
2855 struct Lisp_Vector *
2856 allocate_pseudovector (int memlen, int lisplen, EMACS_INT tag)
2858 struct Lisp_Vector *v = allocate_vectorlike (memlen);
2859 int i;
2861 /* Only the first lisplen slots will be traced normally by the GC. */
2862 for (i = 0; i < lisplen; ++i)
2863 v->contents[i] = Qnil;
2865 XSETPVECTYPESIZE (v, tag, lisplen);
2866 return v;
2869 struct Lisp_Hash_Table *
2870 allocate_hash_table (void)
2872 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table, count, PVEC_HASH_TABLE);
2876 struct window *
2877 allocate_window (void)
2879 return ALLOCATE_PSEUDOVECTOR(struct window, current_matrix, PVEC_WINDOW);
2883 struct terminal *
2884 allocate_terminal (void)
2886 struct terminal *t = ALLOCATE_PSEUDOVECTOR (struct terminal,
2887 next_terminal, PVEC_TERMINAL);
2888 /* Zero out the non-GC'd fields. FIXME: This should be made unnecessary. */
2889 memset (&t->next_terminal, 0,
2890 (char*) (t + 1) - (char*) &t->next_terminal);
2892 return t;
2895 struct frame *
2896 allocate_frame (void)
2898 struct frame *f = ALLOCATE_PSEUDOVECTOR (struct frame,
2899 face_cache, PVEC_FRAME);
2900 /* Zero out the non-GC'd fields. FIXME: This should be made unnecessary. */
2901 memset (&f->face_cache, 0,
2902 (char *) (f + 1) - (char *) &f->face_cache);
2903 return f;
2907 struct Lisp_Process *
2908 allocate_process (void)
2910 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
2914 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
2915 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
2916 See also the function `vector'. */)
2917 (register Lisp_Object length, Lisp_Object init)
2919 Lisp_Object vector;
2920 register EMACS_INT sizei;
2921 register EMACS_INT i;
2922 register struct Lisp_Vector *p;
2924 CHECK_NATNUM (length);
2925 sizei = XFASTINT (length);
2927 p = allocate_vector (sizei);
2928 for (i = 0; i < sizei; i++)
2929 p->contents[i] = init;
2931 XSETVECTOR (vector, p);
2932 return vector;
2936 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
2937 doc: /* Return a newly created vector with specified arguments as elements.
2938 Any number of arguments, even zero arguments, are allowed.
2939 usage: (vector &rest OBJECTS) */)
2940 (ptrdiff_t nargs, Lisp_Object *args)
2942 register Lisp_Object len, val;
2943 ptrdiff_t i;
2944 register struct Lisp_Vector *p;
2946 XSETFASTINT (len, nargs);
2947 val = Fmake_vector (len, Qnil);
2948 p = XVECTOR (val);
2949 for (i = 0; i < nargs; i++)
2950 p->contents[i] = args[i];
2951 return val;
2955 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
2956 doc: /* Create a byte-code object with specified arguments as elements.
2957 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
2958 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
2959 and (optional) INTERACTIVE-SPEC.
2960 The first four arguments are required; at most six have any
2961 significance.
2962 The ARGLIST can be either like the one of `lambda', in which case the arguments
2963 will be dynamically bound before executing the byte code, or it can be an
2964 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
2965 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
2966 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
2967 argument to catch the left-over arguments. If such an integer is used, the
2968 arguments will not be dynamically bound but will be instead pushed on the
2969 stack before executing the byte-code.
2970 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
2971 (ptrdiff_t nargs, Lisp_Object *args)
2973 register Lisp_Object len, val;
2974 ptrdiff_t i;
2975 register struct Lisp_Vector *p;
2977 XSETFASTINT (len, nargs);
2978 if (!NILP (Vpurify_flag))
2979 val = make_pure_vector (nargs);
2980 else
2981 val = Fmake_vector (len, Qnil);
2983 if (nargs > 1 && STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
2984 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
2985 earlier because they produced a raw 8-bit string for byte-code
2986 and now such a byte-code string is loaded as multibyte while
2987 raw 8-bit characters converted to multibyte form. Thus, now we
2988 must convert them back to the original unibyte form. */
2989 args[1] = Fstring_as_unibyte (args[1]);
2991 p = XVECTOR (val);
2992 for (i = 0; i < nargs; i++)
2994 if (!NILP (Vpurify_flag))
2995 args[i] = Fpurecopy (args[i]);
2996 p->contents[i] = args[i];
2998 XSETPVECTYPE (p, PVEC_COMPILED);
2999 XSETCOMPILED (val, p);
3000 return val;
3005 /***********************************************************************
3006 Symbol Allocation
3007 ***********************************************************************/
3009 /* Each symbol_block is just under 1020 bytes long, since malloc
3010 really allocates in units of powers of two and uses 4 bytes for its
3011 own overhead. */
3013 #define SYMBOL_BLOCK_SIZE \
3014 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
3016 struct symbol_block
3018 /* Place `symbols' first, to preserve alignment. */
3019 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3020 struct symbol_block *next;
3023 /* Current symbol block and index of first unused Lisp_Symbol
3024 structure in it. */
3026 static struct symbol_block *symbol_block;
3027 static int symbol_block_index;
3029 /* List of free symbols. */
3031 static struct Lisp_Symbol *symbol_free_list;
3034 /* Initialize symbol allocation. */
3036 static void
3037 init_symbol (void)
3039 symbol_block = NULL;
3040 symbol_block_index = SYMBOL_BLOCK_SIZE;
3041 symbol_free_list = 0;
3045 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3046 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3047 Its value and function definition are void, and its property list is nil. */)
3048 (Lisp_Object name)
3050 register Lisp_Object val;
3051 register struct Lisp_Symbol *p;
3053 CHECK_STRING (name);
3055 /* eassert (!handling_signal); */
3057 MALLOC_BLOCK_INPUT;
3059 if (symbol_free_list)
3061 XSETSYMBOL (val, symbol_free_list);
3062 symbol_free_list = symbol_free_list->next;
3064 else
3066 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3068 struct symbol_block *new;
3069 new = (struct symbol_block *) lisp_malloc (sizeof *new,
3070 MEM_TYPE_SYMBOL);
3071 new->next = symbol_block;
3072 symbol_block = new;
3073 symbol_block_index = 0;
3075 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index]);
3076 symbol_block_index++;
3079 MALLOC_UNBLOCK_INPUT;
3081 p = XSYMBOL (val);
3082 p->xname = name;
3083 p->plist = Qnil;
3084 p->redirect = SYMBOL_PLAINVAL;
3085 SET_SYMBOL_VAL (p, Qunbound);
3086 p->function = Qunbound;
3087 p->next = NULL;
3088 p->gcmarkbit = 0;
3089 p->interned = SYMBOL_UNINTERNED;
3090 p->constant = 0;
3091 p->declared_special = 0;
3092 consing_since_gc += sizeof (struct Lisp_Symbol);
3093 symbols_consed++;
3094 return val;
3099 /***********************************************************************
3100 Marker (Misc) Allocation
3101 ***********************************************************************/
3103 /* Allocation of markers and other objects that share that structure.
3104 Works like allocation of conses. */
3106 #define MARKER_BLOCK_SIZE \
3107 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
3109 struct marker_block
3111 /* Place `markers' first, to preserve alignment. */
3112 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
3113 struct marker_block *next;
3116 static struct marker_block *marker_block;
3117 static int marker_block_index;
3119 static union Lisp_Misc *marker_free_list;
3121 static void
3122 init_marker (void)
3124 marker_block = NULL;
3125 marker_block_index = MARKER_BLOCK_SIZE;
3126 marker_free_list = 0;
3129 /* Return a newly allocated Lisp_Misc object, with no substructure. */
3131 Lisp_Object
3132 allocate_misc (void)
3134 Lisp_Object val;
3136 /* eassert (!handling_signal); */
3138 MALLOC_BLOCK_INPUT;
3140 if (marker_free_list)
3142 XSETMISC (val, marker_free_list);
3143 marker_free_list = marker_free_list->u_free.chain;
3145 else
3147 if (marker_block_index == MARKER_BLOCK_SIZE)
3149 struct marker_block *new;
3150 new = (struct marker_block *) lisp_malloc (sizeof *new,
3151 MEM_TYPE_MISC);
3152 new->next = marker_block;
3153 marker_block = new;
3154 marker_block_index = 0;
3155 total_free_markers += MARKER_BLOCK_SIZE;
3157 XSETMISC (val, &marker_block->markers[marker_block_index]);
3158 marker_block_index++;
3161 MALLOC_UNBLOCK_INPUT;
3163 --total_free_markers;
3164 consing_since_gc += sizeof (union Lisp_Misc);
3165 misc_objects_consed++;
3166 XMISCANY (val)->gcmarkbit = 0;
3167 return val;
3170 /* Free a Lisp_Misc object */
3172 static void
3173 free_misc (Lisp_Object misc)
3175 XMISCTYPE (misc) = Lisp_Misc_Free;
3176 XMISC (misc)->u_free.chain = marker_free_list;
3177 marker_free_list = XMISC (misc);
3179 total_free_markers++;
3182 /* Return a Lisp_Misc_Save_Value object containing POINTER and
3183 INTEGER. This is used to package C values to call record_unwind_protect.
3184 The unwind function can get the C values back using XSAVE_VALUE. */
3186 Lisp_Object
3187 make_save_value (void *pointer, ptrdiff_t integer)
3189 register Lisp_Object val;
3190 register struct Lisp_Save_Value *p;
3192 val = allocate_misc ();
3193 XMISCTYPE (val) = Lisp_Misc_Save_Value;
3194 p = XSAVE_VALUE (val);
3195 p->pointer = pointer;
3196 p->integer = integer;
3197 p->dogc = 0;
3198 return val;
3201 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3202 doc: /* Return a newly allocated marker which does not point at any place. */)
3203 (void)
3205 register Lisp_Object val;
3206 register struct Lisp_Marker *p;
3208 val = allocate_misc ();
3209 XMISCTYPE (val) = Lisp_Misc_Marker;
3210 p = XMARKER (val);
3211 p->buffer = 0;
3212 p->bytepos = 0;
3213 p->charpos = 0;
3214 p->next = NULL;
3215 p->insertion_type = 0;
3216 return val;
3219 /* Put MARKER back on the free list after using it temporarily. */
3221 void
3222 free_marker (Lisp_Object marker)
3224 unchain_marker (XMARKER (marker));
3225 free_misc (marker);
3229 /* Return a newly created vector or string with specified arguments as
3230 elements. If all the arguments are characters that can fit
3231 in a string of events, make a string; otherwise, make a vector.
3233 Any number of arguments, even zero arguments, are allowed. */
3235 Lisp_Object
3236 make_event_array (register int nargs, Lisp_Object *args)
3238 int i;
3240 for (i = 0; i < nargs; i++)
3241 /* The things that fit in a string
3242 are characters that are in 0...127,
3243 after discarding the meta bit and all the bits above it. */
3244 if (!INTEGERP (args[i])
3245 || (XINT (args[i]) & ~(-CHAR_META)) >= 0200)
3246 return Fvector (nargs, args);
3248 /* Since the loop exited, we know that all the things in it are
3249 characters, so we can make a string. */
3251 Lisp_Object result;
3253 result = Fmake_string (make_number (nargs), make_number (0));
3254 for (i = 0; i < nargs; i++)
3256 SSET (result, i, XINT (args[i]));
3257 /* Move the meta bit to the right place for a string char. */
3258 if (XINT (args[i]) & CHAR_META)
3259 SSET (result, i, SREF (result, i) | 0x80);
3262 return result;
3268 /************************************************************************
3269 Memory Full Handling
3270 ************************************************************************/
3273 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
3274 there may have been size_t overflow so that malloc was never
3275 called, or perhaps malloc was invoked successfully but the
3276 resulting pointer had problems fitting into a tagged EMACS_INT. In
3277 either case this counts as memory being full even though malloc did
3278 not fail. */
3280 void
3281 memory_full (size_t nbytes)
3283 /* Do not go into hysterics merely because a large request failed. */
3284 int enough_free_memory = 0;
3285 if (SPARE_MEMORY < nbytes)
3287 void *p;
3289 MALLOC_BLOCK_INPUT;
3290 p = malloc (SPARE_MEMORY);
3291 if (p)
3293 free (p);
3294 enough_free_memory = 1;
3296 MALLOC_UNBLOCK_INPUT;
3299 if (! enough_free_memory)
3301 int i;
3303 Vmemory_full = Qt;
3305 memory_full_cons_threshold = sizeof (struct cons_block);
3307 /* The first time we get here, free the spare memory. */
3308 for (i = 0; i < sizeof (spare_memory) / sizeof (char *); i++)
3309 if (spare_memory[i])
3311 if (i == 0)
3312 free (spare_memory[i]);
3313 else if (i >= 1 && i <= 4)
3314 lisp_align_free (spare_memory[i]);
3315 else
3316 lisp_free (spare_memory[i]);
3317 spare_memory[i] = 0;
3320 /* Record the space now used. When it decreases substantially,
3321 we can refill the memory reserve. */
3322 #if !defined SYSTEM_MALLOC && !defined SYNC_INPUT
3323 bytes_used_when_full = BYTES_USED;
3324 #endif
3327 /* This used to call error, but if we've run out of memory, we could
3328 get infinite recursion trying to build the string. */
3329 xsignal (Qnil, Vmemory_signal_data);
3332 /* If we released our reserve (due to running out of memory),
3333 and we have a fair amount free once again,
3334 try to set aside another reserve in case we run out once more.
3336 This is called when a relocatable block is freed in ralloc.c,
3337 and also directly from this file, in case we're not using ralloc.c. */
3339 void
3340 refill_memory_reserve (void)
3342 #ifndef SYSTEM_MALLOC
3343 if (spare_memory[0] == 0)
3344 spare_memory[0] = (char *) malloc (SPARE_MEMORY);
3345 if (spare_memory[1] == 0)
3346 spare_memory[1] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3347 MEM_TYPE_CONS);
3348 if (spare_memory[2] == 0)
3349 spare_memory[2] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3350 MEM_TYPE_CONS);
3351 if (spare_memory[3] == 0)
3352 spare_memory[3] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3353 MEM_TYPE_CONS);
3354 if (spare_memory[4] == 0)
3355 spare_memory[4] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3356 MEM_TYPE_CONS);
3357 if (spare_memory[5] == 0)
3358 spare_memory[5] = (char *) lisp_malloc (sizeof (struct string_block),
3359 MEM_TYPE_STRING);
3360 if (spare_memory[6] == 0)
3361 spare_memory[6] = (char *) lisp_malloc (sizeof (struct string_block),
3362 MEM_TYPE_STRING);
3363 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
3364 Vmemory_full = Qnil;
3365 #endif
3368 /************************************************************************
3369 C Stack Marking
3370 ************************************************************************/
3372 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
3374 /* Conservative C stack marking requires a method to identify possibly
3375 live Lisp objects given a pointer value. We do this by keeping
3376 track of blocks of Lisp data that are allocated in a red-black tree
3377 (see also the comment of mem_node which is the type of nodes in
3378 that tree). Function lisp_malloc adds information for an allocated
3379 block to the red-black tree with calls to mem_insert, and function
3380 lisp_free removes it with mem_delete. Functions live_string_p etc
3381 call mem_find to lookup information about a given pointer in the
3382 tree, and use that to determine if the pointer points to a Lisp
3383 object or not. */
3385 /* Initialize this part of alloc.c. */
3387 static void
3388 mem_init (void)
3390 mem_z.left = mem_z.right = MEM_NIL;
3391 mem_z.parent = NULL;
3392 mem_z.color = MEM_BLACK;
3393 mem_z.start = mem_z.end = NULL;
3394 mem_root = MEM_NIL;
3398 /* Value is a pointer to the mem_node containing START. Value is
3399 MEM_NIL if there is no node in the tree containing START. */
3401 static inline struct mem_node *
3402 mem_find (void *start)
3404 struct mem_node *p;
3406 if (start < min_heap_address || start > max_heap_address)
3407 return MEM_NIL;
3409 /* Make the search always successful to speed up the loop below. */
3410 mem_z.start = start;
3411 mem_z.end = (char *) start + 1;
3413 p = mem_root;
3414 while (start < p->start || start >= p->end)
3415 p = start < p->start ? p->left : p->right;
3416 return p;
3420 /* Insert a new node into the tree for a block of memory with start
3421 address START, end address END, and type TYPE. Value is a
3422 pointer to the node that was inserted. */
3424 static struct mem_node *
3425 mem_insert (void *start, void *end, enum mem_type type)
3427 struct mem_node *c, *parent, *x;
3429 if (min_heap_address == NULL || start < min_heap_address)
3430 min_heap_address = start;
3431 if (max_heap_address == NULL || end > max_heap_address)
3432 max_heap_address = end;
3434 /* See where in the tree a node for START belongs. In this
3435 particular application, it shouldn't happen that a node is already
3436 present. For debugging purposes, let's check that. */
3437 c = mem_root;
3438 parent = NULL;
3440 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
3442 while (c != MEM_NIL)
3444 if (start >= c->start && start < c->end)
3445 abort ();
3446 parent = c;
3447 c = start < c->start ? c->left : c->right;
3450 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3452 while (c != MEM_NIL)
3454 parent = c;
3455 c = start < c->start ? c->left : c->right;
3458 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3460 /* Create a new node. */
3461 #ifdef GC_MALLOC_CHECK
3462 x = (struct mem_node *) _malloc_internal (sizeof *x);
3463 if (x == NULL)
3464 abort ();
3465 #else
3466 x = (struct mem_node *) xmalloc (sizeof *x);
3467 #endif
3468 x->start = start;
3469 x->end = end;
3470 x->type = type;
3471 x->parent = parent;
3472 x->left = x->right = MEM_NIL;
3473 x->color = MEM_RED;
3475 /* Insert it as child of PARENT or install it as root. */
3476 if (parent)
3478 if (start < parent->start)
3479 parent->left = x;
3480 else
3481 parent->right = x;
3483 else
3484 mem_root = x;
3486 /* Re-establish red-black tree properties. */
3487 mem_insert_fixup (x);
3489 return x;
3493 /* Re-establish the red-black properties of the tree, and thereby
3494 balance the tree, after node X has been inserted; X is always red. */
3496 static void
3497 mem_insert_fixup (struct mem_node *x)
3499 while (x != mem_root && x->parent->color == MEM_RED)
3501 /* X is red and its parent is red. This is a violation of
3502 red-black tree property #3. */
3504 if (x->parent == x->parent->parent->left)
3506 /* We're on the left side of our grandparent, and Y is our
3507 "uncle". */
3508 struct mem_node *y = x->parent->parent->right;
3510 if (y->color == MEM_RED)
3512 /* Uncle and parent are red but should be black because
3513 X is red. Change the colors accordingly and proceed
3514 with the grandparent. */
3515 x->parent->color = MEM_BLACK;
3516 y->color = MEM_BLACK;
3517 x->parent->parent->color = MEM_RED;
3518 x = x->parent->parent;
3520 else
3522 /* Parent and uncle have different colors; parent is
3523 red, uncle is black. */
3524 if (x == x->parent->right)
3526 x = x->parent;
3527 mem_rotate_left (x);
3530 x->parent->color = MEM_BLACK;
3531 x->parent->parent->color = MEM_RED;
3532 mem_rotate_right (x->parent->parent);
3535 else
3537 /* This is the symmetrical case of above. */
3538 struct mem_node *y = x->parent->parent->left;
3540 if (y->color == MEM_RED)
3542 x->parent->color = MEM_BLACK;
3543 y->color = MEM_BLACK;
3544 x->parent->parent->color = MEM_RED;
3545 x = x->parent->parent;
3547 else
3549 if (x == x->parent->left)
3551 x = x->parent;
3552 mem_rotate_right (x);
3555 x->parent->color = MEM_BLACK;
3556 x->parent->parent->color = MEM_RED;
3557 mem_rotate_left (x->parent->parent);
3562 /* The root may have been changed to red due to the algorithm. Set
3563 it to black so that property #5 is satisfied. */
3564 mem_root->color = MEM_BLACK;
3568 /* (x) (y)
3569 / \ / \
3570 a (y) ===> (x) c
3571 / \ / \
3572 b c a b */
3574 static void
3575 mem_rotate_left (struct mem_node *x)
3577 struct mem_node *y;
3579 /* Turn y's left sub-tree into x's right sub-tree. */
3580 y = x->right;
3581 x->right = y->left;
3582 if (y->left != MEM_NIL)
3583 y->left->parent = x;
3585 /* Y's parent was x's parent. */
3586 if (y != MEM_NIL)
3587 y->parent = x->parent;
3589 /* Get the parent to point to y instead of x. */
3590 if (x->parent)
3592 if (x == x->parent->left)
3593 x->parent->left = y;
3594 else
3595 x->parent->right = y;
3597 else
3598 mem_root = y;
3600 /* Put x on y's left. */
3601 y->left = x;
3602 if (x != MEM_NIL)
3603 x->parent = y;
3607 /* (x) (Y)
3608 / \ / \
3609 (y) c ===> a (x)
3610 / \ / \
3611 a b b c */
3613 static void
3614 mem_rotate_right (struct mem_node *x)
3616 struct mem_node *y = x->left;
3618 x->left = y->right;
3619 if (y->right != MEM_NIL)
3620 y->right->parent = x;
3622 if (y != MEM_NIL)
3623 y->parent = x->parent;
3624 if (x->parent)
3626 if (x == x->parent->right)
3627 x->parent->right = y;
3628 else
3629 x->parent->left = y;
3631 else
3632 mem_root = y;
3634 y->right = x;
3635 if (x != MEM_NIL)
3636 x->parent = y;
3640 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
3642 static void
3643 mem_delete (struct mem_node *z)
3645 struct mem_node *x, *y;
3647 if (!z || z == MEM_NIL)
3648 return;
3650 if (z->left == MEM_NIL || z->right == MEM_NIL)
3651 y = z;
3652 else
3654 y = z->right;
3655 while (y->left != MEM_NIL)
3656 y = y->left;
3659 if (y->left != MEM_NIL)
3660 x = y->left;
3661 else
3662 x = y->right;
3664 x->parent = y->parent;
3665 if (y->parent)
3667 if (y == y->parent->left)
3668 y->parent->left = x;
3669 else
3670 y->parent->right = x;
3672 else
3673 mem_root = x;
3675 if (y != z)
3677 z->start = y->start;
3678 z->end = y->end;
3679 z->type = y->type;
3682 if (y->color == MEM_BLACK)
3683 mem_delete_fixup (x);
3685 #ifdef GC_MALLOC_CHECK
3686 _free_internal (y);
3687 #else
3688 xfree (y);
3689 #endif
3693 /* Re-establish the red-black properties of the tree, after a
3694 deletion. */
3696 static void
3697 mem_delete_fixup (struct mem_node *x)
3699 while (x != mem_root && x->color == MEM_BLACK)
3701 if (x == x->parent->left)
3703 struct mem_node *w = x->parent->right;
3705 if (w->color == MEM_RED)
3707 w->color = MEM_BLACK;
3708 x->parent->color = MEM_RED;
3709 mem_rotate_left (x->parent);
3710 w = x->parent->right;
3713 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
3715 w->color = MEM_RED;
3716 x = x->parent;
3718 else
3720 if (w->right->color == MEM_BLACK)
3722 w->left->color = MEM_BLACK;
3723 w->color = MEM_RED;
3724 mem_rotate_right (w);
3725 w = x->parent->right;
3727 w->color = x->parent->color;
3728 x->parent->color = MEM_BLACK;
3729 w->right->color = MEM_BLACK;
3730 mem_rotate_left (x->parent);
3731 x = mem_root;
3734 else
3736 struct mem_node *w = x->parent->left;
3738 if (w->color == MEM_RED)
3740 w->color = MEM_BLACK;
3741 x->parent->color = MEM_RED;
3742 mem_rotate_right (x->parent);
3743 w = x->parent->left;
3746 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
3748 w->color = MEM_RED;
3749 x = x->parent;
3751 else
3753 if (w->left->color == MEM_BLACK)
3755 w->right->color = MEM_BLACK;
3756 w->color = MEM_RED;
3757 mem_rotate_left (w);
3758 w = x->parent->left;
3761 w->color = x->parent->color;
3762 x->parent->color = MEM_BLACK;
3763 w->left->color = MEM_BLACK;
3764 mem_rotate_right (x->parent);
3765 x = mem_root;
3770 x->color = MEM_BLACK;
3774 /* Value is non-zero if P is a pointer to a live Lisp string on
3775 the heap. M is a pointer to the mem_block for P. */
3777 static inline int
3778 live_string_p (struct mem_node *m, void *p)
3780 if (m->type == MEM_TYPE_STRING)
3782 struct string_block *b = (struct string_block *) m->start;
3783 ptrdiff_t offset = (char *) p - (char *) &b->strings[0];
3785 /* P must point to the start of a Lisp_String structure, and it
3786 must not be on the free-list. */
3787 return (offset >= 0
3788 && offset % sizeof b->strings[0] == 0
3789 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
3790 && ((struct Lisp_String *) p)->data != NULL);
3792 else
3793 return 0;
3797 /* Value is non-zero if P is a pointer to a live Lisp cons on
3798 the heap. M is a pointer to the mem_block for P. */
3800 static inline int
3801 live_cons_p (struct mem_node *m, void *p)
3803 if (m->type == MEM_TYPE_CONS)
3805 struct cons_block *b = (struct cons_block *) m->start;
3806 ptrdiff_t offset = (char *) p - (char *) &b->conses[0];
3808 /* P must point to the start of a Lisp_Cons, not be
3809 one of the unused cells in the current cons block,
3810 and not be on the free-list. */
3811 return (offset >= 0
3812 && offset % sizeof b->conses[0] == 0
3813 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
3814 && (b != cons_block
3815 || offset / sizeof b->conses[0] < cons_block_index)
3816 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
3818 else
3819 return 0;
3823 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3824 the heap. M is a pointer to the mem_block for P. */
3826 static inline int
3827 live_symbol_p (struct mem_node *m, void *p)
3829 if (m->type == MEM_TYPE_SYMBOL)
3831 struct symbol_block *b = (struct symbol_block *) m->start;
3832 ptrdiff_t offset = (char *) p - (char *) &b->symbols[0];
3834 /* P must point to the start of a Lisp_Symbol, not be
3835 one of the unused cells in the current symbol block,
3836 and not be on the free-list. */
3837 return (offset >= 0
3838 && offset % sizeof b->symbols[0] == 0
3839 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
3840 && (b != symbol_block
3841 || offset / sizeof b->symbols[0] < symbol_block_index)
3842 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
3844 else
3845 return 0;
3849 /* Value is non-zero if P is a pointer to a live Lisp float on
3850 the heap. M is a pointer to the mem_block for P. */
3852 static inline int
3853 live_float_p (struct mem_node *m, void *p)
3855 if (m->type == MEM_TYPE_FLOAT)
3857 struct float_block *b = (struct float_block *) m->start;
3858 ptrdiff_t offset = (char *) p - (char *) &b->floats[0];
3860 /* P must point to the start of a Lisp_Float and not be
3861 one of the unused cells in the current float block. */
3862 return (offset >= 0
3863 && offset % sizeof b->floats[0] == 0
3864 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
3865 && (b != float_block
3866 || offset / sizeof b->floats[0] < float_block_index));
3868 else
3869 return 0;
3873 /* Value is non-zero if P is a pointer to a live Lisp Misc on
3874 the heap. M is a pointer to the mem_block for P. */
3876 static inline int
3877 live_misc_p (struct mem_node *m, void *p)
3879 if (m->type == MEM_TYPE_MISC)
3881 struct marker_block *b = (struct marker_block *) m->start;
3882 ptrdiff_t offset = (char *) p - (char *) &b->markers[0];
3884 /* P must point to the start of a Lisp_Misc, not be
3885 one of the unused cells in the current misc block,
3886 and not be on the free-list. */
3887 return (offset >= 0
3888 && offset % sizeof b->markers[0] == 0
3889 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
3890 && (b != marker_block
3891 || offset / sizeof b->markers[0] < marker_block_index)
3892 && ((union Lisp_Misc *) p)->u_any.type != Lisp_Misc_Free);
3894 else
3895 return 0;
3899 /* Value is non-zero if P is a pointer to a live vector-like object.
3900 M is a pointer to the mem_block for P. */
3902 static inline int
3903 live_vector_p (struct mem_node *m, void *p)
3905 return (p == m->start && m->type == MEM_TYPE_VECTORLIKE);
3909 /* Value is non-zero if P is a pointer to a live buffer. M is a
3910 pointer to the mem_block for P. */
3912 static inline int
3913 live_buffer_p (struct mem_node *m, void *p)
3915 /* P must point to the start of the block, and the buffer
3916 must not have been killed. */
3917 return (m->type == MEM_TYPE_BUFFER
3918 && p == m->start
3919 && !NILP (((struct buffer *) p)->BUFFER_INTERNAL_FIELD (name)));
3922 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
3924 #if GC_MARK_STACK
3926 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3928 /* Array of objects that are kept alive because the C stack contains
3929 a pattern that looks like a reference to them . */
3931 #define MAX_ZOMBIES 10
3932 static Lisp_Object zombies[MAX_ZOMBIES];
3934 /* Number of zombie objects. */
3936 static EMACS_INT nzombies;
3938 /* Number of garbage collections. */
3940 static EMACS_INT ngcs;
3942 /* Average percentage of zombies per collection. */
3944 static double avg_zombies;
3946 /* Max. number of live and zombie objects. */
3948 static EMACS_INT max_live, max_zombies;
3950 /* Average number of live objects per GC. */
3952 static double avg_live;
3954 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
3955 doc: /* Show information about live and zombie objects. */)
3956 (void)
3958 Lisp_Object args[8], zombie_list = Qnil;
3959 EMACS_INT i;
3960 for (i = 0; i < nzombies; i++)
3961 zombie_list = Fcons (zombies[i], zombie_list);
3962 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
3963 args[1] = make_number (ngcs);
3964 args[2] = make_float (avg_live);
3965 args[3] = make_float (avg_zombies);
3966 args[4] = make_float (avg_zombies / avg_live / 100);
3967 args[5] = make_number (max_live);
3968 args[6] = make_number (max_zombies);
3969 args[7] = zombie_list;
3970 return Fmessage (8, args);
3973 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3976 /* Mark OBJ if we can prove it's a Lisp_Object. */
3978 static inline void
3979 mark_maybe_object (Lisp_Object obj)
3981 void *po;
3982 struct mem_node *m;
3984 if (INTEGERP (obj))
3985 return;
3987 po = (void *) XPNTR (obj);
3988 m = mem_find (po);
3990 if (m != MEM_NIL)
3992 int mark_p = 0;
3994 switch (XTYPE (obj))
3996 case Lisp_String:
3997 mark_p = (live_string_p (m, po)
3998 && !STRING_MARKED_P ((struct Lisp_String *) po));
3999 break;
4001 case Lisp_Cons:
4002 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4003 break;
4005 case Lisp_Symbol:
4006 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4007 break;
4009 case Lisp_Float:
4010 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4011 break;
4013 case Lisp_Vectorlike:
4014 /* Note: can't check BUFFERP before we know it's a
4015 buffer because checking that dereferences the pointer
4016 PO which might point anywhere. */
4017 if (live_vector_p (m, po))
4018 mark_p = !SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4019 else if (live_buffer_p (m, po))
4020 mark_p = BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4021 break;
4023 case Lisp_Misc:
4024 mark_p = (live_misc_p (m, po) && !XMISCANY (obj)->gcmarkbit);
4025 break;
4027 default:
4028 break;
4031 if (mark_p)
4033 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4034 if (nzombies < MAX_ZOMBIES)
4035 zombies[nzombies] = obj;
4036 ++nzombies;
4037 #endif
4038 mark_object (obj);
4044 /* If P points to Lisp data, mark that as live if it isn't already
4045 marked. */
4047 static inline void
4048 mark_maybe_pointer (void *p)
4050 struct mem_node *m;
4052 /* Quickly rule out some values which can't point to Lisp data. */
4053 if ((intptr_t) p %
4054 #ifdef USE_LSB_TAG
4055 8 /* USE_LSB_TAG needs Lisp data to be aligned on multiples of 8. */
4056 #else
4057 2 /* We assume that Lisp data is aligned on even addresses. */
4058 #endif
4060 return;
4062 m = mem_find (p);
4063 if (m != MEM_NIL)
4065 Lisp_Object obj = Qnil;
4067 switch (m->type)
4069 case MEM_TYPE_NON_LISP:
4070 /* Nothing to do; not a pointer to Lisp memory. */
4071 break;
4073 case MEM_TYPE_BUFFER:
4074 if (live_buffer_p (m, p) && !VECTOR_MARKED_P((struct buffer *)p))
4075 XSETVECTOR (obj, p);
4076 break;
4078 case MEM_TYPE_CONS:
4079 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4080 XSETCONS (obj, p);
4081 break;
4083 case MEM_TYPE_STRING:
4084 if (live_string_p (m, p)
4085 && !STRING_MARKED_P ((struct Lisp_String *) p))
4086 XSETSTRING (obj, p);
4087 break;
4089 case MEM_TYPE_MISC:
4090 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4091 XSETMISC (obj, p);
4092 break;
4094 case MEM_TYPE_SYMBOL:
4095 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4096 XSETSYMBOL (obj, p);
4097 break;
4099 case MEM_TYPE_FLOAT:
4100 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4101 XSETFLOAT (obj, p);
4102 break;
4104 case MEM_TYPE_VECTORLIKE:
4105 if (live_vector_p (m, p))
4107 Lisp_Object tem;
4108 XSETVECTOR (tem, p);
4109 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4110 obj = tem;
4112 break;
4114 default:
4115 abort ();
4118 if (!NILP (obj))
4119 mark_object (obj);
4124 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4125 or END+OFFSET..START. */
4127 static void
4128 mark_memory (void *start, void *end, int offset)
4130 Lisp_Object *p;
4131 void **pp;
4133 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4134 nzombies = 0;
4135 #endif
4137 /* Make START the pointer to the start of the memory region,
4138 if it isn't already. */
4139 if (end < start)
4141 void *tem = start;
4142 start = end;
4143 end = tem;
4146 /* Mark Lisp_Objects. */
4147 for (p = (Lisp_Object *) ((char *) start + offset); (void *) p < end; ++p)
4148 mark_maybe_object (*p);
4150 /* Mark Lisp data pointed to. This is necessary because, in some
4151 situations, the C compiler optimizes Lisp objects away, so that
4152 only a pointer to them remains. Example:
4154 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4157 Lisp_Object obj = build_string ("test");
4158 struct Lisp_String *s = XSTRING (obj);
4159 Fgarbage_collect ();
4160 fprintf (stderr, "test `%s'\n", s->data);
4161 return Qnil;
4164 Here, `obj' isn't really used, and the compiler optimizes it
4165 away. The only reference to the life string is through the
4166 pointer `s'. */
4168 for (pp = (void **) ((char *) start + offset); (void *) pp < end; ++pp)
4169 mark_maybe_pointer (*pp);
4172 /* setjmp will work with GCC unless NON_SAVING_SETJMP is defined in
4173 the GCC system configuration. In gcc 3.2, the only systems for
4174 which this is so are i386-sco5 non-ELF, i386-sysv3 (maybe included
4175 by others?) and ns32k-pc532-min. */
4177 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4179 static int setjmp_tested_p, longjmps_done;
4181 #define SETJMP_WILL_LIKELY_WORK "\
4183 Emacs garbage collector has been changed to use conservative stack\n\
4184 marking. Emacs has determined that the method it uses to do the\n\
4185 marking will likely work on your system, but this isn't sure.\n\
4187 If you are a system-programmer, or can get the help of a local wizard\n\
4188 who is, please take a look at the function mark_stack in alloc.c, and\n\
4189 verify that the methods used are appropriate for your system.\n\
4191 Please mail the result to <emacs-devel@gnu.org>.\n\
4194 #define SETJMP_WILL_NOT_WORK "\
4196 Emacs garbage collector has been changed to use conservative stack\n\
4197 marking. Emacs has determined that the default method it uses to do the\n\
4198 marking will not work on your system. We will need a system-dependent\n\
4199 solution for your system.\n\
4201 Please take a look at the function mark_stack in alloc.c, and\n\
4202 try to find a way to make it work on your system.\n\
4204 Note that you may get false negatives, depending on the compiler.\n\
4205 In particular, you need to use -O with GCC for this test.\n\
4207 Please mail the result to <emacs-devel@gnu.org>.\n\
4211 /* Perform a quick check if it looks like setjmp saves registers in a
4212 jmp_buf. Print a message to stderr saying so. When this test
4213 succeeds, this is _not_ a proof that setjmp is sufficient for
4214 conservative stack marking. Only the sources or a disassembly
4215 can prove that. */
4217 static void
4218 test_setjmp (void)
4220 char buf[10];
4221 register int x;
4222 jmp_buf jbuf;
4223 int result = 0;
4225 /* Arrange for X to be put in a register. */
4226 sprintf (buf, "1");
4227 x = strlen (buf);
4228 x = 2 * x - 1;
4230 setjmp (jbuf);
4231 if (longjmps_done == 1)
4233 /* Came here after the longjmp at the end of the function.
4235 If x == 1, the longjmp has restored the register to its
4236 value before the setjmp, and we can hope that setjmp
4237 saves all such registers in the jmp_buf, although that
4238 isn't sure.
4240 For other values of X, either something really strange is
4241 taking place, or the setjmp just didn't save the register. */
4243 if (x == 1)
4244 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4245 else
4247 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4248 exit (1);
4252 ++longjmps_done;
4253 x = 2;
4254 if (longjmps_done == 1)
4255 longjmp (jbuf, 1);
4258 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4261 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4263 /* Abort if anything GCPRO'd doesn't survive the GC. */
4265 static void
4266 check_gcpros (void)
4268 struct gcpro *p;
4269 ptrdiff_t i;
4271 for (p = gcprolist; p; p = p->next)
4272 for (i = 0; i < p->nvars; ++i)
4273 if (!survives_gc_p (p->var[i]))
4274 /* FIXME: It's not necessarily a bug. It might just be that the
4275 GCPRO is unnecessary or should release the object sooner. */
4276 abort ();
4279 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4281 static void
4282 dump_zombies (void)
4284 int i;
4286 fprintf (stderr, "\nZombies kept alive = %"pI":\n", nzombies);
4287 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
4289 fprintf (stderr, " %d = ", i);
4290 debug_print (zombies[i]);
4294 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4297 /* Mark live Lisp objects on the C stack.
4299 There are several system-dependent problems to consider when
4300 porting this to new architectures:
4302 Processor Registers
4304 We have to mark Lisp objects in CPU registers that can hold local
4305 variables or are used to pass parameters.
4307 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4308 something that either saves relevant registers on the stack, or
4309 calls mark_maybe_object passing it each register's contents.
4311 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4312 implementation assumes that calling setjmp saves registers we need
4313 to see in a jmp_buf which itself lies on the stack. This doesn't
4314 have to be true! It must be verified for each system, possibly
4315 by taking a look at the source code of setjmp.
4317 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4318 can use it as a machine independent method to store all registers
4319 to the stack. In this case the macros described in the previous
4320 two paragraphs are not used.
4322 Stack Layout
4324 Architectures differ in the way their processor stack is organized.
4325 For example, the stack might look like this
4327 +----------------+
4328 | Lisp_Object | size = 4
4329 +----------------+
4330 | something else | size = 2
4331 +----------------+
4332 | Lisp_Object | size = 4
4333 +----------------+
4334 | ... |
4336 In such a case, not every Lisp_Object will be aligned equally. To
4337 find all Lisp_Object on the stack it won't be sufficient to walk
4338 the stack in steps of 4 bytes. Instead, two passes will be
4339 necessary, one starting at the start of the stack, and a second
4340 pass starting at the start of the stack + 2. Likewise, if the
4341 minimal alignment of Lisp_Objects on the stack is 1, four passes
4342 would be necessary, each one starting with one byte more offset
4343 from the stack start.
4345 The current code assumes by default that Lisp_Objects are aligned
4346 equally on the stack. */
4348 static void
4349 mark_stack (void)
4351 int i;
4352 void *end;
4354 #ifdef HAVE___BUILTIN_UNWIND_INIT
4355 /* Force callee-saved registers and register windows onto the stack.
4356 This is the preferred method if available, obviating the need for
4357 machine dependent methods. */
4358 __builtin_unwind_init ();
4359 end = &end;
4360 #else /* not HAVE___BUILTIN_UNWIND_INIT */
4361 #ifndef GC_SAVE_REGISTERS_ON_STACK
4362 /* jmp_buf may not be aligned enough on darwin-ppc64 */
4363 union aligned_jmpbuf {
4364 Lisp_Object o;
4365 jmp_buf j;
4366 } j;
4367 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
4368 #endif
4369 /* This trick flushes the register windows so that all the state of
4370 the process is contained in the stack. */
4371 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
4372 needed on ia64 too. See mach_dep.c, where it also says inline
4373 assembler doesn't work with relevant proprietary compilers. */
4374 #ifdef __sparc__
4375 #if defined (__sparc64__) && defined (__FreeBSD__)
4376 /* FreeBSD does not have a ta 3 handler. */
4377 asm ("flushw");
4378 #else
4379 asm ("ta 3");
4380 #endif
4381 #endif
4383 /* Save registers that we need to see on the stack. We need to see
4384 registers used to hold register variables and registers used to
4385 pass parameters. */
4386 #ifdef GC_SAVE_REGISTERS_ON_STACK
4387 GC_SAVE_REGISTERS_ON_STACK (end);
4388 #else /* not GC_SAVE_REGISTERS_ON_STACK */
4390 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
4391 setjmp will definitely work, test it
4392 and print a message with the result
4393 of the test. */
4394 if (!setjmp_tested_p)
4396 setjmp_tested_p = 1;
4397 test_setjmp ();
4399 #endif /* GC_SETJMP_WORKS */
4401 setjmp (j.j);
4402 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
4403 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
4404 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
4406 /* This assumes that the stack is a contiguous region in memory. If
4407 that's not the case, something has to be done here to iterate
4408 over the stack segments. */
4409 #ifndef GC_LISP_OBJECT_ALIGNMENT
4410 #ifdef __GNUC__
4411 #define GC_LISP_OBJECT_ALIGNMENT __alignof__ (Lisp_Object)
4412 #else
4413 #define GC_LISP_OBJECT_ALIGNMENT sizeof (Lisp_Object)
4414 #endif
4415 #endif
4416 for (i = 0; i < sizeof (Lisp_Object); i += GC_LISP_OBJECT_ALIGNMENT)
4417 mark_memory (stack_base, end, i);
4418 /* Allow for marking a secondary stack, like the register stack on the
4419 ia64. */
4420 #ifdef GC_MARK_SECONDARY_STACK
4421 GC_MARK_SECONDARY_STACK ();
4422 #endif
4424 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4425 check_gcpros ();
4426 #endif
4429 #endif /* GC_MARK_STACK != 0 */
4432 /* Determine whether it is safe to access memory at address P. */
4433 static int
4434 valid_pointer_p (void *p)
4436 #ifdef WINDOWSNT
4437 return w32_valid_pointer_p (p, 16);
4438 #else
4439 int fd[2];
4441 /* Obviously, we cannot just access it (we would SEGV trying), so we
4442 trick the o/s to tell us whether p is a valid pointer.
4443 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4444 not validate p in that case. */
4446 if (pipe (fd) == 0)
4448 int valid = (emacs_write (fd[1], (char *) p, 16) == 16);
4449 emacs_close (fd[1]);
4450 emacs_close (fd[0]);
4451 return valid;
4454 return -1;
4455 #endif
4458 /* Return 1 if OBJ is a valid lisp object.
4459 Return 0 if OBJ is NOT a valid lisp object.
4460 Return -1 if we cannot validate OBJ.
4461 This function can be quite slow,
4462 so it should only be used in code for manual debugging. */
4465 valid_lisp_object_p (Lisp_Object obj)
4467 void *p;
4468 #if GC_MARK_STACK
4469 struct mem_node *m;
4470 #endif
4472 if (INTEGERP (obj))
4473 return 1;
4475 p = (void *) XPNTR (obj);
4476 if (PURE_POINTER_P (p))
4477 return 1;
4479 #if !GC_MARK_STACK
4480 return valid_pointer_p (p);
4481 #else
4483 m = mem_find (p);
4485 if (m == MEM_NIL)
4487 int valid = valid_pointer_p (p);
4488 if (valid <= 0)
4489 return valid;
4491 if (SUBRP (obj))
4492 return 1;
4494 return 0;
4497 switch (m->type)
4499 case MEM_TYPE_NON_LISP:
4500 return 0;
4502 case MEM_TYPE_BUFFER:
4503 return live_buffer_p (m, p);
4505 case MEM_TYPE_CONS:
4506 return live_cons_p (m, p);
4508 case MEM_TYPE_STRING:
4509 return live_string_p (m, p);
4511 case MEM_TYPE_MISC:
4512 return live_misc_p (m, p);
4514 case MEM_TYPE_SYMBOL:
4515 return live_symbol_p (m, p);
4517 case MEM_TYPE_FLOAT:
4518 return live_float_p (m, p);
4520 case MEM_TYPE_VECTORLIKE:
4521 return live_vector_p (m, p);
4523 default:
4524 break;
4527 return 0;
4528 #endif
4534 /***********************************************************************
4535 Pure Storage Management
4536 ***********************************************************************/
4538 /* Allocate room for SIZE bytes from pure Lisp storage and return a
4539 pointer to it. TYPE is the Lisp type for which the memory is
4540 allocated. TYPE < 0 means it's not used for a Lisp object. */
4542 static POINTER_TYPE *
4543 pure_alloc (size_t size, int type)
4545 POINTER_TYPE *result;
4546 #ifdef USE_LSB_TAG
4547 size_t alignment = (1 << GCTYPEBITS);
4548 #else
4549 size_t alignment = sizeof (EMACS_INT);
4551 /* Give Lisp_Floats an extra alignment. */
4552 if (type == Lisp_Float)
4554 #if defined __GNUC__ && __GNUC__ >= 2
4555 alignment = __alignof (struct Lisp_Float);
4556 #else
4557 alignment = sizeof (struct Lisp_Float);
4558 #endif
4560 #endif
4562 again:
4563 if (type >= 0)
4565 /* Allocate space for a Lisp object from the beginning of the free
4566 space with taking account of alignment. */
4567 result = ALIGN (purebeg + pure_bytes_used_lisp, alignment);
4568 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
4570 else
4572 /* Allocate space for a non-Lisp object from the end of the free
4573 space. */
4574 pure_bytes_used_non_lisp += size;
4575 result = purebeg + pure_size - pure_bytes_used_non_lisp;
4577 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
4579 if (pure_bytes_used <= pure_size)
4580 return result;
4582 /* Don't allocate a large amount here,
4583 because it might get mmap'd and then its address
4584 might not be usable. */
4585 purebeg = (char *) xmalloc (10000);
4586 pure_size = 10000;
4587 pure_bytes_used_before_overflow += pure_bytes_used - size;
4588 pure_bytes_used = 0;
4589 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
4590 goto again;
4594 /* Print a warning if PURESIZE is too small. */
4596 void
4597 check_pure_size (void)
4599 if (pure_bytes_used_before_overflow)
4600 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI"d"
4601 " bytes needed)"),
4602 pure_bytes_used + pure_bytes_used_before_overflow);
4606 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
4607 the non-Lisp data pool of the pure storage, and return its start
4608 address. Return NULL if not found. */
4610 static char *
4611 find_string_data_in_pure (const char *data, EMACS_INT nbytes)
4613 int i;
4614 EMACS_INT skip, bm_skip[256], last_char_skip, infinity, start, start_max;
4615 const unsigned char *p;
4616 char *non_lisp_beg;
4618 if (pure_bytes_used_non_lisp < nbytes + 1)
4619 return NULL;
4621 /* Set up the Boyer-Moore table. */
4622 skip = nbytes + 1;
4623 for (i = 0; i < 256; i++)
4624 bm_skip[i] = skip;
4626 p = (const unsigned char *) data;
4627 while (--skip > 0)
4628 bm_skip[*p++] = skip;
4630 last_char_skip = bm_skip['\0'];
4632 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
4633 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
4635 /* See the comments in the function `boyer_moore' (search.c) for the
4636 use of `infinity'. */
4637 infinity = pure_bytes_used_non_lisp + 1;
4638 bm_skip['\0'] = infinity;
4640 p = (const unsigned char *) non_lisp_beg + nbytes;
4641 start = 0;
4644 /* Check the last character (== '\0'). */
4647 start += bm_skip[*(p + start)];
4649 while (start <= start_max);
4651 if (start < infinity)
4652 /* Couldn't find the last character. */
4653 return NULL;
4655 /* No less than `infinity' means we could find the last
4656 character at `p[start - infinity]'. */
4657 start -= infinity;
4659 /* Check the remaining characters. */
4660 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
4661 /* Found. */
4662 return non_lisp_beg + start;
4664 start += last_char_skip;
4666 while (start <= start_max);
4668 return NULL;
4672 /* Return a string allocated in pure space. DATA is a buffer holding
4673 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
4674 non-zero means make the result string multibyte.
4676 Must get an error if pure storage is full, since if it cannot hold
4677 a large string it may be able to hold conses that point to that
4678 string; then the string is not protected from gc. */
4680 Lisp_Object
4681 make_pure_string (const char *data,
4682 EMACS_INT nchars, EMACS_INT nbytes, int multibyte)
4684 Lisp_Object string;
4685 struct Lisp_String *s;
4687 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
4688 s->data = (unsigned char *) find_string_data_in_pure (data, nbytes);
4689 if (s->data == NULL)
4691 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
4692 memcpy (s->data, data, nbytes);
4693 s->data[nbytes] = '\0';
4695 s->size = nchars;
4696 s->size_byte = multibyte ? nbytes : -1;
4697 s->intervals = NULL_INTERVAL;
4698 XSETSTRING (string, s);
4699 return string;
4702 /* Return a string a string allocated in pure space. Do not allocate
4703 the string data, just point to DATA. */
4705 Lisp_Object
4706 make_pure_c_string (const char *data)
4708 Lisp_Object string;
4709 struct Lisp_String *s;
4710 EMACS_INT nchars = strlen (data);
4712 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
4713 s->size = nchars;
4714 s->size_byte = -1;
4715 s->data = (unsigned char *) data;
4716 s->intervals = NULL_INTERVAL;
4717 XSETSTRING (string, s);
4718 return string;
4721 /* Return a cons allocated from pure space. Give it pure copies
4722 of CAR as car and CDR as cdr. */
4724 Lisp_Object
4725 pure_cons (Lisp_Object car, Lisp_Object cdr)
4727 register Lisp_Object new;
4728 struct Lisp_Cons *p;
4730 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
4731 XSETCONS (new, p);
4732 XSETCAR (new, Fpurecopy (car));
4733 XSETCDR (new, Fpurecopy (cdr));
4734 return new;
4738 /* Value is a float object with value NUM allocated from pure space. */
4740 static Lisp_Object
4741 make_pure_float (double num)
4743 register Lisp_Object new;
4744 struct Lisp_Float *p;
4746 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
4747 XSETFLOAT (new, p);
4748 XFLOAT_INIT (new, num);
4749 return new;
4753 /* Return a vector with room for LEN Lisp_Objects allocated from
4754 pure space. */
4756 Lisp_Object
4757 make_pure_vector (EMACS_INT len)
4759 Lisp_Object new;
4760 struct Lisp_Vector *p;
4761 size_t size = (offsetof (struct Lisp_Vector, contents)
4762 + len * sizeof (Lisp_Object));
4764 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
4765 XSETVECTOR (new, p);
4766 XVECTOR (new)->header.size = len;
4767 return new;
4771 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
4772 doc: /* Make a copy of object OBJ in pure storage.
4773 Recursively copies contents of vectors and cons cells.
4774 Does not copy symbols. Copies strings without text properties. */)
4775 (register Lisp_Object obj)
4777 if (NILP (Vpurify_flag))
4778 return obj;
4780 if (PURE_POINTER_P (XPNTR (obj)))
4781 return obj;
4783 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
4785 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
4786 if (!NILP (tmp))
4787 return tmp;
4790 if (CONSP (obj))
4791 obj = pure_cons (XCAR (obj), XCDR (obj));
4792 else if (FLOATP (obj))
4793 obj = make_pure_float (XFLOAT_DATA (obj));
4794 else if (STRINGP (obj))
4795 obj = make_pure_string (SSDATA (obj), SCHARS (obj),
4796 SBYTES (obj),
4797 STRING_MULTIBYTE (obj));
4798 else if (COMPILEDP (obj) || VECTORP (obj))
4800 register struct Lisp_Vector *vec;
4801 register EMACS_INT i;
4802 EMACS_INT size;
4804 size = ASIZE (obj);
4805 if (size & PSEUDOVECTOR_FLAG)
4806 size &= PSEUDOVECTOR_SIZE_MASK;
4807 vec = XVECTOR (make_pure_vector (size));
4808 for (i = 0; i < size; i++)
4809 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
4810 if (COMPILEDP (obj))
4812 XSETPVECTYPE (vec, PVEC_COMPILED);
4813 XSETCOMPILED (obj, vec);
4815 else
4816 XSETVECTOR (obj, vec);
4818 else if (MARKERP (obj))
4819 error ("Attempt to copy a marker to pure storage");
4820 else
4821 /* Not purified, don't hash-cons. */
4822 return obj;
4824 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
4825 Fputhash (obj, obj, Vpurify_flag);
4827 return obj;
4832 /***********************************************************************
4833 Protection from GC
4834 ***********************************************************************/
4836 /* Put an entry in staticvec, pointing at the variable with address
4837 VARADDRESS. */
4839 void
4840 staticpro (Lisp_Object *varaddress)
4842 staticvec[staticidx++] = varaddress;
4843 if (staticidx >= NSTATICS)
4844 abort ();
4848 /***********************************************************************
4849 Protection from GC
4850 ***********************************************************************/
4852 /* Temporarily prevent garbage collection. */
4855 inhibit_garbage_collection (void)
4857 int count = SPECPDL_INDEX ();
4859 specbind (Qgc_cons_threshold, make_number (MOST_POSITIVE_FIXNUM));
4860 return count;
4864 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
4865 doc: /* Reclaim storage for Lisp objects no longer needed.
4866 Garbage collection happens automatically if you cons more than
4867 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
4868 `garbage-collect' normally returns a list with info on amount of space in use:
4869 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
4870 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
4871 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)
4872 (USED-STRINGS . FREE-STRINGS))
4873 However, if there was overflow in pure space, `garbage-collect'
4874 returns nil, because real GC can't be done. */)
4875 (void)
4877 register struct specbinding *bind;
4878 char stack_top_variable;
4879 ptrdiff_t i;
4880 int message_p;
4881 Lisp_Object total[8];
4882 int count = SPECPDL_INDEX ();
4883 EMACS_TIME t1, t2, t3;
4885 if (abort_on_gc)
4886 abort ();
4888 /* Can't GC if pure storage overflowed because we can't determine
4889 if something is a pure object or not. */
4890 if (pure_bytes_used_before_overflow)
4891 return Qnil;
4893 CHECK_CONS_LIST ();
4895 /* Don't keep undo information around forever.
4896 Do this early on, so it is no problem if the user quits. */
4898 register struct buffer *nextb = all_buffers;
4900 while (nextb)
4902 /* If a buffer's undo list is Qt, that means that undo is
4903 turned off in that buffer. Calling truncate_undo_list on
4904 Qt tends to return NULL, which effectively turns undo back on.
4905 So don't call truncate_undo_list if undo_list is Qt. */
4906 if (! NILP (nextb->BUFFER_INTERNAL_FIELD (name)) && ! EQ (nextb->BUFFER_INTERNAL_FIELD (undo_list), Qt))
4907 truncate_undo_list (nextb);
4909 /* Shrink buffer gaps, but skip indirect and dead buffers. */
4910 if (nextb->base_buffer == 0 && !NILP (nextb->BUFFER_INTERNAL_FIELD (name))
4911 && ! nextb->text->inhibit_shrinking)
4913 /* If a buffer's gap size is more than 10% of the buffer
4914 size, or larger than 2000 bytes, then shrink it
4915 accordingly. Keep a minimum size of 20 bytes. */
4916 int size = min (2000, max (20, (nextb->text->z_byte / 10)));
4918 if (nextb->text->gap_size > size)
4920 struct buffer *save_current = current_buffer;
4921 current_buffer = nextb;
4922 make_gap (-(nextb->text->gap_size - size));
4923 current_buffer = save_current;
4927 nextb = nextb->header.next.buffer;
4931 EMACS_GET_TIME (t1);
4933 /* In case user calls debug_print during GC,
4934 don't let that cause a recursive GC. */
4935 consing_since_gc = 0;
4937 /* Save what's currently displayed in the echo area. */
4938 message_p = push_message ();
4939 record_unwind_protect (pop_message_unwind, Qnil);
4941 /* Save a copy of the contents of the stack, for debugging. */
4942 #if MAX_SAVE_STACK > 0
4943 if (NILP (Vpurify_flag))
4945 char *stack;
4946 ptrdiff_t stack_size;
4947 if (&stack_top_variable < stack_bottom)
4949 stack = &stack_top_variable;
4950 stack_size = stack_bottom - &stack_top_variable;
4952 else
4954 stack = stack_bottom;
4955 stack_size = &stack_top_variable - stack_bottom;
4957 if (stack_size <= MAX_SAVE_STACK)
4959 if (stack_copy_size < stack_size)
4961 stack_copy = (char *) xrealloc (stack_copy, stack_size);
4962 stack_copy_size = stack_size;
4964 memcpy (stack_copy, stack, stack_size);
4967 #endif /* MAX_SAVE_STACK > 0 */
4969 if (garbage_collection_messages)
4970 message1_nolog ("Garbage collecting...");
4972 BLOCK_INPUT;
4974 shrink_regexp_cache ();
4976 gc_in_progress = 1;
4978 /* clear_marks (); */
4980 /* Mark all the special slots that serve as the roots of accessibility. */
4982 for (i = 0; i < staticidx; i++)
4983 mark_object (*staticvec[i]);
4985 for (bind = specpdl; bind != specpdl_ptr; bind++)
4987 mark_object (bind->symbol);
4988 mark_object (bind->old_value);
4990 mark_terminals ();
4991 mark_kboards ();
4992 mark_ttys ();
4994 #ifdef USE_GTK
4996 extern void xg_mark_data (void);
4997 xg_mark_data ();
4999 #endif
5001 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
5002 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
5003 mark_stack ();
5004 #else
5006 register struct gcpro *tail;
5007 for (tail = gcprolist; tail; tail = tail->next)
5008 for (i = 0; i < tail->nvars; i++)
5009 mark_object (tail->var[i]);
5011 mark_byte_stack ();
5013 struct catchtag *catch;
5014 struct handler *handler;
5016 for (catch = catchlist; catch; catch = catch->next)
5018 mark_object (catch->tag);
5019 mark_object (catch->val);
5021 for (handler = handlerlist; handler; handler = handler->next)
5023 mark_object (handler->handler);
5024 mark_object (handler->var);
5027 mark_backtrace ();
5028 #endif
5030 #ifdef HAVE_WINDOW_SYSTEM
5031 mark_fringe_data ();
5032 #endif
5034 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5035 mark_stack ();
5036 #endif
5038 /* Everything is now marked, except for the things that require special
5039 finalization, i.e. the undo_list.
5040 Look thru every buffer's undo list
5041 for elements that update markers that were not marked,
5042 and delete them. */
5044 register struct buffer *nextb = all_buffers;
5046 while (nextb)
5048 /* If a buffer's undo list is Qt, that means that undo is
5049 turned off in that buffer. Calling truncate_undo_list on
5050 Qt tends to return NULL, which effectively turns undo back on.
5051 So don't call truncate_undo_list if undo_list is Qt. */
5052 if (! EQ (nextb->BUFFER_INTERNAL_FIELD (undo_list), Qt))
5054 Lisp_Object tail, prev;
5055 tail = nextb->BUFFER_INTERNAL_FIELD (undo_list);
5056 prev = Qnil;
5057 while (CONSP (tail))
5059 if (CONSP (XCAR (tail))
5060 && MARKERP (XCAR (XCAR (tail)))
5061 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5063 if (NILP (prev))
5064 nextb->BUFFER_INTERNAL_FIELD (undo_list) = tail = XCDR (tail);
5065 else
5067 tail = XCDR (tail);
5068 XSETCDR (prev, tail);
5071 else
5073 prev = tail;
5074 tail = XCDR (tail);
5078 /* Now that we have stripped the elements that need not be in the
5079 undo_list any more, we can finally mark the list. */
5080 mark_object (nextb->BUFFER_INTERNAL_FIELD (undo_list));
5082 nextb = nextb->header.next.buffer;
5086 gc_sweep ();
5088 /* Clear the mark bits that we set in certain root slots. */
5090 unmark_byte_stack ();
5091 VECTOR_UNMARK (&buffer_defaults);
5092 VECTOR_UNMARK (&buffer_local_symbols);
5094 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
5095 dump_zombies ();
5096 #endif
5098 UNBLOCK_INPUT;
5100 CHECK_CONS_LIST ();
5102 /* clear_marks (); */
5103 gc_in_progress = 0;
5105 consing_since_gc = 0;
5106 if (gc_cons_threshold < 10000)
5107 gc_cons_threshold = 10000;
5109 gc_relative_threshold = 0;
5110 if (FLOATP (Vgc_cons_percentage))
5111 { /* Set gc_cons_combined_threshold. */
5112 double tot = 0;
5114 tot += total_conses * sizeof (struct Lisp_Cons);
5115 tot += total_symbols * sizeof (struct Lisp_Symbol);
5116 tot += total_markers * sizeof (union Lisp_Misc);
5117 tot += total_string_size;
5118 tot += total_vector_size * sizeof (Lisp_Object);
5119 tot += total_floats * sizeof (struct Lisp_Float);
5120 tot += total_intervals * sizeof (struct interval);
5121 tot += total_strings * sizeof (struct Lisp_String);
5123 tot *= XFLOAT_DATA (Vgc_cons_percentage);
5124 if (0 < tot)
5126 if (tot < TYPE_MAXIMUM (EMACS_INT))
5127 gc_relative_threshold = tot;
5128 else
5129 gc_relative_threshold = TYPE_MAXIMUM (EMACS_INT);
5133 if (garbage_collection_messages)
5135 if (message_p || minibuf_level > 0)
5136 restore_message ();
5137 else
5138 message1_nolog ("Garbage collecting...done");
5141 unbind_to (count, Qnil);
5143 total[0] = Fcons (make_number (total_conses),
5144 make_number (total_free_conses));
5145 total[1] = Fcons (make_number (total_symbols),
5146 make_number (total_free_symbols));
5147 total[2] = Fcons (make_number (total_markers),
5148 make_number (total_free_markers));
5149 total[3] = make_number (total_string_size);
5150 total[4] = make_number (total_vector_size);
5151 total[5] = Fcons (make_number (total_floats),
5152 make_number (total_free_floats));
5153 total[6] = Fcons (make_number (total_intervals),
5154 make_number (total_free_intervals));
5155 total[7] = Fcons (make_number (total_strings),
5156 make_number (total_free_strings));
5158 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5160 /* Compute average percentage of zombies. */
5161 double nlive = 0;
5163 for (i = 0; i < 7; ++i)
5164 if (CONSP (total[i]))
5165 nlive += XFASTINT (XCAR (total[i]));
5167 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
5168 max_live = max (nlive, max_live);
5169 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
5170 max_zombies = max (nzombies, max_zombies);
5171 ++ngcs;
5173 #endif
5175 if (!NILP (Vpost_gc_hook))
5177 int gc_count = inhibit_garbage_collection ();
5178 safe_run_hooks (Qpost_gc_hook);
5179 unbind_to (gc_count, Qnil);
5182 /* Accumulate statistics. */
5183 EMACS_GET_TIME (t2);
5184 EMACS_SUB_TIME (t3, t2, t1);
5185 if (FLOATP (Vgc_elapsed))
5186 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed) +
5187 EMACS_SECS (t3) +
5188 EMACS_USECS (t3) * 1.0e-6);
5189 gcs_done++;
5191 return Flist (sizeof total / sizeof *total, total);
5195 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5196 only interesting objects referenced from glyphs are strings. */
5198 static void
5199 mark_glyph_matrix (struct glyph_matrix *matrix)
5201 struct glyph_row *row = matrix->rows;
5202 struct glyph_row *end = row + matrix->nrows;
5204 for (; row < end; ++row)
5205 if (row->enabled_p)
5207 int area;
5208 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
5210 struct glyph *glyph = row->glyphs[area];
5211 struct glyph *end_glyph = glyph + row->used[area];
5213 for (; glyph < end_glyph; ++glyph)
5214 if (STRINGP (glyph->object)
5215 && !STRING_MARKED_P (XSTRING (glyph->object)))
5216 mark_object (glyph->object);
5222 /* Mark Lisp faces in the face cache C. */
5224 static void
5225 mark_face_cache (struct face_cache *c)
5227 if (c)
5229 int i, j;
5230 for (i = 0; i < c->used; ++i)
5232 struct face *face = FACE_FROM_ID (c->f, i);
5234 if (face)
5236 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
5237 mark_object (face->lface[j]);
5245 /* Mark reference to a Lisp_Object.
5246 If the object referred to has not been seen yet, recursively mark
5247 all the references contained in it. */
5249 #define LAST_MARKED_SIZE 500
5250 static Lisp_Object last_marked[LAST_MARKED_SIZE];
5251 static int last_marked_index;
5253 /* For debugging--call abort when we cdr down this many
5254 links of a list, in mark_object. In debugging,
5255 the call to abort will hit a breakpoint.
5256 Normally this is zero and the check never goes off. */
5257 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE;
5259 static void
5260 mark_vectorlike (struct Lisp_Vector *ptr)
5262 EMACS_INT size = ptr->header.size;
5263 EMACS_INT i;
5265 eassert (!VECTOR_MARKED_P (ptr));
5266 VECTOR_MARK (ptr); /* Else mark it */
5267 if (size & PSEUDOVECTOR_FLAG)
5268 size &= PSEUDOVECTOR_SIZE_MASK;
5270 /* Note that this size is not the memory-footprint size, but only
5271 the number of Lisp_Object fields that we should trace.
5272 The distinction is used e.g. by Lisp_Process which places extra
5273 non-Lisp_Object fields at the end of the structure. */
5274 for (i = 0; i < size; i++) /* and then mark its elements */
5275 mark_object (ptr->contents[i]);
5278 /* Like mark_vectorlike but optimized for char-tables (and
5279 sub-char-tables) assuming that the contents are mostly integers or
5280 symbols. */
5282 static void
5283 mark_char_table (struct Lisp_Vector *ptr)
5285 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5286 int i;
5288 eassert (!VECTOR_MARKED_P (ptr));
5289 VECTOR_MARK (ptr);
5290 for (i = 0; i < size; i++)
5292 Lisp_Object val = ptr->contents[i];
5294 if (INTEGERP (val) || (SYMBOLP (val) && XSYMBOL (val)->gcmarkbit))
5295 continue;
5296 if (SUB_CHAR_TABLE_P (val))
5298 if (! VECTOR_MARKED_P (XVECTOR (val)))
5299 mark_char_table (XVECTOR (val));
5301 else
5302 mark_object (val);
5306 void
5307 mark_object (Lisp_Object arg)
5309 register Lisp_Object obj = arg;
5310 #ifdef GC_CHECK_MARKED_OBJECTS
5311 void *po;
5312 struct mem_node *m;
5313 #endif
5314 ptrdiff_t cdr_count = 0;
5316 loop:
5318 if (PURE_POINTER_P (XPNTR (obj)))
5319 return;
5321 last_marked[last_marked_index++] = obj;
5322 if (last_marked_index == LAST_MARKED_SIZE)
5323 last_marked_index = 0;
5325 /* Perform some sanity checks on the objects marked here. Abort if
5326 we encounter an object we know is bogus. This increases GC time
5327 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
5328 #ifdef GC_CHECK_MARKED_OBJECTS
5330 po = (void *) XPNTR (obj);
5332 /* Check that the object pointed to by PO is known to be a Lisp
5333 structure allocated from the heap. */
5334 #define CHECK_ALLOCATED() \
5335 do { \
5336 m = mem_find (po); \
5337 if (m == MEM_NIL) \
5338 abort (); \
5339 } while (0)
5341 /* Check that the object pointed to by PO is live, using predicate
5342 function LIVEP. */
5343 #define CHECK_LIVE(LIVEP) \
5344 do { \
5345 if (!LIVEP (m, po)) \
5346 abort (); \
5347 } while (0)
5349 /* Check both of the above conditions. */
5350 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
5351 do { \
5352 CHECK_ALLOCATED (); \
5353 CHECK_LIVE (LIVEP); \
5354 } while (0) \
5356 #else /* not GC_CHECK_MARKED_OBJECTS */
5358 #define CHECK_LIVE(LIVEP) (void) 0
5359 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
5361 #endif /* not GC_CHECK_MARKED_OBJECTS */
5363 switch (SWITCH_ENUM_CAST (XTYPE (obj)))
5365 case Lisp_String:
5367 register struct Lisp_String *ptr = XSTRING (obj);
5368 if (STRING_MARKED_P (ptr))
5369 break;
5370 CHECK_ALLOCATED_AND_LIVE (live_string_p);
5371 MARK_INTERVAL_TREE (ptr->intervals);
5372 MARK_STRING (ptr);
5373 #ifdef GC_CHECK_STRING_BYTES
5374 /* Check that the string size recorded in the string is the
5375 same as the one recorded in the sdata structure. */
5376 CHECK_STRING_BYTES (ptr);
5377 #endif /* GC_CHECK_STRING_BYTES */
5379 break;
5381 case Lisp_Vectorlike:
5382 if (VECTOR_MARKED_P (XVECTOR (obj)))
5383 break;
5384 #ifdef GC_CHECK_MARKED_OBJECTS
5385 m = mem_find (po);
5386 if (m == MEM_NIL && !SUBRP (obj)
5387 && po != &buffer_defaults
5388 && po != &buffer_local_symbols)
5389 abort ();
5390 #endif /* GC_CHECK_MARKED_OBJECTS */
5392 if (BUFFERP (obj))
5394 #ifdef GC_CHECK_MARKED_OBJECTS
5395 if (po != &buffer_defaults && po != &buffer_local_symbols)
5397 struct buffer *b;
5398 for (b = all_buffers; b && b != po; b = b->header.next.buffer)
5400 if (b == NULL)
5401 abort ();
5403 #endif /* GC_CHECK_MARKED_OBJECTS */
5404 mark_buffer (obj);
5406 else if (SUBRP (obj))
5407 break;
5408 else if (COMPILEDP (obj))
5409 /* We could treat this just like a vector, but it is better to
5410 save the COMPILED_CONSTANTS element for last and avoid
5411 recursion there. */
5413 register struct Lisp_Vector *ptr = XVECTOR (obj);
5414 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5415 int i;
5417 CHECK_LIVE (live_vector_p);
5418 VECTOR_MARK (ptr); /* Else mark it */
5419 for (i = 0; i < size; i++) /* and then mark its elements */
5421 if (i != COMPILED_CONSTANTS)
5422 mark_object (ptr->contents[i]);
5424 obj = ptr->contents[COMPILED_CONSTANTS];
5425 goto loop;
5427 else if (FRAMEP (obj))
5429 register struct frame *ptr = XFRAME (obj);
5430 mark_vectorlike (XVECTOR (obj));
5431 mark_face_cache (ptr->face_cache);
5433 else if (WINDOWP (obj))
5435 register struct Lisp_Vector *ptr = XVECTOR (obj);
5436 struct window *w = XWINDOW (obj);
5437 mark_vectorlike (ptr);
5438 /* Mark glyphs for leaf windows. Marking window matrices is
5439 sufficient because frame matrices use the same glyph
5440 memory. */
5441 if (NILP (w->hchild)
5442 && NILP (w->vchild)
5443 && w->current_matrix)
5445 mark_glyph_matrix (w->current_matrix);
5446 mark_glyph_matrix (w->desired_matrix);
5449 else if (HASH_TABLE_P (obj))
5451 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
5452 mark_vectorlike ((struct Lisp_Vector *)h);
5453 /* If hash table is not weak, mark all keys and values.
5454 For weak tables, mark only the vector. */
5455 if (NILP (h->weak))
5456 mark_object (h->key_and_value);
5457 else
5458 VECTOR_MARK (XVECTOR (h->key_and_value));
5460 else if (CHAR_TABLE_P (obj))
5461 mark_char_table (XVECTOR (obj));
5462 else
5463 mark_vectorlike (XVECTOR (obj));
5464 break;
5466 case Lisp_Symbol:
5468 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
5469 struct Lisp_Symbol *ptrx;
5471 if (ptr->gcmarkbit)
5472 break;
5473 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
5474 ptr->gcmarkbit = 1;
5475 mark_object (ptr->function);
5476 mark_object (ptr->plist);
5477 switch (ptr->redirect)
5479 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
5480 case SYMBOL_VARALIAS:
5482 Lisp_Object tem;
5483 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
5484 mark_object (tem);
5485 break;
5487 case SYMBOL_LOCALIZED:
5489 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
5490 /* If the value is forwarded to a buffer or keyboard field,
5491 these are marked when we see the corresponding object.
5492 And if it's forwarded to a C variable, either it's not
5493 a Lisp_Object var, or it's staticpro'd already. */
5494 mark_object (blv->where);
5495 mark_object (blv->valcell);
5496 mark_object (blv->defcell);
5497 break;
5499 case SYMBOL_FORWARDED:
5500 /* If the value is forwarded to a buffer or keyboard field,
5501 these are marked when we see the corresponding object.
5502 And if it's forwarded to a C variable, either it's not
5503 a Lisp_Object var, or it's staticpro'd already. */
5504 break;
5505 default: abort ();
5507 if (!PURE_POINTER_P (XSTRING (ptr->xname)))
5508 MARK_STRING (XSTRING (ptr->xname));
5509 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr->xname));
5511 ptr = ptr->next;
5512 if (ptr)
5514 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
5515 XSETSYMBOL (obj, ptrx);
5516 goto loop;
5519 break;
5521 case Lisp_Misc:
5522 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
5523 if (XMISCANY (obj)->gcmarkbit)
5524 break;
5525 XMISCANY (obj)->gcmarkbit = 1;
5527 switch (XMISCTYPE (obj))
5530 case Lisp_Misc_Marker:
5531 /* DO NOT mark thru the marker's chain.
5532 The buffer's markers chain does not preserve markers from gc;
5533 instead, markers are removed from the chain when freed by gc. */
5534 break;
5536 case Lisp_Misc_Save_Value:
5537 #if GC_MARK_STACK
5539 register struct Lisp_Save_Value *ptr = XSAVE_VALUE (obj);
5540 /* If DOGC is set, POINTER is the address of a memory
5541 area containing INTEGER potential Lisp_Objects. */
5542 if (ptr->dogc)
5544 Lisp_Object *p = (Lisp_Object *) ptr->pointer;
5545 ptrdiff_t nelt;
5546 for (nelt = ptr->integer; nelt > 0; nelt--, p++)
5547 mark_maybe_object (*p);
5550 #endif
5551 break;
5553 case Lisp_Misc_Overlay:
5555 struct Lisp_Overlay *ptr = XOVERLAY (obj);
5556 mark_object (ptr->start);
5557 mark_object (ptr->end);
5558 mark_object (ptr->plist);
5559 if (ptr->next)
5561 XSETMISC (obj, ptr->next);
5562 goto loop;
5565 break;
5567 default:
5568 abort ();
5570 break;
5572 case Lisp_Cons:
5574 register struct Lisp_Cons *ptr = XCONS (obj);
5575 if (CONS_MARKED_P (ptr))
5576 break;
5577 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
5578 CONS_MARK (ptr);
5579 /* If the cdr is nil, avoid recursion for the car. */
5580 if (EQ (ptr->u.cdr, Qnil))
5582 obj = ptr->car;
5583 cdr_count = 0;
5584 goto loop;
5586 mark_object (ptr->car);
5587 obj = ptr->u.cdr;
5588 cdr_count++;
5589 if (cdr_count == mark_object_loop_halt)
5590 abort ();
5591 goto loop;
5594 case Lisp_Float:
5595 CHECK_ALLOCATED_AND_LIVE (live_float_p);
5596 FLOAT_MARK (XFLOAT (obj));
5597 break;
5599 case_Lisp_Int:
5600 break;
5602 default:
5603 abort ();
5606 #undef CHECK_LIVE
5607 #undef CHECK_ALLOCATED
5608 #undef CHECK_ALLOCATED_AND_LIVE
5611 /* Mark the pointers in a buffer structure. */
5613 static void
5614 mark_buffer (Lisp_Object buf)
5616 register struct buffer *buffer = XBUFFER (buf);
5617 register Lisp_Object *ptr, tmp;
5618 Lisp_Object base_buffer;
5620 eassert (!VECTOR_MARKED_P (buffer));
5621 VECTOR_MARK (buffer);
5623 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
5625 /* For now, we just don't mark the undo_list. It's done later in
5626 a special way just before the sweep phase, and after stripping
5627 some of its elements that are not needed any more. */
5629 if (buffer->overlays_before)
5631 XSETMISC (tmp, buffer->overlays_before);
5632 mark_object (tmp);
5634 if (buffer->overlays_after)
5636 XSETMISC (tmp, buffer->overlays_after);
5637 mark_object (tmp);
5640 /* buffer-local Lisp variables start at `undo_list',
5641 tho only the ones from `name' on are GC'd normally. */
5642 for (ptr = &buffer->BUFFER_INTERNAL_FIELD (name);
5643 ptr <= &PER_BUFFER_VALUE (buffer,
5644 PER_BUFFER_VAR_OFFSET (LAST_FIELD_PER_BUFFER));
5645 ptr++)
5646 mark_object (*ptr);
5648 /* If this is an indirect buffer, mark its base buffer. */
5649 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5651 XSETBUFFER (base_buffer, buffer->base_buffer);
5652 mark_buffer (base_buffer);
5656 /* Mark the Lisp pointers in the terminal objects.
5657 Called by the Fgarbage_collector. */
5659 static void
5660 mark_terminals (void)
5662 struct terminal *t;
5663 for (t = terminal_list; t; t = t->next_terminal)
5665 eassert (t->name != NULL);
5666 #ifdef HAVE_WINDOW_SYSTEM
5667 /* If a terminal object is reachable from a stacpro'ed object,
5668 it might have been marked already. Make sure the image cache
5669 gets marked. */
5670 mark_image_cache (t->image_cache);
5671 #endif /* HAVE_WINDOW_SYSTEM */
5672 if (!VECTOR_MARKED_P (t))
5673 mark_vectorlike ((struct Lisp_Vector *)t);
5679 /* Value is non-zero if OBJ will survive the current GC because it's
5680 either marked or does not need to be marked to survive. */
5683 survives_gc_p (Lisp_Object obj)
5685 int survives_p;
5687 switch (XTYPE (obj))
5689 case_Lisp_Int:
5690 survives_p = 1;
5691 break;
5693 case Lisp_Symbol:
5694 survives_p = XSYMBOL (obj)->gcmarkbit;
5695 break;
5697 case Lisp_Misc:
5698 survives_p = XMISCANY (obj)->gcmarkbit;
5699 break;
5701 case Lisp_String:
5702 survives_p = STRING_MARKED_P (XSTRING (obj));
5703 break;
5705 case Lisp_Vectorlike:
5706 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
5707 break;
5709 case Lisp_Cons:
5710 survives_p = CONS_MARKED_P (XCONS (obj));
5711 break;
5713 case Lisp_Float:
5714 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
5715 break;
5717 default:
5718 abort ();
5721 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
5726 /* Sweep: find all structures not marked, and free them. */
5728 static void
5729 gc_sweep (void)
5731 /* Remove or mark entries in weak hash tables.
5732 This must be done before any object is unmarked. */
5733 sweep_weak_hash_tables ();
5735 sweep_strings ();
5736 #ifdef GC_CHECK_STRING_BYTES
5737 if (!noninteractive)
5738 check_string_bytes (1);
5739 #endif
5741 /* Put all unmarked conses on free list */
5743 register struct cons_block *cblk;
5744 struct cons_block **cprev = &cons_block;
5745 register int lim = cons_block_index;
5746 EMACS_INT num_free = 0, num_used = 0;
5748 cons_free_list = 0;
5750 for (cblk = cons_block; cblk; cblk = *cprev)
5752 register int i = 0;
5753 int this_free = 0;
5754 int ilim = (lim + BITS_PER_INT - 1) / BITS_PER_INT;
5756 /* Scan the mark bits an int at a time. */
5757 for (i = 0; i < ilim; i++)
5759 if (cblk->gcmarkbits[i] == -1)
5761 /* Fast path - all cons cells for this int are marked. */
5762 cblk->gcmarkbits[i] = 0;
5763 num_used += BITS_PER_INT;
5765 else
5767 /* Some cons cells for this int are not marked.
5768 Find which ones, and free them. */
5769 int start, pos, stop;
5771 start = i * BITS_PER_INT;
5772 stop = lim - start;
5773 if (stop > BITS_PER_INT)
5774 stop = BITS_PER_INT;
5775 stop += start;
5777 for (pos = start; pos < stop; pos++)
5779 if (!CONS_MARKED_P (&cblk->conses[pos]))
5781 this_free++;
5782 cblk->conses[pos].u.chain = cons_free_list;
5783 cons_free_list = &cblk->conses[pos];
5784 #if GC_MARK_STACK
5785 cons_free_list->car = Vdead;
5786 #endif
5788 else
5790 num_used++;
5791 CONS_UNMARK (&cblk->conses[pos]);
5797 lim = CONS_BLOCK_SIZE;
5798 /* If this block contains only free conses and we have already
5799 seen more than two blocks worth of free conses then deallocate
5800 this block. */
5801 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
5803 *cprev = cblk->next;
5804 /* Unhook from the free list. */
5805 cons_free_list = cblk->conses[0].u.chain;
5806 lisp_align_free (cblk);
5808 else
5810 num_free += this_free;
5811 cprev = &cblk->next;
5814 total_conses = num_used;
5815 total_free_conses = num_free;
5818 /* Put all unmarked floats on free list */
5820 register struct float_block *fblk;
5821 struct float_block **fprev = &float_block;
5822 register int lim = float_block_index;
5823 EMACS_INT num_free = 0, num_used = 0;
5825 float_free_list = 0;
5827 for (fblk = float_block; fblk; fblk = *fprev)
5829 register int i;
5830 int this_free = 0;
5831 for (i = 0; i < lim; i++)
5832 if (!FLOAT_MARKED_P (&fblk->floats[i]))
5834 this_free++;
5835 fblk->floats[i].u.chain = float_free_list;
5836 float_free_list = &fblk->floats[i];
5838 else
5840 num_used++;
5841 FLOAT_UNMARK (&fblk->floats[i]);
5843 lim = FLOAT_BLOCK_SIZE;
5844 /* If this block contains only free floats and we have already
5845 seen more than two blocks worth of free floats then deallocate
5846 this block. */
5847 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
5849 *fprev = fblk->next;
5850 /* Unhook from the free list. */
5851 float_free_list = fblk->floats[0].u.chain;
5852 lisp_align_free (fblk);
5854 else
5856 num_free += this_free;
5857 fprev = &fblk->next;
5860 total_floats = num_used;
5861 total_free_floats = num_free;
5864 /* Put all unmarked intervals on free list */
5866 register struct interval_block *iblk;
5867 struct interval_block **iprev = &interval_block;
5868 register int lim = interval_block_index;
5869 EMACS_INT num_free = 0, num_used = 0;
5871 interval_free_list = 0;
5873 for (iblk = interval_block; iblk; iblk = *iprev)
5875 register int i;
5876 int this_free = 0;
5878 for (i = 0; i < lim; i++)
5880 if (!iblk->intervals[i].gcmarkbit)
5882 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
5883 interval_free_list = &iblk->intervals[i];
5884 this_free++;
5886 else
5888 num_used++;
5889 iblk->intervals[i].gcmarkbit = 0;
5892 lim = INTERVAL_BLOCK_SIZE;
5893 /* If this block contains only free intervals and we have already
5894 seen more than two blocks worth of free intervals then
5895 deallocate this block. */
5896 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
5898 *iprev = iblk->next;
5899 /* Unhook from the free list. */
5900 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
5901 lisp_free (iblk);
5903 else
5905 num_free += this_free;
5906 iprev = &iblk->next;
5909 total_intervals = num_used;
5910 total_free_intervals = num_free;
5913 /* Put all unmarked symbols on free list */
5915 register struct symbol_block *sblk;
5916 struct symbol_block **sprev = &symbol_block;
5917 register int lim = symbol_block_index;
5918 EMACS_INT num_free = 0, num_used = 0;
5920 symbol_free_list = NULL;
5922 for (sblk = symbol_block; sblk; sblk = *sprev)
5924 int this_free = 0;
5925 struct Lisp_Symbol *sym = sblk->symbols;
5926 struct Lisp_Symbol *end = sym + lim;
5928 for (; sym < end; ++sym)
5930 /* Check if the symbol was created during loadup. In such a case
5931 it might be pointed to by pure bytecode which we don't trace,
5932 so we conservatively assume that it is live. */
5933 int pure_p = PURE_POINTER_P (XSTRING (sym->xname));
5935 if (!sym->gcmarkbit && !pure_p)
5937 if (sym->redirect == SYMBOL_LOCALIZED)
5938 xfree (SYMBOL_BLV (sym));
5939 sym->next = symbol_free_list;
5940 symbol_free_list = sym;
5941 #if GC_MARK_STACK
5942 symbol_free_list->function = Vdead;
5943 #endif
5944 ++this_free;
5946 else
5948 ++num_used;
5949 if (!pure_p)
5950 UNMARK_STRING (XSTRING (sym->xname));
5951 sym->gcmarkbit = 0;
5955 lim = SYMBOL_BLOCK_SIZE;
5956 /* If this block contains only free symbols and we have already
5957 seen more than two blocks worth of free symbols then deallocate
5958 this block. */
5959 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
5961 *sprev = sblk->next;
5962 /* Unhook from the free list. */
5963 symbol_free_list = sblk->symbols[0].next;
5964 lisp_free (sblk);
5966 else
5968 num_free += this_free;
5969 sprev = &sblk->next;
5972 total_symbols = num_used;
5973 total_free_symbols = num_free;
5976 /* Put all unmarked misc's on free list.
5977 For a marker, first unchain it from the buffer it points into. */
5979 register struct marker_block *mblk;
5980 struct marker_block **mprev = &marker_block;
5981 register int lim = marker_block_index;
5982 EMACS_INT num_free = 0, num_used = 0;
5984 marker_free_list = 0;
5986 for (mblk = marker_block; mblk; mblk = *mprev)
5988 register int i;
5989 int this_free = 0;
5991 for (i = 0; i < lim; i++)
5993 if (!mblk->markers[i].u_any.gcmarkbit)
5995 if (mblk->markers[i].u_any.type == Lisp_Misc_Marker)
5996 unchain_marker (&mblk->markers[i].u_marker);
5997 /* Set the type of the freed object to Lisp_Misc_Free.
5998 We could leave the type alone, since nobody checks it,
5999 but this might catch bugs faster. */
6000 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
6001 mblk->markers[i].u_free.chain = marker_free_list;
6002 marker_free_list = &mblk->markers[i];
6003 this_free++;
6005 else
6007 num_used++;
6008 mblk->markers[i].u_any.gcmarkbit = 0;
6011 lim = MARKER_BLOCK_SIZE;
6012 /* If this block contains only free markers and we have already
6013 seen more than two blocks worth of free markers then deallocate
6014 this block. */
6015 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6017 *mprev = mblk->next;
6018 /* Unhook from the free list. */
6019 marker_free_list = mblk->markers[0].u_free.chain;
6020 lisp_free (mblk);
6022 else
6024 num_free += this_free;
6025 mprev = &mblk->next;
6029 total_markers = num_used;
6030 total_free_markers = num_free;
6033 /* Free all unmarked buffers */
6035 register struct buffer *buffer = all_buffers, *prev = 0, *next;
6037 while (buffer)
6038 if (!VECTOR_MARKED_P (buffer))
6040 if (prev)
6041 prev->header.next = buffer->header.next;
6042 else
6043 all_buffers = buffer->header.next.buffer;
6044 next = buffer->header.next.buffer;
6045 lisp_free (buffer);
6046 buffer = next;
6048 else
6050 VECTOR_UNMARK (buffer);
6051 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
6052 prev = buffer, buffer = buffer->header.next.buffer;
6056 /* Free all unmarked vectors */
6058 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
6059 total_vector_size = 0;
6061 while (vector)
6062 if (!VECTOR_MARKED_P (vector))
6064 if (prev)
6065 prev->header.next = vector->header.next;
6066 else
6067 all_vectors = vector->header.next.vector;
6068 next = vector->header.next.vector;
6069 lisp_free (vector);
6070 vector = next;
6073 else
6075 VECTOR_UNMARK (vector);
6076 if (vector->header.size & PSEUDOVECTOR_FLAG)
6077 total_vector_size += PSEUDOVECTOR_SIZE_MASK & vector->header.size;
6078 else
6079 total_vector_size += vector->header.size;
6080 prev = vector, vector = vector->header.next.vector;
6084 #ifdef GC_CHECK_STRING_BYTES
6085 if (!noninteractive)
6086 check_string_bytes (1);
6087 #endif
6093 /* Debugging aids. */
6095 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
6096 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6097 This may be helpful in debugging Emacs's memory usage.
6098 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6099 (void)
6101 Lisp_Object end;
6103 XSETINT (end, (intptr_t) (char *) sbrk (0) / 1024);
6105 return end;
6108 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
6109 doc: /* Return a list of counters that measure how much consing there has been.
6110 Each of these counters increments for a certain kind of object.
6111 The counters wrap around from the largest positive integer to zero.
6112 Garbage collection does not decrease them.
6113 The elements of the value are as follows:
6114 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6115 All are in units of 1 = one object consed
6116 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6117 objects consed.
6118 MISCS include overlays, markers, and some internal types.
6119 Frames, windows, buffers, and subprocesses count as vectors
6120 (but the contents of a buffer's text do not count here). */)
6121 (void)
6123 Lisp_Object consed[8];
6125 consed[0] = make_number (min (MOST_POSITIVE_FIXNUM, cons_cells_consed));
6126 consed[1] = make_number (min (MOST_POSITIVE_FIXNUM, floats_consed));
6127 consed[2] = make_number (min (MOST_POSITIVE_FIXNUM, vector_cells_consed));
6128 consed[3] = make_number (min (MOST_POSITIVE_FIXNUM, symbols_consed));
6129 consed[4] = make_number (min (MOST_POSITIVE_FIXNUM, string_chars_consed));
6130 consed[5] = make_number (min (MOST_POSITIVE_FIXNUM, misc_objects_consed));
6131 consed[6] = make_number (min (MOST_POSITIVE_FIXNUM, intervals_consed));
6132 consed[7] = make_number (min (MOST_POSITIVE_FIXNUM, strings_consed));
6134 return Flist (8, consed);
6137 #ifdef ENABLE_CHECKING
6138 int suppress_checking;
6140 void
6141 die (const char *msg, const char *file, int line)
6143 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: %s\r\n",
6144 file, line, msg);
6145 abort ();
6147 #endif
6149 /* Initialization */
6151 void
6152 init_alloc_once (void)
6154 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
6155 purebeg = PUREBEG;
6156 pure_size = PURESIZE;
6157 pure_bytes_used = 0;
6158 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
6159 pure_bytes_used_before_overflow = 0;
6161 /* Initialize the list of free aligned blocks. */
6162 free_ablock = NULL;
6164 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
6165 mem_init ();
6166 Vdead = make_pure_string ("DEAD", 4, 4, 0);
6167 #endif
6169 all_vectors = 0;
6170 ignore_warnings = 1;
6171 #ifdef DOUG_LEA_MALLOC
6172 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
6173 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
6174 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
6175 #endif
6176 init_strings ();
6177 init_cons ();
6178 init_symbol ();
6179 init_marker ();
6180 init_float ();
6181 init_intervals ();
6182 init_weak_hash_tables ();
6184 #ifdef REL_ALLOC
6185 malloc_hysteresis = 32;
6186 #else
6187 malloc_hysteresis = 0;
6188 #endif
6190 refill_memory_reserve ();
6192 ignore_warnings = 0;
6193 gcprolist = 0;
6194 byte_stack_list = 0;
6195 staticidx = 0;
6196 consing_since_gc = 0;
6197 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
6198 gc_relative_threshold = 0;
6201 void
6202 init_alloc (void)
6204 gcprolist = 0;
6205 byte_stack_list = 0;
6206 #if GC_MARK_STACK
6207 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
6208 setjmp_tested_p = longjmps_done = 0;
6209 #endif
6210 #endif
6211 Vgc_elapsed = make_float (0.0);
6212 gcs_done = 0;
6215 void
6216 syms_of_alloc (void)
6218 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
6219 doc: /* *Number of bytes of consing between garbage collections.
6220 Garbage collection can happen automatically once this many bytes have been
6221 allocated since the last garbage collection. All data types count.
6223 Garbage collection happens automatically only when `eval' is called.
6225 By binding this temporarily to a large number, you can effectively
6226 prevent garbage collection during a part of the program.
6227 See also `gc-cons-percentage'. */);
6229 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
6230 doc: /* *Portion of the heap used for allocation.
6231 Garbage collection can happen automatically once this portion of the heap
6232 has been allocated since the last garbage collection.
6233 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
6234 Vgc_cons_percentage = make_float (0.1);
6236 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
6237 doc: /* Number of bytes of sharable Lisp data allocated so far. */);
6239 DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
6240 doc: /* Number of cons cells that have been consed so far. */);
6242 DEFVAR_INT ("floats-consed", floats_consed,
6243 doc: /* Number of floats that have been consed so far. */);
6245 DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
6246 doc: /* Number of vector cells that have been consed so far. */);
6248 DEFVAR_INT ("symbols-consed", symbols_consed,
6249 doc: /* Number of symbols that have been consed so far. */);
6251 DEFVAR_INT ("string-chars-consed", string_chars_consed,
6252 doc: /* Number of string characters that have been consed so far. */);
6254 DEFVAR_INT ("misc-objects-consed", misc_objects_consed,
6255 doc: /* Number of miscellaneous objects that have been consed so far. */);
6257 DEFVAR_INT ("intervals-consed", intervals_consed,
6258 doc: /* Number of intervals that have been consed so far. */);
6260 DEFVAR_INT ("strings-consed", strings_consed,
6261 doc: /* Number of strings that have been consed so far. */);
6263 DEFVAR_LISP ("purify-flag", Vpurify_flag,
6264 doc: /* Non-nil means loading Lisp code in order to dump an executable.
6265 This means that certain objects should be allocated in shared (pure) space.
6266 It can also be set to a hash-table, in which case this table is used to
6267 do hash-consing of the objects allocated to pure space. */);
6269 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
6270 doc: /* Non-nil means display messages at start and end of garbage collection. */);
6271 garbage_collection_messages = 0;
6273 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
6274 doc: /* Hook run after garbage collection has finished. */);
6275 Vpost_gc_hook = Qnil;
6276 DEFSYM (Qpost_gc_hook, "post-gc-hook");
6278 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
6279 doc: /* Precomputed `signal' argument for memory-full error. */);
6280 /* We build this in advance because if we wait until we need it, we might
6281 not be able to allocate the memory to hold it. */
6282 Vmemory_signal_data
6283 = pure_cons (Qerror,
6284 pure_cons (make_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"), Qnil));
6286 DEFVAR_LISP ("memory-full", Vmemory_full,
6287 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
6288 Vmemory_full = Qnil;
6290 DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
6291 DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
6293 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
6294 doc: /* Accumulated time elapsed in garbage collections.
6295 The time is in seconds as a floating point value. */);
6296 DEFVAR_INT ("gcs-done", gcs_done,
6297 doc: /* Accumulated number of garbage collections done. */);
6299 defsubr (&Scons);
6300 defsubr (&Slist);
6301 defsubr (&Svector);
6302 defsubr (&Smake_byte_code);
6303 defsubr (&Smake_list);
6304 defsubr (&Smake_vector);
6305 defsubr (&Smake_string);
6306 defsubr (&Smake_bool_vector);
6307 defsubr (&Smake_symbol);
6308 defsubr (&Smake_marker);
6309 defsubr (&Spurecopy);
6310 defsubr (&Sgarbage_collect);
6311 defsubr (&Smemory_limit);
6312 defsubr (&Smemory_use_counts);
6314 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
6315 defsubr (&Sgc_status);
6316 #endif