]> code.delx.au - gnu-emacs/blob - src/alloc.c
e1b0d2e4a6053c813829d1477d0a40e573e003de
[gnu-emacs] / src / alloc.c
1 /* Storage allocation and gc for GNU Emacs Lisp interpreter.
2
3 Copyright (C) 1985-1986, 1988, 1993-1995, 1997-2016 Free Software
4 Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21 #include <config.h>
22
23 #include <stdio.h>
24 #include <limits.h> /* For CHAR_BIT. */
25
26 #ifdef ENABLE_CHECKING
27 #include <signal.h> /* For SIGABRT. */
28 #endif
29
30 #ifdef HAVE_PTHREAD
31 #include <pthread.h>
32 #endif
33
34 #include "lisp.h"
35 #include "dispextern.h"
36 #include "intervals.h"
37 #include "puresize.h"
38 #include "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 if (nbytes)
2123 {
2124 memset (SDATA (val), c, nbytes);
2125 SDATA (val)[nbytes] = 0;
2126 }
2127 }
2128 else
2129 {
2130 unsigned char str[MAX_MULTIBYTE_LENGTH];
2131 ptrdiff_t len = CHAR_STRING (c, str);
2132 EMACS_INT string_len = XINT (length);
2133 unsigned char *p, *beg, *end;
2134
2135 if (INT_MULTIPLY_WRAPV (len, string_len, &nbytes))
2136 string_overflow ();
2137 val = make_uninit_multibyte_string (string_len, nbytes);
2138 for (beg = SDATA (val), p = beg, end = beg + nbytes; p < end; p += len)
2139 {
2140 /* First time we just copy `str' to the data of `val'. */
2141 if (p == beg)
2142 memcpy (p, str, len);
2143 else
2144 {
2145 /* Next time we copy largest possible chunk from
2146 initialized to uninitialized part of `val'. */
2147 len = min (p - beg, end - p);
2148 memcpy (p, beg, len);
2149 }
2150 }
2151 if (nbytes)
2152 *p = 0;
2153 }
2154
2155 return val;
2156 }
2157
2158 /* Fill A with 1 bits if INIT is non-nil, and with 0 bits otherwise.
2159 Return A. */
2160
2161 Lisp_Object
2162 bool_vector_fill (Lisp_Object a, Lisp_Object init)
2163 {
2164 EMACS_INT nbits = bool_vector_size (a);
2165 if (0 < nbits)
2166 {
2167 unsigned char *data = bool_vector_uchar_data (a);
2168 int pattern = NILP (init) ? 0 : (1 << BOOL_VECTOR_BITS_PER_CHAR) - 1;
2169 ptrdiff_t nbytes = bool_vector_bytes (nbits);
2170 int last_mask = ~ (~0u << ((nbits - 1) % BOOL_VECTOR_BITS_PER_CHAR + 1));
2171 memset (data, pattern, nbytes - 1);
2172 data[nbytes - 1] = pattern & last_mask;
2173 }
2174 return a;
2175 }
2176
2177 /* Return a newly allocated, uninitialized bool vector of size NBITS. */
2178
2179 Lisp_Object
2180 make_uninit_bool_vector (EMACS_INT nbits)
2181 {
2182 Lisp_Object val;
2183 EMACS_INT words = bool_vector_words (nbits);
2184 EMACS_INT word_bytes = words * sizeof (bits_word);
2185 EMACS_INT needed_elements = ((bool_header_size - header_size + word_bytes
2186 + word_size - 1)
2187 / word_size);
2188 struct Lisp_Bool_Vector *p
2189 = (struct Lisp_Bool_Vector *) allocate_vector (needed_elements);
2190 XSETVECTOR (val, p);
2191 XSETPVECTYPESIZE (XVECTOR (val), PVEC_BOOL_VECTOR, 0, 0);
2192 p->size = nbits;
2193
2194 /* Clear padding at the end. */
2195 if (words)
2196 p->data[words - 1] = 0;
2197
2198 return val;
2199 }
2200
2201 DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
2202 doc: /* Return a new bool-vector of length LENGTH, using INIT for each element.
2203 LENGTH must be a number. INIT matters only in whether it is t or nil. */)
2204 (Lisp_Object length, Lisp_Object init)
2205 {
2206 Lisp_Object val;
2207
2208 CHECK_NATNUM (length);
2209 val = make_uninit_bool_vector (XFASTINT (length));
2210 return bool_vector_fill (val, init);
2211 }
2212
2213 DEFUN ("bool-vector", Fbool_vector, Sbool_vector, 0, MANY, 0,
2214 doc: /* Return a new bool-vector with specified arguments as elements.
2215 Any number of arguments, even zero arguments, are allowed.
2216 usage: (bool-vector &rest OBJECTS) */)
2217 (ptrdiff_t nargs, Lisp_Object *args)
2218 {
2219 ptrdiff_t i;
2220 Lisp_Object vector;
2221
2222 vector = make_uninit_bool_vector (nargs);
2223 for (i = 0; i < nargs; i++)
2224 bool_vector_set (vector, i, !NILP (args[i]));
2225
2226 return vector;
2227 }
2228
2229 /* Make a string from NBYTES bytes at CONTENTS, and compute the number
2230 of characters from the contents. This string may be unibyte or
2231 multibyte, depending on the contents. */
2232
2233 Lisp_Object
2234 make_string (const char *contents, ptrdiff_t nbytes)
2235 {
2236 register Lisp_Object val;
2237 ptrdiff_t nchars, multibyte_nbytes;
2238
2239 parse_str_as_multibyte ((const unsigned char *) contents, nbytes,
2240 &nchars, &multibyte_nbytes);
2241 if (nbytes == nchars || nbytes != multibyte_nbytes)
2242 /* CONTENTS contains no multibyte sequences or contains an invalid
2243 multibyte sequence. We must make unibyte string. */
2244 val = make_unibyte_string (contents, nbytes);
2245 else
2246 val = make_multibyte_string (contents, nchars, nbytes);
2247 return val;
2248 }
2249
2250 /* Make a unibyte string from LENGTH bytes at CONTENTS. */
2251
2252 Lisp_Object
2253 make_unibyte_string (const char *contents, ptrdiff_t length)
2254 {
2255 register Lisp_Object val;
2256 val = make_uninit_string (length);
2257 memcpy (SDATA (val), contents, length);
2258 return val;
2259 }
2260
2261
2262 /* Make a multibyte string from NCHARS characters occupying NBYTES
2263 bytes at CONTENTS. */
2264
2265 Lisp_Object
2266 make_multibyte_string (const char *contents,
2267 ptrdiff_t nchars, ptrdiff_t nbytes)
2268 {
2269 register Lisp_Object val;
2270 val = make_uninit_multibyte_string (nchars, nbytes);
2271 memcpy (SDATA (val), contents, nbytes);
2272 return val;
2273 }
2274
2275
2276 /* Make a string from NCHARS characters occupying NBYTES bytes at
2277 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
2278
2279 Lisp_Object
2280 make_string_from_bytes (const char *contents,
2281 ptrdiff_t nchars, ptrdiff_t nbytes)
2282 {
2283 register Lisp_Object val;
2284 val = make_uninit_multibyte_string (nchars, nbytes);
2285 memcpy (SDATA (val), contents, nbytes);
2286 if (SBYTES (val) == SCHARS (val))
2287 STRING_SET_UNIBYTE (val);
2288 return val;
2289 }
2290
2291
2292 /* Make a string from NCHARS characters occupying NBYTES bytes at
2293 CONTENTS. The argument MULTIBYTE controls whether to label the
2294 string as multibyte. If NCHARS is negative, it counts the number of
2295 characters by itself. */
2296
2297 Lisp_Object
2298 make_specified_string (const char *contents,
2299 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
2300 {
2301 Lisp_Object val;
2302
2303 if (nchars < 0)
2304 {
2305 if (multibyte)
2306 nchars = multibyte_chars_in_text ((const unsigned char *) contents,
2307 nbytes);
2308 else
2309 nchars = nbytes;
2310 }
2311 val = make_uninit_multibyte_string (nchars, nbytes);
2312 memcpy (SDATA (val), contents, nbytes);
2313 if (!multibyte)
2314 STRING_SET_UNIBYTE (val);
2315 return val;
2316 }
2317
2318
2319 /* Return a unibyte Lisp_String set up to hold LENGTH characters
2320 occupying LENGTH bytes. */
2321
2322 Lisp_Object
2323 make_uninit_string (EMACS_INT length)
2324 {
2325 Lisp_Object val;
2326
2327 if (!length)
2328 return empty_unibyte_string;
2329 val = make_uninit_multibyte_string (length, length);
2330 STRING_SET_UNIBYTE (val);
2331 return val;
2332 }
2333
2334
2335 /* Return a multibyte Lisp_String set up to hold NCHARS characters
2336 which occupy NBYTES bytes. */
2337
2338 Lisp_Object
2339 make_uninit_multibyte_string (EMACS_INT nchars, EMACS_INT nbytes)
2340 {
2341 Lisp_Object string;
2342 struct Lisp_String *s;
2343
2344 if (nchars < 0)
2345 emacs_abort ();
2346 if (!nbytes)
2347 return empty_multibyte_string;
2348
2349 s = allocate_string ();
2350 s->intervals = NULL;
2351 allocate_string_data (s, nchars, nbytes);
2352 XSETSTRING (string, s);
2353 string_chars_consed += nbytes;
2354 return string;
2355 }
2356
2357 /* Print arguments to BUF according to a FORMAT, then return
2358 a Lisp_String initialized with the data from BUF. */
2359
2360 Lisp_Object
2361 make_formatted_string (char *buf, const char *format, ...)
2362 {
2363 va_list ap;
2364 int length;
2365
2366 va_start (ap, format);
2367 length = vsprintf (buf, format, ap);
2368 va_end (ap);
2369 return make_string (buf, length);
2370 }
2371
2372 \f
2373 /***********************************************************************
2374 Float Allocation
2375 ***********************************************************************/
2376
2377 /* We store float cells inside of float_blocks, allocating a new
2378 float_block with malloc whenever necessary. Float cells reclaimed
2379 by GC are put on a free list to be reallocated before allocating
2380 any new float cells from the latest float_block. */
2381
2382 #define FLOAT_BLOCK_SIZE \
2383 (((BLOCK_BYTES - sizeof (struct float_block *) \
2384 /* The compiler might add padding at the end. */ \
2385 - (sizeof (struct Lisp_Float) - sizeof (bits_word))) * CHAR_BIT) \
2386 / (sizeof (struct Lisp_Float) * CHAR_BIT + 1))
2387
2388 #define GETMARKBIT(block,n) \
2389 (((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2390 >> ((n) % BITS_PER_BITS_WORD)) \
2391 & 1)
2392
2393 #define SETMARKBIT(block,n) \
2394 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2395 |= (bits_word) 1 << ((n) % BITS_PER_BITS_WORD))
2396
2397 #define UNSETMARKBIT(block,n) \
2398 ((block)->gcmarkbits[(n) / BITS_PER_BITS_WORD] \
2399 &= ~((bits_word) 1 << ((n) % BITS_PER_BITS_WORD)))
2400
2401 #define FLOAT_BLOCK(fptr) \
2402 ((struct float_block *) (((uintptr_t) (fptr)) & ~(BLOCK_ALIGN - 1)))
2403
2404 #define FLOAT_INDEX(fptr) \
2405 ((((uintptr_t) (fptr)) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Float))
2406
2407 struct float_block
2408 {
2409 /* Place `floats' at the beginning, to ease up FLOAT_INDEX's job. */
2410 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
2411 bits_word gcmarkbits[1 + FLOAT_BLOCK_SIZE / BITS_PER_BITS_WORD];
2412 struct float_block *next;
2413 };
2414
2415 #define FLOAT_MARKED_P(fptr) \
2416 GETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2417
2418 #define FLOAT_MARK(fptr) \
2419 SETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2420
2421 #define FLOAT_UNMARK(fptr) \
2422 UNSETMARKBIT (FLOAT_BLOCK (fptr), FLOAT_INDEX ((fptr)))
2423
2424 /* Current float_block. */
2425
2426 static struct float_block *float_block;
2427
2428 /* Index of first unused Lisp_Float in the current float_block. */
2429
2430 static int float_block_index = FLOAT_BLOCK_SIZE;
2431
2432 /* Free-list of Lisp_Floats. */
2433
2434 static struct Lisp_Float *float_free_list;
2435
2436 /* Return a new float object with value FLOAT_VALUE. */
2437
2438 Lisp_Object
2439 make_float (double float_value)
2440 {
2441 register Lisp_Object val;
2442
2443 MALLOC_BLOCK_INPUT;
2444
2445 if (float_free_list)
2446 {
2447 /* We use the data field for chaining the free list
2448 so that we won't use the same field that has the mark bit. */
2449 XSETFLOAT (val, float_free_list);
2450 float_free_list = float_free_list->u.chain;
2451 }
2452 else
2453 {
2454 if (float_block_index == FLOAT_BLOCK_SIZE)
2455 {
2456 struct float_block *new
2457 = lisp_align_malloc (sizeof *new, MEM_TYPE_FLOAT);
2458 new->next = float_block;
2459 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2460 float_block = new;
2461 float_block_index = 0;
2462 total_free_floats += FLOAT_BLOCK_SIZE;
2463 }
2464 XSETFLOAT (val, &float_block->floats[float_block_index]);
2465 float_block_index++;
2466 }
2467
2468 MALLOC_UNBLOCK_INPUT;
2469
2470 XFLOAT_INIT (val, float_value);
2471 eassert (!FLOAT_MARKED_P (XFLOAT (val)));
2472 consing_since_gc += sizeof (struct Lisp_Float);
2473 floats_consed++;
2474 total_free_floats--;
2475 return val;
2476 }
2477
2478
2479 \f
2480 /***********************************************************************
2481 Cons Allocation
2482 ***********************************************************************/
2483
2484 /* We store cons cells inside of cons_blocks, allocating a new
2485 cons_block with malloc whenever necessary. Cons cells reclaimed by
2486 GC are put on a free list to be reallocated before allocating
2487 any new cons cells from the latest cons_block. */
2488
2489 #define CONS_BLOCK_SIZE \
2490 (((BLOCK_BYTES - sizeof (struct cons_block *) \
2491 /* The compiler might add padding at the end. */ \
2492 - (sizeof (struct Lisp_Cons) - sizeof (bits_word))) * CHAR_BIT) \
2493 / (sizeof (struct Lisp_Cons) * CHAR_BIT + 1))
2494
2495 #define CONS_BLOCK(fptr) \
2496 ((struct cons_block *) ((uintptr_t) (fptr) & ~(BLOCK_ALIGN - 1)))
2497
2498 #define CONS_INDEX(fptr) \
2499 (((uintptr_t) (fptr) & (BLOCK_ALIGN - 1)) / sizeof (struct Lisp_Cons))
2500
2501 struct cons_block
2502 {
2503 /* Place `conses' at the beginning, to ease up CONS_INDEX's job. */
2504 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
2505 bits_word gcmarkbits[1 + CONS_BLOCK_SIZE / BITS_PER_BITS_WORD];
2506 struct cons_block *next;
2507 };
2508
2509 #define CONS_MARKED_P(fptr) \
2510 GETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2511
2512 #define CONS_MARK(fptr) \
2513 SETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2514
2515 #define CONS_UNMARK(fptr) \
2516 UNSETMARKBIT (CONS_BLOCK (fptr), CONS_INDEX ((fptr)))
2517
2518 /* Current cons_block. */
2519
2520 static struct cons_block *cons_block;
2521
2522 /* Index of first unused Lisp_Cons in the current block. */
2523
2524 static int cons_block_index = CONS_BLOCK_SIZE;
2525
2526 /* Free-list of Lisp_Cons structures. */
2527
2528 static struct Lisp_Cons *cons_free_list;
2529
2530 /* Explicitly free a cons cell by putting it on the free-list. */
2531
2532 void
2533 free_cons (struct Lisp_Cons *ptr)
2534 {
2535 ptr->u.chain = cons_free_list;
2536 ptr->car = Vdead;
2537 cons_free_list = ptr;
2538 consing_since_gc -= sizeof *ptr;
2539 total_free_conses++;
2540 }
2541
2542 DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2543 doc: /* Create a new cons, give it CAR and CDR as components, and return it. */)
2544 (Lisp_Object car, Lisp_Object cdr)
2545 {
2546 register Lisp_Object val;
2547
2548 MALLOC_BLOCK_INPUT;
2549
2550 if (cons_free_list)
2551 {
2552 /* We use the cdr for chaining the free list
2553 so that we won't use the same field that has the mark bit. */
2554 XSETCONS (val, cons_free_list);
2555 cons_free_list = cons_free_list->u.chain;
2556 }
2557 else
2558 {
2559 if (cons_block_index == CONS_BLOCK_SIZE)
2560 {
2561 struct cons_block *new
2562 = lisp_align_malloc (sizeof *new, MEM_TYPE_CONS);
2563 memset (new->gcmarkbits, 0, sizeof new->gcmarkbits);
2564 new->next = cons_block;
2565 cons_block = new;
2566 cons_block_index = 0;
2567 total_free_conses += CONS_BLOCK_SIZE;
2568 }
2569 XSETCONS (val, &cons_block->conses[cons_block_index]);
2570 cons_block_index++;
2571 }
2572
2573 MALLOC_UNBLOCK_INPUT;
2574
2575 XSETCAR (val, car);
2576 XSETCDR (val, cdr);
2577 eassert (!CONS_MARKED_P (XCONS (val)));
2578 consing_since_gc += sizeof (struct Lisp_Cons);
2579 total_free_conses--;
2580 cons_cells_consed++;
2581 return val;
2582 }
2583
2584 #ifdef GC_CHECK_CONS_LIST
2585 /* Get an error now if there's any junk in the cons free list. */
2586 void
2587 check_cons_list (void)
2588 {
2589 struct Lisp_Cons *tail = cons_free_list;
2590
2591 while (tail)
2592 tail = tail->u.chain;
2593 }
2594 #endif
2595
2596 /* Make a list of 1, 2, 3, 4 or 5 specified objects. */
2597
2598 Lisp_Object
2599 list1 (Lisp_Object arg1)
2600 {
2601 return Fcons (arg1, Qnil);
2602 }
2603
2604 Lisp_Object
2605 list2 (Lisp_Object arg1, Lisp_Object arg2)
2606 {
2607 return Fcons (arg1, Fcons (arg2, Qnil));
2608 }
2609
2610
2611 Lisp_Object
2612 list3 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3)
2613 {
2614 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2615 }
2616
2617
2618 Lisp_Object
2619 list4 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4)
2620 {
2621 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2622 }
2623
2624
2625 Lisp_Object
2626 list5 (Lisp_Object arg1, Lisp_Object arg2, Lisp_Object arg3, Lisp_Object arg4, Lisp_Object arg5)
2627 {
2628 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2629 Fcons (arg5, Qnil)))));
2630 }
2631
2632 /* Make a list of COUNT Lisp_Objects, where ARG is the
2633 first one. Allocate conses from pure space if TYPE
2634 is CONSTYPE_PURE, or allocate as usual if type is CONSTYPE_HEAP. */
2635
2636 Lisp_Object
2637 listn (enum constype type, ptrdiff_t count, Lisp_Object arg, ...)
2638 {
2639 Lisp_Object (*cons) (Lisp_Object, Lisp_Object);
2640 switch (type)
2641 {
2642 case CONSTYPE_PURE: cons = pure_cons; break;
2643 case CONSTYPE_HEAP: cons = Fcons; break;
2644 default: emacs_abort ();
2645 }
2646
2647 eassume (0 < count);
2648 Lisp_Object val = cons (arg, Qnil);
2649 Lisp_Object tail = val;
2650
2651 va_list ap;
2652 va_start (ap, arg);
2653 for (ptrdiff_t i = 1; i < count; i++)
2654 {
2655 Lisp_Object elem = cons (va_arg (ap, Lisp_Object), Qnil);
2656 XSETCDR (tail, elem);
2657 tail = elem;
2658 }
2659 va_end (ap);
2660
2661 return val;
2662 }
2663
2664 DEFUN ("list", Flist, Slist, 0, MANY, 0,
2665 doc: /* Return a newly created list with specified arguments as elements.
2666 Any number of arguments, even zero arguments, are allowed.
2667 usage: (list &rest OBJECTS) */)
2668 (ptrdiff_t nargs, Lisp_Object *args)
2669 {
2670 register Lisp_Object val;
2671 val = Qnil;
2672
2673 while (nargs > 0)
2674 {
2675 nargs--;
2676 val = Fcons (args[nargs], val);
2677 }
2678 return val;
2679 }
2680
2681
2682 DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2683 doc: /* Return a newly created list of length LENGTH, with each element being INIT. */)
2684 (register Lisp_Object length, Lisp_Object init)
2685 {
2686 register Lisp_Object val;
2687 register EMACS_INT size;
2688
2689 CHECK_NATNUM (length);
2690 size = XFASTINT (length);
2691
2692 val = Qnil;
2693 while (size > 0)
2694 {
2695 val = Fcons (init, val);
2696 --size;
2697
2698 if (size > 0)
2699 {
2700 val = Fcons (init, val);
2701 --size;
2702
2703 if (size > 0)
2704 {
2705 val = Fcons (init, val);
2706 --size;
2707
2708 if (size > 0)
2709 {
2710 val = Fcons (init, val);
2711 --size;
2712
2713 if (size > 0)
2714 {
2715 val = Fcons (init, val);
2716 --size;
2717 }
2718 }
2719 }
2720 }
2721
2722 QUIT;
2723 }
2724
2725 return val;
2726 }
2727
2728
2729 \f
2730 /***********************************************************************
2731 Vector Allocation
2732 ***********************************************************************/
2733
2734 /* Sometimes a vector's contents are merely a pointer internally used
2735 in vector allocation code. On the rare platforms where a null
2736 pointer cannot be tagged, represent it with a Lisp 0.
2737 Usually you don't want to touch this. */
2738
2739 static struct Lisp_Vector *
2740 next_vector (struct Lisp_Vector *v)
2741 {
2742 return XUNTAG (v->contents[0], Lisp_Int0);
2743 }
2744
2745 static void
2746 set_next_vector (struct Lisp_Vector *v, struct Lisp_Vector *p)
2747 {
2748 v->contents[0] = make_lisp_ptr (p, Lisp_Int0);
2749 }
2750
2751 /* This value is balanced well enough to avoid too much internal overhead
2752 for the most common cases; it's not required to be a power of two, but
2753 it's expected to be a mult-of-ROUNDUP_SIZE (see below). */
2754
2755 #define VECTOR_BLOCK_SIZE 4096
2756
2757 enum
2758 {
2759 /* Alignment of struct Lisp_Vector objects. */
2760 vector_alignment = COMMON_MULTIPLE (ALIGNOF_STRUCT_LISP_VECTOR,
2761 GCALIGNMENT),
2762
2763 /* Vector size requests are a multiple of this. */
2764 roundup_size = COMMON_MULTIPLE (vector_alignment, word_size)
2765 };
2766
2767 /* Verify assumptions described above. */
2768 verify ((VECTOR_BLOCK_SIZE % roundup_size) == 0);
2769 verify (VECTOR_BLOCK_SIZE <= (1 << PSEUDOVECTOR_SIZE_BITS));
2770
2771 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at compile time. */
2772 #define vroundup_ct(x) ROUNDUP (x, roundup_size)
2773 /* Round up X to nearest mult-of-ROUNDUP_SIZE --- use at runtime. */
2774 #define vroundup(x) (eassume ((x) >= 0), vroundup_ct (x))
2775
2776 /* Rounding helps to maintain alignment constraints if USE_LSB_TAG. */
2777
2778 #define VECTOR_BLOCK_BYTES (VECTOR_BLOCK_SIZE - vroundup_ct (sizeof (void *)))
2779
2780 /* Size of the minimal vector allocated from block. */
2781
2782 #define VBLOCK_BYTES_MIN vroundup_ct (header_size + sizeof (Lisp_Object))
2783
2784 /* Size of the largest vector allocated from block. */
2785
2786 #define VBLOCK_BYTES_MAX \
2787 vroundup ((VECTOR_BLOCK_BYTES / 2) - word_size)
2788
2789 /* We maintain one free list for each possible block-allocated
2790 vector size, and this is the number of free lists we have. */
2791
2792 #define VECTOR_MAX_FREE_LIST_INDEX \
2793 ((VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN) / roundup_size + 1)
2794
2795 /* Common shortcut to advance vector pointer over a block data. */
2796
2797 #define ADVANCE(v, nbytes) ((struct Lisp_Vector *) ((char *) (v) + (nbytes)))
2798
2799 /* Common shortcut to calculate NBYTES-vector index in VECTOR_FREE_LISTS. */
2800
2801 #define VINDEX(nbytes) (((nbytes) - VBLOCK_BYTES_MIN) / roundup_size)
2802
2803 /* Common shortcut to setup vector on a free list. */
2804
2805 #define SETUP_ON_FREE_LIST(v, nbytes, tmp) \
2806 do { \
2807 (tmp) = ((nbytes - header_size) / word_size); \
2808 XSETPVECTYPESIZE (v, PVEC_FREE, 0, (tmp)); \
2809 eassert ((nbytes) % roundup_size == 0); \
2810 (tmp) = VINDEX (nbytes); \
2811 eassert ((tmp) < VECTOR_MAX_FREE_LIST_INDEX); \
2812 set_next_vector (v, vector_free_lists[tmp]); \
2813 vector_free_lists[tmp] = (v); \
2814 total_free_vector_slots += (nbytes) / word_size; \
2815 } while (0)
2816
2817 /* This internal type is used to maintain the list of large vectors
2818 which are allocated at their own, e.g. outside of vector blocks.
2819
2820 struct large_vector itself cannot contain a struct Lisp_Vector, as
2821 the latter contains a flexible array member and C99 does not allow
2822 such structs to be nested. Instead, each struct large_vector
2823 object LV is followed by a struct Lisp_Vector, which is at offset
2824 large_vector_offset from LV, and whose address is therefore
2825 large_vector_vec (&LV). */
2826
2827 struct large_vector
2828 {
2829 struct large_vector *next;
2830 };
2831
2832 enum
2833 {
2834 large_vector_offset = ROUNDUP (sizeof (struct large_vector), vector_alignment)
2835 };
2836
2837 static struct Lisp_Vector *
2838 large_vector_vec (struct large_vector *p)
2839 {
2840 return (struct Lisp_Vector *) ((char *) p + large_vector_offset);
2841 }
2842
2843 /* This internal type is used to maintain an underlying storage
2844 for small vectors. */
2845
2846 struct vector_block
2847 {
2848 char data[VECTOR_BLOCK_BYTES];
2849 struct vector_block *next;
2850 };
2851
2852 /* Chain of vector blocks. */
2853
2854 static struct vector_block *vector_blocks;
2855
2856 /* Vector free lists, where NTH item points to a chain of free
2857 vectors of the same NBYTES size, so NTH == VINDEX (NBYTES). */
2858
2859 static struct Lisp_Vector *vector_free_lists[VECTOR_MAX_FREE_LIST_INDEX];
2860
2861 /* Singly-linked list of large vectors. */
2862
2863 static struct large_vector *large_vectors;
2864
2865 /* The only vector with 0 slots, allocated from pure space. */
2866
2867 Lisp_Object zero_vector;
2868
2869 /* Number of live vectors. */
2870
2871 static EMACS_INT total_vectors;
2872
2873 /* Total size of live and free vectors, in Lisp_Object units. */
2874
2875 static EMACS_INT total_vector_slots, total_free_vector_slots;
2876
2877 /* Get a new vector block. */
2878
2879 static struct vector_block *
2880 allocate_vector_block (void)
2881 {
2882 struct vector_block *block = xmalloc (sizeof *block);
2883
2884 #ifndef GC_MALLOC_CHECK
2885 mem_insert (block->data, block->data + VECTOR_BLOCK_BYTES,
2886 MEM_TYPE_VECTOR_BLOCK);
2887 #endif
2888
2889 block->next = vector_blocks;
2890 vector_blocks = block;
2891 return block;
2892 }
2893
2894 /* Called once to initialize vector allocation. */
2895
2896 static void
2897 init_vectors (void)
2898 {
2899 zero_vector = make_pure_vector (0);
2900 }
2901
2902 /* Allocate vector from a vector block. */
2903
2904 static struct Lisp_Vector *
2905 allocate_vector_from_block (size_t nbytes)
2906 {
2907 struct Lisp_Vector *vector;
2908 struct vector_block *block;
2909 size_t index, restbytes;
2910
2911 eassert (VBLOCK_BYTES_MIN <= nbytes && nbytes <= VBLOCK_BYTES_MAX);
2912 eassert (nbytes % roundup_size == 0);
2913
2914 /* First, try to allocate from a free list
2915 containing vectors of the requested size. */
2916 index = VINDEX (nbytes);
2917 if (vector_free_lists[index])
2918 {
2919 vector = vector_free_lists[index];
2920 vector_free_lists[index] = next_vector (vector);
2921 total_free_vector_slots -= nbytes / word_size;
2922 return vector;
2923 }
2924
2925 /* Next, check free lists containing larger vectors. Since
2926 we will split the result, we should have remaining space
2927 large enough to use for one-slot vector at least. */
2928 for (index = VINDEX (nbytes + VBLOCK_BYTES_MIN);
2929 index < VECTOR_MAX_FREE_LIST_INDEX; index++)
2930 if (vector_free_lists[index])
2931 {
2932 /* This vector is larger than requested. */
2933 vector = vector_free_lists[index];
2934 vector_free_lists[index] = next_vector (vector);
2935 total_free_vector_slots -= nbytes / word_size;
2936
2937 /* Excess bytes are used for the smaller vector,
2938 which should be set on an appropriate free list. */
2939 restbytes = index * roundup_size + VBLOCK_BYTES_MIN - nbytes;
2940 eassert (restbytes % roundup_size == 0);
2941 SETUP_ON_FREE_LIST (ADVANCE (vector, nbytes), restbytes, index);
2942 return vector;
2943 }
2944
2945 /* Finally, need a new vector block. */
2946 block = allocate_vector_block ();
2947
2948 /* New vector will be at the beginning of this block. */
2949 vector = (struct Lisp_Vector *) block->data;
2950
2951 /* If the rest of space from this block is large enough
2952 for one-slot vector at least, set up it on a free list. */
2953 restbytes = VECTOR_BLOCK_BYTES - nbytes;
2954 if (restbytes >= VBLOCK_BYTES_MIN)
2955 {
2956 eassert (restbytes % roundup_size == 0);
2957 SETUP_ON_FREE_LIST (ADVANCE (vector, nbytes), restbytes, index);
2958 }
2959 return vector;
2960 }
2961
2962 /* Nonzero if VECTOR pointer is valid pointer inside BLOCK. */
2963
2964 #define VECTOR_IN_BLOCK(vector, block) \
2965 ((char *) (vector) <= (block)->data \
2966 + VECTOR_BLOCK_BYTES - VBLOCK_BYTES_MIN)
2967
2968 /* Return the memory footprint of V in bytes. */
2969
2970 static ptrdiff_t
2971 vector_nbytes (struct Lisp_Vector *v)
2972 {
2973 ptrdiff_t size = v->header.size & ~ARRAY_MARK_FLAG;
2974 ptrdiff_t nwords;
2975
2976 if (size & PSEUDOVECTOR_FLAG)
2977 {
2978 if (PSEUDOVECTOR_TYPEP (&v->header, PVEC_BOOL_VECTOR))
2979 {
2980 struct Lisp_Bool_Vector *bv = (struct Lisp_Bool_Vector *) v;
2981 ptrdiff_t word_bytes = (bool_vector_words (bv->size)
2982 * sizeof (bits_word));
2983 ptrdiff_t boolvec_bytes = bool_header_size + word_bytes;
2984 verify (header_size <= bool_header_size);
2985 nwords = (boolvec_bytes - header_size + word_size - 1) / word_size;
2986 }
2987 else
2988 nwords = ((size & PSEUDOVECTOR_SIZE_MASK)
2989 + ((size & PSEUDOVECTOR_REST_MASK)
2990 >> PSEUDOVECTOR_SIZE_BITS));
2991 }
2992 else
2993 nwords = size;
2994 return vroundup (header_size + word_size * nwords);
2995 }
2996
2997 /* Release extra resources still in use by VECTOR, which may be any
2998 vector-like object. For now, this is used just to free data in
2999 font objects. */
3000
3001 static void
3002 cleanup_vector (struct Lisp_Vector *vector)
3003 {
3004 detect_suspicious_free (vector);
3005 if (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FONT)
3006 && ((vector->header.size & PSEUDOVECTOR_SIZE_MASK)
3007 == FONT_OBJECT_MAX))
3008 {
3009 struct font_driver *drv = ((struct font *) vector)->driver;
3010
3011 /* The font driver might sometimes be NULL, e.g. if Emacs was
3012 interrupted before it had time to set it up. */
3013 if (drv)
3014 {
3015 /* Attempt to catch subtle bugs like Bug#16140. */
3016 eassert (valid_font_driver (drv));
3017 drv->close ((struct font *) vector);
3018 }
3019 }
3020 }
3021
3022 /* Reclaim space used by unmarked vectors. */
3023
3024 NO_INLINE /* For better stack traces */
3025 static void
3026 sweep_vectors (void)
3027 {
3028 struct vector_block *block, **bprev = &vector_blocks;
3029 struct large_vector *lv, **lvprev = &large_vectors;
3030 struct Lisp_Vector *vector, *next;
3031
3032 total_vectors = total_vector_slots = total_free_vector_slots = 0;
3033 memset (vector_free_lists, 0, sizeof (vector_free_lists));
3034
3035 /* Looking through vector blocks. */
3036
3037 for (block = vector_blocks; block; block = *bprev)
3038 {
3039 bool free_this_block = 0;
3040 ptrdiff_t nbytes;
3041
3042 for (vector = (struct Lisp_Vector *) block->data;
3043 VECTOR_IN_BLOCK (vector, block); vector = next)
3044 {
3045 if (VECTOR_MARKED_P (vector))
3046 {
3047 VECTOR_UNMARK (vector);
3048 total_vectors++;
3049 nbytes = vector_nbytes (vector);
3050 total_vector_slots += nbytes / word_size;
3051 next = ADVANCE (vector, nbytes);
3052 }
3053 else
3054 {
3055 ptrdiff_t total_bytes;
3056
3057 cleanup_vector (vector);
3058 nbytes = vector_nbytes (vector);
3059 total_bytes = nbytes;
3060 next = ADVANCE (vector, nbytes);
3061
3062 /* While NEXT is not marked, try to coalesce with VECTOR,
3063 thus making VECTOR of the largest possible size. */
3064
3065 while (VECTOR_IN_BLOCK (next, block))
3066 {
3067 if (VECTOR_MARKED_P (next))
3068 break;
3069 cleanup_vector (next);
3070 nbytes = vector_nbytes (next);
3071 total_bytes += nbytes;
3072 next = ADVANCE (next, nbytes);
3073 }
3074
3075 eassert (total_bytes % roundup_size == 0);
3076
3077 if (vector == (struct Lisp_Vector *) block->data
3078 && !VECTOR_IN_BLOCK (next, block))
3079 /* This block should be freed because all of its
3080 space was coalesced into the only free vector. */
3081 free_this_block = 1;
3082 else
3083 {
3084 size_t tmp;
3085 SETUP_ON_FREE_LIST (vector, total_bytes, tmp);
3086 }
3087 }
3088 }
3089
3090 if (free_this_block)
3091 {
3092 *bprev = block->next;
3093 #ifndef GC_MALLOC_CHECK
3094 mem_delete (mem_find (block->data));
3095 #endif
3096 xfree (block);
3097 }
3098 else
3099 bprev = &block->next;
3100 }
3101
3102 /* Sweep large vectors. */
3103
3104 for (lv = large_vectors; lv; lv = *lvprev)
3105 {
3106 vector = large_vector_vec (lv);
3107 if (VECTOR_MARKED_P (vector))
3108 {
3109 VECTOR_UNMARK (vector);
3110 total_vectors++;
3111 if (vector->header.size & PSEUDOVECTOR_FLAG)
3112 {
3113 /* All non-bool pseudovectors are small enough to be allocated
3114 from vector blocks. This code should be redesigned if some
3115 pseudovector type grows beyond VBLOCK_BYTES_MAX. */
3116 eassert (PSEUDOVECTOR_TYPEP (&vector->header, PVEC_BOOL_VECTOR));
3117 total_vector_slots += vector_nbytes (vector) / word_size;
3118 }
3119 else
3120 total_vector_slots
3121 += header_size / word_size + vector->header.size;
3122 lvprev = &lv->next;
3123 }
3124 else
3125 {
3126 *lvprev = lv->next;
3127 lisp_free (lv);
3128 }
3129 }
3130 }
3131
3132 /* Value is a pointer to a newly allocated Lisp_Vector structure
3133 with room for LEN Lisp_Objects. */
3134
3135 static struct Lisp_Vector *
3136 allocate_vectorlike (ptrdiff_t len)
3137 {
3138 struct Lisp_Vector *p;
3139
3140 MALLOC_BLOCK_INPUT;
3141
3142 if (len == 0)
3143 p = XVECTOR (zero_vector);
3144 else
3145 {
3146 size_t nbytes = header_size + len * word_size;
3147
3148 #ifdef DOUG_LEA_MALLOC
3149 if (!mmap_lisp_allowed_p ())
3150 mallopt (M_MMAP_MAX, 0);
3151 #endif
3152
3153 if (nbytes <= VBLOCK_BYTES_MAX)
3154 p = allocate_vector_from_block (vroundup (nbytes));
3155 else
3156 {
3157 struct large_vector *lv
3158 = lisp_malloc ((large_vector_offset + header_size
3159 + len * word_size),
3160 MEM_TYPE_VECTORLIKE);
3161 lv->next = large_vectors;
3162 large_vectors = lv;
3163 p = large_vector_vec (lv);
3164 }
3165
3166 #ifdef DOUG_LEA_MALLOC
3167 if (!mmap_lisp_allowed_p ())
3168 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
3169 #endif
3170
3171 if (find_suspicious_object_in_range (p, (char *) p + nbytes))
3172 emacs_abort ();
3173
3174 consing_since_gc += nbytes;
3175 vector_cells_consed += len;
3176 }
3177
3178 MALLOC_UNBLOCK_INPUT;
3179
3180 return p;
3181 }
3182
3183
3184 /* Allocate a vector with LEN slots. */
3185
3186 struct Lisp_Vector *
3187 allocate_vector (EMACS_INT len)
3188 {
3189 struct Lisp_Vector *v;
3190 ptrdiff_t nbytes_max = min (PTRDIFF_MAX, SIZE_MAX);
3191
3192 if (min ((nbytes_max - header_size) / word_size, MOST_POSITIVE_FIXNUM) < len)
3193 memory_full (SIZE_MAX);
3194 v = allocate_vectorlike (len);
3195 if (len)
3196 v->header.size = len;
3197 return v;
3198 }
3199
3200
3201 /* Allocate other vector-like structures. */
3202
3203 struct Lisp_Vector *
3204 allocate_pseudovector (int memlen, int lisplen,
3205 int zerolen, enum pvec_type tag)
3206 {
3207 struct Lisp_Vector *v = allocate_vectorlike (memlen);
3208
3209 /* Catch bogus values. */
3210 eassert (0 <= tag && tag <= PVEC_FONT);
3211 eassert (0 <= lisplen && lisplen <= zerolen && zerolen <= memlen);
3212 eassert (memlen - lisplen <= (1 << PSEUDOVECTOR_REST_BITS) - 1);
3213 eassert (lisplen <= (1 << PSEUDOVECTOR_SIZE_BITS) - 1);
3214
3215 /* Only the first LISPLEN slots will be traced normally by the GC. */
3216 memclear (v->contents, zerolen * word_size);
3217 XSETPVECTYPESIZE (v, tag, lisplen, memlen - lisplen);
3218 return v;
3219 }
3220
3221 struct buffer *
3222 allocate_buffer (void)
3223 {
3224 struct buffer *b = lisp_malloc (sizeof *b, MEM_TYPE_BUFFER);
3225
3226 BUFFER_PVEC_INIT (b);
3227 /* Put B on the chain of all buffers including killed ones. */
3228 b->next = all_buffers;
3229 all_buffers = b;
3230 /* Note that the rest fields of B are not initialized. */
3231 return b;
3232 }
3233
3234 DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
3235 doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
3236 See also the function `vector'. */)
3237 (register Lisp_Object length, Lisp_Object init)
3238 {
3239 Lisp_Object vector;
3240 register ptrdiff_t sizei;
3241 register ptrdiff_t i;
3242 register struct Lisp_Vector *p;
3243
3244 CHECK_NATNUM (length);
3245
3246 p = allocate_vector (XFASTINT (length));
3247 sizei = XFASTINT (length);
3248 for (i = 0; i < sizei; i++)
3249 p->contents[i] = init;
3250
3251 XSETVECTOR (vector, p);
3252 return vector;
3253 }
3254
3255 DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
3256 doc: /* Return a newly created vector with specified arguments as elements.
3257 Any number of arguments, even zero arguments, are allowed.
3258 usage: (vector &rest OBJECTS) */)
3259 (ptrdiff_t nargs, Lisp_Object *args)
3260 {
3261 ptrdiff_t i;
3262 register Lisp_Object val = make_uninit_vector (nargs);
3263 register struct Lisp_Vector *p = XVECTOR (val);
3264
3265 for (i = 0; i < nargs; i++)
3266 p->contents[i] = args[i];
3267 return val;
3268 }
3269
3270 void
3271 make_byte_code (struct Lisp_Vector *v)
3272 {
3273 /* Don't allow the global zero_vector to become a byte code object. */
3274 eassert (0 < v->header.size);
3275
3276 if (v->header.size > 1 && STRINGP (v->contents[1])
3277 && STRING_MULTIBYTE (v->contents[1]))
3278 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
3279 earlier because they produced a raw 8-bit string for byte-code
3280 and now such a byte-code string is loaded as multibyte while
3281 raw 8-bit characters converted to multibyte form. Thus, now we
3282 must convert them back to the original unibyte form. */
3283 v->contents[1] = Fstring_as_unibyte (v->contents[1]);
3284 XSETPVECTYPE (v, PVEC_COMPILED);
3285 }
3286
3287 DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
3288 doc: /* Create a byte-code object with specified arguments as elements.
3289 The arguments should be the ARGLIST, bytecode-string BYTE-CODE, constant
3290 vector CONSTANTS, maximum stack size DEPTH, (optional) DOCSTRING,
3291 and (optional) INTERACTIVE-SPEC.
3292 The first four arguments are required; at most six have any
3293 significance.
3294 The ARGLIST can be either like the one of `lambda', in which case the arguments
3295 will be dynamically bound before executing the byte code, or it can be an
3296 integer of the form NNNNNNNRMMMMMMM where the 7bit MMMMMMM specifies the
3297 minimum number of arguments, the 7-bit NNNNNNN specifies the maximum number
3298 of arguments (ignoring &rest) and the R bit specifies whether there is a &rest
3299 argument to catch the left-over arguments. If such an integer is used, the
3300 arguments will not be dynamically bound but will be instead pushed on the
3301 stack before executing the byte-code.
3302 usage: (make-byte-code ARGLIST BYTE-CODE CONSTANTS DEPTH &optional DOCSTRING INTERACTIVE-SPEC &rest ELEMENTS) */)
3303 (ptrdiff_t nargs, Lisp_Object *args)
3304 {
3305 ptrdiff_t i;
3306 register Lisp_Object val = make_uninit_vector (nargs);
3307 register struct Lisp_Vector *p = XVECTOR (val);
3308
3309 /* We used to purecopy everything here, if purify-flag was set. This worked
3310 OK for Emacs-23, but with Emacs-24's lexical binding code, it can be
3311 dangerous, since make-byte-code is used during execution to build
3312 closures, so any closure built during the preload phase would end up
3313 copied into pure space, including its free variables, which is sometimes
3314 just wasteful and other times plainly wrong (e.g. those free vars may want
3315 to be setcar'd). */
3316
3317 for (i = 0; i < nargs; i++)
3318 p->contents[i] = args[i];
3319 make_byte_code (p);
3320 XSETCOMPILED (val, p);
3321 return val;
3322 }
3323
3324
3325 \f
3326 /***********************************************************************
3327 Symbol Allocation
3328 ***********************************************************************/
3329
3330 /* Like struct Lisp_Symbol, but padded so that the size is a multiple
3331 of the required alignment. */
3332
3333 union aligned_Lisp_Symbol
3334 {
3335 struct Lisp_Symbol s;
3336 unsigned char c[(sizeof (struct Lisp_Symbol) + GCALIGNMENT - 1)
3337 & -GCALIGNMENT];
3338 };
3339
3340 /* Each symbol_block is just under 1020 bytes long, since malloc
3341 really allocates in units of powers of two and uses 4 bytes for its
3342 own overhead. */
3343
3344 #define SYMBOL_BLOCK_SIZE \
3345 ((1020 - sizeof (struct symbol_block *)) / sizeof (union aligned_Lisp_Symbol))
3346
3347 struct symbol_block
3348 {
3349 /* Place `symbols' first, to preserve alignment. */
3350 union aligned_Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
3351 struct symbol_block *next;
3352 };
3353
3354 /* Current symbol block and index of first unused Lisp_Symbol
3355 structure in it. */
3356
3357 static struct symbol_block *symbol_block;
3358 static int symbol_block_index = SYMBOL_BLOCK_SIZE;
3359 /* Pointer to the first symbol_block that contains pinned symbols.
3360 Tests for 24.4 showed that at dump-time, Emacs contains about 15K symbols,
3361 10K of which are pinned (and all but 250 of them are interned in obarray),
3362 whereas a "typical session" has in the order of 30K symbols.
3363 `symbol_block_pinned' lets mark_pinned_symbols scan only 15K symbols rather
3364 than 30K to find the 10K symbols we need to mark. */
3365 static struct symbol_block *symbol_block_pinned;
3366
3367 /* List of free symbols. */
3368
3369 static struct Lisp_Symbol *symbol_free_list;
3370
3371 static void
3372 set_symbol_name (Lisp_Object sym, Lisp_Object name)
3373 {
3374 XSYMBOL (sym)->name = name;
3375 }
3376
3377 void
3378 init_symbol (Lisp_Object val, Lisp_Object name)
3379 {
3380 struct Lisp_Symbol *p = XSYMBOL (val);
3381 set_symbol_name (val, name);
3382 set_symbol_plist (val, Qnil);
3383 p->redirect = SYMBOL_PLAINVAL;
3384 SET_SYMBOL_VAL (p, Qunbound);
3385 set_symbol_function (val, Qnil);
3386 set_symbol_next (val, NULL);
3387 p->gcmarkbit = false;
3388 p->interned = SYMBOL_UNINTERNED;
3389 p->constant = 0;
3390 p->declared_special = false;
3391 p->pinned = false;
3392 }
3393
3394 DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
3395 doc: /* Return a newly allocated uninterned symbol whose name is NAME.
3396 Its value is void, and its function definition and property list are nil. */)
3397 (Lisp_Object name)
3398 {
3399 Lisp_Object val;
3400
3401 CHECK_STRING (name);
3402
3403 MALLOC_BLOCK_INPUT;
3404
3405 if (symbol_free_list)
3406 {
3407 XSETSYMBOL (val, symbol_free_list);
3408 symbol_free_list = symbol_free_list->next;
3409 }
3410 else
3411 {
3412 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
3413 {
3414 struct symbol_block *new
3415 = lisp_malloc (sizeof *new, MEM_TYPE_SYMBOL);
3416 new->next = symbol_block;
3417 symbol_block = new;
3418 symbol_block_index = 0;
3419 total_free_symbols += SYMBOL_BLOCK_SIZE;
3420 }
3421 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index].s);
3422 symbol_block_index++;
3423 }
3424
3425 MALLOC_UNBLOCK_INPUT;
3426
3427 init_symbol (val, name);
3428 consing_since_gc += sizeof (struct Lisp_Symbol);
3429 symbols_consed++;
3430 total_free_symbols--;
3431 return val;
3432 }
3433
3434
3435 \f
3436 /***********************************************************************
3437 Marker (Misc) Allocation
3438 ***********************************************************************/
3439
3440 /* Like union Lisp_Misc, but padded so that its size is a multiple of
3441 the required alignment. */
3442
3443 union aligned_Lisp_Misc
3444 {
3445 union Lisp_Misc m;
3446 unsigned char c[(sizeof (union Lisp_Misc) + GCALIGNMENT - 1)
3447 & -GCALIGNMENT];
3448 };
3449
3450 /* Allocation of markers and other objects that share that structure.
3451 Works like allocation of conses. */
3452
3453 #define MARKER_BLOCK_SIZE \
3454 ((1020 - sizeof (struct marker_block *)) / sizeof (union aligned_Lisp_Misc))
3455
3456 struct marker_block
3457 {
3458 /* Place `markers' first, to preserve alignment. */
3459 union aligned_Lisp_Misc markers[MARKER_BLOCK_SIZE];
3460 struct marker_block *next;
3461 };
3462
3463 static struct marker_block *marker_block;
3464 static int marker_block_index = MARKER_BLOCK_SIZE;
3465
3466 static union Lisp_Misc *marker_free_list;
3467
3468 /* Return a newly allocated Lisp_Misc object of specified TYPE. */
3469
3470 static Lisp_Object
3471 allocate_misc (enum Lisp_Misc_Type type)
3472 {
3473 Lisp_Object val;
3474
3475 MALLOC_BLOCK_INPUT;
3476
3477 if (marker_free_list)
3478 {
3479 XSETMISC (val, marker_free_list);
3480 marker_free_list = marker_free_list->u_free.chain;
3481 }
3482 else
3483 {
3484 if (marker_block_index == MARKER_BLOCK_SIZE)
3485 {
3486 struct marker_block *new = lisp_malloc (sizeof *new, MEM_TYPE_MISC);
3487 new->next = marker_block;
3488 marker_block = new;
3489 marker_block_index = 0;
3490 total_free_markers += MARKER_BLOCK_SIZE;
3491 }
3492 XSETMISC (val, &marker_block->markers[marker_block_index].m);
3493 marker_block_index++;
3494 }
3495
3496 MALLOC_UNBLOCK_INPUT;
3497
3498 --total_free_markers;
3499 consing_since_gc += sizeof (union Lisp_Misc);
3500 misc_objects_consed++;
3501 XMISCANY (val)->type = type;
3502 XMISCANY (val)->gcmarkbit = 0;
3503 return val;
3504 }
3505
3506 /* Free a Lisp_Misc object. */
3507
3508 void
3509 free_misc (Lisp_Object misc)
3510 {
3511 XMISCANY (misc)->type = Lisp_Misc_Free;
3512 XMISC (misc)->u_free.chain = marker_free_list;
3513 marker_free_list = XMISC (misc);
3514 consing_since_gc -= sizeof (union Lisp_Misc);
3515 total_free_markers++;
3516 }
3517
3518 /* Verify properties of Lisp_Save_Value's representation
3519 that are assumed here and elsewhere. */
3520
3521 verify (SAVE_UNUSED == 0);
3522 verify (((SAVE_INTEGER | SAVE_POINTER | SAVE_FUNCPOINTER | SAVE_OBJECT)
3523 >> SAVE_SLOT_BITS)
3524 == 0);
3525
3526 /* Return Lisp_Save_Value objects for the various combinations
3527 that callers need. */
3528
3529 Lisp_Object
3530 make_save_int_int_int (ptrdiff_t a, ptrdiff_t b, ptrdiff_t c)
3531 {
3532 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3533 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3534 p->save_type = SAVE_TYPE_INT_INT_INT;
3535 p->data[0].integer = a;
3536 p->data[1].integer = b;
3537 p->data[2].integer = c;
3538 return val;
3539 }
3540
3541 Lisp_Object
3542 make_save_obj_obj_obj_obj (Lisp_Object a, Lisp_Object b, Lisp_Object c,
3543 Lisp_Object d)
3544 {
3545 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3546 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3547 p->save_type = SAVE_TYPE_OBJ_OBJ_OBJ_OBJ;
3548 p->data[0].object = a;
3549 p->data[1].object = b;
3550 p->data[2].object = c;
3551 p->data[3].object = d;
3552 return val;
3553 }
3554
3555 Lisp_Object
3556 make_save_ptr (void *a)
3557 {
3558 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3559 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3560 p->save_type = SAVE_POINTER;
3561 p->data[0].pointer = a;
3562 return val;
3563 }
3564
3565 Lisp_Object
3566 make_save_ptr_int (void *a, ptrdiff_t b)
3567 {
3568 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3569 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3570 p->save_type = SAVE_TYPE_PTR_INT;
3571 p->data[0].pointer = a;
3572 p->data[1].integer = b;
3573 return val;
3574 }
3575
3576 #if ! (defined USE_X_TOOLKIT || defined USE_GTK)
3577 Lisp_Object
3578 make_save_ptr_ptr (void *a, void *b)
3579 {
3580 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3581 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3582 p->save_type = SAVE_TYPE_PTR_PTR;
3583 p->data[0].pointer = a;
3584 p->data[1].pointer = b;
3585 return val;
3586 }
3587 #endif
3588
3589 Lisp_Object
3590 make_save_funcptr_ptr_obj (void (*a) (void), void *b, Lisp_Object c)
3591 {
3592 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3593 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3594 p->save_type = SAVE_TYPE_FUNCPTR_PTR_OBJ;
3595 p->data[0].funcpointer = a;
3596 p->data[1].pointer = b;
3597 p->data[2].object = c;
3598 return val;
3599 }
3600
3601 /* Return a Lisp_Save_Value object that represents an array A
3602 of N Lisp objects. */
3603
3604 Lisp_Object
3605 make_save_memory (Lisp_Object *a, ptrdiff_t n)
3606 {
3607 Lisp_Object val = allocate_misc (Lisp_Misc_Save_Value);
3608 struct Lisp_Save_Value *p = XSAVE_VALUE (val);
3609 p->save_type = SAVE_TYPE_MEMORY;
3610 p->data[0].pointer = a;
3611 p->data[1].integer = n;
3612 return val;
3613 }
3614
3615 /* Free a Lisp_Save_Value object. Do not use this function
3616 if SAVE contains pointer other than returned by xmalloc. */
3617
3618 void
3619 free_save_value (Lisp_Object save)
3620 {
3621 xfree (XSAVE_POINTER (save, 0));
3622 free_misc (save);
3623 }
3624
3625 /* Return a Lisp_Misc_Overlay object with specified START, END and PLIST. */
3626
3627 Lisp_Object
3628 build_overlay (Lisp_Object start, Lisp_Object end, Lisp_Object plist)
3629 {
3630 register Lisp_Object overlay;
3631
3632 overlay = allocate_misc (Lisp_Misc_Overlay);
3633 OVERLAY_START (overlay) = start;
3634 OVERLAY_END (overlay) = end;
3635 set_overlay_plist (overlay, plist);
3636 XOVERLAY (overlay)->next = NULL;
3637 return overlay;
3638 }
3639
3640 DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
3641 doc: /* Return a newly allocated marker which does not point at any place. */)
3642 (void)
3643 {
3644 register Lisp_Object val;
3645 register struct Lisp_Marker *p;
3646
3647 val = allocate_misc (Lisp_Misc_Marker);
3648 p = XMARKER (val);
3649 p->buffer = 0;
3650 p->bytepos = 0;
3651 p->charpos = 0;
3652 p->next = NULL;
3653 p->insertion_type = 0;
3654 p->need_adjustment = 0;
3655 return val;
3656 }
3657
3658 /* Return a newly allocated marker which points into BUF
3659 at character position CHARPOS and byte position BYTEPOS. */
3660
3661 Lisp_Object
3662 build_marker (struct buffer *buf, ptrdiff_t charpos, ptrdiff_t bytepos)
3663 {
3664 Lisp_Object obj;
3665 struct Lisp_Marker *m;
3666
3667 /* No dead buffers here. */
3668 eassert (BUFFER_LIVE_P (buf));
3669
3670 /* Every character is at least one byte. */
3671 eassert (charpos <= bytepos);
3672
3673 obj = allocate_misc (Lisp_Misc_Marker);
3674 m = XMARKER (obj);
3675 m->buffer = buf;
3676 m->charpos = charpos;
3677 m->bytepos = bytepos;
3678 m->insertion_type = 0;
3679 m->need_adjustment = 0;
3680 m->next = BUF_MARKERS (buf);
3681 BUF_MARKERS (buf) = m;
3682 return obj;
3683 }
3684
3685 /* Put MARKER back on the free list after using it temporarily. */
3686
3687 void
3688 free_marker (Lisp_Object marker)
3689 {
3690 unchain_marker (XMARKER (marker));
3691 free_misc (marker);
3692 }
3693
3694 \f
3695 /* Return a newly created vector or string with specified arguments as
3696 elements. If all the arguments are characters that can fit
3697 in a string of events, make a string; otherwise, make a vector.
3698
3699 Any number of arguments, even zero arguments, are allowed. */
3700
3701 Lisp_Object
3702 make_event_array (ptrdiff_t nargs, Lisp_Object *args)
3703 {
3704 ptrdiff_t i;
3705
3706 for (i = 0; i < nargs; i++)
3707 /* The things that fit in a string
3708 are characters that are in 0...127,
3709 after discarding the meta bit and all the bits above it. */
3710 if (!INTEGERP (args[i])
3711 || (XINT (args[i]) & ~(-CHAR_META)) >= 0200)
3712 return Fvector (nargs, args);
3713
3714 /* Since the loop exited, we know that all the things in it are
3715 characters, so we can make a string. */
3716 {
3717 Lisp_Object result;
3718
3719 result = Fmake_string (make_number (nargs), make_number (0));
3720 for (i = 0; i < nargs; i++)
3721 {
3722 SSET (result, i, XINT (args[i]));
3723 /* Move the meta bit to the right place for a string char. */
3724 if (XINT (args[i]) & CHAR_META)
3725 SSET (result, i, SREF (result, i) | 0x80);
3726 }
3727
3728 return result;
3729 }
3730 }
3731
3732 #ifdef HAVE_MODULES
3733 /* Create a new module user ptr object. */
3734 Lisp_Object
3735 make_user_ptr (void (*finalizer) (void*), void *p)
3736 {
3737 Lisp_Object obj;
3738 struct Lisp_User_Ptr *uptr;
3739
3740 obj = allocate_misc (Lisp_Misc_User_Ptr);
3741 uptr = XUSER_PTR (obj);
3742 uptr->finalizer = finalizer;
3743 uptr->p = p;
3744 return obj;
3745 }
3746
3747 #endif
3748
3749 static void
3750 init_finalizer_list (struct Lisp_Finalizer *head)
3751 {
3752 head->prev = head->next = head;
3753 }
3754
3755 /* Insert FINALIZER before ELEMENT. */
3756
3757 static void
3758 finalizer_insert (struct Lisp_Finalizer *element,
3759 struct Lisp_Finalizer *finalizer)
3760 {
3761 eassert (finalizer->prev == NULL);
3762 eassert (finalizer->next == NULL);
3763 finalizer->next = element;
3764 finalizer->prev = element->prev;
3765 finalizer->prev->next = finalizer;
3766 element->prev = finalizer;
3767 }
3768
3769 static void
3770 unchain_finalizer (struct Lisp_Finalizer *finalizer)
3771 {
3772 if (finalizer->prev != NULL)
3773 {
3774 eassert (finalizer->next != NULL);
3775 finalizer->prev->next = finalizer->next;
3776 finalizer->next->prev = finalizer->prev;
3777 finalizer->prev = finalizer->next = NULL;
3778 }
3779 }
3780
3781 static void
3782 mark_finalizer_list (struct Lisp_Finalizer *head)
3783 {
3784 for (struct Lisp_Finalizer *finalizer = head->next;
3785 finalizer != head;
3786 finalizer = finalizer->next)
3787 {
3788 finalizer->base.gcmarkbit = true;
3789 mark_object (finalizer->function);
3790 }
3791 }
3792
3793 /* Move doomed finalizers to list DEST from list SRC. A doomed
3794 finalizer is one that is not GC-reachable and whose
3795 finalizer->function is non-nil. */
3796
3797 static void
3798 queue_doomed_finalizers (struct Lisp_Finalizer *dest,
3799 struct Lisp_Finalizer *src)
3800 {
3801 struct Lisp_Finalizer *finalizer = src->next;
3802 while (finalizer != src)
3803 {
3804 struct Lisp_Finalizer *next = finalizer->next;
3805 if (!finalizer->base.gcmarkbit && !NILP (finalizer->function))
3806 {
3807 unchain_finalizer (finalizer);
3808 finalizer_insert (dest, finalizer);
3809 }
3810
3811 finalizer = next;
3812 }
3813 }
3814
3815 static Lisp_Object
3816 run_finalizer_handler (Lisp_Object args)
3817 {
3818 add_to_log ("finalizer failed: %S", args);
3819 return Qnil;
3820 }
3821
3822 static void
3823 run_finalizer_function (Lisp_Object function)
3824 {
3825 ptrdiff_t count = SPECPDL_INDEX ();
3826
3827 specbind (Qinhibit_quit, Qt);
3828 internal_condition_case_1 (call0, function, Qt, run_finalizer_handler);
3829 unbind_to (count, Qnil);
3830 }
3831
3832 static void
3833 run_finalizers (struct Lisp_Finalizer *finalizers)
3834 {
3835 struct Lisp_Finalizer *finalizer;
3836 Lisp_Object function;
3837
3838 while (finalizers->next != finalizers)
3839 {
3840 finalizer = finalizers->next;
3841 eassert (finalizer->base.type == Lisp_Misc_Finalizer);
3842 unchain_finalizer (finalizer);
3843 function = finalizer->function;
3844 if (!NILP (function))
3845 {
3846 finalizer->function = Qnil;
3847 run_finalizer_function (function);
3848 }
3849 }
3850 }
3851
3852 DEFUN ("make-finalizer", Fmake_finalizer, Smake_finalizer, 1, 1, 0,
3853 doc: /* Make a finalizer that will run FUNCTION.
3854 FUNCTION will be called after garbage collection when the returned
3855 finalizer object becomes unreachable. If the finalizer object is
3856 reachable only through references from finalizer objects, it does not
3857 count as reachable for the purpose of deciding whether to run
3858 FUNCTION. FUNCTION will be run once per finalizer object. */)
3859 (Lisp_Object function)
3860 {
3861 Lisp_Object val = allocate_misc (Lisp_Misc_Finalizer);
3862 struct Lisp_Finalizer *finalizer = XFINALIZER (val);
3863 finalizer->function = function;
3864 finalizer->prev = finalizer->next = NULL;
3865 finalizer_insert (&finalizers, finalizer);
3866 return val;
3867 }
3868
3869 \f
3870 /************************************************************************
3871 Memory Full Handling
3872 ************************************************************************/
3873
3874
3875 /* Called if malloc (NBYTES) returns zero. If NBYTES == SIZE_MAX,
3876 there may have been size_t overflow so that malloc was never
3877 called, or perhaps malloc was invoked successfully but the
3878 resulting pointer had problems fitting into a tagged EMACS_INT. In
3879 either case this counts as memory being full even though malloc did
3880 not fail. */
3881
3882 void
3883 memory_full (size_t nbytes)
3884 {
3885 /* Do not go into hysterics merely because a large request failed. */
3886 bool enough_free_memory = 0;
3887 if (SPARE_MEMORY < nbytes)
3888 {
3889 void *p;
3890
3891 MALLOC_BLOCK_INPUT;
3892 p = malloc (SPARE_MEMORY);
3893 if (p)
3894 {
3895 free (p);
3896 enough_free_memory = 1;
3897 }
3898 MALLOC_UNBLOCK_INPUT;
3899 }
3900
3901 if (! enough_free_memory)
3902 {
3903 int i;
3904
3905 Vmemory_full = Qt;
3906
3907 memory_full_cons_threshold = sizeof (struct cons_block);
3908
3909 /* The first time we get here, free the spare memory. */
3910 for (i = 0; i < ARRAYELTS (spare_memory); i++)
3911 if (spare_memory[i])
3912 {
3913 if (i == 0)
3914 free (spare_memory[i]);
3915 else if (i >= 1 && i <= 4)
3916 lisp_align_free (spare_memory[i]);
3917 else
3918 lisp_free (spare_memory[i]);
3919 spare_memory[i] = 0;
3920 }
3921 }
3922
3923 /* This used to call error, but if we've run out of memory, we could
3924 get infinite recursion trying to build the string. */
3925 xsignal (Qnil, Vmemory_signal_data);
3926 }
3927
3928 /* If we released our reserve (due to running out of memory),
3929 and we have a fair amount free once again,
3930 try to set aside another reserve in case we run out once more.
3931
3932 This is called when a relocatable block is freed in ralloc.c,
3933 and also directly from this file, in case we're not using ralloc.c. */
3934
3935 void
3936 refill_memory_reserve (void)
3937 {
3938 #if !defined SYSTEM_MALLOC && !defined HYBRID_MALLOC
3939 if (spare_memory[0] == 0)
3940 spare_memory[0] = malloc (SPARE_MEMORY);
3941 if (spare_memory[1] == 0)
3942 spare_memory[1] = lisp_align_malloc (sizeof (struct cons_block),
3943 MEM_TYPE_SPARE);
3944 if (spare_memory[2] == 0)
3945 spare_memory[2] = lisp_align_malloc (sizeof (struct cons_block),
3946 MEM_TYPE_SPARE);
3947 if (spare_memory[3] == 0)
3948 spare_memory[3] = lisp_align_malloc (sizeof (struct cons_block),
3949 MEM_TYPE_SPARE);
3950 if (spare_memory[4] == 0)
3951 spare_memory[4] = lisp_align_malloc (sizeof (struct cons_block),
3952 MEM_TYPE_SPARE);
3953 if (spare_memory[5] == 0)
3954 spare_memory[5] = lisp_malloc (sizeof (struct string_block),
3955 MEM_TYPE_SPARE);
3956 if (spare_memory[6] == 0)
3957 spare_memory[6] = lisp_malloc (sizeof (struct string_block),
3958 MEM_TYPE_SPARE);
3959 if (spare_memory[0] && spare_memory[1] && spare_memory[5])
3960 Vmemory_full = Qnil;
3961 #endif
3962 }
3963 \f
3964 /************************************************************************
3965 C Stack Marking
3966 ************************************************************************/
3967
3968 /* Conservative C stack marking requires a method to identify possibly
3969 live Lisp objects given a pointer value. We do this by keeping
3970 track of blocks of Lisp data that are allocated in a red-black tree
3971 (see also the comment of mem_node which is the type of nodes in
3972 that tree). Function lisp_malloc adds information for an allocated
3973 block to the red-black tree with calls to mem_insert, and function
3974 lisp_free removes it with mem_delete. Functions live_string_p etc
3975 call mem_find to lookup information about a given pointer in the
3976 tree, and use that to determine if the pointer points to a Lisp
3977 object or not. */
3978
3979 /* Initialize this part of alloc.c. */
3980
3981 static void
3982 mem_init (void)
3983 {
3984 mem_z.left = mem_z.right = MEM_NIL;
3985 mem_z.parent = NULL;
3986 mem_z.color = MEM_BLACK;
3987 mem_z.start = mem_z.end = NULL;
3988 mem_root = MEM_NIL;
3989 }
3990
3991
3992 /* Value is a pointer to the mem_node containing START. Value is
3993 MEM_NIL if there is no node in the tree containing START. */
3994
3995 static struct mem_node *
3996 mem_find (void *start)
3997 {
3998 struct mem_node *p;
3999
4000 if (start < min_heap_address || start > max_heap_address)
4001 return MEM_NIL;
4002
4003 /* Make the search always successful to speed up the loop below. */
4004 mem_z.start = start;
4005 mem_z.end = (char *) start + 1;
4006
4007 p = mem_root;
4008 while (start < p->start || start >= p->end)
4009 p = start < p->start ? p->left : p->right;
4010 return p;
4011 }
4012
4013
4014 /* Insert a new node into the tree for a block of memory with start
4015 address START, end address END, and type TYPE. Value is a
4016 pointer to the node that was inserted. */
4017
4018 static struct mem_node *
4019 mem_insert (void *start, void *end, enum mem_type type)
4020 {
4021 struct mem_node *c, *parent, *x;
4022
4023 if (min_heap_address == NULL || start < min_heap_address)
4024 min_heap_address = start;
4025 if (max_heap_address == NULL || end > max_heap_address)
4026 max_heap_address = end;
4027
4028 /* See where in the tree a node for START belongs. In this
4029 particular application, it shouldn't happen that a node is already
4030 present. For debugging purposes, let's check that. */
4031 c = mem_root;
4032 parent = NULL;
4033
4034 while (c != MEM_NIL)
4035 {
4036 parent = c;
4037 c = start < c->start ? c->left : c->right;
4038 }
4039
4040 /* Create a new node. */
4041 #ifdef GC_MALLOC_CHECK
4042 x = malloc (sizeof *x);
4043 if (x == NULL)
4044 emacs_abort ();
4045 #else
4046 x = xmalloc (sizeof *x);
4047 #endif
4048 x->start = start;
4049 x->end = end;
4050 x->type = type;
4051 x->parent = parent;
4052 x->left = x->right = MEM_NIL;
4053 x->color = MEM_RED;
4054
4055 /* Insert it as child of PARENT or install it as root. */
4056 if (parent)
4057 {
4058 if (start < parent->start)
4059 parent->left = x;
4060 else
4061 parent->right = x;
4062 }
4063 else
4064 mem_root = x;
4065
4066 /* Re-establish red-black tree properties. */
4067 mem_insert_fixup (x);
4068
4069 return x;
4070 }
4071
4072
4073 /* Re-establish the red-black properties of the tree, and thereby
4074 balance the tree, after node X has been inserted; X is always red. */
4075
4076 static void
4077 mem_insert_fixup (struct mem_node *x)
4078 {
4079 while (x != mem_root && x->parent->color == MEM_RED)
4080 {
4081 /* X is red and its parent is red. This is a violation of
4082 red-black tree property #3. */
4083
4084 if (x->parent == x->parent->parent->left)
4085 {
4086 /* We're on the left side of our grandparent, and Y is our
4087 "uncle". */
4088 struct mem_node *y = x->parent->parent->right;
4089
4090 if (y->color == MEM_RED)
4091 {
4092 /* Uncle and parent are red but should be black because
4093 X is red. Change the colors accordingly and proceed
4094 with the grandparent. */
4095 x->parent->color = MEM_BLACK;
4096 y->color = MEM_BLACK;
4097 x->parent->parent->color = MEM_RED;
4098 x = x->parent->parent;
4099 }
4100 else
4101 {
4102 /* Parent and uncle have different colors; parent is
4103 red, uncle is black. */
4104 if (x == x->parent->right)
4105 {
4106 x = x->parent;
4107 mem_rotate_left (x);
4108 }
4109
4110 x->parent->color = MEM_BLACK;
4111 x->parent->parent->color = MEM_RED;
4112 mem_rotate_right (x->parent->parent);
4113 }
4114 }
4115 else
4116 {
4117 /* This is the symmetrical case of above. */
4118 struct mem_node *y = x->parent->parent->left;
4119
4120 if (y->color == MEM_RED)
4121 {
4122 x->parent->color = MEM_BLACK;
4123 y->color = MEM_BLACK;
4124 x->parent->parent->color = MEM_RED;
4125 x = x->parent->parent;
4126 }
4127 else
4128 {
4129 if (x == x->parent->left)
4130 {
4131 x = x->parent;
4132 mem_rotate_right (x);
4133 }
4134
4135 x->parent->color = MEM_BLACK;
4136 x->parent->parent->color = MEM_RED;
4137 mem_rotate_left (x->parent->parent);
4138 }
4139 }
4140 }
4141
4142 /* The root may have been changed to red due to the algorithm. Set
4143 it to black so that property #5 is satisfied. */
4144 mem_root->color = MEM_BLACK;
4145 }
4146
4147
4148 /* (x) (y)
4149 / \ / \
4150 a (y) ===> (x) c
4151 / \ / \
4152 b c a b */
4153
4154 static void
4155 mem_rotate_left (struct mem_node *x)
4156 {
4157 struct mem_node *y;
4158
4159 /* Turn y's left sub-tree into x's right sub-tree. */
4160 y = x->right;
4161 x->right = y->left;
4162 if (y->left != MEM_NIL)
4163 y->left->parent = x;
4164
4165 /* Y's parent was x's parent. */
4166 if (y != MEM_NIL)
4167 y->parent = x->parent;
4168
4169 /* Get the parent to point to y instead of x. */
4170 if (x->parent)
4171 {
4172 if (x == x->parent->left)
4173 x->parent->left = y;
4174 else
4175 x->parent->right = y;
4176 }
4177 else
4178 mem_root = y;
4179
4180 /* Put x on y's left. */
4181 y->left = x;
4182 if (x != MEM_NIL)
4183 x->parent = y;
4184 }
4185
4186
4187 /* (x) (Y)
4188 / \ / \
4189 (y) c ===> a (x)
4190 / \ / \
4191 a b b c */
4192
4193 static void
4194 mem_rotate_right (struct mem_node *x)
4195 {
4196 struct mem_node *y = x->left;
4197
4198 x->left = y->right;
4199 if (y->right != MEM_NIL)
4200 y->right->parent = x;
4201
4202 if (y != MEM_NIL)
4203 y->parent = x->parent;
4204 if (x->parent)
4205 {
4206 if (x == x->parent->right)
4207 x->parent->right = y;
4208 else
4209 x->parent->left = y;
4210 }
4211 else
4212 mem_root = y;
4213
4214 y->right = x;
4215 if (x != MEM_NIL)
4216 x->parent = y;
4217 }
4218
4219
4220 /* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
4221
4222 static void
4223 mem_delete (struct mem_node *z)
4224 {
4225 struct mem_node *x, *y;
4226
4227 if (!z || z == MEM_NIL)
4228 return;
4229
4230 if (z->left == MEM_NIL || z->right == MEM_NIL)
4231 y = z;
4232 else
4233 {
4234 y = z->right;
4235 while (y->left != MEM_NIL)
4236 y = y->left;
4237 }
4238
4239 if (y->left != MEM_NIL)
4240 x = y->left;
4241 else
4242 x = y->right;
4243
4244 x->parent = y->parent;
4245 if (y->parent)
4246 {
4247 if (y == y->parent->left)
4248 y->parent->left = x;
4249 else
4250 y->parent->right = x;
4251 }
4252 else
4253 mem_root = x;
4254
4255 if (y != z)
4256 {
4257 z->start = y->start;
4258 z->end = y->end;
4259 z->type = y->type;
4260 }
4261
4262 if (y->color == MEM_BLACK)
4263 mem_delete_fixup (x);
4264
4265 #ifdef GC_MALLOC_CHECK
4266 free (y);
4267 #else
4268 xfree (y);
4269 #endif
4270 }
4271
4272
4273 /* Re-establish the red-black properties of the tree, after a
4274 deletion. */
4275
4276 static void
4277 mem_delete_fixup (struct mem_node *x)
4278 {
4279 while (x != mem_root && x->color == MEM_BLACK)
4280 {
4281 if (x == x->parent->left)
4282 {
4283 struct mem_node *w = x->parent->right;
4284
4285 if (w->color == MEM_RED)
4286 {
4287 w->color = MEM_BLACK;
4288 x->parent->color = MEM_RED;
4289 mem_rotate_left (x->parent);
4290 w = x->parent->right;
4291 }
4292
4293 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
4294 {
4295 w->color = MEM_RED;
4296 x = x->parent;
4297 }
4298 else
4299 {
4300 if (w->right->color == MEM_BLACK)
4301 {
4302 w->left->color = MEM_BLACK;
4303 w->color = MEM_RED;
4304 mem_rotate_right (w);
4305 w = x->parent->right;
4306 }
4307 w->color = x->parent->color;
4308 x->parent->color = MEM_BLACK;
4309 w->right->color = MEM_BLACK;
4310 mem_rotate_left (x->parent);
4311 x = mem_root;
4312 }
4313 }
4314 else
4315 {
4316 struct mem_node *w = x->parent->left;
4317
4318 if (w->color == MEM_RED)
4319 {
4320 w->color = MEM_BLACK;
4321 x->parent->color = MEM_RED;
4322 mem_rotate_right (x->parent);
4323 w = x->parent->left;
4324 }
4325
4326 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
4327 {
4328 w->color = MEM_RED;
4329 x = x->parent;
4330 }
4331 else
4332 {
4333 if (w->left->color == MEM_BLACK)
4334 {
4335 w->right->color = MEM_BLACK;
4336 w->color = MEM_RED;
4337 mem_rotate_left (w);
4338 w = x->parent->left;
4339 }
4340
4341 w->color = x->parent->color;
4342 x->parent->color = MEM_BLACK;
4343 w->left->color = MEM_BLACK;
4344 mem_rotate_right (x->parent);
4345 x = mem_root;
4346 }
4347 }
4348 }
4349
4350 x->color = MEM_BLACK;
4351 }
4352
4353
4354 /* Value is non-zero if P is a pointer to a live Lisp string on
4355 the heap. M is a pointer to the mem_block for P. */
4356
4357 static bool
4358 live_string_p (struct mem_node *m, void *p)
4359 {
4360 if (m->type == MEM_TYPE_STRING)
4361 {
4362 struct string_block *b = m->start;
4363 ptrdiff_t offset = (char *) p - (char *) &b->strings[0];
4364
4365 /* P must point to the start of a Lisp_String structure, and it
4366 must not be on the free-list. */
4367 return (offset >= 0
4368 && offset % sizeof b->strings[0] == 0
4369 && offset < (STRING_BLOCK_SIZE * sizeof b->strings[0])
4370 && ((struct Lisp_String *) p)->data != NULL);
4371 }
4372 else
4373 return 0;
4374 }
4375
4376
4377 /* Value is non-zero if P is a pointer to a live Lisp cons on
4378 the heap. M is a pointer to the mem_block for P. */
4379
4380 static bool
4381 live_cons_p (struct mem_node *m, void *p)
4382 {
4383 if (m->type == MEM_TYPE_CONS)
4384 {
4385 struct cons_block *b = m->start;
4386 ptrdiff_t offset = (char *) p - (char *) &b->conses[0];
4387
4388 /* P must point to the start of a Lisp_Cons, not be
4389 one of the unused cells in the current cons block,
4390 and not be on the free-list. */
4391 return (offset >= 0
4392 && offset % sizeof b->conses[0] == 0
4393 && offset < (CONS_BLOCK_SIZE * sizeof b->conses[0])
4394 && (b != cons_block
4395 || offset / sizeof b->conses[0] < cons_block_index)
4396 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
4397 }
4398 else
4399 return 0;
4400 }
4401
4402
4403 /* Value is non-zero if P is a pointer to a live Lisp symbol on
4404 the heap. M is a pointer to the mem_block for P. */
4405
4406 static bool
4407 live_symbol_p (struct mem_node *m, void *p)
4408 {
4409 if (m->type == MEM_TYPE_SYMBOL)
4410 {
4411 struct symbol_block *b = m->start;
4412 ptrdiff_t offset = (char *) p - (char *) &b->symbols[0];
4413
4414 /* P must point to the start of a Lisp_Symbol, not be
4415 one of the unused cells in the current symbol block,
4416 and not be on the free-list. */
4417 return (offset >= 0
4418 && offset % sizeof b->symbols[0] == 0
4419 && offset < (SYMBOL_BLOCK_SIZE * sizeof b->symbols[0])
4420 && (b != symbol_block
4421 || offset / sizeof b->symbols[0] < symbol_block_index)
4422 && !EQ (((struct Lisp_Symbol *)p)->function, Vdead));
4423 }
4424 else
4425 return 0;
4426 }
4427
4428
4429 /* Value is non-zero if P is a pointer to a live Lisp float on
4430 the heap. M is a pointer to the mem_block for P. */
4431
4432 static bool
4433 live_float_p (struct mem_node *m, void *p)
4434 {
4435 if (m->type == MEM_TYPE_FLOAT)
4436 {
4437 struct float_block *b = m->start;
4438 ptrdiff_t offset = (char *) p - (char *) &b->floats[0];
4439
4440 /* P must point to the start of a Lisp_Float and not be
4441 one of the unused cells in the current float block. */
4442 return (offset >= 0
4443 && offset % sizeof b->floats[0] == 0
4444 && offset < (FLOAT_BLOCK_SIZE * sizeof b->floats[0])
4445 && (b != float_block
4446 || offset / sizeof b->floats[0] < float_block_index));
4447 }
4448 else
4449 return 0;
4450 }
4451
4452
4453 /* Value is non-zero if P is a pointer to a live Lisp Misc on
4454 the heap. M is a pointer to the mem_block for P. */
4455
4456 static bool
4457 live_misc_p (struct mem_node *m, void *p)
4458 {
4459 if (m->type == MEM_TYPE_MISC)
4460 {
4461 struct marker_block *b = m->start;
4462 ptrdiff_t offset = (char *) p - (char *) &b->markers[0];
4463
4464 /* P must point to the start of a Lisp_Misc, not be
4465 one of the unused cells in the current misc block,
4466 and not be on the free-list. */
4467 return (offset >= 0
4468 && offset % sizeof b->markers[0] == 0
4469 && offset < (MARKER_BLOCK_SIZE * sizeof b->markers[0])
4470 && (b != marker_block
4471 || offset / sizeof b->markers[0] < marker_block_index)
4472 && ((union Lisp_Misc *) p)->u_any.type != Lisp_Misc_Free);
4473 }
4474 else
4475 return 0;
4476 }
4477
4478
4479 /* Value is non-zero if P is a pointer to a live vector-like object.
4480 M is a pointer to the mem_block for P. */
4481
4482 static bool
4483 live_vector_p (struct mem_node *m, void *p)
4484 {
4485 if (m->type == MEM_TYPE_VECTOR_BLOCK)
4486 {
4487 /* This memory node corresponds to a vector block. */
4488 struct vector_block *block = m->start;
4489 struct Lisp_Vector *vector = (struct Lisp_Vector *) block->data;
4490
4491 /* P is in the block's allocation range. Scan the block
4492 up to P and see whether P points to the start of some
4493 vector which is not on a free list. FIXME: check whether
4494 some allocation patterns (probably a lot of short vectors)
4495 may cause a substantial overhead of this loop. */
4496 while (VECTOR_IN_BLOCK (vector, block)
4497 && vector <= (struct Lisp_Vector *) p)
4498 {
4499 if (!PSEUDOVECTOR_TYPEP (&vector->header, PVEC_FREE) && vector == p)
4500 return 1;
4501 else
4502 vector = ADVANCE (vector, vector_nbytes (vector));
4503 }
4504 }
4505 else if (m->type == MEM_TYPE_VECTORLIKE && p == large_vector_vec (m->start))
4506 /* This memory node corresponds to a large vector. */
4507 return 1;
4508 return 0;
4509 }
4510
4511
4512 /* Value is non-zero if P is a pointer to a live buffer. M is a
4513 pointer to the mem_block for P. */
4514
4515 static bool
4516 live_buffer_p (struct mem_node *m, void *p)
4517 {
4518 /* P must point to the start of the block, and the buffer
4519 must not have been killed. */
4520 return (m->type == MEM_TYPE_BUFFER
4521 && p == m->start
4522 && !NILP (((struct buffer *) p)->name_));
4523 }
4524
4525 /* Mark OBJ if we can prove it's a Lisp_Object. */
4526
4527 static void
4528 mark_maybe_object (Lisp_Object obj)
4529 {
4530 #if USE_VALGRIND
4531 if (valgrind_p)
4532 VALGRIND_MAKE_MEM_DEFINED (&obj, sizeof (obj));
4533 #endif
4534
4535 if (INTEGERP (obj))
4536 return;
4537
4538 void *po = XPNTR (obj);
4539 struct mem_node *m = mem_find (po);
4540
4541 if (m != MEM_NIL)
4542 {
4543 bool mark_p = false;
4544
4545 switch (XTYPE (obj))
4546 {
4547 case Lisp_String:
4548 mark_p = (live_string_p (m, po)
4549 && !STRING_MARKED_P ((struct Lisp_String *) po));
4550 break;
4551
4552 case Lisp_Cons:
4553 mark_p = (live_cons_p (m, po) && !CONS_MARKED_P (XCONS (obj)));
4554 break;
4555
4556 case Lisp_Symbol:
4557 mark_p = (live_symbol_p (m, po) && !XSYMBOL (obj)->gcmarkbit);
4558 break;
4559
4560 case Lisp_Float:
4561 mark_p = (live_float_p (m, po) && !FLOAT_MARKED_P (XFLOAT (obj)));
4562 break;
4563
4564 case Lisp_Vectorlike:
4565 /* Note: can't check BUFFERP before we know it's a
4566 buffer because checking that dereferences the pointer
4567 PO which might point anywhere. */
4568 if (live_vector_p (m, po))
4569 mark_p = !SUBRP (obj) && !VECTOR_MARKED_P (XVECTOR (obj));
4570 else if (live_buffer_p (m, po))
4571 mark_p = BUFFERP (obj) && !VECTOR_MARKED_P (XBUFFER (obj));
4572 break;
4573
4574 case Lisp_Misc:
4575 mark_p = (live_misc_p (m, po) && !XMISCANY (obj)->gcmarkbit);
4576 break;
4577
4578 default:
4579 break;
4580 }
4581
4582 if (mark_p)
4583 mark_object (obj);
4584 }
4585 }
4586
4587 /* Return true if P can point to Lisp data, and false otherwise.
4588 Symbols are implemented via offsets not pointers, but the offsets
4589 are also multiples of GCALIGNMENT. */
4590
4591 static bool
4592 maybe_lisp_pointer (void *p)
4593 {
4594 return (uintptr_t) p % GCALIGNMENT == 0;
4595 }
4596
4597 /* If P points to Lisp data, mark that as live if it isn't already
4598 marked. */
4599
4600 static void
4601 mark_maybe_pointer (void *p)
4602 {
4603 struct mem_node *m;
4604
4605 #if USE_VALGRIND
4606 if (valgrind_p)
4607 VALGRIND_MAKE_MEM_DEFINED (&p, sizeof (p));
4608 #endif
4609
4610 if (sizeof (Lisp_Object) == sizeof (void *) || !HAVE_MODULES)
4611 {
4612 if (!maybe_lisp_pointer (p))
4613 return;
4614 }
4615 else
4616 /* For the wide-int case, we also have to accept emacs_value "tagged
4617 pointers", which can be generated by emacs-module.c's value_to_lisp. */
4618 p = (void*)((uintptr_t) p & ~(GCALIGNMENT - 1));
4619
4620 m = mem_find (p);
4621 if (m != MEM_NIL)
4622 {
4623 Lisp_Object obj = Qnil;
4624
4625 switch (m->type)
4626 {
4627 case MEM_TYPE_NON_LISP:
4628 case MEM_TYPE_SPARE:
4629 /* Nothing to do; not a pointer to Lisp memory. */
4630 break;
4631
4632 case MEM_TYPE_BUFFER:
4633 if (live_buffer_p (m, p) && !VECTOR_MARKED_P ((struct buffer *)p))
4634 XSETVECTOR (obj, p);
4635 break;
4636
4637 case MEM_TYPE_CONS:
4638 if (live_cons_p (m, p) && !CONS_MARKED_P ((struct Lisp_Cons *) p))
4639 XSETCONS (obj, p);
4640 break;
4641
4642 case MEM_TYPE_STRING:
4643 if (live_string_p (m, p)
4644 && !STRING_MARKED_P ((struct Lisp_String *) p))
4645 XSETSTRING (obj, p);
4646 break;
4647
4648 case MEM_TYPE_MISC:
4649 if (live_misc_p (m, p) && !((struct Lisp_Free *) p)->gcmarkbit)
4650 XSETMISC (obj, p);
4651 break;
4652
4653 case MEM_TYPE_SYMBOL:
4654 if (live_symbol_p (m, p) && !((struct Lisp_Symbol *) p)->gcmarkbit)
4655 XSETSYMBOL (obj, p);
4656 break;
4657
4658 case MEM_TYPE_FLOAT:
4659 if (live_float_p (m, p) && !FLOAT_MARKED_P (p))
4660 XSETFLOAT (obj, p);
4661 break;
4662
4663 case MEM_TYPE_VECTORLIKE:
4664 case MEM_TYPE_VECTOR_BLOCK:
4665 if (live_vector_p (m, p))
4666 {
4667 Lisp_Object tem;
4668 XSETVECTOR (tem, p);
4669 if (!SUBRP (tem) && !VECTOR_MARKED_P (XVECTOR (tem)))
4670 obj = tem;
4671 }
4672 break;
4673
4674 default:
4675 emacs_abort ();
4676 }
4677
4678 if (!NILP (obj))
4679 mark_object (obj);
4680 }
4681 }
4682
4683
4684 /* Alignment of pointer values. Use alignof, as it sometimes returns
4685 a smaller alignment than GCC's __alignof__ and mark_memory might
4686 miss objects if __alignof__ were used. */
4687 #define GC_POINTER_ALIGNMENT alignof (void *)
4688
4689 /* Mark Lisp objects referenced from the address range START+OFFSET..END
4690 or END+OFFSET..START. */
4691
4692 static void ATTRIBUTE_NO_SANITIZE_ADDRESS
4693 mark_memory (void *start, void *end)
4694 {
4695 char *pp;
4696
4697 /* Make START the pointer to the start of the memory region,
4698 if it isn't already. */
4699 if (end < start)
4700 {
4701 void *tem = start;
4702 start = end;
4703 end = tem;
4704 }
4705
4706 eassert (((uintptr_t) start) % GC_POINTER_ALIGNMENT == 0);
4707
4708 /* Mark Lisp data pointed to. This is necessary because, in some
4709 situations, the C compiler optimizes Lisp objects away, so that
4710 only a pointer to them remains. Example:
4711
4712 DEFUN ("testme", Ftestme, Stestme, 0, 0, 0, "")
4713 ()
4714 {
4715 Lisp_Object obj = build_string ("test");
4716 struct Lisp_String *s = XSTRING (obj);
4717 Fgarbage_collect ();
4718 fprintf (stderr, "test '%s'\n", s->data);
4719 return Qnil;
4720 }
4721
4722 Here, `obj' isn't really used, and the compiler optimizes it
4723 away. The only reference to the life string is through the
4724 pointer `s'. */
4725
4726 for (pp = start; (void*)pp < end; pp = pp + GC_POINTER_ALIGNMENT)
4727 {
4728 mark_maybe_pointer (*(void **) pp);
4729 mark_maybe_object (*(Lisp_Object *) pp);
4730 }
4731 }
4732
4733 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
4734
4735 static bool setjmp_tested_p;
4736 static int longjmps_done;
4737
4738 #define SETJMP_WILL_LIKELY_WORK "\
4739 \n\
4740 Emacs garbage collector has been changed to use conservative stack\n\
4741 marking. Emacs has determined that the method it uses to do the\n\
4742 marking will likely work on your system, but this isn't sure.\n\
4743 \n\
4744 If you are a system-programmer, or can get the help of a local wizard\n\
4745 who is, please take a look at the function mark_stack in alloc.c, and\n\
4746 verify that the methods used are appropriate for your system.\n\
4747 \n\
4748 Please mail the result to <emacs-devel@gnu.org>.\n\
4749 "
4750
4751 #define SETJMP_WILL_NOT_WORK "\
4752 \n\
4753 Emacs garbage collector has been changed to use conservative stack\n\
4754 marking. Emacs has determined that the default method it uses to do the\n\
4755 marking will not work on your system. We will need a system-dependent\n\
4756 solution for your system.\n\
4757 \n\
4758 Please take a look at the function mark_stack in alloc.c, and\n\
4759 try to find a way to make it work on your system.\n\
4760 \n\
4761 Note that you may get false negatives, depending on the compiler.\n\
4762 In particular, you need to use -O with GCC for this test.\n\
4763 \n\
4764 Please mail the result to <emacs-devel@gnu.org>.\n\
4765 "
4766
4767
4768 /* Perform a quick check if it looks like setjmp saves registers in a
4769 jmp_buf. Print a message to stderr saying so. When this test
4770 succeeds, this is _not_ a proof that setjmp is sufficient for
4771 conservative stack marking. Only the sources or a disassembly
4772 can prove that. */
4773
4774 static void
4775 test_setjmp (void)
4776 {
4777 char buf[10];
4778 register int x;
4779 sys_jmp_buf jbuf;
4780
4781 /* Arrange for X to be put in a register. */
4782 sprintf (buf, "1");
4783 x = strlen (buf);
4784 x = 2 * x - 1;
4785
4786 sys_setjmp (jbuf);
4787 if (longjmps_done == 1)
4788 {
4789 /* Came here after the longjmp at the end of the function.
4790
4791 If x == 1, the longjmp has restored the register to its
4792 value before the setjmp, and we can hope that setjmp
4793 saves all such registers in the jmp_buf, although that
4794 isn't sure.
4795
4796 For other values of X, either something really strange is
4797 taking place, or the setjmp just didn't save the register. */
4798
4799 if (x == 1)
4800 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
4801 else
4802 {
4803 fprintf (stderr, SETJMP_WILL_NOT_WORK);
4804 exit (1);
4805 }
4806 }
4807
4808 ++longjmps_done;
4809 x = 2;
4810 if (longjmps_done == 1)
4811 sys_longjmp (jbuf, 1);
4812 }
4813
4814 #endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
4815
4816
4817 /* Mark live Lisp objects on the C stack.
4818
4819 There are several system-dependent problems to consider when
4820 porting this to new architectures:
4821
4822 Processor Registers
4823
4824 We have to mark Lisp objects in CPU registers that can hold local
4825 variables or are used to pass parameters.
4826
4827 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
4828 something that either saves relevant registers on the stack, or
4829 calls mark_maybe_object passing it each register's contents.
4830
4831 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
4832 implementation assumes that calling setjmp saves registers we need
4833 to see in a jmp_buf which itself lies on the stack. This doesn't
4834 have to be true! It must be verified for each system, possibly
4835 by taking a look at the source code of setjmp.
4836
4837 If __builtin_unwind_init is available (defined by GCC >= 2.8) we
4838 can use it as a machine independent method to store all registers
4839 to the stack. In this case the macros described in the previous
4840 two paragraphs are not used.
4841
4842 Stack Layout
4843
4844 Architectures differ in the way their processor stack is organized.
4845 For example, the stack might look like this
4846
4847 +----------------+
4848 | Lisp_Object | size = 4
4849 +----------------+
4850 | something else | size = 2
4851 +----------------+
4852 | Lisp_Object | size = 4
4853 +----------------+
4854 | ... |
4855
4856 In such a case, not every Lisp_Object will be aligned equally. To
4857 find all Lisp_Object on the stack it won't be sufficient to walk
4858 the stack in steps of 4 bytes. Instead, two passes will be
4859 necessary, one starting at the start of the stack, and a second
4860 pass starting at the start of the stack + 2. Likewise, if the
4861 minimal alignment of Lisp_Objects on the stack is 1, four passes
4862 would be necessary, each one starting with one byte more offset
4863 from the stack start. */
4864
4865 static void
4866 mark_stack (void *end)
4867 {
4868
4869 /* This assumes that the stack is a contiguous region in memory. If
4870 that's not the case, something has to be done here to iterate
4871 over the stack segments. */
4872 mark_memory (stack_base, end);
4873
4874 /* Allow for marking a secondary stack, like the register stack on the
4875 ia64. */
4876 #ifdef GC_MARK_SECONDARY_STACK
4877 GC_MARK_SECONDARY_STACK ();
4878 #endif
4879 }
4880
4881 static bool
4882 c_symbol_p (struct Lisp_Symbol *sym)
4883 {
4884 char *lispsym_ptr = (char *) lispsym;
4885 char *sym_ptr = (char *) sym;
4886 ptrdiff_t lispsym_offset = sym_ptr - lispsym_ptr;
4887 return 0 <= lispsym_offset && lispsym_offset < sizeof lispsym;
4888 }
4889
4890 /* Determine whether it is safe to access memory at address P. */
4891 static int
4892 valid_pointer_p (void *p)
4893 {
4894 #ifdef WINDOWSNT
4895 return w32_valid_pointer_p (p, 16);
4896 #else
4897
4898 if (ADDRESS_SANITIZER)
4899 return p ? -1 : 0;
4900
4901 int fd[2];
4902
4903 /* Obviously, we cannot just access it (we would SEGV trying), so we
4904 trick the o/s to tell us whether p is a valid pointer.
4905 Unfortunately, we cannot use NULL_DEVICE here, as emacs_write may
4906 not validate p in that case. */
4907
4908 if (emacs_pipe (fd) == 0)
4909 {
4910 bool valid = emacs_write (fd[1], p, 16) == 16;
4911 emacs_close (fd[1]);
4912 emacs_close (fd[0]);
4913 return valid;
4914 }
4915
4916 return -1;
4917 #endif
4918 }
4919
4920 /* Return 2 if OBJ is a killed or special buffer object, 1 if OBJ is a
4921 valid lisp object, 0 if OBJ is NOT a valid lisp object, or -1 if we
4922 cannot validate OBJ. This function can be quite slow, so its primary
4923 use is the manual debugging. The only exception is print_object, where
4924 we use it to check whether the memory referenced by the pointer of
4925 Lisp_Save_Value object contains valid objects. */
4926
4927 int
4928 valid_lisp_object_p (Lisp_Object obj)
4929 {
4930 if (INTEGERP (obj))
4931 return 1;
4932
4933 void *p = XPNTR (obj);
4934 if (PURE_P (p))
4935 return 1;
4936
4937 if (SYMBOLP (obj) && c_symbol_p (p))
4938 return ((char *) p - (char *) lispsym) % sizeof lispsym[0] == 0;
4939
4940 if (p == &buffer_defaults || p == &buffer_local_symbols)
4941 return 2;
4942
4943 struct mem_node *m = mem_find (p);
4944
4945 if (m == MEM_NIL)
4946 {
4947 int valid = valid_pointer_p (p);
4948 if (valid <= 0)
4949 return valid;
4950
4951 if (SUBRP (obj))
4952 return 1;
4953
4954 return 0;
4955 }
4956
4957 switch (m->type)
4958 {
4959 case MEM_TYPE_NON_LISP:
4960 case MEM_TYPE_SPARE:
4961 return 0;
4962
4963 case MEM_TYPE_BUFFER:
4964 return live_buffer_p (m, p) ? 1 : 2;
4965
4966 case MEM_TYPE_CONS:
4967 return live_cons_p (m, p);
4968
4969 case MEM_TYPE_STRING:
4970 return live_string_p (m, p);
4971
4972 case MEM_TYPE_MISC:
4973 return live_misc_p (m, p);
4974
4975 case MEM_TYPE_SYMBOL:
4976 return live_symbol_p (m, p);
4977
4978 case MEM_TYPE_FLOAT:
4979 return live_float_p (m, p);
4980
4981 case MEM_TYPE_VECTORLIKE:
4982 case MEM_TYPE_VECTOR_BLOCK:
4983 return live_vector_p (m, p);
4984
4985 default:
4986 break;
4987 }
4988
4989 return 0;
4990 }
4991
4992 /***********************************************************************
4993 Pure Storage Management
4994 ***********************************************************************/
4995
4996 /* Allocate room for SIZE bytes from pure Lisp storage and return a
4997 pointer to it. TYPE is the Lisp type for which the memory is
4998 allocated. TYPE < 0 means it's not used for a Lisp object. */
4999
5000 static void *
5001 pure_alloc (size_t size, int type)
5002 {
5003 void *result;
5004
5005 again:
5006 if (type >= 0)
5007 {
5008 /* Allocate space for a Lisp object from the beginning of the free
5009 space with taking account of alignment. */
5010 result = ALIGN (purebeg + pure_bytes_used_lisp, GCALIGNMENT);
5011 pure_bytes_used_lisp = ((char *)result - (char *)purebeg) + size;
5012 }
5013 else
5014 {
5015 /* Allocate space for a non-Lisp object from the end of the free
5016 space. */
5017 pure_bytes_used_non_lisp += size;
5018 result = purebeg + pure_size - pure_bytes_used_non_lisp;
5019 }
5020 pure_bytes_used = pure_bytes_used_lisp + pure_bytes_used_non_lisp;
5021
5022 if (pure_bytes_used <= pure_size)
5023 return result;
5024
5025 /* Don't allocate a large amount here,
5026 because it might get mmap'd and then its address
5027 might not be usable. */
5028 purebeg = xmalloc (10000);
5029 pure_size = 10000;
5030 pure_bytes_used_before_overflow += pure_bytes_used - size;
5031 pure_bytes_used = 0;
5032 pure_bytes_used_lisp = pure_bytes_used_non_lisp = 0;
5033 goto again;
5034 }
5035
5036
5037 /* Print a warning if PURESIZE is too small. */
5038
5039 void
5040 check_pure_size (void)
5041 {
5042 if (pure_bytes_used_before_overflow)
5043 message (("emacs:0:Pure Lisp storage overflow (approx. %"pI"d"
5044 " bytes needed)"),
5045 pure_bytes_used + pure_bytes_used_before_overflow);
5046 }
5047
5048
5049 /* Find the byte sequence {DATA[0], ..., DATA[NBYTES-1], '\0'} from
5050 the non-Lisp data pool of the pure storage, and return its start
5051 address. Return NULL if not found. */
5052
5053 static char *
5054 find_string_data_in_pure (const char *data, ptrdiff_t nbytes)
5055 {
5056 int i;
5057 ptrdiff_t skip, bm_skip[256], last_char_skip, infinity, start, start_max;
5058 const unsigned char *p;
5059 char *non_lisp_beg;
5060
5061 if (pure_bytes_used_non_lisp <= nbytes)
5062 return NULL;
5063
5064 /* Set up the Boyer-Moore table. */
5065 skip = nbytes + 1;
5066 for (i = 0; i < 256; i++)
5067 bm_skip[i] = skip;
5068
5069 p = (const unsigned char *) data;
5070 while (--skip > 0)
5071 bm_skip[*p++] = skip;
5072
5073 last_char_skip = bm_skip['\0'];
5074
5075 non_lisp_beg = purebeg + pure_size - pure_bytes_used_non_lisp;
5076 start_max = pure_bytes_used_non_lisp - (nbytes + 1);
5077
5078 /* See the comments in the function `boyer_moore' (search.c) for the
5079 use of `infinity'. */
5080 infinity = pure_bytes_used_non_lisp + 1;
5081 bm_skip['\0'] = infinity;
5082
5083 p = (const unsigned char *) non_lisp_beg + nbytes;
5084 start = 0;
5085 do
5086 {
5087 /* Check the last character (== '\0'). */
5088 do
5089 {
5090 start += bm_skip[*(p + start)];
5091 }
5092 while (start <= start_max);
5093
5094 if (start < infinity)
5095 /* Couldn't find the last character. */
5096 return NULL;
5097
5098 /* No less than `infinity' means we could find the last
5099 character at `p[start - infinity]'. */
5100 start -= infinity;
5101
5102 /* Check the remaining characters. */
5103 if (memcmp (data, non_lisp_beg + start, nbytes) == 0)
5104 /* Found. */
5105 return non_lisp_beg + start;
5106
5107 start += last_char_skip;
5108 }
5109 while (start <= start_max);
5110
5111 return NULL;
5112 }
5113
5114
5115 /* Return a string allocated in pure space. DATA is a buffer holding
5116 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
5117 means make the result string multibyte.
5118
5119 Must get an error if pure storage is full, since if it cannot hold
5120 a large string it may be able to hold conses that point to that
5121 string; then the string is not protected from gc. */
5122
5123 Lisp_Object
5124 make_pure_string (const char *data,
5125 ptrdiff_t nchars, ptrdiff_t nbytes, bool multibyte)
5126 {
5127 Lisp_Object string;
5128 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5129 s->data = (unsigned char *) find_string_data_in_pure (data, nbytes);
5130 if (s->data == NULL)
5131 {
5132 s->data = pure_alloc (nbytes + 1, -1);
5133 memcpy (s->data, data, nbytes);
5134 s->data[nbytes] = '\0';
5135 }
5136 s->size = nchars;
5137 s->size_byte = multibyte ? nbytes : -1;
5138 s->intervals = NULL;
5139 XSETSTRING (string, s);
5140 return string;
5141 }
5142
5143 /* Return a string allocated in pure space. Do not
5144 allocate the string data, just point to DATA. */
5145
5146 Lisp_Object
5147 make_pure_c_string (const char *data, ptrdiff_t nchars)
5148 {
5149 Lisp_Object string;
5150 struct Lisp_String *s = pure_alloc (sizeof *s, Lisp_String);
5151 s->size = nchars;
5152 s->size_byte = -1;
5153 s->data = (unsigned char *) data;
5154 s->intervals = NULL;
5155 XSETSTRING (string, s);
5156 return string;
5157 }
5158
5159 static Lisp_Object purecopy (Lisp_Object obj);
5160
5161 /* Return a cons allocated from pure space. Give it pure copies
5162 of CAR as car and CDR as cdr. */
5163
5164 Lisp_Object
5165 pure_cons (Lisp_Object car, Lisp_Object cdr)
5166 {
5167 Lisp_Object new;
5168 struct Lisp_Cons *p = pure_alloc (sizeof *p, Lisp_Cons);
5169 XSETCONS (new, p);
5170 XSETCAR (new, purecopy (car));
5171 XSETCDR (new, purecopy (cdr));
5172 return new;
5173 }
5174
5175
5176 /* Value is a float object with value NUM allocated from pure space. */
5177
5178 static Lisp_Object
5179 make_pure_float (double num)
5180 {
5181 Lisp_Object new;
5182 struct Lisp_Float *p = pure_alloc (sizeof *p, Lisp_Float);
5183 XSETFLOAT (new, p);
5184 XFLOAT_INIT (new, num);
5185 return new;
5186 }
5187
5188
5189 /* Return a vector with room for LEN Lisp_Objects allocated from
5190 pure space. */
5191
5192 static Lisp_Object
5193 make_pure_vector (ptrdiff_t len)
5194 {
5195 Lisp_Object new;
5196 size_t size = header_size + len * word_size;
5197 struct Lisp_Vector *p = pure_alloc (size, Lisp_Vectorlike);
5198 XSETVECTOR (new, p);
5199 XVECTOR (new)->header.size = len;
5200 return new;
5201 }
5202
5203 DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
5204 doc: /* Make a copy of object OBJ in pure storage.
5205 Recursively copies contents of vectors and cons cells.
5206 Does not copy symbols. Copies strings without text properties. */)
5207 (register Lisp_Object obj)
5208 {
5209 if (NILP (Vpurify_flag))
5210 return obj;
5211 else if (MARKERP (obj) || OVERLAYP (obj)
5212 || HASH_TABLE_P (obj) || SYMBOLP (obj))
5213 /* Can't purify those. */
5214 return obj;
5215 else
5216 return purecopy (obj);
5217 }
5218
5219 static Lisp_Object
5220 purecopy (Lisp_Object obj)
5221 {
5222 if (INTEGERP (obj)
5223 || (! SYMBOLP (obj) && PURE_P (XPNTR_OR_SYMBOL_OFFSET (obj)))
5224 || SUBRP (obj))
5225 return obj; /* Already pure. */
5226
5227 if (STRINGP (obj) && XSTRING (obj)->intervals)
5228 message_with_string ("Dropping text-properties while making string `%s' pure",
5229 obj, true);
5230
5231 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5232 {
5233 Lisp_Object tmp = Fgethash (obj, Vpurify_flag, Qnil);
5234 if (!NILP (tmp))
5235 return tmp;
5236 }
5237
5238 if (CONSP (obj))
5239 obj = pure_cons (XCAR (obj), XCDR (obj));
5240 else if (FLOATP (obj))
5241 obj = make_pure_float (XFLOAT_DATA (obj));
5242 else if (STRINGP (obj))
5243 obj = make_pure_string (SSDATA (obj), SCHARS (obj),
5244 SBYTES (obj),
5245 STRING_MULTIBYTE (obj));
5246 else if (COMPILEDP (obj) || VECTORP (obj) || HASH_TABLE_P (obj))
5247 {
5248 struct Lisp_Vector *objp = XVECTOR (obj);
5249 ptrdiff_t nbytes = vector_nbytes (objp);
5250 struct Lisp_Vector *vec = pure_alloc (nbytes, Lisp_Vectorlike);
5251 register ptrdiff_t i;
5252 ptrdiff_t size = ASIZE (obj);
5253 if (size & PSEUDOVECTOR_FLAG)
5254 size &= PSEUDOVECTOR_SIZE_MASK;
5255 memcpy (vec, objp, nbytes);
5256 for (i = 0; i < size; i++)
5257 vec->contents[i] = purecopy (vec->contents[i]);
5258 XSETVECTOR (obj, vec);
5259 }
5260 else if (SYMBOLP (obj))
5261 {
5262 if (!XSYMBOL (obj)->pinned && !c_symbol_p (XSYMBOL (obj)))
5263 { /* We can't purify them, but they appear in many pure objects.
5264 Mark them as `pinned' so we know to mark them at every GC cycle. */
5265 XSYMBOL (obj)->pinned = true;
5266 symbol_block_pinned = symbol_block;
5267 }
5268 /* Don't hash-cons it. */
5269 return obj;
5270 }
5271 else
5272 {
5273 Lisp_Object fmt = build_pure_c_string ("Don't know how to purify: %S");
5274 Fsignal (Qerror, list1 (CALLN (Fformat, fmt, obj)));
5275 }
5276
5277 if (HASH_TABLE_P (Vpurify_flag)) /* Hash consing. */
5278 Fputhash (obj, obj, Vpurify_flag);
5279
5280 return obj;
5281 }
5282
5283
5284 \f
5285 /***********************************************************************
5286 Protection from GC
5287 ***********************************************************************/
5288
5289 /* Put an entry in staticvec, pointing at the variable with address
5290 VARADDRESS. */
5291
5292 void
5293 staticpro (Lisp_Object *varaddress)
5294 {
5295 if (staticidx >= NSTATICS)
5296 fatal ("NSTATICS too small; try increasing and recompiling Emacs.");
5297 staticvec[staticidx++] = varaddress;
5298 }
5299
5300 \f
5301 /***********************************************************************
5302 Protection from GC
5303 ***********************************************************************/
5304
5305 /* Temporarily prevent garbage collection. */
5306
5307 ptrdiff_t
5308 inhibit_garbage_collection (void)
5309 {
5310 ptrdiff_t count = SPECPDL_INDEX ();
5311
5312 specbind (Qgc_cons_threshold, make_number (MOST_POSITIVE_FIXNUM));
5313 return count;
5314 }
5315
5316 /* Used to avoid possible overflows when
5317 converting from C to Lisp integers. */
5318
5319 static Lisp_Object
5320 bounded_number (EMACS_INT number)
5321 {
5322 return make_number (min (MOST_POSITIVE_FIXNUM, number));
5323 }
5324
5325 /* Calculate total bytes of live objects. */
5326
5327 static size_t
5328 total_bytes_of_live_objects (void)
5329 {
5330 size_t tot = 0;
5331 tot += total_conses * sizeof (struct Lisp_Cons);
5332 tot += total_symbols * sizeof (struct Lisp_Symbol);
5333 tot += total_markers * sizeof (union Lisp_Misc);
5334 tot += total_string_bytes;
5335 tot += total_vector_slots * word_size;
5336 tot += total_floats * sizeof (struct Lisp_Float);
5337 tot += total_intervals * sizeof (struct interval);
5338 tot += total_strings * sizeof (struct Lisp_String);
5339 return tot;
5340 }
5341
5342 #ifdef HAVE_WINDOW_SYSTEM
5343
5344 /* Remove unmarked font-spec and font-entity objects from ENTRY, which is
5345 (DRIVER-TYPE NUM-FRAMES FONT-CACHE-DATA ...), and return changed entry. */
5346
5347 static Lisp_Object
5348 compact_font_cache_entry (Lisp_Object entry)
5349 {
5350 Lisp_Object tail, *prev = &entry;
5351
5352 for (tail = entry; CONSP (tail); tail = XCDR (tail))
5353 {
5354 bool drop = 0;
5355 Lisp_Object obj = XCAR (tail);
5356
5357 /* Consider OBJ if it is (font-spec . [font-entity font-entity ...]). */
5358 if (CONSP (obj) && GC_FONT_SPEC_P (XCAR (obj))
5359 && !VECTOR_MARKED_P (GC_XFONT_SPEC (XCAR (obj)))
5360 /* Don't use VECTORP here, as that calls ASIZE, which could
5361 hit assertion violation during GC. */
5362 && (VECTORLIKEP (XCDR (obj))
5363 && ! (gc_asize (XCDR (obj)) & PSEUDOVECTOR_FLAG)))
5364 {
5365 ptrdiff_t i, size = gc_asize (XCDR (obj));
5366 Lisp_Object obj_cdr = XCDR (obj);
5367
5368 /* If font-spec is not marked, most likely all font-entities
5369 are not marked too. But we must be sure that nothing is
5370 marked within OBJ before we really drop it. */
5371 for (i = 0; i < size; i++)
5372 {
5373 Lisp_Object objlist;
5374
5375 if (VECTOR_MARKED_P (GC_XFONT_ENTITY (AREF (obj_cdr, i))))
5376 break;
5377
5378 objlist = AREF (AREF (obj_cdr, i), FONT_OBJLIST_INDEX);
5379 for (; CONSP (objlist); objlist = XCDR (objlist))
5380 {
5381 Lisp_Object val = XCAR (objlist);
5382 struct font *font = GC_XFONT_OBJECT (val);
5383
5384 if (!NILP (AREF (val, FONT_TYPE_INDEX))
5385 && VECTOR_MARKED_P(font))
5386 break;
5387 }
5388 if (CONSP (objlist))
5389 {
5390 /* Found a marked font, bail out. */
5391 break;
5392 }
5393 }
5394
5395 if (i == size)
5396 {
5397 /* No marked fonts were found, so this entire font
5398 entity can be dropped. */
5399 drop = 1;
5400 }
5401 }
5402 if (drop)
5403 *prev = XCDR (tail);
5404 else
5405 prev = xcdr_addr (tail);
5406 }
5407 return entry;
5408 }
5409
5410 /* Compact font caches on all terminals and mark
5411 everything which is still here after compaction. */
5412
5413 static void
5414 compact_font_caches (void)
5415 {
5416 struct terminal *t;
5417
5418 for (t = terminal_list; t; t = t->next_terminal)
5419 {
5420 Lisp_Object cache = TERMINAL_FONT_CACHE (t);
5421 if (CONSP (cache))
5422 {
5423 Lisp_Object entry;
5424
5425 for (entry = XCDR (cache); CONSP (entry); entry = XCDR (entry))
5426 XSETCAR (entry, compact_font_cache_entry (XCAR (entry)));
5427 }
5428 mark_object (cache);
5429 }
5430 }
5431
5432 #else /* not HAVE_WINDOW_SYSTEM */
5433
5434 #define compact_font_caches() (void)(0)
5435
5436 #endif /* HAVE_WINDOW_SYSTEM */
5437
5438 /* Remove (MARKER . DATA) entries with unmarked MARKER
5439 from buffer undo LIST and return changed list. */
5440
5441 static Lisp_Object
5442 compact_undo_list (Lisp_Object list)
5443 {
5444 Lisp_Object tail, *prev = &list;
5445
5446 for (tail = list; CONSP (tail); tail = XCDR (tail))
5447 {
5448 if (CONSP (XCAR (tail))
5449 && MARKERP (XCAR (XCAR (tail)))
5450 && !XMARKER (XCAR (XCAR (tail)))->gcmarkbit)
5451 *prev = XCDR (tail);
5452 else
5453 prev = xcdr_addr (tail);
5454 }
5455 return list;
5456 }
5457
5458 static void
5459 mark_pinned_symbols (void)
5460 {
5461 struct symbol_block *sblk;
5462 int lim = (symbol_block_pinned == symbol_block
5463 ? symbol_block_index : SYMBOL_BLOCK_SIZE);
5464
5465 for (sblk = symbol_block_pinned; sblk; sblk = sblk->next)
5466 {
5467 union aligned_Lisp_Symbol *sym = sblk->symbols, *end = sym + lim;
5468 for (; sym < end; ++sym)
5469 if (sym->s.pinned)
5470 mark_object (make_lisp_symbol (&sym->s));
5471
5472 lim = SYMBOL_BLOCK_SIZE;
5473 }
5474 }
5475
5476 /* Subroutine of Fgarbage_collect that does most of the work. It is a
5477 separate function so that we could limit mark_stack in searching
5478 the stack frames below this function, thus avoiding the rare cases
5479 where mark_stack finds values that look like live Lisp objects on
5480 portions of stack that couldn't possibly contain such live objects.
5481 For more details of this, see the discussion at
5482 http://lists.gnu.org/archive/html/emacs-devel/2014-05/msg00270.html. */
5483 static Lisp_Object
5484 garbage_collect_1 (void *end)
5485 {
5486 struct buffer *nextb;
5487 char stack_top_variable;
5488 ptrdiff_t i;
5489 bool message_p;
5490 ptrdiff_t count = SPECPDL_INDEX ();
5491 struct timespec start;
5492 Lisp_Object retval = Qnil;
5493 size_t tot_before = 0;
5494
5495 if (abort_on_gc)
5496 emacs_abort ();
5497
5498 /* Can't GC if pure storage overflowed because we can't determine
5499 if something is a pure object or not. */
5500 if (pure_bytes_used_before_overflow)
5501 return Qnil;
5502
5503 /* Record this function, so it appears on the profiler's backtraces. */
5504 record_in_backtrace (Qautomatic_gc, 0, 0);
5505
5506 check_cons_list ();
5507
5508 /* Don't keep undo information around forever.
5509 Do this early on, so it is no problem if the user quits. */
5510 FOR_EACH_BUFFER (nextb)
5511 compact_buffer (nextb);
5512
5513 if (profiler_memory_running)
5514 tot_before = total_bytes_of_live_objects ();
5515
5516 start = current_timespec ();
5517
5518 /* In case user calls debug_print during GC,
5519 don't let that cause a recursive GC. */
5520 consing_since_gc = 0;
5521
5522 /* Save what's currently displayed in the echo area. */
5523 message_p = push_message ();
5524 record_unwind_protect_void (pop_message_unwind);
5525
5526 /* Save a copy of the contents of the stack, for debugging. */
5527 #if MAX_SAVE_STACK > 0
5528 if (NILP (Vpurify_flag))
5529 {
5530 char *stack;
5531 ptrdiff_t stack_size;
5532 if (&stack_top_variable < stack_bottom)
5533 {
5534 stack = &stack_top_variable;
5535 stack_size = stack_bottom - &stack_top_variable;
5536 }
5537 else
5538 {
5539 stack = stack_bottom;
5540 stack_size = &stack_top_variable - stack_bottom;
5541 }
5542 if (stack_size <= MAX_SAVE_STACK)
5543 {
5544 if (stack_copy_size < stack_size)
5545 {
5546 stack_copy = xrealloc (stack_copy, stack_size);
5547 stack_copy_size = stack_size;
5548 }
5549 no_sanitize_memcpy (stack_copy, stack, stack_size);
5550 }
5551 }
5552 #endif /* MAX_SAVE_STACK > 0 */
5553
5554 if (garbage_collection_messages)
5555 message1_nolog ("Garbage collecting...");
5556
5557 block_input ();
5558
5559 shrink_regexp_cache ();
5560
5561 gc_in_progress = 1;
5562
5563 /* Mark all the special slots that serve as the roots of accessibility. */
5564
5565 mark_buffer (&buffer_defaults);
5566 mark_buffer (&buffer_local_symbols);
5567
5568 for (i = 0; i < ARRAYELTS (lispsym); i++)
5569 mark_object (builtin_lisp_symbol (i));
5570
5571 for (i = 0; i < staticidx; i++)
5572 mark_object (*staticvec[i]);
5573
5574 mark_pinned_symbols ();
5575 mark_specpdl ();
5576 mark_terminals ();
5577 mark_kboards ();
5578
5579 #ifdef USE_GTK
5580 xg_mark_data ();
5581 #endif
5582
5583 mark_stack (end);
5584
5585 {
5586 struct handler *handler;
5587 for (handler = handlerlist; handler; handler = handler->next)
5588 {
5589 mark_object (handler->tag_or_ch);
5590 mark_object (handler->val);
5591 }
5592 }
5593 #ifdef HAVE_WINDOW_SYSTEM
5594 mark_fringe_data ();
5595 #endif
5596
5597 /* Everything is now marked, except for the data in font caches,
5598 undo lists, and finalizers. The first two are compacted by
5599 removing an items which aren't reachable otherwise. */
5600
5601 compact_font_caches ();
5602
5603 FOR_EACH_BUFFER (nextb)
5604 {
5605 if (!EQ (BVAR (nextb, undo_list), Qt))
5606 bset_undo_list (nextb, compact_undo_list (BVAR (nextb, undo_list)));
5607 /* Now that we have stripped the elements that need not be
5608 in the undo_list any more, we can finally mark the list. */
5609 mark_object (BVAR (nextb, undo_list));
5610 }
5611
5612 /* Now pre-sweep finalizers. Here, we add any unmarked finalizers
5613 to doomed_finalizers so we can run their associated functions
5614 after GC. It's important to scan finalizers at this stage so
5615 that we can be sure that unmarked finalizers are really
5616 unreachable except for references from their associated functions
5617 and from other finalizers. */
5618
5619 queue_doomed_finalizers (&doomed_finalizers, &finalizers);
5620 mark_finalizer_list (&doomed_finalizers);
5621
5622 gc_sweep ();
5623
5624 relocate_byte_stack ();
5625
5626 /* Clear the mark bits that we set in certain root slots. */
5627 VECTOR_UNMARK (&buffer_defaults);
5628 VECTOR_UNMARK (&buffer_local_symbols);
5629
5630 check_cons_list ();
5631
5632 gc_in_progress = 0;
5633
5634 unblock_input ();
5635
5636 consing_since_gc = 0;
5637 if (gc_cons_threshold < GC_DEFAULT_THRESHOLD / 10)
5638 gc_cons_threshold = GC_DEFAULT_THRESHOLD / 10;
5639
5640 gc_relative_threshold = 0;
5641 if (FLOATP (Vgc_cons_percentage))
5642 { /* Set gc_cons_combined_threshold. */
5643 double tot = total_bytes_of_live_objects ();
5644
5645 tot *= XFLOAT_DATA (Vgc_cons_percentage);
5646 if (0 < tot)
5647 {
5648 if (tot < TYPE_MAXIMUM (EMACS_INT))
5649 gc_relative_threshold = tot;
5650 else
5651 gc_relative_threshold = TYPE_MAXIMUM (EMACS_INT);
5652 }
5653 }
5654
5655 if (garbage_collection_messages)
5656 {
5657 if (message_p || minibuf_level > 0)
5658 restore_message ();
5659 else
5660 message1_nolog ("Garbage collecting...done");
5661 }
5662
5663 unbind_to (count, Qnil);
5664
5665 Lisp_Object total[] = {
5666 list4 (Qconses, make_number (sizeof (struct Lisp_Cons)),
5667 bounded_number (total_conses),
5668 bounded_number (total_free_conses)),
5669 list4 (Qsymbols, make_number (sizeof (struct Lisp_Symbol)),
5670 bounded_number (total_symbols),
5671 bounded_number (total_free_symbols)),
5672 list4 (Qmiscs, make_number (sizeof (union Lisp_Misc)),
5673 bounded_number (total_markers),
5674 bounded_number (total_free_markers)),
5675 list4 (Qstrings, make_number (sizeof (struct Lisp_String)),
5676 bounded_number (total_strings),
5677 bounded_number (total_free_strings)),
5678 list3 (Qstring_bytes, make_number (1),
5679 bounded_number (total_string_bytes)),
5680 list3 (Qvectors,
5681 make_number (header_size + sizeof (Lisp_Object)),
5682 bounded_number (total_vectors)),
5683 list4 (Qvector_slots, make_number (word_size),
5684 bounded_number (total_vector_slots),
5685 bounded_number (total_free_vector_slots)),
5686 list4 (Qfloats, make_number (sizeof (struct Lisp_Float)),
5687 bounded_number (total_floats),
5688 bounded_number (total_free_floats)),
5689 list4 (Qintervals, make_number (sizeof (struct interval)),
5690 bounded_number (total_intervals),
5691 bounded_number (total_free_intervals)),
5692 list3 (Qbuffers, make_number (sizeof (struct buffer)),
5693 bounded_number (total_buffers)),
5694
5695 #ifdef DOUG_LEA_MALLOC
5696 list4 (Qheap, make_number (1024),
5697 bounded_number ((mallinfo ().uordblks + 1023) >> 10),
5698 bounded_number ((mallinfo ().fordblks + 1023) >> 10)),
5699 #endif
5700 };
5701 retval = CALLMANY (Flist, total);
5702
5703 /* GC is complete: now we can run our finalizer callbacks. */
5704 run_finalizers (&doomed_finalizers);
5705
5706 if (!NILP (Vpost_gc_hook))
5707 {
5708 ptrdiff_t gc_count = inhibit_garbage_collection ();
5709 safe_run_hooks (Qpost_gc_hook);
5710 unbind_to (gc_count, Qnil);
5711 }
5712
5713 /* Accumulate statistics. */
5714 if (FLOATP (Vgc_elapsed))
5715 {
5716 struct timespec since_start = timespec_sub (current_timespec (), start);
5717 Vgc_elapsed = make_float (XFLOAT_DATA (Vgc_elapsed)
5718 + timespectod (since_start));
5719 }
5720
5721 gcs_done++;
5722
5723 /* Collect profiling data. */
5724 if (profiler_memory_running)
5725 {
5726 size_t swept = 0;
5727 size_t tot_after = total_bytes_of_live_objects ();
5728 if (tot_before > tot_after)
5729 swept = tot_before - tot_after;
5730 malloc_probe (swept);
5731 }
5732
5733 return retval;
5734 }
5735
5736 DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
5737 doc: /* Reclaim storage for Lisp objects no longer needed.
5738 Garbage collection happens automatically if you cons more than
5739 `gc-cons-threshold' bytes of Lisp data since previous garbage collection.
5740 `garbage-collect' normally returns a list with info on amount of space in use,
5741 where each entry has the form (NAME SIZE USED FREE), where:
5742 - NAME is a symbol describing the kind of objects this entry represents,
5743 - SIZE is the number of bytes used by each one,
5744 - USED is the number of those objects that were found live in the heap,
5745 - FREE is the number of those objects that are not live but that Emacs
5746 keeps around for future allocations (maybe because it does not know how
5747 to return them to the OS).
5748 However, if there was overflow in pure space, `garbage-collect'
5749 returns nil, because real GC can't be done.
5750 See Info node `(elisp)Garbage Collection'. */)
5751 (void)
5752 {
5753 void *end;
5754
5755 #ifdef HAVE___BUILTIN_UNWIND_INIT
5756 /* Force callee-saved registers and register windows onto the stack.
5757 This is the preferred method if available, obviating the need for
5758 machine dependent methods. */
5759 __builtin_unwind_init ();
5760 end = &end;
5761 #else /* not HAVE___BUILTIN_UNWIND_INIT */
5762 #ifndef GC_SAVE_REGISTERS_ON_STACK
5763 /* jmp_buf may not be aligned enough on darwin-ppc64 */
5764 union aligned_jmpbuf {
5765 Lisp_Object o;
5766 sys_jmp_buf j;
5767 } j;
5768 volatile bool stack_grows_down_p = (char *) &j > (char *) stack_base;
5769 #endif
5770 /* This trick flushes the register windows so that all the state of
5771 the process is contained in the stack. */
5772 /* Fixme: Code in the Boehm GC suggests flushing (with `flushrs') is
5773 needed on ia64 too. See mach_dep.c, where it also says inline
5774 assembler doesn't work with relevant proprietary compilers. */
5775 #ifdef __sparc__
5776 #if defined (__sparc64__) && defined (__FreeBSD__)
5777 /* FreeBSD does not have a ta 3 handler. */
5778 asm ("flushw");
5779 #else
5780 asm ("ta 3");
5781 #endif
5782 #endif
5783
5784 /* Save registers that we need to see on the stack. We need to see
5785 registers used to hold register variables and registers used to
5786 pass parameters. */
5787 #ifdef GC_SAVE_REGISTERS_ON_STACK
5788 GC_SAVE_REGISTERS_ON_STACK (end);
5789 #else /* not GC_SAVE_REGISTERS_ON_STACK */
5790
5791 #ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
5792 setjmp will definitely work, test it
5793 and print a message with the result
5794 of the test. */
5795 if (!setjmp_tested_p)
5796 {
5797 setjmp_tested_p = 1;
5798 test_setjmp ();
5799 }
5800 #endif /* GC_SETJMP_WORKS */
5801
5802 sys_setjmp (j.j);
5803 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
5804 #endif /* not GC_SAVE_REGISTERS_ON_STACK */
5805 #endif /* not HAVE___BUILTIN_UNWIND_INIT */
5806 return garbage_collect_1 (end);
5807 }
5808
5809 /* Mark Lisp objects in glyph matrix MATRIX. Currently the
5810 only interesting objects referenced from glyphs are strings. */
5811
5812 static void
5813 mark_glyph_matrix (struct glyph_matrix *matrix)
5814 {
5815 struct glyph_row *row = matrix->rows;
5816 struct glyph_row *end = row + matrix->nrows;
5817
5818 for (; row < end; ++row)
5819 if (row->enabled_p)
5820 {
5821 int area;
5822 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
5823 {
5824 struct glyph *glyph = row->glyphs[area];
5825 struct glyph *end_glyph = glyph + row->used[area];
5826
5827 for (; glyph < end_glyph; ++glyph)
5828 if (STRINGP (glyph->object)
5829 && !STRING_MARKED_P (XSTRING (glyph->object)))
5830 mark_object (glyph->object);
5831 }
5832 }
5833 }
5834
5835 /* Mark reference to a Lisp_Object.
5836 If the object referred to has not been seen yet, recursively mark
5837 all the references contained in it. */
5838
5839 #define LAST_MARKED_SIZE 500
5840 static Lisp_Object last_marked[LAST_MARKED_SIZE];
5841 static int last_marked_index;
5842
5843 /* For debugging--call abort when we cdr down this many
5844 links of a list, in mark_object. In debugging,
5845 the call to abort will hit a breakpoint.
5846 Normally this is zero and the check never goes off. */
5847 ptrdiff_t mark_object_loop_halt EXTERNALLY_VISIBLE;
5848
5849 static void
5850 mark_vectorlike (struct Lisp_Vector *ptr)
5851 {
5852 ptrdiff_t size = ptr->header.size;
5853 ptrdiff_t i;
5854
5855 eassert (!VECTOR_MARKED_P (ptr));
5856 VECTOR_MARK (ptr); /* Else mark it. */
5857 if (size & PSEUDOVECTOR_FLAG)
5858 size &= PSEUDOVECTOR_SIZE_MASK;
5859
5860 /* Note that this size is not the memory-footprint size, but only
5861 the number of Lisp_Object fields that we should trace.
5862 The distinction is used e.g. by Lisp_Process which places extra
5863 non-Lisp_Object fields at the end of the structure... */
5864 for (i = 0; i < size; i++) /* ...and then mark its elements. */
5865 mark_object (ptr->contents[i]);
5866 }
5867
5868 /* Like mark_vectorlike but optimized for char-tables (and
5869 sub-char-tables) assuming that the contents are mostly integers or
5870 symbols. */
5871
5872 static void
5873 mark_char_table (struct Lisp_Vector *ptr, enum pvec_type pvectype)
5874 {
5875 int size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5876 /* Consult the Lisp_Sub_Char_Table layout before changing this. */
5877 int i, idx = (pvectype == PVEC_SUB_CHAR_TABLE ? SUB_CHAR_TABLE_OFFSET : 0);
5878
5879 eassert (!VECTOR_MARKED_P (ptr));
5880 VECTOR_MARK (ptr);
5881 for (i = idx; i < size; i++)
5882 {
5883 Lisp_Object val = ptr->contents[i];
5884
5885 if (INTEGERP (val) || (SYMBOLP (val) && XSYMBOL (val)->gcmarkbit))
5886 continue;
5887 if (SUB_CHAR_TABLE_P (val))
5888 {
5889 if (! VECTOR_MARKED_P (XVECTOR (val)))
5890 mark_char_table (XVECTOR (val), PVEC_SUB_CHAR_TABLE);
5891 }
5892 else
5893 mark_object (val);
5894 }
5895 }
5896
5897 NO_INLINE /* To reduce stack depth in mark_object. */
5898 static Lisp_Object
5899 mark_compiled (struct Lisp_Vector *ptr)
5900 {
5901 int i, size = ptr->header.size & PSEUDOVECTOR_SIZE_MASK;
5902
5903 VECTOR_MARK (ptr);
5904 for (i = 0; i < size; i++)
5905 if (i != COMPILED_CONSTANTS)
5906 mark_object (ptr->contents[i]);
5907 return size > COMPILED_CONSTANTS ? ptr->contents[COMPILED_CONSTANTS] : Qnil;
5908 }
5909
5910 /* Mark the chain of overlays starting at PTR. */
5911
5912 static void
5913 mark_overlay (struct Lisp_Overlay *ptr)
5914 {
5915 for (; ptr && !ptr->gcmarkbit; ptr = ptr->next)
5916 {
5917 ptr->gcmarkbit = 1;
5918 /* These two are always markers and can be marked fast. */
5919 XMARKER (ptr->start)->gcmarkbit = 1;
5920 XMARKER (ptr->end)->gcmarkbit = 1;
5921 mark_object (ptr->plist);
5922 }
5923 }
5924
5925 /* Mark Lisp_Objects and special pointers in BUFFER. */
5926
5927 static void
5928 mark_buffer (struct buffer *buffer)
5929 {
5930 /* This is handled much like other pseudovectors... */
5931 mark_vectorlike ((struct Lisp_Vector *) buffer);
5932
5933 /* ...but there are some buffer-specific things. */
5934
5935 MARK_INTERVAL_TREE (buffer_intervals (buffer));
5936
5937 /* For now, we just don't mark the undo_list. It's done later in
5938 a special way just before the sweep phase, and after stripping
5939 some of its elements that are not needed any more. */
5940
5941 mark_overlay (buffer->overlays_before);
5942 mark_overlay (buffer->overlays_after);
5943
5944 /* If this is an indirect buffer, mark its base buffer. */
5945 if (buffer->base_buffer && !VECTOR_MARKED_P (buffer->base_buffer))
5946 mark_buffer (buffer->base_buffer);
5947 }
5948
5949 /* Mark Lisp faces in the face cache C. */
5950
5951 NO_INLINE /* To reduce stack depth in mark_object. */
5952 static void
5953 mark_face_cache (struct face_cache *c)
5954 {
5955 if (c)
5956 {
5957 int i, j;
5958 for (i = 0; i < c->used; ++i)
5959 {
5960 struct face *face = FACE_FROM_ID (c->f, i);
5961
5962 if (face)
5963 {
5964 if (face->font && !VECTOR_MARKED_P (face->font))
5965 mark_vectorlike ((struct Lisp_Vector *) face->font);
5966
5967 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
5968 mark_object (face->lface[j]);
5969 }
5970 }
5971 }
5972 }
5973
5974 NO_INLINE /* To reduce stack depth in mark_object. */
5975 static void
5976 mark_localized_symbol (struct Lisp_Symbol *ptr)
5977 {
5978 struct Lisp_Buffer_Local_Value *blv = SYMBOL_BLV (ptr);
5979 Lisp_Object where = blv->where;
5980 /* If the value is set up for a killed buffer or deleted
5981 frame, restore its global binding. If the value is
5982 forwarded to a C variable, either it's not a Lisp_Object
5983 var, or it's staticpro'd already. */
5984 if ((BUFFERP (where) && !BUFFER_LIVE_P (XBUFFER (where)))
5985 || (FRAMEP (where) && !FRAME_LIVE_P (XFRAME (where))))
5986 swap_in_global_binding (ptr);
5987 mark_object (blv->where);
5988 mark_object (blv->valcell);
5989 mark_object (blv->defcell);
5990 }
5991
5992 NO_INLINE /* To reduce stack depth in mark_object. */
5993 static void
5994 mark_save_value (struct Lisp_Save_Value *ptr)
5995 {
5996 /* If `save_type' is zero, `data[0].pointer' is the address
5997 of a memory area containing `data[1].integer' potential
5998 Lisp_Objects. */
5999 if (ptr->save_type == SAVE_TYPE_MEMORY)
6000 {
6001 Lisp_Object *p = ptr->data[0].pointer;
6002 ptrdiff_t nelt;
6003 for (nelt = ptr->data[1].integer; nelt > 0; nelt--, p++)
6004 mark_maybe_object (*p);
6005 }
6006 else
6007 {
6008 /* Find Lisp_Objects in `data[N]' slots and mark them. */
6009 int i;
6010 for (i = 0; i < SAVE_VALUE_SLOTS; i++)
6011 if (save_type (ptr, i) == SAVE_OBJECT)
6012 mark_object (ptr->data[i].object);
6013 }
6014 }
6015
6016 /* Remove killed buffers or items whose car is a killed buffer from
6017 LIST, and mark other items. Return changed LIST, which is marked. */
6018
6019 static Lisp_Object
6020 mark_discard_killed_buffers (Lisp_Object list)
6021 {
6022 Lisp_Object tail, *prev = &list;
6023
6024 for (tail = list; CONSP (tail) && !CONS_MARKED_P (XCONS (tail));
6025 tail = XCDR (tail))
6026 {
6027 Lisp_Object tem = XCAR (tail);
6028 if (CONSP (tem))
6029 tem = XCAR (tem);
6030 if (BUFFERP (tem) && !BUFFER_LIVE_P (XBUFFER (tem)))
6031 *prev = XCDR (tail);
6032 else
6033 {
6034 CONS_MARK (XCONS (tail));
6035 mark_object (XCAR (tail));
6036 prev = xcdr_addr (tail);
6037 }
6038 }
6039 mark_object (tail);
6040 return list;
6041 }
6042
6043 /* Determine type of generic Lisp_Object and mark it accordingly.
6044
6045 This function implements a straightforward depth-first marking
6046 algorithm and so the recursion depth may be very high (a few
6047 tens of thousands is not uncommon). To minimize stack usage,
6048 a few cold paths are moved out to NO_INLINE functions above.
6049 In general, inlining them doesn't help you to gain more speed. */
6050
6051 void
6052 mark_object (Lisp_Object arg)
6053 {
6054 register Lisp_Object obj;
6055 void *po;
6056 #ifdef GC_CHECK_MARKED_OBJECTS
6057 struct mem_node *m;
6058 #endif
6059 ptrdiff_t cdr_count = 0;
6060
6061 obj = arg;
6062 loop:
6063
6064 po = XPNTR (obj);
6065 if (PURE_P (po))
6066 return;
6067
6068 last_marked[last_marked_index++] = obj;
6069 if (last_marked_index == LAST_MARKED_SIZE)
6070 last_marked_index = 0;
6071
6072 /* Perform some sanity checks on the objects marked here. Abort if
6073 we encounter an object we know is bogus. This increases GC time
6074 by ~80%. */
6075 #ifdef GC_CHECK_MARKED_OBJECTS
6076
6077 /* Check that the object pointed to by PO is known to be a Lisp
6078 structure allocated from the heap. */
6079 #define CHECK_ALLOCATED() \
6080 do { \
6081 m = mem_find (po); \
6082 if (m == MEM_NIL) \
6083 emacs_abort (); \
6084 } while (0)
6085
6086 /* Check that the object pointed to by PO is live, using predicate
6087 function LIVEP. */
6088 #define CHECK_LIVE(LIVEP) \
6089 do { \
6090 if (!LIVEP (m, po)) \
6091 emacs_abort (); \
6092 } while (0)
6093
6094 /* Check both of the above conditions, for non-symbols. */
6095 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
6096 do { \
6097 CHECK_ALLOCATED (); \
6098 CHECK_LIVE (LIVEP); \
6099 } while (0) \
6100
6101 /* Check both of the above conditions, for symbols. */
6102 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() \
6103 do { \
6104 if (!c_symbol_p (ptr)) \
6105 { \
6106 CHECK_ALLOCATED (); \
6107 CHECK_LIVE (live_symbol_p); \
6108 } \
6109 } while (0) \
6110
6111 #else /* not GC_CHECK_MARKED_OBJECTS */
6112
6113 #define CHECK_LIVE(LIVEP) ((void) 0)
6114 #define CHECK_ALLOCATED_AND_LIVE(LIVEP) ((void) 0)
6115 #define CHECK_ALLOCATED_AND_LIVE_SYMBOL() ((void) 0)
6116
6117 #endif /* not GC_CHECK_MARKED_OBJECTS */
6118
6119 switch (XTYPE (obj))
6120 {
6121 case Lisp_String:
6122 {
6123 register struct Lisp_String *ptr = XSTRING (obj);
6124 if (STRING_MARKED_P (ptr))
6125 break;
6126 CHECK_ALLOCATED_AND_LIVE (live_string_p);
6127 MARK_STRING (ptr);
6128 MARK_INTERVAL_TREE (ptr->intervals);
6129 #ifdef GC_CHECK_STRING_BYTES
6130 /* Check that the string size recorded in the string is the
6131 same as the one recorded in the sdata structure. */
6132 string_bytes (ptr);
6133 #endif /* GC_CHECK_STRING_BYTES */
6134 }
6135 break;
6136
6137 case Lisp_Vectorlike:
6138 {
6139 register struct Lisp_Vector *ptr = XVECTOR (obj);
6140 register ptrdiff_t pvectype;
6141
6142 if (VECTOR_MARKED_P (ptr))
6143 break;
6144
6145 #ifdef GC_CHECK_MARKED_OBJECTS
6146 m = mem_find (po);
6147 if (m == MEM_NIL && !SUBRP (obj))
6148 emacs_abort ();
6149 #endif /* GC_CHECK_MARKED_OBJECTS */
6150
6151 if (ptr->header.size & PSEUDOVECTOR_FLAG)
6152 pvectype = ((ptr->header.size & PVEC_TYPE_MASK)
6153 >> PSEUDOVECTOR_AREA_BITS);
6154 else
6155 pvectype = PVEC_NORMAL_VECTOR;
6156
6157 if (pvectype != PVEC_SUBR && pvectype != PVEC_BUFFER)
6158 CHECK_LIVE (live_vector_p);
6159
6160 switch (pvectype)
6161 {
6162 case PVEC_BUFFER:
6163 #ifdef GC_CHECK_MARKED_OBJECTS
6164 {
6165 struct buffer *b;
6166 FOR_EACH_BUFFER (b)
6167 if (b == po)
6168 break;
6169 if (b == NULL)
6170 emacs_abort ();
6171 }
6172 #endif /* GC_CHECK_MARKED_OBJECTS */
6173 mark_buffer ((struct buffer *) ptr);
6174 break;
6175
6176 case PVEC_COMPILED:
6177 /* Although we could treat this just like a vector, mark_compiled
6178 returns the COMPILED_CONSTANTS element, which is marked at the
6179 next iteration of goto-loop here. This is done to avoid a few
6180 recursive calls to mark_object. */
6181 obj = mark_compiled (ptr);
6182 if (!NILP (obj))
6183 goto loop;
6184 break;
6185
6186 case PVEC_FRAME:
6187 {
6188 struct frame *f = (struct frame *) ptr;
6189
6190 mark_vectorlike (ptr);
6191 mark_face_cache (f->face_cache);
6192 #ifdef HAVE_WINDOW_SYSTEM
6193 if (FRAME_WINDOW_P (f) && FRAME_X_OUTPUT (f))
6194 {
6195 struct font *font = FRAME_FONT (f);
6196
6197 if (font && !VECTOR_MARKED_P (font))
6198 mark_vectorlike ((struct Lisp_Vector *) font);
6199 }
6200 #endif
6201 }
6202 break;
6203
6204 case PVEC_WINDOW:
6205 {
6206 struct window *w = (struct window *) ptr;
6207
6208 mark_vectorlike (ptr);
6209
6210 /* Mark glyph matrices, if any. Marking window
6211 matrices is sufficient because frame matrices
6212 use the same glyph memory. */
6213 if (w->current_matrix)
6214 {
6215 mark_glyph_matrix (w->current_matrix);
6216 mark_glyph_matrix (w->desired_matrix);
6217 }
6218
6219 /* Filter out killed buffers from both buffer lists
6220 in attempt to help GC to reclaim killed buffers faster.
6221 We can do it elsewhere for live windows, but this is the
6222 best place to do it for dead windows. */
6223 wset_prev_buffers
6224 (w, mark_discard_killed_buffers (w->prev_buffers));
6225 wset_next_buffers
6226 (w, mark_discard_killed_buffers (w->next_buffers));
6227 }
6228 break;
6229
6230 case PVEC_HASH_TABLE:
6231 {
6232 struct Lisp_Hash_Table *h = (struct Lisp_Hash_Table *) ptr;
6233
6234 mark_vectorlike (ptr);
6235 mark_object (h->test.name);
6236 mark_object (h->test.user_hash_function);
6237 mark_object (h->test.user_cmp_function);
6238 /* If hash table is not weak, mark all keys and values.
6239 For weak tables, mark only the vector. */
6240 if (NILP (h->weak))
6241 mark_object (h->key_and_value);
6242 else
6243 VECTOR_MARK (XVECTOR (h->key_and_value));
6244 }
6245 break;
6246
6247 case PVEC_CHAR_TABLE:
6248 case PVEC_SUB_CHAR_TABLE:
6249 mark_char_table (ptr, (enum pvec_type) pvectype);
6250 break;
6251
6252 case PVEC_BOOL_VECTOR:
6253 /* No Lisp_Objects to mark in a bool vector. */
6254 VECTOR_MARK (ptr);
6255 break;
6256
6257 case PVEC_SUBR:
6258 break;
6259
6260 case PVEC_FREE:
6261 emacs_abort ();
6262
6263 default:
6264 mark_vectorlike (ptr);
6265 }
6266 }
6267 break;
6268
6269 case Lisp_Symbol:
6270 {
6271 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
6272 nextsym:
6273 if (ptr->gcmarkbit)
6274 break;
6275 CHECK_ALLOCATED_AND_LIVE_SYMBOL ();
6276 ptr->gcmarkbit = 1;
6277 /* Attempt to catch bogus objects. */
6278 eassert (valid_lisp_object_p (ptr->function));
6279 mark_object (ptr->function);
6280 mark_object (ptr->plist);
6281 switch (ptr->redirect)
6282 {
6283 case SYMBOL_PLAINVAL: mark_object (SYMBOL_VAL (ptr)); break;
6284 case SYMBOL_VARALIAS:
6285 {
6286 Lisp_Object tem;
6287 XSETSYMBOL (tem, SYMBOL_ALIAS (ptr));
6288 mark_object (tem);
6289 break;
6290 }
6291 case SYMBOL_LOCALIZED:
6292 mark_localized_symbol (ptr);
6293 break;
6294 case SYMBOL_FORWARDED:
6295 /* If the value is forwarded to a buffer or keyboard field,
6296 these are marked when we see the corresponding object.
6297 And if it's forwarded to a C variable, either it's not
6298 a Lisp_Object var, or it's staticpro'd already. */
6299 break;
6300 default: emacs_abort ();
6301 }
6302 if (!PURE_P (XSTRING (ptr->name)))
6303 MARK_STRING (XSTRING (ptr->name));
6304 MARK_INTERVAL_TREE (string_intervals (ptr->name));
6305 /* Inner loop to mark next symbol in this bucket, if any. */
6306 po = ptr = ptr->next;
6307 if (ptr)
6308 goto nextsym;
6309 }
6310 break;
6311
6312 case Lisp_Misc:
6313 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
6314
6315 if (XMISCANY (obj)->gcmarkbit)
6316 break;
6317
6318 switch (XMISCTYPE (obj))
6319 {
6320 case Lisp_Misc_Marker:
6321 /* DO NOT mark thru the marker's chain.
6322 The buffer's markers chain does not preserve markers from gc;
6323 instead, markers are removed from the chain when freed by gc. */
6324 XMISCANY (obj)->gcmarkbit = 1;
6325 break;
6326
6327 case Lisp_Misc_Save_Value:
6328 XMISCANY (obj)->gcmarkbit = 1;
6329 mark_save_value (XSAVE_VALUE (obj));
6330 break;
6331
6332 case Lisp_Misc_Overlay:
6333 mark_overlay (XOVERLAY (obj));
6334 break;
6335
6336 case Lisp_Misc_Finalizer:
6337 XMISCANY (obj)->gcmarkbit = true;
6338 mark_object (XFINALIZER (obj)->function);
6339 break;
6340
6341 #ifdef HAVE_MODULES
6342 case Lisp_Misc_User_Ptr:
6343 XMISCANY (obj)->gcmarkbit = true;
6344 break;
6345 #endif
6346
6347 default:
6348 emacs_abort ();
6349 }
6350 break;
6351
6352 case Lisp_Cons:
6353 {
6354 register struct Lisp_Cons *ptr = XCONS (obj);
6355 if (CONS_MARKED_P (ptr))
6356 break;
6357 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
6358 CONS_MARK (ptr);
6359 /* If the cdr is nil, avoid recursion for the car. */
6360 if (EQ (ptr->u.cdr, Qnil))
6361 {
6362 obj = ptr->car;
6363 cdr_count = 0;
6364 goto loop;
6365 }
6366 mark_object (ptr->car);
6367 obj = ptr->u.cdr;
6368 cdr_count++;
6369 if (cdr_count == mark_object_loop_halt)
6370 emacs_abort ();
6371 goto loop;
6372 }
6373
6374 case Lisp_Float:
6375 CHECK_ALLOCATED_AND_LIVE (live_float_p);
6376 FLOAT_MARK (XFLOAT (obj));
6377 break;
6378
6379 case_Lisp_Int:
6380 break;
6381
6382 default:
6383 emacs_abort ();
6384 }
6385
6386 #undef CHECK_LIVE
6387 #undef CHECK_ALLOCATED
6388 #undef CHECK_ALLOCATED_AND_LIVE
6389 }
6390 /* Mark the Lisp pointers in the terminal objects.
6391 Called by Fgarbage_collect. */
6392
6393 static void
6394 mark_terminals (void)
6395 {
6396 struct terminal *t;
6397 for (t = terminal_list; t; t = t->next_terminal)
6398 {
6399 eassert (t->name != NULL);
6400 #ifdef HAVE_WINDOW_SYSTEM
6401 /* If a terminal object is reachable from a stacpro'ed object,
6402 it might have been marked already. Make sure the image cache
6403 gets marked. */
6404 mark_image_cache (t->image_cache);
6405 #endif /* HAVE_WINDOW_SYSTEM */
6406 if (!VECTOR_MARKED_P (t))
6407 mark_vectorlike ((struct Lisp_Vector *)t);
6408 }
6409 }
6410
6411
6412
6413 /* Value is non-zero if OBJ will survive the current GC because it's
6414 either marked or does not need to be marked to survive. */
6415
6416 bool
6417 survives_gc_p (Lisp_Object obj)
6418 {
6419 bool survives_p;
6420
6421 switch (XTYPE (obj))
6422 {
6423 case_Lisp_Int:
6424 survives_p = 1;
6425 break;
6426
6427 case Lisp_Symbol:
6428 survives_p = XSYMBOL (obj)->gcmarkbit;
6429 break;
6430
6431 case Lisp_Misc:
6432 survives_p = XMISCANY (obj)->gcmarkbit;
6433 break;
6434
6435 case Lisp_String:
6436 survives_p = STRING_MARKED_P (XSTRING (obj));
6437 break;
6438
6439 case Lisp_Vectorlike:
6440 survives_p = SUBRP (obj) || VECTOR_MARKED_P (XVECTOR (obj));
6441 break;
6442
6443 case Lisp_Cons:
6444 survives_p = CONS_MARKED_P (XCONS (obj));
6445 break;
6446
6447 case Lisp_Float:
6448 survives_p = FLOAT_MARKED_P (XFLOAT (obj));
6449 break;
6450
6451 default:
6452 emacs_abort ();
6453 }
6454
6455 return survives_p || PURE_P (XPNTR (obj));
6456 }
6457
6458
6459 \f
6460
6461 NO_INLINE /* For better stack traces */
6462 static void
6463 sweep_conses (void)
6464 {
6465 struct cons_block *cblk;
6466 struct cons_block **cprev = &cons_block;
6467 int lim = cons_block_index;
6468 EMACS_INT num_free = 0, num_used = 0;
6469
6470 cons_free_list = 0;
6471
6472 for (cblk = cons_block; cblk; cblk = *cprev)
6473 {
6474 int i = 0;
6475 int this_free = 0;
6476 int ilim = (lim + BITS_PER_BITS_WORD - 1) / BITS_PER_BITS_WORD;
6477
6478 /* Scan the mark bits an int at a time. */
6479 for (i = 0; i < ilim; i++)
6480 {
6481 if (cblk->gcmarkbits[i] == BITS_WORD_MAX)
6482 {
6483 /* Fast path - all cons cells for this int are marked. */
6484 cblk->gcmarkbits[i] = 0;
6485 num_used += BITS_PER_BITS_WORD;
6486 }
6487 else
6488 {
6489 /* Some cons cells for this int are not marked.
6490 Find which ones, and free them. */
6491 int start, pos, stop;
6492
6493 start = i * BITS_PER_BITS_WORD;
6494 stop = lim - start;
6495 if (stop > BITS_PER_BITS_WORD)
6496 stop = BITS_PER_BITS_WORD;
6497 stop += start;
6498
6499 for (pos = start; pos < stop; pos++)
6500 {
6501 if (!CONS_MARKED_P (&cblk->conses[pos]))
6502 {
6503 this_free++;
6504 cblk->conses[pos].u.chain = cons_free_list;
6505 cons_free_list = &cblk->conses[pos];
6506 cons_free_list->car = Vdead;
6507 }
6508 else
6509 {
6510 num_used++;
6511 CONS_UNMARK (&cblk->conses[pos]);
6512 }
6513 }
6514 }
6515 }
6516
6517 lim = CONS_BLOCK_SIZE;
6518 /* If this block contains only free conses and we have already
6519 seen more than two blocks worth of free conses then deallocate
6520 this block. */
6521 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
6522 {
6523 *cprev = cblk->next;
6524 /* Unhook from the free list. */
6525 cons_free_list = cblk->conses[0].u.chain;
6526 lisp_align_free (cblk);
6527 }
6528 else
6529 {
6530 num_free += this_free;
6531 cprev = &cblk->next;
6532 }
6533 }
6534 total_conses = num_used;
6535 total_free_conses = num_free;
6536 }
6537
6538 NO_INLINE /* For better stack traces */
6539 static void
6540 sweep_floats (void)
6541 {
6542 register struct float_block *fblk;
6543 struct float_block **fprev = &float_block;
6544 register int lim = float_block_index;
6545 EMACS_INT num_free = 0, num_used = 0;
6546
6547 float_free_list = 0;
6548
6549 for (fblk = float_block; fblk; fblk = *fprev)
6550 {
6551 register int i;
6552 int this_free = 0;
6553 for (i = 0; i < lim; i++)
6554 if (!FLOAT_MARKED_P (&fblk->floats[i]))
6555 {
6556 this_free++;
6557 fblk->floats[i].u.chain = float_free_list;
6558 float_free_list = &fblk->floats[i];
6559 }
6560 else
6561 {
6562 num_used++;
6563 FLOAT_UNMARK (&fblk->floats[i]);
6564 }
6565 lim = FLOAT_BLOCK_SIZE;
6566 /* If this block contains only free floats and we have already
6567 seen more than two blocks worth of free floats then deallocate
6568 this block. */
6569 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6570 {
6571 *fprev = fblk->next;
6572 /* Unhook from the free list. */
6573 float_free_list = fblk->floats[0].u.chain;
6574 lisp_align_free (fblk);
6575 }
6576 else
6577 {
6578 num_free += this_free;
6579 fprev = &fblk->next;
6580 }
6581 }
6582 total_floats = num_used;
6583 total_free_floats = num_free;
6584 }
6585
6586 NO_INLINE /* For better stack traces */
6587 static void
6588 sweep_intervals (void)
6589 {
6590 register struct interval_block *iblk;
6591 struct interval_block **iprev = &interval_block;
6592 register int lim = interval_block_index;
6593 EMACS_INT num_free = 0, num_used = 0;
6594
6595 interval_free_list = 0;
6596
6597 for (iblk = interval_block; iblk; iblk = *iprev)
6598 {
6599 register int i;
6600 int this_free = 0;
6601
6602 for (i = 0; i < lim; i++)
6603 {
6604 if (!iblk->intervals[i].gcmarkbit)
6605 {
6606 set_interval_parent (&iblk->intervals[i], interval_free_list);
6607 interval_free_list = &iblk->intervals[i];
6608 this_free++;
6609 }
6610 else
6611 {
6612 num_used++;
6613 iblk->intervals[i].gcmarkbit = 0;
6614 }
6615 }
6616 lim = INTERVAL_BLOCK_SIZE;
6617 /* If this block contains only free intervals and we have already
6618 seen more than two blocks worth of free intervals then
6619 deallocate this block. */
6620 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6621 {
6622 *iprev = iblk->next;
6623 /* Unhook from the free list. */
6624 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
6625 lisp_free (iblk);
6626 }
6627 else
6628 {
6629 num_free += this_free;
6630 iprev = &iblk->next;
6631 }
6632 }
6633 total_intervals = num_used;
6634 total_free_intervals = num_free;
6635 }
6636
6637 NO_INLINE /* For better stack traces */
6638 static void
6639 sweep_symbols (void)
6640 {
6641 struct symbol_block *sblk;
6642 struct symbol_block **sprev = &symbol_block;
6643 int lim = symbol_block_index;
6644 EMACS_INT num_free = 0, num_used = ARRAYELTS (lispsym);
6645
6646 symbol_free_list = NULL;
6647
6648 for (int i = 0; i < ARRAYELTS (lispsym); i++)
6649 lispsym[i].gcmarkbit = 0;
6650
6651 for (sblk = symbol_block; sblk; sblk = *sprev)
6652 {
6653 int this_free = 0;
6654 union aligned_Lisp_Symbol *sym = sblk->symbols;
6655 union aligned_Lisp_Symbol *end = sym + lim;
6656
6657 for (; sym < end; ++sym)
6658 {
6659 if (!sym->s.gcmarkbit)
6660 {
6661 if (sym->s.redirect == SYMBOL_LOCALIZED)
6662 xfree (SYMBOL_BLV (&sym->s));
6663 sym->s.next = symbol_free_list;
6664 symbol_free_list = &sym->s;
6665 symbol_free_list->function = Vdead;
6666 ++this_free;
6667 }
6668 else
6669 {
6670 ++num_used;
6671 sym->s.gcmarkbit = 0;
6672 /* Attempt to catch bogus objects. */
6673 eassert (valid_lisp_object_p (sym->s.function));
6674 }
6675 }
6676
6677 lim = SYMBOL_BLOCK_SIZE;
6678 /* If this block contains only free symbols and we have already
6679 seen more than two blocks worth of free symbols then deallocate
6680 this block. */
6681 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6682 {
6683 *sprev = sblk->next;
6684 /* Unhook from the free list. */
6685 symbol_free_list = sblk->symbols[0].s.next;
6686 lisp_free (sblk);
6687 }
6688 else
6689 {
6690 num_free += this_free;
6691 sprev = &sblk->next;
6692 }
6693 }
6694 total_symbols = num_used;
6695 total_free_symbols = num_free;
6696 }
6697
6698 NO_INLINE /* For better stack traces. */
6699 static void
6700 sweep_misc (void)
6701 {
6702 register struct marker_block *mblk;
6703 struct marker_block **mprev = &marker_block;
6704 register int lim = marker_block_index;
6705 EMACS_INT num_free = 0, num_used = 0;
6706
6707 /* Put all unmarked misc's on free list. For a marker, first
6708 unchain it from the buffer it points into. */
6709
6710 marker_free_list = 0;
6711
6712 for (mblk = marker_block; mblk; mblk = *mprev)
6713 {
6714 register int i;
6715 int this_free = 0;
6716
6717 for (i = 0; i < lim; i++)
6718 {
6719 if (!mblk->markers[i].m.u_any.gcmarkbit)
6720 {
6721 if (mblk->markers[i].m.u_any.type == Lisp_Misc_Marker)
6722 unchain_marker (&mblk->markers[i].m.u_marker);
6723 else if (mblk->markers[i].m.u_any.type == Lisp_Misc_Finalizer)
6724 unchain_finalizer (&mblk->markers[i].m.u_finalizer);
6725 #ifdef HAVE_MODULES
6726 else if (mblk->markers[i].m.u_any.type == Lisp_Misc_User_Ptr)
6727 {
6728 struct Lisp_User_Ptr *uptr = &mblk->markers[i].m.u_user_ptr;
6729 uptr->finalizer (uptr->p);
6730 }
6731 #endif
6732 /* Set the type of the freed object to Lisp_Misc_Free.
6733 We could leave the type alone, since nobody checks it,
6734 but this might catch bugs faster. */
6735 mblk->markers[i].m.u_marker.type = Lisp_Misc_Free;
6736 mblk->markers[i].m.u_free.chain = marker_free_list;
6737 marker_free_list = &mblk->markers[i].m;
6738 this_free++;
6739 }
6740 else
6741 {
6742 num_used++;
6743 mblk->markers[i].m.u_any.gcmarkbit = 0;
6744 }
6745 }
6746 lim = MARKER_BLOCK_SIZE;
6747 /* If this block contains only free markers and we have already
6748 seen more than two blocks worth of free markers then deallocate
6749 this block. */
6750 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6751 {
6752 *mprev = mblk->next;
6753 /* Unhook from the free list. */
6754 marker_free_list = mblk->markers[0].m.u_free.chain;
6755 lisp_free (mblk);
6756 }
6757 else
6758 {
6759 num_free += this_free;
6760 mprev = &mblk->next;
6761 }
6762 }
6763
6764 total_markers = num_used;
6765 total_free_markers = num_free;
6766 }
6767
6768 NO_INLINE /* For better stack traces */
6769 static void
6770 sweep_buffers (void)
6771 {
6772 register struct buffer *buffer, **bprev = &all_buffers;
6773
6774 total_buffers = 0;
6775 for (buffer = all_buffers; buffer; buffer = *bprev)
6776 if (!VECTOR_MARKED_P (buffer))
6777 {
6778 *bprev = buffer->next;
6779 lisp_free (buffer);
6780 }
6781 else
6782 {
6783 VECTOR_UNMARK (buffer);
6784 /* Do not use buffer_(set|get)_intervals here. */
6785 buffer->text->intervals = balance_intervals (buffer->text->intervals);
6786 total_buffers++;
6787 bprev = &buffer->next;
6788 }
6789 }
6790
6791 /* Sweep: find all structures not marked, and free them. */
6792 static void
6793 gc_sweep (void)
6794 {
6795 /* Remove or mark entries in weak hash tables.
6796 This must be done before any object is unmarked. */
6797 sweep_weak_hash_tables ();
6798
6799 sweep_strings ();
6800 check_string_bytes (!noninteractive);
6801 sweep_conses ();
6802 sweep_floats ();
6803 sweep_intervals ();
6804 sweep_symbols ();
6805 sweep_misc ();
6806 sweep_buffers ();
6807 sweep_vectors ();
6808 check_string_bytes (!noninteractive);
6809 }
6810
6811 DEFUN ("memory-info", Fmemory_info, Smemory_info, 0, 0, 0,
6812 doc: /* Return a list of (TOTAL-RAM FREE-RAM TOTAL-SWAP FREE-SWAP).
6813 All values are in Kbytes. If there is no swap space,
6814 last two values are zero. If the system is not supported
6815 or memory information can't be obtained, return nil. */)
6816 (void)
6817 {
6818 #if defined HAVE_LINUX_SYSINFO
6819 struct sysinfo si;
6820 uintmax_t units;
6821
6822 if (sysinfo (&si))
6823 return Qnil;
6824 #ifdef LINUX_SYSINFO_UNIT
6825 units = si.mem_unit;
6826 #else
6827 units = 1;
6828 #endif
6829 return list4i ((uintmax_t) si.totalram * units / 1024,
6830 (uintmax_t) si.freeram * units / 1024,
6831 (uintmax_t) si.totalswap * units / 1024,
6832 (uintmax_t) si.freeswap * units / 1024);
6833 #elif defined WINDOWSNT
6834 unsigned long long totalram, freeram, totalswap, freeswap;
6835
6836 if (w32_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
6837 return list4i ((uintmax_t) totalram / 1024,
6838 (uintmax_t) freeram / 1024,
6839 (uintmax_t) totalswap / 1024,
6840 (uintmax_t) freeswap / 1024);
6841 else
6842 return Qnil;
6843 #elif defined MSDOS
6844 unsigned long totalram, freeram, totalswap, freeswap;
6845
6846 if (dos_memory_info (&totalram, &freeram, &totalswap, &freeswap) == 0)
6847 return list4i ((uintmax_t) totalram / 1024,
6848 (uintmax_t) freeram / 1024,
6849 (uintmax_t) totalswap / 1024,
6850 (uintmax_t) freeswap / 1024);
6851 else
6852 return Qnil;
6853 #else /* not HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
6854 /* FIXME: add more systems. */
6855 return Qnil;
6856 #endif /* HAVE_LINUX_SYSINFO, not WINDOWSNT, not MSDOS */
6857 }
6858
6859 /* Debugging aids. */
6860
6861 DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
6862 doc: /* Return the address of the last byte Emacs has allocated, divided by 1024.
6863 This may be helpful in debugging Emacs's memory usage.
6864 We divide the value by 1024 to make sure it fits in a Lisp integer. */)
6865 (void)
6866 {
6867 Lisp_Object end;
6868
6869 #ifdef HAVE_NS
6870 /* Avoid warning. sbrk has no relation to memory allocated anyway. */
6871 XSETINT (end, 0);
6872 #else
6873 XSETINT (end, (intptr_t) (char *) sbrk (0) / 1024);
6874 #endif
6875
6876 return end;
6877 }
6878
6879 DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
6880 doc: /* Return a list of counters that measure how much consing there has been.
6881 Each of these counters increments for a certain kind of object.
6882 The counters wrap around from the largest positive integer to zero.
6883 Garbage collection does not decrease them.
6884 The elements of the value are as follows:
6885 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)
6886 All are in units of 1 = one object consed
6887 except for VECTOR-CELLS and STRING-CHARS, which count the total length of
6888 objects consed.
6889 MISCS include overlays, markers, and some internal types.
6890 Frames, windows, buffers, and subprocesses count as vectors
6891 (but the contents of a buffer's text do not count here). */)
6892 (void)
6893 {
6894 return listn (CONSTYPE_HEAP, 8,
6895 bounded_number (cons_cells_consed),
6896 bounded_number (floats_consed),
6897 bounded_number (vector_cells_consed),
6898 bounded_number (symbols_consed),
6899 bounded_number (string_chars_consed),
6900 bounded_number (misc_objects_consed),
6901 bounded_number (intervals_consed),
6902 bounded_number (strings_consed));
6903 }
6904
6905 static bool
6906 symbol_uses_obj (Lisp_Object symbol, Lisp_Object obj)
6907 {
6908 struct Lisp_Symbol *sym = XSYMBOL (symbol);
6909 Lisp_Object val = find_symbol_value (symbol);
6910 return (EQ (val, obj)
6911 || EQ (sym->function, obj)
6912 || (!NILP (sym->function)
6913 && COMPILEDP (sym->function)
6914 && EQ (AREF (sym->function, COMPILED_BYTECODE), obj))
6915 || (!NILP (val)
6916 && COMPILEDP (val)
6917 && EQ (AREF (val, COMPILED_BYTECODE), obj)));
6918 }
6919
6920 /* Find at most FIND_MAX symbols which have OBJ as their value or
6921 function. This is used in gdbinit's `xwhichsymbols' command. */
6922
6923 Lisp_Object
6924 which_symbols (Lisp_Object obj, EMACS_INT find_max)
6925 {
6926 struct symbol_block *sblk;
6927 ptrdiff_t gc_count = inhibit_garbage_collection ();
6928 Lisp_Object found = Qnil;
6929
6930 if (! DEADP (obj))
6931 {
6932 for (int i = 0; i < ARRAYELTS (lispsym); i++)
6933 {
6934 Lisp_Object sym = builtin_lisp_symbol (i);
6935 if (symbol_uses_obj (sym, obj))
6936 {
6937 found = Fcons (sym, found);
6938 if (--find_max == 0)
6939 goto out;
6940 }
6941 }
6942
6943 for (sblk = symbol_block; sblk; sblk = sblk->next)
6944 {
6945 union aligned_Lisp_Symbol *aligned_sym = sblk->symbols;
6946 int bn;
6947
6948 for (bn = 0; bn < SYMBOL_BLOCK_SIZE; bn++, aligned_sym++)
6949 {
6950 if (sblk == symbol_block && bn >= symbol_block_index)
6951 break;
6952
6953 Lisp_Object sym = make_lisp_symbol (&aligned_sym->s);
6954 if (symbol_uses_obj (sym, obj))
6955 {
6956 found = Fcons (sym, found);
6957 if (--find_max == 0)
6958 goto out;
6959 }
6960 }
6961 }
6962 }
6963
6964 out:
6965 unbind_to (gc_count, Qnil);
6966 return found;
6967 }
6968
6969 #ifdef SUSPICIOUS_OBJECT_CHECKING
6970
6971 static void *
6972 find_suspicious_object_in_range (void *begin, void *end)
6973 {
6974 char *begin_a = begin;
6975 char *end_a = end;
6976 int i;
6977
6978 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
6979 {
6980 char *suspicious_object = suspicious_objects[i];
6981 if (begin_a <= suspicious_object && suspicious_object < end_a)
6982 return suspicious_object;
6983 }
6984
6985 return NULL;
6986 }
6987
6988 static void
6989 note_suspicious_free (void* ptr)
6990 {
6991 struct suspicious_free_record* rec;
6992
6993 rec = &suspicious_free_history[suspicious_free_history_index++];
6994 if (suspicious_free_history_index ==
6995 ARRAYELTS (suspicious_free_history))
6996 {
6997 suspicious_free_history_index = 0;
6998 }
6999
7000 memset (rec, 0, sizeof (*rec));
7001 rec->suspicious_object = ptr;
7002 backtrace (&rec->backtrace[0], ARRAYELTS (rec->backtrace));
7003 }
7004
7005 static void
7006 detect_suspicious_free (void* ptr)
7007 {
7008 int i;
7009
7010 eassert (ptr != NULL);
7011
7012 for (i = 0; i < ARRAYELTS (suspicious_objects); ++i)
7013 if (suspicious_objects[i] == ptr)
7014 {
7015 note_suspicious_free (ptr);
7016 suspicious_objects[i] = NULL;
7017 }
7018 }
7019
7020 #endif /* SUSPICIOUS_OBJECT_CHECKING */
7021
7022 DEFUN ("suspicious-object", Fsuspicious_object, Ssuspicious_object, 1, 1, 0,
7023 doc: /* Return OBJ, maybe marking it for extra scrutiny.
7024 If Emacs is compiled with suspicious object checking, capture
7025 a stack trace when OBJ is freed in order to help track down
7026 garbage collection bugs. Otherwise, do nothing and return OBJ. */)
7027 (Lisp_Object obj)
7028 {
7029 #ifdef SUSPICIOUS_OBJECT_CHECKING
7030 /* Right now, we care only about vectors. */
7031 if (VECTORLIKEP (obj))
7032 {
7033 suspicious_objects[suspicious_object_index++] = XVECTOR (obj);
7034 if (suspicious_object_index == ARRAYELTS (suspicious_objects))
7035 suspicious_object_index = 0;
7036 }
7037 #endif
7038 return obj;
7039 }
7040
7041 #ifdef ENABLE_CHECKING
7042
7043 bool suppress_checking;
7044
7045 void
7046 die (const char *msg, const char *file, int line)
7047 {
7048 fprintf (stderr, "\r\n%s:%d: Emacs fatal error: assertion failed: %s\r\n",
7049 file, line, msg);
7050 terminate_due_to_signal (SIGABRT, INT_MAX);
7051 }
7052
7053 #endif /* ENABLE_CHECKING */
7054
7055 #if defined (ENABLE_CHECKING) && USE_STACK_LISP_OBJECTS
7056
7057 /* Debugging check whether STR is ASCII-only. */
7058
7059 const char *
7060 verify_ascii (const char *str)
7061 {
7062 const unsigned char *ptr = (unsigned char *) str, *end = ptr + strlen (str);
7063 while (ptr < end)
7064 {
7065 int c = STRING_CHAR_ADVANCE (ptr);
7066 if (!ASCII_CHAR_P (c))
7067 emacs_abort ();
7068 }
7069 return str;
7070 }
7071
7072 /* Stress alloca with inconveniently sized requests and check
7073 whether all allocated areas may be used for Lisp_Object. */
7074
7075 NO_INLINE static void
7076 verify_alloca (void)
7077 {
7078 int i;
7079 enum { ALLOCA_CHECK_MAX = 256 };
7080 /* Start from size of the smallest Lisp object. */
7081 for (i = sizeof (struct Lisp_Cons); i <= ALLOCA_CHECK_MAX; i++)
7082 {
7083 void *ptr = alloca (i);
7084 make_lisp_ptr (ptr, Lisp_Cons);
7085 }
7086 }
7087
7088 #else /* not ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7089
7090 #define verify_alloca() ((void) 0)
7091
7092 #endif /* ENABLE_CHECKING && USE_STACK_LISP_OBJECTS */
7093
7094 /* Initialization. */
7095
7096 void
7097 init_alloc_once (void)
7098 {
7099 /* Even though Qt's contents are not set up, its address is known. */
7100 Vpurify_flag = Qt;
7101
7102 purebeg = PUREBEG;
7103 pure_size = PURESIZE;
7104
7105 verify_alloca ();
7106 init_finalizer_list (&finalizers);
7107 init_finalizer_list (&doomed_finalizers);
7108
7109 mem_init ();
7110 Vdead = make_pure_string ("DEAD", 4, 4, 0);
7111
7112 #ifdef DOUG_LEA_MALLOC
7113 mallopt (M_TRIM_THRESHOLD, 128 * 1024); /* Trim threshold. */
7114 mallopt (M_MMAP_THRESHOLD, 64 * 1024); /* Mmap threshold. */
7115 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* Max. number of mmap'ed areas. */
7116 #endif
7117 init_strings ();
7118 init_vectors ();
7119
7120 refill_memory_reserve ();
7121 gc_cons_threshold = GC_DEFAULT_THRESHOLD;
7122 }
7123
7124 void
7125 init_alloc (void)
7126 {
7127 #if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
7128 setjmp_tested_p = longjmps_done = 0;
7129 #endif
7130 Vgc_elapsed = make_float (0.0);
7131 gcs_done = 0;
7132
7133 #if USE_VALGRIND
7134 valgrind_p = RUNNING_ON_VALGRIND != 0;
7135 #endif
7136 }
7137
7138 void
7139 syms_of_alloc (void)
7140 {
7141 DEFVAR_INT ("gc-cons-threshold", gc_cons_threshold,
7142 doc: /* Number of bytes of consing between garbage collections.
7143 Garbage collection can happen automatically once this many bytes have been
7144 allocated since the last garbage collection. All data types count.
7145
7146 Garbage collection happens automatically only when `eval' is called.
7147
7148 By binding this temporarily to a large number, you can effectively
7149 prevent garbage collection during a part of the program.
7150 See also `gc-cons-percentage'. */);
7151
7152 DEFVAR_LISP ("gc-cons-percentage", Vgc_cons_percentage,
7153 doc: /* Portion of the heap used for allocation.
7154 Garbage collection can happen automatically once this portion of the heap
7155 has been allocated since the last garbage collection.
7156 If this portion is smaller than `gc-cons-threshold', this is ignored. */);
7157 Vgc_cons_percentage = make_float (0.1);
7158
7159 DEFVAR_INT ("pure-bytes-used", pure_bytes_used,
7160 doc: /* Number of bytes of shareable Lisp data allocated so far. */);
7161
7162 DEFVAR_INT ("cons-cells-consed", cons_cells_consed,
7163 doc: /* Number of cons cells that have been consed so far. */);
7164
7165 DEFVAR_INT ("floats-consed", floats_consed,
7166 doc: /* Number of floats that have been consed so far. */);
7167
7168 DEFVAR_INT ("vector-cells-consed", vector_cells_consed,
7169 doc: /* Number of vector cells that have been consed so far. */);
7170
7171 DEFVAR_INT ("symbols-consed", symbols_consed,
7172 doc: /* Number of symbols that have been consed so far. */);
7173 symbols_consed += ARRAYELTS (lispsym);
7174
7175 DEFVAR_INT ("string-chars-consed", string_chars_consed,
7176 doc: /* Number of string characters that have been consed so far. */);
7177
7178 DEFVAR_INT ("misc-objects-consed", misc_objects_consed,
7179 doc: /* Number of miscellaneous objects that have been consed so far.
7180 These include markers and overlays, plus certain objects not visible
7181 to users. */);
7182
7183 DEFVAR_INT ("intervals-consed", intervals_consed,
7184 doc: /* Number of intervals that have been consed so far. */);
7185
7186 DEFVAR_INT ("strings-consed", strings_consed,
7187 doc: /* Number of strings that have been consed so far. */);
7188
7189 DEFVAR_LISP ("purify-flag", Vpurify_flag,
7190 doc: /* Non-nil means loading Lisp code in order to dump an executable.
7191 This means that certain objects should be allocated in shared (pure) space.
7192 It can also be set to a hash-table, in which case this table is used to
7193 do hash-consing of the objects allocated to pure space. */);
7194
7195 DEFVAR_BOOL ("garbage-collection-messages", garbage_collection_messages,
7196 doc: /* Non-nil means display messages at start and end of garbage collection. */);
7197 garbage_collection_messages = 0;
7198
7199 DEFVAR_LISP ("post-gc-hook", Vpost_gc_hook,
7200 doc: /* Hook run after garbage collection has finished. */);
7201 Vpost_gc_hook = Qnil;
7202 DEFSYM (Qpost_gc_hook, "post-gc-hook");
7203
7204 DEFVAR_LISP ("memory-signal-data", Vmemory_signal_data,
7205 doc: /* Precomputed `signal' argument for memory-full error. */);
7206 /* We build this in advance because if we wait until we need it, we might
7207 not be able to allocate the memory to hold it. */
7208 Vmemory_signal_data
7209 = listn (CONSTYPE_PURE, 2, Qerror,
7210 build_pure_c_string ("Memory exhausted--use M-x save-some-buffers then exit and restart Emacs"));
7211
7212 DEFVAR_LISP ("memory-full", Vmemory_full,
7213 doc: /* Non-nil means Emacs cannot get much more Lisp memory. */);
7214 Vmemory_full = Qnil;
7215
7216 DEFSYM (Qconses, "conses");
7217 DEFSYM (Qsymbols, "symbols");
7218 DEFSYM (Qmiscs, "miscs");
7219 DEFSYM (Qstrings, "strings");
7220 DEFSYM (Qvectors, "vectors");
7221 DEFSYM (Qfloats, "floats");
7222 DEFSYM (Qintervals, "intervals");
7223 DEFSYM (Qbuffers, "buffers");
7224 DEFSYM (Qstring_bytes, "string-bytes");
7225 DEFSYM (Qvector_slots, "vector-slots");
7226 DEFSYM (Qheap, "heap");
7227 DEFSYM (Qautomatic_gc, "Automatic GC");
7228
7229 DEFSYM (Qgc_cons_threshold, "gc-cons-threshold");
7230 DEFSYM (Qchar_table_extra_slots, "char-table-extra-slots");
7231
7232 DEFVAR_LISP ("gc-elapsed", Vgc_elapsed,
7233 doc: /* Accumulated time elapsed in garbage collections.
7234 The time is in seconds as a floating point value. */);
7235 DEFVAR_INT ("gcs-done", gcs_done,
7236 doc: /* Accumulated number of garbage collections done. */);
7237
7238 defsubr (&Scons);
7239 defsubr (&Slist);
7240 defsubr (&Svector);
7241 defsubr (&Sbool_vector);
7242 defsubr (&Smake_byte_code);
7243 defsubr (&Smake_list);
7244 defsubr (&Smake_vector);
7245 defsubr (&Smake_string);
7246 defsubr (&Smake_bool_vector);
7247 defsubr (&Smake_symbol);
7248 defsubr (&Smake_marker);
7249 defsubr (&Smake_finalizer);
7250 defsubr (&Spurecopy);
7251 defsubr (&Sgarbage_collect);
7252 defsubr (&Smemory_limit);
7253 defsubr (&Smemory_info);
7254 defsubr (&Smemory_use_counts);
7255 defsubr (&Ssuspicious_object);
7256 }
7257
7258 /* When compiled with GCC, GDB might say "No enum type named
7259 pvec_type" if we don't have at least one symbol with that type, and
7260 then xbacktrace could fail. Similarly for the other enums and
7261 their values. Some non-GCC compilers don't like these constructs. */
7262 #ifdef __GNUC__
7263 union
7264 {
7265 enum CHARTAB_SIZE_BITS CHARTAB_SIZE_BITS;
7266 enum char_table_specials char_table_specials;
7267 enum char_bits char_bits;
7268 enum CHECK_LISP_OBJECT_TYPE CHECK_LISP_OBJECT_TYPE;
7269 enum DEFAULT_HASH_SIZE DEFAULT_HASH_SIZE;
7270 enum Lisp_Bits Lisp_Bits;
7271 enum Lisp_Compiled Lisp_Compiled;
7272 enum maxargs maxargs;
7273 enum MAX_ALLOCA MAX_ALLOCA;
7274 enum More_Lisp_Bits More_Lisp_Bits;
7275 enum pvec_type pvec_type;
7276 } const EXTERNALLY_VISIBLE gdb_make_enums_visible = {0};
7277 #endif /* __GNUC__ */