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