Mention doc-view.el.
[emacs.git] / src / alloc.c
blob8aea81a0f72fd9b38a1645fac0a7a2b49a079536
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
2 Copyright (C) 1985, 1986, 1988, 1993, 1994, 1995, 1997, 1998, 1999,
3 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, 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 #include "w32.h"
84 #endif
86 #ifdef DOUG_LEA_MALLOC
88 #include <malloc.h>
89 /* malloc.h #defines this as size_t, at least in glibc2. */
90 #ifndef __malloc_size_t
91 #define __malloc_size_t int
92 #endif
94 /* Specify maximum number of areas to mmap. It would be nice to use a
95 value that explicitly means "no limit". */
97 #define MMAP_MAX_AREAS 100000000
99 #else /* not DOUG_LEA_MALLOC */
101 /* The following come from gmalloc.c. */
103 #define __malloc_size_t size_t
104 extern __malloc_size_t _bytes_used;
105 extern __malloc_size_t __malloc_extra_blocks;
107 #endif /* not DOUG_LEA_MALLOC */
109 #if ! defined (SYSTEM_MALLOC) && defined (HAVE_GTK_AND_PTHREAD)
111 /* When GTK uses the file chooser dialog, different backends can be loaded
112 dynamically. One such a backend is the Gnome VFS backend that gets loaded
113 if you run Gnome. That backend creates several threads and also allocates
114 memory with malloc.
116 If Emacs sets malloc hooks (! SYSTEM_MALLOC) and the emacs_blocked_*
117 functions below are called from malloc, there is a chance that one
118 of these threads preempts the Emacs main thread and the hook variables
119 end up in an inconsistent state. So we have a mutex to prevent that (note
120 that the backend handles concurrent access to malloc within its own threads
121 but Emacs code running in the main thread is not included in that control).
123 When UNBLOCK_INPUT is called, reinvoke_input_signal may be called. If this
124 happens in one of the backend threads we will have two threads that tries
125 to run Emacs code at once, and the code is not prepared for that.
126 To prevent that, we only call BLOCK/UNBLOCK from the main thread. */
128 static pthread_mutex_t alloc_mutex;
130 #define BLOCK_INPUT_ALLOC \
131 do \
133 if (pthread_equal (pthread_self (), main_thread)) \
134 BLOCK_INPUT; \
135 pthread_mutex_lock (&alloc_mutex); \
137 while (0)
138 #define UNBLOCK_INPUT_ALLOC \
139 do \
141 pthread_mutex_unlock (&alloc_mutex); \
142 if (pthread_equal (pthread_self (), main_thread)) \
143 UNBLOCK_INPUT; \
145 while (0)
147 #else /* SYSTEM_MALLOC || not HAVE_GTK_AND_PTHREAD */
149 #define BLOCK_INPUT_ALLOC BLOCK_INPUT
150 #define UNBLOCK_INPUT_ALLOC UNBLOCK_INPUT
152 #endif /* SYSTEM_MALLOC || not HAVE_GTK_AND_PTHREAD */
154 /* Value of _bytes_used, when spare_memory was freed. */
156 static __malloc_size_t bytes_used_when_full;
158 static __malloc_size_t bytes_used_when_reconsidered;
160 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
161 to a struct Lisp_String. */
163 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
164 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
165 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
167 #define VECTOR_MARK(V) ((V)->size |= ARRAY_MARK_FLAG)
168 #define VECTOR_UNMARK(V) ((V)->size &= ~ARRAY_MARK_FLAG)
169 #define VECTOR_MARKED_P(V) (((V)->size & ARRAY_MARK_FLAG) != 0)
171 /* Value is the number of bytes/chars of S, a pointer to a struct
172 Lisp_String. This must be used instead of STRING_BYTES (S) or
173 S->size during GC, because S->size contains the mark bit for
174 strings. */
176 #define GC_STRING_BYTES(S) (STRING_BYTES (S))
177 #define GC_STRING_CHARS(S) ((S)->size & ~ARRAY_MARK_FLAG)
179 /* Number of bytes of consing done since the last gc. */
181 int consing_since_gc;
183 /* Count the amount of consing of various sorts of space. */
185 EMACS_INT cons_cells_consed;
186 EMACS_INT floats_consed;
187 EMACS_INT vector_cells_consed;
188 EMACS_INT symbols_consed;
189 EMACS_INT string_chars_consed;
190 EMACS_INT misc_objects_consed;
191 EMACS_INT intervals_consed;
192 EMACS_INT strings_consed;
194 /* Minimum number of bytes of consing since GC before next GC. */
196 EMACS_INT gc_cons_threshold;
198 /* Similar minimum, computed from Vgc_cons_percentage. */
200 EMACS_INT gc_relative_threshold;
202 static Lisp_Object Vgc_cons_percentage;
204 /* Minimum number of bytes of consing since GC before next GC,
205 when memory is full. */
207 EMACS_INT memory_full_cons_threshold;
209 /* Nonzero during GC. */
211 int gc_in_progress;
213 /* Nonzero means abort if try to GC.
214 This is for code which is written on the assumption that
215 no GC will happen, so as to verify that assumption. */
217 int abort_on_gc;
219 /* Nonzero means display messages at beginning and end of GC. */
221 int garbage_collection_messages;
223 #ifndef VIRT_ADDR_VARIES
224 extern
225 #endif /* VIRT_ADDR_VARIES */
226 int malloc_sbrk_used;
228 #ifndef VIRT_ADDR_VARIES
229 extern
230 #endif /* VIRT_ADDR_VARIES */
231 int malloc_sbrk_unused;
233 /* Number of live and free conses etc. */
235 static int total_conses, total_markers, total_symbols, total_vector_size;
236 static int total_free_conses, total_free_markers, total_free_symbols;
237 static int total_free_floats, total_floats;
239 /* Points to memory space allocated as "spare", to be freed if we run
240 out of memory. We keep one large block, four cons-blocks, and
241 two string blocks. */
243 char *spare_memory[7];
245 /* Amount of spare memory to keep in large reserve block. */
247 #define SPARE_MEMORY (1 << 14)
249 /* Number of extra blocks malloc should get when it needs more core. */
251 static int malloc_hysteresis;
253 /* Non-nil means defun should do purecopy on the function definition. */
255 Lisp_Object Vpurify_flag;
257 /* Non-nil means we are handling a memory-full error. */
259 Lisp_Object Vmemory_full;
261 #ifndef HAVE_SHM
263 /* Initialize it to a nonzero value to force it into data space
264 (rather than bss space). That way unexec will remap it into text
265 space (pure), on some systems. We have not implemented the
266 remapping on more recent systems because this is less important
267 nowadays than in the days of small memories and timesharing. */
269 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
270 #define PUREBEG (char *) pure
272 #else /* HAVE_SHM */
274 #define pure PURE_SEG_BITS /* Use shared memory segment */
275 #define PUREBEG (char *)PURE_SEG_BITS
277 #endif /* HAVE_SHM */
279 /* Pointer to the pure area, and its size. */
281 static char *purebeg;
282 static size_t pure_size;
284 /* Number of bytes of pure storage used before pure storage overflowed.
285 If this is non-zero, this implies that an overflow occurred. */
287 static size_t pure_bytes_used_before_overflow;
289 /* Value is non-zero if P points into pure space. */
291 #define PURE_POINTER_P(P) \
292 (((PNTR_COMPARISON_TYPE) (P) \
293 < (PNTR_COMPARISON_TYPE) ((char *) purebeg + pure_size)) \
294 && ((PNTR_COMPARISON_TYPE) (P) \
295 >= (PNTR_COMPARISON_TYPE) purebeg))
297 /* Total number of bytes allocated in pure storage. */
299 EMACS_INT pure_bytes_used;
301 /* Index in pure at which next pure Lisp object will be allocated.. */
303 static EMACS_INT pure_bytes_used_lisp;
305 /* Number of bytes allocated for non-Lisp objects in pure storage. */
307 static EMACS_INT pure_bytes_used_non_lisp;
309 /* If nonzero, this is a warning delivered by malloc and not yet
310 displayed. */
312 char *pending_malloc_warning;
314 /* Pre-computed signal argument for use when memory is exhausted. */
316 Lisp_Object Vmemory_signal_data;
318 /* Maximum amount of C stack to save when a GC happens. */
320 #ifndef MAX_SAVE_STACK
321 #define MAX_SAVE_STACK 16000
322 #endif
324 /* Buffer in which we save a copy of the C stack at each GC. */
326 char *stack_copy;
327 int stack_copy_size;
329 /* Non-zero means ignore malloc warnings. Set during initialization.
330 Currently not used. */
332 int ignore_warnings;
334 Lisp_Object Qgc_cons_threshold, Qchar_table_extra_slots;
336 /* Hook run after GC has finished. */
338 Lisp_Object Vpost_gc_hook, Qpost_gc_hook;
340 Lisp_Object Vgc_elapsed; /* accumulated elapsed time in GC */
341 EMACS_INT gcs_done; /* accumulated GCs */
343 static void mark_buffer P_ ((Lisp_Object));
344 extern void mark_terminals P_ ((void));
345 extern void mark_kboards P_ ((void));
346 extern void mark_ttys P_ ((void));
347 extern void mark_backtrace P_ ((void));
348 static void gc_sweep P_ ((void));
349 static void mark_glyph_matrix P_ ((struct glyph_matrix *));
350 static void mark_face_cache P_ ((struct face_cache *));
352 #ifdef HAVE_WINDOW_SYSTEM
353 extern void mark_fringe_data P_ ((void));
354 static void mark_image P_ ((struct image *));
355 static void mark_image_cache P_ ((struct frame *));
356 #endif /* HAVE_WINDOW_SYSTEM */
358 static struct Lisp_String *allocate_string P_ ((void));
359 static void compact_small_strings P_ ((void));
360 static void free_large_strings P_ ((void));
361 static void sweep_strings P_ ((void));
363 extern int message_enable_multibyte;
365 /* When scanning the C stack for live Lisp objects, Emacs keeps track
366 of what memory allocated via lisp_malloc is intended for what
367 purpose. This enumeration specifies the type of memory. */
369 enum mem_type
371 MEM_TYPE_NON_LISP,
372 MEM_TYPE_BUFFER,
373 MEM_TYPE_CONS,
374 MEM_TYPE_STRING,
375 MEM_TYPE_MISC,
376 MEM_TYPE_SYMBOL,
377 MEM_TYPE_FLOAT,
378 /* Keep the following vector-like types together, with
379 MEM_TYPE_WINDOW being the last, and MEM_TYPE_VECTOR the
380 first. Or change the code of live_vector_p, for instance. */
381 MEM_TYPE_VECTOR,
382 MEM_TYPE_PROCESS,
383 MEM_TYPE_HASH_TABLE,
384 MEM_TYPE_FRAME,
385 MEM_TYPE_WINDOW
388 static POINTER_TYPE *lisp_align_malloc P_ ((size_t, enum mem_type));
389 static POINTER_TYPE *lisp_malloc P_ ((size_t, enum mem_type));
390 void refill_memory_reserve ();
393 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
395 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
396 #include <stdio.h> /* For fprintf. */
397 #endif
399 /* A unique object in pure space used to make some Lisp objects
400 on free lists recognizable in O(1). */
402 Lisp_Object Vdead;
404 #ifdef GC_MALLOC_CHECK
406 enum mem_type allocated_mem_type;
407 int dont_register_blocks;
409 #endif /* GC_MALLOC_CHECK */
411 /* A node in the red-black tree describing allocated memory containing
412 Lisp data. Each such block is recorded with its start and end
413 address when it is allocated, and removed from the tree when it
414 is freed.
416 A red-black tree is a balanced binary tree with the following
417 properties:
419 1. Every node is either red or black.
420 2. Every leaf is black.
421 3. If a node is red, then both of its children are black.
422 4. Every simple path from a node to a descendant leaf contains
423 the same number of black nodes.
424 5. The root is always black.
426 When nodes are inserted into the tree, or deleted from the tree,
427 the tree is "fixed" so that these properties are always true.
429 A red-black tree with N internal nodes has height at most 2
430 log(N+1). Searches, insertions and deletions are done in O(log N).
431 Please see a text book about data structures for a detailed
432 description of red-black trees. Any book worth its salt should
433 describe them. */
435 struct mem_node
437 /* Children of this node. These pointers are never NULL. When there
438 is no child, the value is MEM_NIL, which points to a dummy node. */
439 struct mem_node *left, *right;
441 /* The parent of this node. In the root node, this is NULL. */
442 struct mem_node *parent;
444 /* Start and end of allocated region. */
445 void *start, *end;
447 /* Node color. */
448 enum {MEM_BLACK, MEM_RED} color;
450 /* Memory type. */
451 enum mem_type type;
454 /* Base address of stack. Set in main. */
456 Lisp_Object *stack_base;
458 /* Root of the tree describing allocated Lisp memory. */
460 static struct mem_node *mem_root;
462 /* Lowest and highest known address in the heap. */
464 static void *min_heap_address, *max_heap_address;
466 /* Sentinel node of the tree. */
468 static struct mem_node mem_z;
469 #define MEM_NIL &mem_z
471 static POINTER_TYPE *lisp_malloc P_ ((size_t, enum mem_type));
472 static struct Lisp_Vector *allocate_vectorlike P_ ((EMACS_INT, enum mem_type));
473 static void lisp_free P_ ((POINTER_TYPE *));
474 static void mark_stack P_ ((void));
475 static int live_vector_p P_ ((struct mem_node *, void *));
476 static int live_buffer_p P_ ((struct mem_node *, void *));
477 static int live_string_p P_ ((struct mem_node *, void *));
478 static int live_cons_p P_ ((struct mem_node *, void *));
479 static int live_symbol_p P_ ((struct mem_node *, void *));
480 static int live_float_p P_ ((struct mem_node *, void *));
481 static int live_misc_p P_ ((struct mem_node *, void *));
482 static void mark_maybe_object P_ ((Lisp_Object));
483 static void mark_memory P_ ((void *, void *, int));
484 static void mem_init P_ ((void));
485 static struct mem_node *mem_insert P_ ((void *, void *, enum mem_type));
486 static void mem_insert_fixup P_ ((struct mem_node *));
487 static void mem_rotate_left P_ ((struct mem_node *));
488 static void mem_rotate_right P_ ((struct mem_node *));
489 static void mem_delete P_ ((struct mem_node *));
490 static void mem_delete_fixup P_ ((struct mem_node *));
491 static INLINE struct mem_node *mem_find P_ ((void *));
494 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
495 static void check_gcpros P_ ((void));
496 #endif
498 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
500 /* Recording what needs to be marked for gc. */
502 struct gcpro *gcprolist;
504 /* Addresses of staticpro'd variables. Initialize it to a nonzero
505 value; otherwise some compilers put it into BSS. */
507 #define NSTATICS 1280
508 Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
510 /* Index of next unused slot in staticvec. */
512 int staticidx = 0;
514 static POINTER_TYPE *pure_alloc P_ ((size_t, int));
517 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
518 ALIGNMENT must be a power of 2. */
520 #define ALIGN(ptr, ALIGNMENT) \
521 ((POINTER_TYPE *) ((((EMACS_UINT)(ptr)) + (ALIGNMENT) - 1) \
522 & ~((ALIGNMENT) - 1)))
526 /************************************************************************
527 Malloc
528 ************************************************************************/
530 /* Function malloc calls this if it finds we are near exhausting storage. */
532 void
533 malloc_warning (str)
534 char *str;
536 pending_malloc_warning = str;
540 /* Display an already-pending malloc warning. */
542 void
543 display_malloc_warning ()
545 call3 (intern ("display-warning"),
546 intern ("alloc"),
547 build_string (pending_malloc_warning),
548 intern ("emergency"));
549 pending_malloc_warning = 0;
553 #ifdef DOUG_LEA_MALLOC
554 # define BYTES_USED (mallinfo ().uordblks)
555 #else
556 # define BYTES_USED _bytes_used
557 #endif
559 /* Called if we can't allocate relocatable space for a buffer. */
561 void
562 buffer_memory_full ()
564 /* If buffers use the relocating allocator, no need to free
565 spare_memory, because we may have plenty of malloc space left
566 that we could get, and if we don't, the malloc that fails will
567 itself cause spare_memory to be freed. If buffers don't use the
568 relocating allocator, treat this like any other failing
569 malloc. */
571 #ifndef REL_ALLOC
572 memory_full ();
573 #endif
575 /* This used to call error, but if we've run out of memory, we could
576 get infinite recursion trying to build the string. */
577 xsignal (Qnil, Vmemory_signal_data);
581 #ifdef XMALLOC_OVERRUN_CHECK
583 /* Check for overrun in malloc'ed buffers by wrapping a 16 byte header
584 and a 16 byte trailer around each block.
586 The header consists of 12 fixed bytes + a 4 byte integer contaning the
587 original block size, while the trailer consists of 16 fixed bytes.
589 The header is used to detect whether this block has been allocated
590 through these functions -- as it seems that some low-level libc
591 functions may bypass the malloc hooks.
595 #define XMALLOC_OVERRUN_CHECK_SIZE 16
597 static char xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE-4] =
598 { 0x9a, 0x9b, 0xae, 0xaf,
599 0xbf, 0xbe, 0xce, 0xcf,
600 0xea, 0xeb, 0xec, 0xed };
602 static char xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
603 { 0xaa, 0xab, 0xac, 0xad,
604 0xba, 0xbb, 0xbc, 0xbd,
605 0xca, 0xcb, 0xcc, 0xcd,
606 0xda, 0xdb, 0xdc, 0xdd };
608 /* Macros to insert and extract the block size in the header. */
610 #define XMALLOC_PUT_SIZE(ptr, size) \
611 (ptr[-1] = (size & 0xff), \
612 ptr[-2] = ((size >> 8) & 0xff), \
613 ptr[-3] = ((size >> 16) & 0xff), \
614 ptr[-4] = ((size >> 24) & 0xff))
616 #define XMALLOC_GET_SIZE(ptr) \
617 (size_t)((unsigned)(ptr[-1]) | \
618 ((unsigned)(ptr[-2]) << 8) | \
619 ((unsigned)(ptr[-3]) << 16) | \
620 ((unsigned)(ptr[-4]) << 24))
623 /* The call depth in overrun_check functions. For example, this might happen:
624 xmalloc()
625 overrun_check_malloc()
626 -> malloc -> (via hook)_-> emacs_blocked_malloc
627 -> overrun_check_malloc
628 call malloc (hooks are NULL, so real malloc is called).
629 malloc returns 10000.
630 add overhead, return 10016.
631 <- (back in overrun_check_malloc)
632 add overhead again, return 10032
633 xmalloc returns 10032.
635 (time passes).
637 xfree(10032)
638 overrun_check_free(10032)
639 decrease overhed
640 free(10016) <- crash, because 10000 is the original pointer. */
642 static int check_depth;
644 /* Like malloc, but wraps allocated block with header and trailer. */
646 POINTER_TYPE *
647 overrun_check_malloc (size)
648 size_t size;
650 register unsigned char *val;
651 size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
653 val = (unsigned char *) malloc (size + overhead);
654 if (val && check_depth == 1)
656 bcopy (xmalloc_overrun_check_header, val, XMALLOC_OVERRUN_CHECK_SIZE - 4);
657 val += XMALLOC_OVERRUN_CHECK_SIZE;
658 XMALLOC_PUT_SIZE(val, size);
659 bcopy (xmalloc_overrun_check_trailer, val + size, XMALLOC_OVERRUN_CHECK_SIZE);
661 --check_depth;
662 return (POINTER_TYPE *)val;
666 /* Like realloc, but checks old block for overrun, and wraps new block
667 with header and trailer. */
669 POINTER_TYPE *
670 overrun_check_realloc (block, size)
671 POINTER_TYPE *block;
672 size_t size;
674 register unsigned char *val = (unsigned char *)block;
675 size_t overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_SIZE*2 : 0;
677 if (val
678 && check_depth == 1
679 && bcmp (xmalloc_overrun_check_header,
680 val - XMALLOC_OVERRUN_CHECK_SIZE,
681 XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
683 size_t osize = XMALLOC_GET_SIZE (val);
684 if (bcmp (xmalloc_overrun_check_trailer,
685 val + osize,
686 XMALLOC_OVERRUN_CHECK_SIZE))
687 abort ();
688 bzero (val + osize, XMALLOC_OVERRUN_CHECK_SIZE);
689 val -= XMALLOC_OVERRUN_CHECK_SIZE;
690 bzero (val, XMALLOC_OVERRUN_CHECK_SIZE);
693 val = (unsigned char *) realloc ((POINTER_TYPE *)val, size + overhead);
695 if (val && check_depth == 1)
697 bcopy (xmalloc_overrun_check_header, val, XMALLOC_OVERRUN_CHECK_SIZE - 4);
698 val += XMALLOC_OVERRUN_CHECK_SIZE;
699 XMALLOC_PUT_SIZE(val, size);
700 bcopy (xmalloc_overrun_check_trailer, val + size, XMALLOC_OVERRUN_CHECK_SIZE);
702 --check_depth;
703 return (POINTER_TYPE *)val;
706 /* Like free, but checks block for overrun. */
708 void
709 overrun_check_free (block)
710 POINTER_TYPE *block;
712 unsigned char *val = (unsigned char *)block;
714 ++check_depth;
715 if (val
716 && check_depth == 1
717 && bcmp (xmalloc_overrun_check_header,
718 val - XMALLOC_OVERRUN_CHECK_SIZE,
719 XMALLOC_OVERRUN_CHECK_SIZE - 4) == 0)
721 size_t osize = XMALLOC_GET_SIZE (val);
722 if (bcmp (xmalloc_overrun_check_trailer,
723 val + osize,
724 XMALLOC_OVERRUN_CHECK_SIZE))
725 abort ();
726 #ifdef XMALLOC_CLEAR_FREE_MEMORY
727 val -= XMALLOC_OVERRUN_CHECK_SIZE;
728 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_SIZE*2);
729 #else
730 bzero (val + osize, XMALLOC_OVERRUN_CHECK_SIZE);
731 val -= XMALLOC_OVERRUN_CHECK_SIZE;
732 bzero (val, XMALLOC_OVERRUN_CHECK_SIZE);
733 #endif
736 free (val);
737 --check_depth;
740 #undef malloc
741 #undef realloc
742 #undef free
743 #define malloc overrun_check_malloc
744 #define realloc overrun_check_realloc
745 #define free overrun_check_free
746 #endif
749 /* Like malloc but check for no memory and block interrupt input.. */
751 POINTER_TYPE *
752 xmalloc (size)
753 size_t size;
755 register POINTER_TYPE *val;
757 BLOCK_INPUT;
758 val = (POINTER_TYPE *) malloc (size);
759 UNBLOCK_INPUT;
761 if (!val && size)
762 memory_full ();
763 return val;
767 /* Like realloc but check for no memory and block interrupt input.. */
769 POINTER_TYPE *
770 xrealloc (block, size)
771 POINTER_TYPE *block;
772 size_t size;
774 register POINTER_TYPE *val;
776 BLOCK_INPUT;
777 /* We must call malloc explicitly when BLOCK is 0, since some
778 reallocs don't do this. */
779 if (! block)
780 val = (POINTER_TYPE *) malloc (size);
781 else
782 val = (POINTER_TYPE *) realloc (block, size);
783 UNBLOCK_INPUT;
785 if (!val && size) memory_full ();
786 return val;
790 /* Like free but block interrupt input. */
792 void
793 xfree (block)
794 POINTER_TYPE *block;
796 BLOCK_INPUT;
797 free (block);
798 UNBLOCK_INPUT;
799 /* We don't call refill_memory_reserve here
800 because that duplicates doing so in emacs_blocked_free
801 and the criterion should go there. */
805 /* Like strdup, but uses xmalloc. */
807 char *
808 xstrdup (s)
809 const char *s;
811 size_t len = strlen (s) + 1;
812 char *p = (char *) xmalloc (len);
813 bcopy (s, p, len);
814 return p;
818 /* Unwind for SAFE_ALLOCA */
820 Lisp_Object
821 safe_alloca_unwind (arg)
822 Lisp_Object arg;
824 register struct Lisp_Save_Value *p = XSAVE_VALUE (arg);
826 p->dogc = 0;
827 xfree (p->pointer);
828 p->pointer = 0;
829 free_misc (arg);
830 return Qnil;
834 /* Like malloc but used for allocating Lisp data. NBYTES is the
835 number of bytes to allocate, TYPE describes the intended use of the
836 allcated memory block (for strings, for conses, ...). */
838 #ifndef USE_LSB_TAG
839 static void *lisp_malloc_loser;
840 #endif
842 static POINTER_TYPE *
843 lisp_malloc (nbytes, type)
844 size_t nbytes;
845 enum mem_type type;
847 register void *val;
849 BLOCK_INPUT;
851 #ifdef GC_MALLOC_CHECK
852 allocated_mem_type = type;
853 #endif
855 val = (void *) malloc (nbytes);
857 #ifndef USE_LSB_TAG
858 /* If the memory just allocated cannot be addressed thru a Lisp
859 object's pointer, and it needs to be,
860 that's equivalent to running out of memory. */
861 if (val && type != MEM_TYPE_NON_LISP)
863 Lisp_Object tem;
864 XSETCONS (tem, (char *) val + nbytes - 1);
865 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
867 lisp_malloc_loser = val;
868 free (val);
869 val = 0;
872 #endif
874 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
875 if (val && type != MEM_TYPE_NON_LISP)
876 mem_insert (val, (char *) val + nbytes, type);
877 #endif
879 UNBLOCK_INPUT;
880 if (!val && nbytes)
881 memory_full ();
882 return val;
885 /* Free BLOCK. This must be called to free memory allocated with a
886 call to lisp_malloc. */
888 static void
889 lisp_free (block)
890 POINTER_TYPE *block;
892 BLOCK_INPUT;
893 free (block);
894 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
895 mem_delete (mem_find (block));
896 #endif
897 UNBLOCK_INPUT;
900 /* Allocation of aligned blocks of memory to store Lisp data. */
901 /* The entry point is lisp_align_malloc which returns blocks of at most */
902 /* BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
904 /* Use posix_memalloc if the system has it and we're using the system's
905 malloc (because our gmalloc.c routines don't have posix_memalign although
906 its memalloc could be used). */
907 #if defined (HAVE_POSIX_MEMALIGN) && defined (SYSTEM_MALLOC)
908 #define USE_POSIX_MEMALIGN 1
909 #endif
911 /* BLOCK_ALIGN has to be a power of 2. */
912 #define BLOCK_ALIGN (1 << 10)
914 /* Padding to leave at the end of a malloc'd block. This is to give
915 malloc a chance to minimize the amount of memory wasted to alignment.
916 It should be tuned to the particular malloc library used.
917 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
918 posix_memalign on the other hand would ideally prefer a value of 4
919 because otherwise, there's 1020 bytes wasted between each ablocks.
920 In Emacs, testing shows that those 1020 can most of the time be
921 efficiently used by malloc to place other objects, so a value of 0 can
922 still preferable unless you have a lot of aligned blocks and virtually
923 nothing else. */
924 #define BLOCK_PADDING 0
925 #define BLOCK_BYTES \
926 (BLOCK_ALIGN - sizeof (struct ablock *) - BLOCK_PADDING)
928 /* Internal data structures and constants. */
930 #define ABLOCKS_SIZE 16
932 /* An aligned block of memory. */
933 struct ablock
935 union
937 char payload[BLOCK_BYTES];
938 struct ablock *next_free;
939 } x;
940 /* `abase' is the aligned base of the ablocks. */
941 /* It is overloaded to hold the virtual `busy' field that counts
942 the number of used ablock in the parent ablocks.
943 The first ablock has the `busy' field, the others have the `abase'
944 field. To tell the difference, we assume that pointers will have
945 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
946 is used to tell whether the real base of the parent ablocks is `abase'
947 (if not, the word before the first ablock holds a pointer to the
948 real base). */
949 struct ablocks *abase;
950 /* The padding of all but the last ablock is unused. The padding of
951 the last ablock in an ablocks is not allocated. */
952 #if BLOCK_PADDING
953 char padding[BLOCK_PADDING];
954 #endif
957 /* A bunch of consecutive aligned blocks. */
958 struct ablocks
960 struct ablock blocks[ABLOCKS_SIZE];
963 /* Size of the block requested from malloc or memalign. */
964 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
966 #define ABLOCK_ABASE(block) \
967 (((unsigned long) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
968 ? (struct ablocks *)(block) \
969 : (block)->abase)
971 /* Virtual `busy' field. */
972 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
974 /* Pointer to the (not necessarily aligned) malloc block. */
975 #ifdef USE_POSIX_MEMALIGN
976 #define ABLOCKS_BASE(abase) (abase)
977 #else
978 #define ABLOCKS_BASE(abase) \
979 (1 & (long) ABLOCKS_BUSY (abase) ? abase : ((void**)abase)[-1])
980 #endif
982 /* The list of free ablock. */
983 static struct ablock *free_ablock;
985 /* Allocate an aligned block of nbytes.
986 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
987 smaller or equal to BLOCK_BYTES. */
988 static POINTER_TYPE *
989 lisp_align_malloc (nbytes, type)
990 size_t nbytes;
991 enum mem_type type;
993 void *base, *val;
994 struct ablocks *abase;
996 eassert (nbytes <= BLOCK_BYTES);
998 BLOCK_INPUT;
1000 #ifdef GC_MALLOC_CHECK
1001 allocated_mem_type = type;
1002 #endif
1004 if (!free_ablock)
1006 int i;
1007 EMACS_INT aligned; /* int gets warning casting to 64-bit pointer. */
1009 #ifdef DOUG_LEA_MALLOC
1010 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1011 because mapped region contents are not preserved in
1012 a dumped Emacs. */
1013 mallopt (M_MMAP_MAX, 0);
1014 #endif
1016 #ifdef USE_POSIX_MEMALIGN
1018 int err = posix_memalign (&base, BLOCK_ALIGN, ABLOCKS_BYTES);
1019 if (err)
1020 base = NULL;
1021 abase = base;
1023 #else
1024 base = malloc (ABLOCKS_BYTES);
1025 abase = ALIGN (base, BLOCK_ALIGN);
1026 #endif
1028 if (base == 0)
1030 UNBLOCK_INPUT;
1031 memory_full ();
1034 aligned = (base == abase);
1035 if (!aligned)
1036 ((void**)abase)[-1] = base;
1038 #ifdef DOUG_LEA_MALLOC
1039 /* Back to a reasonable maximum of mmap'ed areas. */
1040 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1041 #endif
1043 #ifndef USE_LSB_TAG
1044 /* If the memory just allocated cannot be addressed thru a Lisp
1045 object's pointer, and it needs to be, that's equivalent to
1046 running out of memory. */
1047 if (type != MEM_TYPE_NON_LISP)
1049 Lisp_Object tem;
1050 char *end = (char *) base + ABLOCKS_BYTES - 1;
1051 XSETCONS (tem, end);
1052 if ((char *) XCONS (tem) != end)
1054 lisp_malloc_loser = base;
1055 free (base);
1056 UNBLOCK_INPUT;
1057 memory_full ();
1060 #endif
1062 /* Initialize the blocks and put them on the free list.
1063 Is `base' was not properly aligned, we can't use the last block. */
1064 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1066 abase->blocks[i].abase = abase;
1067 abase->blocks[i].x.next_free = free_ablock;
1068 free_ablock = &abase->blocks[i];
1070 ABLOCKS_BUSY (abase) = (struct ablocks *) (long) aligned;
1072 eassert (0 == ((EMACS_UINT)abase) % BLOCK_ALIGN);
1073 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1074 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1075 eassert (ABLOCKS_BASE (abase) == base);
1076 eassert (aligned == (long) ABLOCKS_BUSY (abase));
1079 abase = ABLOCK_ABASE (free_ablock);
1080 ABLOCKS_BUSY (abase) = (struct ablocks *) (2 + (long) ABLOCKS_BUSY (abase));
1081 val = free_ablock;
1082 free_ablock = free_ablock->x.next_free;
1084 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1085 if (val && type != MEM_TYPE_NON_LISP)
1086 mem_insert (val, (char *) val + nbytes, type);
1087 #endif
1089 UNBLOCK_INPUT;
1090 if (!val && nbytes)
1091 memory_full ();
1093 eassert (0 == ((EMACS_UINT)val) % BLOCK_ALIGN);
1094 return val;
1097 static void
1098 lisp_align_free (block)
1099 POINTER_TYPE *block;
1101 struct ablock *ablock = block;
1102 struct ablocks *abase = ABLOCK_ABASE (ablock);
1104 BLOCK_INPUT;
1105 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1106 mem_delete (mem_find (block));
1107 #endif
1108 /* Put on free list. */
1109 ablock->x.next_free = free_ablock;
1110 free_ablock = ablock;
1111 /* Update busy count. */
1112 ABLOCKS_BUSY (abase) = (struct ablocks *) (-2 + (long) ABLOCKS_BUSY (abase));
1114 if (2 > (long) ABLOCKS_BUSY (abase))
1115 { /* All the blocks are free. */
1116 int i = 0, aligned = (long) ABLOCKS_BUSY (abase);
1117 struct ablock **tem = &free_ablock;
1118 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1120 while (*tem)
1122 if (*tem >= (struct ablock *) abase && *tem < atop)
1124 i++;
1125 *tem = (*tem)->x.next_free;
1127 else
1128 tem = &(*tem)->x.next_free;
1130 eassert ((aligned & 1) == aligned);
1131 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1132 #ifdef USE_POSIX_MEMALIGN
1133 eassert ((unsigned long)ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1134 #endif
1135 free (ABLOCKS_BASE (abase));
1137 UNBLOCK_INPUT;
1140 /* Return a new buffer structure allocated from the heap with
1141 a call to lisp_malloc. */
1143 struct buffer *
1144 allocate_buffer ()
1146 struct buffer *b
1147 = (struct buffer *) lisp_malloc (sizeof (struct buffer),
1148 MEM_TYPE_BUFFER);
1149 return b;
1153 #ifndef SYSTEM_MALLOC
1155 /* Arranging to disable input signals while we're in malloc.
1157 This only works with GNU malloc. To help out systems which can't
1158 use GNU malloc, all the calls to malloc, realloc, and free
1159 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
1160 pair; unfortunately, we have no idea what C library functions
1161 might call malloc, so we can't really protect them unless you're
1162 using GNU malloc. Fortunately, most of the major operating systems
1163 can use GNU malloc. */
1165 #ifndef SYNC_INPUT
1167 #ifndef DOUG_LEA_MALLOC
1168 extern void * (*__malloc_hook) P_ ((size_t, const void *));
1169 extern void * (*__realloc_hook) P_ ((void *, size_t, const void *));
1170 extern void (*__free_hook) P_ ((void *, const void *));
1171 /* Else declared in malloc.h, perhaps with an extra arg. */
1172 #endif /* DOUG_LEA_MALLOC */
1173 static void * (*old_malloc_hook) P_ ((size_t, const void *));
1174 static void * (*old_realloc_hook) P_ ((void *, size_t, const void*));
1175 static void (*old_free_hook) P_ ((void*, const void*));
1177 /* This function is used as the hook for free to call. */
1179 static void
1180 emacs_blocked_free (ptr, ptr2)
1181 void *ptr;
1182 const void *ptr2;
1184 BLOCK_INPUT_ALLOC;
1186 #ifdef GC_MALLOC_CHECK
1187 if (ptr)
1189 struct mem_node *m;
1191 m = mem_find (ptr);
1192 if (m == MEM_NIL || m->start != ptr)
1194 fprintf (stderr,
1195 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
1196 abort ();
1198 else
1200 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
1201 mem_delete (m);
1204 #endif /* GC_MALLOC_CHECK */
1206 __free_hook = old_free_hook;
1207 free (ptr);
1209 /* If we released our reserve (due to running out of memory),
1210 and we have a fair amount free once again,
1211 try to set aside another reserve in case we run out once more. */
1212 if (! NILP (Vmemory_full)
1213 /* Verify there is enough space that even with the malloc
1214 hysteresis this call won't run out again.
1215 The code here is correct as long as SPARE_MEMORY
1216 is substantially larger than the block size malloc uses. */
1217 && (bytes_used_when_full
1218 > ((bytes_used_when_reconsidered = BYTES_USED)
1219 + max (malloc_hysteresis, 4) * SPARE_MEMORY)))
1220 refill_memory_reserve ();
1222 __free_hook = emacs_blocked_free;
1223 UNBLOCK_INPUT_ALLOC;
1227 /* This function is the malloc hook that Emacs uses. */
1229 static void *
1230 emacs_blocked_malloc (size, ptr)
1231 size_t size;
1232 const void *ptr;
1234 void *value;
1236 BLOCK_INPUT_ALLOC;
1237 __malloc_hook = old_malloc_hook;
1238 #ifdef DOUG_LEA_MALLOC
1239 /* Segfaults on my system. --lorentey */
1240 /* mallopt (M_TOP_PAD, malloc_hysteresis * 4096); */
1241 #else
1242 __malloc_extra_blocks = malloc_hysteresis;
1243 #endif
1245 value = (void *) malloc (size);
1247 #ifdef GC_MALLOC_CHECK
1249 struct mem_node *m = mem_find (value);
1250 if (m != MEM_NIL)
1252 fprintf (stderr, "Malloc returned %p which is already in use\n",
1253 value);
1254 fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
1255 m->start, m->end, (char *) m->end - (char *) m->start,
1256 m->type);
1257 abort ();
1260 if (!dont_register_blocks)
1262 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
1263 allocated_mem_type = MEM_TYPE_NON_LISP;
1266 #endif /* GC_MALLOC_CHECK */
1268 __malloc_hook = emacs_blocked_malloc;
1269 UNBLOCK_INPUT_ALLOC;
1271 /* fprintf (stderr, "%p malloc\n", value); */
1272 return value;
1276 /* This function is the realloc hook that Emacs uses. */
1278 static void *
1279 emacs_blocked_realloc (ptr, size, ptr2)
1280 void *ptr;
1281 size_t size;
1282 const void *ptr2;
1284 void *value;
1286 BLOCK_INPUT_ALLOC;
1287 __realloc_hook = old_realloc_hook;
1289 #ifdef GC_MALLOC_CHECK
1290 if (ptr)
1292 struct mem_node *m = mem_find (ptr);
1293 if (m == MEM_NIL || m->start != ptr)
1295 fprintf (stderr,
1296 "Realloc of %p which wasn't allocated with malloc\n",
1297 ptr);
1298 abort ();
1301 mem_delete (m);
1304 /* fprintf (stderr, "%p -> realloc\n", ptr); */
1306 /* Prevent malloc from registering blocks. */
1307 dont_register_blocks = 1;
1308 #endif /* GC_MALLOC_CHECK */
1310 value = (void *) realloc (ptr, size);
1312 #ifdef GC_MALLOC_CHECK
1313 dont_register_blocks = 0;
1316 struct mem_node *m = mem_find (value);
1317 if (m != MEM_NIL)
1319 fprintf (stderr, "Realloc returns memory that is already in use\n");
1320 abort ();
1323 /* Can't handle zero size regions in the red-black tree. */
1324 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
1327 /* fprintf (stderr, "%p <- realloc\n", value); */
1328 #endif /* GC_MALLOC_CHECK */
1330 __realloc_hook = emacs_blocked_realloc;
1331 UNBLOCK_INPUT_ALLOC;
1333 return value;
1337 #ifdef HAVE_GTK_AND_PTHREAD
1338 /* Called from Fdump_emacs so that when the dumped Emacs starts, it has a
1339 normal malloc. Some thread implementations need this as they call
1340 malloc before main. The pthread_self call in BLOCK_INPUT_ALLOC then
1341 calls malloc because it is the first call, and we have an endless loop. */
1343 void
1344 reset_malloc_hooks ()
1346 __free_hook = 0;
1347 __malloc_hook = 0;
1348 __realloc_hook = 0;
1350 #endif /* HAVE_GTK_AND_PTHREAD */
1353 /* Called from main to set up malloc to use our hooks. */
1355 void
1356 uninterrupt_malloc ()
1358 #ifdef HAVE_GTK_AND_PTHREAD
1359 pthread_mutexattr_t attr;
1361 /* GLIBC has a faster way to do this, but lets keep it portable.
1362 This is according to the Single UNIX Specification. */
1363 pthread_mutexattr_init (&attr);
1364 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1365 pthread_mutex_init (&alloc_mutex, &attr);
1366 #endif /* HAVE_GTK_AND_PTHREAD */
1368 if (__free_hook != emacs_blocked_free)
1369 old_free_hook = __free_hook;
1370 __free_hook = emacs_blocked_free;
1372 if (__malloc_hook != emacs_blocked_malloc)
1373 old_malloc_hook = __malloc_hook;
1374 __malloc_hook = emacs_blocked_malloc;
1376 if (__realloc_hook != emacs_blocked_realloc)
1377 old_realloc_hook = __realloc_hook;
1378 __realloc_hook = emacs_blocked_realloc;
1381 #endif /* not SYNC_INPUT */
1382 #endif /* not SYSTEM_MALLOC */
1386 /***********************************************************************
1387 Interval Allocation
1388 ***********************************************************************/
1390 /* Number of intervals allocated in an interval_block structure.
1391 The 1020 is 1024 minus malloc overhead. */
1393 #define INTERVAL_BLOCK_SIZE \
1394 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1396 /* Intervals are allocated in chunks in form of an interval_block
1397 structure. */
1399 struct interval_block
1401 /* Place `intervals' first, to preserve alignment. */
1402 struct interval intervals[INTERVAL_BLOCK_SIZE];
1403 struct interval_block *next;
1406 /* Current interval block. Its `next' pointer points to older
1407 blocks. */
1409 struct interval_block *interval_block;
1411 /* Index in interval_block above of the next unused interval
1412 structure. */
1414 static int interval_block_index;
1416 /* Number of free and live intervals. */
1418 static int total_free_intervals, total_intervals;
1420 /* List of free intervals. */
1422 INTERVAL interval_free_list;
1424 /* Total number of interval blocks now in use. */
1426 int n_interval_blocks;
1429 /* Initialize interval allocation. */
1431 static void
1432 init_intervals ()
1434 interval_block = NULL;
1435 interval_block_index = INTERVAL_BLOCK_SIZE;
1436 interval_free_list = 0;
1437 n_interval_blocks = 0;
1441 /* Return a new interval. */
1443 INTERVAL
1444 make_interval ()
1446 INTERVAL val;
1448 /* eassert (!handling_signal); */
1450 #ifndef SYNC_INPUT
1451 BLOCK_INPUT;
1452 #endif
1454 if (interval_free_list)
1456 val = interval_free_list;
1457 interval_free_list = INTERVAL_PARENT (interval_free_list);
1459 else
1461 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1463 register struct interval_block *newi;
1465 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
1466 MEM_TYPE_NON_LISP);
1468 newi->next = interval_block;
1469 interval_block = newi;
1470 interval_block_index = 0;
1471 n_interval_blocks++;
1473 val = &interval_block->intervals[interval_block_index++];
1476 #ifndef SYNC_INPUT
1477 UNBLOCK_INPUT;
1478 #endif
1480 consing_since_gc += sizeof (struct interval);
1481 intervals_consed++;
1482 RESET_INTERVAL (val);
1483 val->gcmarkbit = 0;
1484 return val;
1488 /* Mark Lisp objects in interval I. */
1490 static void
1491 mark_interval (i, dummy)
1492 register INTERVAL i;
1493 Lisp_Object dummy;
1495 eassert (!i->gcmarkbit); /* Intervals are never shared. */
1496 i->gcmarkbit = 1;
1497 mark_object (i->plist);
1501 /* Mark the interval tree rooted in TREE. Don't call this directly;
1502 use the macro MARK_INTERVAL_TREE instead. */
1504 static void
1505 mark_interval_tree (tree)
1506 register INTERVAL tree;
1508 /* No need to test if this tree has been marked already; this
1509 function is always called through the MARK_INTERVAL_TREE macro,
1510 which takes care of that. */
1512 traverse_intervals_noorder (tree, mark_interval, Qnil);
1516 /* Mark the interval tree rooted in I. */
1518 #define MARK_INTERVAL_TREE(i) \
1519 do { \
1520 if (!NULL_INTERVAL_P (i) && !i->gcmarkbit) \
1521 mark_interval_tree (i); \
1522 } while (0)
1525 #define UNMARK_BALANCE_INTERVALS(i) \
1526 do { \
1527 if (! NULL_INTERVAL_P (i)) \
1528 (i) = balance_intervals (i); \
1529 } while (0)
1532 /* Number support. If NO_UNION_TYPE isn't in effect, we
1533 can't create number objects in macros. */
1534 #ifndef make_number
1535 Lisp_Object
1536 make_number (n)
1537 EMACS_INT n;
1539 Lisp_Object obj;
1540 obj.s.val = n;
1541 obj.s.type = Lisp_Int;
1542 return obj;
1544 #endif
1546 /***********************************************************************
1547 String Allocation
1548 ***********************************************************************/
1550 /* Lisp_Strings are allocated in string_block structures. When a new
1551 string_block is allocated, all the Lisp_Strings it contains are
1552 added to a free-list string_free_list. When a new Lisp_String is
1553 needed, it is taken from that list. During the sweep phase of GC,
1554 string_blocks that are entirely free are freed, except two which
1555 we keep.
1557 String data is allocated from sblock structures. Strings larger
1558 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1559 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1561 Sblocks consist internally of sdata structures, one for each
1562 Lisp_String. The sdata structure points to the Lisp_String it
1563 belongs to. The Lisp_String points back to the `u.data' member of
1564 its sdata structure.
1566 When a Lisp_String is freed during GC, it is put back on
1567 string_free_list, and its `data' member and its sdata's `string'
1568 pointer is set to null. The size of the string is recorded in the
1569 `u.nbytes' member of the sdata. So, sdata structures that are no
1570 longer used, can be easily recognized, and it's easy to compact the
1571 sblocks of small strings which we do in compact_small_strings. */
1573 /* Size in bytes of an sblock structure used for small strings. This
1574 is 8192 minus malloc overhead. */
1576 #define SBLOCK_SIZE 8188
1578 /* Strings larger than this are considered large strings. String data
1579 for large strings is allocated from individual sblocks. */
1581 #define LARGE_STRING_BYTES 1024
1583 /* Structure describing string memory sub-allocated from an sblock.
1584 This is where the contents of Lisp strings are stored. */
1586 struct sdata
1588 /* Back-pointer to the string this sdata belongs to. If null, this
1589 structure is free, and the NBYTES member of the union below
1590 contains the string's byte size (the same value that STRING_BYTES
1591 would return if STRING were non-null). If non-null, STRING_BYTES
1592 (STRING) is the size of the data, and DATA contains the string's
1593 contents. */
1594 struct Lisp_String *string;
1596 #ifdef GC_CHECK_STRING_BYTES
1598 EMACS_INT nbytes;
1599 unsigned char data[1];
1601 #define SDATA_NBYTES(S) (S)->nbytes
1602 #define SDATA_DATA(S) (S)->data
1604 #else /* not GC_CHECK_STRING_BYTES */
1606 union
1608 /* When STRING in non-null. */
1609 unsigned char data[1];
1611 /* When STRING is null. */
1612 EMACS_INT nbytes;
1613 } u;
1616 #define SDATA_NBYTES(S) (S)->u.nbytes
1617 #define SDATA_DATA(S) (S)->u.data
1619 #endif /* not GC_CHECK_STRING_BYTES */
1623 /* Structure describing a block of memory which is sub-allocated to
1624 obtain string data memory for strings. Blocks for small strings
1625 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1626 as large as needed. */
1628 struct sblock
1630 /* Next in list. */
1631 struct sblock *next;
1633 /* Pointer to the next free sdata block. This points past the end
1634 of the sblock if there isn't any space left in this block. */
1635 struct sdata *next_free;
1637 /* Start of data. */
1638 struct sdata first_data;
1641 /* Number of Lisp strings in a string_block structure. The 1020 is
1642 1024 minus malloc overhead. */
1644 #define STRING_BLOCK_SIZE \
1645 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1647 /* Structure describing a block from which Lisp_String structures
1648 are allocated. */
1650 struct string_block
1652 /* Place `strings' first, to preserve alignment. */
1653 struct Lisp_String strings[STRING_BLOCK_SIZE];
1654 struct string_block *next;
1657 /* Head and tail of the list of sblock structures holding Lisp string
1658 data. We always allocate from current_sblock. The NEXT pointers
1659 in the sblock structures go from oldest_sblock to current_sblock. */
1661 static struct sblock *oldest_sblock, *current_sblock;
1663 /* List of sblocks for large strings. */
1665 static struct sblock *large_sblocks;
1667 /* List of string_block structures, and how many there are. */
1669 static struct string_block *string_blocks;
1670 static int n_string_blocks;
1672 /* Free-list of Lisp_Strings. */
1674 static struct Lisp_String *string_free_list;
1676 /* Number of live and free Lisp_Strings. */
1678 static int total_strings, total_free_strings;
1680 /* Number of bytes used by live strings. */
1682 static int total_string_size;
1684 /* Given a pointer to a Lisp_String S which is on the free-list
1685 string_free_list, return a pointer to its successor in the
1686 free-list. */
1688 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1690 /* Return a pointer to the sdata structure belonging to Lisp string S.
1691 S must be live, i.e. S->data must not be null. S->data is actually
1692 a pointer to the `u.data' member of its sdata structure; the
1693 structure starts at a constant offset in front of that. */
1695 #ifdef GC_CHECK_STRING_BYTES
1697 #define SDATA_OF_STRING(S) \
1698 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *) \
1699 - sizeof (EMACS_INT)))
1701 #else /* not GC_CHECK_STRING_BYTES */
1703 #define SDATA_OF_STRING(S) \
1704 ((struct sdata *) ((S)->data - sizeof (struct Lisp_String *)))
1706 #endif /* not GC_CHECK_STRING_BYTES */
1709 #ifdef GC_CHECK_STRING_OVERRUN
1711 /* We check for overrun in string data blocks by appending a small
1712 "cookie" after each allocated string data block, and check for the
1713 presence of this cookie during GC. */
1715 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1716 static char string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1717 { 0xde, 0xad, 0xbe, 0xef };
1719 #else
1720 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1721 #endif
1723 /* Value is the size of an sdata structure large enough to hold NBYTES
1724 bytes of string data. The value returned includes a terminating
1725 NUL byte, the size of the sdata structure, and padding. */
1727 #ifdef GC_CHECK_STRING_BYTES
1729 #define SDATA_SIZE(NBYTES) \
1730 ((sizeof (struct Lisp_String *) \
1731 + (NBYTES) + 1 \
1732 + sizeof (EMACS_INT) \
1733 + sizeof (EMACS_INT) - 1) \
1734 & ~(sizeof (EMACS_INT) - 1))
1736 #else /* not GC_CHECK_STRING_BYTES */
1738 #define SDATA_SIZE(NBYTES) \
1739 ((sizeof (struct Lisp_String *) \
1740 + (NBYTES) + 1 \
1741 + sizeof (EMACS_INT) - 1) \
1742 & ~(sizeof (EMACS_INT) - 1))
1744 #endif /* not GC_CHECK_STRING_BYTES */
1746 /* Extra bytes to allocate for each string. */
1748 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1750 /* Initialize string allocation. Called from init_alloc_once. */
1752 void
1753 init_strings ()
1755 total_strings = total_free_strings = total_string_size = 0;
1756 oldest_sblock = current_sblock = large_sblocks = NULL;
1757 string_blocks = NULL;
1758 n_string_blocks = 0;
1759 string_free_list = NULL;
1760 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1761 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1765 #ifdef GC_CHECK_STRING_BYTES
1767 static int check_string_bytes_count;
1769 void check_string_bytes P_ ((int));
1770 void check_sblock P_ ((struct sblock *));
1772 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1775 /* Like GC_STRING_BYTES, but with debugging check. */
1778 string_bytes (s)
1779 struct Lisp_String *s;
1781 int nbytes = (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1782 if (!PURE_POINTER_P (s)
1783 && s->data
1784 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1785 abort ();
1786 return nbytes;
1789 /* Check validity of Lisp strings' string_bytes member in B. */
1791 void
1792 check_sblock (b)
1793 struct sblock *b;
1795 struct sdata *from, *end, *from_end;
1797 end = b->next_free;
1799 for (from = &b->first_data; from < end; from = from_end)
1801 /* Compute the next FROM here because copying below may
1802 overwrite data we need to compute it. */
1803 int nbytes;
1805 /* Check that the string size recorded in the string is the
1806 same as the one recorded in the sdata structure. */
1807 if (from->string)
1808 CHECK_STRING_BYTES (from->string);
1810 if (from->string)
1811 nbytes = GC_STRING_BYTES (from->string);
1812 else
1813 nbytes = SDATA_NBYTES (from);
1815 nbytes = SDATA_SIZE (nbytes);
1816 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1821 /* Check validity of Lisp strings' string_bytes member. ALL_P
1822 non-zero means check all strings, otherwise check only most
1823 recently allocated strings. Used for hunting a bug. */
1825 void
1826 check_string_bytes (all_p)
1827 int all_p;
1829 if (all_p)
1831 struct sblock *b;
1833 for (b = large_sblocks; b; b = b->next)
1835 struct Lisp_String *s = b->first_data.string;
1836 if (s)
1837 CHECK_STRING_BYTES (s);
1840 for (b = oldest_sblock; b; b = b->next)
1841 check_sblock (b);
1843 else
1844 check_sblock (current_sblock);
1847 #endif /* GC_CHECK_STRING_BYTES */
1849 #ifdef GC_CHECK_STRING_FREE_LIST
1851 /* Walk through the string free list looking for bogus next pointers.
1852 This may catch buffer overrun from a previous string. */
1854 static void
1855 check_string_free_list ()
1857 struct Lisp_String *s;
1859 /* Pop a Lisp_String off the free-list. */
1860 s = string_free_list;
1861 while (s != NULL)
1863 if ((unsigned)s < 1024)
1864 abort();
1865 s = NEXT_FREE_LISP_STRING (s);
1868 #else
1869 #define check_string_free_list()
1870 #endif
1872 /* Return a new Lisp_String. */
1874 static struct Lisp_String *
1875 allocate_string ()
1877 struct Lisp_String *s;
1879 /* eassert (!handling_signal); */
1881 #ifndef SYNC_INPUT
1882 BLOCK_INPUT;
1883 #endif
1885 /* If the free-list is empty, allocate a new string_block, and
1886 add all the Lisp_Strings in it to the free-list. */
1887 if (string_free_list == NULL)
1889 struct string_block *b;
1890 int i;
1892 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1893 bzero (b, sizeof *b);
1894 b->next = string_blocks;
1895 string_blocks = b;
1896 ++n_string_blocks;
1898 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1900 s = b->strings + i;
1901 NEXT_FREE_LISP_STRING (s) = string_free_list;
1902 string_free_list = s;
1905 total_free_strings += STRING_BLOCK_SIZE;
1908 check_string_free_list ();
1910 /* Pop a Lisp_String off the free-list. */
1911 s = string_free_list;
1912 string_free_list = NEXT_FREE_LISP_STRING (s);
1914 #ifndef SYNC_INPUT
1915 UNBLOCK_INPUT;
1916 #endif
1918 /* Probably not strictly necessary, but play it safe. */
1919 bzero (s, sizeof *s);
1921 --total_free_strings;
1922 ++total_strings;
1923 ++strings_consed;
1924 consing_since_gc += sizeof *s;
1926 #ifdef GC_CHECK_STRING_BYTES
1927 if (!noninteractive
1928 #ifdef MAC_OS8
1929 && current_sblock
1930 #endif
1933 if (++check_string_bytes_count == 200)
1935 check_string_bytes_count = 0;
1936 check_string_bytes (1);
1938 else
1939 check_string_bytes (0);
1941 #endif /* GC_CHECK_STRING_BYTES */
1943 return s;
1947 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1948 plus a NUL byte at the end. Allocate an sdata structure for S, and
1949 set S->data to its `u.data' member. Store a NUL byte at the end of
1950 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1951 S->data if it was initially non-null. */
1953 void
1954 allocate_string_data (s, nchars, nbytes)
1955 struct Lisp_String *s;
1956 int nchars, nbytes;
1958 struct sdata *data, *old_data;
1959 struct sblock *b;
1960 int needed, old_nbytes;
1962 /* Determine the number of bytes needed to store NBYTES bytes
1963 of string data. */
1964 needed = SDATA_SIZE (nbytes);
1965 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1966 old_nbytes = GC_STRING_BYTES (s);
1968 #ifndef SYNC_INPUT
1969 BLOCK_INPUT;
1970 #endif
1972 if (nbytes > LARGE_STRING_BYTES)
1974 size_t size = sizeof *b - sizeof (struct sdata) + needed;
1976 #ifdef DOUG_LEA_MALLOC
1977 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1978 because mapped region contents are not preserved in
1979 a dumped Emacs.
1981 In case you think of allowing it in a dumped Emacs at the
1982 cost of not being able to re-dump, there's another reason:
1983 mmap'ed data typically have an address towards the top of the
1984 address space, which won't fit into an EMACS_INT (at least on
1985 32-bit systems with the current tagging scheme). --fx */
1986 BLOCK_INPUT;
1987 mallopt (M_MMAP_MAX, 0);
1988 UNBLOCK_INPUT;
1989 #endif
1991 b = (struct sblock *) lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
1993 #ifdef DOUG_LEA_MALLOC
1994 /* Back to a reasonable maximum of mmap'ed areas. */
1995 BLOCK_INPUT;
1996 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1997 UNBLOCK_INPUT;
1998 #endif
2000 b->next_free = &b->first_data;
2001 b->first_data.string = NULL;
2002 b->next = large_sblocks;
2003 large_sblocks = b;
2005 else if (current_sblock == NULL
2006 || (((char *) current_sblock + SBLOCK_SIZE
2007 - (char *) current_sblock->next_free)
2008 < (needed + GC_STRING_EXTRA)))
2010 /* Not enough room in the current sblock. */
2011 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
2012 b->next_free = &b->first_data;
2013 b->first_data.string = NULL;
2014 b->next = NULL;
2016 if (current_sblock)
2017 current_sblock->next = b;
2018 else
2019 oldest_sblock = b;
2020 current_sblock = b;
2022 else
2023 b = current_sblock;
2025 data = b->next_free;
2026 b->next_free = (struct sdata *) ((char *) data + needed + GC_STRING_EXTRA);
2028 #ifndef SYNC_INPUT
2029 UNBLOCK_INPUT;
2030 #endif
2032 data->string = s;
2033 s->data = SDATA_DATA (data);
2034 #ifdef GC_CHECK_STRING_BYTES
2035 SDATA_NBYTES (data) = nbytes;
2036 #endif
2037 s->size = nchars;
2038 s->size_byte = nbytes;
2039 s->data[nbytes] = '\0';
2040 #ifdef GC_CHECK_STRING_OVERRUN
2041 bcopy (string_overrun_cookie, (char *) data + needed,
2042 GC_STRING_OVERRUN_COOKIE_SIZE);
2043 #endif
2045 /* If S had already data assigned, mark that as free by setting its
2046 string back-pointer to null, and recording the size of the data
2047 in it. */
2048 if (old_data)
2050 SDATA_NBYTES (old_data) = old_nbytes;
2051 old_data->string = NULL;
2054 consing_since_gc += needed;
2058 /* Sweep and compact strings. */
2060 static void
2061 sweep_strings ()
2063 struct string_block *b, *next;
2064 struct string_block *live_blocks = NULL;
2066 string_free_list = NULL;
2067 total_strings = total_free_strings = 0;
2068 total_string_size = 0;
2070 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
2071 for (b = string_blocks; b; b = next)
2073 int i, nfree = 0;
2074 struct Lisp_String *free_list_before = string_free_list;
2076 next = b->next;
2078 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
2080 struct Lisp_String *s = b->strings + i;
2082 if (s->data)
2084 /* String was not on free-list before. */
2085 if (STRING_MARKED_P (s))
2087 /* String is live; unmark it and its intervals. */
2088 UNMARK_STRING (s);
2090 if (!NULL_INTERVAL_P (s->intervals))
2091 UNMARK_BALANCE_INTERVALS (s->intervals);
2093 ++total_strings;
2094 total_string_size += STRING_BYTES (s);
2096 else
2098 /* String is dead. Put it on the free-list. */
2099 struct sdata *data = SDATA_OF_STRING (s);
2101 /* Save the size of S in its sdata so that we know
2102 how large that is. Reset the sdata's string
2103 back-pointer so that we know it's free. */
2104 #ifdef GC_CHECK_STRING_BYTES
2105 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
2106 abort ();
2107 #else
2108 data->u.nbytes = GC_STRING_BYTES (s);
2109 #endif
2110 data->string = NULL;
2112 /* Reset the strings's `data' member so that we
2113 know it's free. */
2114 s->data = NULL;
2116 /* Put the string on the free-list. */
2117 NEXT_FREE_LISP_STRING (s) = string_free_list;
2118 string_free_list = s;
2119 ++nfree;
2122 else
2124 /* S was on the free-list before. Put it there again. */
2125 NEXT_FREE_LISP_STRING (s) = string_free_list;
2126 string_free_list = s;
2127 ++nfree;
2131 /* Free blocks that contain free Lisp_Strings only, except
2132 the first two of them. */
2133 if (nfree == STRING_BLOCK_SIZE
2134 && total_free_strings > STRING_BLOCK_SIZE)
2136 lisp_free (b);
2137 --n_string_blocks;
2138 string_free_list = free_list_before;
2140 else
2142 total_free_strings += nfree;
2143 b->next = live_blocks;
2144 live_blocks = b;
2148 check_string_free_list ();
2150 string_blocks = live_blocks;
2151 free_large_strings ();
2152 compact_small_strings ();
2154 check_string_free_list ();
2158 /* Free dead large strings. */
2160 static void
2161 free_large_strings ()
2163 struct sblock *b, *next;
2164 struct sblock *live_blocks = NULL;
2166 for (b = large_sblocks; b; b = next)
2168 next = b->next;
2170 if (b->first_data.string == NULL)
2171 lisp_free (b);
2172 else
2174 b->next = live_blocks;
2175 live_blocks = b;
2179 large_sblocks = live_blocks;
2183 /* Compact data of small strings. Free sblocks that don't contain
2184 data of live strings after compaction. */
2186 static void
2187 compact_small_strings ()
2189 struct sblock *b, *tb, *next;
2190 struct sdata *from, *to, *end, *tb_end;
2191 struct sdata *to_end, *from_end;
2193 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2194 to, and TB_END is the end of TB. */
2195 tb = oldest_sblock;
2196 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2197 to = &tb->first_data;
2199 /* Step through the blocks from the oldest to the youngest. We
2200 expect that old blocks will stabilize over time, so that less
2201 copying will happen this way. */
2202 for (b = oldest_sblock; b; b = b->next)
2204 end = b->next_free;
2205 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2207 for (from = &b->first_data; from < end; from = from_end)
2209 /* Compute the next FROM here because copying below may
2210 overwrite data we need to compute it. */
2211 int nbytes;
2213 #ifdef GC_CHECK_STRING_BYTES
2214 /* Check that the string size recorded in the string is the
2215 same as the one recorded in the sdata structure. */
2216 if (from->string
2217 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
2218 abort ();
2219 #endif /* GC_CHECK_STRING_BYTES */
2221 if (from->string)
2222 nbytes = GC_STRING_BYTES (from->string);
2223 else
2224 nbytes = SDATA_NBYTES (from);
2226 if (nbytes > LARGE_STRING_BYTES)
2227 abort ();
2229 nbytes = SDATA_SIZE (nbytes);
2230 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
2232 #ifdef GC_CHECK_STRING_OVERRUN
2233 if (bcmp (string_overrun_cookie,
2234 ((char *) from_end) - GC_STRING_OVERRUN_COOKIE_SIZE,
2235 GC_STRING_OVERRUN_COOKIE_SIZE))
2236 abort ();
2237 #endif
2239 /* FROM->string non-null means it's alive. Copy its data. */
2240 if (from->string)
2242 /* If TB is full, proceed with the next sblock. */
2243 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2244 if (to_end > tb_end)
2246 tb->next_free = to;
2247 tb = tb->next;
2248 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2249 to = &tb->first_data;
2250 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2253 /* Copy, and update the string's `data' pointer. */
2254 if (from != to)
2256 xassert (tb != b || to <= from);
2257 safe_bcopy ((char *) from, (char *) to, nbytes + GC_STRING_EXTRA);
2258 to->string->data = SDATA_DATA (to);
2261 /* Advance past the sdata we copied to. */
2262 to = to_end;
2267 /* The rest of the sblocks following TB don't contain live data, so
2268 we can free them. */
2269 for (b = tb->next; b; b = next)
2271 next = b->next;
2272 lisp_free (b);
2275 tb->next_free = to;
2276 tb->next = NULL;
2277 current_sblock = tb;
2281 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2282 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2283 LENGTH must be an integer.
2284 INIT must be an integer that represents a character. */)
2285 (length, init)
2286 Lisp_Object length, init;
2288 register Lisp_Object val;
2289 register unsigned char *p, *end;
2290 int c, nbytes;
2292 CHECK_NATNUM (length);
2293 CHECK_NUMBER (init);
2295 c = XINT (init);
2296 if (SINGLE_BYTE_CHAR_P (c))
2298 nbytes = XINT (length);
2299 val = make_uninit_string (nbytes);
2300 p = SDATA (val);
2301 end = p + SCHARS (val);
2302 while (p != end)
2303 *p++ = c;
2305 else
2307 unsigned char str[MAX_MULTIBYTE_LENGTH];
2308 int len = CHAR_STRING (c, str);
2310 nbytes = len * XINT (length);
2311 val = make_uninit_multibyte_string (XINT (length), nbytes);
2312 p = SDATA (val);
2313 end = p + nbytes;
2314 while (p != end)
2316 bcopy (str, p, len);
2317 p += len;
2321 *p = 0;
2322 return val;
2326 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2327 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2328 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2329 (length, init)
2330 Lisp_Object length, init;
2332 register Lisp_Object val;
2333 struct Lisp_Bool_Vector *p;
2334 int real_init, i;
2335 int length_in_chars, length_in_elts, bits_per_value;
2337 CHECK_NATNUM (length);
2339 bits_per_value = sizeof (EMACS_INT) * BOOL_VECTOR_BITS_PER_CHAR;
2341 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
2342 length_in_chars = ((XFASTINT (length) + BOOL_VECTOR_BITS_PER_CHAR - 1)
2343 / BOOL_VECTOR_BITS_PER_CHAR);
2345 /* We must allocate one more elements than LENGTH_IN_ELTS for the
2346 slot `size' of the struct Lisp_Bool_Vector. */
2347 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
2348 p = XBOOL_VECTOR (val);
2350 /* Get rid of any bits that would cause confusion. */
2351 p->vector_size = 0;
2352 XSETBOOL_VECTOR (val, p);
2353 p->size = XFASTINT (length);
2355 real_init = (NILP (init) ? 0 : -1);
2356 for (i = 0; i < length_in_chars ; i++)
2357 p->data[i] = real_init;
2359 /* Clear the extraneous bits in the last byte. */
2360 if (XINT (length) != length_in_chars * BOOL_VECTOR_BITS_PER_CHAR)
2361 XBOOL_VECTOR (val)->data[length_in_chars - 1]
2362 &= (1 << (XINT (length) % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2364 return val;
2368 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2369 of characters from the contents. This string may be unibyte or
2370 multibyte, depending on the contents. */
2372 Lisp_Object
2373 make_string (contents, nbytes)
2374 const char *contents;
2375 int nbytes;
2377 register Lisp_Object val;
2378 int nchars, multibyte_nbytes;
2380 parse_str_as_multibyte (contents, nbytes, &nchars, &multibyte_nbytes);
2381 if (nbytes == nchars || nbytes != multibyte_nbytes)
2382 /* CONTENTS contains no multibyte sequences or contains an invalid
2383 multibyte sequence. We must make unibyte string. */
2384 val = make_unibyte_string (contents, nbytes);
2385 else
2386 val = make_multibyte_string (contents, nchars, nbytes);
2387 return val;
2391 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
2393 Lisp_Object
2394 make_unibyte_string (contents, length)
2395 const char *contents;
2396 int length;
2398 register Lisp_Object val;
2399 val = make_uninit_string (length);
2400 bcopy (contents, SDATA (val), length);
2401 STRING_SET_UNIBYTE (val);
2402 return val;
2406 /* Make a multibyte string from NCHARS characters occupying NBYTES
2407 bytes at CONTENTS. */
2409 Lisp_Object
2410 make_multibyte_string (contents, nchars, nbytes)
2411 const char *contents;
2412 int nchars, nbytes;
2414 register Lisp_Object val;
2415 val = make_uninit_multibyte_string (nchars, nbytes);
2416 bcopy (contents, SDATA (val), nbytes);
2417 return val;
2421 /* Make a string from NCHARS characters occupying NBYTES bytes at
2422 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2424 Lisp_Object
2425 make_string_from_bytes (contents, nchars, nbytes)
2426 const char *contents;
2427 int nchars, nbytes;
2429 register Lisp_Object val;
2430 val = make_uninit_multibyte_string (nchars, nbytes);
2431 bcopy (contents, SDATA (val), nbytes);
2432 if (SBYTES (val) == SCHARS (val))
2433 STRING_SET_UNIBYTE (val);
2434 return val;
2438 /* Make a string from NCHARS characters occupying NBYTES bytes at
2439 CONTENTS. The argument MULTIBYTE controls whether to label the
2440 string as multibyte. If NCHARS is negative, it counts the number of
2441 characters by itself. */
2443 Lisp_Object
2444 make_specified_string (contents, nchars, nbytes, multibyte)
2445 const char *contents;
2446 int nchars, nbytes;
2447 int multibyte;
2449 register Lisp_Object val;
2451 if (nchars < 0)
2453 if (multibyte)
2454 nchars = multibyte_chars_in_text (contents, nbytes);
2455 else
2456 nchars = nbytes;
2458 val = make_uninit_multibyte_string (nchars, nbytes);
2459 bcopy (contents, SDATA (val), nbytes);
2460 if (!multibyte)
2461 STRING_SET_UNIBYTE (val);
2462 return val;
2466 /* Make a string from the data at STR, treating it as multibyte if the
2467 data warrants. */
2469 Lisp_Object
2470 build_string (str)
2471 const char *str;
2473 return make_string (str, strlen (str));
2477 /* Return an unibyte Lisp_String set up to hold LENGTH characters
2478 occupying LENGTH bytes. */
2480 Lisp_Object
2481 make_uninit_string (length)
2482 int length;
2484 Lisp_Object val;
2486 if (!length)
2487 return empty_unibyte_string;
2488 val = make_uninit_multibyte_string (length, length);
2489 STRING_SET_UNIBYTE (val);
2490 return val;
2494 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2495 which occupy NBYTES bytes. */
2497 Lisp_Object
2498 make_uninit_multibyte_string (nchars, nbytes)
2499 int nchars, nbytes;
2501 Lisp_Object string;
2502 struct Lisp_String *s;
2504 if (nchars < 0)
2505 abort ();
2506 if (!nbytes)
2507 return empty_multibyte_string;
2509 s = allocate_string ();
2510 allocate_string_data (s, nchars, nbytes);
2511 XSETSTRING (string, s);
2512 string_chars_consed += nbytes;
2513 return string;
2518 /***********************************************************************
2519 Float Allocation
2520 ***********************************************************************/
2522 /* We store float cells inside of float_blocks, allocating a new
2523 float_block with malloc whenever necessary. Float cells reclaimed
2524 by GC are put on a free list to be reallocated before allocating
2525 any new float cells from the latest float_block. */
2527 #define FLOAT_BLOCK_SIZE \
2528 (((BLOCK_BYTES - sizeof (struct float_block *) \
2529 /* The compiler might add padding at the end. */ \
2530 - (sizeof (struct Lisp_Float) - sizeof (int))) * CHAR_BIT) \
2531 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2533 #define GETMARKBIT(block,n) \
2534 (((block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2535 >> ((n) % (sizeof(int) * CHAR_BIT))) \
2536 & 1)
2538 #define SETMARKBIT(block,n) \
2539 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2540 |= 1 << ((n) % (sizeof(int) * CHAR_BIT))
2542 #define UNSETMARKBIT(block,n) \
2543 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2544 &= ~(1 << ((n) % (sizeof(int) * CHAR_BIT)))
2546 #define FLOAT_BLOCK(fptr) \
2547 ((struct float_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
2549 #define FLOAT_INDEX(fptr) \
2550 ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2552 struct float_block
2554 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2555 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2556 int gcmarkbits[1 + FLOAT_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
2557 struct float_block *next;
2560 #define FLOAT_MARKED_P(fptr) \
2561 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2563 #define FLOAT_MARK(fptr) \
2564 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2566 #define FLOAT_UNMARK(fptr) \
2567 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2569 /* Current float_block. */
2571 struct float_block *float_block;
2573 /* Index of first unused Lisp_Float in the current float_block. */
2575 int float_block_index;
2577 /* Total number of float blocks now in use. */
2579 int n_float_blocks;
2581 /* Free-list of Lisp_Floats. */
2583 struct Lisp_Float *float_free_list;
2586 /* Initialize float allocation. */
2588 void
2589 init_float ()
2591 float_block = NULL;
2592 float_block_index = FLOAT_BLOCK_SIZE; /* Force alloc of new float_block. */
2593 float_free_list = 0;
2594 n_float_blocks = 0;
2598 /* Explicitly free a float cell by putting it on the free-list. */
2600 void
2601 free_float (ptr)
2602 struct Lisp_Float *ptr;
2604 ptr->u.chain = float_free_list;
2605 float_free_list = ptr;
2609 /* Return a new float object with value FLOAT_VALUE. */
2611 Lisp_Object
2612 make_float (float_value)
2613 double float_value;
2615 register Lisp_Object val;
2617 /* eassert (!handling_signal); */
2619 #ifndef SYNC_INPUT
2620 BLOCK_INPUT;
2621 #endif
2623 if (float_free_list)
2625 /* We use the data field for chaining the free list
2626 so that we won't use the same field that has the mark bit. */
2627 XSETFLOAT (val, float_free_list);
2628 float_free_list = float_free_list->u.chain;
2630 else
2632 if (float_block_index == FLOAT_BLOCK_SIZE)
2634 register struct float_block *new;
2636 new = (struct float_block *) lisp_align_malloc (sizeof *new,
2637 MEM_TYPE_FLOAT);
2638 new->next = float_block;
2639 bzero ((char *) new->gcmarkbits, sizeof new->gcmarkbits);
2640 float_block = new;
2641 float_block_index = 0;
2642 n_float_blocks++;
2644 XSETFLOAT (val, &float_block->floats[float_block_index]);
2645 float_block_index++;
2648 #ifndef SYNC_INPUT
2649 UNBLOCK_INPUT;
2650 #endif
2652 XFLOAT_DATA (val) = float_value;
2653 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2654 consing_since_gc += sizeof (struct Lisp_Float);
2655 floats_consed++;
2656 return val;
2661 /***********************************************************************
2662 Cons Allocation
2663 ***********************************************************************/
2665 /* We store cons cells inside of cons_blocks, allocating a new
2666 cons_block with malloc whenever necessary. Cons cells reclaimed by
2667 GC are put on a free list to be reallocated before allocating
2668 any new cons cells from the latest cons_block. */
2670 #define CONS_BLOCK_SIZE \
2671 (((BLOCK_BYTES - sizeof (struct cons_block *)) * CHAR_BIT) \
2672 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2674 #define CONS_BLOCK(fptr) \
2675 ((struct cons_block *)(((EMACS_UINT)(fptr)) & ~(BLOCK_ALIGN - 1)))
2677 #define CONS_INDEX(fptr) \
2678 ((((EMACS_UINT)(fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2680 struct cons_block
2682 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2683 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2684 int gcmarkbits[1 + CONS_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
2685 struct cons_block *next;
2688 #define CONS_MARKED_P(fptr) \
2689 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2691 #define CONS_MARK(fptr) \
2692 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2694 #define CONS_UNMARK(fptr) \
2695 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2697 /* Current cons_block. */
2699 struct cons_block *cons_block;
2701 /* Index of first unused Lisp_Cons in the current block. */
2703 int cons_block_index;
2705 /* Free-list of Lisp_Cons structures. */
2707 struct Lisp_Cons *cons_free_list;
2709 /* Total number of cons blocks now in use. */
2711 int n_cons_blocks;
2714 /* Initialize cons allocation. */
2716 void
2717 init_cons ()
2719 cons_block = NULL;
2720 cons_block_index = CONS_BLOCK_SIZE; /* Force alloc of new cons_block. */
2721 cons_free_list = 0;
2722 n_cons_blocks = 0;
2726 /* Explicitly free a cons cell by putting it on the free-list. */
2728 void
2729 free_cons (ptr)
2730 struct Lisp_Cons *ptr;
2732 ptr->u.chain = cons_free_list;
2733 #if GC_MARK_STACK
2734 ptr->car = Vdead;
2735 #endif
2736 cons_free_list = ptr;
2739 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2740 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2741 (car, cdr)
2742 Lisp_Object car, cdr;
2744 register Lisp_Object val;
2746 /* eassert (!handling_signal); */
2748 #ifndef SYNC_INPUT
2749 BLOCK_INPUT;
2750 #endif
2752 if (cons_free_list)
2754 /* We use the cdr for chaining the free list
2755 so that we won't use the same field that has the mark bit. */
2756 XSETCONS (val, cons_free_list);
2757 cons_free_list = cons_free_list->u.chain;
2759 else
2761 if (cons_block_index == CONS_BLOCK_SIZE)
2763 register struct cons_block *new;
2764 new = (struct cons_block *) lisp_align_malloc (sizeof *new,
2765 MEM_TYPE_CONS);
2766 bzero ((char *) new->gcmarkbits, sizeof new->gcmarkbits);
2767 new->next = cons_block;
2768 cons_block = new;
2769 cons_block_index = 0;
2770 n_cons_blocks++;
2772 XSETCONS (val, &cons_block->conses[cons_block_index]);
2773 cons_block_index++;
2776 #ifndef SYNC_INPUT
2777 UNBLOCK_INPUT;
2778 #endif
2780 XSETCAR (val, car);
2781 XSETCDR (val, cdr);
2782 eassert (!CONS_MARKED_P (XCONS (val)));
2783 consing_since_gc += sizeof (struct Lisp_Cons);
2784 cons_cells_consed++;
2785 return val;
2788 /* Get an error now if there's any junk in the cons free list. */
2789 void
2790 check_cons_list ()
2792 #ifdef GC_CHECK_CONS_LIST
2793 struct Lisp_Cons *tail = cons_free_list;
2795 while (tail)
2796 tail = tail->u.chain;
2797 #endif
2800 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2802 Lisp_Object
2803 list1 (arg1)
2804 Lisp_Object arg1;
2806 return Fcons (arg1, Qnil);
2809 Lisp_Object
2810 list2 (arg1, arg2)
2811 Lisp_Object arg1, arg2;
2813 return Fcons (arg1, Fcons (arg2, Qnil));
2817 Lisp_Object
2818 list3 (arg1, arg2, arg3)
2819 Lisp_Object arg1, arg2, arg3;
2821 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2825 Lisp_Object
2826 list4 (arg1, arg2, arg3, arg4)
2827 Lisp_Object arg1, arg2, arg3, arg4;
2829 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2833 Lisp_Object
2834 list5 (arg1, arg2, arg3, arg4, arg5)
2835 Lisp_Object arg1, arg2, arg3, arg4, arg5;
2837 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2838 Fcons (arg5, Qnil)))));
2842 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2843 doc: /* Return a newly created list with specified arguments as elements.
2844 Any number of arguments, even zero arguments, are allowed.
2845 usage: (list &rest OBJECTS) */)
2846 (nargs, args)
2847 int nargs;
2848 register Lisp_Object *args;
2850 register Lisp_Object val;
2851 val = Qnil;
2853 while (nargs > 0)
2855 nargs--;
2856 val = Fcons (args[nargs], val);
2858 return val;
2862 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2863 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2864 (length, init)
2865 register Lisp_Object length, init;
2867 register Lisp_Object val;
2868 register int size;
2870 CHECK_NATNUM (length);
2871 size = XFASTINT (length);
2873 val = Qnil;
2874 while (size > 0)
2876 val = Fcons (init, val);
2877 --size;
2879 if (size > 0)
2881 val = Fcons (init, val);
2882 --size;
2884 if (size > 0)
2886 val = Fcons (init, val);
2887 --size;
2889 if (size > 0)
2891 val = Fcons (init, val);
2892 --size;
2894 if (size > 0)
2896 val = Fcons (init, val);
2897 --size;
2903 QUIT;
2906 return val;
2911 /***********************************************************************
2912 Vector Allocation
2913 ***********************************************************************/
2915 /* Singly-linked list of all vectors. */
2917 struct Lisp_Vector *all_vectors;
2919 /* Total number of vector-like objects now in use. */
2921 int n_vectors;
2924 /* Value is a pointer to a newly allocated Lisp_Vector structure
2925 with room for LEN Lisp_Objects. */
2927 static struct Lisp_Vector *
2928 allocate_vectorlike (len, type)
2929 EMACS_INT len;
2930 enum mem_type type;
2932 struct Lisp_Vector *p;
2933 size_t nbytes;
2935 #ifdef DOUG_LEA_MALLOC
2936 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2937 because mapped region contents are not preserved in
2938 a dumped Emacs. */
2939 BLOCK_INPUT;
2940 mallopt (M_MMAP_MAX, 0);
2941 UNBLOCK_INPUT;
2942 #endif
2944 /* This gets triggered by code which I haven't bothered to fix. --Stef */
2945 /* eassert (!handling_signal); */
2947 nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
2948 p = (struct Lisp_Vector *) lisp_malloc (nbytes, type);
2950 #ifdef DOUG_LEA_MALLOC
2951 /* Back to a reasonable maximum of mmap'ed areas. */
2952 BLOCK_INPUT;
2953 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2954 UNBLOCK_INPUT;
2955 #endif
2957 consing_since_gc += nbytes;
2958 vector_cells_consed += len;
2960 #ifndef SYNC_INPUT
2961 BLOCK_INPUT;
2962 #endif
2964 p->next = all_vectors;
2965 all_vectors = p;
2967 #ifndef SYNC_INPUT
2968 UNBLOCK_INPUT;
2969 #endif
2971 ++n_vectors;
2972 return p;
2976 /* Allocate a vector with NSLOTS slots. */
2978 struct Lisp_Vector *
2979 allocate_vector (nslots)
2980 EMACS_INT nslots;
2982 struct Lisp_Vector *v = allocate_vectorlike (nslots, MEM_TYPE_VECTOR);
2983 v->size = nslots;
2984 return v;
2988 /* Allocate other vector-like structures. */
2990 struct Lisp_Hash_Table *
2991 allocate_hash_table ()
2993 EMACS_INT len = VECSIZE (struct Lisp_Hash_Table);
2994 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_HASH_TABLE);
2995 EMACS_INT i;
2997 v->size = len;
2998 for (i = 0; i < len; ++i)
2999 v->contents[i] = Qnil;
3001 return (struct Lisp_Hash_Table *) v;
3005 struct window *
3006 allocate_window ()
3008 EMACS_INT len = VECSIZE (struct window);
3009 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_WINDOW);
3010 EMACS_INT i;
3012 for (i = 0; i < len; ++i)
3013 v->contents[i] = Qnil;
3014 v->size = len;
3016 return (struct window *) v;
3020 struct frame *
3021 allocate_frame ()
3023 EMACS_INT len = VECSIZE (struct frame);
3024 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_FRAME);
3025 EMACS_INT i;
3027 for (i = 0; i < len; ++i)
3028 v->contents[i] = make_number (0);
3029 v->size = len;
3030 return (struct frame *) v;
3034 struct Lisp_Process *
3035 allocate_process ()
3037 /* Memory-footprint of the object in nb of Lisp_Object fields. */
3038 EMACS_INT memlen = VECSIZE (struct Lisp_Process);
3039 /* Size if we only count the actual Lisp_Object fields (which need to be
3040 traced by the GC). */
3041 EMACS_INT lisplen = PSEUDOVECSIZE (struct Lisp_Process, pid);
3042 struct Lisp_Vector *v = allocate_vectorlike (memlen, MEM_TYPE_PROCESS);
3043 EMACS_INT i;
3045 for (i = 0; i < lisplen; ++i)
3046 v->contents[i] = Qnil;
3047 v->size = lisplen;
3049 return (struct Lisp_Process *) v;
3053 struct Lisp_Vector *
3054 allocate_other_vector (len)
3055 EMACS_INT len;
3057 struct Lisp_Vector *v = allocate_vectorlike (len, MEM_TYPE_VECTOR);
3058 EMACS_INT i;
3060 for (i = 0; i < len; ++i)
3061 v->contents[i] = Qnil;
3062 v->size = len;
3064 return v;
3068 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
3069 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
3070 See also the function `vector'. */)
3071 (length, init)
3072 register Lisp_Object length, init;
3074 Lisp_Object vector;
3075 register EMACS_INT sizei;
3076 register int index;
3077 register struct Lisp_Vector *p;
3079 CHECK_NATNUM (length);
3080 sizei = XFASTINT (length);
3082 p = allocate_vector (sizei);
3083 for (index = 0; index < sizei; index++)
3084 p->contents[index] = init;
3086 XSETVECTOR (vector, p);
3087 return vector;
3091 DEFUN ("make-char-table", Fmake_char_table, Smake_char_table, 1, 2, 0,
3092 doc: /* Return a newly created char-table, with purpose PURPOSE.
3093 Each element is initialized to INIT, which defaults to nil.
3094 PURPOSE should be a symbol which has a `char-table-extra-slots' property.
3095 The property's value should be an integer between 0 and 10. */)
3096 (purpose, init)
3097 register Lisp_Object purpose, init;
3099 Lisp_Object vector;
3100 Lisp_Object n;
3101 CHECK_SYMBOL (purpose);
3102 n = Fget (purpose, Qchar_table_extra_slots);
3103 CHECK_NUMBER (n);
3104 if (XINT (n) < 0 || XINT (n) > 10)
3105 args_out_of_range (n, Qnil);
3106 /* Add 2 to the size for the defalt and parent slots. */
3107 vector = Fmake_vector (make_number (CHAR_TABLE_STANDARD_SLOTS + XINT (n)),
3108 init);
3109 XCHAR_TABLE (vector)->top = Qt;
3110 XCHAR_TABLE (vector)->parent = Qnil;
3111 XCHAR_TABLE (vector)->purpose = purpose;
3112 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
3113 return vector;
3117 /* Return a newly created sub char table with slots initialized by INIT.
3118 Since a sub char table does not appear as a top level Emacs Lisp
3119 object, we don't need a Lisp interface to make it. */
3121 Lisp_Object
3122 make_sub_char_table (init)
3123 Lisp_Object init;
3125 Lisp_Object vector
3126 = Fmake_vector (make_number (SUB_CHAR_TABLE_STANDARD_SLOTS), init);
3127 XCHAR_TABLE (vector)->top = Qnil;
3128 XCHAR_TABLE (vector)->defalt = Qnil;
3129 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
3130 return vector;
3134 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3135 doc: /* Return a newly created vector with specified arguments as elements.
3136 Any number of arguments, even zero arguments, are allowed.
3137 usage: (vector &rest OBJECTS) */)
3138 (nargs, args)
3139 register int nargs;
3140 Lisp_Object *args;
3142 register Lisp_Object len, val;
3143 register int index;
3144 register struct Lisp_Vector *p;
3146 XSETFASTINT (len, nargs);
3147 val = Fmake_vector (len, Qnil);
3148 p = XVECTOR (val);
3149 for (index = 0; index < nargs; index++)
3150 p->contents[index] = args[index];
3151 return val;
3155 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3156 doc: /* Create a byte-code object with specified arguments as elements.
3157 The arguments should be the arglist, bytecode-string, constant vector,
3158 stack size, (optional) doc string, and (optional) interactive spec.
3159 The first four arguments are required; at most six have any
3160 significance.
3161 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3162 (nargs, args)
3163 register int nargs;
3164 Lisp_Object *args;
3166 register Lisp_Object len, val;
3167 register int index;
3168 register struct Lisp_Vector *p;
3170 XSETFASTINT (len, nargs);
3171 if (!NILP (Vpurify_flag))
3172 val = make_pure_vector ((EMACS_INT) nargs);
3173 else
3174 val = Fmake_vector (len, Qnil);
3176 if (STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
3177 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3178 earlier because they produced a raw 8-bit string for byte-code
3179 and now such a byte-code string is loaded as multibyte while
3180 raw 8-bit characters converted to multibyte form. Thus, now we
3181 must convert them back to the original unibyte form. */
3182 args[1] = Fstring_as_unibyte (args[1]);
3184 p = XVECTOR (val);
3185 for (index = 0; index < nargs; index++)
3187 if (!NILP (Vpurify_flag))
3188 args[index] = Fpurecopy (args[index]);
3189 p->contents[index] = args[index];
3191 XSETCOMPILED (val, p);
3192 return val;
3197 /***********************************************************************
3198 Symbol Allocation
3199 ***********************************************************************/
3201 /* Each symbol_block is just under 1020 bytes long, since malloc
3202 really allocates in units of powers of two and uses 4 bytes for its
3203 own overhead. */
3205 #define SYMBOL_BLOCK_SIZE \
3206 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
3208 struct symbol_block
3210 /* Place `symbols' first, to preserve alignment. */
3211 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3212 struct symbol_block *next;
3215 /* Current symbol block and index of first unused Lisp_Symbol
3216 structure in it. */
3218 struct symbol_block *symbol_block;
3219 int symbol_block_index;
3221 /* List of free symbols. */
3223 struct Lisp_Symbol *symbol_free_list;
3225 /* Total number of symbol blocks now in use. */
3227 int n_symbol_blocks;
3230 /* Initialize symbol allocation. */
3232 void
3233 init_symbol ()
3235 symbol_block = NULL;
3236 symbol_block_index = SYMBOL_BLOCK_SIZE;
3237 symbol_free_list = 0;
3238 n_symbol_blocks = 0;
3242 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3243 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3244 Its value and function definition are void, and its property list is nil. */)
3245 (name)
3246 Lisp_Object name;
3248 register Lisp_Object val;
3249 register struct Lisp_Symbol *p;
3251 CHECK_STRING (name);
3253 /* eassert (!handling_signal); */
3255 #ifndef SYNC_INPUT
3256 BLOCK_INPUT;
3257 #endif
3259 if (symbol_free_list)
3261 XSETSYMBOL (val, symbol_free_list);
3262 symbol_free_list = symbol_free_list->next;
3264 else
3266 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3268 struct symbol_block *new;
3269 new = (struct symbol_block *) lisp_malloc (sizeof *new,
3270 MEM_TYPE_SYMBOL);
3271 new->next = symbol_block;
3272 symbol_block = new;
3273 symbol_block_index = 0;
3274 n_symbol_blocks++;
3276 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index]);
3277 symbol_block_index++;
3280 #ifndef SYNC_INPUT
3281 UNBLOCK_INPUT;
3282 #endif
3284 p = XSYMBOL (val);
3285 p->xname = name;
3286 p->plist = Qnil;
3287 p->value = Qunbound;
3288 p->function = Qunbound;
3289 p->next = NULL;
3290 p->gcmarkbit = 0;
3291 p->interned = SYMBOL_UNINTERNED;
3292 p->constant = 0;
3293 p->indirect_variable = 0;
3294 consing_since_gc += sizeof (struct Lisp_Symbol);
3295 symbols_consed++;
3296 return val;
3301 /***********************************************************************
3302 Marker (Misc) Allocation
3303 ***********************************************************************/
3305 /* Allocation of markers and other objects that share that structure.
3306 Works like allocation of conses. */
3308 #define MARKER_BLOCK_SIZE \
3309 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
3311 struct marker_block
3313 /* Place `markers' first, to preserve alignment. */
3314 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
3315 struct marker_block *next;
3318 struct marker_block *marker_block;
3319 int marker_block_index;
3321 union Lisp_Misc *marker_free_list;
3323 /* Total number of marker blocks now in use. */
3325 int n_marker_blocks;
3327 void
3328 init_marker ()
3330 marker_block = NULL;
3331 marker_block_index = MARKER_BLOCK_SIZE;
3332 marker_free_list = 0;
3333 n_marker_blocks = 0;
3336 /* Return a newly allocated Lisp_Misc object, with no substructure. */
3338 Lisp_Object
3339 allocate_misc ()
3341 Lisp_Object val;
3343 /* eassert (!handling_signal); */
3345 #ifndef SYNC_INPUT
3346 BLOCK_INPUT;
3347 #endif
3349 if (marker_free_list)
3351 XSETMISC (val, marker_free_list);
3352 marker_free_list = marker_free_list->u_free.chain;
3354 else
3356 if (marker_block_index == MARKER_BLOCK_SIZE)
3358 struct marker_block *new;
3359 new = (struct marker_block *) lisp_malloc (sizeof *new,
3360 MEM_TYPE_MISC);
3361 new->next = marker_block;
3362 marker_block = new;
3363 marker_block_index = 0;
3364 n_marker_blocks++;
3365 total_free_markers += MARKER_BLOCK_SIZE;
3367 XSETMISC (val, &marker_block->markers[marker_block_index]);
3368 marker_block_index++;
3371 #ifndef SYNC_INPUT
3372 UNBLOCK_INPUT;
3373 #endif
3375 --total_free_markers;
3376 consing_since_gc += sizeof (union Lisp_Misc);
3377 misc_objects_consed++;
3378 XMARKER (val)->gcmarkbit = 0;
3379 return val;
3382 /* Free a Lisp_Misc object */
3384 void
3385 free_misc (misc)
3386 Lisp_Object misc;
3388 XMISC (misc)->u_marker.type = Lisp_Misc_Free;
3389 XMISC (misc)->u_free.chain = marker_free_list;
3390 marker_free_list = XMISC (misc);
3392 total_free_markers++;
3395 /* Return a Lisp_Misc_Save_Value object containing POINTER and
3396 INTEGER. This is used to package C values to call record_unwind_protect.
3397 The unwind function can get the C values back using XSAVE_VALUE. */
3399 Lisp_Object
3400 make_save_value (pointer, integer)
3401 void *pointer;
3402 int integer;
3404 register Lisp_Object val;
3405 register struct Lisp_Save_Value *p;
3407 val = allocate_misc ();
3408 XMISCTYPE (val) = Lisp_Misc_Save_Value;
3409 p = XSAVE_VALUE (val);
3410 p->pointer = pointer;
3411 p->integer = integer;
3412 p->dogc = 0;
3413 return val;
3416 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3417 doc: /* Return a newly allocated marker which does not point at any place. */)
3420 register Lisp_Object val;
3421 register struct Lisp_Marker *p;
3423 val = allocate_misc ();
3424 XMISCTYPE (val) = Lisp_Misc_Marker;
3425 p = XMARKER (val);
3426 p->buffer = 0;
3427 p->bytepos = 0;
3428 p->charpos = 0;
3429 p->next = NULL;
3430 p->insertion_type = 0;
3431 return val;
3434 /* Put MARKER back on the free list after using it temporarily. */
3436 void
3437 free_marker (marker)
3438 Lisp_Object marker;
3440 unchain_marker (XMARKER (marker));
3441 free_misc (marker);
3445 /* Return a newly created vector or string with specified arguments as
3446 elements. If all the arguments are characters that can fit
3447 in a string of events, make a string; otherwise, make a vector.
3449 Any number of arguments, even zero arguments, are allowed. */
3451 Lisp_Object
3452 make_event_array (nargs, args)
3453 register int nargs;
3454 Lisp_Object *args;
3456 int i;
3458 for (i = 0; i < nargs; i++)
3459 /* The things that fit in a string
3460 are characters that are in 0...127,
3461 after discarding the meta bit and all the bits above it. */
3462 if (!INTEGERP (args[i])
3463 || (XUINT (args[i]) & ~(-CHAR_META)) >= 0200)
3464 return Fvector (nargs, args);
3466 /* Since the loop exited, we know that all the things in it are
3467 characters, so we can make a string. */
3469 Lisp_Object result;
3471 result = Fmake_string (make_number (nargs), make_number (0));
3472 for (i = 0; i < nargs; i++)
3474 SSET (result, i, XINT (args[i]));
3475 /* Move the meta bit to the right place for a string char. */
3476 if (XINT (args[i]) & CHAR_META)
3477 SSET (result, i, SREF (result, i) | 0x80);
3480 return result;
3486 /************************************************************************
3487 Memory Full Handling
3488 ************************************************************************/
3491 /* Called if malloc returns zero. */
3493 void
3494 memory_full ()
3496 int i;
3498 Vmemory_full = Qt;
3500 memory_full_cons_threshold = sizeof (struct cons_block);
3502 /* The first time we get here, free the spare memory. */
3503 for (i = 0; i < sizeof (spare_memory) / sizeof (char *); i++)
3504 if (spare_memory[i])
3506 if (i == 0)
3507 free (spare_memory[i]);
3508 else if (i >= 1 && i <= 4)
3509 lisp_align_free (spare_memory[i]);
3510 else
3511 lisp_free (spare_memory[i]);
3512 spare_memory[i] = 0;
3515 /* Record the space now used. When it decreases substantially,
3516 we can refill the memory reserve. */
3517 #ifndef SYSTEM_MALLOC
3518 bytes_used_when_full = BYTES_USED;
3519 #endif
3521 /* This used to call error, but if we've run out of memory, we could
3522 get infinite recursion trying to build the string. */
3523 xsignal (Qnil, Vmemory_signal_data);
3526 /* If we released our reserve (due to running out of memory),
3527 and we have a fair amount free once again,
3528 try to set aside another reserve in case we run out once more.
3530 This is called when a relocatable block is freed in ralloc.c,
3531 and also directly from this file, in case we're not using ralloc.c. */
3533 void
3534 refill_memory_reserve ()
3536 #ifndef SYSTEM_MALLOC
3537 if (spare_memory[0] == 0)
3538 spare_memory[0] = (char *) malloc ((size_t) SPARE_MEMORY);
3539 if (spare_memory[1] == 0)
3540 spare_memory[1] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3541 MEM_TYPE_CONS);
3542 if (spare_memory[2] == 0)
3543 spare_memory[2] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3544 MEM_TYPE_CONS);
3545 if (spare_memory[3] == 0)
3546 spare_memory[3] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3547 MEM_TYPE_CONS);
3548 if (spare_memory[4] == 0)
3549 spare_memory[4] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3550 MEM_TYPE_CONS);
3551 if (spare_memory[5] == 0)
3552 spare_memory[5] = (char *) lisp_malloc (sizeof (struct string_block),
3553 MEM_TYPE_STRING);
3554 if (spare_memory[6] == 0)
3555 spare_memory[6] = (char *) lisp_malloc (sizeof (struct string_block),
3556 MEM_TYPE_STRING);
3557 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
3558 Vmemory_full = Qnil;
3559 #endif
3562 /************************************************************************
3563 C Stack Marking
3564 ************************************************************************/
3566 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
3568 /* Conservative C stack marking requires a method to identify possibly
3569 live Lisp objects given a pointer value. We do this by keeping
3570 track of blocks of Lisp data that are allocated in a red-black tree
3571 (see also the comment of mem_node which is the type of nodes in
3572 that tree). Function lisp_malloc adds information for an allocated
3573 block to the red-black tree with calls to mem_insert, and function
3574 lisp_free removes it with mem_delete. Functions live_string_p etc
3575 call mem_find to lookup information about a given pointer in the
3576 tree, and use that to determine if the pointer points to a Lisp
3577 object or not. */
3579 /* Initialize this part of alloc.c. */
3581 static void
3582 mem_init ()
3584 mem_z.left = mem_z.right = MEM_NIL;
3585 mem_z.parent = NULL;
3586 mem_z.color = MEM_BLACK;
3587 mem_z.start = mem_z.end = NULL;
3588 mem_root = MEM_NIL;
3592 /* Value is a pointer to the mem_node containing START. Value is
3593 MEM_NIL if there is no node in the tree containing START. */
3595 static INLINE struct mem_node *
3596 mem_find (start)
3597 void *start;
3599 struct mem_node *p;
3601 if (start < min_heap_address || start > max_heap_address)
3602 return MEM_NIL;
3604 /* Make the search always successful to speed up the loop below. */
3605 mem_z.start = start;
3606 mem_z.end = (char *) start + 1;
3608 p = mem_root;
3609 while (start < p->start || start >= p->end)
3610 p = start < p->start ? p->left : p->right;
3611 return p;
3615 /* Insert a new node into the tree for a block of memory with start
3616 address START, end address END, and type TYPE. Value is a
3617 pointer to the node that was inserted. */
3619 static struct mem_node *
3620 mem_insert (start, end, type)
3621 void *start, *end;
3622 enum mem_type type;
3624 struct mem_node *c, *parent, *x;
3626 if (min_heap_address == NULL || start < min_heap_address)
3627 min_heap_address = start;
3628 if (max_heap_address == NULL || end > max_heap_address)
3629 max_heap_address = end;
3631 /* See where in the tree a node for START belongs. In this
3632 particular application, it shouldn't happen that a node is already
3633 present. For debugging purposes, let's check that. */
3634 c = mem_root;
3635 parent = NULL;
3637 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
3639 while (c != MEM_NIL)
3641 if (start >= c->start && start < c->end)
3642 abort ();
3643 parent = c;
3644 c = start < c->start ? c->left : c->right;
3647 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3649 while (c != MEM_NIL)
3651 parent = c;
3652 c = start < c->start ? c->left : c->right;
3655 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3657 /* Create a new node. */
3658 #ifdef GC_MALLOC_CHECK
3659 x = (struct mem_node *) _malloc_internal (sizeof *x);
3660 if (x == NULL)
3661 abort ();
3662 #else
3663 x = (struct mem_node *) xmalloc (sizeof *x);
3664 #endif
3665 x->start = start;
3666 x->end = end;
3667 x->type = type;
3668 x->parent = parent;
3669 x->left = x->right = MEM_NIL;
3670 x->color = MEM_RED;
3672 /* Insert it as child of PARENT or install it as root. */
3673 if (parent)
3675 if (start < parent->start)
3676 parent->left = x;
3677 else
3678 parent->right = x;
3680 else
3681 mem_root = x;
3683 /* Re-establish red-black tree properties. */
3684 mem_insert_fixup (x);
3686 return x;
3690 /* Re-establish the red-black properties of the tree, and thereby
3691 balance the tree, after node X has been inserted; X is always red. */
3693 static void
3694 mem_insert_fixup (x)
3695 struct mem_node *x;
3697 while (x != mem_root && x->parent->color == MEM_RED)
3699 /* X is red and its parent is red. This is a violation of
3700 red-black tree property #3. */
3702 if (x->parent == x->parent->parent->left)
3704 /* We're on the left side of our grandparent, and Y is our
3705 "uncle". */
3706 struct mem_node *y = x->parent->parent->right;
3708 if (y->color == MEM_RED)
3710 /* Uncle and parent are red but should be black because
3711 X is red. Change the colors accordingly and proceed
3712 with the grandparent. */
3713 x->parent->color = MEM_BLACK;
3714 y->color = MEM_BLACK;
3715 x->parent->parent->color = MEM_RED;
3716 x = x->parent->parent;
3718 else
3720 /* Parent and uncle have different colors; parent is
3721 red, uncle is black. */
3722 if (x == x->parent->right)
3724 x = x->parent;
3725 mem_rotate_left (x);
3728 x->parent->color = MEM_BLACK;
3729 x->parent->parent->color = MEM_RED;
3730 mem_rotate_right (x->parent->parent);
3733 else
3735 /* This is the symmetrical case of above. */
3736 struct mem_node *y = x->parent->parent->left;
3738 if (y->color == MEM_RED)
3740 x->parent->color = MEM_BLACK;
3741 y->color = MEM_BLACK;
3742 x->parent->parent->color = MEM_RED;
3743 x = x->parent->parent;
3745 else
3747 if (x == x->parent->left)
3749 x = x->parent;
3750 mem_rotate_right (x);
3753 x->parent->color = MEM_BLACK;
3754 x->parent->parent->color = MEM_RED;
3755 mem_rotate_left (x->parent->parent);
3760 /* The root may have been changed to red due to the algorithm. Set
3761 it to black so that property #5 is satisfied. */
3762 mem_root->color = MEM_BLACK;
3766 /* (x) (y)
3767 / \ / \
3768 a (y) ===> (x) c
3769 / \ / \
3770 b c a b */
3772 static void
3773 mem_rotate_left (x)
3774 struct mem_node *x;
3776 struct mem_node *y;
3778 /* Turn y's left sub-tree into x's right sub-tree. */
3779 y = x->right;
3780 x->right = y->left;
3781 if (y->left != MEM_NIL)
3782 y->left->parent = x;
3784 /* Y's parent was x's parent. */
3785 if (y != MEM_NIL)
3786 y->parent = x->parent;
3788 /* Get the parent to point to y instead of x. */
3789 if (x->parent)
3791 if (x == x->parent->left)
3792 x->parent->left = y;
3793 else
3794 x->parent->right = y;
3796 else
3797 mem_root = y;
3799 /* Put x on y's left. */
3800 y->left = x;
3801 if (x != MEM_NIL)
3802 x->parent = y;
3806 /* (x) (Y)
3807 / \ / \
3808 (y) c ===> a (x)
3809 / \ / \
3810 a b b c */
3812 static void
3813 mem_rotate_right (x)
3814 struct mem_node *x;
3816 struct mem_node *y = x->left;
3818 x->left = y->right;
3819 if (y->right != MEM_NIL)
3820 y->right->parent = x;
3822 if (y != MEM_NIL)
3823 y->parent = x->parent;
3824 if (x->parent)
3826 if (x == x->parent->right)
3827 x->parent->right = y;
3828 else
3829 x->parent->left = y;
3831 else
3832 mem_root = y;
3834 y->right = x;
3835 if (x != MEM_NIL)
3836 x->parent = y;
3840 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
3842 static void
3843 mem_delete (z)
3844 struct mem_node *z;
3846 struct mem_node *x, *y;
3848 if (!z || z == MEM_NIL)
3849 return;
3851 if (z->left == MEM_NIL || z->right == MEM_NIL)
3852 y = z;
3853 else
3855 y = z->right;
3856 while (y->left != MEM_NIL)
3857 y = y->left;
3860 if (y->left != MEM_NIL)
3861 x = y->left;
3862 else
3863 x = y->right;
3865 x->parent = y->parent;
3866 if (y->parent)
3868 if (y == y->parent->left)
3869 y->parent->left = x;
3870 else
3871 y->parent->right = x;
3873 else
3874 mem_root = x;
3876 if (y != z)
3878 z->start = y->start;
3879 z->end = y->end;
3880 z->type = y->type;
3883 if (y->color == MEM_BLACK)
3884 mem_delete_fixup (x);
3886 #ifdef GC_MALLOC_CHECK
3887 _free_internal (y);
3888 #else
3889 xfree (y);
3890 #endif
3894 /* Re-establish the red-black properties of the tree, after a
3895 deletion. */
3897 static void
3898 mem_delete_fixup (x)
3899 struct mem_node *x;
3901 while (x != mem_root && x->color == MEM_BLACK)
3903 if (x == x->parent->left)
3905 struct mem_node *w = x->parent->right;
3907 if (w->color == MEM_RED)
3909 w->color = MEM_BLACK;
3910 x->parent->color = MEM_RED;
3911 mem_rotate_left (x->parent);
3912 w = x->parent->right;
3915 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
3917 w->color = MEM_RED;
3918 x = x->parent;
3920 else
3922 if (w->right->color == MEM_BLACK)
3924 w->left->color = MEM_BLACK;
3925 w->color = MEM_RED;
3926 mem_rotate_right (w);
3927 w = x->parent->right;
3929 w->color = x->parent->color;
3930 x->parent->color = MEM_BLACK;
3931 w->right->color = MEM_BLACK;
3932 mem_rotate_left (x->parent);
3933 x = mem_root;
3936 else
3938 struct mem_node *w = x->parent->left;
3940 if (w->color == MEM_RED)
3942 w->color = MEM_BLACK;
3943 x->parent->color = MEM_RED;
3944 mem_rotate_right (x->parent);
3945 w = x->parent->left;
3948 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
3950 w->color = MEM_RED;
3951 x = x->parent;
3953 else
3955 if (w->left->color == MEM_BLACK)
3957 w->right->color = MEM_BLACK;
3958 w->color = MEM_RED;
3959 mem_rotate_left (w);
3960 w = x->parent->left;
3963 w->color = x->parent->color;
3964 x->parent->color = MEM_BLACK;
3965 w->left->color = MEM_BLACK;
3966 mem_rotate_right (x->parent);
3967 x = mem_root;
3972 x->color = MEM_BLACK;
3976 /* Value is non-zero if P is a pointer to a live Lisp string on
3977 the heap. M is a pointer to the mem_block for P. */
3979 static INLINE int
3980 live_string_p (m, p)
3981 struct mem_node *m;
3982 void *p;
3984 if (m->type == MEM_TYPE_STRING)
3986 struct string_block *b = (struct string_block *) m->start;
3987 int offset = (char *) p - (char *) &b->strings[0];
3989 /* P must point to the start of a Lisp_String structure, and it
3990 must not be on the free-list. */
3991 return (offset >= 0
3992 && offset % sizeof b->strings[0] == 0
3993 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
3994 && ((struct Lisp_String *) p)->data != NULL);
3996 else
3997 return 0;
4001 /* Value is non-zero if P is a pointer to a live Lisp cons on
4002 the heap. M is a pointer to the mem_block for P. */
4004 static INLINE int
4005 live_cons_p (m, p)
4006 struct mem_node *m;
4007 void *p;
4009 if (m->type == MEM_TYPE_CONS)
4011 struct cons_block *b = (struct cons_block *) m->start;
4012 int offset = (char *) p - (char *) &b->conses[0];
4014 /* P must point to the start of a Lisp_Cons, not be
4015 one of the unused cells in the current cons block,
4016 and not be on the free-list. */
4017 return (offset >= 0
4018 && offset % sizeof b->conses[0] == 0
4019 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
4020 && (b != cons_block
4021 || offset / sizeof b->conses[0] < cons_block_index)
4022 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
4024 else
4025 return 0;
4029 /* Value is non-zero if P is a pointer to a live Lisp symbol on
4030 the heap. M is a pointer to the mem_block for P. */
4032 static INLINE int
4033 live_symbol_p (m, p)
4034 struct mem_node *m;
4035 void *p;
4037 if (m->type == MEM_TYPE_SYMBOL)
4039 struct symbol_block *b = (struct symbol_block *) m->start;
4040 int offset = (char *) p - (char *) &b->symbols[0];
4042 /* P must point to the start of a Lisp_Symbol, not be
4043 one of the unused cells in the current symbol block,
4044 and not be on the free-list. */
4045 return (offset >= 0
4046 && offset % sizeof b->symbols[0] == 0
4047 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
4048 && (b != symbol_block
4049 || offset / sizeof b->symbols[0] < symbol_block_index)
4050 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
4052 else
4053 return 0;
4057 /* Value is non-zero if P is a pointer to a live Lisp float on
4058 the heap. M is a pointer to the mem_block for P. */
4060 static INLINE int
4061 live_float_p (m, p)
4062 struct mem_node *m;
4063 void *p;
4065 if (m->type == MEM_TYPE_FLOAT)
4067 struct float_block *b = (struct float_block *) m->start;
4068 int offset = (char *) p - (char *) &b->floats[0];
4070 /* P must point to the start of a Lisp_Float and not be
4071 one of the unused cells in the current float block. */
4072 return (offset >= 0
4073 && offset % sizeof b->floats[0] == 0
4074 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
4075 && (b != float_block
4076 || offset / sizeof b->floats[0] < float_block_index));
4078 else
4079 return 0;
4083 /* Value is non-zero if P is a pointer to a live Lisp Misc on
4084 the heap. M is a pointer to the mem_block for P. */
4086 static INLINE int
4087 live_misc_p (m, p)
4088 struct mem_node *m;
4089 void *p;
4091 if (m->type == MEM_TYPE_MISC)
4093 struct marker_block *b = (struct marker_block *) m->start;
4094 int offset = (char *) p - (char *) &b->markers[0];
4096 /* P must point to the start of a Lisp_Misc, not be
4097 one of the unused cells in the current misc block,
4098 and not be on the free-list. */
4099 return (offset >= 0
4100 && offset % sizeof b->markers[0] == 0
4101 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
4102 && (b != marker_block
4103 || offset / sizeof b->markers[0] < marker_block_index)
4104 && ((union Lisp_Misc *) p)->u_marker.type != Lisp_Misc_Free);
4106 else
4107 return 0;
4111 /* Value is non-zero if P is a pointer to a live vector-like object.
4112 M is a pointer to the mem_block for P. */
4114 static INLINE int
4115 live_vector_p (m, p)
4116 struct mem_node *m;
4117 void *p;
4119 return (p == m->start
4120 && m->type >= MEM_TYPE_VECTOR
4121 && m->type <= MEM_TYPE_WINDOW);
4125 /* Value is non-zero if P is a pointer to a live buffer. M is a
4126 pointer to the mem_block for P. */
4128 static INLINE int
4129 live_buffer_p (m, p)
4130 struct mem_node *m;
4131 void *p;
4133 /* P must point to the start of the block, and the buffer
4134 must not have been killed. */
4135 return (m->type == MEM_TYPE_BUFFER
4136 && p == m->start
4137 && !NILP (((struct buffer *) p)->name));
4140 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
4142 #if GC_MARK_STACK
4144 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4146 /* Array of objects that are kept alive because the C stack contains
4147 a pattern that looks like a reference to them . */
4149 #define MAX_ZOMBIES 10
4150 static Lisp_Object zombies[MAX_ZOMBIES];
4152 /* Number of zombie objects. */
4154 static int nzombies;
4156 /* Number of garbage collections. */
4158 static int ngcs;
4160 /* Average percentage of zombies per collection. */
4162 static double avg_zombies;
4164 /* Max. number of live and zombie objects. */
4166 static int max_live, max_zombies;
4168 /* Average number of live objects per GC. */
4170 static double avg_live;
4172 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
4173 doc: /* Show information about live and zombie objects. */)
4176 Lisp_Object args[8], zombie_list = Qnil;
4177 int i;
4178 for (i = 0; i < nzombies; i++)
4179 zombie_list = Fcons (zombies[i], zombie_list);
4180 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
4181 args[1] = make_number (ngcs);
4182 args[2] = make_float (avg_live);
4183 args[3] = make_float (avg_zombies);
4184 args[4] = make_float (avg_zombies / avg_live / 100);
4185 args[5] = make_number (max_live);
4186 args[6] = make_number (max_zombies);
4187 args[7] = zombie_list;
4188 return Fmessage (8, args);
4191 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4194 /* Mark OBJ if we can prove it's a Lisp_Object. */
4196 static INLINE void
4197 mark_maybe_object (obj)
4198 Lisp_Object obj;
4200 void *po = (void *) XPNTR (obj);
4201 struct mem_node *m = mem_find (po);
4203 if (m != MEM_NIL)
4205 int mark_p = 0;
4207 switch (XGCTYPE (obj))
4209 case Lisp_String:
4210 mark_p = (live_string_p (m, po)
4211 && !STRING_MARKED_P ((struct Lisp_String *) po));
4212 break;
4214 case Lisp_Cons:
4215 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4216 break;
4218 case Lisp_Symbol:
4219 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4220 break;
4222 case Lisp_Float:
4223 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4224 break;
4226 case Lisp_Vectorlike:
4227 /* Note: can't check GC_BUFFERP before we know it's a
4228 buffer because checking that dereferences the pointer
4229 PO which might point anywhere. */
4230 if (live_vector_p (m, po))
4231 mark_p = !GC_SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4232 else if (live_buffer_p (m, po))
4233 mark_p = GC_BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4234 break;
4236 case Lisp_Misc:
4237 mark_p = (live_misc_p (m, po) && !XMARKER (obj)->gcmarkbit);
4238 break;
4240 case Lisp_Int:
4241 case Lisp_Type_Limit:
4242 break;
4245 if (mark_p)
4247 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4248 if (nzombies < MAX_ZOMBIES)
4249 zombies[nzombies] = obj;
4250 ++nzombies;
4251 #endif
4252 mark_object (obj);
4258 /* If P points to Lisp data, mark that as live if it isn't already
4259 marked. */
4261 static INLINE void
4262 mark_maybe_pointer (p)
4263 void *p;
4265 struct mem_node *m;
4267 /* Quickly rule out some values which can't point to Lisp data. */
4268 if ((EMACS_INT) p %
4269 #ifdef USE_LSB_TAG
4270 8 /* USE_LSB_TAG needs Lisp data to be aligned on multiples of 8. */
4271 #else
4272 2 /* We assume that Lisp data is aligned on even addresses. */
4273 #endif
4275 return;
4277 m = mem_find (p);
4278 if (m != MEM_NIL)
4280 Lisp_Object obj = Qnil;
4282 switch (m->type)
4284 case MEM_TYPE_NON_LISP:
4285 /* Nothing to do; not a pointer to Lisp memory. */
4286 break;
4288 case MEM_TYPE_BUFFER:
4289 if (live_buffer_p (m, p) && !VECTOR_MARKED_P((struct buffer *)p))
4290 XSETVECTOR (obj, p);
4291 break;
4293 case MEM_TYPE_CONS:
4294 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4295 XSETCONS (obj, p);
4296 break;
4298 case MEM_TYPE_STRING:
4299 if (live_string_p (m, p)
4300 && !STRING_MARKED_P ((struct Lisp_String *) p))
4301 XSETSTRING (obj, p);
4302 break;
4304 case MEM_TYPE_MISC:
4305 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4306 XSETMISC (obj, p);
4307 break;
4309 case MEM_TYPE_SYMBOL:
4310 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4311 XSETSYMBOL (obj, p);
4312 break;
4314 case MEM_TYPE_FLOAT:
4315 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4316 XSETFLOAT (obj, p);
4317 break;
4319 case MEM_TYPE_VECTOR:
4320 case MEM_TYPE_PROCESS:
4321 case MEM_TYPE_HASH_TABLE:
4322 case MEM_TYPE_FRAME:
4323 case MEM_TYPE_WINDOW:
4324 if (live_vector_p (m, p))
4326 Lisp_Object tem;
4327 XSETVECTOR (tem, p);
4328 if (!GC_SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4329 obj = tem;
4331 break;
4333 default:
4334 abort ();
4337 if (!GC_NILP (obj))
4338 mark_object (obj);
4343 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4344 or END+OFFSET..START. */
4346 static void
4347 mark_memory (start, end, offset)
4348 void *start, *end;
4349 int offset;
4351 Lisp_Object *p;
4352 void **pp;
4354 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4355 nzombies = 0;
4356 #endif
4358 /* Make START the pointer to the start of the memory region,
4359 if it isn't already. */
4360 if (end < start)
4362 void *tem = start;
4363 start = end;
4364 end = tem;
4367 /* Mark Lisp_Objects. */
4368 for (p = (Lisp_Object *) ((char *) start + offset); (void *) p < end; ++p)
4369 mark_maybe_object (*p);
4371 /* Mark Lisp data pointed to. This is necessary because, in some
4372 situations, the C compiler optimizes Lisp objects away, so that
4373 only a pointer to them remains. Example:
4375 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4378 Lisp_Object obj = build_string ("test");
4379 struct Lisp_String *s = XSTRING (obj);
4380 Fgarbage_collect ();
4381 fprintf (stderr, "test `%s'\n", s->data);
4382 return Qnil;
4385 Here, `obj' isn't really used, and the compiler optimizes it
4386 away. The only reference to the life string is through the
4387 pointer `s'. */
4389 for (pp = (void **) ((char *) start + offset); (void *) pp < end; ++pp)
4390 mark_maybe_pointer (*pp);
4393 /* setjmp will work with GCC unless NON_SAVING_SETJMP is defined in
4394 the GCC system configuration. In gcc 3.2, the only systems for
4395 which this is so are i386-sco5 non-ELF, i386-sysv3 (maybe included
4396 by others?) and ns32k-pc532-min. */
4398 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4400 static int setjmp_tested_p, longjmps_done;
4402 #define SETJMP_WILL_LIKELY_WORK "\
4404 Emacs garbage collector has been changed to use conservative stack\n\
4405 marking. Emacs has determined that the method it uses to do the\n\
4406 marking will likely work on your system, but this isn't sure.\n\
4408 If you are a system-programmer, or can get the help of a local wizard\n\
4409 who is, please take a look at the function mark_stack in alloc.c, and\n\
4410 verify that the methods used are appropriate for your system.\n\
4412 Please mail the result to <emacs-devel@gnu.org>.\n\
4415 #define SETJMP_WILL_NOT_WORK "\
4417 Emacs garbage collector has been changed to use conservative stack\n\
4418 marking. Emacs has determined that the default method it uses to do the\n\
4419 marking will not work on your system. We will need a system-dependent\n\
4420 solution for your system.\n\
4422 Please take a look at the function mark_stack in alloc.c, and\n\
4423 try to find a way to make it work on your system.\n\
4425 Note that you may get false negatives, depending on the compiler.\n\
4426 In particular, you need to use -O with GCC for this test.\n\
4428 Please mail the result to <emacs-devel@gnu.org>.\n\
4432 /* Perform a quick check if it looks like setjmp saves registers in a
4433 jmp_buf. Print a message to stderr saying so. When this test
4434 succeeds, this is _not_ a proof that setjmp is sufficient for
4435 conservative stack marking. Only the sources or a disassembly
4436 can prove that. */
4438 static void
4439 test_setjmp ()
4441 char buf[10];
4442 register int x;
4443 jmp_buf jbuf;
4444 int result = 0;
4446 /* Arrange for X to be put in a register. */
4447 sprintf (buf, "1");
4448 x = strlen (buf);
4449 x = 2 * x - 1;
4451 setjmp (jbuf);
4452 if (longjmps_done == 1)
4454 /* Came here after the longjmp at the end of the function.
4456 If x == 1, the longjmp has restored the register to its
4457 value before the setjmp, and we can hope that setjmp
4458 saves all such registers in the jmp_buf, although that
4459 isn't sure.
4461 For other values of X, either something really strange is
4462 taking place, or the setjmp just didn't save the register. */
4464 if (x == 1)
4465 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4466 else
4468 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4469 exit (1);
4473 ++longjmps_done;
4474 x = 2;
4475 if (longjmps_done == 1)
4476 longjmp (jbuf, 1);
4479 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4482 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4484 /* Abort if anything GCPRO'd doesn't survive the GC. */
4486 static void
4487 check_gcpros ()
4489 struct gcpro *p;
4490 int i;
4492 for (p = gcprolist; p; p = p->next)
4493 for (i = 0; i < p->nvars; ++i)
4494 if (!survives_gc_p (p->var[i]))
4495 /* FIXME: It's not necessarily a bug. It might just be that the
4496 GCPRO is unnecessary or should release the object sooner. */
4497 abort ();
4500 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4502 static void
4503 dump_zombies ()
4505 int i;
4507 fprintf (stderr, "\nZombies kept alive = %d:\n", nzombies);
4508 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
4510 fprintf (stderr, " %d = ", i);
4511 debug_print (zombies[i]);
4515 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4518 /* Mark live Lisp objects on the C stack.
4520 There are several system-dependent problems to consider when
4521 porting this to new architectures:
4523 Processor Registers
4525 We have to mark Lisp objects in CPU registers that can hold local
4526 variables or are used to pass parameters.
4528 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4529 something that either saves relevant registers on the stack, or
4530 calls mark_maybe_object passing it each register's contents.
4532 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4533 implementation assumes that calling setjmp saves registers we need
4534 to see in a jmp_buf which itself lies on the stack. This doesn't
4535 have to be true! It must be verified for each system, possibly
4536 by taking a look at the source code of setjmp.
4538 Stack Layout
4540 Architectures differ in the way their processor stack is organized.
4541 For example, the stack might look like this
4543 +----------------+
4544 | Lisp_Object | size = 4
4545 +----------------+
4546 | something else | size = 2
4547 +----------------+
4548 | Lisp_Object | size = 4
4549 +----------------+
4550 | ... |
4552 In such a case, not every Lisp_Object will be aligned equally. To
4553 find all Lisp_Object on the stack it won't be sufficient to walk
4554 the stack in steps of 4 bytes. Instead, two passes will be
4555 necessary, one starting at the start of the stack, and a second
4556 pass starting at the start of the stack + 2. Likewise, if the
4557 minimal alignment of Lisp_Objects on the stack is 1, four passes
4558 would be necessary, each one starting with one byte more offset
4559 from the stack start.
4561 The current code assumes by default that Lisp_Objects are aligned
4562 equally on the stack. */
4564 static void
4565 mark_stack ()
4567 int i;
4568 /* jmp_buf may not be aligned enough on darwin-ppc64 */
4569 union aligned_jmpbuf {
4570 Lisp_Object o;
4571 jmp_buf j;
4572 } j;
4573 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
4574 void *end;
4576 /* This trick flushes the register windows so that all the state of
4577 the process is contained in the stack. */
4578 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
4579 needed on ia64 too. See mach_dep.c, where it also says inline
4580 assembler doesn't work with relevant proprietary compilers. */
4581 #ifdef sparc
4582 asm ("ta 3");
4583 #endif
4585 /* Save registers that we need to see on the stack. We need to see
4586 registers used to hold register variables and registers used to
4587 pass parameters. */
4588 #ifdef GC_SAVE_REGISTERS_ON_STACK
4589 GC_SAVE_REGISTERS_ON_STACK (end);
4590 #else /* not GC_SAVE_REGISTERS_ON_STACK */
4592 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
4593 setjmp will definitely work, test it
4594 and print a message with the result
4595 of the test. */
4596 if (!setjmp_tested_p)
4598 setjmp_tested_p = 1;
4599 test_setjmp ();
4601 #endif /* GC_SETJMP_WORKS */
4603 setjmp (j.j);
4604 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
4605 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
4607 /* This assumes that the stack is a contiguous region in memory. If
4608 that's not the case, something has to be done here to iterate
4609 over the stack segments. */
4610 #ifndef GC_LISP_OBJECT_ALIGNMENT
4611 #ifdef __GNUC__
4612 #define GC_LISP_OBJECT_ALIGNMENT __alignof__ (Lisp_Object)
4613 #else
4614 #define GC_LISP_OBJECT_ALIGNMENT sizeof (Lisp_Object)
4615 #endif
4616 #endif
4617 for (i = 0; i < sizeof (Lisp_Object); i += GC_LISP_OBJECT_ALIGNMENT)
4618 mark_memory (stack_base, end, i);
4619 /* Allow for marking a secondary stack, like the register stack on the
4620 ia64. */
4621 #ifdef GC_MARK_SECONDARY_STACK
4622 GC_MARK_SECONDARY_STACK ();
4623 #endif
4625 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4626 check_gcpros ();
4627 #endif
4630 #endif /* GC_MARK_STACK != 0 */
4633 /* Determine whether it is safe to access memory at address P. */
4635 valid_pointer_p (p)
4636 void *p;
4638 #ifdef WINDOWSNT
4639 return w32_valid_pointer_p (p, 16);
4640 #else
4641 int fd;
4643 /* Obviously, we cannot just access it (we would SEGV trying), so we
4644 trick the o/s to tell us whether p is a valid pointer.
4645 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4646 not validate p in that case. */
4648 if ((fd = emacs_open ("__Valid__Lisp__Object__", O_CREAT | O_WRONLY | O_TRUNC, 0666)) >= 0)
4650 int valid = (emacs_write (fd, (char *)p, 16) == 16);
4651 emacs_close (fd);
4652 unlink ("__Valid__Lisp__Object__");
4653 return valid;
4656 return -1;
4657 #endif
4660 /* Return 1 if OBJ is a valid lisp object.
4661 Return 0 if OBJ is NOT a valid lisp object.
4662 Return -1 if we cannot validate OBJ.
4663 This function can be quite slow,
4664 so it should only be used in code for manual debugging. */
4667 valid_lisp_object_p (obj)
4668 Lisp_Object obj;
4670 void *p;
4671 #if GC_MARK_STACK
4672 struct mem_node *m;
4673 #endif
4675 if (INTEGERP (obj))
4676 return 1;
4678 p = (void *) XPNTR (obj);
4679 if (PURE_POINTER_P (p))
4680 return 1;
4682 #if !GC_MARK_STACK
4683 return valid_pointer_p (p);
4684 #else
4686 m = mem_find (p);
4688 if (m == MEM_NIL)
4690 int valid = valid_pointer_p (p);
4691 if (valid <= 0)
4692 return valid;
4694 if (SUBRP (obj))
4695 return 1;
4697 return 0;
4700 switch (m->type)
4702 case MEM_TYPE_NON_LISP:
4703 return 0;
4705 case MEM_TYPE_BUFFER:
4706 return live_buffer_p (m, p);
4708 case MEM_TYPE_CONS:
4709 return live_cons_p (m, p);
4711 case MEM_TYPE_STRING:
4712 return live_string_p (m, p);
4714 case MEM_TYPE_MISC:
4715 return live_misc_p (m, p);
4717 case MEM_TYPE_SYMBOL:
4718 return live_symbol_p (m, p);
4720 case MEM_TYPE_FLOAT:
4721 return live_float_p (m, p);
4723 case MEM_TYPE_VECTOR:
4724 case MEM_TYPE_PROCESS:
4725 case MEM_TYPE_HASH_TABLE:
4726 case MEM_TYPE_FRAME:
4727 case MEM_TYPE_WINDOW:
4728 return live_vector_p (m, p);
4730 default:
4731 break;
4734 return 0;
4735 #endif
4741 /***********************************************************************
4742 Pure Storage Management
4743 ***********************************************************************/
4745 /* Allocate room for SIZE bytes from pure Lisp storage and return a
4746 pointer to it. TYPE is the Lisp type for which the memory is
4747 allocated. TYPE < 0 means it's not used for a Lisp object. */
4749 static POINTER_TYPE *
4750 pure_alloc (size, type)
4751 size_t size;
4752 int type;
4754 POINTER_TYPE *result;
4755 #ifdef USE_LSB_TAG
4756 size_t alignment = (1 << GCTYPEBITS);
4757 #else
4758 size_t alignment = sizeof (EMACS_INT);
4760 /* Give Lisp_Floats an extra alignment. */
4761 if (type == Lisp_Float)
4763 #if defined __GNUC__ && __GNUC__ >= 2
4764 alignment = __alignof (struct Lisp_Float);
4765 #else
4766 alignment = sizeof (struct Lisp_Float);
4767 #endif
4769 #endif
4771 again:
4772 if (type >= 0)
4774 /* Allocate space for a Lisp object from the beginning of the free
4775 space with taking account of alignment. */
4776 result = ALIGN (purebeg + pure_bytes_used_lisp, alignment);
4777 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
4779 else
4781 /* Allocate space for a non-Lisp object from the end of the free
4782 space. */
4783 pure_bytes_used_non_lisp += size;
4784 result = purebeg + pure_size - pure_bytes_used_non_lisp;
4786 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
4788 if (pure_bytes_used <= pure_size)
4789 return result;
4791 /* Don't allocate a large amount here,
4792 because it might get mmap'd and then its address
4793 might not be usable. */
4794 purebeg = (char *) xmalloc (10000);
4795 pure_size = 10000;
4796 pure_bytes_used_before_overflow += pure_bytes_used - size;
4797 pure_bytes_used = 0;
4798 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
4799 goto again;
4803 /* Print a warning if PURESIZE is too small. */
4805 void
4806 check_pure_size ()
4808 if (pure_bytes_used_before_overflow)
4809 message ("emacs:0:Pure Lisp storage overflow (approx. %d bytes needed)",
4810 (int) (pure_bytes_used + pure_bytes_used_before_overflow));
4814 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
4815 the non-Lisp data pool of the pure storage, and return its start
4816 address. Return NULL if not found. */
4818 static char *
4819 find_string_data_in_pure (data, nbytes)
4820 char *data;
4821 int nbytes;
4823 int i, skip, bm_skip[256], last_char_skip, infinity, start, start_max;
4824 unsigned char *p;
4825 char *non_lisp_beg;
4827 if (pure_bytes_used_non_lisp < nbytes + 1)
4828 return NULL;
4830 /* Set up the Boyer-Moore table. */
4831 skip = nbytes + 1;
4832 for (i = 0; i < 256; i++)
4833 bm_skip[i] = skip;
4835 p = (unsigned char *) data;
4836 while (--skip > 0)
4837 bm_skip[*p++] = skip;
4839 last_char_skip = bm_skip['\0'];
4841 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
4842 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
4844 /* See the comments in the function `boyer_moore' (search.c) for the
4845 use of `infinity'. */
4846 infinity = pure_bytes_used_non_lisp + 1;
4847 bm_skip['\0'] = infinity;
4849 p = (unsigned char *) non_lisp_beg + nbytes;
4850 start = 0;
4853 /* Check the last character (== '\0'). */
4856 start += bm_skip[*(p + start)];
4858 while (start <= start_max);
4860 if (start < infinity)
4861 /* Couldn't find the last character. */
4862 return NULL;
4864 /* No less than `infinity' means we could find the last
4865 character at `p[start - infinity]'. */
4866 start -= infinity;
4868 /* Check the remaining characters. */
4869 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
4870 /* Found. */
4871 return non_lisp_beg + start;
4873 start += last_char_skip;
4875 while (start <= start_max);
4877 return NULL;
4881 /* Return a string allocated in pure space. DATA is a buffer holding
4882 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
4883 non-zero means make the result string multibyte.
4885 Must get an error if pure storage is full, since if it cannot hold
4886 a large string it may be able to hold conses that point to that
4887 string; then the string is not protected from gc. */
4889 Lisp_Object
4890 make_pure_string (data, nchars, nbytes, multibyte)
4891 char *data;
4892 int nchars, nbytes;
4893 int multibyte;
4895 Lisp_Object string;
4896 struct Lisp_String *s;
4898 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
4899 s->data = find_string_data_in_pure (data, nbytes);
4900 if (s->data == NULL)
4902 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
4903 bcopy (data, s->data, nbytes);
4904 s->data[nbytes] = '\0';
4906 s->size = nchars;
4907 s->size_byte = multibyte ? nbytes : -1;
4908 s->intervals = NULL_INTERVAL;
4909 XSETSTRING (string, s);
4910 return string;
4914 /* Return a cons allocated from pure space. Give it pure copies
4915 of CAR as car and CDR as cdr. */
4917 Lisp_Object
4918 pure_cons (car, cdr)
4919 Lisp_Object car, cdr;
4921 register Lisp_Object new;
4922 struct Lisp_Cons *p;
4924 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
4925 XSETCONS (new, p);
4926 XSETCAR (new, Fpurecopy (car));
4927 XSETCDR (new, Fpurecopy (cdr));
4928 return new;
4932 /* Value is a float object with value NUM allocated from pure space. */
4934 Lisp_Object
4935 make_pure_float (num)
4936 double num;
4938 register Lisp_Object new;
4939 struct Lisp_Float *p;
4941 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
4942 XSETFLOAT (new, p);
4943 XFLOAT_DATA (new) = num;
4944 return new;
4948 /* Return a vector with room for LEN Lisp_Objects allocated from
4949 pure space. */
4951 Lisp_Object
4952 make_pure_vector (len)
4953 EMACS_INT len;
4955 Lisp_Object new;
4956 struct Lisp_Vector *p;
4957 size_t size = sizeof *p + (len - 1) * sizeof (Lisp_Object);
4959 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
4960 XSETVECTOR (new, p);
4961 XVECTOR (new)->size = len;
4962 return new;
4966 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
4967 doc: /* Make a copy of object OBJ in pure storage.
4968 Recursively copies contents of vectors and cons cells.
4969 Does not copy symbols. Copies strings without text properties. */)
4970 (obj)
4971 register Lisp_Object obj;
4973 if (NILP (Vpurify_flag))
4974 return obj;
4976 if (PURE_POINTER_P (XPNTR (obj)))
4977 return obj;
4979 if (CONSP (obj))
4980 return pure_cons (XCAR (obj), XCDR (obj));
4981 else if (FLOATP (obj))
4982 return make_pure_float (XFLOAT_DATA (obj));
4983 else if (STRINGP (obj))
4984 return make_pure_string (SDATA (obj), SCHARS (obj),
4985 SBYTES (obj),
4986 STRING_MULTIBYTE (obj));
4987 else if (COMPILEDP (obj) || VECTORP (obj))
4989 register struct Lisp_Vector *vec;
4990 register int i;
4991 EMACS_INT size;
4993 size = XVECTOR (obj)->size;
4994 if (size & PSEUDOVECTOR_FLAG)
4995 size &= PSEUDOVECTOR_SIZE_MASK;
4996 vec = XVECTOR (make_pure_vector (size));
4997 for (i = 0; i < size; i++)
4998 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
4999 if (COMPILEDP (obj))
5000 XSETCOMPILED (obj, vec);
5001 else
5002 XSETVECTOR (obj, vec);
5003 return obj;
5005 else if (MARKERP (obj))
5006 error ("Attempt to copy a marker to pure storage");
5008 return obj;
5013 /***********************************************************************
5014 Protection from GC
5015 ***********************************************************************/
5017 /* Put an entry in staticvec, pointing at the variable with address
5018 VARADDRESS. */
5020 void
5021 staticpro (varaddress)
5022 Lisp_Object *varaddress;
5024 staticvec[staticidx++] = varaddress;
5025 if (staticidx >= NSTATICS)
5026 abort ();
5029 struct catchtag
5031 Lisp_Object tag;
5032 Lisp_Object val;
5033 struct catchtag *next;
5037 /***********************************************************************
5038 Protection from GC
5039 ***********************************************************************/
5041 /* Temporarily prevent garbage collection. */
5044 inhibit_garbage_collection ()
5046 int count = SPECPDL_INDEX ();
5047 int nbits = min (VALBITS, BITS_PER_INT);
5049 specbind (Qgc_cons_threshold, make_number (((EMACS_INT) 1 << (nbits - 1)) - 1));
5050 return count;
5054 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
5055 doc: /* Reclaim storage for Lisp objects no longer needed.
5056 Garbage collection happens automatically if you cons more than
5057 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5058 `garbage-collect' normally returns a list with info on amount of space in use:
5059 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
5060 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
5061 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)
5062 (USED-STRINGS . FREE-STRINGS))
5063 However, if there was overflow in pure space, `garbage-collect'
5064 returns nil, because real GC can't be done. */)
5067 register struct specbinding *bind;
5068 struct catchtag *catch;
5069 struct handler *handler;
5070 char stack_top_variable;
5071 register int i;
5072 int message_p;
5073 Lisp_Object total[8];
5074 int count = SPECPDL_INDEX ();
5075 EMACS_TIME t1, t2, t3;
5077 if (abort_on_gc)
5078 abort ();
5080 /* Can't GC if pure storage overflowed because we can't determine
5081 if something is a pure object or not. */
5082 if (pure_bytes_used_before_overflow)
5083 return Qnil;
5085 CHECK_CONS_LIST ();
5087 /* Don't keep undo information around forever.
5088 Do this early on, so it is no problem if the user quits. */
5090 register struct buffer *nextb = all_buffers;
5092 while (nextb)
5094 /* If a buffer's undo list is Qt, that means that undo is
5095 turned off in that buffer. Calling truncate_undo_list on
5096 Qt tends to return NULL, which effectively turns undo back on.
5097 So don't call truncate_undo_list if undo_list is Qt. */
5098 if (! NILP (nextb->name) && ! EQ (nextb->undo_list, Qt))
5099 truncate_undo_list (nextb);
5101 /* Shrink buffer gaps, but skip indirect and dead buffers. */
5102 if (nextb->base_buffer == 0 && !NILP (nextb->name))
5104 /* If a buffer's gap size is more than 10% of the buffer
5105 size, or larger than 2000 bytes, then shrink it
5106 accordingly. Keep a minimum size of 20 bytes. */
5107 int size = min (2000, max (20, (nextb->text->z_byte / 10)));
5109 if (nextb->text->gap_size > size)
5111 struct buffer *save_current = current_buffer;
5112 current_buffer = nextb;
5113 make_gap (-(nextb->text->gap_size - size));
5114 current_buffer = save_current;
5118 nextb = nextb->next;
5122 EMACS_GET_TIME (t1);
5124 /* In case user calls debug_print during GC,
5125 don't let that cause a recursive GC. */
5126 consing_since_gc = 0;
5128 /* Save what's currently displayed in the echo area. */
5129 message_p = push_message ();
5130 record_unwind_protect (pop_message_unwind, Qnil);
5132 /* Save a copy of the contents of the stack, for debugging. */
5133 #if MAX_SAVE_STACK > 0
5134 if (NILP (Vpurify_flag))
5136 i = &stack_top_variable - stack_bottom;
5137 if (i < 0) i = -i;
5138 if (i < MAX_SAVE_STACK)
5140 if (stack_copy == 0)
5141 stack_copy = (char *) xmalloc (stack_copy_size = i);
5142 else if (stack_copy_size < i)
5143 stack_copy = (char *) xrealloc (stack_copy, (stack_copy_size = i));
5144 if (stack_copy)
5146 if ((EMACS_INT) (&stack_top_variable - stack_bottom) > 0)
5147 bcopy (stack_bottom, stack_copy, i);
5148 else
5149 bcopy (&stack_top_variable, stack_copy, i);
5153 #endif /* MAX_SAVE_STACK > 0 */
5155 if (garbage_collection_messages)
5156 message1_nolog ("Garbage collecting...");
5158 BLOCK_INPUT;
5160 shrink_regexp_cache ();
5162 gc_in_progress = 1;
5164 /* clear_marks (); */
5166 /* Mark all the special slots that serve as the roots of accessibility. */
5168 for (i = 0; i < staticidx; i++)
5169 mark_object (*staticvec[i]);
5171 for (bind = specpdl; bind != specpdl_ptr; bind++)
5173 mark_object (bind->symbol);
5174 mark_object (bind->old_value);
5176 mark_terminals ();
5177 mark_kboards ();
5178 mark_ttys ();
5180 #ifdef USE_GTK
5182 extern void xg_mark_data ();
5183 xg_mark_data ();
5185 #endif
5187 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
5188 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
5189 mark_stack ();
5190 #else
5192 register struct gcpro *tail;
5193 for (tail = gcprolist; tail; tail = tail->next)
5194 for (i = 0; i < tail->nvars; i++)
5195 mark_object (tail->var[i]);
5197 #endif
5199 mark_byte_stack ();
5200 for (catch = catchlist; catch; catch = catch->next)
5202 mark_object (catch->tag);
5203 mark_object (catch->val);
5205 for (handler = handlerlist; handler; handler = handler->next)
5207 mark_object (handler->handler);
5208 mark_object (handler->var);
5210 mark_backtrace ();
5212 #ifdef HAVE_WINDOW_SYSTEM
5213 mark_fringe_data ();
5214 #endif
5216 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5217 mark_stack ();
5218 #endif
5220 /* Everything is now marked, except for the things that require special
5221 finalization, i.e. the undo_list.
5222 Look thru every buffer's undo list
5223 for elements that update markers that were not marked,
5224 and delete them. */
5226 register struct buffer *nextb = all_buffers;
5228 while (nextb)
5230 /* If a buffer's undo list is Qt, that means that undo is
5231 turned off in that buffer. Calling truncate_undo_list on
5232 Qt tends to return NULL, which effectively turns undo back on.
5233 So don't call truncate_undo_list if undo_list is Qt. */
5234 if (! EQ (nextb->undo_list, Qt))
5236 Lisp_Object tail, prev;
5237 tail = nextb->undo_list;
5238 prev = Qnil;
5239 while (CONSP (tail))
5241 if (GC_CONSP (XCAR (tail))
5242 && GC_MARKERP (XCAR (XCAR (tail)))
5243 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5245 if (NILP (prev))
5246 nextb->undo_list = tail = XCDR (tail);
5247 else
5249 tail = XCDR (tail);
5250 XSETCDR (prev, tail);
5253 else
5255 prev = tail;
5256 tail = XCDR (tail);
5260 /* Now that we have stripped the elements that need not be in the
5261 undo_list any more, we can finally mark the list. */
5262 mark_object (nextb->undo_list);
5264 nextb = nextb->next;
5268 gc_sweep ();
5270 /* Clear the mark bits that we set in certain root slots. */
5272 unmark_byte_stack ();
5273 VECTOR_UNMARK (&buffer_defaults);
5274 VECTOR_UNMARK (&buffer_local_symbols);
5276 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
5277 dump_zombies ();
5278 #endif
5280 UNBLOCK_INPUT;
5282 CHECK_CONS_LIST ();
5284 /* clear_marks (); */
5285 gc_in_progress = 0;
5287 consing_since_gc = 0;
5288 if (gc_cons_threshold < 10000)
5289 gc_cons_threshold = 10000;
5291 if (FLOATP (Vgc_cons_percentage))
5292 { /* Set gc_cons_combined_threshold. */
5293 EMACS_INT total = 0;
5295 total += total_conses * sizeof (struct Lisp_Cons);
5296 total += total_symbols * sizeof (struct Lisp_Symbol);
5297 total += total_markers * sizeof (union Lisp_Misc);
5298 total += total_string_size;
5299 total += total_vector_size * sizeof (Lisp_Object);
5300 total += total_floats * sizeof (struct Lisp_Float);
5301 total += total_intervals * sizeof (struct interval);
5302 total += total_strings * sizeof (struct Lisp_String);
5304 gc_relative_threshold = total * XFLOAT_DATA (Vgc_cons_percentage);
5306 else
5307 gc_relative_threshold = 0;
5309 if (garbage_collection_messages)
5311 if (message_p || minibuf_level > 0)
5312 restore_message ();
5313 else
5314 message1_nolog ("Garbage collecting...done");
5317 unbind_to (count, Qnil);
5319 total[0] = Fcons (make_number (total_conses),
5320 make_number (total_free_conses));
5321 total[1] = Fcons (make_number (total_symbols),
5322 make_number (total_free_symbols));
5323 total[2] = Fcons (make_number (total_markers),
5324 make_number (total_free_markers));
5325 total[3] = make_number (total_string_size);
5326 total[4] = make_number (total_vector_size);
5327 total[5] = Fcons (make_number (total_floats),
5328 make_number (total_free_floats));
5329 total[6] = Fcons (make_number (total_intervals),
5330 make_number (total_free_intervals));
5331 total[7] = Fcons (make_number (total_strings),
5332 make_number (total_free_strings));
5334 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5336 /* Compute average percentage of zombies. */
5337 double nlive = 0;
5339 for (i = 0; i < 7; ++i)
5340 if (CONSP (total[i]))
5341 nlive += XFASTINT (XCAR (total[i]));
5343 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
5344 max_live = max (nlive, max_live);
5345 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
5346 max_zombies = max (nzombies, max_zombies);
5347 ++ngcs;
5349 #endif
5351 if (!NILP (Vpost_gc_hook))
5353 int count = inhibit_garbage_collection ();
5354 safe_run_hooks (Qpost_gc_hook);
5355 unbind_to (count, Qnil);
5358 /* Accumulate statistics. */
5359 EMACS_GET_TIME (t2);
5360 EMACS_SUB_TIME (t3, t2, t1);
5361 if (FLOATP (Vgc_elapsed))
5362 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed) +
5363 EMACS_SECS (t3) +
5364 EMACS_USECS (t3) * 1.0e-6);
5365 gcs_done++;
5367 return Flist (sizeof total / sizeof *total, total);
5371 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5372 only interesting objects referenced from glyphs are strings. */
5374 static void
5375 mark_glyph_matrix (matrix)
5376 struct glyph_matrix *matrix;
5378 struct glyph_row *row = matrix->rows;
5379 struct glyph_row *end = row + matrix->nrows;
5381 for (; row < end; ++row)
5382 if (row->enabled_p)
5384 int area;
5385 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
5387 struct glyph *glyph = row->glyphs[area];
5388 struct glyph *end_glyph = glyph + row->used[area];
5390 for (; glyph < end_glyph; ++glyph)
5391 if (GC_STRINGP (glyph->object)
5392 && !STRING_MARKED_P (XSTRING (glyph->object)))
5393 mark_object (glyph->object);
5399 /* Mark Lisp faces in the face cache C. */
5401 static void
5402 mark_face_cache (c)
5403 struct face_cache *c;
5405 if (c)
5407 int i, j;
5408 for (i = 0; i < c->used; ++i)
5410 struct face *face = FACE_FROM_ID (c->f, i);
5412 if (face)
5414 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
5415 mark_object (face->lface[j]);
5422 #ifdef HAVE_WINDOW_SYSTEM
5424 /* Mark Lisp objects in image IMG. */
5426 static void
5427 mark_image (img)
5428 struct image *img;
5430 mark_object (img->spec);
5432 if (!NILP (img->data.lisp_val))
5433 mark_object (img->data.lisp_val);
5437 /* Mark Lisp objects in image cache of frame F. It's done this way so
5438 that we don't have to include xterm.h here. */
5440 static void
5441 mark_image_cache (f)
5442 struct frame *f;
5444 forall_images_in_image_cache (f, mark_image);
5447 #endif /* HAVE_X_WINDOWS */
5451 /* Mark reference to a Lisp_Object.
5452 If the object referred to has not been seen yet, recursively mark
5453 all the references contained in it. */
5455 #define LAST_MARKED_SIZE 500
5456 Lisp_Object last_marked[LAST_MARKED_SIZE];
5457 int last_marked_index;
5459 /* For debugging--call abort when we cdr down this many
5460 links of a list, in mark_object. In debugging,
5461 the call to abort will hit a breakpoint.
5462 Normally this is zero and the check never goes off. */
5463 int mark_object_loop_halt;
5465 void
5466 mark_object (arg)
5467 Lisp_Object arg;
5469 register Lisp_Object obj = arg;
5470 #ifdef GC_CHECK_MARKED_OBJECTS
5471 void *po;
5472 struct mem_node *m;
5473 #endif
5474 int cdr_count = 0;
5476 loop:
5478 if (PURE_POINTER_P (XPNTR (obj)))
5479 return;
5481 last_marked[last_marked_index++] = obj;
5482 if (last_marked_index == LAST_MARKED_SIZE)
5483 last_marked_index = 0;
5485 /* Perform some sanity checks on the objects marked here. Abort if
5486 we encounter an object we know is bogus. This increases GC time
5487 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
5488 #ifdef GC_CHECK_MARKED_OBJECTS
5490 po = (void *) XPNTR (obj);
5492 /* Check that the object pointed to by PO is known to be a Lisp
5493 structure allocated from the heap. */
5494 #define CHECK_ALLOCATED() \
5495 do { \
5496 m = mem_find (po); \
5497 if (m == MEM_NIL) \
5498 abort (); \
5499 } while (0)
5501 /* Check that the object pointed to by PO is live, using predicate
5502 function LIVEP. */
5503 #define CHECK_LIVE(LIVEP) \
5504 do { \
5505 if (!LIVEP (m, po)) \
5506 abort (); \
5507 } while (0)
5509 /* Check both of the above conditions. */
5510 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
5511 do { \
5512 CHECK_ALLOCATED (); \
5513 CHECK_LIVE (LIVEP); \
5514 } while (0) \
5516 #else /* not GC_CHECK_MARKED_OBJECTS */
5518 #define CHECK_ALLOCATED() (void) 0
5519 #define CHECK_LIVE(LIVEP) (void) 0
5520 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
5522 #endif /* not GC_CHECK_MARKED_OBJECTS */
5524 switch (SWITCH_ENUM_CAST (XGCTYPE (obj)))
5526 case Lisp_String:
5528 register struct Lisp_String *ptr = XSTRING (obj);
5529 CHECK_ALLOCATED_AND_LIVE (live_string_p);
5530 MARK_INTERVAL_TREE (ptr->intervals);
5531 MARK_STRING (ptr);
5532 #ifdef GC_CHECK_STRING_BYTES
5533 /* Check that the string size recorded in the string is the
5534 same as the one recorded in the sdata structure. */
5535 CHECK_STRING_BYTES (ptr);
5536 #endif /* GC_CHECK_STRING_BYTES */
5538 break;
5540 case Lisp_Vectorlike:
5541 #ifdef GC_CHECK_MARKED_OBJECTS
5542 m = mem_find (po);
5543 if (m == MEM_NIL && !GC_SUBRP (obj)
5544 && po != &buffer_defaults
5545 && po != &buffer_local_symbols)
5546 abort ();
5547 #endif /* GC_CHECK_MARKED_OBJECTS */
5549 if (GC_BUFFERP (obj))
5551 if (!VECTOR_MARKED_P (XBUFFER (obj)))
5553 #ifdef GC_CHECK_MARKED_OBJECTS
5554 if (po != &buffer_defaults && po != &buffer_local_symbols)
5556 struct buffer *b;
5557 for (b = all_buffers; b && b != po; b = b->next)
5559 if (b == NULL)
5560 abort ();
5562 #endif /* GC_CHECK_MARKED_OBJECTS */
5563 mark_buffer (obj);
5566 else if (GC_SUBRP (obj))
5567 break;
5568 else if (GC_COMPILEDP (obj))
5569 /* We could treat this just like a vector, but it is better to
5570 save the COMPILED_CONSTANTS element for last and avoid
5571 recursion there. */
5573 register struct Lisp_Vector *ptr = XVECTOR (obj);
5574 register EMACS_INT size = ptr->size;
5575 register int i;
5577 if (VECTOR_MARKED_P (ptr))
5578 break; /* Already marked */
5580 CHECK_LIVE (live_vector_p);
5581 VECTOR_MARK (ptr); /* Else mark it */
5582 size &= PSEUDOVECTOR_SIZE_MASK;
5583 for (i = 0; i < size; i++) /* and then mark its elements */
5585 if (i != COMPILED_CONSTANTS)
5586 mark_object (ptr->contents[i]);
5588 obj = ptr->contents[COMPILED_CONSTANTS];
5589 goto loop;
5591 else if (GC_FRAMEP (obj))
5593 register struct frame *ptr = XFRAME (obj);
5595 if (VECTOR_MARKED_P (ptr)) break; /* Already marked */
5596 VECTOR_MARK (ptr); /* Else mark it */
5598 CHECK_LIVE (live_vector_p);
5599 mark_object (ptr->name);
5600 mark_object (ptr->icon_name);
5601 mark_object (ptr->title);
5602 mark_object (ptr->focus_frame);
5603 mark_object (ptr->selected_window);
5604 mark_object (ptr->minibuffer_window);
5605 mark_object (ptr->param_alist);
5606 mark_object (ptr->scroll_bars);
5607 mark_object (ptr->condemned_scroll_bars);
5608 mark_object (ptr->menu_bar_items);
5609 mark_object (ptr->face_alist);
5610 mark_object (ptr->menu_bar_vector);
5611 mark_object (ptr->buffer_predicate);
5612 mark_object (ptr->buffer_list);
5613 mark_object (ptr->buried_buffer_list);
5614 mark_object (ptr->menu_bar_window);
5615 mark_object (ptr->tool_bar_window);
5616 mark_face_cache (ptr->face_cache);
5617 #ifdef HAVE_WINDOW_SYSTEM
5618 mark_image_cache (ptr);
5619 mark_object (ptr->tool_bar_items);
5620 mark_object (ptr->desired_tool_bar_string);
5621 mark_object (ptr->current_tool_bar_string);
5622 #endif /* HAVE_WINDOW_SYSTEM */
5624 else if (GC_BOOL_VECTOR_P (obj))
5626 register struct Lisp_Vector *ptr = XVECTOR (obj);
5628 if (VECTOR_MARKED_P (ptr))
5629 break; /* Already marked */
5630 CHECK_LIVE (live_vector_p);
5631 VECTOR_MARK (ptr); /* Else mark it */
5633 else if (GC_WINDOWP (obj))
5635 register struct Lisp_Vector *ptr = XVECTOR (obj);
5636 struct window *w = XWINDOW (obj);
5637 register int i;
5639 /* Stop if already marked. */
5640 if (VECTOR_MARKED_P (ptr))
5641 break;
5643 /* Mark it. */
5644 CHECK_LIVE (live_vector_p);
5645 VECTOR_MARK (ptr);
5647 /* There is no Lisp data above The member CURRENT_MATRIX in
5648 struct WINDOW. Stop marking when that slot is reached. */
5649 for (i = 0;
5650 (char *) &ptr->contents[i] < (char *) &w->current_matrix;
5651 i++)
5652 mark_object (ptr->contents[i]);
5654 /* Mark glyphs for leaf windows. Marking window matrices is
5655 sufficient because frame matrices use the same glyph
5656 memory. */
5657 if (NILP (w->hchild)
5658 && NILP (w->vchild)
5659 && w->current_matrix)
5661 mark_glyph_matrix (w->current_matrix);
5662 mark_glyph_matrix (w->desired_matrix);
5665 else if (GC_HASH_TABLE_P (obj))
5667 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
5669 /* Stop if already marked. */
5670 if (VECTOR_MARKED_P (h))
5671 break;
5673 /* Mark it. */
5674 CHECK_LIVE (live_vector_p);
5675 VECTOR_MARK (h);
5677 /* Mark contents. */
5678 /* Do not mark next_free or next_weak.
5679 Being in the next_weak chain
5680 should not keep the hash table alive.
5681 No need to mark `count' since it is an integer. */
5682 mark_object (h->test);
5683 mark_object (h->weak);
5684 mark_object (h->rehash_size);
5685 mark_object (h->rehash_threshold);
5686 mark_object (h->hash);
5687 mark_object (h->next);
5688 mark_object (h->index);
5689 mark_object (h->user_hash_function);
5690 mark_object (h->user_cmp_function);
5692 /* If hash table is not weak, mark all keys and values.
5693 For weak tables, mark only the vector. */
5694 if (GC_NILP (h->weak))
5695 mark_object (h->key_and_value);
5696 else
5697 VECTOR_MARK (XVECTOR (h->key_and_value));
5699 else
5701 register struct Lisp_Vector *ptr = XVECTOR (obj);
5702 register EMACS_INT size = ptr->size;
5703 register int i;
5705 if (VECTOR_MARKED_P (ptr)) break; /* Already marked */
5706 CHECK_LIVE (live_vector_p);
5707 VECTOR_MARK (ptr); /* Else mark it */
5708 if (size & PSEUDOVECTOR_FLAG)
5709 size &= PSEUDOVECTOR_SIZE_MASK;
5711 /* Note that this size is not the memory-footprint size, but only
5712 the number of Lisp_Object fields that we should trace.
5713 The distinction is used e.g. by Lisp_Process which places extra
5714 non-Lisp_Object fields at the end of the structure. */
5715 for (i = 0; i < size; i++) /* and then mark its elements */
5716 mark_object (ptr->contents[i]);
5718 break;
5720 case Lisp_Symbol:
5722 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
5723 struct Lisp_Symbol *ptrx;
5725 if (ptr->gcmarkbit) break;
5726 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
5727 ptr->gcmarkbit = 1;
5728 mark_object (ptr->value);
5729 mark_object (ptr->function);
5730 mark_object (ptr->plist);
5732 if (!PURE_POINTER_P (XSTRING (ptr->xname)))
5733 MARK_STRING (XSTRING (ptr->xname));
5734 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr->xname));
5736 /* Note that we do not mark the obarray of the symbol.
5737 It is safe not to do so because nothing accesses that
5738 slot except to check whether it is nil. */
5739 ptr = ptr->next;
5740 if (ptr)
5742 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
5743 XSETSYMBOL (obj, ptrx);
5744 goto loop;
5747 break;
5749 case Lisp_Misc:
5750 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
5751 if (XMARKER (obj)->gcmarkbit)
5752 break;
5753 XMARKER (obj)->gcmarkbit = 1;
5755 switch (XMISCTYPE (obj))
5757 case Lisp_Misc_Buffer_Local_Value:
5758 case Lisp_Misc_Some_Buffer_Local_Value:
5760 register struct Lisp_Buffer_Local_Value *ptr
5761 = XBUFFER_LOCAL_VALUE (obj);
5762 /* If the cdr is nil, avoid recursion for the car. */
5763 if (EQ (ptr->cdr, Qnil))
5765 obj = ptr->realvalue;
5766 goto loop;
5768 mark_object (ptr->realvalue);
5769 mark_object (ptr->buffer);
5770 mark_object (ptr->frame);
5771 obj = ptr->cdr;
5772 goto loop;
5775 case Lisp_Misc_Marker:
5776 /* DO NOT mark thru the marker's chain.
5777 The buffer's markers chain does not preserve markers from gc;
5778 instead, markers are removed from the chain when freed by gc. */
5779 break;
5781 case Lisp_Misc_Intfwd:
5782 case Lisp_Misc_Boolfwd:
5783 case Lisp_Misc_Objfwd:
5784 case Lisp_Misc_Buffer_Objfwd:
5785 case Lisp_Misc_Kboard_Objfwd:
5786 /* Don't bother with Lisp_Buffer_Objfwd,
5787 since all markable slots in current buffer marked anyway. */
5788 /* Don't need to do Lisp_Objfwd, since the places they point
5789 are protected with staticpro. */
5790 break;
5792 case Lisp_Misc_Save_Value:
5793 #if GC_MARK_STACK
5795 register struct Lisp_Save_Value *ptr = XSAVE_VALUE (obj);
5796 /* If DOGC is set, POINTER is the address of a memory
5797 area containing INTEGER potential Lisp_Objects. */
5798 if (ptr->dogc)
5800 Lisp_Object *p = (Lisp_Object *) ptr->pointer;
5801 int nelt;
5802 for (nelt = ptr->integer; nelt > 0; nelt--, p++)
5803 mark_maybe_object (*p);
5806 #endif
5807 break;
5809 case Lisp_Misc_Overlay:
5811 struct Lisp_Overlay *ptr = XOVERLAY (obj);
5812 mark_object (ptr->start);
5813 mark_object (ptr->end);
5814 mark_object (ptr->plist);
5815 if (ptr->next)
5817 XSETMISC (obj, ptr->next);
5818 goto loop;
5821 break;
5823 default:
5824 abort ();
5826 break;
5828 case Lisp_Cons:
5830 register struct Lisp_Cons *ptr = XCONS (obj);
5831 if (CONS_MARKED_P (ptr)) break;
5832 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
5833 CONS_MARK (ptr);
5834 /* If the cdr is nil, avoid recursion for the car. */
5835 if (EQ (ptr->u.cdr, Qnil))
5837 obj = ptr->car;
5838 cdr_count = 0;
5839 goto loop;
5841 mark_object (ptr->car);
5842 obj = ptr->u.cdr;
5843 cdr_count++;
5844 if (cdr_count == mark_object_loop_halt)
5845 abort ();
5846 goto loop;
5849 case Lisp_Float:
5850 CHECK_ALLOCATED_AND_LIVE (live_float_p);
5851 FLOAT_MARK (XFLOAT (obj));
5852 break;
5854 case Lisp_Int:
5855 break;
5857 default:
5858 abort ();
5861 #undef CHECK_LIVE
5862 #undef CHECK_ALLOCATED
5863 #undef CHECK_ALLOCATED_AND_LIVE
5866 /* Mark the pointers in a buffer structure. */
5868 static void
5869 mark_buffer (buf)
5870 Lisp_Object buf;
5872 register struct buffer *buffer = XBUFFER (buf);
5873 register Lisp_Object *ptr, tmp;
5874 Lisp_Object base_buffer;
5876 VECTOR_MARK (buffer);
5878 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
5880 /* For now, we just don't mark the undo_list. It's done later in
5881 a special way just before the sweep phase, and after stripping
5882 some of its elements that are not needed any more. */
5884 if (buffer->overlays_before)
5886 XSETMISC (tmp, buffer->overlays_before);
5887 mark_object (tmp);
5889 if (buffer->overlays_after)
5891 XSETMISC (tmp, buffer->overlays_after);
5892 mark_object (tmp);
5895 for (ptr = &buffer->name;
5896 (char *)ptr < (char *)buffer + sizeof (struct buffer);
5897 ptr++)
5898 mark_object (*ptr);
5900 /* If this is an indirect buffer, mark its base buffer. */
5901 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5903 XSETBUFFER (base_buffer, buffer->base_buffer);
5904 mark_buffer (base_buffer);
5909 /* Value is non-zero if OBJ will survive the current GC because it's
5910 either marked or does not need to be marked to survive. */
5913 survives_gc_p (obj)
5914 Lisp_Object obj;
5916 int survives_p;
5918 switch (XGCTYPE (obj))
5920 case Lisp_Int:
5921 survives_p = 1;
5922 break;
5924 case Lisp_Symbol:
5925 survives_p = XSYMBOL (obj)->gcmarkbit;
5926 break;
5928 case Lisp_Misc:
5929 survives_p = XMARKER (obj)->gcmarkbit;
5930 break;
5932 case Lisp_String:
5933 survives_p = STRING_MARKED_P (XSTRING (obj));
5934 break;
5936 case Lisp_Vectorlike:
5937 survives_p = GC_SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
5938 break;
5940 case Lisp_Cons:
5941 survives_p = CONS_MARKED_P (XCONS (obj));
5942 break;
5944 case Lisp_Float:
5945 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
5946 break;
5948 default:
5949 abort ();
5952 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
5957 /* Sweep: find all structures not marked, and free them. */
5959 static void
5960 gc_sweep ()
5962 /* Remove or mark entries in weak hash tables.
5963 This must be done before any object is unmarked. */
5964 sweep_weak_hash_tables ();
5966 sweep_strings ();
5967 #ifdef GC_CHECK_STRING_BYTES
5968 if (!noninteractive)
5969 check_string_bytes (1);
5970 #endif
5972 /* Put all unmarked conses on free list */
5974 register struct cons_block *cblk;
5975 struct cons_block **cprev = &cons_block;
5976 register int lim = cons_block_index;
5977 register int num_free = 0, num_used = 0;
5979 cons_free_list = 0;
5981 for (cblk = cons_block; cblk; cblk = *cprev)
5983 register int i;
5984 int this_free = 0;
5985 for (i = 0; i < lim; i++)
5986 if (!CONS_MARKED_P (&cblk->conses[i]))
5988 this_free++;
5989 cblk->conses[i].u.chain = cons_free_list;
5990 cons_free_list = &cblk->conses[i];
5991 #if GC_MARK_STACK
5992 cons_free_list->car = Vdead;
5993 #endif
5995 else
5997 num_used++;
5998 CONS_UNMARK (&cblk->conses[i]);
6000 lim = CONS_BLOCK_SIZE;
6001 /* If this block contains only free conses and we have already
6002 seen more than two blocks worth of free conses then deallocate
6003 this block. */
6004 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
6006 *cprev = cblk->next;
6007 /* Unhook from the free list. */
6008 cons_free_list = cblk->conses[0].u.chain;
6009 lisp_align_free (cblk);
6010 n_cons_blocks--;
6012 else
6014 num_free += this_free;
6015 cprev = &cblk->next;
6018 total_conses = num_used;
6019 total_free_conses = num_free;
6022 /* Put all unmarked floats on free list */
6024 register struct float_block *fblk;
6025 struct float_block **fprev = &float_block;
6026 register int lim = float_block_index;
6027 register int num_free = 0, num_used = 0;
6029 float_free_list = 0;
6031 for (fblk = float_block; fblk; fblk = *fprev)
6033 register int i;
6034 int this_free = 0;
6035 for (i = 0; i < lim; i++)
6036 if (!FLOAT_MARKED_P (&fblk->floats[i]))
6038 this_free++;
6039 fblk->floats[i].u.chain = float_free_list;
6040 float_free_list = &fblk->floats[i];
6042 else
6044 num_used++;
6045 FLOAT_UNMARK (&fblk->floats[i]);
6047 lim = FLOAT_BLOCK_SIZE;
6048 /* If this block contains only free floats and we have already
6049 seen more than two blocks worth of free floats then deallocate
6050 this block. */
6051 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6053 *fprev = fblk->next;
6054 /* Unhook from the free list. */
6055 float_free_list = fblk->floats[0].u.chain;
6056 lisp_align_free (fblk);
6057 n_float_blocks--;
6059 else
6061 num_free += this_free;
6062 fprev = &fblk->next;
6065 total_floats = num_used;
6066 total_free_floats = num_free;
6069 /* Put all unmarked intervals on free list */
6071 register struct interval_block *iblk;
6072 struct interval_block **iprev = &interval_block;
6073 register int lim = interval_block_index;
6074 register int num_free = 0, num_used = 0;
6076 interval_free_list = 0;
6078 for (iblk = interval_block; iblk; iblk = *iprev)
6080 register int i;
6081 int this_free = 0;
6083 for (i = 0; i < lim; i++)
6085 if (!iblk->intervals[i].gcmarkbit)
6087 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
6088 interval_free_list = &iblk->intervals[i];
6089 this_free++;
6091 else
6093 num_used++;
6094 iblk->intervals[i].gcmarkbit = 0;
6097 lim = INTERVAL_BLOCK_SIZE;
6098 /* If this block contains only free intervals and we have already
6099 seen more than two blocks worth of free intervals then
6100 deallocate this block. */
6101 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6103 *iprev = iblk->next;
6104 /* Unhook from the free list. */
6105 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
6106 lisp_free (iblk);
6107 n_interval_blocks--;
6109 else
6111 num_free += this_free;
6112 iprev = &iblk->next;
6115 total_intervals = num_used;
6116 total_free_intervals = num_free;
6119 /* Put all unmarked symbols on free list */
6121 register struct symbol_block *sblk;
6122 struct symbol_block **sprev = &symbol_block;
6123 register int lim = symbol_block_index;
6124 register int num_free = 0, num_used = 0;
6126 symbol_free_list = NULL;
6128 for (sblk = symbol_block; sblk; sblk = *sprev)
6130 int this_free = 0;
6131 struct Lisp_Symbol *sym = sblk->symbols;
6132 struct Lisp_Symbol *end = sym + lim;
6134 for (; sym < end; ++sym)
6136 /* Check if the symbol was created during loadup. In such a case
6137 it might be pointed to by pure bytecode which we don't trace,
6138 so we conservatively assume that it is live. */
6139 int pure_p = PURE_POINTER_P (XSTRING (sym->xname));
6141 if (!sym->gcmarkbit && !pure_p)
6143 sym->next = symbol_free_list;
6144 symbol_free_list = sym;
6145 #if GC_MARK_STACK
6146 symbol_free_list->function = Vdead;
6147 #endif
6148 ++this_free;
6150 else
6152 ++num_used;
6153 if (!pure_p)
6154 UNMARK_STRING (XSTRING (sym->xname));
6155 sym->gcmarkbit = 0;
6159 lim = SYMBOL_BLOCK_SIZE;
6160 /* If this block contains only free symbols and we have already
6161 seen more than two blocks worth of free symbols then deallocate
6162 this block. */
6163 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6165 *sprev = sblk->next;
6166 /* Unhook from the free list. */
6167 symbol_free_list = sblk->symbols[0].next;
6168 lisp_free (sblk);
6169 n_symbol_blocks--;
6171 else
6173 num_free += this_free;
6174 sprev = &sblk->next;
6177 total_symbols = num_used;
6178 total_free_symbols = num_free;
6181 /* Put all unmarked misc's on free list.
6182 For a marker, first unchain it from the buffer it points into. */
6184 register struct marker_block *mblk;
6185 struct marker_block **mprev = &marker_block;
6186 register int lim = marker_block_index;
6187 register int num_free = 0, num_used = 0;
6189 marker_free_list = 0;
6191 for (mblk = marker_block; mblk; mblk = *mprev)
6193 register int i;
6194 int this_free = 0;
6196 for (i = 0; i < lim; i++)
6198 if (!mblk->markers[i].u_marker.gcmarkbit)
6200 if (mblk->markers[i].u_marker.type == Lisp_Misc_Marker)
6201 unchain_marker (&mblk->markers[i].u_marker);
6202 /* Set the type of the freed object to Lisp_Misc_Free.
6203 We could leave the type alone, since nobody checks it,
6204 but this might catch bugs faster. */
6205 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
6206 mblk->markers[i].u_free.chain = marker_free_list;
6207 marker_free_list = &mblk->markers[i];
6208 this_free++;
6210 else
6212 num_used++;
6213 mblk->markers[i].u_marker.gcmarkbit = 0;
6216 lim = MARKER_BLOCK_SIZE;
6217 /* If this block contains only free markers and we have already
6218 seen more than two blocks worth of free markers then deallocate
6219 this block. */
6220 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6222 *mprev = mblk->next;
6223 /* Unhook from the free list. */
6224 marker_free_list = mblk->markers[0].u_free.chain;
6225 lisp_free (mblk);
6226 n_marker_blocks--;
6228 else
6230 num_free += this_free;
6231 mprev = &mblk->next;
6235 total_markers = num_used;
6236 total_free_markers = num_free;
6239 /* Free all unmarked buffers */
6241 register struct buffer *buffer = all_buffers, *prev = 0, *next;
6243 while (buffer)
6244 if (!VECTOR_MARKED_P (buffer))
6246 if (prev)
6247 prev->next = buffer->next;
6248 else
6249 all_buffers = buffer->next;
6250 next = buffer->next;
6251 lisp_free (buffer);
6252 buffer = next;
6254 else
6256 VECTOR_UNMARK (buffer);
6257 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
6258 prev = buffer, buffer = buffer->next;
6262 /* Free all unmarked vectors */
6264 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
6265 total_vector_size = 0;
6267 while (vector)
6268 if (!VECTOR_MARKED_P (vector))
6270 if (prev)
6271 prev->next = vector->next;
6272 else
6273 all_vectors = vector->next;
6274 next = vector->next;
6275 lisp_free (vector);
6276 n_vectors--;
6277 vector = next;
6280 else
6282 VECTOR_UNMARK (vector);
6283 if (vector->size & PSEUDOVECTOR_FLAG)
6284 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
6285 else
6286 total_vector_size += vector->size;
6287 prev = vector, vector = vector->next;
6291 #ifdef GC_CHECK_STRING_BYTES
6292 if (!noninteractive)
6293 check_string_bytes (1);
6294 #endif
6300 /* Debugging aids. */
6302 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
6303 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6304 This may be helpful in debugging Emacs's memory usage.
6305 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6308 Lisp_Object end;
6310 XSETINT (end, (EMACS_INT) sbrk (0) / 1024);
6312 return end;
6315 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
6316 doc: /* Return a list of counters that measure how much consing there has been.
6317 Each of these counters increments for a certain kind of object.
6318 The counters wrap around from the largest positive integer to zero.
6319 Garbage collection does not decrease them.
6320 The elements of the value are as follows:
6321 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6322 All are in units of 1 = one object consed
6323 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6324 objects consed.
6325 MISCS include overlays, markers, and some internal types.
6326 Frames, windows, buffers, and subprocesses count as vectors
6327 (but the contents of a buffer's text do not count here). */)
6330 Lisp_Object consed[8];
6332 consed[0] = make_number (min (MOST_POSITIVE_FIXNUM, cons_cells_consed));
6333 consed[1] = make_number (min (MOST_POSITIVE_FIXNUM, floats_consed));
6334 consed[2] = make_number (min (MOST_POSITIVE_FIXNUM, vector_cells_consed));
6335 consed[3] = make_number (min (MOST_POSITIVE_FIXNUM, symbols_consed));
6336 consed[4] = make_number (min (MOST_POSITIVE_FIXNUM, string_chars_consed));
6337 consed[5] = make_number (min (MOST_POSITIVE_FIXNUM, misc_objects_consed));
6338 consed[6] = make_number (min (MOST_POSITIVE_FIXNUM, intervals_consed));
6339 consed[7] = make_number (min (MOST_POSITIVE_FIXNUM, strings_consed));
6341 return Flist (8, consed);
6344 int suppress_checking;
6345 void
6346 die (msg, file, line)
6347 const char *msg;
6348 const char *file;
6349 int line;
6351 fprintf (stderr, "\r\nEmacs fatal error: %s:%d: %s\r\n",
6352 file, line, msg);
6353 abort ();
6356 /* Initialization */
6358 void
6359 init_alloc_once ()
6361 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
6362 purebeg = PUREBEG;
6363 pure_size = PURESIZE;
6364 pure_bytes_used = 0;
6365 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
6366 pure_bytes_used_before_overflow = 0;
6368 /* Initialize the list of free aligned blocks. */
6369 free_ablock = NULL;
6371 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
6372 mem_init ();
6373 Vdead = make_pure_string ("DEAD", 4, 4, 0);
6374 #endif
6376 all_vectors = 0;
6377 ignore_warnings = 1;
6378 #ifdef DOUG_LEA_MALLOC
6379 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
6380 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
6381 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
6382 #endif
6383 init_strings ();
6384 init_cons ();
6385 init_symbol ();
6386 init_marker ();
6387 init_float ();
6388 init_intervals ();
6390 #ifdef REL_ALLOC
6391 malloc_hysteresis = 32;
6392 #else
6393 malloc_hysteresis = 0;
6394 #endif
6396 refill_memory_reserve ();
6398 ignore_warnings = 0;
6399 gcprolist = 0;
6400 byte_stack_list = 0;
6401 staticidx = 0;
6402 consing_since_gc = 0;
6403 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
6404 gc_relative_threshold = 0;
6406 #ifdef VIRT_ADDR_VARIES
6407 malloc_sbrk_unused = 1<<22; /* A large number */
6408 malloc_sbrk_used = 100000; /* as reasonable as any number */
6409 #endif /* VIRT_ADDR_VARIES */
6412 void
6413 init_alloc ()
6415 gcprolist = 0;
6416 byte_stack_list = 0;
6417 #if GC_MARK_STACK
6418 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
6419 setjmp_tested_p = longjmps_done = 0;
6420 #endif
6421 #endif
6422 Vgc_elapsed = make_float (0.0);
6423 gcs_done = 0;
6426 void
6427 syms_of_alloc ()
6429 DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold,
6430 doc: /* *Number of bytes of consing between garbage collections.
6431 Garbage collection can happen automatically once this many bytes have been
6432 allocated since the last garbage collection. All data types count.
6434 Garbage collection happens automatically only when `eval' is called.
6436 By binding this temporarily to a large number, you can effectively
6437 prevent garbage collection during a part of the program.
6438 See also `gc-cons-percentage'. */);
6440 DEFVAR_LISP ("gc-cons-percentage", &Vgc_cons_percentage,
6441 doc: /* *Portion of the heap used for allocation.
6442 Garbage collection can happen automatically once this portion of the heap
6443 has been allocated since the last garbage collection.
6444 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
6445 Vgc_cons_percentage = make_float (0.1);
6447 DEFVAR_INT ("pure-bytes-used", &pure_bytes_used,
6448 doc: /* Number of bytes of sharable Lisp data allocated so far. */);
6450 DEFVAR_INT ("cons-cells-consed", &cons_cells_consed,
6451 doc: /* Number of cons cells that have been consed so far. */);
6453 DEFVAR_INT ("floats-consed", &floats_consed,
6454 doc: /* Number of floats that have been consed so far. */);
6456 DEFVAR_INT ("vector-cells-consed", &vector_cells_consed,
6457 doc: /* Number of vector cells that have been consed so far. */);
6459 DEFVAR_INT ("symbols-consed", &symbols_consed,
6460 doc: /* Number of symbols that have been consed so far. */);
6462 DEFVAR_INT ("string-chars-consed", &string_chars_consed,
6463 doc: /* Number of string characters that have been consed so far. */);
6465 DEFVAR_INT ("misc-objects-consed", &misc_objects_consed,
6466 doc: /* Number of miscellaneous objects that have been consed so far. */);
6468 DEFVAR_INT ("intervals-consed", &intervals_consed,
6469 doc: /* Number of intervals that have been consed so far. */);
6471 DEFVAR_INT ("strings-consed", &strings_consed,
6472 doc: /* Number of strings that have been consed so far. */);
6474 DEFVAR_LISP ("purify-flag", &Vpurify_flag,
6475 doc: /* Non-nil means loading Lisp code in order to dump an executable.
6476 This means that certain objects should be allocated in shared (pure) space. */);
6478 DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
6479 doc: /* Non-nil means display messages at start and end of garbage collection. */);
6480 garbage_collection_messages = 0;
6482 DEFVAR_LISP ("post-gc-hook", &Vpost_gc_hook,
6483 doc: /* Hook run after garbage collection has finished. */);
6484 Vpost_gc_hook = Qnil;
6485 Qpost_gc_hook = intern ("post-gc-hook");
6486 staticpro (&Qpost_gc_hook);
6488 DEFVAR_LISP ("memory-signal-data", &Vmemory_signal_data,
6489 doc: /* Precomputed `signal' argument for memory-full error. */);
6490 /* We build this in advance because if we wait until we need it, we might
6491 not be able to allocate the memory to hold it. */
6492 Vmemory_signal_data
6493 = list2 (Qerror,
6494 build_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
6496 DEFVAR_LISP ("memory-full", &Vmemory_full,
6497 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
6498 Vmemory_full = Qnil;
6500 staticpro (&Qgc_cons_threshold);
6501 Qgc_cons_threshold = intern ("gc-cons-threshold");
6503 staticpro (&Qchar_table_extra_slots);
6504 Qchar_table_extra_slots = intern ("char-table-extra-slots");
6506 DEFVAR_LISP ("gc-elapsed", &Vgc_elapsed,
6507 doc: /* Accumulated time elapsed in garbage collections.
6508 The time is in seconds as a floating point value. */);
6509 DEFVAR_INT ("gcs-done", &gcs_done,
6510 doc: /* Accumulated number of garbage collections done. */);
6512 defsubr (&Scons);
6513 defsubr (&Slist);
6514 defsubr (&Svector);
6515 defsubr (&Smake_byte_code);
6516 defsubr (&Smake_list);
6517 defsubr (&Smake_vector);
6518 defsubr (&Smake_char_table);
6519 defsubr (&Smake_string);
6520 defsubr (&Smake_bool_vector);
6521 defsubr (&Smake_symbol);
6522 defsubr (&Smake_marker);
6523 defsubr (&Spurecopy);
6524 defsubr (&Sgarbage_collect);
6525 defsubr (&Smemory_limit);
6526 defsubr (&Smemory_use_counts);
6528 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
6529 defsubr (&Sgc_status);
6530 #endif
6533 /* arch-tag: 6695ca10-e3c5-4c2c-8bc3-ed26a7dda857
6534 (do not change this comment) */