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