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