(Charsets): mention windows-1252
[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
83a96b4d
AC
1325 if (!noninteractive
1326#ifdef macintosh
1327 && current_sblock
1328#endif
1329 )
361b097f 1330 {
676a7251
GM
1331 if (++check_string_bytes_count == 200)
1332 {
1333 check_string_bytes_count = 0;
1334 check_string_bytes (1);
1335 }
1336 else
1337 check_string_bytes (0);
361b097f 1338 }
676a7251 1339#endif /* GC_CHECK_STRING_BYTES */
361b097f 1340
2e471eb5 1341 return s;
c0f51373 1342}
7146af97 1343
7146af97 1344
2e471eb5
GM
1345/* Set up Lisp_String S for holding NCHARS characters, NBYTES bytes,
1346 plus a NUL byte at the end. Allocate an sdata structure for S, and
1347 set S->data to its `u.data' member. Store a NUL byte at the end of
1348 S->data. Set S->size to NCHARS and S->size_byte to NBYTES. Free
1349 S->data if it was initially non-null. */
7146af97 1350
2e471eb5
GM
1351void
1352allocate_string_data (s, nchars, nbytes)
1353 struct Lisp_String *s;
1354 int nchars, nbytes;
7146af97 1355{
5c5fecb3 1356 struct sdata *data, *old_data;
2e471eb5 1357 struct sblock *b;
5c5fecb3 1358 int needed, old_nbytes;
7146af97 1359
2e471eb5
GM
1360 /* Determine the number of bytes needed to store NBYTES bytes
1361 of string data. */
1362 needed = SDATA_SIZE (nbytes);
7146af97 1363
2e471eb5
GM
1364 if (nbytes > LARGE_STRING_BYTES)
1365 {
675d5130 1366 size_t size = sizeof *b - sizeof (struct sdata) + needed;
2e471eb5
GM
1367
1368#ifdef DOUG_LEA_MALLOC
f8608968
GM
1369 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
1370 because mapped region contents are not preserved in
1371 a dumped Emacs. */
2e471eb5
GM
1372 mallopt (M_MMAP_MAX, 0);
1373#endif
1374
34400008 1375 b = (struct sblock *) lisp_malloc (size, MEM_TYPE_NON_LISP);
2e471eb5
GM
1376
1377#ifdef DOUG_LEA_MALLOC
1378 /* Back to a reasonable maximum of mmap'ed areas. */
1379 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
1380#endif
1381
1382 b->next_free = &b->first_data;
1383 b->first_data.string = NULL;
1384 b->next = large_sblocks;
1385 large_sblocks = b;
1386 }
1387 else if (current_sblock == NULL
1388 || (((char *) current_sblock + SBLOCK_SIZE
1389 - (char *) current_sblock->next_free)
1390 < needed))
1391 {
1392 /* Not enough room in the current sblock. */
34400008 1393 b = (struct sblock *) lisp_malloc (SBLOCK_SIZE, MEM_TYPE_NON_LISP);
2e471eb5
GM
1394 b->next_free = &b->first_data;
1395 b->first_data.string = NULL;
1396 b->next = NULL;
1397
1398 if (current_sblock)
1399 current_sblock->next = b;
1400 else
1401 oldest_sblock = b;
1402 current_sblock = b;
1403 }
1404 else
1405 b = current_sblock;
5c5fecb3
GM
1406
1407 old_data = s->data ? SDATA_OF_STRING (s) : NULL;
1408 old_nbytes = GC_STRING_BYTES (s);
2e471eb5
GM
1409
1410 data = b->next_free;
1411 data->string = s;
31d929e5
GM
1412 s->data = SDATA_DATA (data);
1413#ifdef GC_CHECK_STRING_BYTES
1414 SDATA_NBYTES (data) = nbytes;
1415#endif
2e471eb5
GM
1416 s->size = nchars;
1417 s->size_byte = nbytes;
1418 s->data[nbytes] = '\0';
1419 b->next_free = (struct sdata *) ((char *) data + needed);
1420
5c5fecb3
GM
1421 /* If S had already data assigned, mark that as free by setting its
1422 string back-pointer to null, and recording the size of the data
00c9c33c 1423 in it. */
5c5fecb3
GM
1424 if (old_data)
1425 {
31d929e5 1426 SDATA_NBYTES (old_data) = old_nbytes;
5c5fecb3
GM
1427 old_data->string = NULL;
1428 }
1429
2e471eb5
GM
1430 consing_since_gc += needed;
1431}
1432
1433
1434/* Sweep and compact strings. */
1435
1436static void
1437sweep_strings ()
1438{
1439 struct string_block *b, *next;
1440 struct string_block *live_blocks = NULL;
1441
1442 string_free_list = NULL;
1443 total_strings = total_free_strings = 0;
1444 total_string_size = 0;
1445
1446 /* Scan strings_blocks, free Lisp_Strings that aren't marked. */
1447 for (b = string_blocks; b; b = next)
1448 {
1449 int i, nfree = 0;
1450 struct Lisp_String *free_list_before = string_free_list;
1451
1452 next = b->next;
1453
1454 for (i = 0; i < STRINGS_IN_STRING_BLOCK; ++i)
1455 {
1456 struct Lisp_String *s = b->strings + i;
1457
1458 if (s->data)
1459 {
1460 /* String was not on free-list before. */
1461 if (STRING_MARKED_P (s))
1462 {
1463 /* String is live; unmark it and its intervals. */
1464 UNMARK_STRING (s);
1465
1466 if (!NULL_INTERVAL_P (s->intervals))
1467 UNMARK_BALANCE_INTERVALS (s->intervals);
1468
1469 ++total_strings;
1470 total_string_size += STRING_BYTES (s);
1471 }
1472 else
1473 {
1474 /* String is dead. Put it on the free-list. */
1475 struct sdata *data = SDATA_OF_STRING (s);
1476
1477 /* Save the size of S in its sdata so that we know
1478 how large that is. Reset the sdata's string
1479 back-pointer so that we know it's free. */
31d929e5
GM
1480#ifdef GC_CHECK_STRING_BYTES
1481 if (GC_STRING_BYTES (s) != SDATA_NBYTES (data))
1482 abort ();
1483#else
2e471eb5 1484 data->u.nbytes = GC_STRING_BYTES (s);
31d929e5 1485#endif
2e471eb5
GM
1486 data->string = NULL;
1487
1488 /* Reset the strings's `data' member so that we
1489 know it's free. */
1490 s->data = NULL;
1491
1492 /* Put the string on the free-list. */
1493 NEXT_FREE_LISP_STRING (s) = string_free_list;
1494 string_free_list = s;
1495 ++nfree;
1496 }
1497 }
1498 else
1499 {
1500 /* S was on the free-list before. Put it there again. */
1501 NEXT_FREE_LISP_STRING (s) = string_free_list;
1502 string_free_list = s;
1503 ++nfree;
1504 }
1505 }
1506
34400008 1507 /* Free blocks that contain free Lisp_Strings only, except
2e471eb5
GM
1508 the first two of them. */
1509 if (nfree == STRINGS_IN_STRING_BLOCK
1510 && total_free_strings > STRINGS_IN_STRING_BLOCK)
1511 {
1512 lisp_free (b);
1513 --n_string_blocks;
1514 string_free_list = free_list_before;
1515 }
1516 else
1517 {
1518 total_free_strings += nfree;
1519 b->next = live_blocks;
1520 live_blocks = b;
1521 }
1522 }
1523
1524 string_blocks = live_blocks;
1525 free_large_strings ();
1526 compact_small_strings ();
1527}
1528
1529
1530/* Free dead large strings. */
1531
1532static void
1533free_large_strings ()
1534{
1535 struct sblock *b, *next;
1536 struct sblock *live_blocks = NULL;
1537
1538 for (b = large_sblocks; b; b = next)
1539 {
1540 next = b->next;
1541
1542 if (b->first_data.string == NULL)
1543 lisp_free (b);
1544 else
1545 {
1546 b->next = live_blocks;
1547 live_blocks = b;
1548 }
1549 }
1550
1551 large_sblocks = live_blocks;
1552}
1553
1554
1555/* Compact data of small strings. Free sblocks that don't contain
1556 data of live strings after compaction. */
1557
1558static void
1559compact_small_strings ()
1560{
1561 struct sblock *b, *tb, *next;
1562 struct sdata *from, *to, *end, *tb_end;
1563 struct sdata *to_end, *from_end;
1564
1565 /* TB is the sblock we copy to, TO is the sdata within TB we copy
1566 to, and TB_END is the end of TB. */
1567 tb = oldest_sblock;
1568 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1569 to = &tb->first_data;
1570
1571 /* Step through the blocks from the oldest to the youngest. We
1572 expect that old blocks will stabilize over time, so that less
1573 copying will happen this way. */
1574 for (b = oldest_sblock; b; b = b->next)
1575 {
1576 end = b->next_free;
1577 xassert ((char *) end <= (char *) b + SBLOCK_SIZE);
1578
1579 for (from = &b->first_data; from < end; from = from_end)
1580 {
1581 /* Compute the next FROM here because copying below may
1582 overwrite data we need to compute it. */
1583 int nbytes;
1584
31d929e5
GM
1585#ifdef GC_CHECK_STRING_BYTES
1586 /* Check that the string size recorded in the string is the
1587 same as the one recorded in the sdata structure. */
1588 if (from->string
1589 && GC_STRING_BYTES (from->string) != SDATA_NBYTES (from))
1590 abort ();
1591#endif /* GC_CHECK_STRING_BYTES */
1592
2e471eb5
GM
1593 if (from->string)
1594 nbytes = GC_STRING_BYTES (from->string);
1595 else
31d929e5 1596 nbytes = SDATA_NBYTES (from);
2e471eb5
GM
1597
1598 nbytes = SDATA_SIZE (nbytes);
1599 from_end = (struct sdata *) ((char *) from + nbytes);
1600
1601 /* FROM->string non-null means it's alive. Copy its data. */
1602 if (from->string)
1603 {
1604 /* If TB is full, proceed with the next sblock. */
1605 to_end = (struct sdata *) ((char *) to + nbytes);
1606 if (to_end > tb_end)
1607 {
1608 tb->next_free = to;
1609 tb = tb->next;
1610 tb_end = (struct sdata *) ((char *) tb + SBLOCK_SIZE);
1611 to = &tb->first_data;
1612 to_end = (struct sdata *) ((char *) to + nbytes);
1613 }
1614
1615 /* Copy, and update the string's `data' pointer. */
1616 if (from != to)
1617 {
a2407477
GM
1618 xassert (tb != b || to <= from);
1619 safe_bcopy ((char *) from, (char *) to, nbytes);
31d929e5 1620 to->string->data = SDATA_DATA (to);
2e471eb5
GM
1621 }
1622
1623 /* Advance past the sdata we copied to. */
1624 to = to_end;
1625 }
1626 }
1627 }
1628
1629 /* The rest of the sblocks following TB don't contain live data, so
1630 we can free them. */
1631 for (b = tb->next; b; b = next)
1632 {
1633 next = b->next;
1634 lisp_free (b);
1635 }
1636
1637 tb->next_free = to;
1638 tb->next = NULL;
1639 current_sblock = tb;
1640}
1641
1642
1643DEFUN ("make-string", Fmake_string, Smake_string, 2, 2, 0,
1644 "Return a newly created string of length LENGTH, with each element being INIT.\n\
1645Both LENGTH and INIT must be numbers.")
1646 (length, init)
1647 Lisp_Object length, init;
1648{
1649 register Lisp_Object val;
1650 register unsigned char *p, *end;
1651 int c, nbytes;
1652
1653 CHECK_NATNUM (length, 0);
1654 CHECK_NUMBER (init, 1);
1655
1656 c = XINT (init);
1657 if (SINGLE_BYTE_CHAR_P (c))
1658 {
1659 nbytes = XINT (length);
1660 val = make_uninit_string (nbytes);
1661 p = XSTRING (val)->data;
1662 end = p + XSTRING (val)->size;
1663 while (p != end)
1664 *p++ = c;
1665 }
1666 else
1667 {
d942b71c 1668 unsigned char str[MAX_MULTIBYTE_LENGTH];
2e471eb5
GM
1669 int len = CHAR_STRING (c, str);
1670
1671 nbytes = len * XINT (length);
1672 val = make_uninit_multibyte_string (XINT (length), nbytes);
1673 p = XSTRING (val)->data;
1674 end = p + nbytes;
1675 while (p != end)
1676 {
1677 bcopy (str, p, len);
1678 p += len;
1679 }
1680 }
1681
1682 *p = 0;
1683 return val;
1684}
1685
1686
1687DEFUN ("make-bool-vector", Fmake_bool_vector, Smake_bool_vector, 2, 2, 0,
1688 "Return a new bool-vector of length LENGTH, using INIT for as each element.\n\
1689LENGTH must be a number. INIT matters only in whether it is t or nil.")
1690 (length, init)
1691 Lisp_Object length, init;
1692{
1693 register Lisp_Object val;
1694 struct Lisp_Bool_Vector *p;
1695 int real_init, i;
1696 int length_in_chars, length_in_elts, bits_per_value;
1697
1698 CHECK_NATNUM (length, 0);
1699
1700 bits_per_value = sizeof (EMACS_INT) * BITS_PER_CHAR;
1701
1702 length_in_elts = (XFASTINT (length) + bits_per_value - 1) / bits_per_value;
1703 length_in_chars = ((XFASTINT (length) + BITS_PER_CHAR - 1) / BITS_PER_CHAR);
1704
1705 /* We must allocate one more elements than LENGTH_IN_ELTS for the
1706 slot `size' of the struct Lisp_Bool_Vector. */
1707 val = Fmake_vector (make_number (length_in_elts + 1), Qnil);
1708 p = XBOOL_VECTOR (val);
34400008 1709
2e471eb5
GM
1710 /* Get rid of any bits that would cause confusion. */
1711 p->vector_size = 0;
1712 XSETBOOL_VECTOR (val, p);
1713 p->size = XFASTINT (length);
1714
1715 real_init = (NILP (init) ? 0 : -1);
1716 for (i = 0; i < length_in_chars ; i++)
1717 p->data[i] = real_init;
34400008 1718
2e471eb5
GM
1719 /* Clear the extraneous bits in the last byte. */
1720 if (XINT (length) != length_in_chars * BITS_PER_CHAR)
1721 XBOOL_VECTOR (val)->data[length_in_chars - 1]
1722 &= (1 << (XINT (length) % BITS_PER_CHAR)) - 1;
1723
1724 return val;
1725}
1726
1727
1728/* Make a string from NBYTES bytes at CONTENTS, and compute the number
1729 of characters from the contents. This string may be unibyte or
1730 multibyte, depending on the contents. */
1731
1732Lisp_Object
1733make_string (contents, nbytes)
1734 char *contents;
1735 int nbytes;
1736{
1737 register Lisp_Object val;
9eac9d59
KH
1738 int nchars, multibyte_nbytes;
1739
1740 parse_str_as_multibyte (contents, nbytes, &nchars, &multibyte_nbytes);
9eac9d59
KH
1741 if (nbytes == nchars || nbytes != multibyte_nbytes)
1742 /* CONTENTS contains no multibyte sequences or contains an invalid
1743 multibyte sequence. We must make unibyte string. */
495a6df3
KH
1744 val = make_unibyte_string (contents, nbytes);
1745 else
1746 val = make_multibyte_string (contents, nchars, nbytes);
2e471eb5
GM
1747 return val;
1748}
1749
1750
1751/* Make an unibyte string from LENGTH bytes at CONTENTS. */
1752
1753Lisp_Object
1754make_unibyte_string (contents, length)
1755 char *contents;
1756 int length;
1757{
1758 register Lisp_Object val;
1759 val = make_uninit_string (length);
1760 bcopy (contents, XSTRING (val)->data, length);
1761 SET_STRING_BYTES (XSTRING (val), -1);
1762 return val;
1763}
1764
1765
1766/* Make a multibyte string from NCHARS characters occupying NBYTES
1767 bytes at CONTENTS. */
1768
1769Lisp_Object
1770make_multibyte_string (contents, nchars, nbytes)
1771 char *contents;
1772 int nchars, nbytes;
1773{
1774 register Lisp_Object val;
1775 val = make_uninit_multibyte_string (nchars, nbytes);
1776 bcopy (contents, XSTRING (val)->data, nbytes);
1777 return val;
1778}
1779
1780
1781/* Make a string from NCHARS characters occupying NBYTES bytes at
1782 CONTENTS. It is a multibyte string if NBYTES != NCHARS. */
1783
1784Lisp_Object
1785make_string_from_bytes (contents, nchars, nbytes)
1786 char *contents;
1787 int nchars, nbytes;
1788{
1789 register Lisp_Object val;
1790 val = make_uninit_multibyte_string (nchars, nbytes);
1791 bcopy (contents, XSTRING (val)->data, nbytes);
1792 if (STRING_BYTES (XSTRING (val)) == XSTRING (val)->size)
1793 SET_STRING_BYTES (XSTRING (val), -1);
1794 return val;
1795}
1796
1797
1798/* Make a string from NCHARS characters occupying NBYTES bytes at
1799 CONTENTS. The argument MULTIBYTE controls whether to label the
1800 string as multibyte. */
1801
1802Lisp_Object
1803make_specified_string (contents, nchars, nbytes, multibyte)
1804 char *contents;
1805 int nchars, nbytes;
1806 int multibyte;
1807{
1808 register Lisp_Object val;
1809 val = make_uninit_multibyte_string (nchars, nbytes);
1810 bcopy (contents, XSTRING (val)->data, nbytes);
1811 if (!multibyte)
1812 SET_STRING_BYTES (XSTRING (val), -1);
1813 return val;
1814}
1815
1816
1817/* Make a string from the data at STR, treating it as multibyte if the
1818 data warrants. */
1819
1820Lisp_Object
1821build_string (str)
1822 char *str;
1823{
1824 return make_string (str, strlen (str));
1825}
1826
1827
1828/* Return an unibyte Lisp_String set up to hold LENGTH characters
1829 occupying LENGTH bytes. */
1830
1831Lisp_Object
1832make_uninit_string (length)
1833 int length;
1834{
1835 Lisp_Object val;
1836 val = make_uninit_multibyte_string (length, length);
1837 SET_STRING_BYTES (XSTRING (val), -1);
1838 return val;
1839}
1840
1841
1842/* Return a multibyte Lisp_String set up to hold NCHARS characters
1843 which occupy NBYTES bytes. */
1844
1845Lisp_Object
1846make_uninit_multibyte_string (nchars, nbytes)
1847 int nchars, nbytes;
1848{
1849 Lisp_Object string;
1850 struct Lisp_String *s;
1851
1852 if (nchars < 0)
1853 abort ();
1854
1855 s = allocate_string ();
1856 allocate_string_data (s, nchars, nbytes);
1857 XSETSTRING (string, s);
1858 string_chars_consed += nbytes;
1859 return string;
1860}
1861
1862
1863\f
1864/***********************************************************************
1865 Float Allocation
1866 ***********************************************************************/
1867
2e471eb5
GM
1868/* We store float cells inside of float_blocks, allocating a new
1869 float_block with malloc whenever necessary. Float cells reclaimed
1870 by GC are put on a free list to be reallocated before allocating
1871 any new float cells from the latest float_block.
1872
1873 Each float_block is just under 1020 bytes long, since malloc really
1874 allocates in units of powers of two and uses 4 bytes for its own
1875 overhead. */
1876
1877#define FLOAT_BLOCK_SIZE \
1878 ((1020 - sizeof (struct float_block *)) / sizeof (struct Lisp_Float))
1879
1880struct float_block
1881{
1882 struct float_block *next;
1883 struct Lisp_Float floats[FLOAT_BLOCK_SIZE];
1884};
1885
34400008
GM
1886/* Current float_block. */
1887
2e471eb5 1888struct float_block *float_block;
34400008
GM
1889
1890/* Index of first unused Lisp_Float in the current float_block. */
1891
2e471eb5
GM
1892int float_block_index;
1893
1894/* Total number of float blocks now in use. */
1895
1896int n_float_blocks;
1897
34400008
GM
1898/* Free-list of Lisp_Floats. */
1899
2e471eb5
GM
1900struct Lisp_Float *float_free_list;
1901
34400008
GM
1902
1903/* Initialze float allocation. */
1904
2e471eb5
GM
1905void
1906init_float ()
1907{
34400008
GM
1908 float_block = (struct float_block *) lisp_malloc (sizeof *float_block,
1909 MEM_TYPE_FLOAT);
2e471eb5
GM
1910 float_block->next = 0;
1911 bzero ((char *) float_block->floats, sizeof float_block->floats);
1912 float_block_index = 0;
1913 float_free_list = 0;
1914 n_float_blocks = 1;
1915}
1916
34400008
GM
1917
1918/* Explicitly free a float cell by putting it on the free-list. */
2e471eb5
GM
1919
1920void
1921free_float (ptr)
1922 struct Lisp_Float *ptr;
1923{
1924 *(struct Lisp_Float **)&ptr->data = float_free_list;
34400008
GM
1925#if GC_MARK_STACK
1926 ptr->type = Vdead;
1927#endif
2e471eb5
GM
1928 float_free_list = ptr;
1929}
1930
34400008
GM
1931
1932/* Return a new float object with value FLOAT_VALUE. */
1933
2e471eb5
GM
1934Lisp_Object
1935make_float (float_value)
1936 double float_value;
1937{
1938 register Lisp_Object val;
1939
1940 if (float_free_list)
1941 {
1942 /* We use the data field for chaining the free list
1943 so that we won't use the same field that has the mark bit. */
1944 XSETFLOAT (val, float_free_list);
1945 float_free_list = *(struct Lisp_Float **)&float_free_list->data;
1946 }
1947 else
1948 {
1949 if (float_block_index == FLOAT_BLOCK_SIZE)
1950 {
1951 register struct float_block *new;
1952
34400008
GM
1953 new = (struct float_block *) lisp_malloc (sizeof *new,
1954 MEM_TYPE_FLOAT);
2e471eb5
GM
1955 VALIDATE_LISP_STORAGE (new, sizeof *new);
1956 new->next = float_block;
1957 float_block = new;
1958 float_block_index = 0;
1959 n_float_blocks++;
1960 }
1961 XSETFLOAT (val, &float_block->floats[float_block_index++]);
1962 }
1963
1964 XFLOAT_DATA (val) = float_value;
1965 XSETFASTINT (XFLOAT (val)->type, 0); /* bug chasing -wsr */
1966 consing_since_gc += sizeof (struct Lisp_Float);
1967 floats_consed++;
1968 return val;
1969}
1970
2e471eb5
GM
1971
1972\f
1973/***********************************************************************
1974 Cons Allocation
1975 ***********************************************************************/
1976
1977/* We store cons cells inside of cons_blocks, allocating a new
1978 cons_block with malloc whenever necessary. Cons cells reclaimed by
1979 GC are put on a free list to be reallocated before allocating
1980 any new cons cells from the latest cons_block.
1981
1982 Each cons_block is just under 1020 bytes long,
1983 since malloc really allocates in units of powers of two
1984 and uses 4 bytes for its own overhead. */
1985
1986#define CONS_BLOCK_SIZE \
1987 ((1020 - sizeof (struct cons_block *)) / sizeof (struct Lisp_Cons))
1988
1989struct cons_block
1990{
1991 struct cons_block *next;
1992 struct Lisp_Cons conses[CONS_BLOCK_SIZE];
1993};
1994
34400008
GM
1995/* Current cons_block. */
1996
2e471eb5 1997struct cons_block *cons_block;
34400008
GM
1998
1999/* Index of first unused Lisp_Cons in the current block. */
2000
2e471eb5
GM
2001int cons_block_index;
2002
34400008
GM
2003/* Free-list of Lisp_Cons structures. */
2004
2e471eb5
GM
2005struct Lisp_Cons *cons_free_list;
2006
2007/* Total number of cons blocks now in use. */
2008
2009int n_cons_blocks;
2010
34400008
GM
2011
2012/* Initialize cons allocation. */
2013
2e471eb5
GM
2014void
2015init_cons ()
2016{
34400008
GM
2017 cons_block = (struct cons_block *) lisp_malloc (sizeof *cons_block,
2018 MEM_TYPE_CONS);
2e471eb5
GM
2019 cons_block->next = 0;
2020 bzero ((char *) cons_block->conses, sizeof cons_block->conses);
2021 cons_block_index = 0;
2022 cons_free_list = 0;
2023 n_cons_blocks = 1;
2024}
2025
34400008
GM
2026
2027/* Explicitly free a cons cell by putting it on the free-list. */
2e471eb5
GM
2028
2029void
2030free_cons (ptr)
2031 struct Lisp_Cons *ptr;
2032{
2033 *(struct Lisp_Cons **)&ptr->cdr = cons_free_list;
34400008
GM
2034#if GC_MARK_STACK
2035 ptr->car = Vdead;
2036#endif
2e471eb5
GM
2037 cons_free_list = ptr;
2038}
2039
34400008 2040
2e471eb5
GM
2041DEFUN ("cons", Fcons, Scons, 2, 2, 0,
2042 "Create a new cons, give it CAR and CDR as components, and return it.")
2043 (car, cdr)
2044 Lisp_Object car, cdr;
2045{
2046 register Lisp_Object val;
2047
2048 if (cons_free_list)
2049 {
2050 /* We use the cdr for chaining the free list
2051 so that we won't use the same field that has the mark bit. */
2052 XSETCONS (val, cons_free_list);
2053 cons_free_list = *(struct Lisp_Cons **)&cons_free_list->cdr;
2054 }
2055 else
2056 {
2057 if (cons_block_index == CONS_BLOCK_SIZE)
2058 {
2059 register struct cons_block *new;
34400008
GM
2060 new = (struct cons_block *) lisp_malloc (sizeof *new,
2061 MEM_TYPE_CONS);
2e471eb5
GM
2062 VALIDATE_LISP_STORAGE (new, sizeof *new);
2063 new->next = cons_block;
2064 cons_block = new;
2065 cons_block_index = 0;
2066 n_cons_blocks++;
2067 }
2068 XSETCONS (val, &cons_block->conses[cons_block_index++]);
2069 }
2070
2071 XCAR (val) = car;
2072 XCDR (val) = cdr;
2073 consing_since_gc += sizeof (struct Lisp_Cons);
2074 cons_cells_consed++;
2075 return val;
2076}
2077
34400008 2078
2e471eb5
GM
2079/* Make a list of 2, 3, 4 or 5 specified objects. */
2080
2081Lisp_Object
2082list2 (arg1, arg2)
2083 Lisp_Object arg1, arg2;
2084{
2085 return Fcons (arg1, Fcons (arg2, Qnil));
2086}
2087
34400008 2088
2e471eb5
GM
2089Lisp_Object
2090list3 (arg1, arg2, arg3)
2091 Lisp_Object arg1, arg2, arg3;
2092{
2093 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Qnil)));
2094}
2095
34400008 2096
2e471eb5
GM
2097Lisp_Object
2098list4 (arg1, arg2, arg3, arg4)
2099 Lisp_Object arg1, arg2, arg3, arg4;
2100{
2101 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4, Qnil))));
2102}
2103
34400008 2104
2e471eb5
GM
2105Lisp_Object
2106list5 (arg1, arg2, arg3, arg4, arg5)
2107 Lisp_Object arg1, arg2, arg3, arg4, arg5;
2108{
2109 return Fcons (arg1, Fcons (arg2, Fcons (arg3, Fcons (arg4,
2110 Fcons (arg5, Qnil)))));
2111}
2112
34400008 2113
2e471eb5
GM
2114DEFUN ("list", Flist, Slist, 0, MANY, 0,
2115 "Return a newly created list with specified arguments as elements.\n\
2116Any number of arguments, even zero arguments, are allowed.")
2117 (nargs, args)
2118 int nargs;
2119 register Lisp_Object *args;
2120{
2121 register Lisp_Object val;
2122 val = Qnil;
2123
2124 while (nargs > 0)
2125 {
2126 nargs--;
2127 val = Fcons (args[nargs], val);
2128 }
2129 return val;
2130}
2131
34400008 2132
2e471eb5
GM
2133DEFUN ("make-list", Fmake_list, Smake_list, 2, 2, 0,
2134 "Return a newly created list of length LENGTH, with each element being INIT.")
2135 (length, init)
2136 register Lisp_Object length, init;
2137{
2138 register Lisp_Object val;
2139 register int size;
2140
2141 CHECK_NATNUM (length, 0);
2142 size = XFASTINT (length);
2143
2144 val = Qnil;
7146af97
JB
2145 while (size-- > 0)
2146 val = Fcons (init, val);
2147 return val;
2148}
2e471eb5
GM
2149
2150
7146af97 2151\f
2e471eb5
GM
2152/***********************************************************************
2153 Vector Allocation
2154 ***********************************************************************/
7146af97 2155
34400008
GM
2156/* Singly-linked list of all vectors. */
2157
7146af97
JB
2158struct Lisp_Vector *all_vectors;
2159
2e471eb5
GM
2160/* Total number of vector-like objects now in use. */
2161
c8099634
RS
2162int n_vectors;
2163
34400008
GM
2164
2165/* Value is a pointer to a newly allocated Lisp_Vector structure
2166 with room for LEN Lisp_Objects. */
2167
1825c68d
KH
2168struct Lisp_Vector *
2169allocate_vectorlike (len)
2170 EMACS_INT len;
2171{
2172 struct Lisp_Vector *p;
675d5130 2173 size_t nbytes;
1825c68d 2174
d1658221 2175#ifdef DOUG_LEA_MALLOC
f8608968
GM
2176 /* Prevent mmap'ing the chunk. Lisp data may not be mmap'ed
2177 because mapped region contents are not preserved in
2178 a dumped Emacs. */
d1658221
RS
2179 mallopt (M_MMAP_MAX, 0);
2180#endif
34400008
GM
2181
2182 nbytes = sizeof *p + (len - 1) * sizeof p->contents[0];
2183 p = (struct Lisp_Vector *) lisp_malloc (nbytes, MEM_TYPE_VECTOR);
2184
d1658221 2185#ifdef DOUG_LEA_MALLOC
34400008 2186 /* Back to a reasonable maximum of mmap'ed areas. */
81d492d5 2187 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS);
d1658221 2188#endif
34400008 2189
1825c68d 2190 VALIDATE_LISP_STORAGE (p, 0);
34400008 2191 consing_since_gc += nbytes;
310ea200 2192 vector_cells_consed += len;
1825c68d
KH
2193
2194 p->next = all_vectors;
2195 all_vectors = p;
34400008 2196 ++n_vectors;
1825c68d
KH
2197 return p;
2198}
2199
34400008 2200
7146af97
JB
2201DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
2202 "Return a newly created vector of length LENGTH, with each element being INIT.\n\
2203See also the function `vector'.")
2204 (length, init)
2205 register Lisp_Object length, init;
2206{
1825c68d
KH
2207 Lisp_Object vector;
2208 register EMACS_INT sizei;
2209 register int index;
7146af97
JB
2210 register struct Lisp_Vector *p;
2211
c9dad5ed
KH
2212 CHECK_NATNUM (length, 0);
2213 sizei = XFASTINT (length);
7146af97 2214
1825c68d 2215 p = allocate_vectorlike (sizei);
7146af97 2216 p->size = sizei;
7146af97
JB
2217 for (index = 0; index < sizei; index++)
2218 p->contents[index] = init;
2219
1825c68d 2220 XSETVECTOR (vector, p);
7146af97
JB
2221 return vector;
2222}
2223
34400008 2224
a59de17b 2225DEFUN ("make-char-table", Fmake_char_table, Smake_char_table, 1, 2, 0,
c58b2b4d 2226 "Return a newly created char-table, with purpose PURPOSE.\n\
7b07587b 2227Each element is initialized to INIT, which defaults to nil.\n\
d7cd5d4f 2228PURPOSE should be a symbol which has a `char-table-extra-slots' property.\n\
a59de17b
RS
2229The property's value should be an integer between 0 and 10.")
2230 (purpose, init)
2231 register Lisp_Object purpose, init;
7b07587b
RS
2232{
2233 Lisp_Object vector;
a59de17b
RS
2234 Lisp_Object n;
2235 CHECK_SYMBOL (purpose, 1);
0551bde3 2236 n = Fget (purpose, Qchar_table_extra_slots);
a59de17b 2237 CHECK_NUMBER (n, 0);
7b07587b
RS
2238 if (XINT (n) < 0 || XINT (n) > 10)
2239 args_out_of_range (n, Qnil);
2240 /* Add 2 to the size for the defalt and parent slots. */
2241 vector = Fmake_vector (make_number (CHAR_TABLE_STANDARD_SLOTS + XINT (n)),
2242 init);
0551bde3 2243 XCHAR_TABLE (vector)->top = Qt;
c96a008c 2244 XCHAR_TABLE (vector)->parent = Qnil;
a59de17b 2245 XCHAR_TABLE (vector)->purpose = purpose;
7b07587b
RS
2246 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
2247 return vector;
2248}
2249
34400008 2250
0551bde3
KH
2251/* Return a newly created sub char table with default value DEFALT.
2252 Since a sub char table does not appear as a top level Emacs Lisp
2253 object, we don't need a Lisp interface to make it. */
2254
2255Lisp_Object
2256make_sub_char_table (defalt)
2257 Lisp_Object defalt;
2258{
2259 Lisp_Object vector
2260 = Fmake_vector (make_number (SUB_CHAR_TABLE_STANDARD_SLOTS), Qnil);
2261 XCHAR_TABLE (vector)->top = Qnil;
2262 XCHAR_TABLE (vector)->defalt = defalt;
2263 XSETCHAR_TABLE (vector, XCHAR_TABLE (vector));
2264 return vector;
2265}
2266
34400008 2267
7146af97
JB
2268DEFUN ("vector", Fvector, Svector, 0, MANY, 0,
2269 "Return a newly created vector with specified arguments as elements.\n\
2270Any number of arguments, even zero arguments, are allowed.")
2271 (nargs, args)
2272 register int nargs;
2273 Lisp_Object *args;
2274{
2275 register Lisp_Object len, val;
2276 register int index;
2277 register struct Lisp_Vector *p;
2278
67ba9986 2279 XSETFASTINT (len, nargs);
7146af97
JB
2280 val = Fmake_vector (len, Qnil);
2281 p = XVECTOR (val);
2282 for (index = 0; index < nargs; index++)
2283 p->contents[index] = args[index];
2284 return val;
2285}
2286
34400008 2287
7146af97
JB
2288DEFUN ("make-byte-code", Fmake_byte_code, Smake_byte_code, 4, MANY, 0,
2289 "Create a byte-code object with specified arguments as elements.\n\
2290The arguments should be the arglist, bytecode-string, constant vector,\n\
2291stack size, (optional) doc string, and (optional) interactive spec.\n\
2292The first four arguments are required; at most six have any\n\
2293significance.")
2294 (nargs, args)
2295 register int nargs;
2296 Lisp_Object *args;
2297{
2298 register Lisp_Object len, val;
2299 register int index;
2300 register struct Lisp_Vector *p;
2301
67ba9986 2302 XSETFASTINT (len, nargs);
265a9e55 2303 if (!NILP (Vpurify_flag))
5a053ea9 2304 val = make_pure_vector ((EMACS_INT) nargs);
7146af97
JB
2305 else
2306 val = Fmake_vector (len, Qnil);
9eac9d59
KH
2307
2308 if (STRINGP (args[1]) && STRING_MULTIBYTE (args[1]))
2309 /* BYTECODE-STRING must have been produced by Emacs 20.2 or the
2310 earlier because they produced a raw 8-bit string for byte-code
2311 and now such a byte-code string is loaded as multibyte while
2312 raw 8-bit characters converted to multibyte form. Thus, now we
2313 must convert them back to the original unibyte form. */
2314 args[1] = Fstring_as_unibyte (args[1]);
2315
7146af97
JB
2316 p = XVECTOR (val);
2317 for (index = 0; index < nargs; index++)
2318 {
265a9e55 2319 if (!NILP (Vpurify_flag))
7146af97
JB
2320 args[index] = Fpurecopy (args[index]);
2321 p->contents[index] = args[index];
2322 }
50aee051 2323 XSETCOMPILED (val, p);
7146af97
JB
2324 return val;
2325}
2e471eb5 2326
34400008 2327
7146af97 2328\f
2e471eb5
GM
2329/***********************************************************************
2330 Symbol Allocation
2331 ***********************************************************************/
7146af97 2332
2e471eb5
GM
2333/* Each symbol_block is just under 1020 bytes long, since malloc
2334 really allocates in units of powers of two and uses 4 bytes for its
2335 own overhead. */
7146af97
JB
2336
2337#define SYMBOL_BLOCK_SIZE \
2338 ((1020 - sizeof (struct symbol_block *)) / sizeof (struct Lisp_Symbol))
2339
2340struct symbol_block
2e471eb5
GM
2341{
2342 struct symbol_block *next;
2343 struct Lisp_Symbol symbols[SYMBOL_BLOCK_SIZE];
2344};
7146af97 2345
34400008
GM
2346/* Current symbol block and index of first unused Lisp_Symbol
2347 structure in it. */
2348
7146af97
JB
2349struct symbol_block *symbol_block;
2350int symbol_block_index;
2351
34400008
GM
2352/* List of free symbols. */
2353
7146af97
JB
2354struct Lisp_Symbol *symbol_free_list;
2355
c8099634 2356/* Total number of symbol blocks now in use. */
2e471eb5 2357
c8099634
RS
2358int n_symbol_blocks;
2359
34400008
GM
2360
2361/* Initialize symbol allocation. */
2362
7146af97
JB
2363void
2364init_symbol ()
2365{
34400008
GM
2366 symbol_block = (struct symbol_block *) lisp_malloc (sizeof *symbol_block,
2367 MEM_TYPE_SYMBOL);
7146af97 2368 symbol_block->next = 0;
290c8f1e 2369 bzero ((char *) symbol_block->symbols, sizeof symbol_block->symbols);
7146af97
JB
2370 symbol_block_index = 0;
2371 symbol_free_list = 0;
c8099634 2372 n_symbol_blocks = 1;
7146af97
JB
2373}
2374
34400008 2375
7146af97
JB
2376DEFUN ("make-symbol", Fmake_symbol, Smake_symbol, 1, 1, 0,
2377 "Return a newly allocated uninterned symbol whose name is NAME.\n\
2378Its value and function definition are void, and its property list is nil.")
54ee42dd
EN
2379 (name)
2380 Lisp_Object name;
7146af97
JB
2381{
2382 register Lisp_Object val;
2383 register struct Lisp_Symbol *p;
2384
54ee42dd 2385 CHECK_STRING (name, 0);
7146af97
JB
2386
2387 if (symbol_free_list)
2388 {
45d12a89 2389 XSETSYMBOL (val, symbol_free_list);
85481507 2390 symbol_free_list = *(struct Lisp_Symbol **)&symbol_free_list->value;
7146af97
JB
2391 }
2392 else
2393 {
2394 if (symbol_block_index == SYMBOL_BLOCK_SIZE)
2395 {
3c06d205 2396 struct symbol_block *new;
34400008
GM
2397 new = (struct symbol_block *) lisp_malloc (sizeof *new,
2398 MEM_TYPE_SYMBOL);
7146af97
JB
2399 VALIDATE_LISP_STORAGE (new, sizeof *new);
2400 new->next = symbol_block;
2401 symbol_block = new;
2402 symbol_block_index = 0;
c8099634 2403 n_symbol_blocks++;
7146af97 2404 }
45d12a89 2405 XSETSYMBOL (val, &symbol_block->symbols[symbol_block_index++]);
7146af97 2406 }
2e471eb5 2407
7146af97 2408 p = XSYMBOL (val);
636b7260 2409 p->name = XSTRING (name);
47d5b31e 2410 p->obarray = Qnil;
7146af97 2411 p->plist = Qnil;
2e471eb5
GM
2412 p->value = Qunbound;
2413 p->function = Qunbound;
2414 p->next = 0;
2415 consing_since_gc += sizeof (struct Lisp_Symbol);
2416 symbols_consed++;
7146af97
JB
2417 return val;
2418}
2419
3f25e183 2420
2e471eb5
GM
2421\f
2422/***********************************************************************
34400008 2423 Marker (Misc) Allocation
2e471eb5 2424 ***********************************************************************/
3f25e183 2425
2e471eb5
GM
2426/* Allocation of markers and other objects that share that structure.
2427 Works like allocation of conses. */
c0696668 2428
2e471eb5
GM
2429#define MARKER_BLOCK_SIZE \
2430 ((1020 - sizeof (struct marker_block *)) / sizeof (union Lisp_Misc))
2431
2432struct marker_block
c0696668 2433{
2e471eb5
GM
2434 struct marker_block *next;
2435 union Lisp_Misc markers[MARKER_BLOCK_SIZE];
2436};
c0696668 2437
2e471eb5
GM
2438struct marker_block *marker_block;
2439int marker_block_index;
c0696668 2440
2e471eb5 2441union Lisp_Misc *marker_free_list;
c0696668 2442
2e471eb5 2443/* Total number of marker blocks now in use. */
3f25e183 2444
2e471eb5
GM
2445int n_marker_blocks;
2446
2447void
2448init_marker ()
3f25e183 2449{
34400008
GM
2450 marker_block = (struct marker_block *) lisp_malloc (sizeof *marker_block,
2451 MEM_TYPE_MISC);
2e471eb5
GM
2452 marker_block->next = 0;
2453 bzero ((char *) marker_block->markers, sizeof marker_block->markers);
2454 marker_block_index = 0;
2455 marker_free_list = 0;
2456 n_marker_blocks = 1;
3f25e183
RS
2457}
2458
2e471eb5
GM
2459/* Return a newly allocated Lisp_Misc object, with no substructure. */
2460
3f25e183 2461Lisp_Object
2e471eb5 2462allocate_misc ()
7146af97 2463{
2e471eb5 2464 Lisp_Object val;
7146af97 2465
2e471eb5 2466 if (marker_free_list)
7146af97 2467 {
2e471eb5
GM
2468 XSETMISC (val, marker_free_list);
2469 marker_free_list = marker_free_list->u_free.chain;
7146af97
JB
2470 }
2471 else
7146af97 2472 {
2e471eb5
GM
2473 if (marker_block_index == MARKER_BLOCK_SIZE)
2474 {
2475 struct marker_block *new;
34400008
GM
2476 new = (struct marker_block *) lisp_malloc (sizeof *new,
2477 MEM_TYPE_MISC);
2e471eb5
GM
2478 VALIDATE_LISP_STORAGE (new, sizeof *new);
2479 new->next = marker_block;
2480 marker_block = new;
2481 marker_block_index = 0;
2482 n_marker_blocks++;
2483 }
2484 XSETMISC (val, &marker_block->markers[marker_block_index++]);
7146af97 2485 }
2e471eb5
GM
2486
2487 consing_since_gc += sizeof (union Lisp_Misc);
2488 misc_objects_consed++;
2489 return val;
2490}
2491
2492DEFUN ("make-marker", Fmake_marker, Smake_marker, 0, 0, 0,
2493 "Return a newly allocated marker which does not point at any place.")
2494 ()
2495{
2496 register Lisp_Object val;
2497 register struct Lisp_Marker *p;
7146af97 2498
2e471eb5
GM
2499 val = allocate_misc ();
2500 XMISCTYPE (val) = Lisp_Misc_Marker;
2501 p = XMARKER (val);
2502 p->buffer = 0;
2503 p->bytepos = 0;
2504 p->charpos = 0;
2505 p->chain = Qnil;
2506 p->insertion_type = 0;
7146af97
JB
2507 return val;
2508}
2e471eb5
GM
2509
2510/* Put MARKER back on the free list after using it temporarily. */
2511
2512void
2513free_marker (marker)
2514 Lisp_Object marker;
2515{
2516 unchain_marker (marker);
2517
2518 XMISC (marker)->u_marker.type = Lisp_Misc_Free;
2519 XMISC (marker)->u_free.chain = marker_free_list;
2520 marker_free_list = XMISC (marker);
2521
2522 total_free_markers++;
2523}
2524
c0696668 2525\f
7146af97 2526/* Return a newly created vector or string with specified arguments as
736471d1
RS
2527 elements. If all the arguments are characters that can fit
2528 in a string of events, make a string; otherwise, make a vector.
2529
2530 Any number of arguments, even zero arguments, are allowed. */
7146af97
JB
2531
2532Lisp_Object
736471d1 2533make_event_array (nargs, args)
7146af97
JB
2534 register int nargs;
2535 Lisp_Object *args;
2536{
2537 int i;
2538
2539 for (i = 0; i < nargs; i++)
736471d1 2540 /* The things that fit in a string
c9ca4659
RS
2541 are characters that are in 0...127,
2542 after discarding the meta bit and all the bits above it. */
e687453f 2543 if (!INTEGERP (args[i])
c9ca4659 2544 || (XUINT (args[i]) & ~(-CHAR_META)) >= 0200)
7146af97
JB
2545 return Fvector (nargs, args);
2546
2547 /* Since the loop exited, we know that all the things in it are
2548 characters, so we can make a string. */
2549 {
c13ccad2 2550 Lisp_Object result;
7146af97 2551
50aee051 2552 result = Fmake_string (make_number (nargs), make_number (0));
7146af97 2553 for (i = 0; i < nargs; i++)
736471d1
RS
2554 {
2555 XSTRING (result)->data[i] = XINT (args[i]);
2556 /* Move the meta bit to the right place for a string char. */
2557 if (XINT (args[i]) & CHAR_META)
2558 XSTRING (result)->data[i] |= 0x80;
2559 }
7146af97
JB
2560
2561 return result;
2562 }
2563}
2e471eb5
GM
2564
2565
7146af97 2566\f
34400008
GM
2567/************************************************************************
2568 C Stack Marking
2569 ************************************************************************/
2570
13c844fb
GM
2571#if GC_MARK_STACK || defined GC_MALLOC_CHECK
2572
34400008
GM
2573/* Initialize this part of alloc.c. */
2574
2575static void
2576mem_init ()
2577{
2578 mem_z.left = mem_z.right = MEM_NIL;
2579 mem_z.parent = NULL;
2580 mem_z.color = MEM_BLACK;
2581 mem_z.start = mem_z.end = NULL;
2582 mem_root = MEM_NIL;
2583}
2584
2585
2586/* Value is a pointer to the mem_node containing START. Value is
2587 MEM_NIL if there is no node in the tree containing START. */
2588
2589static INLINE struct mem_node *
2590mem_find (start)
2591 void *start;
2592{
2593 struct mem_node *p;
2594
2595 /* Make the search always successful to speed up the loop below. */
2596 mem_z.start = start;
2597 mem_z.end = (char *) start + 1;
2598
2599 p = mem_root;
2600 while (start < p->start || start >= p->end)
2601 p = start < p->start ? p->left : p->right;
2602 return p;
2603}
2604
2605
2606/* Insert a new node into the tree for a block of memory with start
2607 address START, end address END, and type TYPE. Value is a
2608 pointer to the node that was inserted. */
2609
2610static struct mem_node *
2611mem_insert (start, end, type)
2612 void *start, *end;
2613 enum mem_type type;
2614{
2615 struct mem_node *c, *parent, *x;
2616
2617 /* See where in the tree a node for START belongs. In this
2618 particular application, it shouldn't happen that a node is already
2619 present. For debugging purposes, let's check that. */
2620 c = mem_root;
2621 parent = NULL;
2622
2623#if GC_MARK_STACK != GC_MAKE_GCPROS_NOOPS
2624
2625 while (c != MEM_NIL)
2626 {
2627 if (start >= c->start && start < c->end)
2628 abort ();
2629 parent = c;
2630 c = start < c->start ? c->left : c->right;
2631 }
2632
2633#else /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2634
2635 while (c != MEM_NIL)
2636 {
2637 parent = c;
2638 c = start < c->start ? c->left : c->right;
2639 }
2640
2641#endif /* GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS */
2642
2643 /* Create a new node. */
877935b1
GM
2644#ifdef GC_MALLOC_CHECK
2645 x = (struct mem_node *) _malloc_internal (sizeof *x);
2646 if (x == NULL)
2647 abort ();
2648#else
34400008 2649 x = (struct mem_node *) xmalloc (sizeof *x);
877935b1 2650#endif
34400008
GM
2651 x->start = start;
2652 x->end = end;
2653 x->type = type;
2654 x->parent = parent;
2655 x->left = x->right = MEM_NIL;
2656 x->color = MEM_RED;
2657
2658 /* Insert it as child of PARENT or install it as root. */
2659 if (parent)
2660 {
2661 if (start < parent->start)
2662 parent->left = x;
2663 else
2664 parent->right = x;
2665 }
2666 else
2667 mem_root = x;
2668
2669 /* Re-establish red-black tree properties. */
2670 mem_insert_fixup (x);
877935b1 2671
34400008
GM
2672 return x;
2673}
2674
2675
2676/* Re-establish the red-black properties of the tree, and thereby
2677 balance the tree, after node X has been inserted; X is always red. */
2678
2679static void
2680mem_insert_fixup (x)
2681 struct mem_node *x;
2682{
2683 while (x != mem_root && x->parent->color == MEM_RED)
2684 {
2685 /* X is red and its parent is red. This is a violation of
2686 red-black tree property #3. */
2687
2688 if (x->parent == x->parent->parent->left)
2689 {
2690 /* We're on the left side of our grandparent, and Y is our
2691 "uncle". */
2692 struct mem_node *y = x->parent->parent->right;
2693
2694 if (y->color == MEM_RED)
2695 {
2696 /* Uncle and parent are red but should be black because
2697 X is red. Change the colors accordingly and proceed
2698 with the grandparent. */
2699 x->parent->color = MEM_BLACK;
2700 y->color = MEM_BLACK;
2701 x->parent->parent->color = MEM_RED;
2702 x = x->parent->parent;
2703 }
2704 else
2705 {
2706 /* Parent and uncle have different colors; parent is
2707 red, uncle is black. */
2708 if (x == x->parent->right)
2709 {
2710 x = x->parent;
2711 mem_rotate_left (x);
2712 }
2713
2714 x->parent->color = MEM_BLACK;
2715 x->parent->parent->color = MEM_RED;
2716 mem_rotate_right (x->parent->parent);
2717 }
2718 }
2719 else
2720 {
2721 /* This is the symmetrical case of above. */
2722 struct mem_node *y = x->parent->parent->left;
2723
2724 if (y->color == MEM_RED)
2725 {
2726 x->parent->color = MEM_BLACK;
2727 y->color = MEM_BLACK;
2728 x->parent->parent->color = MEM_RED;
2729 x = x->parent->parent;
2730 }
2731 else
2732 {
2733 if (x == x->parent->left)
2734 {
2735 x = x->parent;
2736 mem_rotate_right (x);
2737 }
2738
2739 x->parent->color = MEM_BLACK;
2740 x->parent->parent->color = MEM_RED;
2741 mem_rotate_left (x->parent->parent);
2742 }
2743 }
2744 }
2745
2746 /* The root may have been changed to red due to the algorithm. Set
2747 it to black so that property #5 is satisfied. */
2748 mem_root->color = MEM_BLACK;
2749}
2750
2751
2752/* (x) (y)
2753 / \ / \
2754 a (y) ===> (x) c
2755 / \ / \
2756 b c a b */
2757
2758static void
2759mem_rotate_left (x)
2760 struct mem_node *x;
2761{
2762 struct mem_node *y;
2763
2764 /* Turn y's left sub-tree into x's right sub-tree. */
2765 y = x->right;
2766 x->right = y->left;
2767 if (y->left != MEM_NIL)
2768 y->left->parent = x;
2769
2770 /* Y's parent was x's parent. */
2771 if (y != MEM_NIL)
2772 y->parent = x->parent;
2773
2774 /* Get the parent to point to y instead of x. */
2775 if (x->parent)
2776 {
2777 if (x == x->parent->left)
2778 x->parent->left = y;
2779 else
2780 x->parent->right = y;
2781 }
2782 else
2783 mem_root = y;
2784
2785 /* Put x on y's left. */
2786 y->left = x;
2787 if (x != MEM_NIL)
2788 x->parent = y;
2789}
2790
2791
2792/* (x) (Y)
2793 / \ / \
2794 (y) c ===> a (x)
2795 / \ / \
2796 a b b c */
2797
2798static void
2799mem_rotate_right (x)
2800 struct mem_node *x;
2801{
2802 struct mem_node *y = x->left;
2803
2804 x->left = y->right;
2805 if (y->right != MEM_NIL)
2806 y->right->parent = x;
2807
2808 if (y != MEM_NIL)
2809 y->parent = x->parent;
2810 if (x->parent)
2811 {
2812 if (x == x->parent->right)
2813 x->parent->right = y;
2814 else
2815 x->parent->left = y;
2816 }
2817 else
2818 mem_root = y;
2819
2820 y->right = x;
2821 if (x != MEM_NIL)
2822 x->parent = y;
2823}
2824
2825
2826/* Delete node Z from the tree. If Z is null or MEM_NIL, do nothing. */
2827
2828static void
2829mem_delete (z)
2830 struct mem_node *z;
2831{
2832 struct mem_node *x, *y;
2833
2834 if (!z || z == MEM_NIL)
2835 return;
2836
2837 if (z->left == MEM_NIL || z->right == MEM_NIL)
2838 y = z;
2839 else
2840 {
2841 y = z->right;
2842 while (y->left != MEM_NIL)
2843 y = y->left;
2844 }
2845
2846 if (y->left != MEM_NIL)
2847 x = y->left;
2848 else
2849 x = y->right;
2850
2851 x->parent = y->parent;
2852 if (y->parent)
2853 {
2854 if (y == y->parent->left)
2855 y->parent->left = x;
2856 else
2857 y->parent->right = x;
2858 }
2859 else
2860 mem_root = x;
2861
2862 if (y != z)
2863 {
2864 z->start = y->start;
2865 z->end = y->end;
2866 z->type = y->type;
2867 }
2868
2869 if (y->color == MEM_BLACK)
2870 mem_delete_fixup (x);
877935b1
GM
2871
2872#ifdef GC_MALLOC_CHECK
2873 _free_internal (y);
2874#else
34400008 2875 xfree (y);
877935b1 2876#endif
34400008
GM
2877}
2878
2879
2880/* Re-establish the red-black properties of the tree, after a
2881 deletion. */
2882
2883static void
2884mem_delete_fixup (x)
2885 struct mem_node *x;
2886{
2887 while (x != mem_root && x->color == MEM_BLACK)
2888 {
2889 if (x == x->parent->left)
2890 {
2891 struct mem_node *w = x->parent->right;
2892
2893 if (w->color == MEM_RED)
2894 {
2895 w->color = MEM_BLACK;
2896 x->parent->color = MEM_RED;
2897 mem_rotate_left (x->parent);
2898 w = x->parent->right;
2899 }
2900
2901 if (w->left->color == MEM_BLACK && w->right->color == MEM_BLACK)
2902 {
2903 w->color = MEM_RED;
2904 x = x->parent;
2905 }
2906 else
2907 {
2908 if (w->right->color == MEM_BLACK)
2909 {
2910 w->left->color = MEM_BLACK;
2911 w->color = MEM_RED;
2912 mem_rotate_right (w);
2913 w = x->parent->right;
2914 }
2915 w->color = x->parent->color;
2916 x->parent->color = MEM_BLACK;
2917 w->right->color = MEM_BLACK;
2918 mem_rotate_left (x->parent);
2919 x = mem_root;
2920 }
2921 }
2922 else
2923 {
2924 struct mem_node *w = x->parent->left;
2925
2926 if (w->color == MEM_RED)
2927 {
2928 w->color = MEM_BLACK;
2929 x->parent->color = MEM_RED;
2930 mem_rotate_right (x->parent);
2931 w = x->parent->left;
2932 }
2933
2934 if (w->right->color == MEM_BLACK && w->left->color == MEM_BLACK)
2935 {
2936 w->color = MEM_RED;
2937 x = x->parent;
2938 }
2939 else
2940 {
2941 if (w->left->color == MEM_BLACK)
2942 {
2943 w->right->color = MEM_BLACK;
2944 w->color = MEM_RED;
2945 mem_rotate_left (w);
2946 w = x->parent->left;
2947 }
2948
2949 w->color = x->parent->color;
2950 x->parent->color = MEM_BLACK;
2951 w->left->color = MEM_BLACK;
2952 mem_rotate_right (x->parent);
2953 x = mem_root;
2954 }
2955 }
2956 }
2957
2958 x->color = MEM_BLACK;
2959}
2960
2961
2962/* Value is non-zero if P is a pointer to a live Lisp string on
2963 the heap. M is a pointer to the mem_block for P. */
2964
2965static INLINE int
2966live_string_p (m, p)
2967 struct mem_node *m;
2968 void *p;
2969{
2970 if (m->type == MEM_TYPE_STRING)
2971 {
2972 struct string_block *b = (struct string_block *) m->start;
2973 int offset = (char *) p - (char *) &b->strings[0];
2974
2975 /* P must point to the start of a Lisp_String structure, and it
2976 must not be on the free-list. */
2977 return (offset % sizeof b->strings[0] == 0
2978 && ((struct Lisp_String *) p)->data != NULL);
2979 }
2980 else
2981 return 0;
2982}
2983
2984
2985/* Value is non-zero if P is a pointer to a live Lisp cons on
2986 the heap. M is a pointer to the mem_block for P. */
2987
2988static INLINE int
2989live_cons_p (m, p)
2990 struct mem_node *m;
2991 void *p;
2992{
2993 if (m->type == MEM_TYPE_CONS)
2994 {
2995 struct cons_block *b = (struct cons_block *) m->start;
2996 int offset = (char *) p - (char *) &b->conses[0];
2997
2998 /* P must point to the start of a Lisp_Cons, not be
2999 one of the unused cells in the current cons block,
3000 and not be on the free-list. */
3001 return (offset % sizeof b->conses[0] == 0
3002 && (b != cons_block
3003 || offset / sizeof b->conses[0] < cons_block_index)
3004 && !EQ (((struct Lisp_Cons *) p)->car, Vdead));
3005 }
3006 else
3007 return 0;
3008}
3009
3010
3011/* Value is non-zero if P is a pointer to a live Lisp symbol on
3012 the heap. M is a pointer to the mem_block for P. */
3013
3014static INLINE int
3015live_symbol_p (m, p)
3016 struct mem_node *m;
3017 void *p;
3018{
3019 if (m->type == MEM_TYPE_SYMBOL)
3020 {
3021 struct symbol_block *b = (struct symbol_block *) m->start;
3022 int offset = (char *) p - (char *) &b->symbols[0];
3023
3024 /* P must point to the start of a Lisp_Symbol, not be
3025 one of the unused cells in the current symbol block,
3026 and not be on the free-list. */
3027 return (offset % sizeof b->symbols[0] == 0
3028 && (b != symbol_block
3029 || offset / sizeof b->symbols[0] < symbol_block_index)
3030 && !EQ (((struct Lisp_Symbol *) p)->function, Vdead));
3031 }
3032 else
3033 return 0;
3034}
3035
3036
3037/* Value is non-zero if P is a pointer to a live Lisp float on
3038 the heap. M is a pointer to the mem_block for P. */
3039
3040static INLINE int
3041live_float_p (m, p)
3042 struct mem_node *m;
3043 void *p;
3044{
3045 if (m->type == MEM_TYPE_FLOAT)
3046 {
3047 struct float_block *b = (struct float_block *) m->start;
3048 int offset = (char *) p - (char *) &b->floats[0];
3049
3050 /* P must point to the start of a Lisp_Float, not be
3051 one of the unused cells in the current float block,
3052 and not be on the free-list. */
3053 return (offset % sizeof b->floats[0] == 0
3054 && (b != float_block
3055 || offset / sizeof b->floats[0] < float_block_index)
3056 && !EQ (((struct Lisp_Float *) p)->type, Vdead));
3057 }
3058 else
3059 return 0;
3060}
3061
3062
3063/* Value is non-zero if P is a pointer to a live Lisp Misc on
3064 the heap. M is a pointer to the mem_block for P. */
3065
3066static INLINE int
3067live_misc_p (m, p)
3068 struct mem_node *m;
3069 void *p;
3070{
3071 if (m->type == MEM_TYPE_MISC)
3072 {
3073 struct marker_block *b = (struct marker_block *) m->start;
3074 int offset = (char *) p - (char *) &b->markers[0];
3075
3076 /* P must point to the start of a Lisp_Misc, not be
3077 one of the unused cells in the current misc block,
3078 and not be on the free-list. */
3079 return (offset % sizeof b->markers[0] == 0
3080 && (b != marker_block
3081 || offset / sizeof b->markers[0] < marker_block_index)
3082 && ((union Lisp_Misc *) p)->u_marker.type != Lisp_Misc_Free);
3083 }
3084 else
3085 return 0;
3086}
3087
3088
3089/* Value is non-zero if P is a pointer to a live vector-like object.
3090 M is a pointer to the mem_block for P. */
3091
3092static INLINE int
3093live_vector_p (m, p)
3094 struct mem_node *m;
3095 void *p;
3096{
3097 return m->type == MEM_TYPE_VECTOR && p == m->start;
3098}
3099
3100
3101/* Value is non-zero of P is a pointer to a live buffer. M is a
3102 pointer to the mem_block for P. */
3103
3104static INLINE int
3105live_buffer_p (m, p)
3106 struct mem_node *m;
3107 void *p;
3108{
3109 /* P must point to the start of the block, and the buffer
3110 must not have been killed. */
3111 return (m->type == MEM_TYPE_BUFFER
3112 && p == m->start
3113 && !NILP (((struct buffer *) p)->name));
3114}
3115
13c844fb
GM
3116#endif /* GC_MARK_STACK || defined GC_MALLOC_CHECK */
3117
3118#if GC_MARK_STACK
3119
34400008
GM
3120#if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3121
3122/* Array of objects that are kept alive because the C stack contains
3123 a pattern that looks like a reference to them . */
3124
3125#define MAX_ZOMBIES 10
3126static Lisp_Object zombies[MAX_ZOMBIES];
3127
3128/* Number of zombie objects. */
3129
3130static int nzombies;
3131
3132/* Number of garbage collections. */
3133
3134static int ngcs;
3135
3136/* Average percentage of zombies per collection. */
3137
3138static double avg_zombies;
3139
3140/* Max. number of live and zombie objects. */
3141
3142static int max_live, max_zombies;
3143
3144/* Average number of live objects per GC. */
3145
3146static double avg_live;
3147
3148DEFUN ("gc-status", Fgc_status, Sgc_status, 0, 0, "",
3149 "Show information about live and zombie objects.")
3150 ()
3151{
3152 Lisp_Object args[7];
3153 args[0] = build_string ("%d GCs, avg live/zombies = %.2f/%.2f (%f%%), max %d/%d");
3154 args[1] = make_number (ngcs);
3155 args[2] = make_float (avg_live);
3156 args[3] = make_float (avg_zombies);
3157 args[4] = make_float (avg_zombies / avg_live / 100);
3158 args[5] = make_number (max_live);
3159 args[6] = make_number (max_zombies);
3160 return Fmessage (7, args);
3161}
3162
3163#endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3164
3165
182ff242
GM
3166/* Mark OBJ if we can prove it's a Lisp_Object. */
3167
3168static INLINE void
3169mark_maybe_object (obj)
3170 Lisp_Object obj;
3171{
3172 void *po = (void *) XPNTR (obj);
3173 struct mem_node *m = mem_find (po);
3174
3175 if (m != MEM_NIL)
3176 {
3177 int mark_p = 0;
3178
3179 switch (XGCTYPE (obj))
3180 {
3181 case Lisp_String:
3182 mark_p = (live_string_p (m, po)
3183 && !STRING_MARKED_P ((struct Lisp_String *) po));
3184 break;
3185
3186 case Lisp_Cons:
3187 mark_p = (live_cons_p (m, po)
3188 && !XMARKBIT (XCONS (obj)->car));
3189 break;
3190
3191 case Lisp_Symbol:
3192 mark_p = (live_symbol_p (m, po)
3193 && !XMARKBIT (XSYMBOL (obj)->plist));
3194 break;
3195
3196 case Lisp_Float:
3197 mark_p = (live_float_p (m, po)
3198 && !XMARKBIT (XFLOAT (obj)->type));
3199 break;
3200
3201 case Lisp_Vectorlike:
3202 /* Note: can't check GC_BUFFERP before we know it's a
3203 buffer because checking that dereferences the pointer
3204 PO which might point anywhere. */
3205 if (live_vector_p (m, po))
3206 mark_p = (!GC_SUBRP (obj)
3207 && !(XVECTOR (obj)->size & ARRAY_MARK_FLAG));
3208 else if (live_buffer_p (m, po))
3209 mark_p = GC_BUFFERP (obj) && !XMARKBIT (XBUFFER (obj)->name);
3210 break;
3211
3212 case Lisp_Misc:
3213 if (live_misc_p (m, po))
3214 {
3215 switch (XMISCTYPE (obj))
3216 {
3217 case Lisp_Misc_Marker:
3218 mark_p = !XMARKBIT (XMARKER (obj)->chain);
3219 break;
3220
3221 case Lisp_Misc_Buffer_Local_Value:
3222 case Lisp_Misc_Some_Buffer_Local_Value:
3223 mark_p = !XMARKBIT (XBUFFER_LOCAL_VALUE (obj)->realvalue);
3224 break;
3225
3226 case Lisp_Misc_Overlay:
3227 mark_p = !XMARKBIT (XOVERLAY (obj)->plist);
3228 break;
3229 }
3230 }
3231 break;
6bbd7a29
GM
3232
3233 case Lisp_Int:
31d929e5 3234 case Lisp_Type_Limit:
6bbd7a29 3235 break;
182ff242
GM
3236 }
3237
3238 if (mark_p)
3239 {
3240#if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3241 if (nzombies < MAX_ZOMBIES)
3242 zombies[nzombies] = *p;
3243 ++nzombies;
3244#endif
3245 mark_object (&obj);
3246 }
3247 }
3248}
3249
34400008
GM
3250/* Mark Lisp objects in the address range START..END. */
3251
3252static void
3253mark_memory (start, end)
3254 void *start, *end;
3255{
3256 Lisp_Object *p;
3257
3258#if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3259 nzombies = 0;
3260#endif
3261
3262 /* Make START the pointer to the start of the memory region,
3263 if it isn't already. */
3264 if (end < start)
3265 {
3266 void *tem = start;
3267 start = end;
3268 end = tem;
3269 }
182ff242 3270
34400008 3271 for (p = (Lisp_Object *) start; (void *) p < end; ++p)
182ff242
GM
3272 mark_maybe_object (*p);
3273}
3274
3275
3276#if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
3277
3278static int setjmp_tested_p, longjmps_done;
3279
3280#define SETJMP_WILL_LIKELY_WORK "\
3281\n\
3282Emacs garbage collector has been changed to use conservative stack\n\
3283marking. Emacs has determined that the method it uses to do the\n\
3284marking will likely work on your system, but this isn't sure.\n\
3285\n\
3286If you are a system-programmer, or can get the help of a local wizard\n\
3287who is, please take a look at the function mark_stack in alloc.c, and\n\
3288verify that the methods used are appropriate for your system.\n\
3289\n\
3290Please mail the result to <gerd@gnu.org>.\n\
3291"
3292
3293#define SETJMP_WILL_NOT_WORK "\
3294\n\
3295Emacs garbage collector has been changed to use conservative stack\n\
3296marking. Emacs has determined that the default method it uses to do the\n\
3297marking will not work on your system. We will need a system-dependent\n\
3298solution for your system.\n\
3299\n\
3300Please take a look at the function mark_stack in alloc.c, and\n\
3301try to find a way to make it work on your system.\n\
3302Please mail the result to <gerd@gnu.org>.\n\
3303"
3304
3305
3306/* Perform a quick check if it looks like setjmp saves registers in a
3307 jmp_buf. Print a message to stderr saying so. When this test
3308 succeeds, this is _not_ a proof that setjmp is sufficient for
3309 conservative stack marking. Only the sources or a disassembly
3310 can prove that. */
3311
3312static void
3313test_setjmp ()
3314{
3315 char buf[10];
3316 register int x;
3317 jmp_buf jbuf;
3318 int result = 0;
3319
3320 /* Arrange for X to be put in a register. */
3321 sprintf (buf, "1");
3322 x = strlen (buf);
3323 x = 2 * x - 1;
3324
3325 setjmp (jbuf);
3326 if (longjmps_done == 1)
34400008 3327 {
182ff242 3328 /* Came here after the longjmp at the end of the function.
34400008 3329
182ff242
GM
3330 If x == 1, the longjmp has restored the register to its
3331 value before the setjmp, and we can hope that setjmp
3332 saves all such registers in the jmp_buf, although that
3333 isn't sure.
34400008 3334
182ff242
GM
3335 For other values of X, either something really strange is
3336 taking place, or the setjmp just didn't save the register. */
3337
3338 if (x == 1)
3339 fprintf (stderr, SETJMP_WILL_LIKELY_WORK);
3340 else
3341 {
3342 fprintf (stderr, SETJMP_WILL_NOT_WORK);
3343 exit (1);
34400008
GM
3344 }
3345 }
182ff242
GM
3346
3347 ++longjmps_done;
3348 x = 2;
3349 if (longjmps_done == 1)
3350 longjmp (jbuf, 1);
34400008
GM
3351}
3352
182ff242
GM
3353#endif /* not GC_SAVE_REGISTERS_ON_STACK && not GC_SETJMP_WORKS */
3354
34400008
GM
3355
3356#if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
3357
3358/* Abort if anything GCPRO'd doesn't survive the GC. */
3359
3360static void
3361check_gcpros ()
3362{
3363 struct gcpro *p;
3364 int i;
3365
3366 for (p = gcprolist; p; p = p->next)
3367 for (i = 0; i < p->nvars; ++i)
3368 if (!survives_gc_p (p->var[i]))
3369 abort ();
3370}
3371
3372#elif GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3373
3374static void
3375dump_zombies ()
3376{
3377 int i;
3378
3379 fprintf (stderr, "\nZombies kept alive = %d:\n", nzombies);
3380 for (i = 0; i < min (MAX_ZOMBIES, nzombies); ++i)
3381 {
3382 fprintf (stderr, " %d = ", i);
3383 debug_print (zombies[i]);
3384 }
3385}
3386
3387#endif /* GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES */
3388
3389
182ff242
GM
3390/* Mark live Lisp objects on the C stack.
3391
3392 There are several system-dependent problems to consider when
3393 porting this to new architectures:
3394
3395 Processor Registers
3396
3397 We have to mark Lisp objects in CPU registers that can hold local
3398 variables or are used to pass parameters.
3399
3400 If GC_SAVE_REGISTERS_ON_STACK is defined, it should expand to
3401 something that either saves relevant registers on the stack, or
3402 calls mark_maybe_object passing it each register's contents.
3403
3404 If GC_SAVE_REGISTERS_ON_STACK is not defined, the current
3405 implementation assumes that calling setjmp saves registers we need
3406 to see in a jmp_buf which itself lies on the stack. This doesn't
3407 have to be true! It must be verified for each system, possibly
3408 by taking a look at the source code of setjmp.
3409
3410 Stack Layout
3411
3412 Architectures differ in the way their processor stack is organized.
3413 For example, the stack might look like this
3414
3415 +----------------+
3416 | Lisp_Object | size = 4
3417 +----------------+
3418 | something else | size = 2
3419 +----------------+
3420 | Lisp_Object | size = 4
3421 +----------------+
3422 | ... |
3423
3424 In such a case, not every Lisp_Object will be aligned equally. To
3425 find all Lisp_Object on the stack it won't be sufficient to walk
3426 the stack in steps of 4 bytes. Instead, two passes will be
3427 necessary, one starting at the start of the stack, and a second
3428 pass starting at the start of the stack + 2. Likewise, if the
3429 minimal alignment of Lisp_Objects on the stack is 1, four passes
3430 would be necessary, each one starting with one byte more offset
3431 from the stack start.
3432
3433 The current code assumes by default that Lisp_Objects are aligned
3434 equally on the stack. */
34400008
GM
3435
3436static void
3437mark_stack ()
3438{
3439 jmp_buf j;
6bbd7a29 3440 volatile int stack_grows_down_p = (char *) &j > (char *) stack_base;
34400008
GM
3441 void *end;
3442
3443 /* This trick flushes the register windows so that all the state of
3444 the process is contained in the stack. */
3445#ifdef sparc
3446 asm ("ta 3");
3447#endif
3448
3449 /* Save registers that we need to see on the stack. We need to see
3450 registers used to hold register variables and registers used to
3451 pass parameters. */
3452#ifdef GC_SAVE_REGISTERS_ON_STACK
3453 GC_SAVE_REGISTERS_ON_STACK (end);
182ff242
GM
3454#else /* not GC_SAVE_REGISTERS_ON_STACK */
3455
3456#ifndef GC_SETJMP_WORKS /* If it hasn't been checked yet that
3457 setjmp will definitely work, test it
3458 and print a message with the result
3459 of the test. */
3460 if (!setjmp_tested_p)
3461 {
3462 setjmp_tested_p = 1;
3463 test_setjmp ();
3464 }
3465#endif /* GC_SETJMP_WORKS */
3466
34400008
GM
3467 setjmp (j);
3468 end = stack_grows_down_p ? (char *) &j + sizeof j : (char *) &j;
182ff242 3469#endif /* not GC_SAVE_REGISTERS_ON_STACK */
34400008
GM
3470
3471 /* This assumes that the stack is a contiguous region in memory. If
182ff242
GM
3472 that's not the case, something has to be done here to iterate
3473 over the stack segments. */
3474#if GC_LISP_OBJECT_ALIGNMENT == 1
3475 mark_memory (stack_base, end);
3476 mark_memory ((char *) stack_base + 1, end);
3477 mark_memory ((char *) stack_base + 2, end);
3478 mark_memory ((char *) stack_base + 3, end);
3479#elif GC_LISP_OBJECT_ALIGNMENT == 2
3480 mark_memory (stack_base, end);
3481 mark_memory ((char *) stack_base + 2, end);
3482#else
34400008 3483 mark_memory (stack_base, end);
182ff242 3484#endif
34400008
GM
3485
3486#if GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS
3487 check_gcpros ();
3488#endif
3489}
3490
3491
3492#endif /* GC_MARK_STACK != 0 */
3493
3494
3495\f
2e471eb5
GM
3496/***********************************************************************
3497 Pure Storage Management
3498 ***********************************************************************/
3499
1f0b3fd2
GM
3500/* Allocate room for SIZE bytes from pure Lisp storage and return a
3501 pointer to it. TYPE is the Lisp type for which the memory is
3502 allocated. TYPE < 0 means it's not used for a Lisp object.
3503
3504 If store_pure_type_info is set and TYPE is >= 0, the type of
3505 the allocated object is recorded in pure_types. */
3506
3507static POINTER_TYPE *
3508pure_alloc (size, type)
3509 size_t size;
3510 int type;
3511{
3512 size_t nbytes;
3513 POINTER_TYPE *result;
3514 char *beg = PUREBEG;
3515
3516 /* Give Lisp_Floats an extra alignment. */
3517 if (type == Lisp_Float)
3518 {
3519 size_t alignment;
3520#if defined __GNUC__ && __GNUC__ >= 2
3521 alignment = __alignof (struct Lisp_Float);
3522#else
3523 alignment = sizeof (struct Lisp_Float);
3524#endif
3525 pure_bytes_used = ALIGN (pure_bytes_used, alignment);
3526 }
3527
3528 nbytes = ALIGN (size, sizeof (EMACS_INT));
3529 if (pure_bytes_used + nbytes > PURESIZE)
3530 error ("Pure Lisp storage exhausted");
3531
3532 result = (POINTER_TYPE *) (beg + pure_bytes_used);
3533 pure_bytes_used += nbytes;
3534 return result;
3535}
3536
3537
2e471eb5
GM
3538/* Return a string allocated in pure space. DATA is a buffer holding
3539 NCHARS characters, and NBYTES bytes of string data. MULTIBYTE
3540 non-zero means make the result string multibyte.
1a4f1e2c 3541
2e471eb5
GM
3542 Must get an error if pure storage is full, since if it cannot hold
3543 a large string it may be able to hold conses that point to that
3544 string; then the string is not protected from gc. */
7146af97
JB
3545
3546Lisp_Object
2e471eb5 3547make_pure_string (data, nchars, nbytes, multibyte)
7146af97 3548 char *data;
2e471eb5 3549 int nchars, nbytes;
c0696668 3550 int multibyte;
7146af97 3551{
2e471eb5
GM
3552 Lisp_Object string;
3553 struct Lisp_String *s;
c0696668 3554
1f0b3fd2
GM
3555 s = (struct Lisp_String *) pure_alloc (sizeof *s, Lisp_String);
3556 s->data = (unsigned char *) pure_alloc (nbytes + 1, -1);
2e471eb5
GM
3557 s->size = nchars;
3558 s->size_byte = multibyte ? nbytes : -1;
3559 bcopy (data, s->data, nbytes);
3560 s->data[nbytes] = '\0';
3561 s->intervals = NULL_INTERVAL;
2e471eb5
GM
3562 XSETSTRING (string, s);
3563 return string;
7146af97
JB
3564}
3565
2e471eb5 3566
34400008
GM
3567/* Return a cons allocated from pure space. Give it pure copies
3568 of CAR as car and CDR as cdr. */
3569
7146af97
JB
3570Lisp_Object
3571pure_cons (car, cdr)
3572 Lisp_Object car, cdr;
3573{
3574 register Lisp_Object new;
1f0b3fd2 3575 struct Lisp_Cons *p;
7146af97 3576
1f0b3fd2
GM
3577 p = (struct Lisp_Cons *) pure_alloc (sizeof *p, Lisp_Cons);
3578 XSETCONS (new, p);
70949dac
KR
3579 XCAR (new) = Fpurecopy (car);
3580 XCDR (new) = Fpurecopy (cdr);
7146af97
JB
3581 return new;
3582}
3583
7146af97 3584
34400008
GM
3585/* Value is a float object with value NUM allocated from pure space. */
3586
7146af97
JB
3587Lisp_Object
3588make_pure_float (num)
3589 double num;
3590{
3591 register Lisp_Object new;
1f0b3fd2 3592 struct Lisp_Float *p;
7146af97 3593
1f0b3fd2
GM
3594 p = (struct Lisp_Float *) pure_alloc (sizeof *p, Lisp_Float);
3595 XSETFLOAT (new, p);
70949dac 3596 XFLOAT_DATA (new) = num;
7146af97
JB
3597 return new;
3598}
3599
34400008
GM
3600
3601/* Return a vector with room for LEN Lisp_Objects allocated from
3602 pure space. */
3603
7146af97
JB
3604Lisp_Object
3605make_pure_vector (len)
42607681 3606 EMACS_INT len;
7146af97 3607{
1f0b3fd2
GM
3608 Lisp_Object new;
3609 struct Lisp_Vector *p;
3610 size_t size = sizeof *p + (len - 1) * sizeof (Lisp_Object);
7146af97 3611
1f0b3fd2
GM
3612 p = (struct Lisp_Vector *) pure_alloc (size, Lisp_Vectorlike);
3613 XSETVECTOR (new, p);
7146af97
JB
3614 XVECTOR (new)->size = len;
3615 return new;
3616}
3617
34400008 3618
7146af97
JB
3619DEFUN ("purecopy", Fpurecopy, Spurecopy, 1, 1, 0,
3620 "Make a copy of OBJECT in pure storage.\n\
3621Recursively copies contents of vectors and cons cells.\n\
d71c0668 3622Does not copy symbols. Copies strings without text properties.")
7146af97
JB
3623 (obj)
3624 register Lisp_Object obj;
3625{
265a9e55 3626 if (NILP (Vpurify_flag))
7146af97
JB
3627 return obj;
3628
1f0b3fd2 3629 if (PURE_POINTER_P (XPNTR (obj)))
7146af97
JB
3630 return obj;
3631
d6dd74bb 3632 if (CONSP (obj))
70949dac 3633 return pure_cons (XCAR (obj), XCDR (obj));
d6dd74bb 3634 else if (FLOATP (obj))
70949dac 3635 return make_pure_float (XFLOAT_DATA (obj));
d6dd74bb 3636 else if (STRINGP (obj))
3f25e183 3637 return make_pure_string (XSTRING (obj)->data, XSTRING (obj)->size,
c0696668
RS
3638 STRING_BYTES (XSTRING (obj)),
3639 STRING_MULTIBYTE (obj));
d6dd74bb
KH
3640 else if (COMPILEDP (obj) || VECTORP (obj))
3641 {
3642 register struct Lisp_Vector *vec;
3643 register int i, size;
3644
3645 size = XVECTOR (obj)->size;
7d535c68
KH
3646 if (size & PSEUDOVECTOR_FLAG)
3647 size &= PSEUDOVECTOR_SIZE_MASK;
01a4d290 3648 vec = XVECTOR (make_pure_vector ((EMACS_INT) size));
d6dd74bb
KH
3649 for (i = 0; i < size; i++)
3650 vec->contents[i] = Fpurecopy (XVECTOR (obj)->contents[i]);
3651 if (COMPILEDP (obj))
3652 XSETCOMPILED (obj, vec);
3653 else
3654 XSETVECTOR (obj, vec);
7146af97
JB
3655 return obj;
3656 }
d6dd74bb
KH
3657 else if (MARKERP (obj))
3658 error ("Attempt to copy a marker to pure storage");
6bbd7a29
GM
3659
3660 return obj;
7146af97 3661}
2e471eb5 3662
34400008 3663
7146af97 3664\f
34400008
GM
3665/***********************************************************************
3666 Protection from GC
3667 ***********************************************************************/
3668
2e471eb5
GM
3669/* Put an entry in staticvec, pointing at the variable with address
3670 VARADDRESS. */
7146af97
JB
3671
3672void
3673staticpro (varaddress)
3674 Lisp_Object *varaddress;
3675{
3676 staticvec[staticidx++] = varaddress;
3677 if (staticidx >= NSTATICS)
3678 abort ();
3679}
3680
3681struct catchtag
2e471eb5 3682{
7146af97
JB
3683 Lisp_Object tag;
3684 Lisp_Object val;
3685 struct catchtag *next;
2e471eb5 3686};
7146af97
JB
3687
3688struct backtrace
2e471eb5
GM
3689{
3690 struct backtrace *next;
3691 Lisp_Object *function;
3692 Lisp_Object *args; /* Points to vector of args. */
3693 int nargs; /* Length of vector. */
3694 /* If nargs is UNEVALLED, args points to slot holding list of
3695 unevalled args. */
3696 char evalargs;
3697};
3698
34400008 3699
7146af97 3700\f
34400008
GM
3701/***********************************************************************
3702 Protection from GC
3703 ***********************************************************************/
1a4f1e2c 3704
e8197642
RS
3705/* Temporarily prevent garbage collection. */
3706
3707int
3708inhibit_garbage_collection ()
3709{
3710 int count = specpdl_ptr - specpdl;
26b926e1 3711 Lisp_Object number;
68be917d 3712 int nbits = min (VALBITS, BITS_PER_INT);
e8197642 3713
b580578b 3714 XSETINT (number, ((EMACS_INT) 1 << (nbits - 1)) - 1);
26b926e1
RS
3715
3716 specbind (Qgc_cons_threshold, number);
e8197642
RS
3717
3718 return count;
3719}
3720
34400008 3721
7146af97
JB
3722DEFUN ("garbage-collect", Fgarbage_collect, Sgarbage_collect, 0, 0, "",
3723 "Reclaim storage for Lisp objects no longer needed.\n\
3724Returns info on amount of space in use:\n\
3725 ((USED-CONSES . FREE-CONSES) (USED-SYMS . FREE-SYMS)\n\
3726 (USED-MARKERS . FREE-MARKERS) USED-STRING-CHARS USED-VECTOR-SLOTS\n\
96117bc7 3727 (USED-FLOATS . FREE-FLOATS) (USED-INTERVALS . FREE-INTERVALS)\n\
2e471eb5 3728 (USED-STRINGS . FREE-STRINGS))\n\
7146af97
JB
3729Garbage collection happens automatically if you cons more than\n\
3730`gc-cons-threshold' bytes of Lisp data since previous garbage collection.")
3731 ()
3732{
3733 register struct gcpro *tail;
3734 register struct specbinding *bind;
3735 struct catchtag *catch;
3736 struct handler *handler;
3737 register struct backtrace *backlist;
7146af97
JB
3738 char stack_top_variable;
3739 register int i;
6efc7df7 3740 int message_p;
96117bc7 3741 Lisp_Object total[8];
98edb5ff 3742 int count = BINDING_STACK_SIZE ();
7146af97 3743
58595309
KH
3744 /* In case user calls debug_print during GC,
3745 don't let that cause a recursive GC. */
3746 consing_since_gc = 0;
3747
6efc7df7
GM
3748 /* Save what's currently displayed in the echo area. */
3749 message_p = push_message ();
98edb5ff 3750 record_unwind_protect (push_message_unwind, Qnil);
41c28a37 3751
7146af97
JB
3752 /* Save a copy of the contents of the stack, for debugging. */
3753#if MAX_SAVE_STACK > 0
265a9e55 3754 if (NILP (Vpurify_flag))
7146af97
JB
3755 {
3756 i = &stack_top_variable - stack_bottom;
3757 if (i < 0) i = -i;
3758 if (i < MAX_SAVE_STACK)
3759 {
3760 if (stack_copy == 0)
9ac0d9e0 3761 stack_copy = (char *) xmalloc (stack_copy_size = i);
7146af97 3762 else if (stack_copy_size < i)
9ac0d9e0 3763 stack_copy = (char *) xrealloc (stack_copy, (stack_copy_size = i));
7146af97
JB
3764 if (stack_copy)
3765 {
42607681 3766 if ((EMACS_INT) (&stack_top_variable - stack_bottom) > 0)
7146af97
JB
3767 bcopy (stack_bottom, stack_copy, i);
3768 else
3769 bcopy (&stack_top_variable, stack_copy, i);
3770 }
3771 }
3772 }
3773#endif /* MAX_SAVE_STACK > 0 */
3774
299585ee 3775 if (garbage_collection_messages)
691c4285 3776 message1_nolog ("Garbage collecting...");
7146af97 3777
6e0fca1d
RS
3778 BLOCK_INPUT;
3779
eec7b73d
RS
3780 shrink_regexp_cache ();
3781
4929a878 3782 /* Don't keep undo information around forever. */
7146af97
JB
3783 {
3784 register struct buffer *nextb = all_buffers;
3785
3786 while (nextb)
3787 {
ffd56f97
JB
3788 /* If a buffer's undo list is Qt, that means that undo is
3789 turned off in that buffer. Calling truncate_undo_list on
3790 Qt tends to return NULL, which effectively turns undo back on.
3791 So don't call truncate_undo_list if undo_list is Qt. */
3792 if (! EQ (nextb->undo_list, Qt))
3793 nextb->undo_list
502b9b64
JB
3794 = truncate_undo_list (nextb->undo_list, undo_limit,
3795 undo_strong_limit);
7146af97
JB
3796 nextb = nextb->next;
3797 }
3798 }
3799
3800 gc_in_progress = 1;
3801
c23baf9f 3802 /* clear_marks (); */
7146af97 3803
7146af97
JB
3804 /* Mark all the special slots that serve as the roots of accessibility.
3805
3806 Usually the special slots to mark are contained in particular structures.
3807 Then we know no slot is marked twice because the structures don't overlap.
3808 In some cases, the structures point to the slots to be marked.
3809 For these, we use MARKBIT to avoid double marking of the slot. */
3810
3811 for (i = 0; i < staticidx; i++)
3812 mark_object (staticvec[i]);
34400008
GM
3813
3814#if (GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS \
3815 || GC_MARK_STACK == GC_MARK_STACK_CHECK_GCPROS)
3816 mark_stack ();
3817#else
7146af97
JB
3818 for (tail = gcprolist; tail; tail = tail->next)
3819 for (i = 0; i < tail->nvars; i++)
3820 if (!XMARKBIT (tail->var[i]))
3821 {
1efc2bb9
EZ
3822 /* Explicit casting prevents compiler warning about
3823 discarding the `volatile' qualifier. */
3824 mark_object ((Lisp_Object *)&tail->var[i]);
7146af97
JB
3825 XMARK (tail->var[i]);
3826 }
34400008
GM
3827#endif
3828
630686c8 3829 mark_byte_stack ();
7146af97
JB
3830 for (bind = specpdl; bind != specpdl_ptr; bind++)
3831 {
3832 mark_object (&bind->symbol);
3833 mark_object (&bind->old_value);
3834 }
3835 for (catch = catchlist; catch; catch = catch->next)
3836 {
3837 mark_object (&catch->tag);
3838 mark_object (&catch->val);
3839 }
3840 for (handler = handlerlist; handler; handler = handler->next)
3841 {
3842 mark_object (&handler->handler);
3843 mark_object (&handler->var);
3844 }
3845 for (backlist = backtrace_list; backlist; backlist = backlist->next)
3846 {
3847 if (!XMARKBIT (*backlist->function))
3848 {
3849 mark_object (backlist->function);
3850 XMARK (*backlist->function);
3851 }
3852 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
3853 i = 0;
3854 else
3855 i = backlist->nargs - 1;
3856 for (; i >= 0; i--)
3857 if (!XMARKBIT (backlist->args[i]))
3858 {
3859 mark_object (&backlist->args[i]);
3860 XMARK (backlist->args[i]);
3861 }
3862 }
b875d3f7 3863 mark_kboards ();
7146af97 3864
4c315bda
RS
3865 /* Look thru every buffer's undo list
3866 for elements that update markers that were not marked,
3867 and delete them. */
3868 {
3869 register struct buffer *nextb = all_buffers;
3870
3871 while (nextb)
3872 {
3873 /* If a buffer's undo list is Qt, that means that undo is
3874 turned off in that buffer. Calling truncate_undo_list on
3875 Qt tends to return NULL, which effectively turns undo back on.
3876 So don't call truncate_undo_list if undo_list is Qt. */
3877 if (! EQ (nextb->undo_list, Qt))
3878 {
3879 Lisp_Object tail, prev;
3880 tail = nextb->undo_list;
3881 prev = Qnil;
3882 while (CONSP (tail))
3883 {
70949dac
KR
3884 if (GC_CONSP (XCAR (tail))
3885 && GC_MARKERP (XCAR (XCAR (tail)))
3886 && ! XMARKBIT (XMARKER (XCAR (XCAR (tail)))->chain))
4c315bda
RS
3887 {
3888 if (NILP (prev))
70949dac 3889 nextb->undo_list = tail = XCDR (tail);
4c315bda 3890 else
70949dac 3891 tail = XCDR (prev) = XCDR (tail);
4c315bda
RS
3892 }
3893 else
3894 {
3895 prev = tail;
70949dac 3896 tail = XCDR (tail);
4c315bda
RS
3897 }
3898 }
3899 }
3900
3901 nextb = nextb->next;
3902 }
3903 }
3904
34400008
GM
3905#if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
3906 mark_stack ();
3907#endif
3908
7146af97
JB
3909 gc_sweep ();
3910
3911 /* Clear the mark bits that we set in certain root slots. */
3912
34400008
GM
3913#if (GC_MARK_STACK == GC_USE_GCPROS_AS_BEFORE \
3914 || GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES)
7146af97
JB
3915 for (tail = gcprolist; tail; tail = tail->next)
3916 for (i = 0; i < tail->nvars; i++)
3917 XUNMARK (tail->var[i]);
34400008
GM
3918#endif
3919
033a5fa3 3920 unmark_byte_stack ();
7146af97
JB
3921 for (backlist = backtrace_list; backlist; backlist = backlist->next)
3922 {
3923 XUNMARK (*backlist->function);
3924 if (backlist->nargs == UNEVALLED || backlist->nargs == MANY)
3925 i = 0;
3926 else
3927 i = backlist->nargs - 1;
3928 for (; i >= 0; i--)
3929 XUNMARK (backlist->args[i]);
3930 }
3931 XUNMARK (buffer_defaults.name);
3932 XUNMARK (buffer_local_symbols.name);
3933
34400008
GM
3934#if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES && 0
3935 dump_zombies ();
3936#endif
3937
6e0fca1d
RS
3938 UNBLOCK_INPUT;
3939
c23baf9f 3940 /* clear_marks (); */
7146af97
JB
3941 gc_in_progress = 0;
3942
3943 consing_since_gc = 0;
3944 if (gc_cons_threshold < 10000)
3945 gc_cons_threshold = 10000;
3946
299585ee
RS
3947 if (garbage_collection_messages)
3948 {
6efc7df7
GM
3949 if (message_p || minibuf_level > 0)
3950 restore_message ();
299585ee
RS
3951 else
3952 message1_nolog ("Garbage collecting...done");
3953 }
7146af97 3954
98edb5ff 3955 unbind_to (count, Qnil);
2e471eb5
GM
3956
3957 total[0] = Fcons (make_number (total_conses),
3958 make_number (total_free_conses));
3959 total[1] = Fcons (make_number (total_symbols),
3960 make_number (total_free_symbols));
3961 total[2] = Fcons (make_number (total_markers),
3962 make_number (total_free_markers));
96117bc7
GM
3963 total[3] = make_number (total_string_size);
3964 total[4] = make_number (total_vector_size);
3965 total[5] = Fcons (make_number (total_floats),
2e471eb5 3966 make_number (total_free_floats));
96117bc7 3967 total[6] = Fcons (make_number (total_intervals),
2e471eb5 3968 make_number (total_free_intervals));
96117bc7 3969 total[7] = Fcons (make_number (total_strings),
2e471eb5
GM
3970 make_number (total_free_strings));
3971
34400008 3972#if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
7146af97 3973 {
34400008
GM
3974 /* Compute average percentage of zombies. */
3975 double nlive = 0;
3976
3977 for (i = 0; i < 7; ++i)
3978 nlive += XFASTINT (XCAR (total[i]));
3979
3980 avg_live = (avg_live * ngcs + nlive) / (ngcs + 1);
3981 max_live = max (nlive, max_live);
3982 avg_zombies = (avg_zombies * ngcs + nzombies) / (ngcs + 1);
3983 max_zombies = max (nzombies, max_zombies);
3984 ++ngcs;
3985 }
3986#endif
7146af97 3987
96117bc7 3988 return Flist (sizeof total / sizeof *total, total);
7146af97 3989}
34400008 3990
41c28a37 3991
3770920e
GM
3992/* Mark Lisp objects in glyph matrix MATRIX. Currently the
3993 only interesting objects referenced from glyphs are strings. */
41c28a37
GM
3994
3995static void
3996mark_glyph_matrix (matrix)
3997 struct glyph_matrix *matrix;
3998{
3999 struct glyph_row *row = matrix->rows;
4000 struct glyph_row *end = row + matrix->nrows;
4001
2e471eb5
GM
4002 for (; row < end; ++row)
4003 if (row->enabled_p)
4004 {
4005 int area;
4006 for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
4007 {
4008 struct glyph *glyph = row->glyphs[area];
4009 struct glyph *end_glyph = glyph + row->used[area];
4010
4011 for (; glyph < end_glyph; ++glyph)
4012 if (GC_STRINGP (glyph->object)
4013 && !STRING_MARKED_P (XSTRING (glyph->object)))
4014 mark_object (&glyph->object);
4015 }
4016 }
41c28a37
GM
4017}
4018
34400008 4019
41c28a37
GM
4020/* Mark Lisp faces in the face cache C. */
4021
4022static void
4023mark_face_cache (c)
4024 struct face_cache *c;
4025{
4026 if (c)
4027 {
4028 int i, j;
4029 for (i = 0; i < c->used; ++i)
4030 {
4031 struct face *face = FACE_FROM_ID (c->f, i);
4032
4033 if (face)
4034 {
4035 for (j = 0; j < LFACE_VECTOR_SIZE; ++j)
4036 mark_object (&face->lface[j]);
41c28a37
GM
4037 }
4038 }
4039 }
4040}
4041
4042
4043#ifdef HAVE_WINDOW_SYSTEM
4044
4045/* Mark Lisp objects in image IMG. */
4046
4047static void
4048mark_image (img)
4049 struct image *img;
4050{
4051 mark_object (&img->spec);
4052
3e60b029 4053 if (!NILP (img->data.lisp_val))
41c28a37
GM
4054 mark_object (&img->data.lisp_val);
4055}
4056
4057
4058/* Mark Lisp objects in image cache of frame F. It's done this way so
4059 that we don't have to include xterm.h here. */
4060
4061static void
4062mark_image_cache (f)
4063 struct frame *f;
4064{
4065 forall_images_in_image_cache (f, mark_image);
4066}
4067
4068#endif /* HAVE_X_WINDOWS */
4069
4070
7146af97 4071\f
1a4f1e2c 4072/* Mark reference to a Lisp_Object.
2e471eb5
GM
4073 If the object referred to has not been seen yet, recursively mark
4074 all the references contained in it. */
7146af97 4075
785cd37f
RS
4076#define LAST_MARKED_SIZE 500
4077Lisp_Object *last_marked[LAST_MARKED_SIZE];
4078int last_marked_index;
4079
41c28a37 4080void
436c5811
RS
4081mark_object (argptr)
4082 Lisp_Object *argptr;
7146af97 4083{
436c5811 4084 Lisp_Object *objptr = argptr;
7146af97 4085 register Lisp_Object obj;
4f5c1376
GM
4086#ifdef GC_CHECK_MARKED_OBJECTS
4087 void *po;
4088 struct mem_node *m;
4089#endif
7146af97 4090
9149e743 4091 loop:
7146af97 4092 obj = *objptr;
9149e743 4093 loop2:
7146af97
JB
4094 XUNMARK (obj);
4095
1f0b3fd2 4096 if (PURE_POINTER_P (XPNTR (obj)))
7146af97
JB
4097 return;
4098
785cd37f
RS
4099 last_marked[last_marked_index++] = objptr;
4100 if (last_marked_index == LAST_MARKED_SIZE)
4101 last_marked_index = 0;
4102
4f5c1376
GM
4103 /* Perform some sanity checks on the objects marked here. Abort if
4104 we encounter an object we know is bogus. This increases GC time
4105 by ~80%, and requires compilation with GC_MARK_STACK != 0. */
4106#ifdef GC_CHECK_MARKED_OBJECTS
4107
4108 po = (void *) XPNTR (obj);
4109
4110 /* Check that the object pointed to by PO is known to be a Lisp
4111 structure allocated from the heap. */
4112#define CHECK_ALLOCATED() \
4113 do { \
4114 m = mem_find (po); \
4115 if (m == MEM_NIL) \
4116 abort (); \
4117 } while (0)
4118
4119 /* Check that the object pointed to by PO is live, using predicate
4120 function LIVEP. */
4121#define CHECK_LIVE(LIVEP) \
4122 do { \
4123 if (!LIVEP (m, po)) \
4124 abort (); \
4125 } while (0)
4126
4127 /* Check both of the above conditions. */
4128#define CHECK_ALLOCATED_AND_LIVE(LIVEP) \
4129 do { \
4130 CHECK_ALLOCATED (); \
4131 CHECK_LIVE (LIVEP); \
4132 } while (0) \
4133
4134#else /* not GC_CHECK_MARKED_OBJECTS */
4135
4136#define CHECK_ALLOCATED() (void) 0
4137#define CHECK_LIVE(LIVEP) (void) 0
4138#define CHECK_ALLOCATED_AND_LIVE(LIVEP) (void) 0
4139
4140#endif /* not GC_CHECK_MARKED_OBJECTS */
4141
0220c518 4142 switch (SWITCH_ENUM_CAST (XGCTYPE (obj)))
7146af97
JB
4143 {
4144 case Lisp_String:
4145 {
4146 register struct Lisp_String *ptr = XSTRING (obj);
4f5c1376 4147 CHECK_ALLOCATED_AND_LIVE (live_string_p);
d5e35230 4148 MARK_INTERVAL_TREE (ptr->intervals);
2e471eb5 4149 MARK_STRING (ptr);
361b097f 4150#ifdef GC_CHECK_STRING_BYTES
676a7251
GM
4151 /* Check that the string size recorded in the string is the
4152 same as the one recorded in the sdata structure. */
4153 CHECK_STRING_BYTES (ptr);
361b097f 4154#endif /* GC_CHECK_STRING_BYTES */
7146af97
JB
4155 }
4156 break;
4157
76437631 4158 case Lisp_Vectorlike:
4f5c1376
GM
4159#ifdef GC_CHECK_MARKED_OBJECTS
4160 m = mem_find (po);
4161 if (m == MEM_NIL && !GC_SUBRP (obj)
4162 && po != &buffer_defaults
4163 && po != &buffer_local_symbols)
4164 abort ();
4165#endif /* GC_CHECK_MARKED_OBJECTS */
4166
30e3190a 4167 if (GC_BUFFERP (obj))
6b552283
KH
4168 {
4169 if (!XMARKBIT (XBUFFER (obj)->name))
4f5c1376
GM
4170 {
4171#ifdef GC_CHECK_MARKED_OBJECTS
4172 if (po != &buffer_defaults && po != &buffer_local_symbols)
4173 {
4174 struct buffer *b;
4175 for (b = all_buffers; b && b != po; b = b->next)
4176 ;
4177 if (b == NULL)
4178 abort ();
4179 }
4180#endif /* GC_CHECK_MARKED_OBJECTS */
4181 mark_buffer (obj);
4182 }
6b552283 4183 }
30e3190a 4184 else if (GC_SUBRP (obj))
169ee243
RS
4185 break;
4186 else if (GC_COMPILEDP (obj))
2e471eb5
GM
4187 /* We could treat this just like a vector, but it is better to
4188 save the COMPILED_CONSTANTS element for last and avoid
4189 recursion there. */
169ee243
RS
4190 {
4191 register struct Lisp_Vector *ptr = XVECTOR (obj);
4192 register EMACS_INT size = ptr->size;
169ee243
RS
4193 register int i;
4194
4195 if (size & ARRAY_MARK_FLAG)
4196 break; /* Already marked */
4f5c1376
GM
4197
4198 CHECK_LIVE (live_vector_p);
169ee243 4199 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
76437631 4200 size &= PSEUDOVECTOR_SIZE_MASK;
169ee243
RS
4201 for (i = 0; i < size; i++) /* and then mark its elements */
4202 {
4203 if (i != COMPILED_CONSTANTS)
c70bbf06 4204 mark_object (&ptr->contents[i]);
169ee243
RS
4205 }
4206 /* This cast should be unnecessary, but some Mips compiler complains
4207 (MIPS-ABI + SysVR4, DC/OSx, etc). */
c70bbf06 4208 objptr = (Lisp_Object *) &ptr->contents[COMPILED_CONSTANTS];
169ee243
RS
4209 goto loop;
4210 }
169ee243
RS
4211 else if (GC_FRAMEP (obj))
4212 {
c70bbf06 4213 register struct frame *ptr = XFRAME (obj);
169ee243
RS
4214 register EMACS_INT size = ptr->size;
4215
4216 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
4217 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4218
4f5c1376 4219 CHECK_LIVE (live_vector_p);
169ee243 4220 mark_object (&ptr->name);
894a9d16 4221 mark_object (&ptr->icon_name);
aba6deb8 4222 mark_object (&ptr->title);
169ee243
RS
4223 mark_object (&ptr->focus_frame);
4224 mark_object (&ptr->selected_window);
4225 mark_object (&ptr->minibuffer_window);
4226 mark_object (&ptr->param_alist);
4227 mark_object (&ptr->scroll_bars);
4228 mark_object (&ptr->condemned_scroll_bars);
4229 mark_object (&ptr->menu_bar_items);
4230 mark_object (&ptr->face_alist);
4231 mark_object (&ptr->menu_bar_vector);
4232 mark_object (&ptr->buffer_predicate);
a0e1f185 4233 mark_object (&ptr->buffer_list);
41c28a37 4234 mark_object (&ptr->menu_bar_window);
9ea173e8 4235 mark_object (&ptr->tool_bar_window);
41c28a37
GM
4236 mark_face_cache (ptr->face_cache);
4237#ifdef HAVE_WINDOW_SYSTEM
4238 mark_image_cache (ptr);
e2c556b4 4239 mark_object (&ptr->tool_bar_items);
9ea173e8
GM
4240 mark_object (&ptr->desired_tool_bar_string);
4241 mark_object (&ptr->current_tool_bar_string);
41c28a37 4242#endif /* HAVE_WINDOW_SYSTEM */
169ee243 4243 }
7b07587b 4244 else if (GC_BOOL_VECTOR_P (obj))
707788bd
RS
4245 {
4246 register struct Lisp_Vector *ptr = XVECTOR (obj);
4247
4248 if (ptr->size & ARRAY_MARK_FLAG)
4249 break; /* Already marked */
4f5c1376 4250 CHECK_LIVE (live_vector_p);
707788bd
RS
4251 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4252 }
41c28a37
GM
4253 else if (GC_WINDOWP (obj))
4254 {
4255 register struct Lisp_Vector *ptr = XVECTOR (obj);
4256 struct window *w = XWINDOW (obj);
4257 register EMACS_INT size = ptr->size;
41c28a37
GM
4258 register int i;
4259
4260 /* Stop if already marked. */
4261 if (size & ARRAY_MARK_FLAG)
4262 break;
4263
4264 /* Mark it. */
4f5c1376 4265 CHECK_LIVE (live_vector_p);
41c28a37
GM
4266 ptr->size |= ARRAY_MARK_FLAG;
4267
4268 /* There is no Lisp data above The member CURRENT_MATRIX in
4269 struct WINDOW. Stop marking when that slot is reached. */
4270 for (i = 0;
c70bbf06 4271 (char *) &ptr->contents[i] < (char *) &w->current_matrix;
41c28a37 4272 i++)
c70bbf06 4273 mark_object (&ptr->contents[i]);
41c28a37
GM
4274
4275 /* Mark glyphs for leaf windows. Marking window matrices is
4276 sufficient because frame matrices use the same glyph
4277 memory. */
4278 if (NILP (w->hchild)
4279 && NILP (w->vchild)
4280 && w->current_matrix)
4281 {
4282 mark_glyph_matrix (w->current_matrix);
4283 mark_glyph_matrix (w->desired_matrix);
4284 }
4285 }
4286 else if (GC_HASH_TABLE_P (obj))
4287 {
4288 struct Lisp_Hash_Table *h = XHASH_TABLE (obj);
4289 EMACS_INT size = h->size;
4290
4291 /* Stop if already marked. */
4292 if (size & ARRAY_MARK_FLAG)
4293 break;
4f5c1376 4294
41c28a37 4295 /* Mark it. */
4f5c1376 4296 CHECK_LIVE (live_vector_p);
41c28a37
GM
4297 h->size |= ARRAY_MARK_FLAG;
4298
4299 /* Mark contents. */
4300 mark_object (&h->test);
4301 mark_object (&h->weak);
4302 mark_object (&h->rehash_size);
4303 mark_object (&h->rehash_threshold);
4304 mark_object (&h->hash);
4305 mark_object (&h->next);
4306 mark_object (&h->index);
4307 mark_object (&h->user_hash_function);
4308 mark_object (&h->user_cmp_function);
4309
4310 /* If hash table is not weak, mark all keys and values.
4311 For weak tables, mark only the vector. */
4312 if (GC_NILP (h->weak))
4313 mark_object (&h->key_and_value);
4314 else
4315 XVECTOR (h->key_and_value)->size |= ARRAY_MARK_FLAG;
4316
4317 }
04ff9756 4318 else
169ee243
RS
4319 {
4320 register struct Lisp_Vector *ptr = XVECTOR (obj);
4321 register EMACS_INT size = ptr->size;
169ee243
RS
4322 register int i;
4323
4324 if (size & ARRAY_MARK_FLAG) break; /* Already marked */
4f5c1376 4325 CHECK_LIVE (live_vector_p);
169ee243
RS
4326 ptr->size |= ARRAY_MARK_FLAG; /* Else mark it */
4327 if (size & PSEUDOVECTOR_FLAG)
4328 size &= PSEUDOVECTOR_SIZE_MASK;
41c28a37 4329
169ee243 4330 for (i = 0; i < size; i++) /* and then mark its elements */
c70bbf06 4331 mark_object (&ptr->contents[i]);
169ee243
RS
4332 }
4333 break;
7146af97 4334
7146af97
JB
4335 case Lisp_Symbol:
4336 {
c70bbf06 4337 register struct Lisp_Symbol *ptr = XSYMBOL (obj);
7146af97
JB
4338 struct Lisp_Symbol *ptrx;
4339
4340 if (XMARKBIT (ptr->plist)) break;
4f5c1376 4341 CHECK_ALLOCATED_AND_LIVE (live_symbol_p);
7146af97 4342 XMARK (ptr->plist);
7146af97
JB
4343 mark_object ((Lisp_Object *) &ptr->value);
4344 mark_object (&ptr->function);
4345 mark_object (&ptr->plist);
34400008
GM
4346
4347 if (!PURE_POINTER_P (ptr->name))
4348 MARK_STRING (ptr->name);
2e471eb5 4349 MARK_INTERVAL_TREE (ptr->name->intervals);
2e471eb5 4350
1c6bb482
RS
4351 /* Note that we do not mark the obarray of the symbol.
4352 It is safe not to do so because nothing accesses that
4353 slot except to check whether it is nil. */
7146af97
JB
4354 ptr = ptr->next;
4355 if (ptr)
4356 {
9149e743
KH
4357 /* For the benefit of the last_marked log. */
4358 objptr = (Lisp_Object *)&XSYMBOL (obj)->next;
b0846f52 4359 ptrx = ptr; /* Use of ptrx avoids compiler bug on Sun */
7146af97 4360 XSETSYMBOL (obj, ptrx);
9149e743
KH
4361 /* We can't goto loop here because *objptr doesn't contain an
4362 actual Lisp_Object with valid datatype field. */
4363 goto loop2;
7146af97
JB
4364 }
4365 }
4366 break;
4367
a0a38eb7 4368 case Lisp_Misc:
4f5c1376 4369 CHECK_ALLOCATED_AND_LIVE (live_misc_p);
a5da44fe 4370 switch (XMISCTYPE (obj))
a0a38eb7
KH
4371 {
4372 case Lisp_Misc_Marker:
4373 XMARK (XMARKER (obj)->chain);
4374 /* DO NOT mark thru the marker's chain.
4375 The buffer's markers chain does not preserve markers from gc;
4376 instead, markers are removed from the chain when freed by gc. */
4377 break;
4378
465edf35
KH
4379 case Lisp_Misc_Buffer_Local_Value:
4380 case Lisp_Misc_Some_Buffer_Local_Value:
4381 {
4382 register struct Lisp_Buffer_Local_Value *ptr
4383 = XBUFFER_LOCAL_VALUE (obj);
a9faeabe
RS
4384 if (XMARKBIT (ptr->realvalue)) break;
4385 XMARK (ptr->realvalue);
465edf35
KH
4386 /* If the cdr is nil, avoid recursion for the car. */
4387 if (EQ (ptr->cdr, Qnil))
4388 {
a9faeabe 4389 objptr = &ptr->realvalue;
465edf35
KH
4390 goto loop;
4391 }
a9faeabe
RS
4392 mark_object (&ptr->realvalue);
4393 mark_object (&ptr->buffer);
4394 mark_object (&ptr->frame);
c70bbf06 4395 objptr = &ptr->cdr;
465edf35
KH
4396 goto loop;
4397 }
4398
c8616056
KH
4399 case Lisp_Misc_Intfwd:
4400 case Lisp_Misc_Boolfwd:
4401 case Lisp_Misc_Objfwd:
4402 case Lisp_Misc_Buffer_Objfwd:
b875d3f7 4403 case Lisp_Misc_Kboard_Objfwd:
c8616056
KH
4404 /* Don't bother with Lisp_Buffer_Objfwd,
4405 since all markable slots in current buffer marked anyway. */
4406 /* Don't need to do Lisp_Objfwd, since the places they point
4407 are protected with staticpro. */
4408 break;
4409
e202fa34
KH
4410 case Lisp_Misc_Overlay:
4411 {
4412 struct Lisp_Overlay *ptr = XOVERLAY (obj);
4413 if (!XMARKBIT (ptr->plist))
4414 {
4415 XMARK (ptr->plist);
4416 mark_object (&ptr->start);
4417 mark_object (&ptr->end);
4418 objptr = &ptr->plist;
4419 goto loop;
4420 }
4421 }
4422 break;
4423
a0a38eb7
KH
4424 default:
4425 abort ();
4426 }
7146af97
JB
4427 break;
4428
4429 case Lisp_Cons:
7146af97
JB
4430 {
4431 register struct Lisp_Cons *ptr = XCONS (obj);
4432 if (XMARKBIT (ptr->car)) break;
4f5c1376 4433 CHECK_ALLOCATED_AND_LIVE (live_cons_p);
7146af97 4434 XMARK (ptr->car);
c54ca951
RS
4435 /* If the cdr is nil, avoid recursion for the car. */
4436 if (EQ (ptr->cdr, Qnil))
4437 {
4438 objptr = &ptr->car;
c54ca951
RS
4439 goto loop;
4440 }
7146af97 4441 mark_object (&ptr->car);
c70bbf06 4442 objptr = &ptr->cdr;
7146af97
JB
4443 goto loop;
4444 }
4445
7146af97 4446 case Lisp_Float:
4f5c1376 4447 CHECK_ALLOCATED_AND_LIVE (live_float_p);
7146af97
JB
4448 XMARK (XFLOAT (obj)->type);
4449 break;
7146af97 4450
7146af97 4451 case Lisp_Int:
7146af97
JB
4452 break;
4453
4454 default:
4455 abort ();
4456 }
4f5c1376
GM
4457
4458#undef CHECK_LIVE
4459#undef CHECK_ALLOCATED
4460#undef CHECK_ALLOCATED_AND_LIVE
7146af97
JB
4461}
4462
4463/* Mark the pointers in a buffer structure. */
4464
4465static void
4466mark_buffer (buf)
4467 Lisp_Object buf;
4468{
7146af97
JB
4469 register struct buffer *buffer = XBUFFER (buf);
4470 register Lisp_Object *ptr;
30e3190a 4471 Lisp_Object base_buffer;
7146af97
JB
4472
4473 /* This is the buffer's markbit */
4474 mark_object (&buffer->name);
4475 XMARK (buffer->name);
4476
30e3190a 4477 MARK_INTERVAL_TREE (BUF_INTERVALS (buffer));
d5e35230 4478
4c315bda
RS
4479 if (CONSP (buffer->undo_list))
4480 {
4481 Lisp_Object tail;
4482 tail = buffer->undo_list;
4483
4484 while (CONSP (tail))
4485 {
4486 register struct Lisp_Cons *ptr = XCONS (tail);
4487
4488 if (XMARKBIT (ptr->car))
4489 break;
4490 XMARK (ptr->car);
4491 if (GC_CONSP (ptr->car)
70949dac
KR
4492 && ! XMARKBIT (XCAR (ptr->car))
4493 && GC_MARKERP (XCAR (ptr->car)))
4c315bda 4494 {
70949dac
KR
4495 XMARK (XCAR (ptr->car));
4496 mark_object (&XCDR (ptr->car));
4c315bda
RS
4497 }
4498 else
4499 mark_object (&ptr->car);
4500
4501 if (CONSP (ptr->cdr))
4502 tail = ptr->cdr;
4503 else
4504 break;
4505 }
4506
70949dac 4507 mark_object (&XCDR (tail));
4c315bda
RS
4508 }
4509 else
4510 mark_object (&buffer->undo_list);
4511
7146af97
JB
4512 for (ptr = &buffer->name + 1;
4513 (char *)ptr < (char *)buffer + sizeof (struct buffer);
4514 ptr++)
4515 mark_object (ptr);
30e3190a
RS
4516
4517 /* If this is an indirect buffer, mark its base buffer. */
6b552283 4518 if (buffer->base_buffer && !XMARKBIT (buffer->base_buffer->name))
30e3190a
RS
4519 {
4520 XSETBUFFER (base_buffer, buffer->base_buffer);
4521 mark_buffer (base_buffer);
4522 }
7146af97 4523}
084b1a0c
KH
4524
4525
b875d3f7 4526/* Mark the pointers in the kboard objects. */
084b1a0c
KH
4527
4528static void
b875d3f7 4529mark_kboards ()
084b1a0c 4530{
b875d3f7 4531 KBOARD *kb;
b94daf1e 4532 Lisp_Object *p;
b875d3f7 4533 for (kb = all_kboards; kb; kb = kb->next_kboard)
084b1a0c 4534 {
b94daf1e
KH
4535 if (kb->kbd_macro_buffer)
4536 for (p = kb->kbd_macro_buffer; p < kb->kbd_macro_ptr; p++)
4537 mark_object (p);
4bfd0c4f
RS
4538 mark_object (&kb->Voverriding_terminal_local_map);
4539 mark_object (&kb->Vlast_command);
4540 mark_object (&kb->Vreal_last_command);
9671abc2 4541 mark_object (&kb->Vprefix_arg);
23c73c16 4542 mark_object (&kb->Vlast_prefix_arg);
b875d3f7 4543 mark_object (&kb->kbd_queue);
4bfd0c4f 4544 mark_object (&kb->defining_kbd_macro);
b875d3f7 4545 mark_object (&kb->Vlast_kbd_macro);
b94daf1e 4546 mark_object (&kb->Vsystem_key_alist);
6d03a6fd 4547 mark_object (&kb->system_key_syms);
4bfd0c4f 4548 mark_object (&kb->Vdefault_minibuffer_frame);
084b1a0c
KH
4549 }
4550}
41c28a37
GM
4551
4552
4553/* Value is non-zero if OBJ will survive the current GC because it's
4554 either marked or does not need to be marked to survive. */
4555
4556int
4557survives_gc_p (obj)
4558 Lisp_Object obj;
4559{
4560 int survives_p;
4561
4562 switch (XGCTYPE (obj))
4563 {
4564 case Lisp_Int:
4565 survives_p = 1;
4566 break;
4567
4568 case Lisp_Symbol:
4569 survives_p = XMARKBIT (XSYMBOL (obj)->plist);
4570 break;
4571
4572 case Lisp_Misc:
4573 switch (XMISCTYPE (obj))
4574 {
4575 case Lisp_Misc_Marker:
4576 survives_p = XMARKBIT (obj);
4577 break;
4578
4579 case Lisp_Misc_Buffer_Local_Value:
4580 case Lisp_Misc_Some_Buffer_Local_Value:
4581 survives_p = XMARKBIT (XBUFFER_LOCAL_VALUE (obj)->realvalue);
4582 break;
4583
4584 case Lisp_Misc_Intfwd:
4585 case Lisp_Misc_Boolfwd:
4586 case Lisp_Misc_Objfwd:
4587 case Lisp_Misc_Buffer_Objfwd:
4588 case Lisp_Misc_Kboard_Objfwd:
4589 survives_p = 1;
4590 break;
4591
4592 case Lisp_Misc_Overlay:
4593 survives_p = XMARKBIT (XOVERLAY (obj)->plist);
4594 break;
4595
4596 default:
4597 abort ();
4598 }
4599 break;
4600
4601 case Lisp_String:
4602 {
4603 struct Lisp_String *s = XSTRING (obj);
2e471eb5 4604 survives_p = STRING_MARKED_P (s);
41c28a37
GM
4605 }
4606 break;
4607
4608 case Lisp_Vectorlike:
4609 if (GC_BUFFERP (obj))
4610 survives_p = XMARKBIT (XBUFFER (obj)->name);
4611 else if (GC_SUBRP (obj))
4612 survives_p = 1;
4613 else
4614 survives_p = XVECTOR (obj)->size & ARRAY_MARK_FLAG;
4615 break;
4616
4617 case Lisp_Cons:
4618 survives_p = XMARKBIT (XCAR (obj));
4619 break;
4620
41c28a37
GM
4621 case Lisp_Float:
4622 survives_p = XMARKBIT (XFLOAT (obj)->type);
4623 break;
41c28a37
GM
4624
4625 default:
4626 abort ();
4627 }
4628
34400008 4629 return survives_p || PURE_POINTER_P ((void *) XPNTR (obj));
41c28a37
GM
4630}
4631
4632
7146af97 4633\f
1a4f1e2c 4634/* Sweep: find all structures not marked, and free them. */
7146af97
JB
4635
4636static void
4637gc_sweep ()
4638{
41c28a37
GM
4639 /* Remove or mark entries in weak hash tables.
4640 This must be done before any object is unmarked. */
4641 sweep_weak_hash_tables ();
4642
2e471eb5 4643 sweep_strings ();
676a7251
GM
4644#ifdef GC_CHECK_STRING_BYTES
4645 if (!noninteractive)
4646 check_string_bytes (1);
4647#endif
7146af97
JB
4648
4649 /* Put all unmarked conses on free list */
4650 {
4651 register struct cons_block *cblk;
6ca94ac9 4652 struct cons_block **cprev = &cons_block;
7146af97
JB
4653 register int lim = cons_block_index;
4654 register int num_free = 0, num_used = 0;
4655
4656 cons_free_list = 0;
4657
6ca94ac9 4658 for (cblk = cons_block; cblk; cblk = *cprev)
7146af97
JB
4659 {
4660 register int i;
6ca94ac9 4661 int this_free = 0;
7146af97
JB
4662 for (i = 0; i < lim; i++)
4663 if (!XMARKBIT (cblk->conses[i].car))
4664 {
6ca94ac9 4665 this_free++;
1cd5fe6a 4666 *(struct Lisp_Cons **)&cblk->conses[i].cdr = cons_free_list;
7146af97 4667 cons_free_list = &cblk->conses[i];
34400008
GM
4668#if GC_MARK_STACK
4669 cons_free_list->car = Vdead;
4670#endif
7146af97
JB
4671 }
4672 else
4673 {
4674 num_used++;
4675 XUNMARK (cblk->conses[i].car);
4676 }
4677 lim = CONS_BLOCK_SIZE;
6ca94ac9
KH
4678 /* If this block contains only free conses and we have already
4679 seen more than two blocks worth of free conses then deallocate
4680 this block. */
6feef451 4681 if (this_free == CONS_BLOCK_SIZE && num_free > CONS_BLOCK_SIZE)
6ca94ac9 4682 {
6ca94ac9
KH
4683 *cprev = cblk->next;
4684 /* Unhook from the free list. */
4685 cons_free_list = *(struct Lisp_Cons **) &cblk->conses[0].cdr;
c8099634
RS
4686 lisp_free (cblk);
4687 n_cons_blocks--;
6ca94ac9
KH
4688 }
4689 else
6feef451
AS
4690 {
4691 num_free += this_free;
4692 cprev = &cblk->next;
4693 }
7146af97
JB
4694 }
4695 total_conses = num_used;
4696 total_free_conses = num_free;
4697 }
4698
7146af97
JB
4699 /* Put all unmarked floats on free list */
4700 {
4701 register struct float_block *fblk;
6ca94ac9 4702 struct float_block **fprev = &float_block;
7146af97
JB
4703 register int lim = float_block_index;
4704 register int num_free = 0, num_used = 0;
4705
4706 float_free_list = 0;
4707
6ca94ac9 4708 for (fblk = float_block; fblk; fblk = *fprev)
7146af97
JB
4709 {
4710 register int i;
6ca94ac9 4711 int this_free = 0;
7146af97
JB
4712 for (i = 0; i < lim; i++)
4713 if (!XMARKBIT (fblk->floats[i].type))
4714 {
6ca94ac9 4715 this_free++;
1cd5fe6a 4716 *(struct Lisp_Float **)&fblk->floats[i].data = float_free_list;
7146af97 4717 float_free_list = &fblk->floats[i];
34400008
GM
4718#if GC_MARK_STACK
4719 float_free_list->type = Vdead;
4720#endif
7146af97
JB
4721 }
4722 else
4723 {
4724 num_used++;
4725 XUNMARK (fblk->floats[i].type);
4726 }
4727 lim = FLOAT_BLOCK_SIZE;
6ca94ac9
KH
4728 /* If this block contains only free floats and we have already
4729 seen more than two blocks worth of free floats then deallocate
4730 this block. */
6feef451 4731 if (this_free == FLOAT_BLOCK_SIZE && num_free > FLOAT_BLOCK_SIZE)
6ca94ac9 4732 {
6ca94ac9
KH
4733 *fprev = fblk->next;
4734 /* Unhook from the free list. */
4735 float_free_list = *(struct Lisp_Float **) &fblk->floats[0].data;
c8099634
RS
4736 lisp_free (fblk);
4737 n_float_blocks--;
6ca94ac9
KH
4738 }
4739 else
6feef451
AS
4740 {
4741 num_free += this_free;
4742 fprev = &fblk->next;
4743 }
7146af97
JB
4744 }
4745 total_floats = num_used;
4746 total_free_floats = num_free;
4747 }
7146af97 4748
d5e35230
JA
4749 /* Put all unmarked intervals on free list */
4750 {
4751 register struct interval_block *iblk;
6ca94ac9 4752 struct interval_block **iprev = &interval_block;
d5e35230
JA
4753 register int lim = interval_block_index;
4754 register int num_free = 0, num_used = 0;
4755
4756 interval_free_list = 0;
4757
6ca94ac9 4758 for (iblk = interval_block; iblk; iblk = *iprev)
d5e35230
JA
4759 {
4760 register int i;
6ca94ac9 4761 int this_free = 0;
d5e35230
JA
4762
4763 for (i = 0; i < lim; i++)
4764 {
4765 if (! XMARKBIT (iblk->intervals[i].plist))
4766 {
439d5cb4 4767 SET_INTERVAL_PARENT (&iblk->intervals[i], interval_free_list);
d5e35230 4768 interval_free_list = &iblk->intervals[i];
6ca94ac9 4769 this_free++;
d5e35230
JA
4770 }
4771 else
4772 {
4773 num_used++;
4774 XUNMARK (iblk->intervals[i].plist);
4775 }
4776 }
4777 lim = INTERVAL_BLOCK_SIZE;
6ca94ac9
KH
4778 /* If this block contains only free intervals and we have already
4779 seen more than two blocks worth of free intervals then
4780 deallocate this block. */
6feef451 4781 if (this_free == INTERVAL_BLOCK_SIZE && num_free > INTERVAL_BLOCK_SIZE)
6ca94ac9 4782 {
6ca94ac9
KH
4783 *iprev = iblk->next;
4784 /* Unhook from the free list. */
439d5cb4 4785 interval_free_list = INTERVAL_PARENT (&iblk->intervals[0]);
c8099634
RS
4786 lisp_free (iblk);
4787 n_interval_blocks--;
6ca94ac9
KH
4788 }
4789 else
6feef451
AS
4790 {
4791 num_free += this_free;
4792 iprev = &iblk->next;
4793 }
d5e35230
JA
4794 }
4795 total_intervals = num_used;
4796 total_free_intervals = num_free;
4797 }
d5e35230 4798
7146af97
JB
4799 /* Put all unmarked symbols on free list */
4800 {
4801 register struct symbol_block *sblk;
6ca94ac9 4802 struct symbol_block **sprev = &symbol_block;
7146af97
JB
4803 register int lim = symbol_block_index;
4804 register int num_free = 0, num_used = 0;
4805
d285b373 4806 symbol_free_list = NULL;
7146af97 4807
6ca94ac9 4808 for (sblk = symbol_block; sblk; sblk = *sprev)
7146af97 4809 {
6ca94ac9 4810 int this_free = 0;
d285b373
GM
4811 struct Lisp_Symbol *sym = sblk->symbols;
4812 struct Lisp_Symbol *end = sym + lim;
4813
4814 for (; sym < end; ++sym)
4815 {
20035321
SM
4816 /* Check if the symbol was created during loadup. In such a case
4817 it might be pointed to by pure bytecode which we don't trace,
4818 so we conservatively assume that it is live. */
d285b373
GM
4819 int pure_p = PURE_POINTER_P (sym->name);
4820
4821 if (!XMARKBIT (sym->plist) && !pure_p)
4822 {
4823 *(struct Lisp_Symbol **) &sym->value = symbol_free_list;
4824 symbol_free_list = sym;
34400008 4825#if GC_MARK_STACK
d285b373 4826 symbol_free_list->function = Vdead;
34400008 4827#endif
d285b373
GM
4828 ++this_free;
4829 }
4830 else
4831 {
4832 ++num_used;
4833 if (!pure_p)
4834 UNMARK_STRING (sym->name);
4835 XUNMARK (sym->plist);
4836 }
4837 }
4838
7146af97 4839 lim = SYMBOL_BLOCK_SIZE;
6ca94ac9
KH
4840 /* If this block contains only free symbols and we have already
4841 seen more than two blocks worth of free symbols then deallocate
4842 this block. */
6feef451 4843 if (this_free == SYMBOL_BLOCK_SIZE && num_free > SYMBOL_BLOCK_SIZE)
6ca94ac9 4844 {
6ca94ac9
KH
4845 *sprev = sblk->next;
4846 /* Unhook from the free list. */
4847 symbol_free_list = *(struct Lisp_Symbol **)&sblk->symbols[0].value;
c8099634
RS
4848 lisp_free (sblk);
4849 n_symbol_blocks--;
6ca94ac9
KH
4850 }
4851 else
6feef451
AS
4852 {
4853 num_free += this_free;
4854 sprev = &sblk->next;
4855 }
7146af97
JB
4856 }
4857 total_symbols = num_used;
4858 total_free_symbols = num_free;
4859 }
4860
a9faeabe
RS
4861 /* Put all unmarked misc's on free list.
4862 For a marker, first unchain it from the buffer it points into. */
7146af97
JB
4863 {
4864 register struct marker_block *mblk;
6ca94ac9 4865 struct marker_block **mprev = &marker_block;
7146af97
JB
4866 register int lim = marker_block_index;
4867 register int num_free = 0, num_used = 0;
4868
4869 marker_free_list = 0;
4870
6ca94ac9 4871 for (mblk = marker_block; mblk; mblk = *mprev)
7146af97
JB
4872 {
4873 register int i;
6ca94ac9 4874 int this_free = 0;
26b926e1 4875 EMACS_INT already_free = -1;
fa05e253 4876
7146af97 4877 for (i = 0; i < lim; i++)
465edf35
KH
4878 {
4879 Lisp_Object *markword;
a5da44fe 4880 switch (mblk->markers[i].u_marker.type)
465edf35
KH
4881 {
4882 case Lisp_Misc_Marker:
4883 markword = &mblk->markers[i].u_marker.chain;
4884 break;
4885 case Lisp_Misc_Buffer_Local_Value:
4886 case Lisp_Misc_Some_Buffer_Local_Value:
a9faeabe 4887 markword = &mblk->markers[i].u_buffer_local_value.realvalue;
465edf35 4888 break;
e202fa34
KH
4889 case Lisp_Misc_Overlay:
4890 markword = &mblk->markers[i].u_overlay.plist;
4891 break;
fa05e253
RS
4892 case Lisp_Misc_Free:
4893 /* If the object was already free, keep it
4894 on the free list. */
74d84334 4895 markword = (Lisp_Object *) &already_free;
fa05e253 4896 break;
465edf35
KH
4897 default:
4898 markword = 0;
e202fa34 4899 break;
465edf35
KH
4900 }
4901 if (markword && !XMARKBIT (*markword))
4902 {
4903 Lisp_Object tem;
a5da44fe 4904 if (mblk->markers[i].u_marker.type == Lisp_Misc_Marker)
465edf35
KH
4905 {
4906 /* tem1 avoids Sun compiler bug */
4907 struct Lisp_Marker *tem1 = &mblk->markers[i].u_marker;
4908 XSETMARKER (tem, tem1);
4909 unchain_marker (tem);
4910 }
fa05e253
RS
4911 /* Set the type of the freed object to Lisp_Misc_Free.
4912 We could leave the type alone, since nobody checks it,
465edf35 4913 but this might catch bugs faster. */
a5da44fe 4914 mblk->markers[i].u_marker.type = Lisp_Misc_Free;
465edf35
KH
4915 mblk->markers[i].u_free.chain = marker_free_list;
4916 marker_free_list = &mblk->markers[i];
6ca94ac9 4917 this_free++;
465edf35
KH
4918 }
4919 else
4920 {
4921 num_used++;
4922 if (markword)
4923 XUNMARK (*markword);
4924 }
4925 }
7146af97 4926 lim = MARKER_BLOCK_SIZE;
6ca94ac9
KH
4927 /* If this block contains only free markers and we have already
4928 seen more than two blocks worth of free markers then deallocate
4929 this block. */
6feef451 4930 if (this_free == MARKER_BLOCK_SIZE && num_free > MARKER_BLOCK_SIZE)
6ca94ac9 4931 {
6ca94ac9
KH
4932 *mprev = mblk->next;
4933 /* Unhook from the free list. */
4934 marker_free_list = mblk->markers[0].u_free.chain;
c8099634
RS
4935 lisp_free (mblk);
4936 n_marker_blocks--;
6ca94ac9
KH
4937 }
4938 else
6feef451
AS
4939 {
4940 num_free += this_free;
4941 mprev = &mblk->next;
4942 }
7146af97
JB
4943 }
4944
4945 total_markers = num_used;
4946 total_free_markers = num_free;
4947 }
4948
4949 /* Free all unmarked buffers */
4950 {
4951 register struct buffer *buffer = all_buffers, *prev = 0, *next;
4952
4953 while (buffer)
4954 if (!XMARKBIT (buffer->name))
4955 {
4956 if (prev)
4957 prev->next = buffer->next;
4958 else
4959 all_buffers = buffer->next;
4960 next = buffer->next;
34400008 4961 lisp_free (buffer);
7146af97
JB
4962 buffer = next;
4963 }
4964 else
4965 {
4966 XUNMARK (buffer->name);
30e3190a 4967 UNMARK_BALANCE_INTERVALS (BUF_INTERVALS (buffer));
7146af97
JB
4968 prev = buffer, buffer = buffer->next;
4969 }
4970 }
4971
7146af97
JB
4972 /* Free all unmarked vectors */
4973 {
4974 register struct Lisp_Vector *vector = all_vectors, *prev = 0, *next;
4975 total_vector_size = 0;
4976
4977 while (vector)
4978 if (!(vector->size & ARRAY_MARK_FLAG))
4979 {
4980 if (prev)
4981 prev->next = vector->next;
4982 else
4983 all_vectors = vector->next;
4984 next = vector->next;
c8099634
RS
4985 lisp_free (vector);
4986 n_vectors--;
7146af97 4987 vector = next;
41c28a37 4988
7146af97
JB
4989 }
4990 else
4991 {
4992 vector->size &= ~ARRAY_MARK_FLAG;
fa05e253
RS
4993 if (vector->size & PSEUDOVECTOR_FLAG)
4994 total_vector_size += (PSEUDOVECTOR_SIZE_MASK & vector->size);
4995 else
4996 total_vector_size += vector->size;
7146af97
JB
4997 prev = vector, vector = vector->next;
4998 }
4999 }
676a7251
GM
5000
5001#ifdef GC_CHECK_STRING_BYTES
5002 if (!noninteractive)
5003 check_string_bytes (1);
5004#endif
7146af97 5005}
7146af97 5006
7146af97 5007
7146af97 5008
7146af97 5009\f
20d24714
JB
5010/* Debugging aids. */
5011
31ce1c91 5012DEFUN ("memory-limit", Fmemory_limit, Smemory_limit, 0, 0, 0,
20d24714
JB
5013 "Return the address of the last byte Emacs has allocated, divided by 1024.\n\
5014This may be helpful in debugging Emacs's memory usage.\n\
e41ae81f 5015We divide the value by 1024 to make sure it fits in a Lisp integer.")
20d24714
JB
5016 ()
5017{
5018 Lisp_Object end;
5019
45d12a89 5020 XSETINT (end, (EMACS_INT) sbrk (0) / 1024);
20d24714
JB
5021
5022 return end;
5023}
5024
310ea200
RS
5025DEFUN ("memory-use-counts", Fmemory_use_counts, Smemory_use_counts, 0, 0, 0,
5026 "Return a list of counters that measure how much consing there has been.\n\
5027Each of these counters increments for a certain kind of object.\n\
5028The counters wrap around from the largest positive integer to zero.\n\
5029Garbage collection does not decrease them.\n\
5030The elements of the value are as follows:\n\
2e471eb5 5031 (CONSES FLOATS VECTOR-CELLS SYMBOLS STRING-CHARS MISCS INTERVALS STRINGS)\n\
310ea200
RS
5032All are in units of 1 = one object consed\n\
5033except for VECTOR-CELLS and STRING-CHARS, which count the total length of\n\
5034objects consed.\n\
5035MISCS include overlays, markers, and some internal types.\n\
5036Frames, windows, buffers, and subprocesses count as vectors\n\
5037 (but the contents of a buffer's text do not count here).")
5038 ()
5039{
2e471eb5 5040 Lisp_Object consed[8];
310ea200 5041
2e471eb5 5042 XSETINT (consed[0],
290c8f1e 5043 cons_cells_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
2e471eb5 5044 XSETINT (consed[1],
290c8f1e 5045 floats_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
2e471eb5 5046 XSETINT (consed[2],
290c8f1e 5047 vector_cells_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
2e471eb5 5048 XSETINT (consed[3],
290c8f1e 5049 symbols_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
2e471eb5 5050 XSETINT (consed[4],
290c8f1e 5051 string_chars_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
2e471eb5 5052 XSETINT (consed[5],
290c8f1e 5053 misc_objects_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
2e471eb5 5054 XSETINT (consed[6],
290c8f1e 5055 intervals_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
2e471eb5
GM
5056 XSETINT (consed[7],
5057 strings_consed & ~(((EMACS_INT) 1) << (VALBITS - 1)));
310ea200 5058
2e471eb5 5059 return Flist (8, consed);
310ea200 5060}
e0b8c689
KR
5061
5062int suppress_checking;
5063void
5064die (msg, file, line)
5065 const char *msg;
5066 const char *file;
5067 int line;
5068{
5069 fprintf (stderr, "\r\nEmacs fatal error: %s:%d: %s\r\n",
5070 file, line, msg);
5071 abort ();
5072}
20d24714 5073\f
7146af97
JB
5074/* Initialization */
5075
dfcf069d 5076void
7146af97
JB
5077init_alloc_once ()
5078{
5079 /* Used to do Vpurify_flag = Qt here, but Qt isn't set up yet! */
1f0b3fd2 5080 pure_bytes_used = 0;
877935b1 5081#if GC_MARK_STACK || defined GC_MALLOC_CHECK
34400008
GM
5082 mem_init ();
5083 Vdead = make_pure_string ("DEAD", 4, 4, 0);
5084#endif
4c0be5f4
JB
5085#ifdef HAVE_SHM
5086 pure_size = PURESIZE;
5087#endif
7146af97
JB
5088 all_vectors = 0;
5089 ignore_warnings = 1;
d1658221
RS
5090#ifdef DOUG_LEA_MALLOC
5091 mallopt (M_TRIM_THRESHOLD, 128*1024); /* trim threshold */
5092 mallopt (M_MMAP_THRESHOLD, 64*1024); /* mmap threshold */
81d492d5 5093 mallopt (M_MMAP_MAX, MMAP_MAX_AREAS); /* max. number of mmap'ed areas */
d1658221 5094#endif
7146af97
JB
5095 init_strings ();
5096 init_cons ();
5097 init_symbol ();
5098 init_marker ();
7146af97 5099 init_float ();
34400008 5100 init_intervals ();
d5e35230 5101
276cbe5a
RS
5102#ifdef REL_ALLOC
5103 malloc_hysteresis = 32;
5104#else
5105 malloc_hysteresis = 0;
5106#endif
5107
5108 spare_memory = (char *) malloc (SPARE_MEMORY);
5109
7146af97
JB
5110 ignore_warnings = 0;
5111 gcprolist = 0;
630686c8 5112 byte_stack_list = 0;
7146af97
JB
5113 staticidx = 0;
5114 consing_since_gc = 0;
7d179cea 5115 gc_cons_threshold = 100000 * sizeof (Lisp_Object);
7146af97
JB
5116#ifdef VIRT_ADDR_VARIES
5117 malloc_sbrk_unused = 1<<22; /* A large number */
5118 malloc_sbrk_used = 100000; /* as reasonable as any number */
5119#endif /* VIRT_ADDR_VARIES */
5120}
5121
dfcf069d 5122void
7146af97
JB
5123init_alloc ()
5124{
5125 gcprolist = 0;
630686c8 5126 byte_stack_list = 0;
182ff242
GM
5127#if GC_MARK_STACK
5128#if !defined GC_SAVE_REGISTERS_ON_STACK && !defined GC_SETJMP_WORKS
5129 setjmp_tested_p = longjmps_done = 0;
5130#endif
5131#endif
7146af97
JB
5132}
5133
5134void
5135syms_of_alloc ()
5136{
5137 DEFVAR_INT ("gc-cons-threshold", &gc_cons_threshold,
5138 "*Number of bytes of consing between garbage collections.\n\
5139Garbage collection can happen automatically once this many bytes have been\n\
5140allocated since the last garbage collection. All data types count.\n\n\
5141Garbage collection happens automatically only when `eval' is called.\n\n\
5142By binding this temporarily to a large number, you can effectively\n\
5143prevent garbage collection during a part of the program.");
5144
1f0b3fd2 5145 DEFVAR_INT ("pure-bytes-used", &pure_bytes_used,
7146af97
JB
5146 "Number of bytes of sharable Lisp data allocated so far.");
5147
0819585c
RS
5148 DEFVAR_INT ("cons-cells-consed", &cons_cells_consed,
5149 "Number of cons cells that have been consed so far.");
5150
5151 DEFVAR_INT ("floats-consed", &floats_consed,
5152 "Number of floats that have been consed so far.");
5153
5154 DEFVAR_INT ("vector-cells-consed", &vector_cells_consed,
5155 "Number of vector cells that have been consed so far.");
5156
5157 DEFVAR_INT ("symbols-consed", &symbols_consed,
5158 "Number of symbols that have been consed so far.");
5159
5160 DEFVAR_INT ("string-chars-consed", &string_chars_consed,
5161 "Number of string characters that have been consed so far.");
5162
5163 DEFVAR_INT ("misc-objects-consed", &misc_objects_consed,
5164 "Number of miscellaneous objects that have been consed so far.");
5165
5166 DEFVAR_INT ("intervals-consed", &intervals_consed,
5167 "Number of intervals that have been consed so far.");
5168
2e471eb5
GM
5169 DEFVAR_INT ("strings-consed", &strings_consed,
5170 "Number of strings that have been consed so far.");
5171
7146af97
JB
5172 DEFVAR_LISP ("purify-flag", &Vpurify_flag,
5173 "Non-nil means loading Lisp code in order to dump an executable.\n\
5174This means that certain objects should be allocated in shared (pure) space.");
5175
502b9b64 5176 DEFVAR_INT ("undo-limit", &undo_limit,
7146af97 5177 "Keep no more undo information once it exceeds this size.\n\
502b9b64 5178This limit is applied when garbage collection happens.\n\
7146af97
JB
5179The size is counted as the number of bytes occupied,\n\
5180which includes both saved text and other data.");
502b9b64 5181 undo_limit = 20000;
7146af97 5182
502b9b64 5183 DEFVAR_INT ("undo-strong-limit", &undo_strong_limit,
7146af97
JB
5184 "Don't keep more than this much size of undo information.\n\
5185A command which pushes past this size is itself forgotten.\n\
502b9b64 5186This limit is applied when garbage collection happens.\n\
7146af97
JB
5187The size is counted as the number of bytes occupied,\n\
5188which includes both saved text and other data.");
502b9b64 5189 undo_strong_limit = 30000;
7146af97 5190
299585ee
RS
5191 DEFVAR_BOOL ("garbage-collection-messages", &garbage_collection_messages,
5192 "Non-nil means display messages at start and end of garbage collection.");
5193 garbage_collection_messages = 0;
5194
bcb61d60
KH
5195 /* We build this in advance because if we wait until we need it, we might
5196 not be able to allocate the memory to hold it. */
cf3540e4 5197 memory_signal_data
276cbe5a 5198 = Fcons (Qerror, Fcons (build_string ("Memory exhausted--use M-x save-some-buffers RET"), Qnil));
bcb61d60
KH
5199 staticpro (&memory_signal_data);
5200
e8197642
RS
5201 staticpro (&Qgc_cons_threshold);
5202 Qgc_cons_threshold = intern ("gc-cons-threshold");
5203
a59de17b
RS
5204 staticpro (&Qchar_table_extra_slots);
5205 Qchar_table_extra_slots = intern ("char-table-extra-slots");
5206
7146af97
JB
5207 defsubr (&Scons);
5208 defsubr (&Slist);
5209 defsubr (&Svector);
5210 defsubr (&Smake_byte_code);
5211 defsubr (&Smake_list);
5212 defsubr (&Smake_vector);
7b07587b 5213 defsubr (&Smake_char_table);
7146af97 5214 defsubr (&Smake_string);
7b07587b 5215 defsubr (&Smake_bool_vector);
7146af97
JB
5216 defsubr (&Smake_symbol);
5217 defsubr (&Smake_marker);
5218 defsubr (&Spurecopy);
5219 defsubr (&Sgarbage_collect);
20d24714 5220 defsubr (&Smemory_limit);
310ea200 5221 defsubr (&Smemory_use_counts);
34400008
GM
5222
5223#if GC_MARK_STACK == GC_USE_GCPROS_CHECK_ZOMBIES
5224 defsubr (&Sgc_status);
5225#endif
7146af97 5226}