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