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