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