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