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