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