(Operating on Files): Simplify previous change and fix Texinfo usage.
[emacs.git] / src / alloc.c
blobe5735e03fd91dc8037c7c54eb7cf1b4d072d8795
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
2 Copyright (C) 1985, 1986, 1988, 1993, 1994, 1995, 1997, 1998, 1999,
3 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
22 #include <config.h>
23 #include <stdio.h>
24 #include <limits.h> /* For CHAR_BIT. */
26 #ifdef STDC_HEADERS
27 #include <stddef.h> /* For offsetof, used by PSEUDOVECSIZE. */
28 #endif
30 #ifdef ALLOC_DEBUG
31 #undef INLINE
32 #endif
34 /* Note that this declares bzero on OSF/1. How dumb. */
36 #include <signal.h>
38 #ifdef HAVE_GTK_AND_PTHREAD
39 #include <pthread.h>
40 #endif
42 /* This file is part of the core Lisp implementation, and thus must
43 deal with the real data structures. If the Lisp implementation is
44 replaced, this file likely will not be used. */
46 #undef HIDE_LISP_IMPLEMENTATION
47 #include "lisp.h"
48 #include "process.h"
49 #include "intervals.h"
50 #include "puresize.h"
51 #include "buffer.h"
52 #include "window.h"
53 #include "keyboard.h"
54 #include "frame.h"
55 #include "blockinput.h"
56 #include "charset.h"
57 #include "syssignal.h"
58 #include <setjmp.h>
60 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
61 memory. Can do this only if using gmalloc.c. */
63 #if defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC
64 #undef GC_MALLOC_CHECK
65 #endif
67 #ifdef HAVE_UNISTD_H
68 #include <unistd.h>
69 #else
70 extern POINTER_TYPE *sbrk ();
71 #endif
73 #ifdef HAVE_FCNTL_H
74 #define INCLUDED_FCNTL
75 #include <fcntl.h>
76 #endif
77 #ifndef O_WRONLY
78 #define O_WRONLY 1
79 #endif
81 #ifdef WINDOWSNT
82 #include <fcntl.h>
83 #endif
85 #ifdef DOUG_LEA_MALLOC
87 #include <malloc.h>
88 /* malloc.h #defines this as size_t, at least in glibc2. */
89 #ifndef __malloc_size_t
90 #define __malloc_size_t int
91 #endif
93 /* Specify maximum number of areas to mmap. It would be nice to use a
94 value that explicitly means "no limit". */
96 #define MMAP_MAX_AREAS 100000000
98 #else /* not DOUG_LEA_MALLOC */
100 /* The following come from gmalloc.c. */
102 #define __malloc_size_t size_t
103 extern __malloc_size_t _bytes_used;
104 extern __malloc_size_t __malloc_extra_blocks;
106 #endif /* not DOUG_LEA_MALLOC */
108 #if ! defined (SYSTEM_MALLOC) && defined (HAVE_GTK_AND_PTHREAD)
110 /* When GTK uses the file chooser dialog, different backends can be loaded
111 dynamically. One such a backend is the Gnome VFS backend that gets loaded
112 if you run Gnome. That backend creates several threads and also allocates
113 memory with malloc.
115 If Emacs sets malloc hooks (! SYSTEM_MALLOC) and the emacs_blocked_*
116 functions below are called from malloc, there is a chance that one
117 of these threads preempts the Emacs main thread and the hook variables
118 end up in an inconsistent state. So we have a mutex to prevent that (note
119 that the backend handles concurrent access to malloc within its own threads
120 but Emacs code running in the main thread is not included in that control).
122 When UNBLOCK_INPUT is called, reinvoke_input_signal may be called. If this
123 happens in one of the backend threads we will have two threads that tries
124 to run Emacs code at once, and the code is not prepared for that.
125 To prevent that, we only call BLOCK/UNBLOCK from the main thread. */
127 static pthread_mutex_t alloc_mutex;
129 #define BLOCK_INPUT_ALLOC \
130 do \
132 pthread_mutex_lock (&alloc_mutex); \
133 if (pthread_self () == main_thread) \
134 BLOCK_INPUT; \
136 while (0)
137 #define UNBLOCK_INPUT_ALLOC \
138 do \
140 if (pthread_self () == main_thread) \
141 UNBLOCK_INPUT; \
142 pthread_mutex_unlock (&alloc_mutex); \
144 while (0)
146 #else /* SYSTEM_MALLOC || not HAVE_GTK_AND_PTHREAD */
148 #define BLOCK_INPUT_ALLOC BLOCK_INPUT
149 #define UNBLOCK_INPUT_ALLOC UNBLOCK_INPUT
151 #endif /* SYSTEM_MALLOC || not HAVE_GTK_AND_PTHREAD */
153 /* Value of _bytes_used, when spare_memory was freed. */
155 static __malloc_size_t bytes_used_when_full;
157 static __malloc_size_t bytes_used_when_reconsidered;
159 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
160 to a struct Lisp_String. */
162 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
163 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
164 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
166 #define VECTOR_MARK(V) ((V)->size |= ARRAY_MARK_FLAG)
167 #define VECTOR_UNMARK(V) ((V)->size &= ~ARRAY_MARK_FLAG)
168 #define VECTOR_MARKED_P(V) (((V)->size & ARRAY_MARK_FLAG) != 0)
170 /* Value is the number of bytes/chars of S, a pointer to a struct
171 Lisp_String. This must be used instead of STRING_BYTES (S) or
172 S->size during GC, because S->size contains the mark bit for
173 strings. */
175 #define GC_STRING_BYTES(S) (STRING_BYTES (S))
176 #define GC_STRING_CHARS(S) ((S)->size & ~ARRAY_MARK_FLAG)
178 /* Number of bytes of consing done since the last gc. */
180 int consing_since_gc;
182 /* Count the amount of consing of various sorts of space. */
184 EMACS_INT cons_cells_consed;
185 EMACS_INT floats_consed;
186 EMACS_INT vector_cells_consed;
187 EMACS_INT symbols_consed;
188 EMACS_INT string_chars_consed;
189 EMACS_INT misc_objects_consed;
190 EMACS_INT intervals_consed;
191 EMACS_INT strings_consed;
193 /* Minimum number of bytes of consing since GC before next GC. */
195 EMACS_INT gc_cons_threshold;
197 /* Similar minimum, computed from Vgc_cons_percentage. */
199 EMACS_INT gc_relative_threshold;
201 static Lisp_Object Vgc_cons_percentage;
203 /* Minimum number of bytes of consing since GC before next GC,
204 when memory is full. */
206 EMACS_INT memory_full_cons_threshold;
208 /* Nonzero during GC. */
210 int gc_in_progress;
212 /* Nonzero means abort if try to GC.
213 This is for code which is written on the assumption that
214 no GC will happen, so as to verify that assumption. */
216 int abort_on_gc;
218 /* Nonzero means display messages at beginning and end of GC. */
220 int garbage_collection_messages;
222 #ifndef VIRT_ADDR_VARIES
223 extern
224 #endif /* VIRT_ADDR_VARIES */
225 int malloc_sbrk_used;
227 #ifndef VIRT_ADDR_VARIES
228 extern
229 #endif /* VIRT_ADDR_VARIES */
230 int malloc_sbrk_unused;
232 /* Number of live and free conses etc. */
234 static int total_conses, total_markers, total_symbols, total_vector_size;
235 static int total_free_conses, total_free_markers, total_free_symbols;
236 static int total_free_floats, total_floats;
238 /* Points to memory space allocated as "spare", to be freed if we run
239 out of memory. We keep one large block, four cons-blocks, and
240 two string blocks. */
242 char *spare_memory[7];
244 /* Amount of spare memory to keep in large reserve block. */
246 #define SPARE_MEMORY (1 << 14)
248 /* Number of extra blocks malloc should get when it needs more core. */
250 static int malloc_hysteresis;
252 /* Non-nil means defun should do purecopy on the function definition. */
254 Lisp_Object Vpurify_flag;
256 /* Non-nil means we are handling a memory-full error. */
258 Lisp_Object Vmemory_full;
260 #ifndef HAVE_SHM
262 /* Initialize it to a nonzero value to force it into data space
263 (rather than bss space). That way unexec will remap it into text
264 space (pure), on some systems. We have not implemented the
265 remapping on more recent systems because this is less important
266 nowadays than in the days of small memories and timesharing. */
268 EMACS_INT pure[PURESIZE / sizeof (EMACS_INT)] = {1,};
269 #define PUREBEG (char *) pure
271 #else /* HAVE_SHM */
273 #define pure PURE_SEG_BITS /* Use shared memory segment */
274 #define PUREBEG (char *)PURE_SEG_BITS
276 #endif /* HAVE_SHM */
278 /* Pointer to the pure area, and its size. */
280 static char *purebeg;
281 static size_t pure_size;
283 /* Number of bytes of pure storage used before pure storage overflowed.
284 If this is non-zero, this implies that an overflow occurred. */
286 static size_t pure_bytes_used_before_overflow;
288 /* Value is non-zero if P points into pure space. */
290 #define PURE_POINTER_P(P) \
291 (((PNTR_COMPARISON_TYPE) (P) \
292 < (PNTR_COMPARISON_TYPE) ((char *) purebeg + pure_size)) \
293 && ((PNTR_COMPARISON_TYPE) (P) \
294 >= (PNTR_COMPARISON_TYPE) purebeg))
296 /* Total number of bytes allocated in pure storage. */
298 EMACS_INT pure_bytes_used;
300 /* Index in pure at which next pure Lisp object will be allocated.. */
302 static EMACS_INT pure_bytes_used_lisp;
304 /* Number of bytes allocated for non-Lisp objects in pure storage. */
306 static EMACS_INT pure_bytes_used_non_lisp;
308 /* If nonzero, this is a warning delivered by malloc and not yet
309 displayed. */
311 char *pending_malloc_warning;
313 /* Pre-computed signal argument for use when memory is exhausted. */
315 Lisp_Object Vmemory_signal_data;
317 /* Maximum amount of C stack to save when a GC happens. */
319 #ifndef MAX_SAVE_STACK
320 #define MAX_SAVE_STACK 16000
321 #endif
323 /* Buffer in which we save a copy of the C stack at each GC. */
325 char *stack_copy;
326 int stack_copy_size;
328 /* Non-zero means ignore malloc warnings. Set during initialization.
329 Currently not used. */
331 int ignore_warnings;
333 Lisp_Object Qgc_cons_threshold, Qchar_table_extra_slots;
335 /* Hook run after GC has finished. */
337 Lisp_Object Vpost_gc_hook, Qpost_gc_hook;
339 Lisp_Object Vgc_elapsed; /* accumulated elapsed time in GC */
340 EMACS_INT gcs_done; /* accumulated GCs */
342 static void mark_buffer P_ ((Lisp_Object));
343 extern void mark_kboards P_ ((void));
344 extern void mark_backtrace P_ ((void));
345 static void gc_sweep P_ ((void));
346 static void mark_glyph_matrix P_ ((struct glyph_matrix *));
347 static void mark_face_cache P_ ((struct face_cache *));
349 #ifdef HAVE_WINDOW_SYSTEM
350 extern void mark_fringe_data P_ ((void));
351 static void mark_image P_ ((struct image *));
352 static void mark_image_cache P_ ((struct frame *));
353 #endif /* HAVE_WINDOW_SYSTEM */
355 static struct Lisp_String *allocate_string P_ ((void));
356 static void compact_small_strings P_ ((void));
357 static void free_large_strings P_ ((void));
358 static void sweep_strings P_ ((void));
360 extern int message_enable_multibyte;
362 /* When scanning the C stack for live Lisp objects, Emacs keeps track
363 of what memory allocated via lisp_malloc is intended for what
364 purpose. This enumeration specifies the type of memory. */
366 enum mem_type
368 MEM_TYPE_NON_LISP,
369 MEM_TYPE_BUFFER,
370 MEM_TYPE_CONS,
371 MEM_TYPE_STRING,
372 MEM_TYPE_MISC,
373 MEM_TYPE_SYMBOL,
374 MEM_TYPE_FLOAT,
375 /* Keep the following vector-like types together, with
376 MEM_TYPE_WINDOW being the last, and MEM_TYPE_VECTOR the
377 first. Or change the code of live_vector_p, for instance. */
378 MEM_TYPE_VECTOR,
379 MEM_TYPE_PROCESS,
380 MEM_TYPE_HASH_TABLE,
381 MEM_TYPE_FRAME,
382 MEM_TYPE_WINDOW
385 static POINTER_TYPE *lisp_align_malloc P_ ((size_t, enum mem_type));
386 static POINTER_TYPE *lisp_malloc P_ ((size_t, enum mem_type));
387 void refill_memory_reserve ();
390 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
392 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
393 #include <stdio.h> /* For fprintf. */
394 #endif
396 /* A unique object in pure space used to make some Lisp objects
397 on free lists recognizable in O(1). */
399 Lisp_Object Vdead;
401 #ifdef GC_MALLOC_CHECK
403 enum mem_type allocated_mem_type;
404 int dont_register_blocks;
406 #endif /* GC_MALLOC_CHECK */
408 /* A node in the red-black tree describing allocated memory containing
409 Lisp data. Each such block is recorded with its start and end
410 address when it is allocated, and removed from the tree when it
411 is freed.
413 A red-black tree is a balanced binary tree with the following
414 properties:
416 1. Every node is either red or black.
417 2. Every leaf is black.
418 3. If a node is red, then both of its children are black.
419 4. Every simple path from a node to a descendant leaf contains
420 the same number of black nodes.
421 5. The root is always black.
423 When nodes are inserted into the tree, or deleted from the tree,
424 the tree is "fixed" so that these properties are always true.
426 A red-black tree with N internal nodes has height at most 2
427 log(N+1). Searches, insertions and deletions are done in O(log N).
428 Please see a text book about data structures for a detailed
429 description of red-black trees. Any book worth its salt should
430 describe them. */
432 struct mem_node
434 /* Children of this node. These pointers are never NULL. When there
435 is no child, the value is MEM_NIL, which points to a dummy node. */
436 struct mem_node *left, *right;
438 /* The parent of this node. In the root node, this is NULL. */
439 struct mem_node *parent;
441 /* Start and end of allocated region. */
442 void *start, *end;
444 /* Node color. */
445 enum {MEM_BLACK, MEM_RED} color;
447 /* Memory type. */
448 enum mem_type type;
451 /* Base address of stack. Set in main. */
453 Lisp_Object *stack_base;
455 /* Root of the tree describing allocated Lisp memory. */
457 static struct mem_node *mem_root;
459 /* Lowest and highest known address in the heap. */
461 static void *min_heap_address, *max_heap_address;
463 /* Sentinel node of the tree. */
465 static struct mem_node mem_z;
466 #define MEM_NIL &mem_z
468 static POINTER_TYPE *lisp_malloc P_ ((size_t, enum mem_type));
469 static struct Lisp_Vector *allocate_vectorlike P_ ((EMACS_INT, enum mem_type));
470 static void lisp_free P_ ((POINTER_TYPE *));
471 static void mark_stack P_ ((void));
472 static int live_vector_p P_ ((struct mem_node *, void *));
473 static int live_buffer_p P_ ((struct mem_node *, void *));
474 static int live_string_p P_ ((struct mem_node *, void *));
475 static int live_cons_p P_ ((struct mem_node *, void *));
476 static int live_symbol_p P_ ((struct mem_node *, void *));
477 static int live_float_p P_ ((struct mem_node *, void *));
478 static int live_misc_p P_ ((struct mem_node *, void *));
479 static void mark_maybe_object P_ ((Lisp_Object));
480 static void mark_memory P_ ((void *, void *));
481 static void mem_init P_ ((void));
482 static struct mem_node *mem_insert P_ ((void *, void *, enum mem_type));
483 static void mem_insert_fixup P_ ((struct mem_node *));
484 static void mem_rotate_left P_ ((struct mem_node *));
485 static void mem_rotate_right P_ ((struct mem_node *));
486 static void mem_delete P_ ((struct mem_node *));
487 static void mem_delete_fixup P_ ((struct mem_node *));
488 static INLINE struct mem_node *mem_find P_ ((void *));
491 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
492 static void check_gcpros P_ ((void));
493 #endif
495 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
497 /* Recording what needs to be marked for gc. */
499 struct gcpro *gcprolist;
501 /* Addresses of staticpro'd variables. Initialize it to a nonzero
502 value; otherwise some compilers put it into BSS. */
504 #define NSTATICS 1280
505 Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
507 /* Index of next unused slot in staticvec. */
509 int staticidx = 0;
511 static POINTER_TYPE *pure_alloc P_ ((size_t, int));
514 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
515 ALIGNMENT must be a power of 2. */
517 #define ALIGN(ptr, ALIGNMENT) \
518 ((POINTER_TYPE *) ((((EMACS_UINT)(ptr)) + (ALIGNMENT) - 1) \
519 & ~((ALIGNMENT) - 1)))
523 /************************************************************************
524 Malloc
525 ************************************************************************/
527 /* Function malloc calls this if it finds we are near exhausting storage. */
529 void
530 malloc_warning (str)
531 char *str;
533 pending_malloc_warning = str;
537 /* Display an already-pending malloc warning. */
539 void
540 display_malloc_warning ()
542 call3 (intern ("display-warning"),
543 intern ("alloc"),
544 build_string (pending_malloc_warning),
545 intern ("emergency"));
546 pending_malloc_warning = 0;
550 #ifdef DOUG_LEA_MALLOC
551 # define BYTES_USED (mallinfo ().uordblks)
552 #else
553 # define BYTES_USED _bytes_used
554 #endif
556 /* Called if we can't allocate relocatable space for a buffer. */
558 void
559 buffer_memory_full ()
561 /* If buffers use the relocating allocator, no need to free
562 spare_memory, because we may have plenty of malloc space left
563 that we could get, and if we don't, the malloc that fails will
564 itself cause spare_memory to be freed. If buffers don't use the
565 relocating allocator, treat this like any other failing
566 malloc. */
568 #ifndef REL_ALLOC
569 memory_full ();
570 #endif
572 /* This used to call error, but if we've run out of memory, we could
573 get infinite recursion trying to build the string. */
574 xsignal (Qnil, Vmemory_signal_data);
578 #ifdef XMALLOC_OVERRUN_CHECK
580 /* Check for overrun in malloc'ed buffers by wrapping a 16 byte header
581 and a 16 byte trailer around each block.
583 The header consists of 12 fixed bytes + a 4 byte integer contaning the
584 original block size, while the trailer consists of 16 fixed bytes.
586 The header is used to detect whether this block has been allocated
587 through these functions -- as it seems that some low-level libc
588 functions may bypass the malloc hooks.
592 #define XMALLOC_OVERRUN_CHECK_SIZE 16
594 static char xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE-4] =
595 { 0x9a, 0x9b, 0xae, 0xaf,
596 0xbf, 0xbe, 0xce, 0xcf,
597 0xea, 0xeb, 0xec, 0xed };
599 static char xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
600 { 0xaa, 0xab, 0xac, 0xad,
601 0xba, 0xbb, 0xbc, 0xbd,
602 0xca, 0xcb, 0xcc, 0xcd,
603 0xda, 0xdb, 0xdc, 0xdd };
605 /* Macros to insert and extract the block size in the header. */
607 #define XMALLOC_PUT_SIZE(ptr, size) \
608 (ptr[-1] = (size & 0xff), \
609 ptr[-2] = ((size >> 8) & 0xff), \
610 ptr[-3] = ((size >> 16) & 0xff), \
611 ptr[-4] = ((size >> 24) & 0xff))
613 #define XMALLOC_GET_SIZE(ptr) \
614 (size_t)((unsigned)(ptr[-1]) | \
615 ((unsigned)(ptr[-2]) << 8) | \
616 ((unsigned)(ptr[-3]) << 16) | \
617 ((unsigned)(ptr[-4]) << 24))
620 /* The call depth in overrun_check functions. For example, this might happen:
621 xmalloc()
622 overrun_check_malloc()
623 -> malloc -> (via hook)_-> emacs_blocked_malloc
624 -> overrun_check_malloc
625 call malloc (hooks are NULL, so real malloc is called).
626 malloc returns 10000.
627 add overhead, return 10016.
628 <- (back in overrun_check_malloc)
629 add overhead again, return 10032
630 xmalloc returns 10032.
632 (time passes).
634 xfree(10032)
635 overrun_check_free(10032)
636 decrease overhed
637 free(10016) <- crash, because 10000 is the original pointer. */
639 static int check_depth;
641 /* Like malloc, but wraps allocated block with header and trailer. */
643 POINTER_TYPE *
644 overrun_check_malloc (size)
645 size_t size;
647 register unsigned char *val;
648 size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
650 val = (unsigned char *) malloc (size + overhead);
651 if (val && check_depth == 1)
653 bcopy (xmalloc_overrun_check_header, val, XMALLOC_OVERRUN_CHECK_SIZE - 4);
654 val += XMALLOC_OVERRUN_CHECK_SIZE;
655 XMALLOC_PUT_SIZE(val, size);
656 bcopy (xmalloc_overrun_check_trailer, val + size, XMALLOC_OVERRUN_CHECK_SIZE);
658 --check_depth;
659 return (POINTER_TYPE *)val;
663 /* Like realloc, but checks old block for overrun, and wraps new block
664 with header and trailer. */
666 POINTER_TYPE *
667 overrun_check_realloc (block, size)
668 POINTER_TYPE *block;
669 size_t size;
671 register unsigned char *val = (unsigned char *)block;
672 size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
674 if (val
675 && check_depth == 1
676 && bcmp (xmalloc_overrun_check_header,
677 val - XMALLOC_OVERRUN_CHECK_SIZE,
678 XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
680 size_t osize = XMALLOC_GET_SIZE (val);
681 if (bcmp (xmalloc_overrun_check_trailer,
682 val + osize,
683 XMALLOC_OVERRUN_CHECK_SIZE))
684 abort ();
685 bzero (val + osize, XMALLOC_OVERRUN_CHECK_SIZE);
686 val -= XMALLOC_OVERRUN_CHECK_SIZE;
687 bzero (val, XMALLOC_OVERRUN_CHECK_SIZE);
690 val = (unsigned char *) realloc ((POINTER_TYPE *)val, size + overhead);
692 if (val && check_depth == 1)
694 bcopy (xmalloc_overrun_check_header, val, XMALLOC_OVERRUN_CHECK_SIZE - 4);
695 val += XMALLOC_OVERRUN_CHECK_SIZE;
696 XMALLOC_PUT_SIZE(val, size);
697 bcopy (xmalloc_overrun_check_trailer, val + size, XMALLOC_OVERRUN_CHECK_SIZE);
699 --check_depth;
700 return (POINTER_TYPE *)val;
703 /* Like free, but checks block for overrun. */
705 void
706 overrun_check_free (block)
707 POINTER_TYPE *block;
709 unsigned char *val = (unsigned char *)block;
711 ++check_depth;
712 if (val
713 && check_depth == 1
714 && bcmp (xmalloc_overrun_check_header,
715 val - XMALLOC_OVERRUN_CHECK_SIZE,
716 XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
718 size_t osize = XMALLOC_GET_SIZE (val);
719 if (bcmp (xmalloc_overrun_check_trailer,
720 val + osize,
721 XMALLOC_OVERRUN_CHECK_SIZE))
722 abort ();
723 #ifdef XMALLOC_CLEAR_FREE_MEMORY
724 val -= XMALLOC_OVERRUN_CHECK_SIZE;
725 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_SIZE*2);
726 #else
727 bzero (val + osize, XMALLOC_OVERRUN_CHECK_SIZE);
728 val -= XMALLOC_OVERRUN_CHECK_SIZE;
729 bzero (val, XMALLOC_OVERRUN_CHECK_SIZE);
730 #endif
733 free (val);
734 --check_depth;
737 #undef malloc
738 #undef realloc
739 #undef free
740 #define malloc overrun_check_malloc
741 #define realloc overrun_check_realloc
742 #define free overrun_check_free
743 #endif
746 /* Like malloc but check for no memory and block interrupt input.. */
748 POINTER_TYPE *
749 xmalloc (size)
750 size_t size;
752 register POINTER_TYPE *val;
754 BLOCK_INPUT;
755 val = (POINTER_TYPE *) malloc (size);
756 UNBLOCK_INPUT;
758 if (!val && size)
759 memory_full ();
760 return val;
764 /* Like realloc but check for no memory and block interrupt input.. */
766 POINTER_TYPE *
767 xrealloc (block, size)
768 POINTER_TYPE *block;
769 size_t size;
771 register POINTER_TYPE *val;
773 BLOCK_INPUT;
774 /* We must call malloc explicitly when BLOCK is 0, since some
775 reallocs don't do this. */
776 if (! block)
777 val = (POINTER_TYPE *) malloc (size);
778 else
779 val = (POINTER_TYPE *) realloc (block, size);
780 UNBLOCK_INPUT;
782 if (!val && size) memory_full ();
783 return val;
787 /* Like free but block interrupt input. */
789 void
790 xfree (block)
791 POINTER_TYPE *block;
793 BLOCK_INPUT;
794 free (block);
795 UNBLOCK_INPUT;
796 /* We don't call refill_memory_reserve here
797 because that duplicates doing so in emacs_blocked_free
798 and the criterion should go there. */
802 /* Like strdup, but uses xmalloc. */
804 char *
805 xstrdup (s)
806 const char *s;
808 size_t len = strlen (s) + 1;
809 char *p = (char *) xmalloc (len);
810 bcopy (s, p, len);
811 return p;
815 /* Unwind for SAFE_ALLOCA */
817 Lisp_Object
818 safe_alloca_unwind (arg)
819 Lisp_Object arg;
821 register struct Lisp_Save_Value *p = XSAVE_VALUE (arg);
823 p->dogc = 0;
824 xfree (p->pointer);
825 p->pointer = 0;
826 free_misc (arg);
827 return Qnil;
831 /* Like malloc but used for allocating Lisp data. NBYTES is the
832 number of bytes to allocate, TYPE describes the intended use of the
833 allcated memory block (for strings, for conses, ...). */
835 #ifndef USE_LSB_TAG
836 static void *lisp_malloc_loser;
837 #endif
839 static POINTER_TYPE *
840 lisp_malloc (nbytes, type)
841 size_t nbytes;
842 enum mem_type type;
844 register void *val;
846 BLOCK_INPUT;
848 #ifdef GC_MALLOC_CHECK
849 allocated_mem_type = type;
850 #endif
852 val = (void *) malloc (nbytes);
854 #ifndef USE_LSB_TAG
855 /* If the memory just allocated cannot be addressed thru a Lisp
856 object's pointer, and it needs to be,
857 that's equivalent to running out of memory. */
858 if (val && type != MEM_TYPE_NON_LISP)
860 Lisp_Object tem;
861 XSETCONS (tem, (char *) val + nbytes - 1);
862 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
864 lisp_malloc_loser = val;
865 free (val);
866 val = 0;
869 #endif
871 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
872 if (val && type != MEM_TYPE_NON_LISP)
873 mem_insert (val, (char *) val + nbytes, type);
874 #endif
876 UNBLOCK_INPUT;
877 if (!val && nbytes)
878 memory_full ();
879 return val;
882 /* Free BLOCK. This must be called to free memory allocated with a
883 call to lisp_malloc. */
885 static void
886 lisp_free (block)
887 POINTER_TYPE *block;
889 BLOCK_INPUT;
890 free (block);
891 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
892 mem_delete (mem_find (block));
893 #endif
894 UNBLOCK_INPUT;
897 /* Allocation of aligned blocks of memory to store Lisp data. */
898 /* The entry point is lisp_align_malloc which returns blocks of at most */
899 /* BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
901 /* Use posix_memalloc if the system has it and we're using the system's
902 malloc (because our gmalloc.c routines don't have posix_memalign although
903 its memalloc could be used). */
904 #if defined (HAVE_POSIX_MEMALIGN) && defined (SYSTEM_MALLOC)
905 #define USE_POSIX_MEMALIGN 1
906 #endif
908 /* BLOCK_ALIGN has to be a power of 2. */
909 #define BLOCK_ALIGN (1 << 10)
911 /* Padding to leave at the end of a malloc'd block. This is to give
912 malloc a chance to minimize the amount of memory wasted to alignment.
913 It should be tuned to the particular malloc library used.
914 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
915 posix_memalign on the other hand would ideally prefer a value of 4
916 because otherwise, there's 1020 bytes wasted between each ablocks.
917 In Emacs, testing shows that those 1020 can most of the time be
918 efficiently used by malloc to place other objects, so a value of 0 can
919 still preferable unless you have a lot of aligned blocks and virtually
920 nothing else. */
921 #define BLOCK_PADDING 0
922 #define BLOCK_BYTES \
923 (BLOCK_ALIGN - sizeof (struct ablock *) - BLOCK_PADDING)
925 /* Internal data structures and constants. */
927 #define ABLOCKS_SIZE 16
929 /* An aligned block of memory. */
930 struct ablock
932 union
934 char payload[BLOCK_BYTES];
935 struct ablock *next_free;
936 } x;
937 /* `abase' is the aligned base of the ablocks. */
938 /* It is overloaded to hold the virtual `busy' field that counts
939 the number of used ablock in the parent ablocks.
940 The first ablock has the `busy' field, the others have the `abase'
941 field. To tell the difference, we assume that pointers will have
942 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
943 is used to tell whether the real base of the parent ablocks is `abase'
944 (if not, the word before the first ablock holds a pointer to the
945 real base). */
946 struct ablocks *abase;
947 /* The padding of all but the last ablock is unused. The padding of
948 the last ablock in an ablocks is not allocated. */
949 #if BLOCK_PADDING
950 char padding[BLOCK_PADDING];
951 #endif
954 /* A bunch of consecutive aligned blocks. */
955 struct ablocks
957 struct ablock blocks[ABLOCKS_SIZE];
960 /* Size of the block requested from malloc or memalign. */
961 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
963 #define ABLOCK_ABASE(block) \
964 (((unsigned long) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
965 ? (struct ablocks *)(block) \
966 : (block)->abase)
968 /* Virtual `busy' field. */
969 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
971 /* Pointer to the (not necessarily aligned) malloc block. */
972 #ifdef USE_POSIX_MEMALIGN
973 #define ABLOCKS_BASE(abase) (abase)
974 #else
975 #define ABLOCKS_BASE(abase) \
976 (1 & (long) ABLOCKS_BUSY (abase) ? abase : ((void**)abase)[-1])
977 #endif
979 /* The list of free ablock. */
980 static struct ablock *free_ablock;
982 /* Allocate an aligned block of nbytes.
983 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
984 smaller or equal to BLOCK_BYTES. */
985 static POINTER_TYPE *
986 lisp_align_malloc (nbytes, type)
987 size_t nbytes;
988 enum mem_type type;
990 void *base, *val;
991 struct ablocks *abase;
993 eassert (nbytes <= BLOCK_BYTES);
995 BLOCK_INPUT;
997 #ifdef GC_MALLOC_CHECK
998 allocated_mem_type = type;
999 #endif
1001 if (!free_ablock)
1003 int i;
1004 EMACS_INT aligned; /* int gets warning casting to 64-bit pointer. */
1006 #ifdef DOUG_LEA_MALLOC
1007 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1008 because mapped region contents are not preserved in
1009 a dumped Emacs. */
1010 mallopt (M_MMAP_MAX, 0);
1011 #endif
1013 #ifdef USE_POSIX_MEMALIGN
1015 int err = posix_memalign (&base, BLOCK_ALIGN, ABLOCKS_BYTES);
1016 if (err)
1017 base = NULL;
1018 abase = base;
1020 #else
1021 base = malloc (ABLOCKS_BYTES);
1022 abase = ALIGN (base, BLOCK_ALIGN);
1023 #endif
1025 if (base == 0)
1027 UNBLOCK_INPUT;
1028 memory_full ();
1031 aligned = (base == abase);
1032 if (!aligned)
1033 ((void**)abase)[-1] = base;
1035 #ifdef DOUG_LEA_MALLOC
1036 /* Back to a reasonable maximum of mmap'ed areas. */
1037 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1038 #endif
1040 #ifndef USE_LSB_TAG
1041 /* If the memory just allocated cannot be addressed thru a Lisp
1042 object's pointer, and it needs to be, that's equivalent to
1043 running out of memory. */
1044 if (type != MEM_TYPE_NON_LISP)
1046 Lisp_Object tem;
1047 char *end = (char *) base + ABLOCKS_BYTES - 1;
1048 XSETCONS (tem, end);
1049 if ((char *) XCONS (tem) != end)
1051 lisp_malloc_loser = base;
1052 free (base);
1053 UNBLOCK_INPUT;
1054 memory_full ();
1057 #endif
1059 /* Initialize the blocks and put them on the free list.
1060 Is `base' was not properly aligned, we can't use the last block. */
1061 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1063 abase->blocks[i].abase = abase;
1064 abase->blocks[i].x.next_free = free_ablock;
1065 free_ablock = &abase->blocks[i];
1067 ABLOCKS_BUSY (abase) = (struct ablocks *) (long) aligned;
1069 eassert (0 == ((EMACS_UINT)abase) % BLOCK_ALIGN);
1070 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1071 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1072 eassert (ABLOCKS_BASE (abase) == base);
1073 eassert (aligned == (long) ABLOCKS_BUSY (abase));
1076 abase = ABLOCK_ABASE (free_ablock);
1077 ABLOCKS_BUSY (abase) = (struct ablocks *) (2 + (long) ABLOCKS_BUSY (abase));
1078 val = free_ablock;
1079 free_ablock = free_ablock->x.next_free;
1081 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1082 if (val && type != MEM_TYPE_NON_LISP)
1083 mem_insert (val, (char *) val + nbytes, type);
1084 #endif
1086 UNBLOCK_INPUT;
1087 if (!val && nbytes)
1088 memory_full ();
1090 eassert (0 == ((EMACS_UINT)val) % BLOCK_ALIGN);
1091 return val;
1094 static void
1095 lisp_align_free (block)
1096 POINTER_TYPE *block;
1098 struct ablock *ablock = block;
1099 struct ablocks *abase = ABLOCK_ABASE (ablock);
1101 BLOCK_INPUT;
1102 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1103 mem_delete (mem_find (block));
1104 #endif
1105 /* Put on free list. */
1106 ablock->x.next_free = free_ablock;
1107 free_ablock = ablock;
1108 /* Update busy count. */
1109 ABLOCKS_BUSY (abase) = (struct ablocks *) (-2 + (long) ABLOCKS_BUSY (abase));
1111 if (2 > (long) ABLOCKS_BUSY (abase))
1112 { /* All the blocks are free. */
1113 int i = 0, aligned = (long) ABLOCKS_BUSY (abase);
1114 struct ablock **tem = &free_ablock;
1115 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1117 while (*tem)
1119 if (*tem >= (struct ablock *) abase && *tem < atop)
1121 i++;
1122 *tem = (*tem)->x.next_free;
1124 else
1125 tem = &(*tem)->x.next_free;
1127 eassert ((aligned & 1) == aligned);
1128 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1129 #ifdef USE_POSIX_MEMALIGN
1130 eassert ((unsigned long)ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1131 #endif
1132 free (ABLOCKS_BASE (abase));
1134 UNBLOCK_INPUT;
1137 /* Return a new buffer structure allocated from the heap with
1138 a call to lisp_malloc. */
1140 struct buffer *
1141 allocate_buffer ()
1143 struct buffer *b
1144 = (struct buffer *) lisp_malloc (sizeof (struct buffer),
1145 MEM_TYPE_BUFFER);
1146 return b;
1150 #ifndef SYSTEM_MALLOC
1152 /* Arranging to disable input signals while we're in malloc.
1154 This only works with GNU malloc. To help out systems which can't
1155 use GNU malloc, all the calls to malloc, realloc, and free
1156 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
1157 pair; unfortunately, we have no idea what C library functions
1158 might call malloc, so we can't really protect them unless you're
1159 using GNU malloc. Fortunately, most of the major operating systems
1160 can use GNU malloc. */
1162 #ifndef SYNC_INPUT
1164 #ifndef DOUG_LEA_MALLOC
1165 extern void * (*__malloc_hook) P_ ((size_t, const void *));
1166 extern void * (*__realloc_hook) P_ ((void *, size_t, const void *));
1167 extern void (*__free_hook) P_ ((void *, const void *));
1168 /* Else declared in malloc.h, perhaps with an extra arg. */
1169 #endif /* DOUG_LEA_MALLOC */
1170 static void * (*old_malloc_hook) P_ ((size_t, const void *));
1171 static void * (*old_realloc_hook) P_ ((void *, size_t, const void*));
1172 static void (*old_free_hook) P_ ((void*, const void*));
1174 /* This function is used as the hook for free to call. */
1176 static void
1177 emacs_blocked_free (ptr, ptr2)
1178 void *ptr;
1179 const void *ptr2;
1181 EMACS_INT bytes_used_now;
1183 BLOCK_INPUT_ALLOC;
1185 #ifdef GC_MALLOC_CHECK
1186 if (ptr)
1188 struct mem_node *m;
1190 m = mem_find (ptr);
1191 if (m == MEM_NIL || m->start != ptr)
1193 fprintf (stderr,
1194 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
1195 abort ();
1197 else
1199 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
1200 mem_delete (m);
1203 #endif /* GC_MALLOC_CHECK */
1205 __free_hook = old_free_hook;
1206 free (ptr);
1208 /* If we released our reserve (due to running out of memory),
1209 and we have a fair amount free once again,
1210 try to set aside another reserve in case we run out once more. */
1211 if (! NILP (Vmemory_full)
1212 /* Verify there is enough space that even with the malloc
1213 hysteresis this call won't run out again.
1214 The code here is correct as long as SPARE_MEMORY
1215 is substantially larger than the block size malloc uses. */
1216 && (bytes_used_when_full
1217 > ((bytes_used_when_reconsidered = BYTES_USED)
1218 + max (malloc_hysteresis, 4) * SPARE_MEMORY)))
1219 refill_memory_reserve ();
1221 __free_hook = emacs_blocked_free;
1222 UNBLOCK_INPUT_ALLOC;
1226 /* This function is the malloc hook that Emacs uses. */
1228 static void *
1229 emacs_blocked_malloc (size, ptr)
1230 size_t size;
1231 const void *ptr;
1233 void *value;
1235 BLOCK_INPUT_ALLOC;
1236 __malloc_hook = old_malloc_hook;
1237 #ifdef DOUG_LEA_MALLOC
1238 mallopt (M_TOP_PAD, malloc_hysteresis * 4096);
1239 #else
1240 __malloc_extra_blocks = malloc_hysteresis;
1241 #endif
1243 value = (void *) malloc (size);
1245 #ifdef GC_MALLOC_CHECK
1247 struct mem_node *m = mem_find (value);
1248 if (m != MEM_NIL)
1250 fprintf (stderr, "Malloc returned %p which is already in use\n",
1251 value);
1252 fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
1253 m->start, m->end, (char *) m->end - (char *) m->start,
1254 m->type);
1255 abort ();
1258 if (!dont_register_blocks)
1260 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
1261 allocated_mem_type = MEM_TYPE_NON_LISP;
1264 #endif /* GC_MALLOC_CHECK */
1266 __malloc_hook = emacs_blocked_malloc;
1267 UNBLOCK_INPUT_ALLOC;
1269 /* fprintf (stderr, "%p malloc\n", value); */
1270 return value;
1274 /* This function is the realloc hook that Emacs uses. */
1276 static void *
1277 emacs_blocked_realloc (ptr, size, ptr2)
1278 void *ptr;
1279 size_t size;
1280 const void *ptr2;
1282 void *value;
1284 BLOCK_INPUT_ALLOC;
1285 __realloc_hook = old_realloc_hook;
1287 #ifdef GC_MALLOC_CHECK
1288 if (ptr)
1290 struct mem_node *m = mem_find (ptr);
1291 if (m == MEM_NIL || m->start != ptr)
1293 fprintf (stderr,
1294 "Realloc of %p which wasn't allocated with malloc\n",
1295 ptr);
1296 abort ();
1299 mem_delete (m);
1302 /* fprintf (stderr, "%p -> realloc\n", ptr); */
1304 /* Prevent malloc from registering blocks. */
1305 dont_register_blocks = 1;
1306 #endif /* GC_MALLOC_CHECK */
1308 value = (void *) realloc (ptr, size);
1310 #ifdef GC_MALLOC_CHECK
1311 dont_register_blocks = 0;
1314 struct mem_node *m = mem_find (value);
1315 if (m != MEM_NIL)
1317 fprintf (stderr, "Realloc returns memory that is already in use\n");
1318 abort ();
1321 /* Can't handle zero size regions in the red-black tree. */
1322 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
1325 /* fprintf (stderr, "%p <- realloc\n", value); */
1326 #endif /* GC_MALLOC_CHECK */
1328 __realloc_hook = emacs_blocked_realloc;
1329 UNBLOCK_INPUT_ALLOC;
1331 return value;
1335 #ifdef HAVE_GTK_AND_PTHREAD
1336 /* Called from Fdump_emacs so that when the dumped Emacs starts, it has a
1337 normal malloc. Some thread implementations need this as they call
1338 malloc before main. The pthread_self call in BLOCK_INPUT_ALLOC then
1339 calls malloc because it is the first call, and we have an endless loop. */
1341 void
1342 reset_malloc_hooks ()
1344 __free_hook = 0;
1345 __malloc_hook = 0;
1346 __realloc_hook = 0;
1348 #endif /* HAVE_GTK_AND_PTHREAD */
1351 /* Called from main to set up malloc to use our hooks. */
1353 void
1354 uninterrupt_malloc ()
1356 #ifdef HAVE_GTK_AND_PTHREAD
1357 pthread_mutexattr_t attr;
1359 /* GLIBC has a faster way to do this, but lets keep it portable.
1360 This is according to the Single UNIX Specification. */
1361 pthread_mutexattr_init (&attr);
1362 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1363 pthread_mutex_init (&alloc_mutex, &attr);
1364 #endif /* HAVE_GTK_AND_PTHREAD */
1366 if (__free_hook != emacs_blocked_free)
1367 old_free_hook = __free_hook;
1368 __free_hook = emacs_blocked_free;
1370 if (__malloc_hook != emacs_blocked_malloc)
1371 old_malloc_hook = __malloc_hook;
1372 __malloc_hook = emacs_blocked_malloc;
1374 if (__realloc_hook != emacs_blocked_realloc)
1375 old_realloc_hook = __realloc_hook;
1376 __realloc_hook = emacs_blocked_realloc;
1379 #endif /* not SYNC_INPUT */
1380 #endif /* not SYSTEM_MALLOC */
1384 /***********************************************************************
1385 Interval Allocation
1386 ***********************************************************************/
1388 /* Number of intervals allocated in an interval_block structure.
1389 The 1020 is 1024 minus malloc overhead. */
1391 #define INTERVAL_BLOCK_SIZE \
1392 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1394 /* Intervals are allocated in chunks in form of an interval_block
1395 structure. */
1397 struct interval_block
1399 /* Place `intervals' first, to preserve alignment. */
1400 struct interval intervals[INTERVAL_BLOCK_SIZE];
1401 struct interval_block *next;
1404 /* Current interval block. Its `next' pointer points to older
1405 blocks. */
1407 struct interval_block *interval_block;
1409 /* Index in interval_block above of the next unused interval
1410 structure. */
1412 static int interval_block_index;
1414 /* Number of free and live intervals. */
1416 static int total_free_intervals, total_intervals;
1418 /* List of free intervals. */
1420 INTERVAL interval_free_list;
1422 /* Total number of interval blocks now in use. */
1424 int n_interval_blocks;
1427 /* Initialize interval allocation. */
1429 static void
1430 init_intervals ()
1432 interval_block = NULL;
1433 interval_block_index = INTERVAL_BLOCK_SIZE;
1434 interval_free_list = 0;
1435 n_interval_blocks = 0;
1439 /* Return a new interval. */
1441 INTERVAL
1442 make_interval ()
1444 INTERVAL val;
1446 /* eassert (!handling_signal); */
1448 #ifndef SYNC_INPUT
1449 BLOCK_INPUT;
1450 #endif
1452 if (interval_free_list)
1454 val = interval_free_list;
1455 interval_free_list = INTERVAL_PARENT (interval_free_list);
1457 else
1459 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1461 register struct interval_block *newi;
1463 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
1464 MEM_TYPE_NON_LISP);
1466 newi->next = interval_block;
1467 interval_block = newi;
1468 interval_block_index = 0;
1469 n_interval_blocks++;
1471 val = &interval_block->intervals[interval_block_index++];
1474 #ifndef SYNC_INPUT
1475 UNBLOCK_INPUT;
1476 #endif
1478 consing_since_gc += sizeof (struct interval);
1479 intervals_consed++;
1480 RESET_INTERVAL (val);
1481 val->gcmarkbit = 0;
1482 return val;
1486 /* Mark Lisp objects in interval I. */
1488 static void
1489 mark_interval (i, dummy)
1490 register INTERVAL i;
1491 Lisp_Object dummy;
1493 eassert (!i->gcmarkbit); /* Intervals are never shared. */
1494 i->gcmarkbit = 1;
1495 mark_object (i->plist);
1499 /* Mark the interval tree rooted in TREE. Don't call this directly;
1500 use the macro MARK_INTERVAL_TREE instead. */
1502 static void
1503 mark_interval_tree (tree)
1504 register INTERVAL tree;
1506 /* No need to test if this tree has been marked already; this
1507 function is always called through the MARK_INTERVAL_TREE macro,
1508 which takes care of that. */
1510 traverse_intervals_noorder (tree, mark_interval, Qnil);
1514 /* Mark the interval tree rooted in I. */
1516 #define MARK_INTERVAL_TREE(i) \
1517 do { \
1518 if (!NULL_INTERVAL_P (i) && !i->gcmarkbit) \
1519 mark_interval_tree (i); \
1520 } while (0)
1523 #define UNMARK_BALANCE_INTERVALS(i) \
1524 do { \
1525 if (! NULL_INTERVAL_P (i)) \
1526 (i) = balance_intervals (i); \
1527 } while (0)
1530 /* Number support. If NO_UNION_TYPE isn't in effect, we
1531 can't create number objects in macros. */
1532 #ifndef make_number
1533 Lisp_Object
1534 make_number (n)
1535 EMACS_INT n;
1537 Lisp_Object obj;
1538 obj.s.val = n;
1539 obj.s.type = Lisp_Int;
1540 return obj;
1542 #endif
1544 /***********************************************************************
1545 String Allocation
1546 ***********************************************************************/
1548 /* Lisp_Strings are allocated in string_block structures. When a new
1549 string_block is allocated, all the Lisp_Strings it contains are
1550 added to a free-list string_free_list. When a new Lisp_String is
1551 needed, it is taken from that list. During the sweep phase of GC,
1552 string_blocks that are entirely free are freed, except two which
1553 we keep.
1555 String data is allocated from sblock structures. Strings larger
1556 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1557 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1559 Sblocks consist internally of sdata structures, one for each
1560 Lisp_String. The sdata structure points to the Lisp_String it
1561 belongs to. The Lisp_String points back to the `u.data' member of
1562 its sdata structure.
1564 When a Lisp_String is freed during GC, it is put back on
1565 string_free_list, and its `data' member and its sdata's `string'
1566 pointer is set to null. The size of the string is recorded in the
1567 `u.nbytes' member of the sdata. So, sdata structures that are no
1568 longer used, can be easily recognized, and it's easy to compact the
1569 sblocks of small strings which we do in compact_small_strings. */
1571 /* Size in bytes of an sblock structure used for small strings. This
1572 is 8192 minus malloc overhead. */
1574 #define SBLOCK_SIZE 8188
1576 /* Strings larger than this are considered large strings. String data
1577 for large strings is allocated from individual sblocks. */
1579 #define LARGE_STRING_BYTES 1024
1581 /* Structure describing string memory sub-allocated from an sblock.
1582 This is where the contents of Lisp strings are stored. */
1584 struct sdata
1586 /* Back-pointer to the string this sdata belongs to. If null, this
1587 structure is free, and the NBYTES member of the union below
1588 contains the string's byte size (the same value that STRING_BYTES
1589 would return if STRING were non-null). If non-null, STRING_BYTES
1590 (STRING) is the size of the data, and DATA contains the string's
1591 contents. */
1592 struct Lisp_String *string;
1594 #ifdef GC_CHECK_STRING_BYTES
1596 EMACS_INT nbytes;
1597 unsigned char data[1];
1599 #define SDATA_NBYTES(S) (S)->nbytes
1600 #define SDATA_DATA(S) (S)->data
1602 #else /* not GC_CHECK_STRING_BYTES */
1604 union
1606 /* When STRING in non-null. */
1607 unsigned char data[1];
1609 /* When STRING is null. */
1610 EMACS_INT nbytes;
1611 } u;
1614 #define SDATA_NBYTES(S) (S)->u.nbytes
1615 #define SDATA_DATA(S) (S)->u.data
1617 #endif /* not GC_CHECK_STRING_BYTES */
1621 /* Structure describing a block of memory which is sub-allocated to
1622 obtain string data memory for strings. Blocks for small strings
1623 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1624 as large as needed. */
1626 struct sblock
1628 /* Next in list. */
1629 struct sblock *next;
1631 /* Pointer to the next free sdata block. This points past the end
1632 of the sblock if there isn't any space left in this block. */
1633 struct sdata *next_free;
1635 /* Start of data. */
1636 struct sdata first_data;
1639 /* Number of Lisp strings in a string_block structure. The 1020 is
1640 1024 minus malloc overhead. */
1642 #define STRING_BLOCK_SIZE \
1643 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1645 /* Structure describing a block from which Lisp_String structures
1646 are allocated. */
1648 struct string_block
1650 /* Place `strings' first, to preserve alignment. */
1651 struct Lisp_String strings[STRING_BLOCK_SIZE];
1652 struct string_block *next;
1655 /* Head and tail of the list of sblock structures holding Lisp string
1656 data. We always allocate from current_sblock. The NEXT pointers
1657 in the sblock structures go from oldest_sblock to current_sblock. */
1659 static struct sblock *oldest_sblock, *current_sblock;
1661 /* List of sblocks for large strings. */
1663 static struct sblock *large_sblocks;
1665 /* List of string_block structures, and how many there are. */
1667 static struct string_block *string_blocks;
1668 static int n_string_blocks;
1670 /* Free-list of Lisp_Strings. */
1672 static struct Lisp_String *string_free_list;
1674 /* Number of live and free Lisp_Strings. */
1676 static int total_strings, total_free_strings;
1678 /* Number of bytes used by live strings. */
1680 static int total_string_size;
1682 /* Given a pointer to a Lisp_String S which is on the free-list
1683 string_free_list, return a pointer to its successor in the
1684 free-list. */
1686 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1688 /* Return a pointer to the sdata structure belonging to Lisp string S.
1689 S must be live, i.e. S->data must not be null. S->data is actually
1690 a pointer to the `u.data' member of its sdata structure; the
1691 structure starts at a constant offset in front of that. */
1693 #ifdef GC_CHECK_STRING_BYTES
1695 #define SDATA_OF_STRING(S) \
1696 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *) \
1697 - sizeof (EMACS_INT)))
1699 #else /* not GC_CHECK_STRING_BYTES */
1701 #define SDATA_OF_STRING(S) \
1702 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))
1704 #endif /* not GC_CHECK_STRING_BYTES */
1707 #ifdef GC_CHECK_STRING_OVERRUN
1709 /* We check for overrun in string data blocks by appending a small
1710 "cookie" after each allocated string data block, and check for the
1711 presence of this cookie during GC. */
1713 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1714 static char string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1715 { 0xde, 0xad, 0xbe, 0xef };
1717 #else
1718 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1719 #endif
1721 /* Value is the size of an sdata structure large enough to hold NBYTES
1722 bytes of string data. The value returned includes a terminating
1723 NUL byte, the size of the sdata structure, and padding. */
1725 #ifdef GC_CHECK_STRING_BYTES
1727 #define SDATA_SIZE(NBYTES) \
1728 ((sizeof (struct Lisp_String *) \
1729 + (NBYTES) + 1 \
1730 + sizeof (EMACS_INT) \
1731 + sizeof (EMACS_INT) - 1) \
1732 & ~(sizeof (EMACS_INT) - 1))
1734 #else /* not GC_CHECK_STRING_BYTES */
1736 #define SDATA_SIZE(NBYTES) \
1737 ((sizeof (struct Lisp_String *) \
1738 + (NBYTES) + 1 \
1739 + sizeof (EMACS_INT) - 1) \
1740 & ~(sizeof (EMACS_INT) - 1))
1742 #endif /* not GC_CHECK_STRING_BYTES */
1744 /* Extra bytes to allocate for each string. */
1746 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1748 /* Initialize string allocation. Called from init_alloc_once. */
1750 void
1751 init_strings ()
1753 total_strings = total_free_strings = total_string_size = 0;
1754 oldest_sblock = current_sblock = large_sblocks = NULL;
1755 string_blocks = NULL;
1756 n_string_blocks = 0;
1757 string_free_list = NULL;
1761 #ifdef GC_CHECK_STRING_BYTES
1763 static int check_string_bytes_count;
1765 void check_string_bytes P_ ((int));
1766 void check_sblock P_ ((struct sblock *));
1768 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1771 /* Like GC_STRING_BYTES, but with debugging check. */
1774 string_bytes (s)
1775 struct Lisp_String *s;
1777 int nbytes = (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1778 if (!PURE_POINTER_P (s)
1779 && s->data
1780 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1781 abort ();
1782 return nbytes;
1785 /* Check validity of Lisp strings' string_bytes member in B. */
1787 void
1788 check_sblock (b)
1789 struct sblock *b;
1791 struct sdata *from, *end, *from_end;
1793 end = b->next_free;
1795 for (from = &b->first_data; from < end; from = from_end)
1797 /* Compute the next FROM here because copying below may
1798 overwrite data we need to compute it. */
1799 int nbytes;
1801 /* Check that the string size recorded in the string is the
1802 same as the one recorded in the sdata structure. */
1803 if (from->string)
1804 CHECK_STRING_BYTES (from->string);
1806 if (from->string)
1807 nbytes = GC_STRING_BYTES (from->string);
1808 else
1809 nbytes = SDATA_NBYTES (from);
1811 nbytes = SDATA_SIZE (nbytes);
1812 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1817 /* Check validity of Lisp strings' string_bytes member. ALL_P
1818 non-zero means check all strings, otherwise check only most
1819 recently allocated strings. Used for hunting a bug. */
1821 void
1822 check_string_bytes (all_p)
1823 int all_p;
1825 if (all_p)
1827 struct sblock *b;
1829 for (b = large_sblocks; b; b = b->next)
1831 struct Lisp_String *s = b->first_data.string;
1832 if (s)
1833 CHECK_STRING_BYTES (s);
1836 for (b = oldest_sblock; b; b = b->next)
1837 check_sblock (b);
1839 else
1840 check_sblock (current_sblock);
1843 #endif /* GC_CHECK_STRING_BYTES */
1845 #ifdef GC_CHECK_STRING_FREE_LIST
1847 /* Walk through the string free list looking for bogus next pointers.
1848 This may catch buffer overrun from a previous string. */
1850 static void
1851 check_string_free_list ()
1853 struct Lisp_String *s;
1855 /* Pop a Lisp_String off the free-list. */
1856 s = string_free_list;
1857 while (s != NULL)
1859 if ((unsigned)s < 1024)
1860 abort();
1861 s = NEXT_FREE_LISP_STRING (s);
1864 #else
1865 #define check_string_free_list()
1866 #endif
1868 /* Return a new Lisp_String. */
1870 static struct Lisp_String *
1871 allocate_string ()
1873 struct Lisp_String *s;
1875 /* eassert (!handling_signal); */
1877 #ifndef SYNC_INPUT
1878 BLOCK_INPUT;
1879 #endif
1881 /* If the free-list is empty, allocate a new string_block, and
1882 add all the Lisp_Strings in it to the free-list. */
1883 if (string_free_list == NULL)
1885 struct string_block *b;
1886 int i;
1888 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1889 bzero (b, sizeof *b);
1890 b->next = string_blocks;
1891 string_blocks = b;
1892 ++n_string_blocks;
1894 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1896 s = b->strings + i;
1897 NEXT_FREE_LISP_STRING (s) = string_free_list;
1898 string_free_list = s;
1901 total_free_strings += STRING_BLOCK_SIZE;
1904 check_string_free_list ();
1906 /* Pop a Lisp_String off the free-list. */
1907 s = string_free_list;
1908 string_free_list = NEXT_FREE_LISP_STRING (s);
1910 #ifndef SYNC_INPUT
1911 UNBLOCK_INPUT;
1912 #endif
1914 /* Probably not strictly necessary, but play it safe. */
1915 bzero (s, sizeof *s);
1917 --total_free_strings;
1918 ++total_strings;
1919 ++strings_consed;
1920 consing_since_gc += sizeof *s;
1922 #ifdef GC_CHECK_STRING_BYTES
1923 if (!noninteractive
1924 #ifdef MAC_OS8
1925 && current_sblock
1926 #endif
1929 if (++check_string_bytes_count == 200)
1931 check_string_bytes_count = 0;
1932 check_string_bytes (1);
1934 else
1935 check_string_bytes (0);
1937 #endif /* GC_CHECK_STRING_BYTES */
1939 return s;
1943 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1944 plus a NUL byte at the end. Allocate an sdata structure for S, and
1945 set S->data to its `u.data' member. Store a NUL byte at the end of
1946 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1947 S->data if it was initially non-null. */
1949 void
1950 allocate_string_data (s, nchars, nbytes)
1951 struct Lisp_String *s;
1952 int nchars, nbytes;
1954 struct sdata *data, *old_data;
1955 struct sblock *b;
1956 int needed, old_nbytes;
1958 /* Determine the number of bytes needed to store NBYTES bytes
1959 of string data. */
1960 needed = SDATA_SIZE (nbytes);
1961 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1962 old_nbytes = GC_STRING_BYTES (s);
1964 #ifndef SYNC_INPUT
1965 BLOCK_INPUT;
1966 #endif
1968 if (nbytes > LARGE_STRING_BYTES)
1970 size_t size = sizeof *b - sizeof (struct sdata) + needed;
1972 #ifdef DOUG_LEA_MALLOC
1973 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1974 because mapped region contents are not preserved in
1975 a dumped Emacs.
1977 In case you think of allowing it in a dumped Emacs at the
1978 cost of not being able to re-dump, there's another reason:
1979 mmap'ed data typically have an address towards the top of the
1980 address space, which won't fit into an EMACS_INT (at least on
1981 32-bit systems with the current tagging scheme). --fx */
1982 BLOCK_INPUT;
1983 mallopt (M_MMAP_MAX, 0);
1984 UNBLOCK_INPUT;
1985 #endif
1987 b = (struct sblock *) lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
1989 #ifdef DOUG_LEA_MALLOC
1990 /* Back to a reasonable maximum of mmap'ed areas. */
1991 BLOCK_INPUT;
1992 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1993 UNBLOCK_INPUT;
1994 #endif
1996 b->next_free = &b->first_data;
1997 b->first_data.string = NULL;
1998 b->next = large_sblocks;
1999 large_sblocks = b;
2001 else if (current_sblock == NULL
2002 || (((char *) current_sblock + SBLOCK_SIZE
2003 - (char *) current_sblock->next_free)
2004 < (needed + GC_STRING_EXTRA)))
2006 /* Not enough room in the current sblock. */
2007 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
2008 b->next_free = &b->first_data;
2009 b->first_data.string = NULL;
2010 b->next = NULL;
2012 if (current_sblock)
2013 current_sblock->next = b;
2014 else
2015 oldest_sblock = b;
2016 current_sblock = b;
2018 else
2019 b = current_sblock;
2021 data = b->next_free;
2022 b->next_free = (struct sdata *) ((char *) data + needed + GC_STRING_EXTRA);
2024 #ifndef SYNC_INPUT
2025 UNBLOCK_INPUT;
2026 #endif
2028 data->string = s;
2029 s->data = SDATA_DATA (data);
2030 #ifdef GC_CHECK_STRING_BYTES
2031 SDATA_NBYTES (data) = nbytes;
2032 #endif
2033 s->size = nchars;
2034 s->size_byte = nbytes;
2035 s->data[nbytes] = '\0';
2036 #ifdef GC_CHECK_STRING_OVERRUN
2037 bcopy (string_overrun_cookie, (char *) data + needed,
2038 GC_STRING_OVERRUN_COOKIE_SIZE);
2039 #endif
2041 /* If S had already data assigned, mark that as free by setting its
2042 string back-pointer to null, and recording the size of the data
2043 in it. */
2044 if (old_data)
2046 SDATA_NBYTES (old_data) = old_nbytes;
2047 old_data->string = NULL;
2050 consing_since_gc += needed;
2054 /* Sweep and compact strings. */
2056 static void
2057 sweep_strings ()
2059 struct string_block *b, *next;
2060 struct string_block *live_blocks = NULL;
2062 string_free_list = NULL;
2063 total_strings = total_free_strings = 0;
2064 total_string_size = 0;
2066 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
2067 for (b = string_blocks; b; b = next)
2069 int i, nfree = 0;
2070 struct Lisp_String *free_list_before = string_free_list;
2072 next = b->next;
2074 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
2076 struct Lisp_String *s = b->strings + i;
2078 if (s->data)
2080 /* String was not on free-list before. */
2081 if (STRING_MARKED_P (s))
2083 /* String is live; unmark it and its intervals. */
2084 UNMARK_STRING (s);
2086 if (!NULL_INTERVAL_P (s->intervals))
2087 UNMARK_BALANCE_INTERVALS (s->intervals);
2089 ++total_strings;
2090 total_string_size += STRING_BYTES (s);
2092 else
2094 /* String is dead. Put it on the free-list. */
2095 struct sdata *data = SDATA_OF_STRING (s);
2097 /* Save the size of S in its sdata so that we know
2098 how large that is. Reset the sdata's string
2099 back-pointer so that we know it's free. */
2100 #ifdef GC_CHECK_STRING_BYTES
2101 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
2102 abort ();
2103 #else
2104 data->u.nbytes = GC_STRING_BYTES (s);
2105 #endif
2106 data->string = NULL;
2108 /* Reset the strings's `data' member so that we
2109 know it's free. */
2110 s->data = NULL;
2112 /* Put the string on the free-list. */
2113 NEXT_FREE_LISP_STRING (s) = string_free_list;
2114 string_free_list = s;
2115 ++nfree;
2118 else
2120 /* S was on the free-list before. Put it there again. */
2121 NEXT_FREE_LISP_STRING (s) = string_free_list;
2122 string_free_list = s;
2123 ++nfree;
2127 /* Free blocks that contain free Lisp_Strings only, except
2128 the first two of them. */
2129 if (nfree == STRING_BLOCK_SIZE
2130 && total_free_strings > STRING_BLOCK_SIZE)
2132 lisp_free (b);
2133 --n_string_blocks;
2134 string_free_list = free_list_before;
2136 else
2138 total_free_strings += nfree;
2139 b->next = live_blocks;
2140 live_blocks = b;
2144 check_string_free_list ();
2146 string_blocks = live_blocks;
2147 free_large_strings ();
2148 compact_small_strings ();
2150 check_string_free_list ();
2154 /* Free dead large strings. */
2156 static void
2157 free_large_strings ()
2159 struct sblock *b, *next;
2160 struct sblock *live_blocks = NULL;
2162 for (b = large_sblocks; b; b = next)
2164 next = b->next;
2166 if (b->first_data.string == NULL)
2167 lisp_free (b);
2168 else
2170 b->next = live_blocks;
2171 live_blocks = b;
2175 large_sblocks = live_blocks;
2179 /* Compact data of small strings. Free sblocks that don't contain
2180 data of live strings after compaction. */
2182 static void
2183 compact_small_strings ()
2185 struct sblock *b, *tb, *next;
2186 struct sdata *from, *to, *end, *tb_end;
2187 struct sdata *to_end, *from_end;
2189 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2190 to, and TB_END is the end of TB. */
2191 tb = oldest_sblock;
2192 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2193 to = &tb->first_data;
2195 /* Step through the blocks from the oldest to the youngest. We
2196 expect that old blocks will stabilize over time, so that less
2197 copying will happen this way. */
2198 for (b = oldest_sblock; b; b = b->next)
2200 end = b->next_free;
2201 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2203 for (from = &b->first_data; from < end; from = from_end)
2205 /* Compute the next FROM here because copying below may
2206 overwrite data we need to compute it. */
2207 int nbytes;
2209 #ifdef GC_CHECK_STRING_BYTES
2210 /* Check that the string size recorded in the string is the
2211 same as the one recorded in the sdata structure. */
2212 if (from->string
2213 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
2214 abort ();
2215 #endif /* GC_CHECK_STRING_BYTES */
2217 if (from->string)
2218 nbytes = GC_STRING_BYTES (from->string);
2219 else
2220 nbytes = SDATA_NBYTES (from);
2222 if (nbytes > LARGE_STRING_BYTES)
2223 abort ();
2225 nbytes = SDATA_SIZE (nbytes);
2226 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
2228 #ifdef GC_CHECK_STRING_OVERRUN
2229 if (bcmp (string_overrun_cookie,
2230 ((char *) from_end) - GC_STRING_OVERRUN_COOKIE_SIZE,
2231 GC_STRING_OVERRUN_COOKIE_SIZE))
2232 abort ();
2233 #endif
2235 /* FROM->string non-null means it's alive. Copy its data. */
2236 if (from->string)
2238 /* If TB is full, proceed with the next sblock. */
2239 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2240 if (to_end > tb_end)
2242 tb->next_free = to;
2243 tb = tb->next;
2244 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2245 to = &tb->first_data;
2246 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2249 /* Copy, and update the string's `data' pointer. */
2250 if (from != to)
2252 xassert (tb != b || to <= from);
2253 safe_bcopy ((char *) from, (char *) to, nbytes + GC_STRING_EXTRA);
2254 to->string->data = SDATA_DATA (to);
2257 /* Advance past the sdata we copied to. */
2258 to = to_end;
2263 /* The rest of the sblocks following TB don't contain live data, so
2264 we can free them. */
2265 for (b = tb->next; b; b = next)
2267 next = b->next;
2268 lisp_free (b);
2271 tb->next_free = to;
2272 tb->next = NULL;
2273 current_sblock = tb;
2277 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2278 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2279 LENGTH must be an integer.
2280 INIT must be an integer that represents a character. */)
2281 (length, init)
2282 Lisp_Object length, init;
2284 register Lisp_Object val;
2285 register unsigned char *p, *end;
2286 int c, nbytes;
2288 CHECK_NATNUM (length);
2289 CHECK_NUMBER (init);
2291 c = XINT (init);
2292 if (SINGLE_BYTE_CHAR_P (c))
2294 nbytes = XINT (length);
2295 val = make_uninit_string (nbytes);
2296 p = SDATA (val);
2297 end = p + SCHARS (val);
2298 while (p != end)
2299 *p++ = c;
2301 else
2303 unsigned char str[MAX_MULTIBYTE_LENGTH];
2304 int len = CHAR_STRING (c, str);
2306 nbytes = len * XINT (length);
2307 val = make_uninit_multibyte_string (XINT (length), nbytes);
2308 p = SDATA (val);
2309 end = p + nbytes;
2310 while (p != end)
2312 bcopy (str, p, len);
2313 p += len;
2317 *p = 0;
2318 return val;
2322 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2323 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2324 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2325 (length, init)
2326 Lisp_Object length, init;
2328 register Lisp_Object val;
2329 struct Lisp_Bool_Vector *p;
2330 int real_init, i;
2331 int length_in_chars, length_in_elts, bits_per_value;
2333 CHECK_NATNUM (length);
2335 bits_per_value = sizeof (EMACS_INT) * BOOL_VECTOR_BITS_PER_CHAR;
2337 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
2338 length_in_chars = ((XFASTINT (length) + BOOL_VECTOR_BITS_PER_CHAR - 1)
2339 / BOOL_VECTOR_BITS_PER_CHAR);
2341 /* We must allocate one more elements than LENGTH_IN_ELTS for the
2342 slot `size' of the struct Lisp_Bool_Vector. */
2343 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
2344 p = XBOOL_VECTOR (val);
2346 /* Get rid of any bits that would cause confusion. */
2347 p->vector_size = 0;
2348 XSETBOOL_VECTOR (val, p);
2349 p->size = XFASTINT (length);
2351 real_init = (NILP (init) ? 0 : -1);
2352 for (i = 0; i < length_in_chars ; i++)
2353 p->data[i] = real_init;
2355 /* Clear the extraneous bits in the last byte. */
2356 if (XINT (length) != length_in_chars * BOOL_VECTOR_BITS_PER_CHAR)
2357 XBOOL_VECTOR (val)->data[length_in_chars - 1]
2358 &= (1 << (XINT (length) % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2360 return val;
2364 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2365 of characters from the contents. This string may be unibyte or
2366 multibyte, depending on the contents. */
2368 Lisp_Object
2369 make_string (contents, nbytes)
2370 const char *contents;
2371 int nbytes;
2373 register Lisp_Object val;
2374 int nchars, multibyte_nbytes;
2376 parse_str_as_multibyte (contents, nbytes, &nchars, &multibyte_nbytes);
2377 if (nbytes == nchars || nbytes != multibyte_nbytes)
2378 /* CONTENTS contains no multibyte sequences or contains an invalid
2379 multibyte sequence. We must make unibyte string. */
2380 val = make_unibyte_string (contents, nbytes);
2381 else
2382 val = make_multibyte_string (contents, nchars, nbytes);
2383 return val;
2387 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
2389 Lisp_Object
2390 make_unibyte_string (contents, length)
2391 const char *contents;
2392 int length;
2394 register Lisp_Object val;
2395 val = make_uninit_string (length);
2396 bcopy (contents, SDATA (val), length);
2397 STRING_SET_UNIBYTE (val);
2398 return val;
2402 /* Make a multibyte string from NCHARS characters occupying NBYTES
2403 bytes at CONTENTS. */
2405 Lisp_Object
2406 make_multibyte_string (contents, nchars, nbytes)
2407 const char *contents;
2408 int nchars, nbytes;
2410 register Lisp_Object val;
2411 val = make_uninit_multibyte_string (nchars, nbytes);
2412 bcopy (contents, SDATA (val), nbytes);
2413 return val;
2417 /* Make a string from NCHARS characters occupying NBYTES bytes at
2418 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2420 Lisp_Object
2421 make_string_from_bytes (contents, nchars, nbytes)
2422 const char *contents;
2423 int nchars, nbytes;
2425 register Lisp_Object val;
2426 val = make_uninit_multibyte_string (nchars, nbytes);
2427 bcopy (contents, SDATA (val), nbytes);
2428 if (SBYTES (val) == SCHARS (val))
2429 STRING_SET_UNIBYTE (val);
2430 return val;
2434 /* Make a string from NCHARS characters occupying NBYTES bytes at
2435 CONTENTS. The argument MULTIBYTE controls whether to label the
2436 string as multibyte. If NCHARS is negative, it counts the number of
2437 characters by itself. */
2439 Lisp_Object
2440 make_specified_string (contents, nchars, nbytes, multibyte)
2441 const char *contents;
2442 int nchars, nbytes;
2443 int multibyte;
2445 register Lisp_Object val;
2447 if (nchars < 0)
2449 if (multibyte)
2450 nchars = multibyte_chars_in_text (contents, nbytes);
2451 else
2452 nchars = nbytes;
2454 val = make_uninit_multibyte_string (nchars, nbytes);
2455 bcopy (contents, SDATA (val), nbytes);
2456 if (!multibyte)
2457 STRING_SET_UNIBYTE (val);
2458 return val;
2462 /* Make a string from the data at STR, treating it as multibyte if the
2463 data warrants. */
2465 Lisp_Object
2466 build_string (str)
2467 const char *str;
2469 return make_string (str, strlen (str));
2473 /* Return an unibyte Lisp_String set up to hold LENGTH characters
2474 occupying LENGTH bytes. */
2476 Lisp_Object
2477 make_uninit_string (length)
2478 int length;
2480 Lisp_Object val;
2481 val = make_uninit_multibyte_string (length, length);
2482 STRING_SET_UNIBYTE (val);
2483 return val;
2487 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2488 which occupy NBYTES bytes. */
2490 Lisp_Object
2491 make_uninit_multibyte_string (nchars, nbytes)
2492 int nchars, nbytes;
2494 Lisp_Object string;
2495 struct Lisp_String *s;
2497 if (nchars < 0)
2498 abort ();
2500 s = allocate_string ();
2501 allocate_string_data (s, nchars, nbytes);
2502 XSETSTRING (string, s);
2503 string_chars_consed += nbytes;
2504 return string;
2509 /***********************************************************************
2510 Float Allocation
2511 ***********************************************************************/
2513 /* We store float cells inside of float_blocks, allocating a new
2514 float_block with malloc whenever necessary. Float cells reclaimed
2515 by GC are put on a free list to be reallocated before allocating
2516 any new float cells from the latest float_block. */
2518 #define FLOAT_BLOCK_SIZE \
2519 (((BLOCK_BYTES - sizeof (struct float_block *) \
2520 /* The compiler might add padding at the end. */ \
2521 - (sizeof (struct Lisp_Float) - sizeof (int))) * CHAR_BIT) \
2522 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2524 #define GETMARKBIT(block,n) \
2525 (((block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2526 >> ((n) % (sizeof(int) * CHAR_BIT))) \
2527 & 1)
2529 #define SETMARKBIT(block,n) \
2530 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2531 |= 1 << ((n) % (sizeof(int) * CHAR_BIT))
2533 #define UNSETMARKBIT(block,n) \
2534 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2535 &= ~(1 << ((n) % (sizeof(int) * CHAR_BIT)))
2537 #define FLOAT_BLOCK(fptr) \
2538 ((struct float_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
2540 #define FLOAT_INDEX(fptr) \
2541 ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2543 struct float_block
2545 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2546 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2547 int gcmarkbits[1 + FLOAT_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
2548 struct float_block *next;
2551 #define FLOAT_MARKED_P(fptr) \
2552 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2554 #define FLOAT_MARK(fptr) \
2555 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2557 #define FLOAT_UNMARK(fptr) \
2558 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2560 /* Current float_block. */
2562 struct float_block *float_block;
2564 /* Index of first unused Lisp_Float in the current float_block. */
2566 int float_block_index;
2568 /* Total number of float blocks now in use. */
2570 int n_float_blocks;
2572 /* Free-list of Lisp_Floats. */
2574 struct Lisp_Float *float_free_list;
2577 /* Initialize float allocation. */
2579 void
2580 init_float ()
2582 float_block = NULL;
2583 float_block_index = FLOAT_BLOCK_SIZE; /* Force alloc of new float_block. */
2584 float_free_list = 0;
2585 n_float_blocks = 0;
2589 /* Explicitly free a float cell by putting it on the free-list. */
2591 void
2592 free_float (ptr)
2593 struct Lisp_Float *ptr;
2595 ptr->u.chain = float_free_list;
2596 float_free_list = ptr;
2600 /* Return a new float object with value FLOAT_VALUE. */
2602 Lisp_Object
2603 make_float (float_value)
2604 double float_value;
2606 register Lisp_Object val;
2608 /* eassert (!handling_signal); */
2610 #ifndef SYNC_INPUT
2611 BLOCK_INPUT;
2612 #endif
2614 if (float_free_list)
2616 /* We use the data field for chaining the free list
2617 so that we won't use the same field that has the mark bit. */
2618 XSETFLOAT (val, float_free_list);
2619 float_free_list = float_free_list->u.chain;
2621 else
2623 if (float_block_index == FLOAT_BLOCK_SIZE)
2625 register struct float_block *new;
2627 new = (struct float_block *) lisp_align_malloc (sizeof *new,
2628 MEM_TYPE_FLOAT);
2629 new->next = float_block;
2630 bzero ((char *) new->gcmarkbits, sizeof new->gcmarkbits);
2631 float_block = new;
2632 float_block_index = 0;
2633 n_float_blocks++;
2635 XSETFLOAT (val, &float_block->floats[float_block_index]);
2636 float_block_index++;
2639 #ifndef SYNC_INPUT
2640 UNBLOCK_INPUT;
2641 #endif
2643 XFLOAT_DATA (val) = float_value;
2644 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2645 consing_since_gc += sizeof (struct Lisp_Float);
2646 floats_consed++;
2647 return val;
2652 /***********************************************************************
2653 Cons Allocation
2654 ***********************************************************************/
2656 /* We store cons cells inside of cons_blocks, allocating a new
2657 cons_block with malloc whenever necessary. Cons cells reclaimed by
2658 GC are put on a free list to be reallocated before allocating
2659 any new cons cells from the latest cons_block. */
2661 #define CONS_BLOCK_SIZE \
2662 (((BLOCK_BYTES - sizeof (struct cons_block *)) * CHAR_BIT) \
2663 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2665 #define CONS_BLOCK(fptr) \
2666 ((struct cons_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
2668 #define CONS_INDEX(fptr) \
2669 ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2671 struct cons_block
2673 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2674 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2675 int gcmarkbits[1 + CONS_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
2676 struct cons_block *next;
2679 #define CONS_MARKED_P(fptr) \
2680 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2682 #define CONS_MARK(fptr) \
2683 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2685 #define CONS_UNMARK(fptr) \
2686 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2688 /* Current cons_block. */
2690 struct cons_block *cons_block;
2692 /* Index of first unused Lisp_Cons in the current block. */
2694 int cons_block_index;
2696 /* Free-list of Lisp_Cons structures. */
2698 struct Lisp_Cons *cons_free_list;
2700 /* Total number of cons blocks now in use. */
2702 int n_cons_blocks;
2705 /* Initialize cons allocation. */
2707 void
2708 init_cons ()
2710 cons_block = NULL;
2711 cons_block_index = CONS_BLOCK_SIZE; /* Force alloc of new cons_block. */
2712 cons_free_list = 0;
2713 n_cons_blocks = 0;
2717 /* Explicitly free a cons cell by putting it on the free-list. */
2719 void
2720 free_cons (ptr)
2721 struct Lisp_Cons *ptr;
2723 ptr->u.chain = cons_free_list;
2724 #if GC_MARK_STACK
2725 ptr->car = Vdead;
2726 #endif
2727 cons_free_list = ptr;
2730 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2731 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2732 (car, cdr)
2733 Lisp_Object car, cdr;
2735 register Lisp_Object val;
2737 /* eassert (!handling_signal); */
2739 #ifndef SYNC_INPUT
2740 BLOCK_INPUT;
2741 #endif
2743 if (cons_free_list)
2745 /* We use the cdr for chaining the free list
2746 so that we won't use the same field that has the mark bit. */
2747 XSETCONS (val, cons_free_list);
2748 cons_free_list = cons_free_list->u.chain;
2750 else
2752 if (cons_block_index == CONS_BLOCK_SIZE)
2754 register struct cons_block *new;
2755 new = (struct cons_block *) lisp_align_malloc (sizeof *new,
2756 MEM_TYPE_CONS);
2757 bzero ((char *) new->gcmarkbits, sizeof new->gcmarkbits);
2758 new->next = cons_block;
2759 cons_block = new;
2760 cons_block_index = 0;
2761 n_cons_blocks++;
2763 XSETCONS (val, &cons_block->conses[cons_block_index]);
2764 cons_block_index++;
2767 #ifndef SYNC_INPUT
2768 UNBLOCK_INPUT;
2769 #endif
2771 XSETCAR (val, car);
2772 XSETCDR (val, cdr);
2773 eassert (!CONS_MARKED_P (XCONS (val)));
2774 consing_since_gc += sizeof (struct Lisp_Cons);
2775 cons_cells_consed++;
2776 return val;
2779 /* Get an error now if there's any junk in the cons free list. */
2780 void
2781 check_cons_list ()
2783 #ifdef GC_CHECK_CONS_LIST
2784 struct Lisp_Cons *tail = cons_free_list;
2786 while (tail)
2787 tail = tail->u.chain;
2788 #endif
2791 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2793 Lisp_Object
2794 list1 (arg1)
2795 Lisp_Object arg1;
2797 return Fcons (arg1, Qnil);
2800 Lisp_Object
2801 list2 (arg1, arg2)
2802 Lisp_Object arg1, arg2;
2804 return Fcons (arg1, Fcons (arg2, Qnil));
2808 Lisp_Object
2809 list3 (arg1, arg2, arg3)
2810 Lisp_Object arg1, arg2, arg3;
2812 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2816 Lisp_Object
2817 list4 (arg1, arg2, arg3, arg4)
2818 Lisp_Object arg1, arg2, arg3, arg4;
2820 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2824 Lisp_Object
2825 list5 (arg1, arg2, arg3, arg4, arg5)
2826 Lisp_Object arg1, arg2, arg3, arg4, arg5;
2828 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2829 Fcons (arg5, Qnil)))));
2833 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2834 doc: /* Return a newly created list with specified arguments as elements.
2835 Any number of arguments, even zero arguments, are allowed.
2836 usage: (list &rest OBJECTS) */)
2837 (nargs, args)
2838 int nargs;
2839 register Lisp_Object *args;
2841 register Lisp_Object val;
2842 val = Qnil;
2844 while (nargs > 0)
2846 nargs--;
2847 val = Fcons (args[nargs], val);
2849 return val;
2853 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2854 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2855 (length, init)
2856 register Lisp_Object length, init;
2858 register Lisp_Object val;
2859 register int size;
2861 CHECK_NATNUM (length);
2862 size = XFASTINT (length);
2864 val = Qnil;
2865 while (size > 0)
2867 val = Fcons (init, val);
2868 --size;
2870 if (size > 0)
2872 val = Fcons (init, val);
2873 --size;
2875 if (size > 0)
2877 val = Fcons (init, val);
2878 --size;
2880 if (size > 0)
2882 val = Fcons (init, val);
2883 --size;
2885 if (size > 0)
2887 val = Fcons (init, val);
2888 --size;
2894 QUIT;
2897 return val;
2902 /***********************************************************************
2903 Vector Allocation
2904 ***********************************************************************/
2906 /* Singly-linked list of all vectors. */
2908 struct Lisp_Vector *all_vectors;
2910 /* Total number of vector-like objects now in use. */
2912 int n_vectors;
2915 /* Value is a pointer to a newly allocated Lisp_Vector structure
2916 with room for LEN Lisp_Objects. */
2918 static struct Lisp_Vector *
2919 allocate_vectorlike (len, type)
2920 EMACS_INT len;
2921 enum mem_type type;
2923 struct Lisp_Vector *p;
2924 size_t nbytes;
2926 #ifdef DOUG_LEA_MALLOC
2927 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2928 because mapped region contents are not preserved in
2929 a dumped Emacs. */
2930 BLOCK_INPUT;
2931 mallopt (M_MMAP_MAX, 0);
2932 UNBLOCK_INPUT;
2933 #endif
2935 /* This gets triggered by code which I haven't bothered to fix. --Stef */
2936 /* eassert (!handling_signal); */
2938 nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
2939 p = (struct Lisp_Vector *) lisp_malloc (nbytes, type);
2941 #ifdef DOUG_LEA_MALLOC
2942 /* Back to a reasonable maximum of mmap'ed areas. */
2943 BLOCK_INPUT;
2944 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2945 UNBLOCK_INPUT;
2946 #endif
2948 consing_since_gc += nbytes;
2949 vector_cells_consed += len;
2951 #ifndef SYNC_INPUT
2952 BLOCK_INPUT;
2953 #endif
2955 p->next = all_vectors;
2956 all_vectors = p;
2958 #ifndef SYNC_INPUT
2959 UNBLOCK_INPUT;
2960 #endif
2962 ++n_vectors;
2963 return p;
2967 /* Allocate a vector with NSLOTS slots. */
2969 struct Lisp_Vector *
2970 allocate_vector (nslots)
2971 EMACS_INT nslots;
2973 struct Lisp_Vector *v = allocate_vectorlike (nslots, MEM_TYPE_VECTOR);
2974 v->size = nslots;
2975 return v;
2979 /* Allocate other vector-like structures. */
2981 struct Lisp_Hash_Table *
2982 allocate_hash_table ()
2984 EMACS_INT len = VECSIZE (struct Lisp_Hash_Table);
2985 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_HASH_TABLE);
2986 EMACS_INT i;
2988 v->size = len;
2989 for (i = 0; i < len; ++i)
2990 v->contents[i] = Qnil;
2992 return (struct Lisp_Hash_Table *) v;
2996 struct window *
2997 allocate_window ()
2999 EMACS_INT len = VECSIZE (struct window);
3000 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_WINDOW);
3001 EMACS_INT i;
3003 for (i = 0; i < len; ++i)
3004 v->contents[i] = Qnil;
3005 v->size = len;
3007 return (struct window *) v;
3011 struct frame *
3012 allocate_frame ()
3014 EMACS_INT len = VECSIZE (struct frame);
3015 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_FRAME);
3016 EMACS_INT i;
3018 for (i = 0; i < len; ++i)
3019 v->contents[i] = make_number (0);
3020 v->size = len;
3021 return (struct frame *) v;
3025 struct Lisp_Process *
3026 allocate_process ()
3028 /* Memory-footprint of the object in nb of Lisp_Object fields. */
3029 EMACS_INT memlen = VECSIZE (struct Lisp_Process);
3030 /* Size if we only count the actual Lisp_Object fields (which need to be
3031 traced by the GC). */
3032 EMACS_INT lisplen = PSEUDOVECSIZE (struct Lisp_Process, pid);
3033 struct Lisp_Vector *v = allocate_vectorlike (memlen, MEM_TYPE_PROCESS);
3034 EMACS_INT i;
3036 for (i = 0; i < lisplen; ++i)
3037 v->contents[i] = Qnil;
3038 v->size = lisplen;
3040 return (struct Lisp_Process *) v;
3044 struct Lisp_Vector *
3045 allocate_other_vector (len)
3046 EMACS_INT len;
3048 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_VECTOR);
3049 EMACS_INT i;
3051 for (i = 0; i < len; ++i)
3052 v->contents[i] = Qnil;
3053 v->size = len;
3055 return v;
3059 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
3060 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
3061 See also the function `vector'. */)
3062 (length, init)
3063 register Lisp_Object length, init;
3065 Lisp_Object vector;
3066 register EMACS_INT sizei;
3067 register int index;
3068 register struct Lisp_Vector *p;
3070 CHECK_NATNUM (length);
3071 sizei = XFASTINT (length);
3073 p = allocate_vector (sizei);
3074 for (index = 0; index < sizei; index++)
3075 p->contents[index] = init;
3077 XSETVECTOR (vector, p);
3078 return vector;
3082 DEFUN ("make-char-table", Fmake_char_table, Smake_char_table, 1, 2, 0,
3083 doc: /* Return a newly created char-table, with purpose PURPOSE.
3084 Each element is initialized to INIT, which defaults to nil.
3085 PURPOSE should be a symbol which has a `char-table-extra-slots' property.
3086 The property's value should be an integer between 0 and 10. */)
3087 (purpose, init)
3088 register Lisp_Object purpose, init;
3090 Lisp_Object vector;
3091 Lisp_Object n;
3092 CHECK_SYMBOL (purpose);
3093 n = Fget (purpose, Qchar_table_extra_slots);
3094 CHECK_NUMBER (n);
3095 if (XINT (n) < 0 || XINT (n) > 10)
3096 args_out_of_range (n, Qnil);
3097 /* Add 2 to the size for the defalt and parent slots. */
3098 vector = Fmake_vector (make_number (CHAR_TABLE_STANDARD_SLOTS + XINT (n)),
3099 init);
3100 XCHAR_TABLE (vector)->top = Qt;
3101 XCHAR_TABLE (vector)->parent = Qnil;
3102 XCHAR_TABLE (vector)->purpose = purpose;
3103 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
3104 return vector;
3108 /* Return a newly created sub char table with slots initialized by INIT.
3109 Since a sub char table does not appear as a top level Emacs Lisp
3110 object, we don't need a Lisp interface to make it. */
3112 Lisp_Object
3113 make_sub_char_table (init)
3114 Lisp_Object init;
3116 Lisp_Object vector
3117 = Fmake_vector (make_number (SUB_CHAR_TABLE_STANDARD_SLOTS), init);
3118 XCHAR_TABLE (vector)->top = Qnil;
3119 XCHAR_TABLE (vector)->defalt = Qnil;
3120 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
3121 return vector;
3125 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3126 doc: /* Return a newly created vector with specified arguments as elements.
3127 Any number of arguments, even zero arguments, are allowed.
3128 usage: (vector &rest OBJECTS) */)
3129 (nargs, args)
3130 register int nargs;
3131 Lisp_Object *args;
3133 register Lisp_Object len, val;
3134 register int index;
3135 register struct Lisp_Vector *p;
3137 XSETFASTINT (len, nargs);
3138 val = Fmake_vector (len, Qnil);
3139 p = XVECTOR (val);
3140 for (index = 0; index < nargs; index++)
3141 p->contents[index] = args[index];
3142 return val;
3146 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3147 doc: /* Create a byte-code object with specified arguments as elements.
3148 The arguments should be the arglist, bytecode-string, constant vector,
3149 stack size, (optional) doc string, and (optional) interactive spec.
3150 The first four arguments are required; at most six have any
3151 significance.
3152 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3153 (nargs, args)
3154 register int nargs;
3155 Lisp_Object *args;
3157 register Lisp_Object len, val;
3158 register int index;
3159 register struct Lisp_Vector *p;
3161 XSETFASTINT (len, nargs);
3162 if (!NILP (Vpurify_flag))
3163 val = make_pure_vector ((EMACS_INT) nargs);
3164 else
3165 val = Fmake_vector (len, Qnil);
3167 if (STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
3168 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3169 earlier because they produced a raw 8-bit string for byte-code
3170 and now such a byte-code string is loaded as multibyte while
3171 raw 8-bit characters converted to multibyte form. Thus, now we
3172 must convert them back to the original unibyte form. */
3173 args[1] = Fstring_as_unibyte (args[1]);
3175 p = XVECTOR (val);
3176 for (index = 0; index < nargs; index++)
3178 if (!NILP (Vpurify_flag))
3179 args[index] = Fpurecopy (args[index]);
3180 p->contents[index] = args[index];
3182 XSETCOMPILED (val, p);
3183 return val;
3188 /***********************************************************************
3189 Symbol Allocation
3190 ***********************************************************************/
3192 /* Each symbol_block is just under 1020 bytes long, since malloc
3193 really allocates in units of powers of two and uses 4 bytes for its
3194 own overhead. */
3196 #define SYMBOL_BLOCK_SIZE \
3197 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
3199 struct symbol_block
3201 /* Place `symbols' first, to preserve alignment. */
3202 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3203 struct symbol_block *next;
3206 /* Current symbol block and index of first unused Lisp_Symbol
3207 structure in it. */
3209 struct symbol_block *symbol_block;
3210 int symbol_block_index;
3212 /* List of free symbols. */
3214 struct Lisp_Symbol *symbol_free_list;
3216 /* Total number of symbol blocks now in use. */
3218 int n_symbol_blocks;
3221 /* Initialize symbol allocation. */
3223 void
3224 init_symbol ()
3226 symbol_block = NULL;
3227 symbol_block_index = SYMBOL_BLOCK_SIZE;
3228 symbol_free_list = 0;
3229 n_symbol_blocks = 0;
3233 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3234 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3235 Its value and function definition are void, and its property list is nil. */)
3236 (name)
3237 Lisp_Object name;
3239 register Lisp_Object val;
3240 register struct Lisp_Symbol *p;
3242 CHECK_STRING (name);
3244 /* eassert (!handling_signal); */
3246 #ifndef SYNC_INPUT
3247 BLOCK_INPUT;
3248 #endif
3250 if (symbol_free_list)
3252 XSETSYMBOL (val, symbol_free_list);
3253 symbol_free_list = symbol_free_list->next;
3255 else
3257 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3259 struct symbol_block *new;
3260 new = (struct symbol_block *) lisp_malloc (sizeof *new,
3261 MEM_TYPE_SYMBOL);
3262 new->next = symbol_block;
3263 symbol_block = new;
3264 symbol_block_index = 0;
3265 n_symbol_blocks++;
3267 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index]);
3268 symbol_block_index++;
3271 #ifndef SYNC_INPUT
3272 UNBLOCK_INPUT;
3273 #endif
3275 p = XSYMBOL (val);
3276 p->xname = name;
3277 p->plist = Qnil;
3278 p->value = Qunbound;
3279 p->function = Qunbound;
3280 p->next = NULL;
3281 p->gcmarkbit = 0;
3282 p->interned = SYMBOL_UNINTERNED;
3283 p->constant = 0;
3284 p->indirect_variable = 0;
3285 consing_since_gc += sizeof (struct Lisp_Symbol);
3286 symbols_consed++;
3287 return val;
3292 /***********************************************************************
3293 Marker (Misc) Allocation
3294 ***********************************************************************/
3296 /* Allocation of markers and other objects that share that structure.
3297 Works like allocation of conses. */
3299 #define MARKER_BLOCK_SIZE \
3300 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
3302 struct marker_block
3304 /* Place `markers' first, to preserve alignment. */
3305 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
3306 struct marker_block *next;
3309 struct marker_block *marker_block;
3310 int marker_block_index;
3312 union Lisp_Misc *marker_free_list;
3314 /* Total number of marker blocks now in use. */
3316 int n_marker_blocks;
3318 void
3319 init_marker ()
3321 marker_block = NULL;
3322 marker_block_index = MARKER_BLOCK_SIZE;
3323 marker_free_list = 0;
3324 n_marker_blocks = 0;
3327 /* Return a newly allocated Lisp_Misc object, with no substructure. */
3329 Lisp_Object
3330 allocate_misc ()
3332 Lisp_Object val;
3334 /* eassert (!handling_signal); */
3336 #ifndef SYNC_INPUT
3337 BLOCK_INPUT;
3338 #endif
3340 if (marker_free_list)
3342 XSETMISC (val, marker_free_list);
3343 marker_free_list = marker_free_list->u_free.chain;
3345 else
3347 if (marker_block_index == MARKER_BLOCK_SIZE)
3349 struct marker_block *new;
3350 new = (struct marker_block *) lisp_malloc (sizeof *new,
3351 MEM_TYPE_MISC);
3352 new->next = marker_block;
3353 marker_block = new;
3354 marker_block_index = 0;
3355 n_marker_blocks++;
3356 total_free_markers += MARKER_BLOCK_SIZE;
3358 XSETMISC (val, &marker_block->markers[marker_block_index]);
3359 marker_block_index++;
3362 #ifndef SYNC_INPUT
3363 UNBLOCK_INPUT;
3364 #endif
3366 --total_free_markers;
3367 consing_since_gc += sizeof (union Lisp_Misc);
3368 misc_objects_consed++;
3369 XMARKER (val)->gcmarkbit = 0;
3370 return val;
3373 /* Free a Lisp_Misc object */
3375 void
3376 free_misc (misc)
3377 Lisp_Object misc;
3379 XMISC (misc)->u_marker.type = Lisp_Misc_Free;
3380 XMISC (misc)->u_free.chain = marker_free_list;
3381 marker_free_list = XMISC (misc);
3383 total_free_markers++;
3386 /* Return a Lisp_Misc_Save_Value object containing POINTER and
3387 INTEGER. This is used to package C values to call record_unwind_protect.
3388 The unwind function can get the C values back using XSAVE_VALUE. */
3390 Lisp_Object
3391 make_save_value (pointer, integer)
3392 void *pointer;
3393 int integer;
3395 register Lisp_Object val;
3396 register struct Lisp_Save_Value *p;
3398 val = allocate_misc ();
3399 XMISCTYPE (val) = Lisp_Misc_Save_Value;
3400 p = XSAVE_VALUE (val);
3401 p->pointer = pointer;
3402 p->integer = integer;
3403 p->dogc = 0;
3404 return val;
3407 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3408 doc: /* Return a newly allocated marker which does not point at any place. */)
3411 register Lisp_Object val;
3412 register struct Lisp_Marker *p;
3414 val = allocate_misc ();
3415 XMISCTYPE (val) = Lisp_Misc_Marker;
3416 p = XMARKER (val);
3417 p->buffer = 0;
3418 p->bytepos = 0;
3419 p->charpos = 0;
3420 p->next = NULL;
3421 p->insertion_type = 0;
3422 return val;
3425 /* Put MARKER back on the free list after using it temporarily. */
3427 void
3428 free_marker (marker)
3429 Lisp_Object marker;
3431 unchain_marker (XMARKER (marker));
3432 free_misc (marker);
3436 /* Return a newly created vector or string with specified arguments as
3437 elements. If all the arguments are characters that can fit
3438 in a string of events, make a string; otherwise, make a vector.
3440 Any number of arguments, even zero arguments, are allowed. */
3442 Lisp_Object
3443 make_event_array (nargs, args)
3444 register int nargs;
3445 Lisp_Object *args;
3447 int i;
3449 for (i = 0; i < nargs; i++)
3450 /* The things that fit in a string
3451 are characters that are in 0...127,
3452 after discarding the meta bit and all the bits above it. */
3453 if (!INTEGERP (args[i])
3454 || (XUINT (args[i]) & ~(-CHAR_META)) >= 0200)
3455 return Fvector (nargs, args);
3457 /* Since the loop exited, we know that all the things in it are
3458 characters, so we can make a string. */
3460 Lisp_Object result;
3462 result = Fmake_string (make_number (nargs), make_number (0));
3463 for (i = 0; i < nargs; i++)
3465 SSET (result, i, XINT (args[i]));
3466 /* Move the meta bit to the right place for a string char. */
3467 if (XINT (args[i]) & CHAR_META)
3468 SSET (result, i, SREF (result, i) | 0x80);
3471 return result;
3477 /************************************************************************
3478 Memory Full Handling
3479 ************************************************************************/
3482 /* Called if malloc returns zero. */
3484 void
3485 memory_full ()
3487 int i;
3489 Vmemory_full = Qt;
3491 memory_full_cons_threshold = sizeof (struct cons_block);
3493 /* The first time we get here, free the spare memory. */
3494 for (i = 0; i < sizeof (spare_memory) / sizeof (char *); i++)
3495 if (spare_memory[i])
3497 if (i == 0)
3498 free (spare_memory[i]);
3499 else if (i >= 1 && i <= 4)
3500 lisp_align_free (spare_memory[i]);
3501 else
3502 lisp_free (spare_memory[i]);
3503 spare_memory[i] = 0;
3506 /* Record the space now used. When it decreases substantially,
3507 we can refill the memory reserve. */
3508 #ifndef SYSTEM_MALLOC
3509 bytes_used_when_full = BYTES_USED;
3510 #endif
3512 /* This used to call error, but if we've run out of memory, we could
3513 get infinite recursion trying to build the string. */
3514 xsignal (Qnil, Vmemory_signal_data);
3517 /* If we released our reserve (due to running out of memory),
3518 and we have a fair amount free once again,
3519 try to set aside another reserve in case we run out once more.
3521 This is called when a relocatable block is freed in ralloc.c,
3522 and also directly from this file, in case we're not using ralloc.c. */
3524 void
3525 refill_memory_reserve ()
3527 #ifndef SYSTEM_MALLOC
3528 if (spare_memory[0] == 0)
3529 spare_memory[0] = (char *) malloc ((size_t) SPARE_MEMORY);
3530 if (spare_memory[1] == 0)
3531 spare_memory[1] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3532 MEM_TYPE_CONS);
3533 if (spare_memory[2] == 0)
3534 spare_memory[2] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3535 MEM_TYPE_CONS);
3536 if (spare_memory[3] == 0)
3537 spare_memory[3] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3538 MEM_TYPE_CONS);
3539 if (spare_memory[4] == 0)
3540 spare_memory[4] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3541 MEM_TYPE_CONS);
3542 if (spare_memory[5] == 0)
3543 spare_memory[5] = (char *) lisp_malloc (sizeof (struct string_block),
3544 MEM_TYPE_STRING);
3545 if (spare_memory[6] == 0)
3546 spare_memory[6] = (char *) lisp_malloc (sizeof (struct string_block),
3547 MEM_TYPE_STRING);
3548 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
3549 Vmemory_full = Qnil;
3550 #endif
3553 /************************************************************************
3554 C Stack Marking
3555 ************************************************************************/
3557 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
3559 /* Conservative C stack marking requires a method to identify possibly
3560 live Lisp objects given a pointer value. We do this by keeping
3561 track of blocks of Lisp data that are allocated in a red-black tree
3562 (see also the comment of mem_node which is the type of nodes in
3563 that tree). Function lisp_malloc adds information for an allocated
3564 block to the red-black tree with calls to mem_insert, and function
3565 lisp_free removes it with mem_delete. Functions live_string_p etc
3566 call mem_find to lookup information about a given pointer in the
3567 tree, and use that to determine if the pointer points to a Lisp
3568 object or not. */
3570 /* Initialize this part of alloc.c. */
3572 static void
3573 mem_init ()
3575 mem_z.left = mem_z.right = MEM_NIL;
3576 mem_z.parent = NULL;
3577 mem_z.color = MEM_BLACK;
3578 mem_z.start = mem_z.end = NULL;
3579 mem_root = MEM_NIL;
3583 /* Value is a pointer to the mem_node containing START. Value is
3584 MEM_NIL if there is no node in the tree containing START. */
3586 static INLINE struct mem_node *
3587 mem_find (start)
3588 void *start;
3590 struct mem_node *p;
3592 if (start < min_heap_address || start > max_heap_address)
3593 return MEM_NIL;
3595 /* Make the search always successful to speed up the loop below. */
3596 mem_z.start = start;
3597 mem_z.end = (char *) start + 1;
3599 p = mem_root;
3600 while (start < p->start || start >= p->end)
3601 p = start < p->start ? p->left : p->right;
3602 return p;
3606 /* Insert a new node into the tree for a block of memory with start
3607 address START, end address END, and type TYPE. Value is a
3608 pointer to the node that was inserted. */
3610 static struct mem_node *
3611 mem_insert (start, end, type)
3612 void *start, *end;
3613 enum mem_type type;
3615 struct mem_node *c, *parent, *x;
3617 if (start < min_heap_address)
3618 min_heap_address = start;
3619 if (end > max_heap_address)
3620 max_heap_address = end;
3622 /* See where in the tree a node for START belongs. In this
3623 particular application, it shouldn't happen that a node is already
3624 present. For debugging purposes, let's check that. */
3625 c = mem_root;
3626 parent = NULL;
3628 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
3630 while (c != MEM_NIL)
3632 if (start >= c->start && start < c->end)
3633 abort ();
3634 parent = c;
3635 c = start < c->start ? c->left : c->right;
3638 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3640 while (c != MEM_NIL)
3642 parent = c;
3643 c = start < c->start ? c->left : c->right;
3646 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3648 /* Create a new node. */
3649 #ifdef GC_MALLOC_CHECK
3650 x = (struct mem_node *) _malloc_internal (sizeof *x);
3651 if (x == NULL)
3652 abort ();
3653 #else
3654 x = (struct mem_node *) xmalloc (sizeof *x);
3655 #endif
3656 x->start = start;
3657 x->end = end;
3658 x->type = type;
3659 x->parent = parent;
3660 x->left = x->right = MEM_NIL;
3661 x->color = MEM_RED;
3663 /* Insert it as child of PARENT or install it as root. */
3664 if (parent)
3666 if (start < parent->start)
3667 parent->left = x;
3668 else
3669 parent->right = x;
3671 else
3672 mem_root = x;
3674 /* Re-establish red-black tree properties. */
3675 mem_insert_fixup (x);
3677 return x;
3681 /* Re-establish the red-black properties of the tree, and thereby
3682 balance the tree, after node X has been inserted; X is always red. */
3684 static void
3685 mem_insert_fixup (x)
3686 struct mem_node *x;
3688 while (x != mem_root && x->parent->color == MEM_RED)
3690 /* X is red and its parent is red. This is a violation of
3691 red-black tree property #3. */
3693 if (x->parent == x->parent->parent->left)
3695 /* We're on the left side of our grandparent, and Y is our
3696 "uncle". */
3697 struct mem_node *y = x->parent->parent->right;
3699 if (y->color == MEM_RED)
3701 /* Uncle and parent are red but should be black because
3702 X is red. Change the colors accordingly and proceed
3703 with the grandparent. */
3704 x->parent->color = MEM_BLACK;
3705 y->color = MEM_BLACK;
3706 x->parent->parent->color = MEM_RED;
3707 x = x->parent->parent;
3709 else
3711 /* Parent and uncle have different colors; parent is
3712 red, uncle is black. */
3713 if (x == x->parent->right)
3715 x = x->parent;
3716 mem_rotate_left (x);
3719 x->parent->color = MEM_BLACK;
3720 x->parent->parent->color = MEM_RED;
3721 mem_rotate_right (x->parent->parent);
3724 else
3726 /* This is the symmetrical case of above. */
3727 struct mem_node *y = x->parent->parent->left;
3729 if (y->color == MEM_RED)
3731 x->parent->color = MEM_BLACK;
3732 y->color = MEM_BLACK;
3733 x->parent->parent->color = MEM_RED;
3734 x = x->parent->parent;
3736 else
3738 if (x == x->parent->left)
3740 x = x->parent;
3741 mem_rotate_right (x);
3744 x->parent->color = MEM_BLACK;
3745 x->parent->parent->color = MEM_RED;
3746 mem_rotate_left (x->parent->parent);
3751 /* The root may have been changed to red due to the algorithm. Set
3752 it to black so that property #5 is satisfied. */
3753 mem_root->color = MEM_BLACK;
3757 /* (x) (y)
3758 / \ / \
3759 a (y) ===> (x) c
3760 / \ / \
3761 b c a b */
3763 static void
3764 mem_rotate_left (x)
3765 struct mem_node *x;
3767 struct mem_node *y;
3769 /* Turn y's left sub-tree into x's right sub-tree. */
3770 y = x->right;
3771 x->right = y->left;
3772 if (y->left != MEM_NIL)
3773 y->left->parent = x;
3775 /* Y's parent was x's parent. */
3776 if (y != MEM_NIL)
3777 y->parent = x->parent;
3779 /* Get the parent to point to y instead of x. */
3780 if (x->parent)
3782 if (x == x->parent->left)
3783 x->parent->left = y;
3784 else
3785 x->parent->right = y;
3787 else
3788 mem_root = y;
3790 /* Put x on y's left. */
3791 y->left = x;
3792 if (x != MEM_NIL)
3793 x->parent = y;
3797 /* (x) (Y)
3798 / \ / \
3799 (y) c ===> a (x)
3800 / \ / \
3801 a b b c */
3803 static void
3804 mem_rotate_right (x)
3805 struct mem_node *x;
3807 struct mem_node *y = x->left;
3809 x->left = y->right;
3810 if (y->right != MEM_NIL)
3811 y->right->parent = x;
3813 if (y != MEM_NIL)
3814 y->parent = x->parent;
3815 if (x->parent)
3817 if (x == x->parent->right)
3818 x->parent->right = y;
3819 else
3820 x->parent->left = y;
3822 else
3823 mem_root = y;
3825 y->right = x;
3826 if (x != MEM_NIL)
3827 x->parent = y;
3831 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
3833 static void
3834 mem_delete (z)
3835 struct mem_node *z;
3837 struct mem_node *x, *y;
3839 if (!z || z == MEM_NIL)
3840 return;
3842 if (z->left == MEM_NIL || z->right == MEM_NIL)
3843 y = z;
3844 else
3846 y = z->right;
3847 while (y->left != MEM_NIL)
3848 y = y->left;
3851 if (y->left != MEM_NIL)
3852 x = y->left;
3853 else
3854 x = y->right;
3856 x->parent = y->parent;
3857 if (y->parent)
3859 if (y == y->parent->left)
3860 y->parent->left = x;
3861 else
3862 y->parent->right = x;
3864 else
3865 mem_root = x;
3867 if (y != z)
3869 z->start = y->start;
3870 z->end = y->end;
3871 z->type = y->type;
3874 if (y->color == MEM_BLACK)
3875 mem_delete_fixup (x);
3877 #ifdef GC_MALLOC_CHECK
3878 _free_internal (y);
3879 #else
3880 xfree (y);
3881 #endif
3885 /* Re-establish the red-black properties of the tree, after a
3886 deletion. */
3888 static void
3889 mem_delete_fixup (x)
3890 struct mem_node *x;
3892 while (x != mem_root && x->color == MEM_BLACK)
3894 if (x == x->parent->left)
3896 struct mem_node *w = x->parent->right;
3898 if (w->color == MEM_RED)
3900 w->color = MEM_BLACK;
3901 x->parent->color = MEM_RED;
3902 mem_rotate_left (x->parent);
3903 w = x->parent->right;
3906 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
3908 w->color = MEM_RED;
3909 x = x->parent;
3911 else
3913 if (w->right->color == MEM_BLACK)
3915 w->left->color = MEM_BLACK;
3916 w->color = MEM_RED;
3917 mem_rotate_right (w);
3918 w = x->parent->right;
3920 w->color = x->parent->color;
3921 x->parent->color = MEM_BLACK;
3922 w->right->color = MEM_BLACK;
3923 mem_rotate_left (x->parent);
3924 x = mem_root;
3927 else
3929 struct mem_node *w = x->parent->left;
3931 if (w->color == MEM_RED)
3933 w->color = MEM_BLACK;
3934 x->parent->color = MEM_RED;
3935 mem_rotate_right (x->parent);
3936 w = x->parent->left;
3939 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
3941 w->color = MEM_RED;
3942 x = x->parent;
3944 else
3946 if (w->left->color == MEM_BLACK)
3948 w->right->color = MEM_BLACK;
3949 w->color = MEM_RED;
3950 mem_rotate_left (w);
3951 w = x->parent->left;
3954 w->color = x->parent->color;
3955 x->parent->color = MEM_BLACK;
3956 w->left->color = MEM_BLACK;
3957 mem_rotate_right (x->parent);
3958 x = mem_root;
3963 x->color = MEM_BLACK;
3967 /* Value is non-zero if P is a pointer to a live Lisp string on
3968 the heap. M is a pointer to the mem_block for P. */
3970 static INLINE int
3971 live_string_p (m, p)
3972 struct mem_node *m;
3973 void *p;
3975 if (m->type == MEM_TYPE_STRING)
3977 struct string_block *b = (struct string_block *) m->start;
3978 int offset = (char *) p - (char *) &b->strings[0];
3980 /* P must point to the start of a Lisp_String structure, and it
3981 must not be on the free-list. */
3982 return (offset >= 0
3983 && offset % sizeof b->strings[0] == 0
3984 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
3985 && ((struct Lisp_String *) p)->data != NULL);
3987 else
3988 return 0;
3992 /* Value is non-zero if P is a pointer to a live Lisp cons on
3993 the heap. M is a pointer to the mem_block for P. */
3995 static INLINE int
3996 live_cons_p (m, p)
3997 struct mem_node *m;
3998 void *p;
4000 if (m->type == MEM_TYPE_CONS)
4002 struct cons_block *b = (struct cons_block *) m->start;
4003 int offset = (char *) p - (char *) &b->conses[0];
4005 /* P must point to the start of a Lisp_Cons, not be
4006 one of the unused cells in the current cons block,
4007 and not be on the free-list. */
4008 return (offset >= 0
4009 && offset % sizeof b->conses[0] == 0
4010 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
4011 && (b != cons_block
4012 || offset / sizeof b->conses[0] < cons_block_index)
4013 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
4015 else
4016 return 0;
4020 /* Value is non-zero if P is a pointer to a live Lisp symbol on
4021 the heap. M is a pointer to the mem_block for P. */
4023 static INLINE int
4024 live_symbol_p (m, p)
4025 struct mem_node *m;
4026 void *p;
4028 if (m->type == MEM_TYPE_SYMBOL)
4030 struct symbol_block *b = (struct symbol_block *) m->start;
4031 int offset = (char *) p - (char *) &b->symbols[0];
4033 /* P must point to the start of a Lisp_Symbol, not be
4034 one of the unused cells in the current symbol block,
4035 and not be on the free-list. */
4036 return (offset >= 0
4037 && offset % sizeof b->symbols[0] == 0
4038 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
4039 && (b != symbol_block
4040 || offset / sizeof b->symbols[0] < symbol_block_index)
4041 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
4043 else
4044 return 0;
4048 /* Value is non-zero if P is a pointer to a live Lisp float on
4049 the heap. M is a pointer to the mem_block for P. */
4051 static INLINE int
4052 live_float_p (m, p)
4053 struct mem_node *m;
4054 void *p;
4056 if (m->type == MEM_TYPE_FLOAT)
4058 struct float_block *b = (struct float_block *) m->start;
4059 int offset = (char *) p - (char *) &b->floats[0];
4061 /* P must point to the start of a Lisp_Float and not be
4062 one of the unused cells in the current float block. */
4063 return (offset >= 0
4064 && offset % sizeof b->floats[0] == 0
4065 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
4066 && (b != float_block
4067 || offset / sizeof b->floats[0] < float_block_index));
4069 else
4070 return 0;
4074 /* Value is non-zero if P is a pointer to a live Lisp Misc on
4075 the heap. M is a pointer to the mem_block for P. */
4077 static INLINE int
4078 live_misc_p (m, p)
4079 struct mem_node *m;
4080 void *p;
4082 if (m->type == MEM_TYPE_MISC)
4084 struct marker_block *b = (struct marker_block *) m->start;
4085 int offset = (char *) p - (char *) &b->markers[0];
4087 /* P must point to the start of a Lisp_Misc, not be
4088 one of the unused cells in the current misc block,
4089 and not be on the free-list. */
4090 return (offset >= 0
4091 && offset % sizeof b->markers[0] == 0
4092 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
4093 && (b != marker_block
4094 || offset / sizeof b->markers[0] < marker_block_index)
4095 && ((union Lisp_Misc *) p)->u_marker.type != Lisp_Misc_Free);
4097 else
4098 return 0;
4102 /* Value is non-zero if P is a pointer to a live vector-like object.
4103 M is a pointer to the mem_block for P. */
4105 static INLINE int
4106 live_vector_p (m, p)
4107 struct mem_node *m;
4108 void *p;
4110 return (p == m->start
4111 && m->type >= MEM_TYPE_VECTOR
4112 && m->type <= MEM_TYPE_WINDOW);
4116 /* Value is non-zero if P is a pointer to a live buffer. M is a
4117 pointer to the mem_block for P. */
4119 static INLINE int
4120 live_buffer_p (m, p)
4121 struct mem_node *m;
4122 void *p;
4124 /* P must point to the start of the block, and the buffer
4125 must not have been killed. */
4126 return (m->type == MEM_TYPE_BUFFER
4127 && p == m->start
4128 && !NILP (((struct buffer *) p)->name));
4131 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
4133 #if GC_MARK_STACK
4135 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4137 /* Array of objects that are kept alive because the C stack contains
4138 a pattern that looks like a reference to them . */
4140 #define MAX_ZOMBIES 10
4141 static Lisp_Object zombies[MAX_ZOMBIES];
4143 /* Number of zombie objects. */
4145 static int nzombies;
4147 /* Number of garbage collections. */
4149 static int ngcs;
4151 /* Average percentage of zombies per collection. */
4153 static double avg_zombies;
4155 /* Max. number of live and zombie objects. */
4157 static int max_live, max_zombies;
4159 /* Average number of live objects per GC. */
4161 static double avg_live;
4163 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
4164 doc: /* Show information about live and zombie objects. */)
4167 Lisp_Object args[8], zombie_list = Qnil;
4168 int i;
4169 for (i = 0; i < nzombies; i++)
4170 zombie_list = Fcons (zombies[i], zombie_list);
4171 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
4172 args[1] = make_number (ngcs);
4173 args[2] = make_float (avg_live);
4174 args[3] = make_float (avg_zombies);
4175 args[4] = make_float (avg_zombies / avg_live / 100);
4176 args[5] = make_number (max_live);
4177 args[6] = make_number (max_zombies);
4178 args[7] = zombie_list;
4179 return Fmessage (8, args);
4182 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4185 /* Mark OBJ if we can prove it's a Lisp_Object. */
4187 static INLINE void
4188 mark_maybe_object (obj)
4189 Lisp_Object obj;
4191 void *po = (void *) XPNTR (obj);
4192 struct mem_node *m = mem_find (po);
4194 if (m != MEM_NIL)
4196 int mark_p = 0;
4198 switch (XGCTYPE (obj))
4200 case Lisp_String:
4201 mark_p = (live_string_p (m, po)
4202 && !STRING_MARKED_P ((struct Lisp_String *) po));
4203 break;
4205 case Lisp_Cons:
4206 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4207 break;
4209 case Lisp_Symbol:
4210 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4211 break;
4213 case Lisp_Float:
4214 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4215 break;
4217 case Lisp_Vectorlike:
4218 /* Note: can't check GC_BUFFERP before we know it's a
4219 buffer because checking that dereferences the pointer
4220 PO which might point anywhere. */
4221 if (live_vector_p (m, po))
4222 mark_p = !GC_SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4223 else if (live_buffer_p (m, po))
4224 mark_p = GC_BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4225 break;
4227 case Lisp_Misc:
4228 mark_p = (live_misc_p (m, po) && !XMARKER (obj)->gcmarkbit);
4229 break;
4231 case Lisp_Int:
4232 case Lisp_Type_Limit:
4233 break;
4236 if (mark_p)
4238 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4239 if (nzombies < MAX_ZOMBIES)
4240 zombies[nzombies] = obj;
4241 ++nzombies;
4242 #endif
4243 mark_object (obj);
4249 /* If P points to Lisp data, mark that as live if it isn't already
4250 marked. */
4252 static INLINE void
4253 mark_maybe_pointer (p)
4254 void *p;
4256 struct mem_node *m;
4258 /* Quickly rule out some values which can't point to Lisp data. We
4259 assume that Lisp data is aligned on even addresses. */
4260 if ((EMACS_INT) p & 1)
4261 return;
4263 m = mem_find (p);
4264 if (m != MEM_NIL)
4266 Lisp_Object obj = Qnil;
4268 switch (m->type)
4270 case MEM_TYPE_NON_LISP:
4271 /* Nothing to do; not a pointer to Lisp memory. */
4272 break;
4274 case MEM_TYPE_BUFFER:
4275 if (live_buffer_p (m, p) && !VECTOR_MARKED_P((struct buffer *)p))
4276 XSETVECTOR (obj, p);
4277 break;
4279 case MEM_TYPE_CONS:
4280 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4281 XSETCONS (obj, p);
4282 break;
4284 case MEM_TYPE_STRING:
4285 if (live_string_p (m, p)
4286 && !STRING_MARKED_P ((struct Lisp_String *) p))
4287 XSETSTRING (obj, p);
4288 break;
4290 case MEM_TYPE_MISC:
4291 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4292 XSETMISC (obj, p);
4293 break;
4295 case MEM_TYPE_SYMBOL:
4296 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4297 XSETSYMBOL (obj, p);
4298 break;
4300 case MEM_TYPE_FLOAT:
4301 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4302 XSETFLOAT (obj, p);
4303 break;
4305 case MEM_TYPE_VECTOR:
4306 case MEM_TYPE_PROCESS:
4307 case MEM_TYPE_HASH_TABLE:
4308 case MEM_TYPE_FRAME:
4309 case MEM_TYPE_WINDOW:
4310 if (live_vector_p (m, p))
4312 Lisp_Object tem;
4313 XSETVECTOR (tem, p);
4314 if (!GC_SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4315 obj = tem;
4317 break;
4319 default:
4320 abort ();
4323 if (!GC_NILP (obj))
4324 mark_object (obj);
4329 /* Mark Lisp objects referenced from the address range START..END. */
4331 static void
4332 mark_memory (start, end)
4333 void *start, *end;
4335 Lisp_Object *p;
4336 void **pp;
4338 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4339 nzombies = 0;
4340 #endif
4342 /* Make START the pointer to the start of the memory region,
4343 if it isn't already. */
4344 if (end < start)
4346 void *tem = start;
4347 start = end;
4348 end = tem;
4351 /* Mark Lisp_Objects. */
4352 for (p = (Lisp_Object *) start; (void *) p < end; ++p)
4353 mark_maybe_object (*p);
4355 /* Mark Lisp data pointed to. This is necessary because, in some
4356 situations, the C compiler optimizes Lisp objects away, so that
4357 only a pointer to them remains. Example:
4359 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4362 Lisp_Object obj = build_string ("test");
4363 struct Lisp_String *s = XSTRING (obj);
4364 Fgarbage_collect ();
4365 fprintf (stderr, "test `%s'\n", s->data);
4366 return Qnil;
4369 Here, `obj' isn't really used, and the compiler optimizes it
4370 away. The only reference to the life string is through the
4371 pointer `s'. */
4373 for (pp = (void **) start; (void *) pp < end; ++pp)
4374 mark_maybe_pointer (*pp);
4377 /* setjmp will work with GCC unless NON_SAVING_SETJMP is defined in
4378 the GCC system configuration. In gcc 3.2, the only systems for
4379 which this is so are i386-sco5 non-ELF, i386-sysv3 (maybe included
4380 by others?) and ns32k-pc532-min. */
4382 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4384 static int setjmp_tested_p, longjmps_done;
4386 #define SETJMP_WILL_LIKELY_WORK "\
4388 Emacs garbage collector has been changed to use conservative stack\n\
4389 marking. Emacs has determined that the method it uses to do the\n\
4390 marking will likely work on your system, but this isn't sure.\n\
4392 If you are a system-programmer, or can get the help of a local wizard\n\
4393 who is, please take a look at the function mark_stack in alloc.c, and\n\
4394 verify that the methods used are appropriate for your system.\n\
4396 Please mail the result to <emacs-devel@gnu.org>.\n\
4399 #define SETJMP_WILL_NOT_WORK "\
4401 Emacs garbage collector has been changed to use conservative stack\n\
4402 marking. Emacs has determined that the default method it uses to do the\n\
4403 marking will not work on your system. We will need a system-dependent\n\
4404 solution for your system.\n\
4406 Please take a look at the function mark_stack in alloc.c, and\n\
4407 try to find a way to make it work on your system.\n\
4409 Note that you may get false negatives, depending on the compiler.\n\
4410 In particular, you need to use -O with GCC for this test.\n\
4412 Please mail the result to <emacs-devel@gnu.org>.\n\
4416 /* Perform a quick check if it looks like setjmp saves registers in a
4417 jmp_buf. Print a message to stderr saying so. When this test
4418 succeeds, this is _not_ a proof that setjmp is sufficient for
4419 conservative stack marking. Only the sources or a disassembly
4420 can prove that. */
4422 static void
4423 test_setjmp ()
4425 char buf[10];
4426 register int x;
4427 jmp_buf jbuf;
4428 int result = 0;
4430 /* Arrange for X to be put in a register. */
4431 sprintf (buf, "1");
4432 x = strlen (buf);
4433 x = 2 * x - 1;
4435 setjmp (jbuf);
4436 if (longjmps_done == 1)
4438 /* Came here after the longjmp at the end of the function.
4440 If x == 1, the longjmp has restored the register to its
4441 value before the setjmp, and we can hope that setjmp
4442 saves all such registers in the jmp_buf, although that
4443 isn't sure.
4445 For other values of X, either something really strange is
4446 taking place, or the setjmp just didn't save the register. */
4448 if (x == 1)
4449 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4450 else
4452 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4453 exit (1);
4457 ++longjmps_done;
4458 x = 2;
4459 if (longjmps_done == 1)
4460 longjmp (jbuf, 1);
4463 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4466 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4468 /* Abort if anything GCPRO'd doesn't survive the GC. */
4470 static void
4471 check_gcpros ()
4473 struct gcpro *p;
4474 int i;
4476 for (p = gcprolist; p; p = p->next)
4477 for (i = 0; i < p->nvars; ++i)
4478 if (!survives_gc_p (p->var[i]))
4479 /* FIXME: It's not necessarily a bug. It might just be that the
4480 GCPRO is unnecessary or should release the object sooner. */
4481 abort ();
4484 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4486 static void
4487 dump_zombies ()
4489 int i;
4491 fprintf (stderr, "\nZombies kept alive = %d:\n", nzombies);
4492 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
4494 fprintf (stderr, " %d = ", i);
4495 debug_print (zombies[i]);
4499 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4502 /* Mark live Lisp objects on the C stack.
4504 There are several system-dependent problems to consider when
4505 porting this to new architectures:
4507 Processor Registers
4509 We have to mark Lisp objects in CPU registers that can hold local
4510 variables or are used to pass parameters.
4512 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4513 something that either saves relevant registers on the stack, or
4514 calls mark_maybe_object passing it each register's contents.
4516 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4517 implementation assumes that calling setjmp saves registers we need
4518 to see in a jmp_buf which itself lies on the stack. This doesn't
4519 have to be true! It must be verified for each system, possibly
4520 by taking a look at the source code of setjmp.
4522 Stack Layout
4524 Architectures differ in the way their processor stack is organized.
4525 For example, the stack might look like this
4527 +----------------+
4528 | Lisp_Object | size = 4
4529 +----------------+
4530 | something else | size = 2
4531 +----------------+
4532 | Lisp_Object | size = 4
4533 +----------------+
4534 | ... |
4536 In such a case, not every Lisp_Object will be aligned equally. To
4537 find all Lisp_Object on the stack it won't be sufficient to walk
4538 the stack in steps of 4 bytes. Instead, two passes will be
4539 necessary, one starting at the start of the stack, and a second
4540 pass starting at the start of the stack + 2. Likewise, if the
4541 minimal alignment of Lisp_Objects on the stack is 1, four passes
4542 would be necessary, each one starting with one byte more offset
4543 from the stack start.
4545 The current code assumes by default that Lisp_Objects are aligned
4546 equally on the stack. */
4548 static void
4549 mark_stack ()
4551 int i;
4552 jmp_buf j;
4553 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
4554 void *end;
4556 /* This trick flushes the register windows so that all the state of
4557 the process is contained in the stack. */
4558 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
4559 needed on ia64 too. See mach_dep.c, where it also says inline
4560 assembler doesn't work with relevant proprietary compilers. */
4561 #ifdef sparc
4562 asm ("ta 3");
4563 #endif
4565 /* Save registers that we need to see on the stack. We need to see
4566 registers used to hold register variables and registers used to
4567 pass parameters. */
4568 #ifdef GC_SAVE_REGISTERS_ON_STACK
4569 GC_SAVE_REGISTERS_ON_STACK (end);
4570 #else /* not GC_SAVE_REGISTERS_ON_STACK */
4572 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
4573 setjmp will definitely work, test it
4574 and print a message with the result
4575 of the test. */
4576 if (!setjmp_tested_p)
4578 setjmp_tested_p = 1;
4579 test_setjmp ();
4581 #endif /* GC_SETJMP_WORKS */
4583 setjmp (j);
4584 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
4585 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
4587 /* This assumes that the stack is a contiguous region in memory. If
4588 that's not the case, something has to be done here to iterate
4589 over the stack segments. */
4590 #ifndef GC_LISP_OBJECT_ALIGNMENT
4591 #ifdef __GNUC__
4592 #define GC_LISP_OBJECT_ALIGNMENT __alignof__ (Lisp_Object)
4593 #else
4594 #define GC_LISP_OBJECT_ALIGNMENT sizeof (Lisp_Object)
4595 #endif
4596 #endif
4597 for (i = 0; i < sizeof (Lisp_Object); i += GC_LISP_OBJECT_ALIGNMENT)
4598 mark_memory ((char *) stack_base + i, end);
4599 /* Allow for marking a secondary stack, like the register stack on the
4600 ia64. */
4601 #ifdef GC_MARK_SECONDARY_STACK
4602 GC_MARK_SECONDARY_STACK ();
4603 #endif
4605 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4606 check_gcpros ();
4607 #endif
4610 #endif /* GC_MARK_STACK != 0 */
4613 /* Determine whether it is safe to access memory at address P. */
4615 valid_pointer_p (p)
4616 void *p;
4618 int fd;
4620 /* Obviously, we cannot just access it (we would SEGV trying), so we
4621 trick the o/s to tell us whether p is a valid pointer.
4622 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4623 not validate p in that case. */
4625 if ((fd = emacs_open ("__Valid__Lisp__Object__", O_CREAT | O_WRONLY | O_TRUNC, 0666)) >= 0)
4627 int valid = (emacs_write (fd, (char *)p, 16) == 16);
4628 emacs_close (fd);
4629 unlink ("__Valid__Lisp__Object__");
4630 return valid;
4633 return -1;
4636 /* Return 1 if OBJ is a valid lisp object.
4637 Return 0 if OBJ is NOT a valid lisp object.
4638 Return -1 if we cannot validate OBJ.
4639 This function can be quite slow,
4640 so it should only be used in code for manual debugging. */
4643 valid_lisp_object_p (obj)
4644 Lisp_Object obj;
4646 void *p;
4647 #if GC_MARK_STACK
4648 struct mem_node *m;
4649 #endif
4651 if (INTEGERP (obj))
4652 return 1;
4654 p = (void *) XPNTR (obj);
4655 if (PURE_POINTER_P (p))
4656 return 1;
4658 #if !GC_MARK_STACK
4659 return valid_pointer_p (p);
4660 #else
4662 m = mem_find (p);
4664 if (m == MEM_NIL)
4666 int valid = valid_pointer_p (p);
4667 if (valid <= 0)
4668 return valid;
4670 if (SUBRP (obj))
4671 return 1;
4673 return 0;
4676 switch (m->type)
4678 case MEM_TYPE_NON_LISP:
4679 return 0;
4681 case MEM_TYPE_BUFFER:
4682 return live_buffer_p (m, p);
4684 case MEM_TYPE_CONS:
4685 return live_cons_p (m, p);
4687 case MEM_TYPE_STRING:
4688 return live_string_p (m, p);
4690 case MEM_TYPE_MISC:
4691 return live_misc_p (m, p);
4693 case MEM_TYPE_SYMBOL:
4694 return live_symbol_p (m, p);
4696 case MEM_TYPE_FLOAT:
4697 return live_float_p (m, p);
4699 case MEM_TYPE_VECTOR:
4700 case MEM_TYPE_PROCESS:
4701 case MEM_TYPE_HASH_TABLE:
4702 case MEM_TYPE_FRAME:
4703 case MEM_TYPE_WINDOW:
4704 return live_vector_p (m, p);
4706 default:
4707 break;
4710 return 0;
4711 #endif
4717 /***********************************************************************
4718 Pure Storage Management
4719 ***********************************************************************/
4721 /* Allocate room for SIZE bytes from pure Lisp storage and return a
4722 pointer to it. TYPE is the Lisp type for which the memory is
4723 allocated. TYPE < 0 means it's not used for a Lisp object. */
4725 static POINTER_TYPE *
4726 pure_alloc (size, type)
4727 size_t size;
4728 int type;
4730 POINTER_TYPE *result;
4731 #ifdef USE_LSB_TAG
4732 size_t alignment = (1 << GCTYPEBITS);
4733 #else
4734 size_t alignment = sizeof (EMACS_INT);
4736 /* Give Lisp_Floats an extra alignment. */
4737 if (type == Lisp_Float)
4739 #if defined __GNUC__ && __GNUC__ >= 2
4740 alignment = __alignof (struct Lisp_Float);
4741 #else
4742 alignment = sizeof (struct Lisp_Float);
4743 #endif
4745 #endif
4747 again:
4748 if (type >= 0)
4750 /* Allocate space for a Lisp object from the beginning of the free
4751 space with taking account of alignment. */
4752 result = ALIGN (purebeg + pure_bytes_used_lisp, alignment);
4753 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
4755 else
4757 /* Allocate space for a non-Lisp object from the end of the free
4758 space. */
4759 pure_bytes_used_non_lisp += size;
4760 result = purebeg + pure_size - pure_bytes_used_non_lisp;
4762 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
4764 if (pure_bytes_used <= pure_size)
4765 return result;
4767 /* Don't allocate a large amount here,
4768 because it might get mmap'd and then its address
4769 might not be usable. */
4770 purebeg = (char *) xmalloc (10000);
4771 pure_size = 10000;
4772 pure_bytes_used_before_overflow += pure_bytes_used - size;
4773 pure_bytes_used = 0;
4774 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
4775 goto again;
4779 /* Print a warning if PURESIZE is too small. */
4781 void
4782 check_pure_size ()
4784 if (pure_bytes_used_before_overflow)
4785 message ("emacs:0:Pure Lisp storage overflow (approx. %d bytes needed)",
4786 (int) (pure_bytes_used + pure_bytes_used_before_overflow));
4790 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
4791 the non-Lisp data pool of the pure storage, and return its start
4792 address. Return NULL if not found. */
4794 static char *
4795 find_string_data_in_pure (data, nbytes)
4796 char *data;
4797 int nbytes;
4799 int i, skip, bm_skip[256], last_char_skip, infinity, start, start_max;
4800 unsigned char *p;
4801 char *non_lisp_beg;
4803 if (pure_bytes_used_non_lisp < nbytes + 1)
4804 return NULL;
4806 /* Set up the Boyer-Moore table. */
4807 skip = nbytes + 1;
4808 for (i = 0; i < 256; i++)
4809 bm_skip[i] = skip;
4811 p = (unsigned char *) data;
4812 while (--skip > 0)
4813 bm_skip[*p++] = skip;
4815 last_char_skip = bm_skip['\0'];
4817 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
4818 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
4820 /* See the comments in the function `boyer_moore' (search.c) for the
4821 use of `infinity'. */
4822 infinity = pure_bytes_used_non_lisp + 1;
4823 bm_skip['\0'] = infinity;
4825 p = (unsigned char *) non_lisp_beg + nbytes;
4826 start = 0;
4829 /* Check the last character (== '\0'). */
4832 start += bm_skip[*(p + start)];
4834 while (start <= start_max);
4836 if (start < infinity)
4837 /* Couldn't find the last character. */
4838 return NULL;
4840 /* No less than `infinity' means we could find the last
4841 character at `p[start - infinity]'. */
4842 start -= infinity;
4844 /* Check the remaining characters. */
4845 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
4846 /* Found. */
4847 return non_lisp_beg + start;
4849 start += last_char_skip;
4851 while (start <= start_max);
4853 return NULL;
4857 /* Return a string allocated in pure space. DATA is a buffer holding
4858 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
4859 non-zero means make the result string multibyte.
4861 Must get an error if pure storage is full, since if it cannot hold
4862 a large string it may be able to hold conses that point to that
4863 string; then the string is not protected from gc. */
4865 Lisp_Object
4866 make_pure_string (data, nchars, nbytes, multibyte)
4867 char *data;
4868 int nchars, nbytes;
4869 int multibyte;
4871 Lisp_Object string;
4872 struct Lisp_String *s;
4874 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
4875 s->data = find_string_data_in_pure (data, nbytes);
4876 if (s->data == NULL)
4878 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
4879 bcopy (data, s->data, nbytes);
4880 s->data[nbytes] = '\0';
4882 s->size = nchars;
4883 s->size_byte = multibyte ? nbytes : -1;
4884 s->intervals = NULL_INTERVAL;
4885 XSETSTRING (string, s);
4886 return string;
4890 /* Return a cons allocated from pure space. Give it pure copies
4891 of CAR as car and CDR as cdr. */
4893 Lisp_Object
4894 pure_cons (car, cdr)
4895 Lisp_Object car, cdr;
4897 register Lisp_Object new;
4898 struct Lisp_Cons *p;
4900 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
4901 XSETCONS (new, p);
4902 XSETCAR (new, Fpurecopy (car));
4903 XSETCDR (new, Fpurecopy (cdr));
4904 return new;
4908 /* Value is a float object with value NUM allocated from pure space. */
4910 Lisp_Object
4911 make_pure_float (num)
4912 double num;
4914 register Lisp_Object new;
4915 struct Lisp_Float *p;
4917 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
4918 XSETFLOAT (new, p);
4919 XFLOAT_DATA (new) = num;
4920 return new;
4924 /* Return a vector with room for LEN Lisp_Objects allocated from
4925 pure space. */
4927 Lisp_Object
4928 make_pure_vector (len)
4929 EMACS_INT len;
4931 Lisp_Object new;
4932 struct Lisp_Vector *p;
4933 size_t size = sizeof *p + (len - 1) * sizeof (Lisp_Object);
4935 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
4936 XSETVECTOR (new, p);
4937 XVECTOR (new)->size = len;
4938 return new;
4942 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
4943 doc: /* Make a copy of object OBJ in pure storage.
4944 Recursively copies contents of vectors and cons cells.
4945 Does not copy symbols. Copies strings without text properties. */)
4946 (obj)
4947 register Lisp_Object obj;
4949 if (NILP (Vpurify_flag))
4950 return obj;
4952 if (PURE_POINTER_P (XPNTR (obj)))
4953 return obj;
4955 if (CONSP (obj))
4956 return pure_cons (XCAR (obj), XCDR (obj));
4957 else if (FLOATP (obj))
4958 return make_pure_float (XFLOAT_DATA (obj));
4959 else if (STRINGP (obj))
4960 return make_pure_string (SDATA (obj), SCHARS (obj),
4961 SBYTES (obj),
4962 STRING_MULTIBYTE (obj));
4963 else if (COMPILEDP (obj) || VECTORP (obj))
4965 register struct Lisp_Vector *vec;
4966 register int i;
4967 EMACS_INT size;
4969 size = XVECTOR (obj)->size;
4970 if (size & PSEUDOVECTOR_FLAG)
4971 size &= PSEUDOVECTOR_SIZE_MASK;
4972 vec = XVECTOR (make_pure_vector (size));
4973 for (i = 0; i < size; i++)
4974 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
4975 if (COMPILEDP (obj))
4976 XSETCOMPILED (obj, vec);
4977 else
4978 XSETVECTOR (obj, vec);
4979 return obj;
4981 else if (MARKERP (obj))
4982 error ("Attempt to copy a marker to pure storage");
4984 return obj;
4989 /***********************************************************************
4990 Protection from GC
4991 ***********************************************************************/
4993 /* Put an entry in staticvec, pointing at the variable with address
4994 VARADDRESS. */
4996 void
4997 staticpro (varaddress)
4998 Lisp_Object *varaddress;
5000 staticvec[staticidx++] = varaddress;
5001 if (staticidx >= NSTATICS)
5002 abort ();
5005 struct catchtag
5007 Lisp_Object tag;
5008 Lisp_Object val;
5009 struct catchtag *next;
5013 /***********************************************************************
5014 Protection from GC
5015 ***********************************************************************/
5017 /* Temporarily prevent garbage collection. */
5020 inhibit_garbage_collection ()
5022 int count = SPECPDL_INDEX ();
5023 int nbits = min (VALBITS, BITS_PER_INT);
5025 specbind (Qgc_cons_threshold, make_number (((EMACS_INT) 1 << (nbits - 1)) - 1));
5026 return count;
5030 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
5031 doc: /* Reclaim storage for Lisp objects no longer needed.
5032 Garbage collection happens automatically if you cons more than
5033 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5034 `garbage-collect' normally returns a list with info on amount of space in use:
5035 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
5036 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
5037 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)
5038 (USED-STRINGS . FREE-STRINGS))
5039 However, if there was overflow in pure space, `garbage-collect'
5040 returns nil, because real GC can't be done. */)
5043 register struct specbinding *bind;
5044 struct catchtag *catch;
5045 struct handler *handler;
5046 char stack_top_variable;
5047 register int i;
5048 int message_p;
5049 Lisp_Object total[8];
5050 int count = SPECPDL_INDEX ();
5051 EMACS_TIME t1, t2, t3;
5053 if (abort_on_gc)
5054 abort ();
5056 /* Can't GC if pure storage overflowed because we can't determine
5057 if something is a pure object or not. */
5058 if (pure_bytes_used_before_overflow)
5059 return Qnil;
5061 CHECK_CONS_LIST ();
5063 /* Don't keep undo information around forever.
5064 Do this early on, so it is no problem if the user quits. */
5066 register struct buffer *nextb = all_buffers;
5068 while (nextb)
5070 /* If a buffer's undo list is Qt, that means that undo is
5071 turned off in that buffer. Calling truncate_undo_list on
5072 Qt tends to return NULL, which effectively turns undo back on.
5073 So don't call truncate_undo_list if undo_list is Qt. */
5074 if (! NILP (nextb->name) && ! EQ (nextb->undo_list, Qt))
5075 truncate_undo_list (nextb);
5077 /* Shrink buffer gaps, but skip indirect and dead buffers. */
5078 if (nextb->base_buffer == 0 && !NILP (nextb->name))
5080 /* If a buffer's gap size is more than 10% of the buffer
5081 size, or larger than 2000 bytes, then shrink it
5082 accordingly. Keep a minimum size of 20 bytes. */
5083 int size = min (2000, max (20, (nextb->text->z_byte / 10)));
5085 if (nextb->text->gap_size > size)
5087 struct buffer *save_current = current_buffer;
5088 current_buffer = nextb;
5089 make_gap (-(nextb->text->gap_size - size));
5090 current_buffer = save_current;
5094 nextb = nextb->next;
5098 EMACS_GET_TIME (t1);
5100 /* In case user calls debug_print during GC,
5101 don't let that cause a recursive GC. */
5102 consing_since_gc = 0;
5104 /* Save what's currently displayed in the echo area. */
5105 message_p = push_message ();
5106 record_unwind_protect (pop_message_unwind, Qnil);
5108 /* Save a copy of the contents of the stack, for debugging. */
5109 #if MAX_SAVE_STACK > 0
5110 if (NILP (Vpurify_flag))
5112 i = &stack_top_variable - stack_bottom;
5113 if (i < 0) i = -i;
5114 if (i < MAX_SAVE_STACK)
5116 if (stack_copy == 0)
5117 stack_copy = (char *) xmalloc (stack_copy_size = i);
5118 else if (stack_copy_size < i)
5119 stack_copy = (char *) xrealloc (stack_copy, (stack_copy_size = i));
5120 if (stack_copy)
5122 if ((EMACS_INT) (&stack_top_variable - stack_bottom) > 0)
5123 bcopy (stack_bottom, stack_copy, i);
5124 else
5125 bcopy (&stack_top_variable, stack_copy, i);
5129 #endif /* MAX_SAVE_STACK > 0 */
5131 if (garbage_collection_messages)
5132 message1_nolog ("Garbage collecting...");
5134 BLOCK_INPUT;
5136 shrink_regexp_cache ();
5138 gc_in_progress = 1;
5140 /* clear_marks (); */
5142 /* Mark all the special slots that serve as the roots of accessibility. */
5144 for (i = 0; i < staticidx; i++)
5145 mark_object (*staticvec[i]);
5147 for (bind = specpdl; bind != specpdl_ptr; bind++)
5149 mark_object (bind->symbol);
5150 mark_object (bind->old_value);
5152 mark_kboards ();
5154 #ifdef USE_GTK
5156 extern void xg_mark_data ();
5157 xg_mark_data ();
5159 #endif
5161 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
5162 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
5163 mark_stack ();
5164 #else
5166 register struct gcpro *tail;
5167 for (tail = gcprolist; tail; tail = tail->next)
5168 for (i = 0; i < tail->nvars; i++)
5169 mark_object (tail->var[i]);
5171 #endif
5173 mark_byte_stack ();
5174 for (catch = catchlist; catch; catch = catch->next)
5176 mark_object (catch->tag);
5177 mark_object (catch->val);
5179 for (handler = handlerlist; handler; handler = handler->next)
5181 mark_object (handler->handler);
5182 mark_object (handler->var);
5184 mark_backtrace ();
5186 #ifdef HAVE_WINDOW_SYSTEM
5187 mark_fringe_data ();
5188 #endif
5190 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5191 mark_stack ();
5192 #endif
5194 /* Everything is now marked, except for the things that require special
5195 finalization, i.e. the undo_list.
5196 Look thru every buffer's undo list
5197 for elements that update markers that were not marked,
5198 and delete them. */
5200 register struct buffer *nextb = all_buffers;
5202 while (nextb)
5204 /* If a buffer's undo list is Qt, that means that undo is
5205 turned off in that buffer. Calling truncate_undo_list on
5206 Qt tends to return NULL, which effectively turns undo back on.
5207 So don't call truncate_undo_list if undo_list is Qt. */
5208 if (! EQ (nextb->undo_list, Qt))
5210 Lisp_Object tail, prev;
5211 tail = nextb->undo_list;
5212 prev = Qnil;
5213 while (CONSP (tail))
5215 if (GC_CONSP (XCAR (tail))
5216 && GC_MARKERP (XCAR (XCAR (tail)))
5217 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5219 if (NILP (prev))
5220 nextb->undo_list = tail = XCDR (tail);
5221 else
5223 tail = XCDR (tail);
5224 XSETCDR (prev, tail);
5227 else
5229 prev = tail;
5230 tail = XCDR (tail);
5234 /* Now that we have stripped the elements that need not be in the
5235 undo_list any more, we can finally mark the list. */
5236 mark_object (nextb->undo_list);
5238 nextb = nextb->next;
5242 gc_sweep ();
5244 /* Clear the mark bits that we set in certain root slots. */
5246 unmark_byte_stack ();
5247 VECTOR_UNMARK (&buffer_defaults);
5248 VECTOR_UNMARK (&buffer_local_symbols);
5250 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
5251 dump_zombies ();
5252 #endif
5254 UNBLOCK_INPUT;
5256 CHECK_CONS_LIST ();
5258 /* clear_marks (); */
5259 gc_in_progress = 0;
5261 consing_since_gc = 0;
5262 if (gc_cons_threshold < 10000)
5263 gc_cons_threshold = 10000;
5265 if (FLOATP (Vgc_cons_percentage))
5266 { /* Set gc_cons_combined_threshold. */
5267 EMACS_INT total = 0;
5269 total += total_conses * sizeof (struct Lisp_Cons);
5270 total += total_symbols * sizeof (struct Lisp_Symbol);
5271 total += total_markers * sizeof (union Lisp_Misc);
5272 total += total_string_size;
5273 total += total_vector_size * sizeof (Lisp_Object);
5274 total += total_floats * sizeof (struct Lisp_Float);
5275 total += total_intervals * sizeof (struct interval);
5276 total += total_strings * sizeof (struct Lisp_String);
5278 gc_relative_threshold = total * XFLOAT_DATA (Vgc_cons_percentage);
5280 else
5281 gc_relative_threshold = 0;
5283 if (garbage_collection_messages)
5285 if (message_p || minibuf_level > 0)
5286 restore_message ();
5287 else
5288 message1_nolog ("Garbage collecting...done");
5291 unbind_to (count, Qnil);
5293 total[0] = Fcons (make_number (total_conses),
5294 make_number (total_free_conses));
5295 total[1] = Fcons (make_number (total_symbols),
5296 make_number (total_free_symbols));
5297 total[2] = Fcons (make_number (total_markers),
5298 make_number (total_free_markers));
5299 total[3] = make_number (total_string_size);
5300 total[4] = make_number (total_vector_size);
5301 total[5] = Fcons (make_number (total_floats),
5302 make_number (total_free_floats));
5303 total[6] = Fcons (make_number (total_intervals),
5304 make_number (total_free_intervals));
5305 total[7] = Fcons (make_number (total_strings),
5306 make_number (total_free_strings));
5308 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5310 /* Compute average percentage of zombies. */
5311 double nlive = 0;
5313 for (i = 0; i < 7; ++i)
5314 if (CONSP (total[i]))
5315 nlive += XFASTINT (XCAR (total[i]));
5317 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
5318 max_live = max (nlive, max_live);
5319 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
5320 max_zombies = max (nzombies, max_zombies);
5321 ++ngcs;
5323 #endif
5325 if (!NILP (Vpost_gc_hook))
5327 int count = inhibit_garbage_collection ();
5328 safe_run_hooks (Qpost_gc_hook);
5329 unbind_to (count, Qnil);
5332 /* Accumulate statistics. */
5333 EMACS_GET_TIME (t2);
5334 EMACS_SUB_TIME (t3, t2, t1);
5335 if (FLOATP (Vgc_elapsed))
5336 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed) +
5337 EMACS_SECS (t3) +
5338 EMACS_USECS (t3) * 1.0e-6);
5339 gcs_done++;
5341 return Flist (sizeof total / sizeof *total, total);
5345 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5346 only interesting objects referenced from glyphs are strings. */
5348 static void
5349 mark_glyph_matrix (matrix)
5350 struct glyph_matrix *matrix;
5352 struct glyph_row *row = matrix->rows;
5353 struct glyph_row *end = row + matrix->nrows;
5355 for (; row < end; ++row)
5356 if (row->enabled_p)
5358 int area;
5359 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
5361 struct glyph *glyph = row->glyphs[area];
5362 struct glyph *end_glyph = glyph + row->used[area];
5364 for (; glyph < end_glyph; ++glyph)
5365 if (GC_STRINGP (glyph->object)
5366 && !STRING_MARKED_P (XSTRING (glyph->object)))
5367 mark_object (glyph->object);
5373 /* Mark Lisp faces in the face cache C. */
5375 static void
5376 mark_face_cache (c)
5377 struct face_cache *c;
5379 if (c)
5381 int i, j;
5382 for (i = 0; i < c->used; ++i)
5384 struct face *face = FACE_FROM_ID (c->f, i);
5386 if (face)
5388 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
5389 mark_object (face->lface[j]);
5396 #ifdef HAVE_WINDOW_SYSTEM
5398 /* Mark Lisp objects in image IMG. */
5400 static void
5401 mark_image (img)
5402 struct image *img;
5404 mark_object (img->spec);
5406 if (!NILP (img->data.lisp_val))
5407 mark_object (img->data.lisp_val);
5411 /* Mark Lisp objects in image cache of frame F. It's done this way so
5412 that we don't have to include xterm.h here. */
5414 static void
5415 mark_image_cache (f)
5416 struct frame *f;
5418 forall_images_in_image_cache (f, mark_image);
5421 #endif /* HAVE_X_WINDOWS */
5425 /* Mark reference to a Lisp_Object.
5426 If the object referred to has not been seen yet, recursively mark
5427 all the references contained in it. */
5429 #define LAST_MARKED_SIZE 500
5430 Lisp_Object last_marked[LAST_MARKED_SIZE];
5431 int last_marked_index;
5433 /* For debugging--call abort when we cdr down this many
5434 links of a list, in mark_object. In debugging,
5435 the call to abort will hit a breakpoint.
5436 Normally this is zero and the check never goes off. */
5437 int mark_object_loop_halt;
5439 void
5440 mark_object (arg)
5441 Lisp_Object arg;
5443 register Lisp_Object obj = arg;
5444 #ifdef GC_CHECK_MARKED_OBJECTS
5445 void *po;
5446 struct mem_node *m;
5447 #endif
5448 int cdr_count = 0;
5450 loop:
5452 if (PURE_POINTER_P (XPNTR (obj)))
5453 return;
5455 last_marked[last_marked_index++] = obj;
5456 if (last_marked_index == LAST_MARKED_SIZE)
5457 last_marked_index = 0;
5459 /* Perform some sanity checks on the objects marked here. Abort if
5460 we encounter an object we know is bogus. This increases GC time
5461 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
5462 #ifdef GC_CHECK_MARKED_OBJECTS
5464 po = (void *) XPNTR (obj);
5466 /* Check that the object pointed to by PO is known to be a Lisp
5467 structure allocated from the heap. */
5468 #define CHECK_ALLOCATED() \
5469 do { \
5470 m = mem_find (po); \
5471 if (m == MEM_NIL) \
5472 abort (); \
5473 } while (0)
5475 /* Check that the object pointed to by PO is live, using predicate
5476 function LIVEP. */
5477 #define CHECK_LIVE(LIVEP) \
5478 do { \
5479 if (!LIVEP (m, po)) \
5480 abort (); \
5481 } while (0)
5483 /* Check both of the above conditions. */
5484 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
5485 do { \
5486 CHECK_ALLOCATED (); \
5487 CHECK_LIVE (LIVEP); \
5488 } while (0) \
5490 #else /* not GC_CHECK_MARKED_OBJECTS */
5492 #define CHECK_ALLOCATED() (void) 0
5493 #define CHECK_LIVE(LIVEP) (void) 0
5494 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
5496 #endif /* not GC_CHECK_MARKED_OBJECTS */
5498 switch (SWITCH_ENUM_CAST (XGCTYPE (obj)))
5500 case Lisp_String:
5502 register struct Lisp_String *ptr = XSTRING (obj);
5503 CHECK_ALLOCATED_AND_LIVE (live_string_p);
5504 MARK_INTERVAL_TREE (ptr->intervals);
5505 MARK_STRING (ptr);
5506 #ifdef GC_CHECK_STRING_BYTES
5507 /* Check that the string size recorded in the string is the
5508 same as the one recorded in the sdata structure. */
5509 CHECK_STRING_BYTES (ptr);
5510 #endif /* GC_CHECK_STRING_BYTES */
5512 break;
5514 case Lisp_Vectorlike:
5515 #ifdef GC_CHECK_MARKED_OBJECTS
5516 m = mem_find (po);
5517 if (m == MEM_NIL && !GC_SUBRP (obj)
5518 && po != &buffer_defaults
5519 && po != &buffer_local_symbols)
5520 abort ();
5521 #endif /* GC_CHECK_MARKED_OBJECTS */
5523 if (GC_BUFFERP (obj))
5525 if (!VECTOR_MARKED_P (XBUFFER (obj)))
5527 #ifdef GC_CHECK_MARKED_OBJECTS
5528 if (po != &buffer_defaults && po != &buffer_local_symbols)
5530 struct buffer *b;
5531 for (b = all_buffers; b && b != po; b = b->next)
5533 if (b == NULL)
5534 abort ();
5536 #endif /* GC_CHECK_MARKED_OBJECTS */
5537 mark_buffer (obj);
5540 else if (GC_SUBRP (obj))
5541 break;
5542 else if (GC_COMPILEDP (obj))
5543 /* We could treat this just like a vector, but it is better to
5544 save the COMPILED_CONSTANTS element for last and avoid
5545 recursion there. */
5547 register struct Lisp_Vector *ptr = XVECTOR (obj);
5548 register EMACS_INT size = ptr->size;
5549 register int i;
5551 if (VECTOR_MARKED_P (ptr))
5552 break; /* Already marked */
5554 CHECK_LIVE (live_vector_p);
5555 VECTOR_MARK (ptr); /* Else mark it */
5556 size &= PSEUDOVECTOR_SIZE_MASK;
5557 for (i = 0; i < size; i++) /* and then mark its elements */
5559 if (i != COMPILED_CONSTANTS)
5560 mark_object (ptr->contents[i]);
5562 obj = ptr->contents[COMPILED_CONSTANTS];
5563 goto loop;
5565 else if (GC_FRAMEP (obj))
5567 register struct frame *ptr = XFRAME (obj);
5569 if (VECTOR_MARKED_P (ptr)) break; /* Already marked */
5570 VECTOR_MARK (ptr); /* Else mark it */
5572 CHECK_LIVE (live_vector_p);
5573 mark_object (ptr->name);
5574 mark_object (ptr->icon_name);
5575 mark_object (ptr->title);
5576 mark_object (ptr->focus_frame);
5577 mark_object (ptr->selected_window);
5578 mark_object (ptr->minibuffer_window);
5579 mark_object (ptr->param_alist);
5580 mark_object (ptr->scroll_bars);
5581 mark_object (ptr->condemned_scroll_bars);
5582 mark_object (ptr->menu_bar_items);
5583 mark_object (ptr->face_alist);
5584 mark_object (ptr->menu_bar_vector);
5585 mark_object (ptr->buffer_predicate);
5586 mark_object (ptr->buffer_list);
5587 mark_object (ptr->menu_bar_window);
5588 mark_object (ptr->tool_bar_window);
5589 mark_face_cache (ptr->face_cache);
5590 #ifdef HAVE_WINDOW_SYSTEM
5591 mark_image_cache (ptr);
5592 mark_object (ptr->tool_bar_items);
5593 mark_object (ptr->desired_tool_bar_string);
5594 mark_object (ptr->current_tool_bar_string);
5595 #endif /* HAVE_WINDOW_SYSTEM */
5597 else if (GC_BOOL_VECTOR_P (obj))
5599 register struct Lisp_Vector *ptr = XVECTOR (obj);
5601 if (VECTOR_MARKED_P (ptr))
5602 break; /* Already marked */
5603 CHECK_LIVE (live_vector_p);
5604 VECTOR_MARK (ptr); /* Else mark it */
5606 else if (GC_WINDOWP (obj))
5608 register struct Lisp_Vector *ptr = XVECTOR (obj);
5609 struct window *w = XWINDOW (obj);
5610 register int i;
5612 /* Stop if already marked. */
5613 if (VECTOR_MARKED_P (ptr))
5614 break;
5616 /* Mark it. */
5617 CHECK_LIVE (live_vector_p);
5618 VECTOR_MARK (ptr);
5620 /* There is no Lisp data above The member CURRENT_MATRIX in
5621 struct WINDOW. Stop marking when that slot is reached. */
5622 for (i = 0;
5623 (char *) &ptr->contents[i] < (char *) &w->current_matrix;
5624 i++)
5625 mark_object (ptr->contents[i]);
5627 /* Mark glyphs for leaf windows. Marking window matrices is
5628 sufficient because frame matrices use the same glyph
5629 memory. */
5630 if (NILP (w->hchild)
5631 && NILP (w->vchild)
5632 && w->current_matrix)
5634 mark_glyph_matrix (w->current_matrix);
5635 mark_glyph_matrix (w->desired_matrix);
5638 else if (GC_HASH_TABLE_P (obj))
5640 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
5642 /* Stop if already marked. */
5643 if (VECTOR_MARKED_P (h))
5644 break;
5646 /* Mark it. */
5647 CHECK_LIVE (live_vector_p);
5648 VECTOR_MARK (h);
5650 /* Mark contents. */
5651 /* Do not mark next_free or next_weak.
5652 Being in the next_weak chain
5653 should not keep the hash table alive.
5654 No need to mark `count' since it is an integer. */
5655 mark_object (h->test);
5656 mark_object (h->weak);
5657 mark_object (h->rehash_size);
5658 mark_object (h->rehash_threshold);
5659 mark_object (h->hash);
5660 mark_object (h->next);
5661 mark_object (h->index);
5662 mark_object (h->user_hash_function);
5663 mark_object (h->user_cmp_function);
5665 /* If hash table is not weak, mark all keys and values.
5666 For weak tables, mark only the vector. */
5667 if (GC_NILP (h->weak))
5668 mark_object (h->key_and_value);
5669 else
5670 VECTOR_MARK (XVECTOR (h->key_and_value));
5672 else
5674 register struct Lisp_Vector *ptr = XVECTOR (obj);
5675 register EMACS_INT size = ptr->size;
5676 register int i;
5678 if (VECTOR_MARKED_P (ptr)) break; /* Already marked */
5679 CHECK_LIVE (live_vector_p);
5680 VECTOR_MARK (ptr); /* Else mark it */
5681 if (size & PSEUDOVECTOR_FLAG)
5682 size &= PSEUDOVECTOR_SIZE_MASK;
5684 /* Note that this size is not the memory-footprint size, but only
5685 the number of Lisp_Object fields that we should trace.
5686 The distinction is used e.g. by Lisp_Process which places extra
5687 non-Lisp_Object fields at the end of the structure. */
5688 for (i = 0; i < size; i++) /* and then mark its elements */
5689 mark_object (ptr->contents[i]);
5691 break;
5693 case Lisp_Symbol:
5695 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
5696 struct Lisp_Symbol *ptrx;
5698 if (ptr->gcmarkbit) break;
5699 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
5700 ptr->gcmarkbit = 1;
5701 mark_object (ptr->value);
5702 mark_object (ptr->function);
5703 mark_object (ptr->plist);
5705 if (!PURE_POINTER_P (XSTRING (ptr->xname)))
5706 MARK_STRING (XSTRING (ptr->xname));
5707 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr->xname));
5709 /* Note that we do not mark the obarray of the symbol.
5710 It is safe not to do so because nothing accesses that
5711 slot except to check whether it is nil. */
5712 ptr = ptr->next;
5713 if (ptr)
5715 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
5716 XSETSYMBOL (obj, ptrx);
5717 goto loop;
5720 break;
5722 case Lisp_Misc:
5723 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
5724 if (XMARKER (obj)->gcmarkbit)
5725 break;
5726 XMARKER (obj)->gcmarkbit = 1;
5728 switch (XMISCTYPE (obj))
5730 case Lisp_Misc_Buffer_Local_Value:
5731 case Lisp_Misc_Some_Buffer_Local_Value:
5733 register struct Lisp_Buffer_Local_Value *ptr
5734 = XBUFFER_LOCAL_VALUE (obj);
5735 /* If the cdr is nil, avoid recursion for the car. */
5736 if (EQ (ptr->cdr, Qnil))
5738 obj = ptr->realvalue;
5739 goto loop;
5741 mark_object (ptr->realvalue);
5742 mark_object (ptr->buffer);
5743 mark_object (ptr->frame);
5744 obj = ptr->cdr;
5745 goto loop;
5748 case Lisp_Misc_Marker:
5749 /* DO NOT mark thru the marker's chain.
5750 The buffer's markers chain does not preserve markers from gc;
5751 instead, markers are removed from the chain when freed by gc. */
5752 break;
5754 case Lisp_Misc_Intfwd:
5755 case Lisp_Misc_Boolfwd:
5756 case Lisp_Misc_Objfwd:
5757 case Lisp_Misc_Buffer_Objfwd:
5758 case Lisp_Misc_Kboard_Objfwd:
5759 /* Don't bother with Lisp_Buffer_Objfwd,
5760 since all markable slots in current buffer marked anyway. */
5761 /* Don't need to do Lisp_Objfwd, since the places they point
5762 are protected with staticpro. */
5763 break;
5765 case Lisp_Misc_Save_Value:
5766 #if GC_MARK_STACK
5768 register struct Lisp_Save_Value *ptr = XSAVE_VALUE (obj);
5769 /* If DOGC is set, POINTER is the address of a memory
5770 area containing INTEGER potential Lisp_Objects. */
5771 if (ptr->dogc)
5773 Lisp_Object *p = (Lisp_Object *) ptr->pointer;
5774 int nelt;
5775 for (nelt = ptr->integer; nelt > 0; nelt--, p++)
5776 mark_maybe_object (*p);
5779 #endif
5780 break;
5782 case Lisp_Misc_Overlay:
5784 struct Lisp_Overlay *ptr = XOVERLAY (obj);
5785 mark_object (ptr->start);
5786 mark_object (ptr->end);
5787 mark_object (ptr->plist);
5788 if (ptr->next)
5790 XSETMISC (obj, ptr->next);
5791 goto loop;
5794 break;
5796 default:
5797 abort ();
5799 break;
5801 case Lisp_Cons:
5803 register struct Lisp_Cons *ptr = XCONS (obj);
5804 if (CONS_MARKED_P (ptr)) break;
5805 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
5806 CONS_MARK (ptr);
5807 /* If the cdr is nil, avoid recursion for the car. */
5808 if (EQ (ptr->u.cdr, Qnil))
5810 obj = ptr->car;
5811 cdr_count = 0;
5812 goto loop;
5814 mark_object (ptr->car);
5815 obj = ptr->u.cdr;
5816 cdr_count++;
5817 if (cdr_count == mark_object_loop_halt)
5818 abort ();
5819 goto loop;
5822 case Lisp_Float:
5823 CHECK_ALLOCATED_AND_LIVE (live_float_p);
5824 FLOAT_MARK (XFLOAT (obj));
5825 break;
5827 case Lisp_Int:
5828 break;
5830 default:
5831 abort ();
5834 #undef CHECK_LIVE
5835 #undef CHECK_ALLOCATED
5836 #undef CHECK_ALLOCATED_AND_LIVE
5839 /* Mark the pointers in a buffer structure. */
5841 static void
5842 mark_buffer (buf)
5843 Lisp_Object buf;
5845 register struct buffer *buffer = XBUFFER (buf);
5846 register Lisp_Object *ptr, tmp;
5847 Lisp_Object base_buffer;
5849 VECTOR_MARK (buffer);
5851 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
5853 /* For now, we just don't mark the undo_list. It's done later in
5854 a special way just before the sweep phase, and after stripping
5855 some of its elements that are not needed any more. */
5857 if (buffer->overlays_before)
5859 XSETMISC (tmp, buffer->overlays_before);
5860 mark_object (tmp);
5862 if (buffer->overlays_after)
5864 XSETMISC (tmp, buffer->overlays_after);
5865 mark_object (tmp);
5868 for (ptr = &buffer->name;
5869 (char *)ptr < (char *)buffer + sizeof (struct buffer);
5870 ptr++)
5871 mark_object (*ptr);
5873 /* If this is an indirect buffer, mark its base buffer. */
5874 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5876 XSETBUFFER (base_buffer, buffer->base_buffer);
5877 mark_buffer (base_buffer);
5882 /* Value is non-zero if OBJ will survive the current GC because it's
5883 either marked or does not need to be marked to survive. */
5886 survives_gc_p (obj)
5887 Lisp_Object obj;
5889 int survives_p;
5891 switch (XGCTYPE (obj))
5893 case Lisp_Int:
5894 survives_p = 1;
5895 break;
5897 case Lisp_Symbol:
5898 survives_p = XSYMBOL (obj)->gcmarkbit;
5899 break;
5901 case Lisp_Misc:
5902 survives_p = XMARKER (obj)->gcmarkbit;
5903 break;
5905 case Lisp_String:
5906 survives_p = STRING_MARKED_P (XSTRING (obj));
5907 break;
5909 case Lisp_Vectorlike:
5910 survives_p = GC_SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
5911 break;
5913 case Lisp_Cons:
5914 survives_p = CONS_MARKED_P (XCONS (obj));
5915 break;
5917 case Lisp_Float:
5918 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
5919 break;
5921 default:
5922 abort ();
5925 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
5930 /* Sweep: find all structures not marked, and free them. */
5932 static void
5933 gc_sweep ()
5935 /* Remove or mark entries in weak hash tables.
5936 This must be done before any object is unmarked. */
5937 sweep_weak_hash_tables ();
5939 sweep_strings ();
5940 #ifdef GC_CHECK_STRING_BYTES
5941 if (!noninteractive)
5942 check_string_bytes (1);
5943 #endif
5945 /* Put all unmarked conses on free list */
5947 register struct cons_block *cblk;
5948 struct cons_block **cprev = &cons_block;
5949 register int lim = cons_block_index;
5950 register int num_free = 0, num_used = 0;
5952 cons_free_list = 0;
5954 for (cblk = cons_block; cblk; cblk = *cprev)
5956 register int i;
5957 int this_free = 0;
5958 for (i = 0; i < lim; i++)
5959 if (!CONS_MARKED_P (&cblk->conses[i]))
5961 this_free++;
5962 cblk->conses[i].u.chain = cons_free_list;
5963 cons_free_list = &cblk->conses[i];
5964 #if GC_MARK_STACK
5965 cons_free_list->car = Vdead;
5966 #endif
5968 else
5970 num_used++;
5971 CONS_UNMARK (&cblk->conses[i]);
5973 lim = CONS_BLOCK_SIZE;
5974 /* If this block contains only free conses and we have already
5975 seen more than two blocks worth of free conses then deallocate
5976 this block. */
5977 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
5979 *cprev = cblk->next;
5980 /* Unhook from the free list. */
5981 cons_free_list = cblk->conses[0].u.chain;
5982 lisp_align_free (cblk);
5983 n_cons_blocks--;
5985 else
5987 num_free += this_free;
5988 cprev = &cblk->next;
5991 total_conses = num_used;
5992 total_free_conses = num_free;
5995 /* Put all unmarked floats on free list */
5997 register struct float_block *fblk;
5998 struct float_block **fprev = &float_block;
5999 register int lim = float_block_index;
6000 register int num_free = 0, num_used = 0;
6002 float_free_list = 0;
6004 for (fblk = float_block; fblk; fblk = *fprev)
6006 register int i;
6007 int this_free = 0;
6008 for (i = 0; i < lim; i++)
6009 if (!FLOAT_MARKED_P (&fblk->floats[i]))
6011 this_free++;
6012 fblk->floats[i].u.chain = float_free_list;
6013 float_free_list = &fblk->floats[i];
6015 else
6017 num_used++;
6018 FLOAT_UNMARK (&fblk->floats[i]);
6020 lim = FLOAT_BLOCK_SIZE;
6021 /* If this block contains only free floats and we have already
6022 seen more than two blocks worth of free floats then deallocate
6023 this block. */
6024 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6026 *fprev = fblk->next;
6027 /* Unhook from the free list. */
6028 float_free_list = fblk->floats[0].u.chain;
6029 lisp_align_free (fblk);
6030 n_float_blocks--;
6032 else
6034 num_free += this_free;
6035 fprev = &fblk->next;
6038 total_floats = num_used;
6039 total_free_floats = num_free;
6042 /* Put all unmarked intervals on free list */
6044 register struct interval_block *iblk;
6045 struct interval_block **iprev = &interval_block;
6046 register int lim = interval_block_index;
6047 register int num_free = 0, num_used = 0;
6049 interval_free_list = 0;
6051 for (iblk = interval_block; iblk; iblk = *iprev)
6053 register int i;
6054 int this_free = 0;
6056 for (i = 0; i < lim; i++)
6058 if (!iblk->intervals[i].gcmarkbit)
6060 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
6061 interval_free_list = &iblk->intervals[i];
6062 this_free++;
6064 else
6066 num_used++;
6067 iblk->intervals[i].gcmarkbit = 0;
6070 lim = INTERVAL_BLOCK_SIZE;
6071 /* If this block contains only free intervals and we have already
6072 seen more than two blocks worth of free intervals then
6073 deallocate this block. */
6074 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6076 *iprev = iblk->next;
6077 /* Unhook from the free list. */
6078 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
6079 lisp_free (iblk);
6080 n_interval_blocks--;
6082 else
6084 num_free += this_free;
6085 iprev = &iblk->next;
6088 total_intervals = num_used;
6089 total_free_intervals = num_free;
6092 /* Put all unmarked symbols on free list */
6094 register struct symbol_block *sblk;
6095 struct symbol_block **sprev = &symbol_block;
6096 register int lim = symbol_block_index;
6097 register int num_free = 0, num_used = 0;
6099 symbol_free_list = NULL;
6101 for (sblk = symbol_block; sblk; sblk = *sprev)
6103 int this_free = 0;
6104 struct Lisp_Symbol *sym = sblk->symbols;
6105 struct Lisp_Symbol *end = sym + lim;
6107 for (; sym < end; ++sym)
6109 /* Check if the symbol was created during loadup. In such a case
6110 it might be pointed to by pure bytecode which we don't trace,
6111 so we conservatively assume that it is live. */
6112 int pure_p = PURE_POINTER_P (XSTRING (sym->xname));
6114 if (!sym->gcmarkbit && !pure_p)
6116 sym->next = symbol_free_list;
6117 symbol_free_list = sym;
6118 #if GC_MARK_STACK
6119 symbol_free_list->function = Vdead;
6120 #endif
6121 ++this_free;
6123 else
6125 ++num_used;
6126 if (!pure_p)
6127 UNMARK_STRING (XSTRING (sym->xname));
6128 sym->gcmarkbit = 0;
6132 lim = SYMBOL_BLOCK_SIZE;
6133 /* If this block contains only free symbols and we have already
6134 seen more than two blocks worth of free symbols then deallocate
6135 this block. */
6136 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6138 *sprev = sblk->next;
6139 /* Unhook from the free list. */
6140 symbol_free_list = sblk->symbols[0].next;
6141 lisp_free (sblk);
6142 n_symbol_blocks--;
6144 else
6146 num_free += this_free;
6147 sprev = &sblk->next;
6150 total_symbols = num_used;
6151 total_free_symbols = num_free;
6154 /* Put all unmarked misc's on free list.
6155 For a marker, first unchain it from the buffer it points into. */
6157 register struct marker_block *mblk;
6158 struct marker_block **mprev = &marker_block;
6159 register int lim = marker_block_index;
6160 register int num_free = 0, num_used = 0;
6162 marker_free_list = 0;
6164 for (mblk = marker_block; mblk; mblk = *mprev)
6166 register int i;
6167 int this_free = 0;
6169 for (i = 0; i < lim; i++)
6171 if (!mblk->markers[i].u_marker.gcmarkbit)
6173 if (mblk->markers[i].u_marker.type == Lisp_Misc_Marker)
6174 unchain_marker (&mblk->markers[i].u_marker);
6175 /* Set the type of the freed object to Lisp_Misc_Free.
6176 We could leave the type alone, since nobody checks it,
6177 but this might catch bugs faster. */
6178 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
6179 mblk->markers[i].u_free.chain = marker_free_list;
6180 marker_free_list = &mblk->markers[i];
6181 this_free++;
6183 else
6185 num_used++;
6186 mblk->markers[i].u_marker.gcmarkbit = 0;
6189 lim = MARKER_BLOCK_SIZE;
6190 /* If this block contains only free markers and we have already
6191 seen more than two blocks worth of free markers then deallocate
6192 this block. */
6193 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6195 *mprev = mblk->next;
6196 /* Unhook from the free list. */
6197 marker_free_list = mblk->markers[0].u_free.chain;
6198 lisp_free (mblk);
6199 n_marker_blocks--;
6201 else
6203 num_free += this_free;
6204 mprev = &mblk->next;
6208 total_markers = num_used;
6209 total_free_markers = num_free;
6212 /* Free all unmarked buffers */
6214 register struct buffer *buffer = all_buffers, *prev = 0, *next;
6216 while (buffer)
6217 if (!VECTOR_MARKED_P (buffer))
6219 if (prev)
6220 prev->next = buffer->next;
6221 else
6222 all_buffers = buffer->next;
6223 next = buffer->next;
6224 lisp_free (buffer);
6225 buffer = next;
6227 else
6229 VECTOR_UNMARK (buffer);
6230 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
6231 prev = buffer, buffer = buffer->next;
6235 /* Free all unmarked vectors */
6237 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
6238 total_vector_size = 0;
6240 while (vector)
6241 if (!VECTOR_MARKED_P (vector))
6243 if (prev)
6244 prev->next = vector->next;
6245 else
6246 all_vectors = vector->next;
6247 next = vector->next;
6248 lisp_free (vector);
6249 n_vectors--;
6250 vector = next;
6253 else
6255 VECTOR_UNMARK (vector);
6256 if (vector->size & PSEUDOVECTOR_FLAG)
6257 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
6258 else
6259 total_vector_size += vector->size;
6260 prev = vector, vector = vector->next;
6264 #ifdef GC_CHECK_STRING_BYTES
6265 if (!noninteractive)
6266 check_string_bytes (1);
6267 #endif
6273 /* Debugging aids. */
6275 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
6276 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6277 This may be helpful in debugging Emacs's memory usage.
6278 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6281 Lisp_Object end;
6283 XSETINT (end, (EMACS_INT) sbrk (0) / 1024);
6285 return end;
6288 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
6289 doc: /* Return a list of counters that measure how much consing there has been.
6290 Each of these counters increments for a certain kind of object.
6291 The counters wrap around from the largest positive integer to zero.
6292 Garbage collection does not decrease them.
6293 The elements of the value are as follows:
6294 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6295 All are in units of 1 = one object consed
6296 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6297 objects consed.
6298 MISCS include overlays, markers, and some internal types.
6299 Frames, windows, buffers, and subprocesses count as vectors
6300 (but the contents of a buffer's text do not count here). */)
6303 Lisp_Object consed[8];
6305 consed[0] = make_number (min (MOST_POSITIVE_FIXNUM, cons_cells_consed));
6306 consed[1] = make_number (min (MOST_POSITIVE_FIXNUM, floats_consed));
6307 consed[2] = make_number (min (MOST_POSITIVE_FIXNUM, vector_cells_consed));
6308 consed[3] = make_number (min (MOST_POSITIVE_FIXNUM, symbols_consed));
6309 consed[4] = make_number (min (MOST_POSITIVE_FIXNUM, string_chars_consed));
6310 consed[5] = make_number (min (MOST_POSITIVE_FIXNUM, misc_objects_consed));
6311 consed[6] = make_number (min (MOST_POSITIVE_FIXNUM, intervals_consed));
6312 consed[7] = make_number (min (MOST_POSITIVE_FIXNUM, strings_consed));
6314 return Flist (8, consed);
6317 int suppress_checking;
6318 void
6319 die (msg, file, line)
6320 const char *msg;
6321 const char *file;
6322 int line;
6324 fprintf (stderr, "\r\nEmacs fatal error: %s:%d: %s\r\n",
6325 file, line, msg);
6326 abort ();
6329 /* Initialization */
6331 void
6332 init_alloc_once ()
6334 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
6335 purebeg = PUREBEG;
6336 pure_size = PURESIZE;
6337 pure_bytes_used = 0;
6338 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
6339 pure_bytes_used_before_overflow = 0;
6341 /* Initialize the list of free aligned blocks. */
6342 free_ablock = NULL;
6344 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
6345 mem_init ();
6346 Vdead = make_pure_string ("DEAD", 4, 4, 0);
6347 #endif
6349 all_vectors = 0;
6350 ignore_warnings = 1;
6351 #ifdef DOUG_LEA_MALLOC
6352 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
6353 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
6354 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
6355 #endif
6356 init_strings ();
6357 init_cons ();
6358 init_symbol ();
6359 init_marker ();
6360 init_float ();
6361 init_intervals ();
6363 #ifdef REL_ALLOC
6364 malloc_hysteresis = 32;
6365 #else
6366 malloc_hysteresis = 0;
6367 #endif
6369 refill_memory_reserve ();
6371 ignore_warnings = 0;
6372 gcprolist = 0;
6373 byte_stack_list = 0;
6374 staticidx = 0;
6375 consing_since_gc = 0;
6376 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
6377 gc_relative_threshold = 0;
6379 #ifdef VIRT_ADDR_VARIES
6380 malloc_sbrk_unused = 1<<22; /* A large number */
6381 malloc_sbrk_used = 100000; /* as reasonable as any number */
6382 #endif /* VIRT_ADDR_VARIES */
6385 void
6386 init_alloc ()
6388 gcprolist = 0;
6389 byte_stack_list = 0;
6390 #if GC_MARK_STACK
6391 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
6392 setjmp_tested_p = longjmps_done = 0;
6393 #endif
6394 #endif
6395 Vgc_elapsed = make_float (0.0);
6396 gcs_done = 0;
6399 void
6400 syms_of_alloc ()
6402 DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold,
6403 doc: /* *Number of bytes of consing between garbage collections.
6404 Garbage collection can happen automatically once this many bytes have been
6405 allocated since the last garbage collection. All data types count.
6407 Garbage collection happens automatically only when `eval' is called.
6409 By binding this temporarily to a large number, you can effectively
6410 prevent garbage collection during a part of the program.
6411 See also `gc-cons-percentage'. */);
6413 DEFVAR_LISP ("gc-cons-percentage", &Vgc_cons_percentage,
6414 doc: /* *Portion of the heap used for allocation.
6415 Garbage collection can happen automatically once this portion of the heap
6416 has been allocated since the last garbage collection.
6417 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
6418 Vgc_cons_percentage = make_float (0.1);
6420 DEFVAR_INT ("pure-bytes-used", &pure_bytes_used,
6421 doc: /* Number of bytes of sharable Lisp data allocated so far. */);
6423 DEFVAR_INT ("cons-cells-consed", &cons_cells_consed,
6424 doc: /* Number of cons cells that have been consed so far. */);
6426 DEFVAR_INT ("floats-consed", &floats_consed,
6427 doc: /* Number of floats that have been consed so far. */);
6429 DEFVAR_INT ("vector-cells-consed", &vector_cells_consed,
6430 doc: /* Number of vector cells that have been consed so far. */);
6432 DEFVAR_INT ("symbols-consed", &symbols_consed,
6433 doc: /* Number of symbols that have been consed so far. */);
6435 DEFVAR_INT ("string-chars-consed", &string_chars_consed,
6436 doc: /* Number of string characters that have been consed so far. */);
6438 DEFVAR_INT ("misc-objects-consed", &misc_objects_consed,
6439 doc: /* Number of miscellaneous objects that have been consed so far. */);
6441 DEFVAR_INT ("intervals-consed", &intervals_consed,
6442 doc: /* Number of intervals that have been consed so far. */);
6444 DEFVAR_INT ("strings-consed", &strings_consed,
6445 doc: /* Number of strings that have been consed so far. */);
6447 DEFVAR_LISP ("purify-flag", &Vpurify_flag,
6448 doc: /* Non-nil means loading Lisp code in order to dump an executable.
6449 This means that certain objects should be allocated in shared (pure) space. */);
6451 DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
6452 doc: /* Non-nil means display messages at start and end of garbage collection. */);
6453 garbage_collection_messages = 0;
6455 DEFVAR_LISP ("post-gc-hook", &Vpost_gc_hook,
6456 doc: /* Hook run after garbage collection has finished. */);
6457 Vpost_gc_hook = Qnil;
6458 Qpost_gc_hook = intern ("post-gc-hook");
6459 staticpro (&Qpost_gc_hook);
6461 DEFVAR_LISP ("memory-signal-data", &Vmemory_signal_data,
6462 doc: /* Precomputed `signal' argument for memory-full error. */);
6463 /* We build this in advance because if we wait until we need it, we might
6464 not be able to allocate the memory to hold it. */
6465 Vmemory_signal_data
6466 = list2 (Qerror,
6467 build_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
6469 DEFVAR_LISP ("memory-full", &Vmemory_full,
6470 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
6471 Vmemory_full = Qnil;
6473 staticpro (&Qgc_cons_threshold);
6474 Qgc_cons_threshold = intern ("gc-cons-threshold");
6476 staticpro (&Qchar_table_extra_slots);
6477 Qchar_table_extra_slots = intern ("char-table-extra-slots");
6479 DEFVAR_LISP ("gc-elapsed", &Vgc_elapsed,
6480 doc: /* Accumulated time elapsed in garbage collections.
6481 The time is in seconds as a floating point value. */);
6482 DEFVAR_INT ("gcs-done", &gcs_done,
6483 doc: /* Accumulated number of garbage collections done. */);
6485 defsubr (&Scons);
6486 defsubr (&Slist);
6487 defsubr (&Svector);
6488 defsubr (&Smake_byte_code);
6489 defsubr (&Smake_list);
6490 defsubr (&Smake_vector);
6491 defsubr (&Smake_char_table);
6492 defsubr (&Smake_string);
6493 defsubr (&Smake_bool_vector);
6494 defsubr (&Smake_symbol);
6495 defsubr (&Smake_marker);
6496 defsubr (&Spurecopy);
6497 defsubr (&Sgarbage_collect);
6498 defsubr (&Smemory_limit);
6499 defsubr (&Smemory_use_counts);
6501 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
6502 defsubr (&Sgc_status);
6503 #endif
6506 /* arch-tag: 6695ca10-e3c5-4c2c-8bc3-ed26a7dda857
6507 (do not change this comment) */