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