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