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