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