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