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