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