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