2d256800466eae5cf11c65adeb2fd635175a347d
[bpt/emacs.git] / src / alloc.c
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
2 Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2011
3 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
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.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <limits.h> /* For CHAR_BIT. */
23 #include <setjmp.h>
24
25 #include <signal.h>
26
27 #ifdef HAVE_PTHREAD
28 #include <pthread.h>
29 #endif
30
31 /* This file is part of the core Lisp implementation, and thus must
32 deal with the real data structures. If the Lisp implementation is
33 replaced, this file likely will not be used. */
34
35 #undef HIDE_LISP_IMPLEMENTATION
36 #include "lisp.h"
37 #include "process.h"
38 #include "intervals.h"
39 #include "puresize.h"
40 #include "buffer.h"
41 #include "window.h"
42 #include "keyboard.h"
43 #include "frame.h"
44 #include "blockinput.h"
45 #include "character.h"
46 #include "syssignal.h"
47 #include "termhooks.h" /* For struct terminal. */
48 #include <setjmp.h>
49 #include <verify.h>
50
51 /* GC_MALLOC_CHECK defined means perform validity checks of malloc'd
52 memory. Can do this only if using gmalloc.c. */
53
54 #if defined SYSTEM_MALLOC || defined DOUG_LEA_MALLOC
55 #undef GC_MALLOC_CHECK
56 #endif
57
58 #include <unistd.h>
59 #ifndef HAVE_UNISTD_H
60 extern POINTER_TYPE *sbrk ();
61 #endif
62
63 #include <fcntl.h>
64
65 #ifdef WINDOWSNT
66 #include "w32.h"
67 #endif
68
69 #ifdef DOUG_LEA_MALLOC
70
71 #include <malloc.h>
72
73 /* Specify maximum number of areas to mmap. It would be nice to use a
74 value that explicitly means "no limit". */
75
76 #define MMAP_MAX_AREAS 100000000
77
78 #else /* not DOUG_LEA_MALLOC */
79
80 /* The following come from gmalloc.c. */
81
82 extern size_t _bytes_used;
83 extern size_t __malloc_extra_blocks;
84
85 #endif /* not DOUG_LEA_MALLOC */
86
87 #if ! defined SYSTEM_MALLOC && ! defined SYNC_INPUT
88 #ifdef HAVE_PTHREAD
89
90 /* When GTK uses the file chooser dialog, different backends can be loaded
91 dynamically. One such a backend is the Gnome VFS backend that gets loaded
92 if you run Gnome. That backend creates several threads and also allocates
93 memory with malloc.
94
95 Also, gconf and gsettings may create several threads.
96
97 If Emacs sets malloc hooks (! SYSTEM_MALLOC) and the emacs_blocked_*
98 functions below are called from malloc, there is a chance that one
99 of these threads preempts the Emacs main thread and the hook variables
100 end up in an inconsistent state. So we have a mutex to prevent that (note
101 that the backend handles concurrent access to malloc within its own threads
102 but Emacs code running in the main thread is not included in that control).
103
104 When UNBLOCK_INPUT is called, reinvoke_input_signal may be called. If this
105 happens in one of the backend threads we will have two threads that tries
106 to run Emacs code at once, and the code is not prepared for that.
107 To prevent that, we only call BLOCK/UNBLOCK from the main thread. */
108
109 static pthread_mutex_t alloc_mutex;
110
111 #define BLOCK_INPUT_ALLOC \
112 do \
113 { \
114 if (pthread_equal (pthread_self (), main_thread)) \
115 BLOCK_INPUT; \
116 pthread_mutex_lock (&alloc_mutex); \
117 } \
118 while (0)
119 #define UNBLOCK_INPUT_ALLOC \
120 do \
121 { \
122 pthread_mutex_unlock (&alloc_mutex); \
123 if (pthread_equal (pthread_self (), main_thread)) \
124 UNBLOCK_INPUT; \
125 } \
126 while (0)
127
128 #else /* ! defined HAVE_PTHREAD */
129
130 #define BLOCK_INPUT_ALLOC BLOCK_INPUT
131 #define UNBLOCK_INPUT_ALLOC UNBLOCK_INPUT
132
133 #endif /* ! defined HAVE_PTHREAD */
134 #endif /* ! defined SYSTEM_MALLOC && ! defined SYNC_INPUT */
135
136 /* Mark, unmark, query mark bit of a Lisp string. S must be a pointer
137 to a struct Lisp_String. */
138
139 #define MARK_STRING(S) ((S)->size |= ARRAY_MARK_FLAG)
140 #define UNMARK_STRING(S) ((S)->size &= ~ARRAY_MARK_FLAG)
141 #define STRING_MARKED_P(S) (((S)->size & ARRAY_MARK_FLAG) != 0)
142
143 #define VECTOR_MARK(V) ((V)->header.size |= ARRAY_MARK_FLAG)
144 #define VECTOR_UNMARK(V) ((V)->header.size &= ~ARRAY_MARK_FLAG)
145 #define VECTOR_MARKED_P(V) (((V)->header.size & ARRAY_MARK_FLAG) != 0)
146
147 /* Value is the number of bytes of S, a pointer to a struct Lisp_String.
148 Be careful during GC, because S->size contains the mark bit for
149 strings. */
150
151 #define GC_STRING_BYTES(S) (STRING_BYTES (S))
152
153 /* Global variables. */
154 struct emacs_globals globals;
155
156 /* Number of bytes of consing done since the last gc. */
157
158 EMACS_INT consing_since_gc;
159
160 /* Similar minimum, computed from Vgc_cons_percentage. */
161
162 EMACS_INT gc_relative_threshold;
163
164 /* Minimum number of bytes of consing since GC before next GC,
165 when memory is full. */
166
167 EMACS_INT memory_full_cons_threshold;
168
169 /* Nonzero during GC. */
170
171 int gc_in_progress;
172
173 /* Nonzero means abort if try to GC.
174 This is for code which is written on the assumption that
175 no GC will happen, so as to verify that assumption. */
176
177 int abort_on_gc;
178
179 /* Number of live and free conses etc. */
180
181 static EMACS_INT total_conses, total_markers, total_symbols, total_vector_size;
182 static EMACS_INT total_free_conses, total_free_markers, total_free_symbols;
183 static EMACS_INT total_free_floats, total_floats;
184
185 /* Points to memory space allocated as "spare", to be freed if we run
186 out of memory. We keep one large block, four cons-blocks, and
187 two string blocks. */
188
189 static char *spare_memory[7];
190
191 /* Amount of spare memory to keep in large reserve block, or to see
192 whether this much is available when malloc fails on a larger request. */
193
194 #define SPARE_MEMORY (1 << 14)
195
196 /* Number of extra blocks malloc should get when it needs more core. */
197
198 static int malloc_hysteresis;
199
200 /* Initialize it to a nonzero value to force it into data space
201 (rather than bss space). That way unexec will remap it into text
202 space (pure), on some systems. We have not implemented the
203 remapping on more recent systems because this is less important
204 nowadays than in the days of small memories and timesharing. */
205
206 #ifndef VIRT_ADDR_VARIES
207 static
208 #endif
209 EMACS_INT pure[(PURESIZE + sizeof (EMACS_INT) - 1) / sizeof (EMACS_INT)] = {1,};
210 #define PUREBEG (char *) pure
211
212 /* Pointer to the pure area, and its size. */
213
214 static char *purebeg;
215 static ptrdiff_t pure_size;
216
217 /* Number of bytes of pure storage used before pure storage overflowed.
218 If this is non-zero, this implies that an overflow occurred. */
219
220 static ptrdiff_t pure_bytes_used_before_overflow;
221
222 /* Value is non-zero if P points into pure space. */
223
224 #define PURE_POINTER_P(P) \
225 (((PNTR_COMPARISON_TYPE) (P) \
226 < (PNTR_COMPARISON_TYPE) ((char *) purebeg + pure_size)) \
227 && ((PNTR_COMPARISON_TYPE) (P) \
228 >= (PNTR_COMPARISON_TYPE) purebeg))
229
230 /* Index in pure at which next pure Lisp object will be allocated.. */
231
232 static EMACS_INT pure_bytes_used_lisp;
233
234 /* Number of bytes allocated for non-Lisp objects in pure storage. */
235
236 static EMACS_INT pure_bytes_used_non_lisp;
237
238 /* If nonzero, this is a warning delivered by malloc and not yet
239 displayed. */
240
241 const char *pending_malloc_warning;
242
243 /* Maximum amount of C stack to save when a GC happens. */
244
245 #ifndef MAX_SAVE_STACK
246 #define MAX_SAVE_STACK 16000
247 #endif
248
249 /* Buffer in which we save a copy of the C stack at each GC. */
250
251 #if MAX_SAVE_STACK > 0
252 static char *stack_copy;
253 static ptrdiff_t stack_copy_size;
254 #endif
255
256 /* Non-zero means ignore malloc warnings. Set during initialization.
257 Currently not used. */
258
259 static int ignore_warnings;
260
261 static Lisp_Object Qgc_cons_threshold;
262 Lisp_Object Qchar_table_extra_slots;
263
264 /* Hook run after GC has finished. */
265
266 static Lisp_Object Qpost_gc_hook;
267
268 static void mark_buffer (Lisp_Object);
269 static void mark_terminals (void);
270 static void gc_sweep (void);
271 static void mark_glyph_matrix (struct glyph_matrix *);
272 static void mark_face_cache (struct face_cache *);
273
274 #if !defined REL_ALLOC || defined SYSTEM_MALLOC
275 static void refill_memory_reserve (void);
276 #endif
277 static struct Lisp_String *allocate_string (void);
278 static void compact_small_strings (void);
279 static void free_large_strings (void);
280 static void sweep_strings (void);
281 static void free_misc (Lisp_Object);
282
283 /* When scanning the C stack for live Lisp objects, Emacs keeps track
284 of what memory allocated via lisp_malloc is intended for what
285 purpose. This enumeration specifies the type of memory. */
286
287 enum mem_type
288 {
289 MEM_TYPE_NON_LISP,
290 MEM_TYPE_BUFFER,
291 MEM_TYPE_CONS,
292 MEM_TYPE_STRING,
293 MEM_TYPE_MISC,
294 MEM_TYPE_SYMBOL,
295 MEM_TYPE_FLOAT,
296 /* We used to keep separate mem_types for subtypes of vectors such as
297 process, hash_table, frame, terminal, and window, but we never made
298 use of the distinction, so it only caused source-code complexity
299 and runtime slowdown. Minor but pointless. */
300 MEM_TYPE_VECTORLIKE
301 };
302
303 static POINTER_TYPE *lisp_align_malloc (size_t, enum mem_type);
304 static POINTER_TYPE *lisp_malloc (size_t, enum mem_type);
305
306
307 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
308
309 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
310 #include <stdio.h> /* For fprintf. */
311 #endif
312
313 /* A unique object in pure space used to make some Lisp objects
314 on free lists recognizable in O(1). */
315
316 static Lisp_Object Vdead;
317
318 #ifdef GC_MALLOC_CHECK
319
320 enum mem_type allocated_mem_type;
321 static int dont_register_blocks;
322
323 #endif /* GC_MALLOC_CHECK */
324
325 /* A node in the red-black tree describing allocated memory containing
326 Lisp data. Each such block is recorded with its start and end
327 address when it is allocated, and removed from the tree when it
328 is freed.
329
330 A red-black tree is a balanced binary tree with the following
331 properties:
332
333 1. Every node is either red or black.
334 2. Every leaf is black.
335 3. If a node is red, then both of its children are black.
336 4. Every simple path from a node to a descendant leaf contains
337 the same number of black nodes.
338 5. The root is always black.
339
340 When nodes are inserted into the tree, or deleted from the tree,
341 the tree is "fixed" so that these properties are always true.
342
343 A red-black tree with N internal nodes has height at most 2
344 log(N+1). Searches, insertions and deletions are done in O(log N).
345 Please see a text book about data structures for a detailed
346 description of red-black trees. Any book worth its salt should
347 describe them. */
348
349 struct mem_node
350 {
351 /* Children of this node. These pointers are never NULL. When there
352 is no child, the value is MEM_NIL, which points to a dummy node. */
353 struct mem_node *left, *right;
354
355 /* The parent of this node. In the root node, this is NULL. */
356 struct mem_node *parent;
357
358 /* Start and end of allocated region. */
359 void *start, *end;
360
361 /* Node color. */
362 enum {MEM_BLACK, MEM_RED} color;
363
364 /* Memory type. */
365 enum mem_type type;
366 };
367
368 /* Base address of stack. Set in main. */
369
370 Lisp_Object *stack_base;
371
372 /* Root of the tree describing allocated Lisp memory. */
373
374 static struct mem_node *mem_root;
375
376 /* Lowest and highest known address in the heap. */
377
378 static void *min_heap_address, *max_heap_address;
379
380 /* Sentinel node of the tree. */
381
382 static struct mem_node mem_z;
383 #define MEM_NIL &mem_z
384
385 static struct Lisp_Vector *allocate_vectorlike (EMACS_INT);
386 static void lisp_free (POINTER_TYPE *);
387 static void mark_stack (void);
388 static int live_vector_p (struct mem_node *, void *);
389 static int live_buffer_p (struct mem_node *, void *);
390 static int live_string_p (struct mem_node *, void *);
391 static int live_cons_p (struct mem_node *, void *);
392 static int live_symbol_p (struct mem_node *, void *);
393 static int live_float_p (struct mem_node *, void *);
394 static int live_misc_p (struct mem_node *, void *);
395 static void mark_maybe_object (Lisp_Object);
396 static void mark_memory (void *, void *, int);
397 static void mem_init (void);
398 static struct mem_node *mem_insert (void *, void *, enum mem_type);
399 static void mem_insert_fixup (struct mem_node *);
400 static void mem_rotate_left (struct mem_node *);
401 static void mem_rotate_right (struct mem_node *);
402 static void mem_delete (struct mem_node *);
403 static void mem_delete_fixup (struct mem_node *);
404 static inline struct mem_node *mem_find (void *);
405
406
407 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
408 static void check_gcpros (void);
409 #endif
410
411 #endif /* GC_MARK_STACK || GC_MALLOC_CHECK */
412
413 /* Recording what needs to be marked for gc. */
414
415 struct gcpro *gcprolist;
416
417 /* Addresses of staticpro'd variables. Initialize it to a nonzero
418 value; otherwise some compilers put it into BSS. */
419
420 #define NSTATICS 0x640
421 static Lisp_Object *staticvec[NSTATICS] = {&Vpurify_flag};
422
423 /* Index of next unused slot in staticvec. */
424
425 static int staticidx = 0;
426
427 static POINTER_TYPE *pure_alloc (size_t, int);
428
429
430 /* Value is SZ rounded up to the next multiple of ALIGNMENT.
431 ALIGNMENT must be a power of 2. */
432
433 #define ALIGN(ptr, ALIGNMENT) \
434 ((POINTER_TYPE *) ((((uintptr_t) (ptr)) + (ALIGNMENT) - 1) \
435 & ~((ALIGNMENT) - 1)))
436
437
438 \f
439 /************************************************************************
440 Malloc
441 ************************************************************************/
442
443 /* Function malloc calls this if it finds we are near exhausting storage. */
444
445 void
446 malloc_warning (const char *str)
447 {
448 pending_malloc_warning = str;
449 }
450
451
452 /* Display an already-pending malloc warning. */
453
454 void
455 display_malloc_warning (void)
456 {
457 call3 (intern ("display-warning"),
458 intern ("alloc"),
459 build_string (pending_malloc_warning),
460 intern ("emergency"));
461 pending_malloc_warning = 0;
462 }
463 \f
464 /* Called if we can't allocate relocatable space for a buffer. */
465
466 void
467 buffer_memory_full (EMACS_INT nbytes)
468 {
469 /* If buffers use the relocating allocator, no need to free
470 spare_memory, because we may have plenty of malloc space left
471 that we could get, and if we don't, the malloc that fails will
472 itself cause spare_memory to be freed. If buffers don't use the
473 relocating allocator, treat this like any other failing
474 malloc. */
475
476 #ifndef REL_ALLOC
477 memory_full (nbytes);
478 #endif
479
480 /* This used to call error, but if we've run out of memory, we could
481 get infinite recursion trying to build the string. */
482 xsignal (Qnil, Vmemory_signal_data);
483 }
484
485
486 #ifndef XMALLOC_OVERRUN_CHECK
487 #define XMALLOC_OVERRUN_CHECK_OVERHEAD 0
488 #else
489
490 /* Check for overrun in malloc'ed buffers by wrapping a header and trailer
491 around each block.
492
493 The header consists of 16 fixed bytes followed by sizeof (size_t) bytes
494 containing the original block size in little-endian order,
495 while the trailer consists of 16 fixed bytes.
496
497 The header is used to detect whether this block has been allocated
498 through these functions -- as it seems that some low-level libc
499 functions may bypass the malloc hooks.
500 */
501
502
503 #define XMALLOC_OVERRUN_CHECK_SIZE 16
504 #define XMALLOC_OVERRUN_CHECK_OVERHEAD \
505 (2 * XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t))
506
507 static char const xmalloc_overrun_check_header[XMALLOC_OVERRUN_CHECK_SIZE] =
508 { '\x9a', '\x9b', '\xae', '\xaf',
509 '\xbf', '\xbe', '\xce', '\xcf',
510 '\xea', '\xeb', '\xec', '\xed',
511 '\xdf', '\xde', '\x9c', '\x9d' };
512
513 static char const xmalloc_overrun_check_trailer[XMALLOC_OVERRUN_CHECK_SIZE] =
514 { '\xaa', '\xab', '\xac', '\xad',
515 '\xba', '\xbb', '\xbc', '\xbd',
516 '\xca', '\xcb', '\xcc', '\xcd',
517 '\xda', '\xdb', '\xdc', '\xdd' };
518
519 /* Insert and extract the block size in the header. */
520
521 static void
522 xmalloc_put_size (unsigned char *ptr, size_t size)
523 {
524 int i;
525 for (i = 0; i < sizeof (size_t); i++)
526 {
527 *--ptr = size & (1 << CHAR_BIT) - 1;
528 size >>= CHAR_BIT;
529 }
530 }
531
532 static size_t
533 xmalloc_get_size (unsigned char *ptr)
534 {
535 size_t size = 0;
536 int i;
537 ptr -= sizeof (size_t);
538 for (i = 0; i < sizeof (size_t); i++)
539 {
540 size <<= CHAR_BIT;
541 size += *ptr++;
542 }
543 return size;
544 }
545
546
547 /* The call depth in overrun_check functions. For example, this might happen:
548 xmalloc()
549 overrun_check_malloc()
550 -> malloc -> (via hook)_-> emacs_blocked_malloc
551 -> overrun_check_malloc
552 call malloc (hooks are NULL, so real malloc is called).
553 malloc returns 10000.
554 add overhead, return 10016.
555 <- (back in overrun_check_malloc)
556 add overhead again, return 10032
557 xmalloc returns 10032.
558
559 (time passes).
560
561 xfree(10032)
562 overrun_check_free(10032)
563 decrease overhead
564 free(10016) <- crash, because 10000 is the original pointer. */
565
566 static ptrdiff_t check_depth;
567
568 /* Like malloc, but wraps allocated block with header and trailer. */
569
570 static POINTER_TYPE *
571 overrun_check_malloc (size_t size)
572 {
573 register unsigned char *val;
574 int overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_OVERHEAD : 0;
575 if (SIZE_MAX - overhead < size)
576 abort ();
577
578 val = (unsigned char *) malloc (size + overhead);
579 if (val && check_depth == 1)
580 {
581 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
582 val += XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t);
583 xmalloc_put_size (val, size);
584 memcpy (val + size, xmalloc_overrun_check_trailer,
585 XMALLOC_OVERRUN_CHECK_SIZE);
586 }
587 --check_depth;
588 return (POINTER_TYPE *)val;
589 }
590
591
592 /* Like realloc, but checks old block for overrun, and wraps new block
593 with header and trailer. */
594
595 static POINTER_TYPE *
596 overrun_check_realloc (POINTER_TYPE *block, size_t size)
597 {
598 register unsigned char *val = (unsigned char *) block;
599 int overhead = ++check_depth == 1 ? XMALLOC_OVERRUN_CHECK_OVERHEAD : 0;
600 if (SIZE_MAX - overhead < size)
601 abort ();
602
603 if (val
604 && check_depth == 1
605 && memcmp (xmalloc_overrun_check_header,
606 val - XMALLOC_OVERRUN_CHECK_SIZE - sizeof (size_t),
607 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
608 {
609 size_t osize = xmalloc_get_size (val);
610 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
611 XMALLOC_OVERRUN_CHECK_SIZE))
612 abort ();
613 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
614 val -= XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t);
615 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t));
616 }
617
618 val = (unsigned char *) realloc ((POINTER_TYPE *)val, size + overhead);
619
620 if (val && check_depth == 1)
621 {
622 memcpy (val, xmalloc_overrun_check_header, XMALLOC_OVERRUN_CHECK_SIZE);
623 val += XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t);
624 xmalloc_put_size (val, size);
625 memcpy (val + size, xmalloc_overrun_check_trailer,
626 XMALLOC_OVERRUN_CHECK_SIZE);
627 }
628 --check_depth;
629 return (POINTER_TYPE *)val;
630 }
631
632 /* Like free, but checks block for overrun. */
633
634 static void
635 overrun_check_free (POINTER_TYPE *block)
636 {
637 unsigned char *val = (unsigned char *) block;
638
639 ++check_depth;
640 if (val
641 && check_depth == 1
642 && memcmp (xmalloc_overrun_check_header,
643 val - XMALLOC_OVERRUN_CHECK_SIZE - sizeof (size_t),
644 XMALLOC_OVERRUN_CHECK_SIZE) == 0)
645 {
646 size_t osize = xmalloc_get_size (val);
647 if (memcmp (xmalloc_overrun_check_trailer, val + osize,
648 XMALLOC_OVERRUN_CHECK_SIZE))
649 abort ();
650 #ifdef XMALLOC_CLEAR_FREE_MEMORY
651 val -= XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t);
652 memset (val, 0xff, osize + XMALLOC_OVERRUN_CHECK_OVERHEAD);
653 #else
654 memset (val + osize, 0, XMALLOC_OVERRUN_CHECK_SIZE);
655 val -= XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t);
656 memset (val, 0, XMALLOC_OVERRUN_CHECK_SIZE + sizeof (size_t));
657 #endif
658 }
659
660 free (val);
661 --check_depth;
662 }
663
664 #undef malloc
665 #undef realloc
666 #undef free
667 #define malloc overrun_check_malloc
668 #define realloc overrun_check_realloc
669 #define free overrun_check_free
670 #endif
671
672 #ifdef SYNC_INPUT
673 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
674 there's no need to block input around malloc. */
675 #define MALLOC_BLOCK_INPUT ((void)0)
676 #define MALLOC_UNBLOCK_INPUT ((void)0)
677 #else
678 #define MALLOC_BLOCK_INPUT BLOCK_INPUT
679 #define MALLOC_UNBLOCK_INPUT UNBLOCK_INPUT
680 #endif
681
682 /* Like malloc but check for no memory and block interrupt input.. */
683
684 POINTER_TYPE *
685 xmalloc (size_t size)
686 {
687 register POINTER_TYPE *val;
688
689 MALLOC_BLOCK_INPUT;
690 val = (POINTER_TYPE *) malloc (size);
691 MALLOC_UNBLOCK_INPUT;
692
693 if (!val && size)
694 memory_full (size);
695 return val;
696 }
697
698
699 /* Like realloc but check for no memory and block interrupt input.. */
700
701 POINTER_TYPE *
702 xrealloc (POINTER_TYPE *block, size_t size)
703 {
704 register POINTER_TYPE *val;
705
706 MALLOC_BLOCK_INPUT;
707 /* We must call malloc explicitly when BLOCK is 0, since some
708 reallocs don't do this. */
709 if (! block)
710 val = (POINTER_TYPE *) malloc (size);
711 else
712 val = (POINTER_TYPE *) realloc (block, size);
713 MALLOC_UNBLOCK_INPUT;
714
715 if (!val && size)
716 memory_full (size);
717 return val;
718 }
719
720
721 /* Like free but block interrupt input. */
722
723 void
724 xfree (POINTER_TYPE *block)
725 {
726 if (!block)
727 return;
728 MALLOC_BLOCK_INPUT;
729 free (block);
730 MALLOC_UNBLOCK_INPUT;
731 /* We don't call refill_memory_reserve here
732 because that duplicates doing so in emacs_blocked_free
733 and the criterion should go there. */
734 }
735
736
737 /* Other parts of Emacs pass large int values to allocator functions
738 expecting ptrdiff_t. This is portable in practice, but check it to
739 be safe. */
740 verify (INT_MAX <= PTRDIFF_MAX);
741
742
743 /* Allocate an array of NITEMS items, each of size ITEM_SIZE.
744 Signal an error on memory exhaustion, and block interrupt input. */
745
746 void *
747 xnmalloc (ptrdiff_t nitems, ptrdiff_t item_size)
748 {
749 xassert (0 <= nitems && 0 < item_size);
750 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
751 memory_full (SIZE_MAX);
752 return xmalloc (nitems * item_size);
753 }
754
755
756 /* Reallocate an array PA to make it of NITEMS items, each of size ITEM_SIZE.
757 Signal an error on memory exhaustion, and block interrupt input. */
758
759 void *
760 xnrealloc (void *pa, ptrdiff_t nitems, ptrdiff_t item_size)
761 {
762 xassert (0 <= nitems && 0 < item_size);
763 if (min (PTRDIFF_MAX, SIZE_MAX) / item_size < nitems)
764 memory_full (SIZE_MAX);
765 return xrealloc (pa, nitems * item_size);
766 }
767
768
769 /* Grow PA, which points to an array of *NITEMS items, and return the
770 location of the reallocated array, updating *NITEMS to reflect its
771 new size. The new array will contain at least NITEMS_INCR_MIN more
772 items, but will not contain more than NITEMS_MAX items total.
773 ITEM_SIZE is the size of each item, in bytes.
774
775 ITEM_SIZE and NITEMS_INCR_MIN must be positive. *NITEMS must be
776 nonnegative. If NITEMS_MAX is -1, it is treated as if it were
777 infinity.
778
779 If PA is null, then allocate a new array instead of reallocating
780 the old one. Thus, to grow an array A without saving its old
781 contents, invoke xfree (A) immediately followed by xgrowalloc (0,
782 &NITEMS, ...).
783
784 Block interrupt input as needed. If memory exhaustion occurs, set
785 *NITEMS to zero if PA is null, and signal an error (i.e., do not
786 return). */
787
788 void *
789 xpalloc (void *pa, ptrdiff_t *nitems, ptrdiff_t nitems_incr_min,
790 ptrdiff_t nitems_max, ptrdiff_t item_size)
791 {
792 /* The approximate size to use for initial small allocation
793 requests. This is the largest "small" request for the GNU C
794 library malloc. */
795 enum { DEFAULT_MXFAST = 64 * sizeof (size_t) / 4 };
796
797 /* If the array is tiny, grow it to about (but no greater than)
798 DEFAULT_MXFAST bytes. Otherwise, grow it by about 50%. */
799 ptrdiff_t n = *nitems;
800 ptrdiff_t tiny_max = DEFAULT_MXFAST / item_size - n;
801 ptrdiff_t half_again = n >> 1;
802 ptrdiff_t incr_estimate = max (tiny_max, half_again);
803
804 /* Adjust the increment according to three constraints: NITEMS_INCR_MIN,
805 NITEMS_MAX, and what the C language can represent safely. */
806 ptrdiff_t C_language_max = min (PTRDIFF_MAX, SIZE_MAX) / item_size;
807 ptrdiff_t n_max = (0 <= nitems_max && nitems_max < C_language_max
808 ? nitems_max : C_language_max);
809 ptrdiff_t nitems_incr_max = n_max - n;
810 ptrdiff_t incr = max (nitems_incr_min, min (incr_estimate, nitems_incr_max));
811
812 xassert (0 < item_size && 0 < nitems_incr_min && 0 <= n && -1 <= nitems_max);
813 if (! pa)
814 *nitems = 0;
815 if (nitems_incr_max < incr)
816 memory_full (SIZE_MAX);
817 n += incr;
818 pa = xrealloc (pa, n * item_size);
819 *nitems = n;
820 return pa;
821 }
822
823
824 /* Like strdup, but uses xmalloc. */
825
826 char *
827 xstrdup (const char *s)
828 {
829 size_t len = strlen (s) + 1;
830 char *p = (char *) xmalloc (len);
831 memcpy (p, s, len);
832 return p;
833 }
834
835
836 /* Unwind for SAFE_ALLOCA */
837
838 Lisp_Object
839 safe_alloca_unwind (Lisp_Object arg)
840 {
841 register struct Lisp_Save_Value *p = XSAVE_VALUE (arg);
842
843 p->dogc = 0;
844 xfree (p->pointer);
845 p->pointer = 0;
846 free_misc (arg);
847 return Qnil;
848 }
849
850
851 /* Like malloc but used for allocating Lisp data. NBYTES is the
852 number of bytes to allocate, TYPE describes the intended use of the
853 allcated memory block (for strings, for conses, ...). */
854
855 #ifndef USE_LSB_TAG
856 static void *lisp_malloc_loser;
857 #endif
858
859 static POINTER_TYPE *
860 lisp_malloc (size_t nbytes, enum mem_type type)
861 {
862 register void *val;
863
864 MALLOC_BLOCK_INPUT;
865
866 #ifdef GC_MALLOC_CHECK
867 allocated_mem_type = type;
868 #endif
869
870 val = (void *) malloc (nbytes);
871
872 #ifndef USE_LSB_TAG
873 /* If the memory just allocated cannot be addressed thru a Lisp
874 object's pointer, and it needs to be,
875 that's equivalent to running out of memory. */
876 if (val && type != MEM_TYPE_NON_LISP)
877 {
878 Lisp_Object tem;
879 XSETCONS (tem, (char *) val + nbytes - 1);
880 if ((char *) XCONS (tem) != (char *) val + nbytes - 1)
881 {
882 lisp_malloc_loser = val;
883 free (val);
884 val = 0;
885 }
886 }
887 #endif
888
889 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
890 if (val && type != MEM_TYPE_NON_LISP)
891 mem_insert (val, (char *) val + nbytes, type);
892 #endif
893
894 MALLOC_UNBLOCK_INPUT;
895 if (!val && nbytes)
896 memory_full (nbytes);
897 return val;
898 }
899
900 /* Free BLOCK. This must be called to free memory allocated with a
901 call to lisp_malloc. */
902
903 static void
904 lisp_free (POINTER_TYPE *block)
905 {
906 MALLOC_BLOCK_INPUT;
907 free (block);
908 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
909 mem_delete (mem_find (block));
910 #endif
911 MALLOC_UNBLOCK_INPUT;
912 }
913
914 /* Allocation of aligned blocks of memory to store Lisp data. */
915 /* The entry point is lisp_align_malloc which returns blocks of at most */
916 /* BLOCK_BYTES and guarantees they are aligned on a BLOCK_ALIGN boundary. */
917
918 /* Use posix_memalloc if the system has it and we're using the system's
919 malloc (because our gmalloc.c routines don't have posix_memalign although
920 its memalloc could be used). */
921 #if defined (HAVE_POSIX_MEMALIGN) && defined (SYSTEM_MALLOC)
922 #define USE_POSIX_MEMALIGN 1
923 #endif
924
925 /* BLOCK_ALIGN has to be a power of 2. */
926 #define BLOCK_ALIGN (1 << 10)
927
928 /* Padding to leave at the end of a malloc'd block. This is to give
929 malloc a chance to minimize the amount of memory wasted to alignment.
930 It should be tuned to the particular malloc library used.
931 On glibc-2.3.2, malloc never tries to align, so a padding of 0 is best.
932 posix_memalign on the other hand would ideally prefer a value of 4
933 because otherwise, there's 1020 bytes wasted between each ablocks.
934 In Emacs, testing shows that those 1020 can most of the time be
935 efficiently used by malloc to place other objects, so a value of 0 can
936 still preferable unless you have a lot of aligned blocks and virtually
937 nothing else. */
938 #define BLOCK_PADDING 0
939 #define BLOCK_BYTES \
940 (BLOCK_ALIGN - sizeof (struct ablocks *) - BLOCK_PADDING)
941
942 /* Internal data structures and constants. */
943
944 #define ABLOCKS_SIZE 16
945
946 /* An aligned block of memory. */
947 struct ablock
948 {
949 union
950 {
951 char payload[BLOCK_BYTES];
952 struct ablock *next_free;
953 } x;
954 /* `abase' is the aligned base of the ablocks. */
955 /* It is overloaded to hold the virtual `busy' field that counts
956 the number of used ablock in the parent ablocks.
957 The first ablock has the `busy' field, the others have the `abase'
958 field. To tell the difference, we assume that pointers will have
959 integer values larger than 2 * ABLOCKS_SIZE. The lowest bit of `busy'
960 is used to tell whether the real base of the parent ablocks is `abase'
961 (if not, the word before the first ablock holds a pointer to the
962 real base). */
963 struct ablocks *abase;
964 /* The padding of all but the last ablock is unused. The padding of
965 the last ablock in an ablocks is not allocated. */
966 #if BLOCK_PADDING
967 char padding[BLOCK_PADDING];
968 #endif
969 };
970
971 /* A bunch of consecutive aligned blocks. */
972 struct ablocks
973 {
974 struct ablock blocks[ABLOCKS_SIZE];
975 };
976
977 /* Size of the block requested from malloc or memalign. */
978 #define ABLOCKS_BYTES (sizeof (struct ablocks) - BLOCK_PADDING)
979
980 #define ABLOCK_ABASE(block) \
981 (((uintptr_t) (block)->abase) <= (1 + 2 * ABLOCKS_SIZE) \
982 ? (struct ablocks *)(block) \
983 : (block)->abase)
984
985 /* Virtual `busy' field. */
986 #define ABLOCKS_BUSY(abase) ((abase)->blocks[0].abase)
987
988 /* Pointer to the (not necessarily aligned) malloc block. */
989 #ifdef USE_POSIX_MEMALIGN
990 #define ABLOCKS_BASE(abase) (abase)
991 #else
992 #define ABLOCKS_BASE(abase) \
993 (1 & (intptr_t) ABLOCKS_BUSY (abase) ? abase : ((void**)abase)[-1])
994 #endif
995
996 /* The list of free ablock. */
997 static struct ablock *free_ablock;
998
999 /* Allocate an aligned block of nbytes.
1000 Alignment is on a multiple of BLOCK_ALIGN and `nbytes' has to be
1001 smaller or equal to BLOCK_BYTES. */
1002 static POINTER_TYPE *
1003 lisp_align_malloc (size_t nbytes, enum mem_type type)
1004 {
1005 void *base, *val;
1006 struct ablocks *abase;
1007
1008 eassert (nbytes <= BLOCK_BYTES);
1009
1010 MALLOC_BLOCK_INPUT;
1011
1012 #ifdef GC_MALLOC_CHECK
1013 allocated_mem_type = type;
1014 #endif
1015
1016 if (!free_ablock)
1017 {
1018 int i;
1019 intptr_t aligned; /* int gets warning casting to 64-bit pointer. */
1020
1021 #ifdef DOUG_LEA_MALLOC
1022 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1023 because mapped region contents are not preserved in
1024 a dumped Emacs. */
1025 mallopt (M_MMAP_MAX, 0);
1026 #endif
1027
1028 #ifdef USE_POSIX_MEMALIGN
1029 {
1030 int err = posix_memalign (&base, BLOCK_ALIGN, ABLOCKS_BYTES);
1031 if (err)
1032 base = NULL;
1033 abase = base;
1034 }
1035 #else
1036 base = malloc (ABLOCKS_BYTES);
1037 abase = ALIGN (base, BLOCK_ALIGN);
1038 #endif
1039
1040 if (base == 0)
1041 {
1042 MALLOC_UNBLOCK_INPUT;
1043 memory_full (ABLOCKS_BYTES);
1044 }
1045
1046 aligned = (base == abase);
1047 if (!aligned)
1048 ((void**)abase)[-1] = base;
1049
1050 #ifdef DOUG_LEA_MALLOC
1051 /* Back to a reasonable maximum of mmap'ed areas. */
1052 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1053 #endif
1054
1055 #ifndef USE_LSB_TAG
1056 /* If the memory just allocated cannot be addressed thru a Lisp
1057 object's pointer, and it needs to be, that's equivalent to
1058 running out of memory. */
1059 if (type != MEM_TYPE_NON_LISP)
1060 {
1061 Lisp_Object tem;
1062 char *end = (char *) base + ABLOCKS_BYTES - 1;
1063 XSETCONS (tem, end);
1064 if ((char *) XCONS (tem) != end)
1065 {
1066 lisp_malloc_loser = base;
1067 free (base);
1068 MALLOC_UNBLOCK_INPUT;
1069 memory_full (SIZE_MAX);
1070 }
1071 }
1072 #endif
1073
1074 /* Initialize the blocks and put them on the free list.
1075 Is `base' was not properly aligned, we can't use the last block. */
1076 for (i = 0; i < (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1); i++)
1077 {
1078 abase->blocks[i].abase = abase;
1079 abase->blocks[i].x.next_free = free_ablock;
1080 free_ablock = &abase->blocks[i];
1081 }
1082 ABLOCKS_BUSY (abase) = (struct ablocks *) aligned;
1083
1084 eassert (0 == ((uintptr_t) abase) % BLOCK_ALIGN);
1085 eassert (ABLOCK_ABASE (&abase->blocks[3]) == abase); /* 3 is arbitrary */
1086 eassert (ABLOCK_ABASE (&abase->blocks[0]) == abase);
1087 eassert (ABLOCKS_BASE (abase) == base);
1088 eassert (aligned == (intptr_t) ABLOCKS_BUSY (abase));
1089 }
1090
1091 abase = ABLOCK_ABASE (free_ablock);
1092 ABLOCKS_BUSY (abase) =
1093 (struct ablocks *) (2 + (intptr_t) ABLOCKS_BUSY (abase));
1094 val = free_ablock;
1095 free_ablock = free_ablock->x.next_free;
1096
1097 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1098 if (type != MEM_TYPE_NON_LISP)
1099 mem_insert (val, (char *) val + nbytes, type);
1100 #endif
1101
1102 MALLOC_UNBLOCK_INPUT;
1103
1104 eassert (0 == ((uintptr_t) val) % BLOCK_ALIGN);
1105 return val;
1106 }
1107
1108 static void
1109 lisp_align_free (POINTER_TYPE *block)
1110 {
1111 struct ablock *ablock = block;
1112 struct ablocks *abase = ABLOCK_ABASE (ablock);
1113
1114 MALLOC_BLOCK_INPUT;
1115 #if GC_MARK_STACK && !defined GC_MALLOC_CHECK
1116 mem_delete (mem_find (block));
1117 #endif
1118 /* Put on free list. */
1119 ablock->x.next_free = free_ablock;
1120 free_ablock = ablock;
1121 /* Update busy count. */
1122 ABLOCKS_BUSY (abase) =
1123 (struct ablocks *) (-2 + (intptr_t) ABLOCKS_BUSY (abase));
1124
1125 if (2 > (intptr_t) ABLOCKS_BUSY (abase))
1126 { /* All the blocks are free. */
1127 int i = 0, aligned = (intptr_t) ABLOCKS_BUSY (abase);
1128 struct ablock **tem = &free_ablock;
1129 struct ablock *atop = &abase->blocks[aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1];
1130
1131 while (*tem)
1132 {
1133 if (*tem >= (struct ablock *) abase && *tem < atop)
1134 {
1135 i++;
1136 *tem = (*tem)->x.next_free;
1137 }
1138 else
1139 tem = &(*tem)->x.next_free;
1140 }
1141 eassert ((aligned & 1) == aligned);
1142 eassert (i == (aligned ? ABLOCKS_SIZE : ABLOCKS_SIZE - 1));
1143 #ifdef USE_POSIX_MEMALIGN
1144 eassert ((uintptr_t) ABLOCKS_BASE (abase) % BLOCK_ALIGN == 0);
1145 #endif
1146 free (ABLOCKS_BASE (abase));
1147 }
1148 MALLOC_UNBLOCK_INPUT;
1149 }
1150
1151 /* Return a new buffer structure allocated from the heap with
1152 a call to lisp_malloc. */
1153
1154 struct buffer *
1155 allocate_buffer (void)
1156 {
1157 struct buffer *b
1158 = (struct buffer *) lisp_malloc (sizeof (struct buffer),
1159 MEM_TYPE_BUFFER);
1160 XSETPVECTYPESIZE (b, PVEC_BUFFER,
1161 ((sizeof (struct buffer) + sizeof (EMACS_INT) - 1)
1162 / sizeof (EMACS_INT)));
1163 return b;
1164 }
1165
1166 \f
1167 #ifndef SYSTEM_MALLOC
1168
1169 /* Arranging to disable input signals while we're in malloc.
1170
1171 This only works with GNU malloc. To help out systems which can't
1172 use GNU malloc, all the calls to malloc, realloc, and free
1173 elsewhere in the code should be inside a BLOCK_INPUT/UNBLOCK_INPUT
1174 pair; unfortunately, we have no idea what C library functions
1175 might call malloc, so we can't really protect them unless you're
1176 using GNU malloc. Fortunately, most of the major operating systems
1177 can use GNU malloc. */
1178
1179 #ifndef SYNC_INPUT
1180 /* When using SYNC_INPUT, we don't call malloc from a signal handler, so
1181 there's no need to block input around malloc. */
1182
1183 #ifndef DOUG_LEA_MALLOC
1184 extern void * (*__malloc_hook) (size_t, const void *);
1185 extern void * (*__realloc_hook) (void *, size_t, const void *);
1186 extern void (*__free_hook) (void *, const void *);
1187 /* Else declared in malloc.h, perhaps with an extra arg. */
1188 #endif /* DOUG_LEA_MALLOC */
1189 static void * (*old_malloc_hook) (size_t, const void *);
1190 static void * (*old_realloc_hook) (void *, size_t, const void*);
1191 static void (*old_free_hook) (void*, const void*);
1192
1193 #ifdef DOUG_LEA_MALLOC
1194 # define BYTES_USED (mallinfo ().uordblks)
1195 #else
1196 # define BYTES_USED _bytes_used
1197 #endif
1198
1199 static size_t bytes_used_when_reconsidered;
1200
1201 /* Value of _bytes_used, when spare_memory was freed. */
1202
1203 static size_t bytes_used_when_full;
1204
1205 /* This function is used as the hook for free to call. */
1206
1207 static void
1208 emacs_blocked_free (void *ptr, const void *ptr2)
1209 {
1210 BLOCK_INPUT_ALLOC;
1211
1212 #ifdef GC_MALLOC_CHECK
1213 if (ptr)
1214 {
1215 struct mem_node *m;
1216
1217 m = mem_find (ptr);
1218 if (m == MEM_NIL || m->start != ptr)
1219 {
1220 fprintf (stderr,
1221 "Freeing `%p' which wasn't allocated with malloc\n", ptr);
1222 abort ();
1223 }
1224 else
1225 {
1226 /* fprintf (stderr, "free %p...%p (%p)\n", m->start, m->end, ptr); */
1227 mem_delete (m);
1228 }
1229 }
1230 #endif /* GC_MALLOC_CHECK */
1231
1232 __free_hook = old_free_hook;
1233 free (ptr);
1234
1235 /* If we released our reserve (due to running out of memory),
1236 and we have a fair amount free once again,
1237 try to set aside another reserve in case we run out once more. */
1238 if (! NILP (Vmemory_full)
1239 /* Verify there is enough space that even with the malloc
1240 hysteresis this call won't run out again.
1241 The code here is correct as long as SPARE_MEMORY
1242 is substantially larger than the block size malloc uses. */
1243 && (bytes_used_when_full
1244 > ((bytes_used_when_reconsidered = BYTES_USED)
1245 + max (malloc_hysteresis, 4) * SPARE_MEMORY)))
1246 refill_memory_reserve ();
1247
1248 __free_hook = emacs_blocked_free;
1249 UNBLOCK_INPUT_ALLOC;
1250 }
1251
1252
1253 /* This function is the malloc hook that Emacs uses. */
1254
1255 static void *
1256 emacs_blocked_malloc (size_t size, const void *ptr)
1257 {
1258 void *value;
1259
1260 BLOCK_INPUT_ALLOC;
1261 __malloc_hook = old_malloc_hook;
1262 #ifdef DOUG_LEA_MALLOC
1263 /* Segfaults on my system. --lorentey */
1264 /* mallopt (M_TOP_PAD, malloc_hysteresis * 4096); */
1265 #else
1266 __malloc_extra_blocks = malloc_hysteresis;
1267 #endif
1268
1269 value = (void *) malloc (size);
1270
1271 #ifdef GC_MALLOC_CHECK
1272 {
1273 struct mem_node *m = mem_find (value);
1274 if (m != MEM_NIL)
1275 {
1276 fprintf (stderr, "Malloc returned %p which is already in use\n",
1277 value);
1278 fprintf (stderr, "Region in use is %p...%p, %u bytes, type %d\n",
1279 m->start, m->end, (char *) m->end - (char *) m->start,
1280 m->type);
1281 abort ();
1282 }
1283
1284 if (!dont_register_blocks)
1285 {
1286 mem_insert (value, (char *) value + max (1, size), allocated_mem_type);
1287 allocated_mem_type = MEM_TYPE_NON_LISP;
1288 }
1289 }
1290 #endif /* GC_MALLOC_CHECK */
1291
1292 __malloc_hook = emacs_blocked_malloc;
1293 UNBLOCK_INPUT_ALLOC;
1294
1295 /* fprintf (stderr, "%p malloc\n", value); */
1296 return value;
1297 }
1298
1299
1300 /* This function is the realloc hook that Emacs uses. */
1301
1302 static void *
1303 emacs_blocked_realloc (void *ptr, size_t size, const void *ptr2)
1304 {
1305 void *value;
1306
1307 BLOCK_INPUT_ALLOC;
1308 __realloc_hook = old_realloc_hook;
1309
1310 #ifdef GC_MALLOC_CHECK
1311 if (ptr)
1312 {
1313 struct mem_node *m = mem_find (ptr);
1314 if (m == MEM_NIL || m->start != ptr)
1315 {
1316 fprintf (stderr,
1317 "Realloc of %p which wasn't allocated with malloc\n",
1318 ptr);
1319 abort ();
1320 }
1321
1322 mem_delete (m);
1323 }
1324
1325 /* fprintf (stderr, "%p -> realloc\n", ptr); */
1326
1327 /* Prevent malloc from registering blocks. */
1328 dont_register_blocks = 1;
1329 #endif /* GC_MALLOC_CHECK */
1330
1331 value = (void *) realloc (ptr, size);
1332
1333 #ifdef GC_MALLOC_CHECK
1334 dont_register_blocks = 0;
1335
1336 {
1337 struct mem_node *m = mem_find (value);
1338 if (m != MEM_NIL)
1339 {
1340 fprintf (stderr, "Realloc returns memory that is already in use\n");
1341 abort ();
1342 }
1343
1344 /* Can't handle zero size regions in the red-black tree. */
1345 mem_insert (value, (char *) value + max (size, 1), MEM_TYPE_NON_LISP);
1346 }
1347
1348 /* fprintf (stderr, "%p <- realloc\n", value); */
1349 #endif /* GC_MALLOC_CHECK */
1350
1351 __realloc_hook = emacs_blocked_realloc;
1352 UNBLOCK_INPUT_ALLOC;
1353
1354 return value;
1355 }
1356
1357
1358 #ifdef HAVE_PTHREAD
1359 /* Called from Fdump_emacs so that when the dumped Emacs starts, it has a
1360 normal malloc. Some thread implementations need this as they call
1361 malloc before main. The pthread_self call in BLOCK_INPUT_ALLOC then
1362 calls malloc because it is the first call, and we have an endless loop. */
1363
1364 void
1365 reset_malloc_hooks (void)
1366 {
1367 __free_hook = old_free_hook;
1368 __malloc_hook = old_malloc_hook;
1369 __realloc_hook = old_realloc_hook;
1370 }
1371 #endif /* HAVE_PTHREAD */
1372
1373
1374 /* Called from main to set up malloc to use our hooks. */
1375
1376 void
1377 uninterrupt_malloc (void)
1378 {
1379 #ifdef HAVE_PTHREAD
1380 #ifdef DOUG_LEA_MALLOC
1381 pthread_mutexattr_t attr;
1382
1383 /* GLIBC has a faster way to do this, but lets keep it portable.
1384 This is according to the Single UNIX Specification. */
1385 pthread_mutexattr_init (&attr);
1386 pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
1387 pthread_mutex_init (&alloc_mutex, &attr);
1388 #else /* !DOUG_LEA_MALLOC */
1389 /* Some systems such as Solaris 2.6 don't have a recursive mutex,
1390 and the bundled gmalloc.c doesn't require it. */
1391 pthread_mutex_init (&alloc_mutex, NULL);
1392 #endif /* !DOUG_LEA_MALLOC */
1393 #endif /* HAVE_PTHREAD */
1394
1395 if (__free_hook != emacs_blocked_free)
1396 old_free_hook = __free_hook;
1397 __free_hook = emacs_blocked_free;
1398
1399 if (__malloc_hook != emacs_blocked_malloc)
1400 old_malloc_hook = __malloc_hook;
1401 __malloc_hook = emacs_blocked_malloc;
1402
1403 if (__realloc_hook != emacs_blocked_realloc)
1404 old_realloc_hook = __realloc_hook;
1405 __realloc_hook = emacs_blocked_realloc;
1406 }
1407
1408 #endif /* not SYNC_INPUT */
1409 #endif /* not SYSTEM_MALLOC */
1410
1411
1412 \f
1413 /***********************************************************************
1414 Interval Allocation
1415 ***********************************************************************/
1416
1417 /* Number of intervals allocated in an interval_block structure.
1418 The 1020 is 1024 minus malloc overhead. */
1419
1420 #define INTERVAL_BLOCK_SIZE \
1421 ((1020 - sizeof (struct interval_block *)) / sizeof (struct interval))
1422
1423 /* Intervals are allocated in chunks in form of an interval_block
1424 structure. */
1425
1426 struct interval_block
1427 {
1428 /* Place `intervals' first, to preserve alignment. */
1429 struct interval intervals[INTERVAL_BLOCK_SIZE];
1430 struct interval_block *next;
1431 };
1432
1433 /* Current interval block. Its `next' pointer points to older
1434 blocks. */
1435
1436 static struct interval_block *interval_block;
1437
1438 /* Index in interval_block above of the next unused interval
1439 structure. */
1440
1441 static int interval_block_index;
1442
1443 /* Number of free and live intervals. */
1444
1445 static EMACS_INT total_free_intervals, total_intervals;
1446
1447 /* List of free intervals. */
1448
1449 static INTERVAL interval_free_list;
1450
1451
1452 /* Initialize interval allocation. */
1453
1454 static void
1455 init_intervals (void)
1456 {
1457 interval_block = NULL;
1458 interval_block_index = INTERVAL_BLOCK_SIZE;
1459 interval_free_list = 0;
1460 }
1461
1462
1463 /* Return a new interval. */
1464
1465 INTERVAL
1466 make_interval (void)
1467 {
1468 INTERVAL val;
1469
1470 /* eassert (!handling_signal); */
1471
1472 MALLOC_BLOCK_INPUT;
1473
1474 if (interval_free_list)
1475 {
1476 val = interval_free_list;
1477 interval_free_list = INTERVAL_PARENT (interval_free_list);
1478 }
1479 else
1480 {
1481 if (interval_block_index == INTERVAL_BLOCK_SIZE)
1482 {
1483 register struct interval_block *newi;
1484
1485 newi = (struct interval_block *) lisp_malloc (sizeof *newi,
1486 MEM_TYPE_NON_LISP);
1487
1488 newi->next = interval_block;
1489 interval_block = newi;
1490 interval_block_index = 0;
1491 }
1492 val = &interval_block->intervals[interval_block_index++];
1493 }
1494
1495 MALLOC_UNBLOCK_INPUT;
1496
1497 consing_since_gc += sizeof (struct interval);
1498 intervals_consed++;
1499 RESET_INTERVAL (val);
1500 val->gcmarkbit = 0;
1501 return val;
1502 }
1503
1504
1505 /* Mark Lisp objects in interval I. */
1506
1507 static void
1508 mark_interval (register INTERVAL i, Lisp_Object dummy)
1509 {
1510 eassert (!i->gcmarkbit); /* Intervals are never shared. */
1511 i->gcmarkbit = 1;
1512 mark_object (i->plist);
1513 }
1514
1515
1516 /* Mark the interval tree rooted in TREE. Don't call this directly;
1517 use the macro MARK_INTERVAL_TREE instead. */
1518
1519 static void
1520 mark_interval_tree (register INTERVAL tree)
1521 {
1522 /* No need to test if this tree has been marked already; this
1523 function is always called through the MARK_INTERVAL_TREE macro,
1524 which takes care of that. */
1525
1526 traverse_intervals_noorder (tree, mark_interval, Qnil);
1527 }
1528
1529
1530 /* Mark the interval tree rooted in I. */
1531
1532 #define MARK_INTERVAL_TREE(i) \
1533 do { \
1534 if (!NULL_INTERVAL_P (i) && !i->gcmarkbit) \
1535 mark_interval_tree (i); \
1536 } while (0)
1537
1538
1539 #define UNMARK_BALANCE_INTERVALS(i) \
1540 do { \
1541 if (! NULL_INTERVAL_P (i)) \
1542 (i) = balance_intervals (i); \
1543 } while (0)
1544
1545 \f
1546 /* Number support. If USE_LISP_UNION_TYPE is in effect, we
1547 can't create number objects in macros. */
1548 #ifndef make_number
1549 Lisp_Object
1550 make_number (EMACS_INT n)
1551 {
1552 Lisp_Object obj;
1553 obj.s.val = n;
1554 obj.s.type = Lisp_Int;
1555 return obj;
1556 }
1557 #endif
1558 \f
1559 /***********************************************************************
1560 String Allocation
1561 ***********************************************************************/
1562
1563 /* Lisp_Strings are allocated in string_block structures. When a new
1564 string_block is allocated, all the Lisp_Strings it contains are
1565 added to a free-list string_free_list. When a new Lisp_String is
1566 needed, it is taken from that list. During the sweep phase of GC,
1567 string_blocks that are entirely free are freed, except two which
1568 we keep.
1569
1570 String data is allocated from sblock structures. Strings larger
1571 than LARGE_STRING_BYTES, get their own sblock, data for smaller
1572 strings is sub-allocated out of sblocks of size SBLOCK_SIZE.
1573
1574 Sblocks consist internally of sdata structures, one for each
1575 Lisp_String. The sdata structure points to the Lisp_String it
1576 belongs to. The Lisp_String points back to the `u.data' member of
1577 its sdata structure.
1578
1579 When a Lisp_String is freed during GC, it is put back on
1580 string_free_list, and its `data' member and its sdata's `string'
1581 pointer is set to null. The size of the string is recorded in the
1582 `u.nbytes' member of the sdata. So, sdata structures that are no
1583 longer used, can be easily recognized, and it's easy to compact the
1584 sblocks of small strings which we do in compact_small_strings. */
1585
1586 /* Size in bytes of an sblock structure used for small strings. This
1587 is 8192 minus malloc overhead. */
1588
1589 #define SBLOCK_SIZE 8188
1590
1591 /* Strings larger than this are considered large strings. String data
1592 for large strings is allocated from individual sblocks. */
1593
1594 #define LARGE_STRING_BYTES 1024
1595
1596 /* Structure describing string memory sub-allocated from an sblock.
1597 This is where the contents of Lisp strings are stored. */
1598
1599 struct sdata
1600 {
1601 /* Back-pointer to the string this sdata belongs to. If null, this
1602 structure is free, and the NBYTES member of the union below
1603 contains the string's byte size (the same value that STRING_BYTES
1604 would return if STRING were non-null). If non-null, STRING_BYTES
1605 (STRING) is the size of the data, and DATA contains the string's
1606 contents. */
1607 struct Lisp_String *string;
1608
1609 #ifdef GC_CHECK_STRING_BYTES
1610
1611 EMACS_INT nbytes;
1612 unsigned char data[1];
1613
1614 #define SDATA_NBYTES(S) (S)->nbytes
1615 #define SDATA_DATA(S) (S)->data
1616 #define SDATA_SELECTOR(member) member
1617
1618 #else /* not GC_CHECK_STRING_BYTES */
1619
1620 union
1621 {
1622 /* When STRING is non-null. */
1623 unsigned char data[1];
1624
1625 /* When STRING is null. */
1626 EMACS_INT nbytes;
1627 } u;
1628
1629 #define SDATA_NBYTES(S) (S)->u.nbytes
1630 #define SDATA_DATA(S) (S)->u.data
1631 #define SDATA_SELECTOR(member) u.member
1632
1633 #endif /* not GC_CHECK_STRING_BYTES */
1634
1635 #define SDATA_DATA_OFFSET offsetof (struct sdata, SDATA_SELECTOR (data))
1636 };
1637
1638
1639 /* Structure describing a block of memory which is sub-allocated to
1640 obtain string data memory for strings. Blocks for small strings
1641 are of fixed size SBLOCK_SIZE. Blocks for large strings are made
1642 as large as needed. */
1643
1644 struct sblock
1645 {
1646 /* Next in list. */
1647 struct sblock *next;
1648
1649 /* Pointer to the next free sdata block. This points past the end
1650 of the sblock if there isn't any space left in this block. */
1651 struct sdata *next_free;
1652
1653 /* Start of data. */
1654 struct sdata first_data;
1655 };
1656
1657 /* Number of Lisp strings in a string_block structure. The 1020 is
1658 1024 minus malloc overhead. */
1659
1660 #define STRING_BLOCK_SIZE \
1661 ((1020 - sizeof (struct string_block *)) / sizeof (struct Lisp_String))
1662
1663 /* Structure describing a block from which Lisp_String structures
1664 are allocated. */
1665
1666 struct string_block
1667 {
1668 /* Place `strings' first, to preserve alignment. */
1669 struct Lisp_String strings[STRING_BLOCK_SIZE];
1670 struct string_block *next;
1671 };
1672
1673 /* Head and tail of the list of sblock structures holding Lisp string
1674 data. We always allocate from current_sblock. The NEXT pointers
1675 in the sblock structures go from oldest_sblock to current_sblock. */
1676
1677 static struct sblock *oldest_sblock, *current_sblock;
1678
1679 /* List of sblocks for large strings. */
1680
1681 static struct sblock *large_sblocks;
1682
1683 /* List of string_block structures. */
1684
1685 static struct string_block *string_blocks;
1686
1687 /* Free-list of Lisp_Strings. */
1688
1689 static struct Lisp_String *string_free_list;
1690
1691 /* Number of live and free Lisp_Strings. */
1692
1693 static EMACS_INT total_strings, total_free_strings;
1694
1695 /* Number of bytes used by live strings. */
1696
1697 static EMACS_INT total_string_size;
1698
1699 /* Given a pointer to a Lisp_String S which is on the free-list
1700 string_free_list, return a pointer to its successor in the
1701 free-list. */
1702
1703 #define NEXT_FREE_LISP_STRING(S) (*(struct Lisp_String **) (S))
1704
1705 /* Return a pointer to the sdata structure belonging to Lisp string S.
1706 S must be live, i.e. S->data must not be null. S->data is actually
1707 a pointer to the `u.data' member of its sdata structure; the
1708 structure starts at a constant offset in front of that. */
1709
1710 #define SDATA_OF_STRING(S) ((struct sdata *) ((S)->data - SDATA_DATA_OFFSET))
1711
1712
1713 #ifdef GC_CHECK_STRING_OVERRUN
1714
1715 /* We check for overrun in string data blocks by appending a small
1716 "cookie" after each allocated string data block, and check for the
1717 presence of this cookie during GC. */
1718
1719 #define GC_STRING_OVERRUN_COOKIE_SIZE 4
1720 static char const string_overrun_cookie[GC_STRING_OVERRUN_COOKIE_SIZE] =
1721 { '\xde', '\xad', '\xbe', '\xef' };
1722
1723 #else
1724 #define GC_STRING_OVERRUN_COOKIE_SIZE 0
1725 #endif
1726
1727 /* Value is the size of an sdata structure large enough to hold NBYTES
1728 bytes of string data. The value returned includes a terminating
1729 NUL byte, the size of the sdata structure, and padding. */
1730
1731 #ifdef GC_CHECK_STRING_BYTES
1732
1733 #define SDATA_SIZE(NBYTES) \
1734 ((SDATA_DATA_OFFSET \
1735 + (NBYTES) + 1 \
1736 + sizeof (EMACS_INT) - 1) \
1737 & ~(sizeof (EMACS_INT) - 1))
1738
1739 #else /* not GC_CHECK_STRING_BYTES */
1740
1741 /* The 'max' reserves space for the nbytes union member even when NBYTES + 1 is
1742 less than the size of that member. The 'max' is not needed when
1743 SDATA_DATA_OFFSET is a multiple of sizeof (EMACS_INT), because then the
1744 alignment code reserves enough space. */
1745
1746 #define SDATA_SIZE(NBYTES) \
1747 ((SDATA_DATA_OFFSET \
1748 + (SDATA_DATA_OFFSET % sizeof (EMACS_INT) == 0 \
1749 ? NBYTES \
1750 : max (NBYTES, sizeof (EMACS_INT) - 1)) \
1751 + 1 \
1752 + sizeof (EMACS_INT) - 1) \
1753 & ~(sizeof (EMACS_INT) - 1))
1754
1755 #endif /* not GC_CHECK_STRING_BYTES */
1756
1757 /* Extra bytes to allocate for each string. */
1758
1759 #define GC_STRING_EXTRA (GC_STRING_OVERRUN_COOKIE_SIZE)
1760
1761 /* Exact bound on the number of bytes in a string, not counting the
1762 terminating null. A string cannot contain more bytes than
1763 STRING_BYTES_BOUND, nor can it be so long that the size_t
1764 arithmetic in allocate_string_data would overflow while it is
1765 calculating a value to be passed to malloc. */
1766 #define STRING_BYTES_MAX \
1767 min (STRING_BYTES_BOUND, \
1768 ((SIZE_MAX - XMALLOC_OVERRUN_CHECK_OVERHEAD \
1769 - GC_STRING_EXTRA \
1770 - offsetof (struct sblock, first_data) \
1771 - SDATA_DATA_OFFSET) \
1772 & ~(sizeof (EMACS_INT) - 1)))
1773
1774 /* Initialize string allocation. Called from init_alloc_once. */
1775
1776 static void
1777 init_strings (void)
1778 {
1779 total_strings = total_free_strings = total_string_size = 0;
1780 oldest_sblock = current_sblock = large_sblocks = NULL;
1781 string_blocks = NULL;
1782 string_free_list = NULL;
1783 empty_unibyte_string = make_pure_string ("", 0, 0, 0);
1784 empty_multibyte_string = make_pure_string ("", 0, 0, 1);
1785 }
1786
1787
1788 #ifdef GC_CHECK_STRING_BYTES
1789
1790 static int check_string_bytes_count;
1791
1792 #define CHECK_STRING_BYTES(S) STRING_BYTES (S)
1793
1794
1795 /* Like GC_STRING_BYTES, but with debugging check. */
1796
1797 EMACS_INT
1798 string_bytes (struct Lisp_String *s)
1799 {
1800 EMACS_INT nbytes =
1801 (s->size_byte < 0 ? s->size & ~ARRAY_MARK_FLAG : s->size_byte);
1802
1803 if (!PURE_POINTER_P (s)
1804 && s->data
1805 && nbytes != SDATA_NBYTES (SDATA_OF_STRING (s)))
1806 abort ();
1807 return nbytes;
1808 }
1809
1810 /* Check validity of Lisp strings' string_bytes member in B. */
1811
1812 static void
1813 check_sblock (struct sblock *b)
1814 {
1815 struct sdata *from, *end, *from_end;
1816
1817 end = b->next_free;
1818
1819 for (from = &b->first_data; from < end; from = from_end)
1820 {
1821 /* Compute the next FROM here because copying below may
1822 overwrite data we need to compute it. */
1823 EMACS_INT nbytes;
1824
1825 /* Check that the string size recorded in the string is the
1826 same as the one recorded in the sdata structure. */
1827 if (from->string)
1828 CHECK_STRING_BYTES (from->string);
1829
1830 if (from->string)
1831 nbytes = GC_STRING_BYTES (from->string);
1832 else
1833 nbytes = SDATA_NBYTES (from);
1834
1835 nbytes = SDATA_SIZE (nbytes);
1836 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
1837 }
1838 }
1839
1840
1841 /* Check validity of Lisp strings' string_bytes member. ALL_P
1842 non-zero means check all strings, otherwise check only most
1843 recently allocated strings. Used for hunting a bug. */
1844
1845 static void
1846 check_string_bytes (int all_p)
1847 {
1848 if (all_p)
1849 {
1850 struct sblock *b;
1851
1852 for (b = large_sblocks; b; b = b->next)
1853 {
1854 struct Lisp_String *s = b->first_data.string;
1855 if (s)
1856 CHECK_STRING_BYTES (s);
1857 }
1858
1859 for (b = oldest_sblock; b; b = b->next)
1860 check_sblock (b);
1861 }
1862 else
1863 check_sblock (current_sblock);
1864 }
1865
1866 #endif /* GC_CHECK_STRING_BYTES */
1867
1868 #ifdef GC_CHECK_STRING_FREE_LIST
1869
1870 /* Walk through the string free list looking for bogus next pointers.
1871 This may catch buffer overrun from a previous string. */
1872
1873 static void
1874 check_string_free_list (void)
1875 {
1876 struct Lisp_String *s;
1877
1878 /* Pop a Lisp_String off the free-list. */
1879 s = string_free_list;
1880 while (s != NULL)
1881 {
1882 if ((uintptr_t) s < 1024)
1883 abort();
1884 s = NEXT_FREE_LISP_STRING (s);
1885 }
1886 }
1887 #else
1888 #define check_string_free_list()
1889 #endif
1890
1891 /* Return a new Lisp_String. */
1892
1893 static struct Lisp_String *
1894 allocate_string (void)
1895 {
1896 struct Lisp_String *s;
1897
1898 /* eassert (!handling_signal); */
1899
1900 MALLOC_BLOCK_INPUT;
1901
1902 /* If the free-list is empty, allocate a new string_block, and
1903 add all the Lisp_Strings in it to the free-list. */
1904 if (string_free_list == NULL)
1905 {
1906 struct string_block *b;
1907 int i;
1908
1909 b = (struct string_block *) lisp_malloc (sizeof *b, MEM_TYPE_STRING);
1910 memset (b, 0, sizeof *b);
1911 b->next = string_blocks;
1912 string_blocks = b;
1913
1914 for (i = STRING_BLOCK_SIZE - 1; i >= 0; --i)
1915 {
1916 s = b->strings + i;
1917 NEXT_FREE_LISP_STRING (s) = string_free_list;
1918 string_free_list = s;
1919 }
1920
1921 total_free_strings += STRING_BLOCK_SIZE;
1922 }
1923
1924 check_string_free_list ();
1925
1926 /* Pop a Lisp_String off the free-list. */
1927 s = string_free_list;
1928 string_free_list = NEXT_FREE_LISP_STRING (s);
1929
1930 MALLOC_UNBLOCK_INPUT;
1931
1932 /* Probably not strictly necessary, but play it safe. */
1933 memset (s, 0, sizeof *s);
1934
1935 --total_free_strings;
1936 ++total_strings;
1937 ++strings_consed;
1938 consing_since_gc += sizeof *s;
1939
1940 #ifdef GC_CHECK_STRING_BYTES
1941 if (!noninteractive)
1942 {
1943 if (++check_string_bytes_count == 200)
1944 {
1945 check_string_bytes_count = 0;
1946 check_string_bytes (1);
1947 }
1948 else
1949 check_string_bytes (0);
1950 }
1951 #endif /* GC_CHECK_STRING_BYTES */
1952
1953 return s;
1954 }
1955
1956
1957 /* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1958 plus a NUL byte at the end. Allocate an sdata structure for S, and
1959 set S->data to its `u.data' member. Store a NUL byte at the end of
1960 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1961 S->data if it was initially non-null. */
1962
1963 void
1964 allocate_string_data (struct Lisp_String *s,
1965 EMACS_INT nchars, EMACS_INT nbytes)
1966 {
1967 struct sdata *data, *old_data;
1968 struct sblock *b;
1969 EMACS_INT needed, old_nbytes;
1970
1971 if (STRING_BYTES_MAX < nbytes)
1972 string_overflow ();
1973
1974 /* Determine the number of bytes needed to store NBYTES bytes
1975 of string data. */
1976 needed = SDATA_SIZE (nbytes);
1977 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1978 old_nbytes = GC_STRING_BYTES (s);
1979
1980 MALLOC_BLOCK_INPUT;
1981
1982 if (nbytes > LARGE_STRING_BYTES)
1983 {
1984 size_t size = offsetof (struct sblock, first_data) + needed;
1985
1986 #ifdef DOUG_LEA_MALLOC
1987 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1988 because mapped region contents are not preserved in
1989 a dumped Emacs.
1990
1991 In case you think of allowing it in a dumped Emacs at the
1992 cost of not being able to re-dump, there's another reason:
1993 mmap'ed data typically have an address towards the top of the
1994 address space, which won't fit into an EMACS_INT (at least on
1995 32-bit systems with the current tagging scheme). --fx */
1996 mallopt (M_MMAP_MAX, 0);
1997 #endif
1998
1999 b = (struct sblock *) lisp_malloc (size + GC_STRING_EXTRA, MEM_TYPE_NON_LISP);
2000
2001 #ifdef DOUG_LEA_MALLOC
2002 /* Back to a reasonable maximum of mmap'ed areas. */
2003 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2004 #endif
2005
2006 b->next_free = &b->first_data;
2007 b->first_data.string = NULL;
2008 b->next = large_sblocks;
2009 large_sblocks = b;
2010 }
2011 else if (current_sblock == NULL
2012 || (((char *) current_sblock + SBLOCK_SIZE
2013 - (char *) current_sblock->next_free)
2014 < (needed + GC_STRING_EXTRA)))
2015 {
2016 /* Not enough room in the current sblock. */
2017 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
2018 b->next_free = &b->first_data;
2019 b->first_data.string = NULL;
2020 b->next = NULL;
2021
2022 if (current_sblock)
2023 current_sblock->next = b;
2024 else
2025 oldest_sblock = b;
2026 current_sblock = b;
2027 }
2028 else
2029 b = current_sblock;
2030
2031 data = b->next_free;
2032 b->next_free = (struct sdata *) ((char *) data + needed + GC_STRING_EXTRA);
2033
2034 MALLOC_UNBLOCK_INPUT;
2035
2036 data->string = s;
2037 s->data = SDATA_DATA (data);
2038 #ifdef GC_CHECK_STRING_BYTES
2039 SDATA_NBYTES (data) = nbytes;
2040 #endif
2041 s->size = nchars;
2042 s->size_byte = nbytes;
2043 s->data[nbytes] = '\0';
2044 #ifdef GC_CHECK_STRING_OVERRUN
2045 memcpy ((char *) data + needed, string_overrun_cookie,
2046 GC_STRING_OVERRUN_COOKIE_SIZE);
2047 #endif
2048
2049 /* If S had already data assigned, mark that as free by setting its
2050 string back-pointer to null, and recording the size of the data
2051 in it. */
2052 if (old_data)
2053 {
2054 SDATA_NBYTES (old_data) = old_nbytes;
2055 old_data->string = NULL;
2056 }
2057
2058 consing_since_gc += needed;
2059 }
2060
2061
2062 /* Sweep and compact strings. */
2063
2064 static void
2065 sweep_strings (void)
2066 {
2067 struct string_block *b, *next;
2068 struct string_block *live_blocks = NULL;
2069
2070 string_free_list = NULL;
2071 total_strings = total_free_strings = 0;
2072 total_string_size = 0;
2073
2074 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
2075 for (b = string_blocks; b; b = next)
2076 {
2077 int i, nfree = 0;
2078 struct Lisp_String *free_list_before = string_free_list;
2079
2080 next = b->next;
2081
2082 for (i = 0; i < STRING_BLOCK_SIZE; ++i)
2083 {
2084 struct Lisp_String *s = b->strings + i;
2085
2086 if (s->data)
2087 {
2088 /* String was not on free-list before. */
2089 if (STRING_MARKED_P (s))
2090 {
2091 /* String is live; unmark it and its intervals. */
2092 UNMARK_STRING (s);
2093
2094 if (!NULL_INTERVAL_P (s->intervals))
2095 UNMARK_BALANCE_INTERVALS (s->intervals);
2096
2097 ++total_strings;
2098 total_string_size += STRING_BYTES (s);
2099 }
2100 else
2101 {
2102 /* String is dead. Put it on the free-list. */
2103 struct sdata *data = SDATA_OF_STRING (s);
2104
2105 /* Save the size of S in its sdata so that we know
2106 how large that is. Reset the sdata's string
2107 back-pointer so that we know it's free. */
2108 #ifdef GC_CHECK_STRING_BYTES
2109 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
2110 abort ();
2111 #else
2112 data->u.nbytes = GC_STRING_BYTES (s);
2113 #endif
2114 data->string = NULL;
2115
2116 /* Reset the strings's `data' member so that we
2117 know it's free. */
2118 s->data = NULL;
2119
2120 /* Put the string on the free-list. */
2121 NEXT_FREE_LISP_STRING (s) = string_free_list;
2122 string_free_list = s;
2123 ++nfree;
2124 }
2125 }
2126 else
2127 {
2128 /* S was on the free-list before. Put it there again. */
2129 NEXT_FREE_LISP_STRING (s) = string_free_list;
2130 string_free_list = s;
2131 ++nfree;
2132 }
2133 }
2134
2135 /* Free blocks that contain free Lisp_Strings only, except
2136 the first two of them. */
2137 if (nfree == STRING_BLOCK_SIZE
2138 && total_free_strings > STRING_BLOCK_SIZE)
2139 {
2140 lisp_free (b);
2141 string_free_list = free_list_before;
2142 }
2143 else
2144 {
2145 total_free_strings += nfree;
2146 b->next = live_blocks;
2147 live_blocks = b;
2148 }
2149 }
2150
2151 check_string_free_list ();
2152
2153 string_blocks = live_blocks;
2154 free_large_strings ();
2155 compact_small_strings ();
2156
2157 check_string_free_list ();
2158 }
2159
2160
2161 /* Free dead large strings. */
2162
2163 static void
2164 free_large_strings (void)
2165 {
2166 struct sblock *b, *next;
2167 struct sblock *live_blocks = NULL;
2168
2169 for (b = large_sblocks; b; b = next)
2170 {
2171 next = b->next;
2172
2173 if (b->first_data.string == NULL)
2174 lisp_free (b);
2175 else
2176 {
2177 b->next = live_blocks;
2178 live_blocks = b;
2179 }
2180 }
2181
2182 large_sblocks = live_blocks;
2183 }
2184
2185
2186 /* Compact data of small strings. Free sblocks that don't contain
2187 data of live strings after compaction. */
2188
2189 static void
2190 compact_small_strings (void)
2191 {
2192 struct sblock *b, *tb, *next;
2193 struct sdata *from, *to, *end, *tb_end;
2194 struct sdata *to_end, *from_end;
2195
2196 /* TB is the sblock we copy to, TO is the sdata within TB we copy
2197 to, and TB_END is the end of TB. */
2198 tb = oldest_sblock;
2199 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2200 to = &tb->first_data;
2201
2202 /* Step through the blocks from the oldest to the youngest. We
2203 expect that old blocks will stabilize over time, so that less
2204 copying will happen this way. */
2205 for (b = oldest_sblock; b; b = b->next)
2206 {
2207 end = b->next_free;
2208 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
2209
2210 for (from = &b->first_data; from < end; from = from_end)
2211 {
2212 /* Compute the next FROM here because copying below may
2213 overwrite data we need to compute it. */
2214 EMACS_INT nbytes;
2215
2216 #ifdef GC_CHECK_STRING_BYTES
2217 /* Check that the string size recorded in the string is the
2218 same as the one recorded in the sdata structure. */
2219 if (from->string
2220 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
2221 abort ();
2222 #endif /* GC_CHECK_STRING_BYTES */
2223
2224 if (from->string)
2225 nbytes = GC_STRING_BYTES (from->string);
2226 else
2227 nbytes = SDATA_NBYTES (from);
2228
2229 if (nbytes > LARGE_STRING_BYTES)
2230 abort ();
2231
2232 nbytes = SDATA_SIZE (nbytes);
2233 from_end = (struct sdata *) ((char *) from + nbytes + GC_STRING_EXTRA);
2234
2235 #ifdef GC_CHECK_STRING_OVERRUN
2236 if (memcmp (string_overrun_cookie,
2237 (char *) from_end - GC_STRING_OVERRUN_COOKIE_SIZE,
2238 GC_STRING_OVERRUN_COOKIE_SIZE))
2239 abort ();
2240 #endif
2241
2242 /* FROM->string non-null means it's alive. Copy its data. */
2243 if (from->string)
2244 {
2245 /* If TB is full, proceed with the next sblock. */
2246 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2247 if (to_end > tb_end)
2248 {
2249 tb->next_free = to;
2250 tb = tb->next;
2251 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
2252 to = &tb->first_data;
2253 to_end = (struct sdata *) ((char *) to + nbytes + GC_STRING_EXTRA);
2254 }
2255
2256 /* Copy, and update the string's `data' pointer. */
2257 if (from != to)
2258 {
2259 xassert (tb != b || to < from);
2260 memmove (to, from, nbytes + GC_STRING_EXTRA);
2261 to->string->data = SDATA_DATA (to);
2262 }
2263
2264 /* Advance past the sdata we copied to. */
2265 to = to_end;
2266 }
2267 }
2268 }
2269
2270 /* The rest of the sblocks following TB don't contain live data, so
2271 we can free them. */
2272 for (b = tb->next; b; b = next)
2273 {
2274 next = b->next;
2275 lisp_free (b);
2276 }
2277
2278 tb->next_free = to;
2279 tb->next = NULL;
2280 current_sblock = tb;
2281 }
2282
2283 void
2284 string_overflow (void)
2285 {
2286 error ("Maximum string size exceeded");
2287 }
2288
2289 DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
2290 doc: /* Return a newly created string of length LENGTH, with INIT in each element.
2291 LENGTH must be an integer.
2292 INIT must be an integer that represents a character. */)
2293 (Lisp_Object length, Lisp_Object init)
2294 {
2295 register Lisp_Object val;
2296 register unsigned char *p, *end;
2297 int c;
2298 EMACS_INT nbytes;
2299
2300 CHECK_NATNUM (length);
2301 CHECK_CHARACTER (init);
2302
2303 c = XFASTINT (init);
2304 if (ASCII_CHAR_P (c))
2305 {
2306 nbytes = XINT (length);
2307 val = make_uninit_string (nbytes);
2308 p = SDATA (val);
2309 end = p + SCHARS (val);
2310 while (p != end)
2311 *p++ = c;
2312 }
2313 else
2314 {
2315 unsigned char str[MAX_MULTIBYTE_LENGTH];
2316 int len = CHAR_STRING (c, str);
2317 EMACS_INT string_len = XINT (length);
2318
2319 if (string_len > STRING_BYTES_MAX / len)
2320 string_overflow ();
2321 nbytes = len * string_len;
2322 val = make_uninit_multibyte_string (string_len, nbytes);
2323 p = SDATA (val);
2324 end = p + nbytes;
2325 while (p != end)
2326 {
2327 memcpy (p, str, len);
2328 p += len;
2329 }
2330 }
2331
2332 *p = 0;
2333 return val;
2334 }
2335
2336
2337 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2338 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2339 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2340 (Lisp_Object length, Lisp_Object init)
2341 {
2342 register Lisp_Object val;
2343 struct Lisp_Bool_Vector *p;
2344 EMACS_INT length_in_chars, length_in_elts;
2345 int bits_per_value;
2346
2347 CHECK_NATNUM (length);
2348
2349 bits_per_value = sizeof (EMACS_INT) * BOOL_VECTOR_BITS_PER_CHAR;
2350
2351 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
2352 length_in_chars = ((XFASTINT (length) + BOOL_VECTOR_BITS_PER_CHAR - 1)
2353 / BOOL_VECTOR_BITS_PER_CHAR);
2354
2355 /* We must allocate one more elements than LENGTH_IN_ELTS for the
2356 slot `size' of the struct Lisp_Bool_Vector. */
2357 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
2358
2359 /* No Lisp_Object to trace in there. */
2360 XSETPVECTYPESIZE (XVECTOR (val), PVEC_BOOL_VECTOR, 0);
2361
2362 p = XBOOL_VECTOR (val);
2363 p->size = XFASTINT (length);
2364
2365 if (length_in_chars)
2366 {
2367 memset (p->data, ! NILP (init) ? -1 : 0, length_in_chars);
2368
2369 /* Clear any extraneous bits in the last byte. */
2370 p->data[length_in_chars - 1]
2371 &= (1 << (XINT (length) % BOOL_VECTOR_BITS_PER_CHAR)) - 1;
2372 }
2373
2374 return val;
2375 }
2376
2377
2378 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2379 of characters from the contents. This string may be unibyte or
2380 multibyte, depending on the contents. */
2381
2382 Lisp_Object
2383 make_string (const char *contents, EMACS_INT nbytes)
2384 {
2385 register Lisp_Object val;
2386 EMACS_INT nchars, multibyte_nbytes;
2387
2388 parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
2389 &nchars, &multibyte_nbytes);
2390 if (nbytes == nchars || nbytes != multibyte_nbytes)
2391 /* CONTENTS contains no multibyte sequences or contains an invalid
2392 multibyte sequence. We must make unibyte string. */
2393 val = make_unibyte_string (contents, nbytes);
2394 else
2395 val = make_multibyte_string (contents, nchars, nbytes);
2396 return val;
2397 }
2398
2399
2400 /* Make an unibyte string from LENGTH bytes at CONTENTS. */
2401
2402 Lisp_Object
2403 make_unibyte_string (const char *contents, EMACS_INT length)
2404 {
2405 register Lisp_Object val;
2406 val = make_uninit_string (length);
2407 memcpy (SDATA (val), contents, length);
2408 return val;
2409 }
2410
2411
2412 /* Make a multibyte string from NCHARS characters occupying NBYTES
2413 bytes at CONTENTS. */
2414
2415 Lisp_Object
2416 make_multibyte_string (const char *contents,
2417 EMACS_INT nchars, EMACS_INT nbytes)
2418 {
2419 register Lisp_Object val;
2420 val = make_uninit_multibyte_string (nchars, nbytes);
2421 memcpy (SDATA (val), contents, nbytes);
2422 return val;
2423 }
2424
2425
2426 /* Make a string from NCHARS characters occupying NBYTES bytes at
2427 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2428
2429 Lisp_Object
2430 make_string_from_bytes (const char *contents,
2431 EMACS_INT nchars, EMACS_INT nbytes)
2432 {
2433 register Lisp_Object val;
2434 val = make_uninit_multibyte_string (nchars, nbytes);
2435 memcpy (SDATA (val), contents, nbytes);
2436 if (SBYTES (val) == SCHARS (val))
2437 STRING_SET_UNIBYTE (val);
2438 return val;
2439 }
2440
2441
2442 /* Make a string from NCHARS characters occupying NBYTES bytes at
2443 CONTENTS. The argument MULTIBYTE controls whether to label the
2444 string as multibyte. If NCHARS is negative, it counts the number of
2445 characters by itself. */
2446
2447 Lisp_Object
2448 make_specified_string (const char *contents,
2449 EMACS_INT nchars, EMACS_INT nbytes, int multibyte)
2450 {
2451 register Lisp_Object val;
2452
2453 if (nchars < 0)
2454 {
2455 if (multibyte)
2456 nchars = multibyte_chars_in_text ((const unsigned char *) contents,
2457 nbytes);
2458 else
2459 nchars = nbytes;
2460 }
2461 val = make_uninit_multibyte_string (nchars, nbytes);
2462 memcpy (SDATA (val), contents, nbytes);
2463 if (!multibyte)
2464 STRING_SET_UNIBYTE (val);
2465 return val;
2466 }
2467
2468
2469 /* Make a string from the data at STR, treating it as multibyte if the
2470 data warrants. */
2471
2472 Lisp_Object
2473 build_string (const char *str)
2474 {
2475 return make_string (str, strlen (str));
2476 }
2477
2478
2479 /* Return an unibyte Lisp_String set up to hold LENGTH characters
2480 occupying LENGTH bytes. */
2481
2482 Lisp_Object
2483 make_uninit_string (EMACS_INT length)
2484 {
2485 Lisp_Object val;
2486
2487 if (!length)
2488 return empty_unibyte_string;
2489 val = make_uninit_multibyte_string (length, length);
2490 STRING_SET_UNIBYTE (val);
2491 return val;
2492 }
2493
2494
2495 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2496 which occupy NBYTES bytes. */
2497
2498 Lisp_Object
2499 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2500 {
2501 Lisp_Object string;
2502 struct Lisp_String *s;
2503
2504 if (nchars < 0)
2505 abort ();
2506 if (!nbytes)
2507 return empty_multibyte_string;
2508
2509 s = allocate_string ();
2510 allocate_string_data (s, nchars, nbytes);
2511 XSETSTRING (string, s);
2512 string_chars_consed += nbytes;
2513 return string;
2514 }
2515
2516
2517 \f
2518 /***********************************************************************
2519 Float Allocation
2520 ***********************************************************************/
2521
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. */
2526
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))
2532
2533 #define GETMARKBIT(block,n) \
2534 (((block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2535 >> ((n) % (sizeof(int) * CHAR_BIT))) \
2536 & 1)
2537
2538 #define SETMARKBIT(block,n) \
2539 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2540 |= 1 << ((n) % (sizeof(int) * CHAR_BIT))
2541
2542 #define UNSETMARKBIT(block,n) \
2543 (block)->gcmarkbits[(n) / (sizeof(int) * CHAR_BIT)] \
2544 &= ~(1 << ((n) % (sizeof(int) * CHAR_BIT)))
2545
2546 #define FLOAT_BLOCK(fptr) \
2547 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2548
2549 #define FLOAT_INDEX(fptr) \
2550 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2551
2552 struct float_block
2553 {
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;
2558 };
2559
2560 #define FLOAT_MARKED_P(fptr) \
2561 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2562
2563 #define FLOAT_MARK(fptr) \
2564 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2565
2566 #define FLOAT_UNMARK(fptr) \
2567 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2568
2569 /* Current float_block. */
2570
2571 static struct float_block *float_block;
2572
2573 /* Index of first unused Lisp_Float in the current float_block. */
2574
2575 static int float_block_index;
2576
2577 /* Free-list of Lisp_Floats. */
2578
2579 static struct Lisp_Float *float_free_list;
2580
2581
2582 /* Initialize float allocation. */
2583
2584 static void
2585 init_float (void)
2586 {
2587 float_block = NULL;
2588 float_block_index = FLOAT_BLOCK_SIZE; /* Force alloc of new float_block. */
2589 float_free_list = 0;
2590 }
2591
2592
2593 /* Return a new float object with value FLOAT_VALUE. */
2594
2595 Lisp_Object
2596 make_float (double float_value)
2597 {
2598 register Lisp_Object val;
2599
2600 /* eassert (!handling_signal); */
2601
2602 MALLOC_BLOCK_INPUT;
2603
2604 if (float_free_list)
2605 {
2606 /* We use the data field for chaining the free list
2607 so that we won't use the same field that has the mark bit. */
2608 XSETFLOAT (val, float_free_list);
2609 float_free_list = float_free_list->u.chain;
2610 }
2611 else
2612 {
2613 if (float_block_index == FLOAT_BLOCK_SIZE)
2614 {
2615 register struct float_block *new;
2616
2617 new = (struct float_block *) lisp_align_malloc (sizeof *new,
2618 MEM_TYPE_FLOAT);
2619 new->next = float_block;
2620 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2621 float_block = new;
2622 float_block_index = 0;
2623 }
2624 XSETFLOAT (val, &float_block->floats[float_block_index]);
2625 float_block_index++;
2626 }
2627
2628 MALLOC_UNBLOCK_INPUT;
2629
2630 XFLOAT_INIT (val, float_value);
2631 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2632 consing_since_gc += sizeof (struct Lisp_Float);
2633 floats_consed++;
2634 return val;
2635 }
2636
2637
2638 \f
2639 /***********************************************************************
2640 Cons Allocation
2641 ***********************************************************************/
2642
2643 /* We store cons cells inside of cons_blocks, allocating a new
2644 cons_block with malloc whenever necessary. Cons cells reclaimed by
2645 GC are put on a free list to be reallocated before allocating
2646 any new cons cells from the latest cons_block. */
2647
2648 #define CONS_BLOCK_SIZE \
2649 (((BLOCK_BYTES - sizeof (struct cons_block *)) * CHAR_BIT) \
2650 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2651
2652 #define CONS_BLOCK(fptr) \
2653 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2654
2655 #define CONS_INDEX(fptr) \
2656 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2657
2658 struct cons_block
2659 {
2660 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2661 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2662 int gcmarkbits[1 + CONS_BLOCK_SIZE / (sizeof(int) * CHAR_BIT)];
2663 struct cons_block *next;
2664 };
2665
2666 #define CONS_MARKED_P(fptr) \
2667 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2668
2669 #define CONS_MARK(fptr) \
2670 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2671
2672 #define CONS_UNMARK(fptr) \
2673 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2674
2675 /* Current cons_block. */
2676
2677 static struct cons_block *cons_block;
2678
2679 /* Index of first unused Lisp_Cons in the current block. */
2680
2681 static int cons_block_index;
2682
2683 /* Free-list of Lisp_Cons structures. */
2684
2685 static struct Lisp_Cons *cons_free_list;
2686
2687
2688 /* Initialize cons allocation. */
2689
2690 static void
2691 init_cons (void)
2692 {
2693 cons_block = NULL;
2694 cons_block_index = CONS_BLOCK_SIZE; /* Force alloc of new cons_block. */
2695 cons_free_list = 0;
2696 }
2697
2698
2699 /* Explicitly free a cons cell by putting it on the free-list. */
2700
2701 void
2702 free_cons (struct Lisp_Cons *ptr)
2703 {
2704 ptr->u.chain = cons_free_list;
2705 #if GC_MARK_STACK
2706 ptr->car = Vdead;
2707 #endif
2708 cons_free_list = ptr;
2709 }
2710
2711 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2712 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2713 (Lisp_Object car, Lisp_Object cdr)
2714 {
2715 register Lisp_Object val;
2716
2717 /* eassert (!handling_signal); */
2718
2719 MALLOC_BLOCK_INPUT;
2720
2721 if (cons_free_list)
2722 {
2723 /* We use the cdr for chaining the free list
2724 so that we won't use the same field that has the mark bit. */
2725 XSETCONS (val, cons_free_list);
2726 cons_free_list = cons_free_list->u.chain;
2727 }
2728 else
2729 {
2730 if (cons_block_index == CONS_BLOCK_SIZE)
2731 {
2732 register struct cons_block *new;
2733 new = (struct cons_block *) lisp_align_malloc (sizeof *new,
2734 MEM_TYPE_CONS);
2735 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2736 new->next = cons_block;
2737 cons_block = new;
2738 cons_block_index = 0;
2739 }
2740 XSETCONS (val, &cons_block->conses[cons_block_index]);
2741 cons_block_index++;
2742 }
2743
2744 MALLOC_UNBLOCK_INPUT;
2745
2746 XSETCAR (val, car);
2747 XSETCDR (val, cdr);
2748 eassert (!CONS_MARKED_P (XCONS (val)));
2749 consing_since_gc += sizeof (struct Lisp_Cons);
2750 cons_cells_consed++;
2751 return val;
2752 }
2753
2754 #ifdef GC_CHECK_CONS_LIST
2755 /* Get an error now if there's any junk in the cons free list. */
2756 void
2757 check_cons_list (void)
2758 {
2759 struct Lisp_Cons *tail = cons_free_list;
2760
2761 while (tail)
2762 tail = tail->u.chain;
2763 }
2764 #endif
2765
2766 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2767
2768 Lisp_Object
2769 list1 (Lisp_Object arg1)
2770 {
2771 return Fcons (arg1, Qnil);
2772 }
2773
2774 Lisp_Object
2775 list2 (Lisp_Object arg1, Lisp_Object arg2)
2776 {
2777 return Fcons (arg1, Fcons (arg2, Qnil));
2778 }
2779
2780
2781 Lisp_Object
2782 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2783 {
2784 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2785 }
2786
2787
2788 Lisp_Object
2789 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2790 {
2791 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2792 }
2793
2794
2795 Lisp_Object
2796 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2797 {
2798 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2799 Fcons (arg5, Qnil)))));
2800 }
2801
2802
2803 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2804 doc: /* Return a newly created list with specified arguments as elements.
2805 Any number of arguments, even zero arguments, are allowed.
2806 usage: (list &rest OBJECTS) */)
2807 (ptrdiff_t nargs, Lisp_Object *args)
2808 {
2809 register Lisp_Object val;
2810 val = Qnil;
2811
2812 while (nargs > 0)
2813 {
2814 nargs--;
2815 val = Fcons (args[nargs], val);
2816 }
2817 return val;
2818 }
2819
2820
2821 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2822 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2823 (register Lisp_Object length, Lisp_Object init)
2824 {
2825 register Lisp_Object val;
2826 register EMACS_INT size;
2827
2828 CHECK_NATNUM (length);
2829 size = XFASTINT (length);
2830
2831 val = Qnil;
2832 while (size > 0)
2833 {
2834 val = Fcons (init, val);
2835 --size;
2836
2837 if (size > 0)
2838 {
2839 val = Fcons (init, val);
2840 --size;
2841
2842 if (size > 0)
2843 {
2844 val = Fcons (init, val);
2845 --size;
2846
2847 if (size > 0)
2848 {
2849 val = Fcons (init, val);
2850 --size;
2851
2852 if (size > 0)
2853 {
2854 val = Fcons (init, val);
2855 --size;
2856 }
2857 }
2858 }
2859 }
2860
2861 QUIT;
2862 }
2863
2864 return val;
2865 }
2866
2867
2868 \f
2869 /***********************************************************************
2870 Vector Allocation
2871 ***********************************************************************/
2872
2873 /* Singly-linked list of all vectors. */
2874
2875 static struct Lisp_Vector *all_vectors;
2876
2877 /* Handy constants for vectorlike objects. */
2878 enum
2879 {
2880 header_size = offsetof (struct Lisp_Vector, contents),
2881 word_size = sizeof (Lisp_Object)
2882 };
2883
2884 /* Value is a pointer to a newly allocated Lisp_Vector structure
2885 with room for LEN Lisp_Objects. */
2886
2887 static struct Lisp_Vector *
2888 allocate_vectorlike (EMACS_INT len)
2889 {
2890 struct Lisp_Vector *p;
2891 size_t nbytes;
2892
2893 MALLOC_BLOCK_INPUT;
2894
2895 #ifdef DOUG_LEA_MALLOC
2896 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2897 because mapped region contents are not preserved in
2898 a dumped Emacs. */
2899 mallopt (M_MMAP_MAX, 0);
2900 #endif
2901
2902 /* This gets triggered by code which I haven't bothered to fix. --Stef */
2903 /* eassert (!handling_signal); */
2904
2905 nbytes = header_size + len * word_size;
2906 p = (struct Lisp_Vector *) lisp_malloc (nbytes, MEM_TYPE_VECTORLIKE);
2907
2908 #ifdef DOUG_LEA_MALLOC
2909 /* Back to a reasonable maximum of mmap'ed areas. */
2910 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
2911 #endif
2912
2913 consing_since_gc += nbytes;
2914 vector_cells_consed += len;
2915
2916 p->header.next.vector = all_vectors;
2917 all_vectors = p;
2918
2919 MALLOC_UNBLOCK_INPUT;
2920
2921 return p;
2922 }
2923
2924
2925 /* Allocate a vector with LEN slots. */
2926
2927 struct Lisp_Vector *
2928 allocate_vector (EMACS_INT len)
2929 {
2930 struct Lisp_Vector *v;
2931 ptrdiff_t nbytes_max = min (PTRDIFF_MAX, SIZE_MAX);
2932
2933 if (min ((nbytes_max - header_size) / word_size, MOST_POSITIVE_FIXNUM) < len)
2934 memory_full (SIZE_MAX);
2935 v = allocate_vectorlike (len);
2936 v->header.size = len;
2937 return v;
2938 }
2939
2940
2941 /* Allocate other vector-like structures. */
2942
2943 struct Lisp_Vector *
2944 allocate_pseudovector (int memlen, int lisplen, EMACS_INT tag)
2945 {
2946 struct Lisp_Vector *v = allocate_vectorlike (memlen);
2947 int i;
2948
2949 /* Only the first lisplen slots will be traced normally by the GC. */
2950 for (i = 0; i < lisplen; ++i)
2951 v->contents[i] = Qnil;
2952
2953 XSETPVECTYPESIZE (v, tag, lisplen);
2954 return v;
2955 }
2956
2957 struct Lisp_Hash_Table *
2958 allocate_hash_table (void)
2959 {
2960 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Hash_Table, count, PVEC_HASH_TABLE);
2961 }
2962
2963
2964 struct window *
2965 allocate_window (void)
2966 {
2967 return ALLOCATE_PSEUDOVECTOR(struct window, current_matrix, PVEC_WINDOW);
2968 }
2969
2970
2971 struct terminal *
2972 allocate_terminal (void)
2973 {
2974 struct terminal *t = ALLOCATE_PSEUDOVECTOR (struct terminal,
2975 next_terminal, PVEC_TERMINAL);
2976 /* Zero out the non-GC'd fields. FIXME: This should be made unnecessary. */
2977 memset (&t->next_terminal, 0,
2978 (char*) (t + 1) - (char*) &t->next_terminal);
2979
2980 return t;
2981 }
2982
2983 struct frame *
2984 allocate_frame (void)
2985 {
2986 struct frame *f = ALLOCATE_PSEUDOVECTOR (struct frame,
2987 face_cache, PVEC_FRAME);
2988 /* Zero out the non-GC'd fields. FIXME: This should be made unnecessary. */
2989 memset (&f->face_cache, 0,
2990 (char *) (f + 1) - (char *) &f->face_cache);
2991 return f;
2992 }
2993
2994
2995 struct Lisp_Process *
2996 allocate_process (void)
2997 {
2998 return ALLOCATE_PSEUDOVECTOR (struct Lisp_Process, pid, PVEC_PROCESS);
2999 }
3000
3001
3002 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
3003 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
3004 See also the function `vector'. */)
3005 (register Lisp_Object length, Lisp_Object init)
3006 {
3007 Lisp_Object vector;
3008 register EMACS_INT sizei;
3009 register EMACS_INT i;
3010 register struct Lisp_Vector *p;
3011
3012 CHECK_NATNUM (length);
3013 sizei = XFASTINT (length);
3014
3015 p = allocate_vector (sizei);
3016 for (i = 0; i < sizei; i++)
3017 p->contents[i] = init;
3018
3019 XSETVECTOR (vector, p);
3020 return vector;
3021 }
3022
3023
3024 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3025 doc: /* Return a newly created vector with specified arguments as elements.
3026 Any number of arguments, even zero arguments, are allowed.
3027 usage: (vector &rest OBJECTS) */)
3028 (ptrdiff_t nargs, Lisp_Object *args)
3029 {
3030 register Lisp_Object len, val;
3031 ptrdiff_t i;
3032 register struct Lisp_Vector *p;
3033
3034 XSETFASTINT (len, nargs);
3035 val = Fmake_vector (len, Qnil);
3036 p = XVECTOR (val);
3037 for (i = 0; i < nargs; i++)
3038 p->contents[i] = args[i];
3039 return val;
3040 }
3041
3042
3043 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3044 doc: /* Create a byte-code object with specified arguments as elements.
3045 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3046 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3047 and (optional) INTERACTIVE-SPEC.
3048 The first four arguments are required; at most six have any
3049 significance.
3050 The ARGLIST can be either like the one of `lambda', in which case the arguments
3051 will be dynamically bound before executing the byte code, or it can be an
3052 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3053 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3054 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3055 argument to catch the left-over arguments. If such an integer is used, the
3056 arguments will not be dynamically bound but will be instead pushed on the
3057 stack before executing the byte-code.
3058 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3059 (ptrdiff_t nargs, Lisp_Object *args)
3060 {
3061 register Lisp_Object len, val;
3062 ptrdiff_t i;
3063 register struct Lisp_Vector *p;
3064
3065 XSETFASTINT (len, nargs);
3066 if (!NILP (Vpurify_flag))
3067 val = make_pure_vector (nargs);
3068 else
3069 val = Fmake_vector (len, Qnil);
3070
3071 if (nargs > 1 && STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
3072 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3073 earlier because they produced a raw 8-bit string for byte-code
3074 and now such a byte-code string is loaded as multibyte while
3075 raw 8-bit characters converted to multibyte form. Thus, now we
3076 must convert them back to the original unibyte form. */
3077 args[1] = Fstring_as_unibyte (args[1]);
3078
3079 p = XVECTOR (val);
3080 for (i = 0; i < nargs; i++)
3081 {
3082 if (!NILP (Vpurify_flag))
3083 args[i] = Fpurecopy (args[i]);
3084 p->contents[i] = args[i];
3085 }
3086 XSETPVECTYPE (p, PVEC_COMPILED);
3087 XSETCOMPILED (val, p);
3088 return val;
3089 }
3090
3091
3092 \f
3093 /***********************************************************************
3094 Symbol Allocation
3095 ***********************************************************************/
3096
3097 /* Each symbol_block is just under 1020 bytes long, since malloc
3098 really allocates in units of powers of two and uses 4 bytes for its
3099 own overhead. */
3100
3101 #define SYMBOL_BLOCK_SIZE \
3102 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
3103
3104 struct symbol_block
3105 {
3106 /* Place `symbols' first, to preserve alignment. */
3107 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3108 struct symbol_block *next;
3109 };
3110
3111 /* Current symbol block and index of first unused Lisp_Symbol
3112 structure in it. */
3113
3114 static struct symbol_block *symbol_block;
3115 static int symbol_block_index;
3116
3117 /* List of free symbols. */
3118
3119 static struct Lisp_Symbol *symbol_free_list;
3120
3121
3122 /* Initialize symbol allocation. */
3123
3124 static void
3125 init_symbol (void)
3126 {
3127 symbol_block = NULL;
3128 symbol_block_index = SYMBOL_BLOCK_SIZE;
3129 symbol_free_list = 0;
3130 }
3131
3132
3133 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3134 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3135 Its value and function definition are void, and its property list is nil. */)
3136 (Lisp_Object name)
3137 {
3138 register Lisp_Object val;
3139 register struct Lisp_Symbol *p;
3140
3141 CHECK_STRING (name);
3142
3143 /* eassert (!handling_signal); */
3144
3145 MALLOC_BLOCK_INPUT;
3146
3147 if (symbol_free_list)
3148 {
3149 XSETSYMBOL (val, symbol_free_list);
3150 symbol_free_list = symbol_free_list->next;
3151 }
3152 else
3153 {
3154 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3155 {
3156 struct symbol_block *new;
3157 new = (struct symbol_block *) lisp_malloc (sizeof *new,
3158 MEM_TYPE_SYMBOL);
3159 new->next = symbol_block;
3160 symbol_block = new;
3161 symbol_block_index = 0;
3162 }
3163 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index]);
3164 symbol_block_index++;
3165 }
3166
3167 MALLOC_UNBLOCK_INPUT;
3168
3169 p = XSYMBOL (val);
3170 p->xname = name;
3171 p->plist = Qnil;
3172 p->redirect = SYMBOL_PLAINVAL;
3173 SET_SYMBOL_VAL (p, Qunbound);
3174 p->function = Qunbound;
3175 p->next = NULL;
3176 p->gcmarkbit = 0;
3177 p->interned = SYMBOL_UNINTERNED;
3178 p->constant = 0;
3179 p->declared_special = 0;
3180 consing_since_gc += sizeof (struct Lisp_Symbol);
3181 symbols_consed++;
3182 return val;
3183 }
3184
3185
3186 \f
3187 /***********************************************************************
3188 Marker (Misc) Allocation
3189 ***********************************************************************/
3190
3191 /* Allocation of markers and other objects that share that structure.
3192 Works like allocation of conses. */
3193
3194 #define MARKER_BLOCK_SIZE \
3195 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
3196
3197 struct marker_block
3198 {
3199 /* Place `markers' first, to preserve alignment. */
3200 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
3201 struct marker_block *next;
3202 };
3203
3204 static struct marker_block *marker_block;
3205 static int marker_block_index;
3206
3207 static union Lisp_Misc *marker_free_list;
3208
3209 static void
3210 init_marker (void)
3211 {
3212 marker_block = NULL;
3213 marker_block_index = MARKER_BLOCK_SIZE;
3214 marker_free_list = 0;
3215 }
3216
3217 /* Return a newly allocated Lisp_Misc object, with no substructure. */
3218
3219 Lisp_Object
3220 allocate_misc (void)
3221 {
3222 Lisp_Object val;
3223
3224 /* eassert (!handling_signal); */
3225
3226 MALLOC_BLOCK_INPUT;
3227
3228 if (marker_free_list)
3229 {
3230 XSETMISC (val, marker_free_list);
3231 marker_free_list = marker_free_list->u_free.chain;
3232 }
3233 else
3234 {
3235 if (marker_block_index == MARKER_BLOCK_SIZE)
3236 {
3237 struct marker_block *new;
3238 new = (struct marker_block *) lisp_malloc (sizeof *new,
3239 MEM_TYPE_MISC);
3240 new->next = marker_block;
3241 marker_block = new;
3242 marker_block_index = 0;
3243 total_free_markers += MARKER_BLOCK_SIZE;
3244 }
3245 XSETMISC (val, &marker_block->markers[marker_block_index]);
3246 marker_block_index++;
3247 }
3248
3249 MALLOC_UNBLOCK_INPUT;
3250
3251 --total_free_markers;
3252 consing_since_gc += sizeof (union Lisp_Misc);
3253 misc_objects_consed++;
3254 XMISCANY (val)->gcmarkbit = 0;
3255 return val;
3256 }
3257
3258 /* Free a Lisp_Misc object */
3259
3260 static void
3261 free_misc (Lisp_Object misc)
3262 {
3263 XMISCTYPE (misc) = Lisp_Misc_Free;
3264 XMISC (misc)->u_free.chain = marker_free_list;
3265 marker_free_list = XMISC (misc);
3266
3267 total_free_markers++;
3268 }
3269
3270 /* Return a Lisp_Misc_Save_Value object containing POINTER and
3271 INTEGER. This is used to package C values to call record_unwind_protect.
3272 The unwind function can get the C values back using XSAVE_VALUE. */
3273
3274 Lisp_Object
3275 make_save_value (void *pointer, ptrdiff_t integer)
3276 {
3277 register Lisp_Object val;
3278 register struct Lisp_Save_Value *p;
3279
3280 val = allocate_misc ();
3281 XMISCTYPE (val) = Lisp_Misc_Save_Value;
3282 p = XSAVE_VALUE (val);
3283 p->pointer = pointer;
3284 p->integer = integer;
3285 p->dogc = 0;
3286 return val;
3287 }
3288
3289 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3290 doc: /* Return a newly allocated marker which does not point at any place. */)
3291 (void)
3292 {
3293 register Lisp_Object val;
3294 register struct Lisp_Marker *p;
3295
3296 val = allocate_misc ();
3297 XMISCTYPE (val) = Lisp_Misc_Marker;
3298 p = XMARKER (val);
3299 p->buffer = 0;
3300 p->bytepos = 0;
3301 p->charpos = 0;
3302 p->next = NULL;
3303 p->insertion_type = 0;
3304 return val;
3305 }
3306
3307 /* Put MARKER back on the free list after using it temporarily. */
3308
3309 void
3310 free_marker (Lisp_Object marker)
3311 {
3312 unchain_marker (XMARKER (marker));
3313 free_misc (marker);
3314 }
3315
3316 \f
3317 /* Return a newly created vector or string with specified arguments as
3318 elements. If all the arguments are characters that can fit
3319 in a string of events, make a string; otherwise, make a vector.
3320
3321 Any number of arguments, even zero arguments, are allowed. */
3322
3323 Lisp_Object
3324 make_event_array (register int nargs, Lisp_Object *args)
3325 {
3326 int i;
3327
3328 for (i = 0; i < nargs; i++)
3329 /* The things that fit in a string
3330 are characters that are in 0...127,
3331 after discarding the meta bit and all the bits above it. */
3332 if (!INTEGERP (args[i])
3333 || (XINT (args[i]) & ~(-CHAR_META)) >= 0200)
3334 return Fvector (nargs, args);
3335
3336 /* Since the loop exited, we know that all the things in it are
3337 characters, so we can make a string. */
3338 {
3339 Lisp_Object result;
3340
3341 result = Fmake_string (make_number (nargs), make_number (0));
3342 for (i = 0; i < nargs; i++)
3343 {
3344 SSET (result, i, XINT (args[i]));
3345 /* Move the meta bit to the right place for a string char. */
3346 if (XINT (args[i]) & CHAR_META)
3347 SSET (result, i, SREF (result, i) | 0x80);
3348 }
3349
3350 return result;
3351 }
3352 }
3353
3354
3355 \f
3356 /************************************************************************
3357 Memory Full Handling
3358 ************************************************************************/
3359
3360
3361 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
3362 there may have been size_t overflow so that malloc was never
3363 called, or perhaps malloc was invoked successfully but the
3364 resulting pointer had problems fitting into a tagged EMACS_INT. In
3365 either case this counts as memory being full even though malloc did
3366 not fail. */
3367
3368 void
3369 memory_full (size_t nbytes)
3370 {
3371 /* Do not go into hysterics merely because a large request failed. */
3372 int enough_free_memory = 0;
3373 if (SPARE_MEMORY < nbytes)
3374 {
3375 void *p;
3376
3377 MALLOC_BLOCK_INPUT;
3378 p = malloc (SPARE_MEMORY);
3379 if (p)
3380 {
3381 free (p);
3382 enough_free_memory = 1;
3383 }
3384 MALLOC_UNBLOCK_INPUT;
3385 }
3386
3387 if (! enough_free_memory)
3388 {
3389 int i;
3390
3391 Vmemory_full = Qt;
3392
3393 memory_full_cons_threshold = sizeof (struct cons_block);
3394
3395 /* The first time we get here, free the spare memory. */
3396 for (i = 0; i < sizeof (spare_memory) / sizeof (char *); i++)
3397 if (spare_memory[i])
3398 {
3399 if (i == 0)
3400 free (spare_memory[i]);
3401 else if (i >= 1 && i <= 4)
3402 lisp_align_free (spare_memory[i]);
3403 else
3404 lisp_free (spare_memory[i]);
3405 spare_memory[i] = 0;
3406 }
3407
3408 /* Record the space now used. When it decreases substantially,
3409 we can refill the memory reserve. */
3410 #if !defined SYSTEM_MALLOC && !defined SYNC_INPUT
3411 bytes_used_when_full = BYTES_USED;
3412 #endif
3413 }
3414
3415 /* This used to call error, but if we've run out of memory, we could
3416 get infinite recursion trying to build the string. */
3417 xsignal (Qnil, Vmemory_signal_data);
3418 }
3419
3420 /* If we released our reserve (due to running out of memory),
3421 and we have a fair amount free once again,
3422 try to set aside another reserve in case we run out once more.
3423
3424 This is called when a relocatable block is freed in ralloc.c,
3425 and also directly from this file, in case we're not using ralloc.c. */
3426
3427 void
3428 refill_memory_reserve (void)
3429 {
3430 #ifndef SYSTEM_MALLOC
3431 if (spare_memory[0] == 0)
3432 spare_memory[0] = (char *) malloc (SPARE_MEMORY);
3433 if (spare_memory[1] == 0)
3434 spare_memory[1] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3435 MEM_TYPE_CONS);
3436 if (spare_memory[2] == 0)
3437 spare_memory[2] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3438 MEM_TYPE_CONS);
3439 if (spare_memory[3] == 0)
3440 spare_memory[3] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3441 MEM_TYPE_CONS);
3442 if (spare_memory[4] == 0)
3443 spare_memory[4] = (char *) lisp_align_malloc (sizeof (struct cons_block),
3444 MEM_TYPE_CONS);
3445 if (spare_memory[5] == 0)
3446 spare_memory[5] = (char *) lisp_malloc (sizeof (struct string_block),
3447 MEM_TYPE_STRING);
3448 if (spare_memory[6] == 0)
3449 spare_memory[6] = (char *) lisp_malloc (sizeof (struct string_block),
3450 MEM_TYPE_STRING);
3451 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
3452 Vmemory_full = Qnil;
3453 #endif
3454 }
3455 \f
3456 /************************************************************************
3457 C Stack Marking
3458 ************************************************************************/
3459
3460 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
3461
3462 /* Conservative C stack marking requires a method to identify possibly
3463 live Lisp objects given a pointer value. We do this by keeping
3464 track of blocks of Lisp data that are allocated in a red-black tree
3465 (see also the comment of mem_node which is the type of nodes in
3466 that tree). Function lisp_malloc adds information for an allocated
3467 block to the red-black tree with calls to mem_insert, and function
3468 lisp_free removes it with mem_delete. Functions live_string_p etc
3469 call mem_find to lookup information about a given pointer in the
3470 tree, and use that to determine if the pointer points to a Lisp
3471 object or not. */
3472
3473 /* Initialize this part of alloc.c. */
3474
3475 static void
3476 mem_init (void)
3477 {
3478 mem_z.left = mem_z.right = MEM_NIL;
3479 mem_z.parent = NULL;
3480 mem_z.color = MEM_BLACK;
3481 mem_z.start = mem_z.end = NULL;
3482 mem_root = MEM_NIL;
3483 }
3484
3485
3486 /* Value is a pointer to the mem_node containing START. Value is
3487 MEM_NIL if there is no node in the tree containing START. */
3488
3489 static inline struct mem_node *
3490 mem_find (void *start)
3491 {
3492 struct mem_node *p;
3493
3494 if (start < min_heap_address || start > max_heap_address)
3495 return MEM_NIL;
3496
3497 /* Make the search always successful to speed up the loop below. */
3498 mem_z.start = start;
3499 mem_z.end = (char *) start + 1;
3500
3501 p = mem_root;
3502 while (start < p->start || start >= p->end)
3503 p = start < p->start ? p->left : p->right;
3504 return p;
3505 }
3506
3507
3508 /* Insert a new node into the tree for a block of memory with start
3509 address START, end address END, and type TYPE. Value is a
3510 pointer to the node that was inserted. */
3511
3512 static struct mem_node *
3513 mem_insert (void *start, void *end, enum mem_type type)
3514 {
3515 struct mem_node *c, *parent, *x;
3516
3517 if (min_heap_address == NULL || start < min_heap_address)
3518 min_heap_address = start;
3519 if (max_heap_address == NULL || end > max_heap_address)
3520 max_heap_address = end;
3521
3522 /* See where in the tree a node for START belongs. In this
3523 particular application, it shouldn't happen that a node is already
3524 present. For debugging purposes, let's check that. */
3525 c = mem_root;
3526 parent = NULL;
3527
3528 #if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
3529
3530 while (c != MEM_NIL)
3531 {
3532 if (start >= c->start && start < c->end)
3533 abort ();
3534 parent = c;
3535 c = start < c->start ? c->left : c->right;
3536 }
3537
3538 #else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3539
3540 while (c != MEM_NIL)
3541 {
3542 parent = c;
3543 c = start < c->start ? c->left : c->right;
3544 }
3545
3546 #endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
3547
3548 /* Create a new node. */
3549 #ifdef GC_MALLOC_CHECK
3550 x = (struct mem_node *) _malloc_internal (sizeof *x);
3551 if (x == NULL)
3552 abort ();
3553 #else
3554 x = (struct mem_node *) xmalloc (sizeof *x);
3555 #endif
3556 x->start = start;
3557 x->end = end;
3558 x->type = type;
3559 x->parent = parent;
3560 x->left = x->right = MEM_NIL;
3561 x->color = MEM_RED;
3562
3563 /* Insert it as child of PARENT or install it as root. */
3564 if (parent)
3565 {
3566 if (start < parent->start)
3567 parent->left = x;
3568 else
3569 parent->right = x;
3570 }
3571 else
3572 mem_root = x;
3573
3574 /* Re-establish red-black tree properties. */
3575 mem_insert_fixup (x);
3576
3577 return x;
3578 }
3579
3580
3581 /* Re-establish the red-black properties of the tree, and thereby
3582 balance the tree, after node X has been inserted; X is always red. */
3583
3584 static void
3585 mem_insert_fixup (struct mem_node *x)
3586 {
3587 while (x != mem_root && x->parent->color == MEM_RED)
3588 {
3589 /* X is red and its parent is red. This is a violation of
3590 red-black tree property #3. */
3591
3592 if (x->parent == x->parent->parent->left)
3593 {
3594 /* We're on the left side of our grandparent, and Y is our
3595 "uncle". */
3596 struct mem_node *y = x->parent->parent->right;
3597
3598 if (y->color == MEM_RED)
3599 {
3600 /* Uncle and parent are red but should be black because
3601 X is red. Change the colors accordingly and proceed
3602 with the grandparent. */
3603 x->parent->color = MEM_BLACK;
3604 y->color = MEM_BLACK;
3605 x->parent->parent->color = MEM_RED;
3606 x = x->parent->parent;
3607 }
3608 else
3609 {
3610 /* Parent and uncle have different colors; parent is
3611 red, uncle is black. */
3612 if (x == x->parent->right)
3613 {
3614 x = x->parent;
3615 mem_rotate_left (x);
3616 }
3617
3618 x->parent->color = MEM_BLACK;
3619 x->parent->parent->color = MEM_RED;
3620 mem_rotate_right (x->parent->parent);
3621 }
3622 }
3623 else
3624 {
3625 /* This is the symmetrical case of above. */
3626 struct mem_node *y = x->parent->parent->left;
3627
3628 if (y->color == MEM_RED)
3629 {
3630 x->parent->color = MEM_BLACK;
3631 y->color = MEM_BLACK;
3632 x->parent->parent->color = MEM_RED;
3633 x = x->parent->parent;
3634 }
3635 else
3636 {
3637 if (x == x->parent->left)
3638 {
3639 x = x->parent;
3640 mem_rotate_right (x);
3641 }
3642
3643 x->parent->color = MEM_BLACK;
3644 x->parent->parent->color = MEM_RED;
3645 mem_rotate_left (x->parent->parent);
3646 }
3647 }
3648 }
3649
3650 /* The root may have been changed to red due to the algorithm. Set
3651 it to black so that property #5 is satisfied. */
3652 mem_root->color = MEM_BLACK;
3653 }
3654
3655
3656 /* (x) (y)
3657 / \ / \
3658 a (y) ===> (x) c
3659 / \ / \
3660 b c a b */
3661
3662 static void
3663 mem_rotate_left (struct mem_node *x)
3664 {
3665 struct mem_node *y;
3666
3667 /* Turn y's left sub-tree into x's right sub-tree. */
3668 y = x->right;
3669 x->right = y->left;
3670 if (y->left != MEM_NIL)
3671 y->left->parent = x;
3672
3673 /* Y's parent was x's parent. */
3674 if (y != MEM_NIL)
3675 y->parent = x->parent;
3676
3677 /* Get the parent to point to y instead of x. */
3678 if (x->parent)
3679 {
3680 if (x == x->parent->left)
3681 x->parent->left = y;
3682 else
3683 x->parent->right = y;
3684 }
3685 else
3686 mem_root = y;
3687
3688 /* Put x on y's left. */
3689 y->left = x;
3690 if (x != MEM_NIL)
3691 x->parent = y;
3692 }
3693
3694
3695 /* (x) (Y)
3696 / \ / \
3697 (y) c ===> a (x)
3698 / \ / \
3699 a b b c */
3700
3701 static void
3702 mem_rotate_right (struct mem_node *x)
3703 {
3704 struct mem_node *y = x->left;
3705
3706 x->left = y->right;
3707 if (y->right != MEM_NIL)
3708 y->right->parent = x;
3709
3710 if (y != MEM_NIL)
3711 y->parent = x->parent;
3712 if (x->parent)
3713 {
3714 if (x == x->parent->right)
3715 x->parent->right = y;
3716 else
3717 x->parent->left = y;
3718 }
3719 else
3720 mem_root = y;
3721
3722 y->right = x;
3723 if (x != MEM_NIL)
3724 x->parent = y;
3725 }
3726
3727
3728 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
3729
3730 static void
3731 mem_delete (struct mem_node *z)
3732 {
3733 struct mem_node *x, *y;
3734
3735 if (!z || z == MEM_NIL)
3736 return;
3737
3738 if (z->left == MEM_NIL || z->right == MEM_NIL)
3739 y = z;
3740 else
3741 {
3742 y = z->right;
3743 while (y->left != MEM_NIL)
3744 y = y->left;
3745 }
3746
3747 if (y->left != MEM_NIL)
3748 x = y->left;
3749 else
3750 x = y->right;
3751
3752 x->parent = y->parent;
3753 if (y->parent)
3754 {
3755 if (y == y->parent->left)
3756 y->parent->left = x;
3757 else
3758 y->parent->right = x;
3759 }
3760 else
3761 mem_root = x;
3762
3763 if (y != z)
3764 {
3765 z->start = y->start;
3766 z->end = y->end;
3767 z->type = y->type;
3768 }
3769
3770 if (y->color == MEM_BLACK)
3771 mem_delete_fixup (x);
3772
3773 #ifdef GC_MALLOC_CHECK
3774 _free_internal (y);
3775 #else
3776 xfree (y);
3777 #endif
3778 }
3779
3780
3781 /* Re-establish the red-black properties of the tree, after a
3782 deletion. */
3783
3784 static void
3785 mem_delete_fixup (struct mem_node *x)
3786 {
3787 while (x != mem_root && x->color == MEM_BLACK)
3788 {
3789 if (x == x->parent->left)
3790 {
3791 struct mem_node *w = x->parent->right;
3792
3793 if (w->color == MEM_RED)
3794 {
3795 w->color = MEM_BLACK;
3796 x->parent->color = MEM_RED;
3797 mem_rotate_left (x->parent);
3798 w = x->parent->right;
3799 }
3800
3801 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
3802 {
3803 w->color = MEM_RED;
3804 x = x->parent;
3805 }
3806 else
3807 {
3808 if (w->right->color == MEM_BLACK)
3809 {
3810 w->left->color = MEM_BLACK;
3811 w->color = MEM_RED;
3812 mem_rotate_right (w);
3813 w = x->parent->right;
3814 }
3815 w->color = x->parent->color;
3816 x->parent->color = MEM_BLACK;
3817 w->right->color = MEM_BLACK;
3818 mem_rotate_left (x->parent);
3819 x = mem_root;
3820 }
3821 }
3822 else
3823 {
3824 struct mem_node *w = x->parent->left;
3825
3826 if (w->color == MEM_RED)
3827 {
3828 w->color = MEM_BLACK;
3829 x->parent->color = MEM_RED;
3830 mem_rotate_right (x->parent);
3831 w = x->parent->left;
3832 }
3833
3834 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
3835 {
3836 w->color = MEM_RED;
3837 x = x->parent;
3838 }
3839 else
3840 {
3841 if (w->left->color == MEM_BLACK)
3842 {
3843 w->right->color = MEM_BLACK;
3844 w->color = MEM_RED;
3845 mem_rotate_left (w);
3846 w = x->parent->left;
3847 }
3848
3849 w->color = x->parent->color;
3850 x->parent->color = MEM_BLACK;
3851 w->left->color = MEM_BLACK;
3852 mem_rotate_right (x->parent);
3853 x = mem_root;
3854 }
3855 }
3856 }
3857
3858 x->color = MEM_BLACK;
3859 }
3860
3861
3862 /* Value is non-zero if P is a pointer to a live Lisp string on
3863 the heap. M is a pointer to the mem_block for P. */
3864
3865 static inline int
3866 live_string_p (struct mem_node *m, void *p)
3867 {
3868 if (m->type == MEM_TYPE_STRING)
3869 {
3870 struct string_block *b = (struct string_block *) m->start;
3871 ptrdiff_t offset = (char *) p - (char *) &b->strings[0];
3872
3873 /* P must point to the start of a Lisp_String structure, and it
3874 must not be on the free-list. */
3875 return (offset >= 0
3876 && offset % sizeof b->strings[0] == 0
3877 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
3878 && ((struct Lisp_String *) p)->data != NULL);
3879 }
3880 else
3881 return 0;
3882 }
3883
3884
3885 /* Value is non-zero if P is a pointer to a live Lisp cons on
3886 the heap. M is a pointer to the mem_block for P. */
3887
3888 static inline int
3889 live_cons_p (struct mem_node *m, void *p)
3890 {
3891 if (m->type == MEM_TYPE_CONS)
3892 {
3893 struct cons_block *b = (struct cons_block *) m->start;
3894 ptrdiff_t offset = (char *) p - (char *) &b->conses[0];
3895
3896 /* P must point to the start of a Lisp_Cons, not be
3897 one of the unused cells in the current cons block,
3898 and not be on the free-list. */
3899 return (offset >= 0
3900 && offset % sizeof b->conses[0] == 0
3901 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
3902 && (b != cons_block
3903 || offset / sizeof b->conses[0] < cons_block_index)
3904 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
3905 }
3906 else
3907 return 0;
3908 }
3909
3910
3911 /* Value is non-zero if P is a pointer to a live Lisp symbol on
3912 the heap. M is a pointer to the mem_block for P. */
3913
3914 static inline int
3915 live_symbol_p (struct mem_node *m, void *p)
3916 {
3917 if (m->type == MEM_TYPE_SYMBOL)
3918 {
3919 struct symbol_block *b = (struct symbol_block *) m->start;
3920 ptrdiff_t offset = (char *) p - (char *) &b->symbols[0];
3921
3922 /* P must point to the start of a Lisp_Symbol, not be
3923 one of the unused cells in the current symbol block,
3924 and not be on the free-list. */
3925 return (offset >= 0
3926 && offset % sizeof b->symbols[0] == 0
3927 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
3928 && (b != symbol_block
3929 || offset / sizeof b->symbols[0] < symbol_block_index)
3930 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
3931 }
3932 else
3933 return 0;
3934 }
3935
3936
3937 /* Value is non-zero if P is a pointer to a live Lisp float on
3938 the heap. M is a pointer to the mem_block for P. */
3939
3940 static inline int
3941 live_float_p (struct mem_node *m, void *p)
3942 {
3943 if (m->type == MEM_TYPE_FLOAT)
3944 {
3945 struct float_block *b = (struct float_block *) m->start;
3946 ptrdiff_t offset = (char *) p - (char *) &b->floats[0];
3947
3948 /* P must point to the start of a Lisp_Float and not be
3949 one of the unused cells in the current float block. */
3950 return (offset >= 0
3951 && offset % sizeof b->floats[0] == 0
3952 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
3953 && (b != float_block
3954 || offset / sizeof b->floats[0] < float_block_index));
3955 }
3956 else
3957 return 0;
3958 }
3959
3960
3961 /* Value is non-zero if P is a pointer to a live Lisp Misc on
3962 the heap. M is a pointer to the mem_block for P. */
3963
3964 static inline int
3965 live_misc_p (struct mem_node *m, void *p)
3966 {
3967 if (m->type == MEM_TYPE_MISC)
3968 {
3969 struct marker_block *b = (struct marker_block *) m->start;
3970 ptrdiff_t offset = (char *) p - (char *) &b->markers[0];
3971
3972 /* P must point to the start of a Lisp_Misc, not be
3973 one of the unused cells in the current misc block,
3974 and not be on the free-list. */
3975 return (offset >= 0
3976 && offset % sizeof b->markers[0] == 0
3977 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
3978 && (b != marker_block
3979 || offset / sizeof b->markers[0] < marker_block_index)
3980 && ((union Lisp_Misc *) p)->u_any.type != Lisp_Misc_Free);
3981 }
3982 else
3983 return 0;
3984 }
3985
3986
3987 /* Value is non-zero if P is a pointer to a live vector-like object.
3988 M is a pointer to the mem_block for P. */
3989
3990 static inline int
3991 live_vector_p (struct mem_node *m, void *p)
3992 {
3993 return (p == m->start && m->type == MEM_TYPE_VECTORLIKE);
3994 }
3995
3996
3997 /* Value is non-zero if P is a pointer to a live buffer. M is a
3998 pointer to the mem_block for P. */
3999
4000 static inline int
4001 live_buffer_p (struct mem_node *m, void *p)
4002 {
4003 /* P must point to the start of the block, and the buffer
4004 must not have been killed. */
4005 return (m->type == MEM_TYPE_BUFFER
4006 && p == m->start
4007 && !NILP (((struct buffer *) p)->BUFFER_INTERNAL_FIELD (name)));
4008 }
4009
4010 #endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
4011
4012 #if GC_MARK_STACK
4013
4014 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4015
4016 /* Array of objects that are kept alive because the C stack contains
4017 a pattern that looks like a reference to them . */
4018
4019 #define MAX_ZOMBIES 10
4020 static Lisp_Object zombies[MAX_ZOMBIES];
4021
4022 /* Number of zombie objects. */
4023
4024 static EMACS_INT nzombies;
4025
4026 /* Number of garbage collections. */
4027
4028 static EMACS_INT ngcs;
4029
4030 /* Average percentage of zombies per collection. */
4031
4032 static double avg_zombies;
4033
4034 /* Max. number of live and zombie objects. */
4035
4036 static EMACS_INT max_live, max_zombies;
4037
4038 /* Average number of live objects per GC. */
4039
4040 static double avg_live;
4041
4042 DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
4043 doc: /* Show information about live and zombie objects. */)
4044 (void)
4045 {
4046 Lisp_Object args[8], zombie_list = Qnil;
4047 EMACS_INT i;
4048 for (i = 0; i < nzombies; i++)
4049 zombie_list = Fcons (zombies[i], zombie_list);
4050 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d\nzombies: %S");
4051 args[1] = make_number (ngcs);
4052 args[2] = make_float (avg_live);
4053 args[3] = make_float (avg_zombies);
4054 args[4] = make_float (avg_zombies / avg_live / 100);
4055 args[5] = make_number (max_live);
4056 args[6] = make_number (max_zombies);
4057 args[7] = zombie_list;
4058 return Fmessage (8, args);
4059 }
4060
4061 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4062
4063
4064 /* Mark OBJ if we can prove it's a Lisp_Object. */
4065
4066 static inline void
4067 mark_maybe_object (Lisp_Object obj)
4068 {
4069 void *po;
4070 struct mem_node *m;
4071
4072 if (INTEGERP (obj))
4073 return;
4074
4075 po = (void *) XPNTR (obj);
4076 m = mem_find (po);
4077
4078 if (m != MEM_NIL)
4079 {
4080 int mark_p = 0;
4081
4082 switch (XTYPE (obj))
4083 {
4084 case Lisp_String:
4085 mark_p = (live_string_p (m, po)
4086 && !STRING_MARKED_P ((struct Lisp_String *) po));
4087 break;
4088
4089 case Lisp_Cons:
4090 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4091 break;
4092
4093 case Lisp_Symbol:
4094 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4095 break;
4096
4097 case Lisp_Float:
4098 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4099 break;
4100
4101 case Lisp_Vectorlike:
4102 /* Note: can't check BUFFERP before we know it's a
4103 buffer because checking that dereferences the pointer
4104 PO which might point anywhere. */
4105 if (live_vector_p (m, po))
4106 mark_p = !SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4107 else if (live_buffer_p (m, po))
4108 mark_p = BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4109 break;
4110
4111 case Lisp_Misc:
4112 mark_p = (live_misc_p (m, po) && !XMISCANY (obj)->gcmarkbit);
4113 break;
4114
4115 default:
4116 break;
4117 }
4118
4119 if (mark_p)
4120 {
4121 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4122 if (nzombies < MAX_ZOMBIES)
4123 zombies[nzombies] = obj;
4124 ++nzombies;
4125 #endif
4126 mark_object (obj);
4127 }
4128 }
4129 }
4130
4131
4132 /* If P points to Lisp data, mark that as live if it isn't already
4133 marked. */
4134
4135 static inline void
4136 mark_maybe_pointer (void *p)
4137 {
4138 struct mem_node *m;
4139
4140 /* Quickly rule out some values which can't point to Lisp data. */
4141 if ((intptr_t) p %
4142 #ifdef USE_LSB_TAG
4143 8 /* USE_LSB_TAG needs Lisp data to be aligned on multiples of 8. */
4144 #else
4145 2 /* We assume that Lisp data is aligned on even addresses. */
4146 #endif
4147 )
4148 return;
4149
4150 m = mem_find (p);
4151 if (m != MEM_NIL)
4152 {
4153 Lisp_Object obj = Qnil;
4154
4155 switch (m->type)
4156 {
4157 case MEM_TYPE_NON_LISP:
4158 /* Nothing to do; not a pointer to Lisp memory. */
4159 break;
4160
4161 case MEM_TYPE_BUFFER:
4162 if (live_buffer_p (m, p) && !VECTOR_MARKED_P((struct buffer *)p))
4163 XSETVECTOR (obj, p);
4164 break;
4165
4166 case MEM_TYPE_CONS:
4167 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4168 XSETCONS (obj, p);
4169 break;
4170
4171 case MEM_TYPE_STRING:
4172 if (live_string_p (m, p)
4173 && !STRING_MARKED_P ((struct Lisp_String *) p))
4174 XSETSTRING (obj, p);
4175 break;
4176
4177 case MEM_TYPE_MISC:
4178 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4179 XSETMISC (obj, p);
4180 break;
4181
4182 case MEM_TYPE_SYMBOL:
4183 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4184 XSETSYMBOL (obj, p);
4185 break;
4186
4187 case MEM_TYPE_FLOAT:
4188 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4189 XSETFLOAT (obj, p);
4190 break;
4191
4192 case MEM_TYPE_VECTORLIKE:
4193 if (live_vector_p (m, p))
4194 {
4195 Lisp_Object tem;
4196 XSETVECTOR (tem, p);
4197 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4198 obj = tem;
4199 }
4200 break;
4201
4202 default:
4203 abort ();
4204 }
4205
4206 if (!NILP (obj))
4207 mark_object (obj);
4208 }
4209 }
4210
4211
4212 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4213 or END+OFFSET..START. */
4214
4215 static void
4216 mark_memory (void *start, void *end, int offset)
4217 {
4218 Lisp_Object *p;
4219 void **pp;
4220
4221 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4222 nzombies = 0;
4223 #endif
4224
4225 /* Make START the pointer to the start of the memory region,
4226 if it isn't already. */
4227 if (end < start)
4228 {
4229 void *tem = start;
4230 start = end;
4231 end = tem;
4232 }
4233
4234 /* Mark Lisp_Objects. */
4235 for (p = (Lisp_Object *) ((char *) start + offset); (void *) p < end; ++p)
4236 mark_maybe_object (*p);
4237
4238 /* Mark Lisp data pointed to. This is necessary because, in some
4239 situations, the C compiler optimizes Lisp objects away, so that
4240 only a pointer to them remains. Example:
4241
4242 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4243 ()
4244 {
4245 Lisp_Object obj = build_string ("test");
4246 struct Lisp_String *s = XSTRING (obj);
4247 Fgarbage_collect ();
4248 fprintf (stderr, "test `%s'\n", s->data);
4249 return Qnil;
4250 }
4251
4252 Here, `obj' isn't really used, and the compiler optimizes it
4253 away. The only reference to the life string is through the
4254 pointer `s'. */
4255
4256 for (pp = (void **) ((char *) start + offset); (void *) pp < end; ++pp)
4257 mark_maybe_pointer (*pp);
4258 }
4259
4260 /* setjmp will work with GCC unless NON_SAVING_SETJMP is defined in
4261 the GCC system configuration. In gcc 3.2, the only systems for
4262 which this is so are i386-sco5 non-ELF, i386-sysv3 (maybe included
4263 by others?) and ns32k-pc532-min. */
4264
4265 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4266
4267 static int setjmp_tested_p, longjmps_done;
4268
4269 #define SETJMP_WILL_LIKELY_WORK "\
4270 \n\
4271 Emacs garbage collector has been changed to use conservative stack\n\
4272 marking. Emacs has determined that the method it uses to do the\n\
4273 marking will likely work on your system, but this isn't sure.\n\
4274 \n\
4275 If you are a system-programmer, or can get the help of a local wizard\n\
4276 who is, please take a look at the function mark_stack in alloc.c, and\n\
4277 verify that the methods used are appropriate for your system.\n\
4278 \n\
4279 Please mail the result to <emacs-devel@gnu.org>.\n\
4280 "
4281
4282 #define SETJMP_WILL_NOT_WORK "\
4283 \n\
4284 Emacs garbage collector has been changed to use conservative stack\n\
4285 marking. Emacs has determined that the default method it uses to do the\n\
4286 marking will not work on your system. We will need a system-dependent\n\
4287 solution for your system.\n\
4288 \n\
4289 Please take a look at the function mark_stack in alloc.c, and\n\
4290 try to find a way to make it work on your system.\n\
4291 \n\
4292 Note that you may get false negatives, depending on the compiler.\n\
4293 In particular, you need to use -O with GCC for this test.\n\
4294 \n\
4295 Please mail the result to <emacs-devel@gnu.org>.\n\
4296 "
4297
4298
4299 /* Perform a quick check if it looks like setjmp saves registers in a
4300 jmp_buf. Print a message to stderr saying so. When this test
4301 succeeds, this is _not_ a proof that setjmp is sufficient for
4302 conservative stack marking. Only the sources or a disassembly
4303 can prove that. */
4304
4305 static void
4306 test_setjmp (void)
4307 {
4308 char buf[10];
4309 register int x;
4310 jmp_buf jbuf;
4311 int result = 0;
4312
4313 /* Arrange for X to be put in a register. */
4314 sprintf (buf, "1");
4315 x = strlen (buf);
4316 x = 2 * x - 1;
4317
4318 setjmp (jbuf);
4319 if (longjmps_done == 1)
4320 {
4321 /* Came here after the longjmp at the end of the function.
4322
4323 If x == 1, the longjmp has restored the register to its
4324 value before the setjmp, and we can hope that setjmp
4325 saves all such registers in the jmp_buf, although that
4326 isn't sure.
4327
4328 For other values of X, either something really strange is
4329 taking place, or the setjmp just didn't save the register. */
4330
4331 if (x == 1)
4332 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4333 else
4334 {
4335 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4336 exit (1);
4337 }
4338 }
4339
4340 ++longjmps_done;
4341 x = 2;
4342 if (longjmps_done == 1)
4343 longjmp (jbuf, 1);
4344 }
4345
4346 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4347
4348
4349 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4350
4351 /* Abort if anything GCPRO'd doesn't survive the GC. */
4352
4353 static void
4354 check_gcpros (void)
4355 {
4356 struct gcpro *p;
4357 ptrdiff_t i;
4358
4359 for (p = gcprolist; p; p = p->next)
4360 for (i = 0; i < p->nvars; ++i)
4361 if (!survives_gc_p (p->var[i]))
4362 /* FIXME: It's not necessarily a bug. It might just be that the
4363 GCPRO is unnecessary or should release the object sooner. */
4364 abort ();
4365 }
4366
4367 #elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
4368
4369 static void
4370 dump_zombies (void)
4371 {
4372 int i;
4373
4374 fprintf (stderr, "\nZombies kept alive = %"pI":\n", nzombies);
4375 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
4376 {
4377 fprintf (stderr, " %d = ", i);
4378 debug_print (zombies[i]);
4379 }
4380 }
4381
4382 #endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
4383
4384
4385 /* Mark live Lisp objects on the C stack.
4386
4387 There are several system-dependent problems to consider when
4388 porting this to new architectures:
4389
4390 Processor Registers
4391
4392 We have to mark Lisp objects in CPU registers that can hold local
4393 variables or are used to pass parameters.
4394
4395 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4396 something that either saves relevant registers on the stack, or
4397 calls mark_maybe_object passing it each register's contents.
4398
4399 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4400 implementation assumes that calling setjmp saves registers we need
4401 to see in a jmp_buf which itself lies on the stack. This doesn't
4402 have to be true! It must be verified for each system, possibly
4403 by taking a look at the source code of setjmp.
4404
4405 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4406 can use it as a machine independent method to store all registers
4407 to the stack. In this case the macros described in the previous
4408 two paragraphs are not used.
4409
4410 Stack Layout
4411
4412 Architectures differ in the way their processor stack is organized.
4413 For example, the stack might look like this
4414
4415 +----------------+
4416 | Lisp_Object | size = 4
4417 +----------------+
4418 | something else | size = 2
4419 +----------------+
4420 | Lisp_Object | size = 4
4421 +----------------+
4422 | ... |
4423
4424 In such a case, not every Lisp_Object will be aligned equally. To
4425 find all Lisp_Object on the stack it won't be sufficient to walk
4426 the stack in steps of 4 bytes. Instead, two passes will be
4427 necessary, one starting at the start of the stack, and a second
4428 pass starting at the start of the stack + 2. Likewise, if the
4429 minimal alignment of Lisp_Objects on the stack is 1, four passes
4430 would be necessary, each one starting with one byte more offset
4431 from the stack start.
4432
4433 The current code assumes by default that Lisp_Objects are aligned
4434 equally on the stack. */
4435
4436 static void
4437 mark_stack (void)
4438 {
4439 int i;
4440 void *end;
4441
4442 #ifdef HAVE___BUILTIN_UNWIND_INIT
4443 /* Force callee-saved registers and register windows onto the stack.
4444 This is the preferred method if available, obviating the need for
4445 machine dependent methods. */
4446 __builtin_unwind_init ();
4447 end = &end;
4448 #else /* not HAVE___BUILTIN_UNWIND_INIT */
4449 #ifndef GC_SAVE_REGISTERS_ON_STACK
4450 /* jmp_buf may not be aligned enough on darwin-ppc64 */
4451 union aligned_jmpbuf {
4452 Lisp_Object o;
4453 jmp_buf j;
4454 } j;
4455 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
4456 #endif
4457 /* This trick flushes the register windows so that all the state of
4458 the process is contained in the stack. */
4459 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
4460 needed on ia64 too. See mach_dep.c, where it also says inline
4461 assembler doesn't work with relevant proprietary compilers. */
4462 #ifdef __sparc__
4463 #if defined (__sparc64__) && defined (__FreeBSD__)
4464 /* FreeBSD does not have a ta 3 handler. */
4465 asm ("flushw");
4466 #else
4467 asm ("ta 3");
4468 #endif
4469 #endif
4470
4471 /* Save registers that we need to see on the stack. We need to see
4472 registers used to hold register variables and registers used to
4473 pass parameters. */
4474 #ifdef GC_SAVE_REGISTERS_ON_STACK
4475 GC_SAVE_REGISTERS_ON_STACK (end);
4476 #else /* not GC_SAVE_REGISTERS_ON_STACK */
4477
4478 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
4479 setjmp will definitely work, test it
4480 and print a message with the result
4481 of the test. */
4482 if (!setjmp_tested_p)
4483 {
4484 setjmp_tested_p = 1;
4485 test_setjmp ();
4486 }
4487 #endif /* GC_SETJMP_WORKS */
4488
4489 setjmp (j.j);
4490 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
4491 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
4492 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
4493
4494 /* This assumes that the stack is a contiguous region in memory. If
4495 that's not the case, something has to be done here to iterate
4496 over the stack segments. */
4497 #ifndef GC_LISP_OBJECT_ALIGNMENT
4498 #ifdef __GNUC__
4499 #define GC_LISP_OBJECT_ALIGNMENT __alignof__ (Lisp_Object)
4500 #else
4501 #define GC_LISP_OBJECT_ALIGNMENT sizeof (Lisp_Object)
4502 #endif
4503 #endif
4504 for (i = 0; i < sizeof (Lisp_Object); i += GC_LISP_OBJECT_ALIGNMENT)
4505 mark_memory (stack_base, end, i);
4506 /* Allow for marking a secondary stack, like the register stack on the
4507 ia64. */
4508 #ifdef GC_MARK_SECONDARY_STACK
4509 GC_MARK_SECONDARY_STACK ();
4510 #endif
4511
4512 #if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
4513 check_gcpros ();
4514 #endif
4515 }
4516
4517 #endif /* GC_MARK_STACK != 0 */
4518
4519
4520 /* Determine whether it is safe to access memory at address P. */
4521 static int
4522 valid_pointer_p (void *p)
4523 {
4524 #ifdef WINDOWSNT
4525 return w32_valid_pointer_p (p, 16);
4526 #else
4527 int fd[2];
4528
4529 /* Obviously, we cannot just access it (we would SEGV trying), so we
4530 trick the o/s to tell us whether p is a valid pointer.
4531 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4532 not validate p in that case. */
4533
4534 if (pipe (fd) == 0)
4535 {
4536 int valid = (emacs_write (fd[1], (char *) p, 16) == 16);
4537 emacs_close (fd[1]);
4538 emacs_close (fd[0]);
4539 return valid;
4540 }
4541
4542 return -1;
4543 #endif
4544 }
4545
4546 /* Return 1 if OBJ is a valid lisp object.
4547 Return 0 if OBJ is NOT a valid lisp object.
4548 Return -1 if we cannot validate OBJ.
4549 This function can be quite slow,
4550 so it should only be used in code for manual debugging. */
4551
4552 int
4553 valid_lisp_object_p (Lisp_Object obj)
4554 {
4555 void *p;
4556 #if GC_MARK_STACK
4557 struct mem_node *m;
4558 #endif
4559
4560 if (INTEGERP (obj))
4561 return 1;
4562
4563 p = (void *) XPNTR (obj);
4564 if (PURE_POINTER_P (p))
4565 return 1;
4566
4567 #if !GC_MARK_STACK
4568 return valid_pointer_p (p);
4569 #else
4570
4571 m = mem_find (p);
4572
4573 if (m == MEM_NIL)
4574 {
4575 int valid = valid_pointer_p (p);
4576 if (valid <= 0)
4577 return valid;
4578
4579 if (SUBRP (obj))
4580 return 1;
4581
4582 return 0;
4583 }
4584
4585 switch (m->type)
4586 {
4587 case MEM_TYPE_NON_LISP:
4588 return 0;
4589
4590 case MEM_TYPE_BUFFER:
4591 return live_buffer_p (m, p);
4592
4593 case MEM_TYPE_CONS:
4594 return live_cons_p (m, p);
4595
4596 case MEM_TYPE_STRING:
4597 return live_string_p (m, p);
4598
4599 case MEM_TYPE_MISC:
4600 return live_misc_p (m, p);
4601
4602 case MEM_TYPE_SYMBOL:
4603 return live_symbol_p (m, p);
4604
4605 case MEM_TYPE_FLOAT:
4606 return live_float_p (m, p);
4607
4608 case MEM_TYPE_VECTORLIKE:
4609 return live_vector_p (m, p);
4610
4611 default:
4612 break;
4613 }
4614
4615 return 0;
4616 #endif
4617 }
4618
4619
4620
4621 \f
4622 /***********************************************************************
4623 Pure Storage Management
4624 ***********************************************************************/
4625
4626 /* Allocate room for SIZE bytes from pure Lisp storage and return a
4627 pointer to it. TYPE is the Lisp type for which the memory is
4628 allocated. TYPE < 0 means it's not used for a Lisp object. */
4629
4630 static POINTER_TYPE *
4631 pure_alloc (size_t size, int type)
4632 {
4633 POINTER_TYPE *result;
4634 #ifdef USE_LSB_TAG
4635 size_t alignment = (1 << GCTYPEBITS);
4636 #else
4637 size_t alignment = sizeof (EMACS_INT);
4638
4639 /* Give Lisp_Floats an extra alignment. */
4640 if (type == Lisp_Float)
4641 {
4642 #if defined __GNUC__ && __GNUC__ >= 2
4643 alignment = __alignof (struct Lisp_Float);
4644 #else
4645 alignment = sizeof (struct Lisp_Float);
4646 #endif
4647 }
4648 #endif
4649
4650 again:
4651 if (type >= 0)
4652 {
4653 /* Allocate space for a Lisp object from the beginning of the free
4654 space with taking account of alignment. */
4655 result = ALIGN (purebeg + pure_bytes_used_lisp, alignment);
4656 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
4657 }
4658 else
4659 {
4660 /* Allocate space for a non-Lisp object from the end of the free
4661 space. */
4662 pure_bytes_used_non_lisp += size;
4663 result = purebeg + pure_size - pure_bytes_used_non_lisp;
4664 }
4665 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
4666
4667 if (pure_bytes_used <= pure_size)
4668 return result;
4669
4670 /* Don't allocate a large amount here,
4671 because it might get mmap'd and then its address
4672 might not be usable. */
4673 purebeg = (char *) xmalloc (10000);
4674 pure_size = 10000;
4675 pure_bytes_used_before_overflow += pure_bytes_used - size;
4676 pure_bytes_used = 0;
4677 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
4678 goto again;
4679 }
4680
4681
4682 /* Print a warning if PURESIZE is too small. */
4683
4684 void
4685 check_pure_size (void)
4686 {
4687 if (pure_bytes_used_before_overflow)
4688 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI"d"
4689 " bytes needed)"),
4690 pure_bytes_used + pure_bytes_used_before_overflow);
4691 }
4692
4693
4694 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
4695 the non-Lisp data pool of the pure storage, and return its start
4696 address. Return NULL if not found. */
4697
4698 static char *
4699 find_string_data_in_pure (const char *data, EMACS_INT nbytes)
4700 {
4701 int i;
4702 EMACS_INT skip, bm_skip[256], last_char_skip, infinity, start, start_max;
4703 const unsigned char *p;
4704 char *non_lisp_beg;
4705
4706 if (pure_bytes_used_non_lisp < nbytes + 1)
4707 return NULL;
4708
4709 /* Set up the Boyer-Moore table. */
4710 skip = nbytes + 1;
4711 for (i = 0; i < 256; i++)
4712 bm_skip[i] = skip;
4713
4714 p = (const unsigned char *) data;
4715 while (--skip > 0)
4716 bm_skip[*p++] = skip;
4717
4718 last_char_skip = bm_skip['\0'];
4719
4720 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
4721 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
4722
4723 /* See the comments in the function `boyer_moore' (search.c) for the
4724 use of `infinity'. */
4725 infinity = pure_bytes_used_non_lisp + 1;
4726 bm_skip['\0'] = infinity;
4727
4728 p = (const unsigned char *) non_lisp_beg + nbytes;
4729 start = 0;
4730 do
4731 {
4732 /* Check the last character (== '\0'). */
4733 do
4734 {
4735 start += bm_skip[*(p + start)];
4736 }
4737 while (start <= start_max);
4738
4739 if (start < infinity)
4740 /* Couldn't find the last character. */
4741 return NULL;
4742
4743 /* No less than `infinity' means we could find the last
4744 character at `p[start - infinity]'. */
4745 start -= infinity;
4746
4747 /* Check the remaining characters. */
4748 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
4749 /* Found. */
4750 return non_lisp_beg + start;
4751
4752 start += last_char_skip;
4753 }
4754 while (start <= start_max);
4755
4756 return NULL;
4757 }
4758
4759
4760 /* Return a string allocated in pure space. DATA is a buffer holding
4761 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
4762 non-zero means make the result string multibyte.
4763
4764 Must get an error if pure storage is full, since if it cannot hold
4765 a large string it may be able to hold conses that point to that
4766 string; then the string is not protected from gc. */
4767
4768 Lisp_Object
4769 make_pure_string (const char *data,
4770 EMACS_INT nchars, EMACS_INT nbytes, int multibyte)
4771 {
4772 Lisp_Object string;
4773 struct Lisp_String *s;
4774
4775 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
4776 s->data = (unsigned char *) find_string_data_in_pure (data, nbytes);
4777 if (s->data == NULL)
4778 {
4779 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
4780 memcpy (s->data, data, nbytes);
4781 s->data[nbytes] = '\0';
4782 }
4783 s->size = nchars;
4784 s->size_byte = multibyte ? nbytes : -1;
4785 s->intervals = NULL_INTERVAL;
4786 XSETSTRING (string, s);
4787 return string;
4788 }
4789
4790 /* Return a string a string allocated in pure space. Do not allocate
4791 the string data, just point to DATA. */
4792
4793 Lisp_Object
4794 make_pure_c_string (const char *data)
4795 {
4796 Lisp_Object string;
4797 struct Lisp_String *s;
4798 EMACS_INT nchars = strlen (data);
4799
4800 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
4801 s->size = nchars;
4802 s->size_byte = -1;
4803 s->data = (unsigned char *) data;
4804 s->intervals = NULL_INTERVAL;
4805 XSETSTRING (string, s);
4806 return string;
4807 }
4808
4809 /* Return a cons allocated from pure space. Give it pure copies
4810 of CAR as car and CDR as cdr. */
4811
4812 Lisp_Object
4813 pure_cons (Lisp_Object car, Lisp_Object cdr)
4814 {
4815 register Lisp_Object new;
4816 struct Lisp_Cons *p;
4817
4818 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
4819 XSETCONS (new, p);
4820 XSETCAR (new, Fpurecopy (car));
4821 XSETCDR (new, Fpurecopy (cdr));
4822 return new;
4823 }
4824
4825
4826 /* Value is a float object with value NUM allocated from pure space. */
4827
4828 static Lisp_Object
4829 make_pure_float (double num)
4830 {
4831 register Lisp_Object new;
4832 struct Lisp_Float *p;
4833
4834 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
4835 XSETFLOAT (new, p);
4836 XFLOAT_INIT (new, num);
4837 return new;
4838 }
4839
4840
4841 /* Return a vector with room for LEN Lisp_Objects allocated from
4842 pure space. */
4843
4844 Lisp_Object
4845 make_pure_vector (EMACS_INT len)
4846 {
4847 Lisp_Object new;
4848 struct Lisp_Vector *p;
4849 size_t size = (offsetof (struct Lisp_Vector, contents)
4850 + len * sizeof (Lisp_Object));
4851
4852 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
4853 XSETVECTOR (new, p);
4854 XVECTOR (new)->header.size = len;
4855 return new;
4856 }
4857
4858
4859 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
4860 doc: /* Make a copy of object OBJ in pure storage.
4861 Recursively copies contents of vectors and cons cells.
4862 Does not copy symbols. Copies strings without text properties. */)
4863 (register Lisp_Object obj)
4864 {
4865 if (NILP (Vpurify_flag))
4866 return obj;
4867
4868 if (PURE_POINTER_P (XPNTR (obj)))
4869 return obj;
4870
4871 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
4872 {
4873 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
4874 if (!NILP (tmp))
4875 return tmp;
4876 }
4877
4878 if (CONSP (obj))
4879 obj = pure_cons (XCAR (obj), XCDR (obj));
4880 else if (FLOATP (obj))
4881 obj = make_pure_float (XFLOAT_DATA (obj));
4882 else if (STRINGP (obj))
4883 obj = make_pure_string (SSDATA (obj), SCHARS (obj),
4884 SBYTES (obj),
4885 STRING_MULTIBYTE (obj));
4886 else if (COMPILEDP (obj) || VECTORP (obj))
4887 {
4888 register struct Lisp_Vector *vec;
4889 register EMACS_INT i;
4890 EMACS_INT size;
4891
4892 size = ASIZE (obj);
4893 if (size & PSEUDOVECTOR_FLAG)
4894 size &= PSEUDOVECTOR_SIZE_MASK;
4895 vec = XVECTOR (make_pure_vector (size));
4896 for (i = 0; i < size; i++)
4897 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
4898 if (COMPILEDP (obj))
4899 {
4900 XSETPVECTYPE (vec, PVEC_COMPILED);
4901 XSETCOMPILED (obj, vec);
4902 }
4903 else
4904 XSETVECTOR (obj, vec);
4905 }
4906 else if (MARKERP (obj))
4907 error ("Attempt to copy a marker to pure storage");
4908 else
4909 /* Not purified, don't hash-cons. */
4910 return obj;
4911
4912 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
4913 Fputhash (obj, obj, Vpurify_flag);
4914
4915 return obj;
4916 }
4917
4918
4919 \f
4920 /***********************************************************************
4921 Protection from GC
4922 ***********************************************************************/
4923
4924 /* Put an entry in staticvec, pointing at the variable with address
4925 VARADDRESS. */
4926
4927 void
4928 staticpro (Lisp_Object *varaddress)
4929 {
4930 staticvec[staticidx++] = varaddress;
4931 if (staticidx >= NSTATICS)
4932 abort ();
4933 }
4934
4935 \f
4936 /***********************************************************************
4937 Protection from GC
4938 ***********************************************************************/
4939
4940 /* Temporarily prevent garbage collection. */
4941
4942 int
4943 inhibit_garbage_collection (void)
4944 {
4945 int count = SPECPDL_INDEX ();
4946
4947 specbind (Qgc_cons_threshold, make_number (MOST_POSITIVE_FIXNUM));
4948 return count;
4949 }
4950
4951
4952 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
4953 doc: /* Reclaim storage for Lisp objects no longer needed.
4954 Garbage collection happens automatically if you cons more than
4955 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
4956 `garbage-collect' normally returns a list with info on amount of space in use:
4957 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)
4958 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS
4959 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)
4960 (USED-STRINGS . FREE-STRINGS))
4961 However, if there was overflow in pure space, `garbage-collect'
4962 returns nil, because real GC can't be done. */)
4963 (void)
4964 {
4965 register struct specbinding *bind;
4966 char stack_top_variable;
4967 ptrdiff_t i;
4968 int message_p;
4969 Lisp_Object total[8];
4970 int count = SPECPDL_INDEX ();
4971 EMACS_TIME t1, t2, t3;
4972
4973 if (abort_on_gc)
4974 abort ();
4975
4976 /* Can't GC if pure storage overflowed because we can't determine
4977 if something is a pure object or not. */
4978 if (pure_bytes_used_before_overflow)
4979 return Qnil;
4980
4981 CHECK_CONS_LIST ();
4982
4983 /* Don't keep undo information around forever.
4984 Do this early on, so it is no problem if the user quits. */
4985 {
4986 register struct buffer *nextb = all_buffers;
4987
4988 while (nextb)
4989 {
4990 /* If a buffer's undo list is Qt, that means that undo is
4991 turned off in that buffer. Calling truncate_undo_list on
4992 Qt tends to return NULL, which effectively turns undo back on.
4993 So don't call truncate_undo_list if undo_list is Qt. */
4994 if (! NILP (nextb->BUFFER_INTERNAL_FIELD (name)) && ! EQ (nextb->BUFFER_INTERNAL_FIELD (undo_list), Qt))
4995 truncate_undo_list (nextb);
4996
4997 /* Shrink buffer gaps, but skip indirect and dead buffers. */
4998 if (nextb->base_buffer == 0 && !NILP (nextb->BUFFER_INTERNAL_FIELD (name))
4999 && ! nextb->text->inhibit_shrinking)
5000 {
5001 /* If a buffer's gap size is more than 10% of the buffer
5002 size, or larger than 2000 bytes, then shrink it
5003 accordingly. Keep a minimum size of 20 bytes. */
5004 int size = min (2000, max (20, (nextb->text->z_byte / 10)));
5005
5006 if (nextb->text->gap_size > size)
5007 {
5008 struct buffer *save_current = current_buffer;
5009 current_buffer = nextb;
5010 make_gap (-(nextb->text->gap_size - size));
5011 current_buffer = save_current;
5012 }
5013 }
5014
5015 nextb = nextb->header.next.buffer;
5016 }
5017 }
5018
5019 EMACS_GET_TIME (t1);
5020
5021 /* In case user calls debug_print during GC,
5022 don't let that cause a recursive GC. */
5023 consing_since_gc = 0;
5024
5025 /* Save what's currently displayed in the echo area. */
5026 message_p = push_message ();
5027 record_unwind_protect (pop_message_unwind, Qnil);
5028
5029 /* Save a copy of the contents of the stack, for debugging. */
5030 #if MAX_SAVE_STACK > 0
5031 if (NILP (Vpurify_flag))
5032 {
5033 char *stack;
5034 ptrdiff_t stack_size;
5035 if (&stack_top_variable < stack_bottom)
5036 {
5037 stack = &stack_top_variable;
5038 stack_size = stack_bottom - &stack_top_variable;
5039 }
5040 else
5041 {
5042 stack = stack_bottom;
5043 stack_size = &stack_top_variable - stack_bottom;
5044 }
5045 if (stack_size <= MAX_SAVE_STACK)
5046 {
5047 if (stack_copy_size < stack_size)
5048 {
5049 stack_copy = (char *) xrealloc (stack_copy, stack_size);
5050 stack_copy_size = stack_size;
5051 }
5052 memcpy (stack_copy, stack, stack_size);
5053 }
5054 }
5055 #endif /* MAX_SAVE_STACK > 0 */
5056
5057 if (garbage_collection_messages)
5058 message1_nolog ("Garbage collecting...");
5059
5060 BLOCK_INPUT;
5061
5062 shrink_regexp_cache ();
5063
5064 gc_in_progress = 1;
5065
5066 /* clear_marks (); */
5067
5068 /* Mark all the special slots that serve as the roots of accessibility. */
5069
5070 for (i = 0; i < staticidx; i++)
5071 mark_object (*staticvec[i]);
5072
5073 for (bind = specpdl; bind != specpdl_ptr; bind++)
5074 {
5075 mark_object (bind->symbol);
5076 mark_object (bind->old_value);
5077 }
5078 mark_terminals ();
5079 mark_kboards ();
5080 mark_ttys ();
5081
5082 #ifdef USE_GTK
5083 {
5084 extern void xg_mark_data (void);
5085 xg_mark_data ();
5086 }
5087 #endif
5088
5089 #if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
5090 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
5091 mark_stack ();
5092 #else
5093 {
5094 register struct gcpro *tail;
5095 for (tail = gcprolist; tail; tail = tail->next)
5096 for (i = 0; i < tail->nvars; i++)
5097 mark_object (tail->var[i]);
5098 }
5099 mark_byte_stack ();
5100 {
5101 struct catchtag *catch;
5102 struct handler *handler;
5103
5104 for (catch = catchlist; catch; catch = catch->next)
5105 {
5106 mark_object (catch->tag);
5107 mark_object (catch->val);
5108 }
5109 for (handler = handlerlist; handler; handler = handler->next)
5110 {
5111 mark_object (handler->handler);
5112 mark_object (handler->var);
5113 }
5114 }
5115 mark_backtrace ();
5116 #endif
5117
5118 #ifdef HAVE_WINDOW_SYSTEM
5119 mark_fringe_data ();
5120 #endif
5121
5122 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5123 mark_stack ();
5124 #endif
5125
5126 /* Everything is now marked, except for the things that require special
5127 finalization, i.e. the undo_list.
5128 Look thru every buffer's undo list
5129 for elements that update markers that were not marked,
5130 and delete them. */
5131 {
5132 register struct buffer *nextb = all_buffers;
5133
5134 while (nextb)
5135 {
5136 /* If a buffer's undo list is Qt, that means that undo is
5137 turned off in that buffer. Calling truncate_undo_list on
5138 Qt tends to return NULL, which effectively turns undo back on.
5139 So don't call truncate_undo_list if undo_list is Qt. */
5140 if (! EQ (nextb->BUFFER_INTERNAL_FIELD (undo_list), Qt))
5141 {
5142 Lisp_Object tail, prev;
5143 tail = nextb->BUFFER_INTERNAL_FIELD (undo_list);
5144 prev = Qnil;
5145 while (CONSP (tail))
5146 {
5147 if (CONSP (XCAR (tail))
5148 && MARKERP (XCAR (XCAR (tail)))
5149 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5150 {
5151 if (NILP (prev))
5152 nextb->BUFFER_INTERNAL_FIELD (undo_list) = tail = XCDR (tail);
5153 else
5154 {
5155 tail = XCDR (tail);
5156 XSETCDR (prev, tail);
5157 }
5158 }
5159 else
5160 {
5161 prev = tail;
5162 tail = XCDR (tail);
5163 }
5164 }
5165 }
5166 /* Now that we have stripped the elements that need not be in the
5167 undo_list any more, we can finally mark the list. */
5168 mark_object (nextb->BUFFER_INTERNAL_FIELD (undo_list));
5169
5170 nextb = nextb->header.next.buffer;
5171 }
5172 }
5173
5174 gc_sweep ();
5175
5176 /* Clear the mark bits that we set in certain root slots. */
5177
5178 unmark_byte_stack ();
5179 VECTOR_UNMARK (&buffer_defaults);
5180 VECTOR_UNMARK (&buffer_local_symbols);
5181
5182 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
5183 dump_zombies ();
5184 #endif
5185
5186 UNBLOCK_INPUT;
5187
5188 CHECK_CONS_LIST ();
5189
5190 /* clear_marks (); */
5191 gc_in_progress = 0;
5192
5193 consing_since_gc = 0;
5194 if (gc_cons_threshold < 10000)
5195 gc_cons_threshold = 10000;
5196
5197 gc_relative_threshold = 0;
5198 if (FLOATP (Vgc_cons_percentage))
5199 { /* Set gc_cons_combined_threshold. */
5200 double tot = 0;
5201
5202 tot += total_conses * sizeof (struct Lisp_Cons);
5203 tot += total_symbols * sizeof (struct Lisp_Symbol);
5204 tot += total_markers * sizeof (union Lisp_Misc);
5205 tot += total_string_size;
5206 tot += total_vector_size * sizeof (Lisp_Object);
5207 tot += total_floats * sizeof (struct Lisp_Float);
5208 tot += total_intervals * sizeof (struct interval);
5209 tot += total_strings * sizeof (struct Lisp_String);
5210
5211 tot *= XFLOAT_DATA (Vgc_cons_percentage);
5212 if (0 < tot)
5213 {
5214 if (tot < TYPE_MAXIMUM (EMACS_INT))
5215 gc_relative_threshold = tot;
5216 else
5217 gc_relative_threshold = TYPE_MAXIMUM (EMACS_INT);
5218 }
5219 }
5220
5221 if (garbage_collection_messages)
5222 {
5223 if (message_p || minibuf_level > 0)
5224 restore_message ();
5225 else
5226 message1_nolog ("Garbage collecting...done");
5227 }
5228
5229 unbind_to (count, Qnil);
5230
5231 total[0] = Fcons (make_number (total_conses),
5232 make_number (total_free_conses));
5233 total[1] = Fcons (make_number (total_symbols),
5234 make_number (total_free_symbols));
5235 total[2] = Fcons (make_number (total_markers),
5236 make_number (total_free_markers));
5237 total[3] = make_number (total_string_size);
5238 total[4] = make_number (total_vector_size);
5239 total[5] = Fcons (make_number (total_floats),
5240 make_number (total_free_floats));
5241 total[6] = Fcons (make_number (total_intervals),
5242 make_number (total_free_intervals));
5243 total[7] = Fcons (make_number (total_strings),
5244 make_number (total_free_strings));
5245
5246 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5247 {
5248 /* Compute average percentage of zombies. */
5249 double nlive = 0;
5250
5251 for (i = 0; i < 7; ++i)
5252 if (CONSP (total[i]))
5253 nlive += XFASTINT (XCAR (total[i]));
5254
5255 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
5256 max_live = max (nlive, max_live);
5257 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
5258 max_zombies = max (nzombies, max_zombies);
5259 ++ngcs;
5260 }
5261 #endif
5262
5263 if (!NILP (Vpost_gc_hook))
5264 {
5265 int gc_count = inhibit_garbage_collection ();
5266 safe_run_hooks (Qpost_gc_hook);
5267 unbind_to (gc_count, Qnil);
5268 }
5269
5270 /* Accumulate statistics. */
5271 EMACS_GET_TIME (t2);
5272 EMACS_SUB_TIME (t3, t2, t1);
5273 if (FLOATP (Vgc_elapsed))
5274 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed) +
5275 EMACS_SECS (t3) +
5276 EMACS_USECS (t3) * 1.0e-6);
5277 gcs_done++;
5278
5279 return Flist (sizeof total / sizeof *total, total);
5280 }
5281
5282
5283 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5284 only interesting objects referenced from glyphs are strings. */
5285
5286 static void
5287 mark_glyph_matrix (struct glyph_matrix *matrix)
5288 {
5289 struct glyph_row *row = matrix->rows;
5290 struct glyph_row *end = row + matrix->nrows;
5291
5292 for (; row < end; ++row)
5293 if (row->enabled_p)
5294 {
5295 int area;
5296 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
5297 {
5298 struct glyph *glyph = row->glyphs[area];
5299 struct glyph *end_glyph = glyph + row->used[area];
5300
5301 for (; glyph < end_glyph; ++glyph)
5302 if (STRINGP (glyph->object)
5303 && !STRING_MARKED_P (XSTRING (glyph->object)))
5304 mark_object (glyph->object);
5305 }
5306 }
5307 }
5308
5309
5310 /* Mark Lisp faces in the face cache C. */
5311
5312 static void
5313 mark_face_cache (struct face_cache *c)
5314 {
5315 if (c)
5316 {
5317 int i, j;
5318 for (i = 0; i < c->used; ++i)
5319 {
5320 struct face *face = FACE_FROM_ID (c->f, i);
5321
5322 if (face)
5323 {
5324 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
5325 mark_object (face->lface[j]);
5326 }
5327 }
5328 }
5329 }
5330
5331
5332 \f
5333 /* Mark reference to a Lisp_Object.
5334 If the object referred to has not been seen yet, recursively mark
5335 all the references contained in it. */
5336
5337 #define LAST_MARKED_SIZE 500
5338 static Lisp_Object last_marked[LAST_MARKED_SIZE];
5339 static int last_marked_index;
5340
5341 /* For debugging--call abort when we cdr down this many
5342 links of a list, in mark_object. In debugging,
5343 the call to abort will hit a breakpoint.
5344 Normally this is zero and the check never goes off. */
5345 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE;
5346
5347 static void
5348 mark_vectorlike (struct Lisp_Vector *ptr)
5349 {
5350 EMACS_INT size = ptr->header.size;
5351 EMACS_INT i;
5352
5353 eassert (!VECTOR_MARKED_P (ptr));
5354 VECTOR_MARK (ptr); /* Else mark it */
5355 if (size & PSEUDOVECTOR_FLAG)
5356 size &= PSEUDOVECTOR_SIZE_MASK;
5357
5358 /* Note that this size is not the memory-footprint size, but only
5359 the number of Lisp_Object fields that we should trace.
5360 The distinction is used e.g. by Lisp_Process which places extra
5361 non-Lisp_Object fields at the end of the structure. */
5362 for (i = 0; i < size; i++) /* and then mark its elements */
5363 mark_object (ptr->contents[i]);
5364 }
5365
5366 /* Like mark_vectorlike but optimized for char-tables (and
5367 sub-char-tables) assuming that the contents are mostly integers or
5368 symbols. */
5369
5370 static void
5371 mark_char_table (struct Lisp_Vector *ptr)
5372 {
5373 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5374 int i;
5375
5376 eassert (!VECTOR_MARKED_P (ptr));
5377 VECTOR_MARK (ptr);
5378 for (i = 0; i < size; i++)
5379 {
5380 Lisp_Object val = ptr->contents[i];
5381
5382 if (INTEGERP (val) || (SYMBOLP (val) && XSYMBOL (val)->gcmarkbit))
5383 continue;
5384 if (SUB_CHAR_TABLE_P (val))
5385 {
5386 if (! VECTOR_MARKED_P (XVECTOR (val)))
5387 mark_char_table (XVECTOR (val));
5388 }
5389 else
5390 mark_object (val);
5391 }
5392 }
5393
5394 void
5395 mark_object (Lisp_Object arg)
5396 {
5397 register Lisp_Object obj = arg;
5398 #ifdef GC_CHECK_MARKED_OBJECTS
5399 void *po;
5400 struct mem_node *m;
5401 #endif
5402 ptrdiff_t cdr_count = 0;
5403
5404 loop:
5405
5406 if (PURE_POINTER_P (XPNTR (obj)))
5407 return;
5408
5409 last_marked[last_marked_index++] = obj;
5410 if (last_marked_index == LAST_MARKED_SIZE)
5411 last_marked_index = 0;
5412
5413 /* Perform some sanity checks on the objects marked here. Abort if
5414 we encounter an object we know is bogus. This increases GC time
5415 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
5416 #ifdef GC_CHECK_MARKED_OBJECTS
5417
5418 po = (void *) XPNTR (obj);
5419
5420 /* Check that the object pointed to by PO is known to be a Lisp
5421 structure allocated from the heap. */
5422 #define CHECK_ALLOCATED() \
5423 do { \
5424 m = mem_find (po); \
5425 if (m == MEM_NIL) \
5426 abort (); \
5427 } while (0)
5428
5429 /* Check that the object pointed to by PO is live, using predicate
5430 function LIVEP. */
5431 #define CHECK_LIVE(LIVEP) \
5432 do { \
5433 if (!LIVEP (m, po)) \
5434 abort (); \
5435 } while (0)
5436
5437 /* Check both of the above conditions. */
5438 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
5439 do { \
5440 CHECK_ALLOCATED (); \
5441 CHECK_LIVE (LIVEP); \
5442 } while (0) \
5443
5444 #else /* not GC_CHECK_MARKED_OBJECTS */
5445
5446 #define CHECK_LIVE(LIVEP) (void) 0
5447 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
5448
5449 #endif /* not GC_CHECK_MARKED_OBJECTS */
5450
5451 switch (SWITCH_ENUM_CAST (XTYPE (obj)))
5452 {
5453 case Lisp_String:
5454 {
5455 register struct Lisp_String *ptr = XSTRING (obj);
5456 if (STRING_MARKED_P (ptr))
5457 break;
5458 CHECK_ALLOCATED_AND_LIVE (live_string_p);
5459 MARK_INTERVAL_TREE (ptr->intervals);
5460 MARK_STRING (ptr);
5461 #ifdef GC_CHECK_STRING_BYTES
5462 /* Check that the string size recorded in the string is the
5463 same as the one recorded in the sdata structure. */
5464 CHECK_STRING_BYTES (ptr);
5465 #endif /* GC_CHECK_STRING_BYTES */
5466 }
5467 break;
5468
5469 case Lisp_Vectorlike:
5470 if (VECTOR_MARKED_P (XVECTOR (obj)))
5471 break;
5472 #ifdef GC_CHECK_MARKED_OBJECTS
5473 m = mem_find (po);
5474 if (m == MEM_NIL && !SUBRP (obj)
5475 && po != &buffer_defaults
5476 && po != &buffer_local_symbols)
5477 abort ();
5478 #endif /* GC_CHECK_MARKED_OBJECTS */
5479
5480 if (BUFFERP (obj))
5481 {
5482 #ifdef GC_CHECK_MARKED_OBJECTS
5483 if (po != &buffer_defaults && po != &buffer_local_symbols)
5484 {
5485 struct buffer *b;
5486 for (b = all_buffers; b && b != po; b = b->header.next.buffer)
5487 ;
5488 if (b == NULL)
5489 abort ();
5490 }
5491 #endif /* GC_CHECK_MARKED_OBJECTS */
5492 mark_buffer (obj);
5493 }
5494 else if (SUBRP (obj))
5495 break;
5496 else if (COMPILEDP (obj))
5497 /* We could treat this just like a vector, but it is better to
5498 save the COMPILED_CONSTANTS element for last and avoid
5499 recursion there. */
5500 {
5501 register struct Lisp_Vector *ptr = XVECTOR (obj);
5502 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5503 int i;
5504
5505 CHECK_LIVE (live_vector_p);
5506 VECTOR_MARK (ptr); /* Else mark it */
5507 for (i = 0; i < size; i++) /* and then mark its elements */
5508 {
5509 if (i != COMPILED_CONSTANTS)
5510 mark_object (ptr->contents[i]);
5511 }
5512 obj = ptr->contents[COMPILED_CONSTANTS];
5513 goto loop;
5514 }
5515 else if (FRAMEP (obj))
5516 {
5517 register struct frame *ptr = XFRAME (obj);
5518 mark_vectorlike (XVECTOR (obj));
5519 mark_face_cache (ptr->face_cache);
5520 }
5521 else if (WINDOWP (obj))
5522 {
5523 register struct Lisp_Vector *ptr = XVECTOR (obj);
5524 struct window *w = XWINDOW (obj);
5525 mark_vectorlike (ptr);
5526 /* Mark glyphs for leaf windows. Marking window matrices is
5527 sufficient because frame matrices use the same glyph
5528 memory. */
5529 if (NILP (w->hchild)
5530 && NILP (w->vchild)
5531 && w->current_matrix)
5532 {
5533 mark_glyph_matrix (w->current_matrix);
5534 mark_glyph_matrix (w->desired_matrix);
5535 }
5536 }
5537 else if (HASH_TABLE_P (obj))
5538 {
5539 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
5540 mark_vectorlike ((struct Lisp_Vector *)h);
5541 /* If hash table is not weak, mark all keys and values.
5542 For weak tables, mark only the vector. */
5543 if (NILP (h->weak))
5544 mark_object (h->key_and_value);
5545 else
5546 VECTOR_MARK (XVECTOR (h->key_and_value));
5547 }
5548 else if (CHAR_TABLE_P (obj))
5549 mark_char_table (XVECTOR (obj));
5550 else
5551 mark_vectorlike (XVECTOR (obj));
5552 break;
5553
5554 case Lisp_Symbol:
5555 {
5556 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
5557 struct Lisp_Symbol *ptrx;
5558
5559 if (ptr->gcmarkbit)
5560 break;
5561 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
5562 ptr->gcmarkbit = 1;
5563 mark_object (ptr->function);
5564 mark_object (ptr->plist);
5565 switch (ptr->redirect)
5566 {
5567 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
5568 case SYMBOL_VARALIAS:
5569 {
5570 Lisp_Object tem;
5571 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
5572 mark_object (tem);
5573 break;
5574 }
5575 case SYMBOL_LOCALIZED:
5576 {
5577 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
5578 /* If the value is forwarded to a buffer or keyboard field,
5579 these are marked when we see the corresponding object.
5580 And if it's forwarded to a C variable, either it's not
5581 a Lisp_Object var, or it's staticpro'd already. */
5582 mark_object (blv->where);
5583 mark_object (blv->valcell);
5584 mark_object (blv->defcell);
5585 break;
5586 }
5587 case SYMBOL_FORWARDED:
5588 /* If the value is forwarded to a buffer or keyboard field,
5589 these are marked when we see the corresponding object.
5590 And if it's forwarded to a C variable, either it's not
5591 a Lisp_Object var, or it's staticpro'd already. */
5592 break;
5593 default: abort ();
5594 }
5595 if (!PURE_POINTER_P (XSTRING (ptr->xname)))
5596 MARK_STRING (XSTRING (ptr->xname));
5597 MARK_INTERVAL_TREE (STRING_INTERVALS (ptr->xname));
5598
5599 ptr = ptr->next;
5600 if (ptr)
5601 {
5602 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
5603 XSETSYMBOL (obj, ptrx);
5604 goto loop;
5605 }
5606 }
5607 break;
5608
5609 case Lisp_Misc:
5610 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
5611 if (XMISCANY (obj)->gcmarkbit)
5612 break;
5613 XMISCANY (obj)->gcmarkbit = 1;
5614
5615 switch (XMISCTYPE (obj))
5616 {
5617
5618 case Lisp_Misc_Marker:
5619 /* DO NOT mark thru the marker's chain.
5620 The buffer's markers chain does not preserve markers from gc;
5621 instead, markers are removed from the chain when freed by gc. */
5622 break;
5623
5624 case Lisp_Misc_Save_Value:
5625 #if GC_MARK_STACK
5626 {
5627 register struct Lisp_Save_Value *ptr = XSAVE_VALUE (obj);
5628 /* If DOGC is set, POINTER is the address of a memory
5629 area containing INTEGER potential Lisp_Objects. */
5630 if (ptr->dogc)
5631 {
5632 Lisp_Object *p = (Lisp_Object *) ptr->pointer;
5633 ptrdiff_t nelt;
5634 for (nelt = ptr->integer; nelt > 0; nelt--, p++)
5635 mark_maybe_object (*p);
5636 }
5637 }
5638 #endif
5639 break;
5640
5641 case Lisp_Misc_Overlay:
5642 {
5643 struct Lisp_Overlay *ptr = XOVERLAY (obj);
5644 mark_object (ptr->start);
5645 mark_object (ptr->end);
5646 mark_object (ptr->plist);
5647 if (ptr->next)
5648 {
5649 XSETMISC (obj, ptr->next);
5650 goto loop;
5651 }
5652 }
5653 break;
5654
5655 default:
5656 abort ();
5657 }
5658 break;
5659
5660 case Lisp_Cons:
5661 {
5662 register struct Lisp_Cons *ptr = XCONS (obj);
5663 if (CONS_MARKED_P (ptr))
5664 break;
5665 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
5666 CONS_MARK (ptr);
5667 /* If the cdr is nil, avoid recursion for the car. */
5668 if (EQ (ptr->u.cdr, Qnil))
5669 {
5670 obj = ptr->car;
5671 cdr_count = 0;
5672 goto loop;
5673 }
5674 mark_object (ptr->car);
5675 obj = ptr->u.cdr;
5676 cdr_count++;
5677 if (cdr_count == mark_object_loop_halt)
5678 abort ();
5679 goto loop;
5680 }
5681
5682 case Lisp_Float:
5683 CHECK_ALLOCATED_AND_LIVE (live_float_p);
5684 FLOAT_MARK (XFLOAT (obj));
5685 break;
5686
5687 case_Lisp_Int:
5688 break;
5689
5690 default:
5691 abort ();
5692 }
5693
5694 #undef CHECK_LIVE
5695 #undef CHECK_ALLOCATED
5696 #undef CHECK_ALLOCATED_AND_LIVE
5697 }
5698
5699 /* Mark the pointers in a buffer structure. */
5700
5701 static void
5702 mark_buffer (Lisp_Object buf)
5703 {
5704 register struct buffer *buffer = XBUFFER (buf);
5705 register Lisp_Object *ptr, tmp;
5706 Lisp_Object base_buffer;
5707
5708 eassert (!VECTOR_MARKED_P (buffer));
5709 VECTOR_MARK (buffer);
5710
5711 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
5712
5713 /* For now, we just don't mark the undo_list. It's done later in
5714 a special way just before the sweep phase, and after stripping
5715 some of its elements that are not needed any more. */
5716
5717 if (buffer->overlays_before)
5718 {
5719 XSETMISC (tmp, buffer->overlays_before);
5720 mark_object (tmp);
5721 }
5722 if (buffer->overlays_after)
5723 {
5724 XSETMISC (tmp, buffer->overlays_after);
5725 mark_object (tmp);
5726 }
5727
5728 /* buffer-local Lisp variables start at `undo_list',
5729 tho only the ones from `name' on are GC'd normally. */
5730 for (ptr = &buffer->BUFFER_INTERNAL_FIELD (name);
5731 ptr <= &PER_BUFFER_VALUE (buffer,
5732 PER_BUFFER_VAR_OFFSET (LAST_FIELD_PER_BUFFER));
5733 ptr++)
5734 mark_object (*ptr);
5735
5736 /* If this is an indirect buffer, mark its base buffer. */
5737 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5738 {
5739 XSETBUFFER (base_buffer, buffer->base_buffer);
5740 mark_buffer (base_buffer);
5741 }
5742 }
5743
5744 /* Mark the Lisp pointers in the terminal objects.
5745 Called by the Fgarbage_collector. */
5746
5747 static void
5748 mark_terminals (void)
5749 {
5750 struct terminal *t;
5751 for (t = terminal_list; t; t = t->next_terminal)
5752 {
5753 eassert (t->name != NULL);
5754 #ifdef HAVE_WINDOW_SYSTEM
5755 /* If a terminal object is reachable from a stacpro'ed object,
5756 it might have been marked already. Make sure the image cache
5757 gets marked. */
5758 mark_image_cache (t->image_cache);
5759 #endif /* HAVE_WINDOW_SYSTEM */
5760 if (!VECTOR_MARKED_P (t))
5761 mark_vectorlike ((struct Lisp_Vector *)t);
5762 }
5763 }
5764
5765
5766
5767 /* Value is non-zero if OBJ will survive the current GC because it's
5768 either marked or does not need to be marked to survive. */
5769
5770 int
5771 survives_gc_p (Lisp_Object obj)
5772 {
5773 int survives_p;
5774
5775 switch (XTYPE (obj))
5776 {
5777 case_Lisp_Int:
5778 survives_p = 1;
5779 break;
5780
5781 case Lisp_Symbol:
5782 survives_p = XSYMBOL (obj)->gcmarkbit;
5783 break;
5784
5785 case Lisp_Misc:
5786 survives_p = XMISCANY (obj)->gcmarkbit;
5787 break;
5788
5789 case Lisp_String:
5790 survives_p = STRING_MARKED_P (XSTRING (obj));
5791 break;
5792
5793 case Lisp_Vectorlike:
5794 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
5795 break;
5796
5797 case Lisp_Cons:
5798 survives_p = CONS_MARKED_P (XCONS (obj));
5799 break;
5800
5801 case Lisp_Float:
5802 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
5803 break;
5804
5805 default:
5806 abort ();
5807 }
5808
5809 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
5810 }
5811
5812
5813 \f
5814 /* Sweep: find all structures not marked, and free them. */
5815
5816 static void
5817 gc_sweep (void)
5818 {
5819 /* Remove or mark entries in weak hash tables.
5820 This must be done before any object is unmarked. */
5821 sweep_weak_hash_tables ();
5822
5823 sweep_strings ();
5824 #ifdef GC_CHECK_STRING_BYTES
5825 if (!noninteractive)
5826 check_string_bytes (1);
5827 #endif
5828
5829 /* Put all unmarked conses on free list */
5830 {
5831 register struct cons_block *cblk;
5832 struct cons_block **cprev = &cons_block;
5833 register int lim = cons_block_index;
5834 EMACS_INT num_free = 0, num_used = 0;
5835
5836 cons_free_list = 0;
5837
5838 for (cblk = cons_block; cblk; cblk = *cprev)
5839 {
5840 register int i = 0;
5841 int this_free = 0;
5842 int ilim = (lim + BITS_PER_INT - 1) / BITS_PER_INT;
5843
5844 /* Scan the mark bits an int at a time. */
5845 for (i = 0; i < ilim; i++)
5846 {
5847 if (cblk->gcmarkbits[i] == -1)
5848 {
5849 /* Fast path - all cons cells for this int are marked. */
5850 cblk->gcmarkbits[i] = 0;
5851 num_used += BITS_PER_INT;
5852 }
5853 else
5854 {
5855 /* Some cons cells for this int are not marked.
5856 Find which ones, and free them. */
5857 int start, pos, stop;
5858
5859 start = i * BITS_PER_INT;
5860 stop = lim - start;
5861 if (stop > BITS_PER_INT)
5862 stop = BITS_PER_INT;
5863 stop += start;
5864
5865 for (pos = start; pos < stop; pos++)
5866 {
5867 if (!CONS_MARKED_P (&cblk->conses[pos]))
5868 {
5869 this_free++;
5870 cblk->conses[pos].u.chain = cons_free_list;
5871 cons_free_list = &cblk->conses[pos];
5872 #if GC_MARK_STACK
5873 cons_free_list->car = Vdead;
5874 #endif
5875 }
5876 else
5877 {
5878 num_used++;
5879 CONS_UNMARK (&cblk->conses[pos]);
5880 }
5881 }
5882 }
5883 }
5884
5885 lim = CONS_BLOCK_SIZE;
5886 /* If this block contains only free conses and we have already
5887 seen more than two blocks worth of free conses then deallocate
5888 this block. */
5889 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
5890 {
5891 *cprev = cblk->next;
5892 /* Unhook from the free list. */
5893 cons_free_list = cblk->conses[0].u.chain;
5894 lisp_align_free (cblk);
5895 }
5896 else
5897 {
5898 num_free += this_free;
5899 cprev = &cblk->next;
5900 }
5901 }
5902 total_conses = num_used;
5903 total_free_conses = num_free;
5904 }
5905
5906 /* Put all unmarked floats on free list */
5907 {
5908 register struct float_block *fblk;
5909 struct float_block **fprev = &float_block;
5910 register int lim = float_block_index;
5911 EMACS_INT num_free = 0, num_used = 0;
5912
5913 float_free_list = 0;
5914
5915 for (fblk = float_block; fblk; fblk = *fprev)
5916 {
5917 register int i;
5918 int this_free = 0;
5919 for (i = 0; i < lim; i++)
5920 if (!FLOAT_MARKED_P (&fblk->floats[i]))
5921 {
5922 this_free++;
5923 fblk->floats[i].u.chain = float_free_list;
5924 float_free_list = &fblk->floats[i];
5925 }
5926 else
5927 {
5928 num_used++;
5929 FLOAT_UNMARK (&fblk->floats[i]);
5930 }
5931 lim = FLOAT_BLOCK_SIZE;
5932 /* If this block contains only free floats and we have already
5933 seen more than two blocks worth of free floats then deallocate
5934 this block. */
5935 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
5936 {
5937 *fprev = fblk->next;
5938 /* Unhook from the free list. */
5939 float_free_list = fblk->floats[0].u.chain;
5940 lisp_align_free (fblk);
5941 }
5942 else
5943 {
5944 num_free += this_free;
5945 fprev = &fblk->next;
5946 }
5947 }
5948 total_floats = num_used;
5949 total_free_floats = num_free;
5950 }
5951
5952 /* Put all unmarked intervals on free list */
5953 {
5954 register struct interval_block *iblk;
5955 struct interval_block **iprev = &interval_block;
5956 register int lim = interval_block_index;
5957 EMACS_INT num_free = 0, num_used = 0;
5958
5959 interval_free_list = 0;
5960
5961 for (iblk = interval_block; iblk; iblk = *iprev)
5962 {
5963 register int i;
5964 int this_free = 0;
5965
5966 for (i = 0; i < lim; i++)
5967 {
5968 if (!iblk->intervals[i].gcmarkbit)
5969 {
5970 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
5971 interval_free_list = &iblk->intervals[i];
5972 this_free++;
5973 }
5974 else
5975 {
5976 num_used++;
5977 iblk->intervals[i].gcmarkbit = 0;
5978 }
5979 }
5980 lim = INTERVAL_BLOCK_SIZE;
5981 /* If this block contains only free intervals and we have already
5982 seen more than two blocks worth of free intervals then
5983 deallocate this block. */
5984 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
5985 {
5986 *iprev = iblk->next;
5987 /* Unhook from the free list. */
5988 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
5989 lisp_free (iblk);
5990 }
5991 else
5992 {
5993 num_free += this_free;
5994 iprev = &iblk->next;
5995 }
5996 }
5997 total_intervals = num_used;
5998 total_free_intervals = num_free;
5999 }
6000
6001 /* Put all unmarked symbols on free list */
6002 {
6003 register struct symbol_block *sblk;
6004 struct symbol_block **sprev = &symbol_block;
6005 register int lim = symbol_block_index;
6006 EMACS_INT num_free = 0, num_used = 0;
6007
6008 symbol_free_list = NULL;
6009
6010 for (sblk = symbol_block; sblk; sblk = *sprev)
6011 {
6012 int this_free = 0;
6013 struct Lisp_Symbol *sym = sblk->symbols;
6014 struct Lisp_Symbol *end = sym + lim;
6015
6016 for (; sym < end; ++sym)
6017 {
6018 /* Check if the symbol was created during loadup. In such a case
6019 it might be pointed to by pure bytecode which we don't trace,
6020 so we conservatively assume that it is live. */
6021 int pure_p = PURE_POINTER_P (XSTRING (sym->xname));
6022
6023 if (!sym->gcmarkbit && !pure_p)
6024 {
6025 if (sym->redirect == SYMBOL_LOCALIZED)
6026 xfree (SYMBOL_BLV (sym));
6027 sym->next = symbol_free_list;
6028 symbol_free_list = sym;
6029 #if GC_MARK_STACK
6030 symbol_free_list->function = Vdead;
6031 #endif
6032 ++this_free;
6033 }
6034 else
6035 {
6036 ++num_used;
6037 if (!pure_p)
6038 UNMARK_STRING (XSTRING (sym->xname));
6039 sym->gcmarkbit = 0;
6040 }
6041 }
6042
6043 lim = SYMBOL_BLOCK_SIZE;
6044 /* If this block contains only free symbols and we have already
6045 seen more than two blocks worth of free symbols then deallocate
6046 this block. */
6047 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6048 {
6049 *sprev = sblk->next;
6050 /* Unhook from the free list. */
6051 symbol_free_list = sblk->symbols[0].next;
6052 lisp_free (sblk);
6053 }
6054 else
6055 {
6056 num_free += this_free;
6057 sprev = &sblk->next;
6058 }
6059 }
6060 total_symbols = num_used;
6061 total_free_symbols = num_free;
6062 }
6063
6064 /* Put all unmarked misc's on free list.
6065 For a marker, first unchain it from the buffer it points into. */
6066 {
6067 register struct marker_block *mblk;
6068 struct marker_block **mprev = &marker_block;
6069 register int lim = marker_block_index;
6070 EMACS_INT num_free = 0, num_used = 0;
6071
6072 marker_free_list = 0;
6073
6074 for (mblk = marker_block; mblk; mblk = *mprev)
6075 {
6076 register int i;
6077 int this_free = 0;
6078
6079 for (i = 0; i < lim; i++)
6080 {
6081 if (!mblk->markers[i].u_any.gcmarkbit)
6082 {
6083 if (mblk->markers[i].u_any.type == Lisp_Misc_Marker)
6084 unchain_marker (&mblk->markers[i].u_marker);
6085 /* Set the type of the freed object to Lisp_Misc_Free.
6086 We could leave the type alone, since nobody checks it,
6087 but this might catch bugs faster. */
6088 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
6089 mblk->markers[i].u_free.chain = marker_free_list;
6090 marker_free_list = &mblk->markers[i];
6091 this_free++;
6092 }
6093 else
6094 {
6095 num_used++;
6096 mblk->markers[i].u_any.gcmarkbit = 0;
6097 }
6098 }
6099 lim = MARKER_BLOCK_SIZE;
6100 /* If this block contains only free markers and we have already
6101 seen more than two blocks worth of free markers then deallocate
6102 this block. */
6103 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6104 {
6105 *mprev = mblk->next;
6106 /* Unhook from the free list. */
6107 marker_free_list = mblk->markers[0].u_free.chain;
6108 lisp_free (mblk);
6109 }
6110 else
6111 {
6112 num_free += this_free;
6113 mprev = &mblk->next;
6114 }
6115 }
6116
6117 total_markers = num_used;
6118 total_free_markers = num_free;
6119 }
6120
6121 /* Free all unmarked buffers */
6122 {
6123 register struct buffer *buffer = all_buffers, *prev = 0, *next;
6124
6125 while (buffer)
6126 if (!VECTOR_MARKED_P (buffer))
6127 {
6128 if (prev)
6129 prev->header.next = buffer->header.next;
6130 else
6131 all_buffers = buffer->header.next.buffer;
6132 next = buffer->header.next.buffer;
6133 lisp_free (buffer);
6134 buffer = next;
6135 }
6136 else
6137 {
6138 VECTOR_UNMARK (buffer);
6139 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
6140 prev = buffer, buffer = buffer->header.next.buffer;
6141 }
6142 }
6143
6144 /* Free all unmarked vectors */
6145 {
6146 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
6147 total_vector_size = 0;
6148
6149 while (vector)
6150 if (!VECTOR_MARKED_P (vector))
6151 {
6152 if (prev)
6153 prev->header.next = vector->header.next;
6154 else
6155 all_vectors = vector->header.next.vector;
6156 next = vector->header.next.vector;
6157 lisp_free (vector);
6158 vector = next;
6159
6160 }
6161 else
6162 {
6163 VECTOR_UNMARK (vector);
6164 if (vector->header.size & PSEUDOVECTOR_FLAG)
6165 total_vector_size += PSEUDOVECTOR_SIZE_MASK & vector->header.size;
6166 else
6167 total_vector_size += vector->header.size;
6168 prev = vector, vector = vector->header.next.vector;
6169 }
6170 }
6171
6172 #ifdef GC_CHECK_STRING_BYTES
6173 if (!noninteractive)
6174 check_string_bytes (1);
6175 #endif
6176 }
6177
6178
6179
6180 \f
6181 /* Debugging aids. */
6182
6183 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
6184 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6185 This may be helpful in debugging Emacs's memory usage.
6186 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6187 (void)
6188 {
6189 Lisp_Object end;
6190
6191 XSETINT (end, (intptr_t) (char *) sbrk (0) / 1024);
6192
6193 return end;
6194 }
6195
6196 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
6197 doc: /* Return a list of counters that measure how much consing there has been.
6198 Each of these counters increments for a certain kind of object.
6199 The counters wrap around from the largest positive integer to zero.
6200 Garbage collection does not decrease them.
6201 The elements of the value are as follows:
6202 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6203 All are in units of 1 = one object consed
6204 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6205 objects consed.
6206 MISCS include overlays, markers, and some internal types.
6207 Frames, windows, buffers, and subprocesses count as vectors
6208 (but the contents of a buffer's text do not count here). */)
6209 (void)
6210 {
6211 Lisp_Object consed[8];
6212
6213 consed[0] = make_number (min (MOST_POSITIVE_FIXNUM, cons_cells_consed));
6214 consed[1] = make_number (min (MOST_POSITIVE_FIXNUM, floats_consed));
6215 consed[2] = make_number (min (MOST_POSITIVE_FIXNUM, vector_cells_consed));
6216 consed[3] = make_number (min (MOST_POSITIVE_FIXNUM, symbols_consed));
6217 consed[4] = make_number (min (MOST_POSITIVE_FIXNUM, string_chars_consed));
6218 consed[5] = make_number (min (MOST_POSITIVE_FIXNUM, misc_objects_consed));
6219 consed[6] = make_number (min (MOST_POSITIVE_FIXNUM, intervals_consed));
6220 consed[7] = make_number (min (MOST_POSITIVE_FIXNUM, strings_consed));
6221
6222 return Flist (8, consed);
6223 }
6224
6225 #ifdef ENABLE_CHECKING
6226 int suppress_checking;
6227
6228 void
6229 die (const char *msg, const char *file, int line)
6230 {
6231 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: %s\r\n",
6232 file, line, msg);
6233 abort ();
6234 }
6235 #endif
6236 \f
6237 /* Initialization */
6238
6239 void
6240 init_alloc_once (void)
6241 {
6242 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
6243 purebeg = PUREBEG;
6244 pure_size = PURESIZE;
6245 pure_bytes_used = 0;
6246 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
6247 pure_bytes_used_before_overflow = 0;
6248
6249 /* Initialize the list of free aligned blocks. */
6250 free_ablock = NULL;
6251
6252 #if GC_MARK_STACK || defined GC_MALLOC_CHECK
6253 mem_init ();
6254 Vdead = make_pure_string ("DEAD", 4, 4, 0);
6255 #endif
6256
6257 all_vectors = 0;
6258 ignore_warnings = 1;
6259 #ifdef DOUG_LEA_MALLOC
6260 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
6261 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
6262 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
6263 #endif
6264 init_strings ();
6265 init_cons ();
6266 init_symbol ();
6267 init_marker ();
6268 init_float ();
6269 init_intervals ();
6270 init_weak_hash_tables ();
6271
6272 #ifdef REL_ALLOC
6273 malloc_hysteresis = 32;
6274 #else
6275 malloc_hysteresis = 0;
6276 #endif
6277
6278 refill_memory_reserve ();
6279
6280 ignore_warnings = 0;
6281 gcprolist = 0;
6282 byte_stack_list = 0;
6283 staticidx = 0;
6284 consing_since_gc = 0;
6285 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
6286 gc_relative_threshold = 0;
6287 }
6288
6289 void
6290 init_alloc (void)
6291 {
6292 gcprolist = 0;
6293 byte_stack_list = 0;
6294 #if GC_MARK_STACK
6295 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
6296 setjmp_tested_p = longjmps_done = 0;
6297 #endif
6298 #endif
6299 Vgc_elapsed = make_float (0.0);
6300 gcs_done = 0;
6301 }
6302
6303 void
6304 syms_of_alloc (void)
6305 {
6306 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
6307 doc: /* *Number of bytes of consing between garbage collections.
6308 Garbage collection can happen automatically once this many bytes have been
6309 allocated since the last garbage collection. All data types count.
6310
6311 Garbage collection happens automatically only when `eval' is called.
6312
6313 By binding this temporarily to a large number, you can effectively
6314 prevent garbage collection during a part of the program.
6315 See also `gc-cons-percentage'. */);
6316
6317 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
6318 doc: /* *Portion of the heap used for allocation.
6319 Garbage collection can happen automatically once this portion of the heap
6320 has been allocated since the last garbage collection.
6321 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
6322 Vgc_cons_percentage = make_float (0.1);
6323
6324 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
6325 doc: /* Number of bytes of sharable Lisp data allocated so far. */);
6326
6327 DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
6328 doc: /* Number of cons cells that have been consed so far. */);
6329
6330 DEFVAR_INT ("floats-consed", floats_consed,
6331 doc: /* Number of floats that have been consed so far. */);
6332
6333 DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
6334 doc: /* Number of vector cells that have been consed so far. */);
6335
6336 DEFVAR_INT ("symbols-consed", symbols_consed,
6337 doc: /* Number of symbols that have been consed so far. */);
6338
6339 DEFVAR_INT ("string-chars-consed", string_chars_consed,
6340 doc: /* Number of string characters that have been consed so far. */);
6341
6342 DEFVAR_INT ("misc-objects-consed", misc_objects_consed,
6343 doc: /* Number of miscellaneous objects that have been consed so far. */);
6344
6345 DEFVAR_INT ("intervals-consed", intervals_consed,
6346 doc: /* Number of intervals that have been consed so far. */);
6347
6348 DEFVAR_INT ("strings-consed", strings_consed,
6349 doc: /* Number of strings that have been consed so far. */);
6350
6351 DEFVAR_LISP ("purify-flag", Vpurify_flag,
6352 doc: /* Non-nil means loading Lisp code in order to dump an executable.
6353 This means that certain objects should be allocated in shared (pure) space.
6354 It can also be set to a hash-table, in which case this table is used to
6355 do hash-consing of the objects allocated to pure space. */);
6356
6357 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
6358 doc: /* Non-nil means display messages at start and end of garbage collection. */);
6359 garbage_collection_messages = 0;
6360
6361 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
6362 doc: /* Hook run after garbage collection has finished. */);
6363 Vpost_gc_hook = Qnil;
6364 DEFSYM (Qpost_gc_hook, "post-gc-hook");
6365
6366 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
6367 doc: /* Precomputed `signal' argument for memory-full error. */);
6368 /* We build this in advance because if we wait until we need it, we might
6369 not be able to allocate the memory to hold it. */
6370 Vmemory_signal_data
6371 = pure_cons (Qerror,
6372 pure_cons (make_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"), Qnil));
6373
6374 DEFVAR_LISP ("memory-full", Vmemory_full,
6375 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
6376 Vmemory_full = Qnil;
6377
6378 DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
6379 DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
6380
6381 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
6382 doc: /* Accumulated time elapsed in garbage collections.
6383 The time is in seconds as a floating point value. */);
6384 DEFVAR_INT ("gcs-done", gcs_done,
6385 doc: /* Accumulated number of garbage collections done. */);
6386
6387 defsubr (&Scons);
6388 defsubr (&Slist);
6389 defsubr (&Svector);
6390 defsubr (&Smake_byte_code);
6391 defsubr (&Smake_list);
6392 defsubr (&Smake_vector);
6393 defsubr (&Smake_string);
6394 defsubr (&Smake_bool_vector);
6395 defsubr (&Smake_symbol);
6396 defsubr (&Smake_marker);
6397 defsubr (&Spurecopy);
6398 defsubr (&Sgarbage_collect);
6399 defsubr (&Smemory_limit);
6400 defsubr (&Smemory_use_counts);
6401
6402 #if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
6403 defsubr (&Sgc_status);
6404 #endif
6405 }