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